code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public void setTTLParam(int ttl) {
try {
getSipURI().setTTLParam(ttl);
super.parameters.put(TTL, "" + ttl);
} catch (InvalidArgumentException e) {
logger.error("invalid argument", e);
}
} } | public class class_name {
public void setTTLParam(int ttl) {
try {
getSipURI().setTTLParam(ttl);
// depends on control dependency: [try], data = [none]
super.parameters.put(TTL, "" + ttl);
// depends on control dependency: [try], data = [none]
} catch (InvalidArgumentException e) {
logger.error("invalid argument", e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public Integer parameterAsInteger(String name, Integer defaultValue) {
Integer parameter = parameterAsInteger(name);
if (parameter == null) {
return defaultValue;
}
return parameter;
} } | public class class_name {
@Override
public Integer parameterAsInteger(String name, Integer defaultValue) {
Integer parameter = parameterAsInteger(name);
if (parameter == null) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
return parameter;
} } |
public class class_name {
protected void waitForSync(String peer)
throws InterruptedException, TimeoutException, IOException {
LOG.debug("Waiting sync from {}.", peer);
Log log = this.persistence.getLog();
Zxid lastZxid = persistence.getLatestZxid();
// The last zxid of peer.
Zxid lastZxidPeer = null;
Message msg = null;
String source = null;
// Expects getting message of DIFF or TRUNCATE or SNAPSHOT from peer or
// PULL_TXN_REQ from leader.
while (true) {
MessageTuple tuple = filter.getMessage(getSyncTimeoutMs());
source = tuple.getServerId();
msg = tuple.getMessage();
if ((msg.getType() != MessageType.DIFF &&
msg.getType() != MessageType.TRUNCATE &&
msg.getType() != MessageType.SNAPSHOT &&
msg.getType() != MessageType.PULL_TXN_REQ) ||
!source.equals(peer)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Got unexpected message {} from {}.",
TextFormat.shortDebugString(msg), source);
}
continue;
} else {
break;
}
}
if (msg.getType() == MessageType.PULL_TXN_REQ) {
// PULL_TXN_REQ message. This message is only received at FOLLOWER side.
LOG.debug("Got pull transaction request from {}",
source);
ZabMessage.Zxid z = msg.getPullTxnReq().getLastZxid();
lastZxidPeer = MessageBuilder.fromProtoZxid(z);
// Synchronize its history to leader.
SyncPeerTask syncTask =
new SyncPeerTask(source, lastZxidPeer, lastZxid,
this.persistence.getLastSeenConfig());
syncTask.run();
// After synchronization, leader should have same history as this
// server, so next message should be an empty DIFF.
MessageTuple tuple = filter.getExpectedMessage(MessageType.DIFF, peer,
getSyncTimeoutMs());
msg = tuple.getMessage();
ZabMessage.Diff diff = msg.getDiff();
lastZxidPeer = MessageBuilder.fromProtoZxid(diff.getLastZxid());
// Check if they match.
if (lastZxidPeer.compareTo(lastZxid) != 0) {
LOG.error("The history of leader and follower are not same.");
throw new RuntimeException("Expecting leader and follower have same"
+ "history.");
}
waitForSyncEnd(peer);
return;
}
if (msg.getType() == MessageType.DIFF) {
// DIFF message.
if (LOG.isDebugEnabled()) {
LOG.debug("Got message {}",
TextFormat.shortDebugString(msg));
}
ZabMessage.Diff diff = msg.getDiff();
// Remember last zxid of the peer.
lastZxidPeer = MessageBuilder.fromProtoZxid(diff.getLastZxid());
if(lastZxid.compareTo(lastZxidPeer) == 0) {
// Means the two nodes have exact same history.
waitForSyncEnd(peer);
return;
}
} else if (msg.getType() == MessageType.TRUNCATE) {
// TRUNCATE message.
if (LOG.isDebugEnabled()) {
LOG.debug("Got message {}",
TextFormat.shortDebugString(msg));
}
ZabMessage.Truncate trunc = msg.getTruncate();
Zxid lastPrefixZxid =
MessageBuilder.fromProtoZxid(trunc.getLastPrefixZxid());
lastZxidPeer = MessageBuilder.fromProtoZxid(trunc.getLastZxid());
if (lastZxidPeer.equals(Zxid.ZXID_NOT_EXIST)) {
// When the truncate zxid is <0, -1>, we treat this as a state
// transfer even it might not be.
persistence.beginStateTransfer();
} else {
log.truncate(lastPrefixZxid);
}
if (lastZxidPeer.compareTo(lastPrefixZxid) == 0) {
waitForSyncEnd(peer);
return;
}
} else {
// SNAPSHOT message.
if (LOG.isDebugEnabled()) {
LOG.debug("Got message {}",
TextFormat.shortDebugString(msg));
}
ZabMessage.Snapshot snap = msg.getSnapshot();
lastZxidPeer = MessageBuilder.fromProtoZxid(snap.getLastZxid());
Zxid snapZxid = MessageBuilder.fromProtoZxid(snap.getSnapZxid());
// Waiting for snapshot file to be received.
msg = filter.getExpectedMessage(MessageType.FILE_RECEIVED,
peer,
getSyncTimeoutMs()).getMessage();
// Turns the temp file to snapshot file.
File file = new File(msg.getFileReceived().getFullPath());
// If the message is SNAPSHOT, it's state transferring.
persistence.beginStateTransfer();
persistence.setSnapshotFile(file, snapZxid);
// Truncates the whole log.
log.truncate(Zxid.ZXID_NOT_EXIST);
// Checks if there's any proposals after snapshot.
if (lastZxidPeer.compareTo(snapZxid) == 0) {
// If no, done with synchronization.
waitForSyncEnd(peer);
return;
}
}
log = persistence.getLog();
// Get subsequent proposals.
while (true) {
MessageTuple tuple = filter.getExpectedMessage(MessageType.PROPOSAL,
peer,
getSyncTimeoutMs());
msg = tuple.getMessage();
source = tuple.getServerId();
if (LOG.isDebugEnabled()) {
LOG.debug("Got message {} from {}", TextFormat.shortDebugString(msg),
source);
}
ZabMessage.Proposal prop = msg.getProposal();
Zxid zxid = MessageBuilder.fromProtoZxid(prop.getZxid());
// Accept the proposal.
log.append(MessageBuilder.fromProposal(prop));
// Check if this is the last proposal.
if (zxid.compareTo(lastZxidPeer) == 0) {
waitForSyncEnd(peer);
return;
}
}
} } | public class class_name {
protected void waitForSync(String peer)
throws InterruptedException, TimeoutException, IOException {
LOG.debug("Waiting sync from {}.", peer);
Log log = this.persistence.getLog();
Zxid lastZxid = persistence.getLatestZxid();
// The last zxid of peer.
Zxid lastZxidPeer = null;
Message msg = null;
String source = null;
// Expects getting message of DIFF or TRUNCATE or SNAPSHOT from peer or
// PULL_TXN_REQ from leader.
while (true) {
MessageTuple tuple = filter.getMessage(getSyncTimeoutMs());
source = tuple.getServerId();
msg = tuple.getMessage();
if ((msg.getType() != MessageType.DIFF &&
msg.getType() != MessageType.TRUNCATE &&
msg.getType() != MessageType.SNAPSHOT &&
msg.getType() != MessageType.PULL_TXN_REQ) ||
!source.equals(peer)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Got unexpected message {} from {}.",
TextFormat.shortDebugString(msg), source); // depends on control dependency: [if], data = [none]
}
continue;
} else {
break;
}
}
if (msg.getType() == MessageType.PULL_TXN_REQ) {
// PULL_TXN_REQ message. This message is only received at FOLLOWER side.
LOG.debug("Got pull transaction request from {}",
source);
ZabMessage.Zxid z = msg.getPullTxnReq().getLastZxid();
lastZxidPeer = MessageBuilder.fromProtoZxid(z);
// Synchronize its history to leader.
SyncPeerTask syncTask =
new SyncPeerTask(source, lastZxidPeer, lastZxid,
this.persistence.getLastSeenConfig());
syncTask.run();
// After synchronization, leader should have same history as this
// server, so next message should be an empty DIFF.
MessageTuple tuple = filter.getExpectedMessage(MessageType.DIFF, peer,
getSyncTimeoutMs());
msg = tuple.getMessage();
ZabMessage.Diff diff = msg.getDiff();
lastZxidPeer = MessageBuilder.fromProtoZxid(diff.getLastZxid());
// Check if they match.
if (lastZxidPeer.compareTo(lastZxid) != 0) {
LOG.error("The history of leader and follower are not same."); // depends on control dependency: [if], data = [none]
throw new RuntimeException("Expecting leader and follower have same"
+ "history.");
}
waitForSyncEnd(peer);
return;
}
if (msg.getType() == MessageType.DIFF) {
// DIFF message.
if (LOG.isDebugEnabled()) {
LOG.debug("Got message {}",
TextFormat.shortDebugString(msg)); // depends on control dependency: [if], data = [none]
}
ZabMessage.Diff diff = msg.getDiff();
// Remember last zxid of the peer.
lastZxidPeer = MessageBuilder.fromProtoZxid(diff.getLastZxid());
if(lastZxid.compareTo(lastZxidPeer) == 0) {
// Means the two nodes have exact same history.
waitForSyncEnd(peer); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else if (msg.getType() == MessageType.TRUNCATE) {
// TRUNCATE message.
if (LOG.isDebugEnabled()) {
LOG.debug("Got message {}",
TextFormat.shortDebugString(msg)); // depends on control dependency: [if], data = [none]
}
ZabMessage.Truncate trunc = msg.getTruncate();
Zxid lastPrefixZxid =
MessageBuilder.fromProtoZxid(trunc.getLastPrefixZxid());
lastZxidPeer = MessageBuilder.fromProtoZxid(trunc.getLastZxid());
if (lastZxidPeer.equals(Zxid.ZXID_NOT_EXIST)) {
// When the truncate zxid is <0, -1>, we treat this as a state
// transfer even it might not be.
persistence.beginStateTransfer(); // depends on control dependency: [if], data = [none]
} else {
log.truncate(lastPrefixZxid); // depends on control dependency: [if], data = [none]
}
if (lastZxidPeer.compareTo(lastPrefixZxid) == 0) {
waitForSyncEnd(peer); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else {
// SNAPSHOT message.
if (LOG.isDebugEnabled()) {
LOG.debug("Got message {}",
TextFormat.shortDebugString(msg)); // depends on control dependency: [if], data = [none]
}
ZabMessage.Snapshot snap = msg.getSnapshot();
lastZxidPeer = MessageBuilder.fromProtoZxid(snap.getLastZxid());
Zxid snapZxid = MessageBuilder.fromProtoZxid(snap.getSnapZxid());
// Waiting for snapshot file to be received.
msg = filter.getExpectedMessage(MessageType.FILE_RECEIVED,
peer,
getSyncTimeoutMs()).getMessage();
// Turns the temp file to snapshot file.
File file = new File(msg.getFileReceived().getFullPath());
// If the message is SNAPSHOT, it's state transferring.
persistence.beginStateTransfer();
persistence.setSnapshotFile(file, snapZxid);
// Truncates the whole log.
log.truncate(Zxid.ZXID_NOT_EXIST);
// Checks if there's any proposals after snapshot.
if (lastZxidPeer.compareTo(snapZxid) == 0) {
// If no, done with synchronization.
waitForSyncEnd(peer); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
log = persistence.getLog();
// Get subsequent proposals.
while (true) {
MessageTuple tuple = filter.getExpectedMessage(MessageType.PROPOSAL,
peer,
getSyncTimeoutMs());
msg = tuple.getMessage();
source = tuple.getServerId();
if (LOG.isDebugEnabled()) {
LOG.debug("Got message {} from {}", TextFormat.shortDebugString(msg),
source); // depends on control dependency: [if], data = [none]
}
ZabMessage.Proposal prop = msg.getProposal();
Zxid zxid = MessageBuilder.fromProtoZxid(prop.getZxid());
// Accept the proposal.
log.append(MessageBuilder.fromProposal(prop));
// Check if this is the last proposal.
if (zxid.compareTo(lastZxidPeer) == 0) {
waitForSyncEnd(peer); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static double regularizedIncompleteGamma(double s, double x) {
if (s < 0.0) {
throw new IllegalArgumentException("Invalid s: " + s);
}
if (x < 0.0) {
throw new IllegalArgumentException("Invalid x: " + x);
}
double igf = 0.0;
if (x < s + 1.0) {
// Series representation
igf = regularizedIncompleteGammaSeries(s, x);
} else {
// Continued fraction representation
igf = regularizedIncompleteGammaFraction(s, x);
}
return igf;
} } | public class class_name {
public static double regularizedIncompleteGamma(double s, double x) {
if (s < 0.0) {
throw new IllegalArgumentException("Invalid s: " + s);
}
if (x < 0.0) {
throw new IllegalArgumentException("Invalid x: " + x);
}
double igf = 0.0;
if (x < s + 1.0) {
// Series representation
igf = regularizedIncompleteGammaSeries(s, x); // depends on control dependency: [if], data = [none]
} else {
// Continued fraction representation
igf = regularizedIncompleteGammaFraction(s, x); // depends on control dependency: [if], data = [none]
}
return igf;
} } |
public class class_name {
public final boolean isReadOnly() {
Entry<?> entry = getEntry();
Calendar calendar = entry.getCalendar();
if (calendar != null) {
return calendar.isReadOnly();
}
return false;
} } | public class class_name {
public final boolean isReadOnly() {
Entry<?> entry = getEntry();
Calendar calendar = entry.getCalendar();
if (calendar != null) {
return calendar.isReadOnly(); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void marshall(ClassifierMetadata classifierMetadata, ProtocolMarshaller protocolMarshaller) {
if (classifierMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(classifierMetadata.getNumberOfLabels(), NUMBEROFLABELS_BINDING);
protocolMarshaller.marshall(classifierMetadata.getNumberOfTrainedDocuments(), NUMBEROFTRAINEDDOCUMENTS_BINDING);
protocolMarshaller.marshall(classifierMetadata.getNumberOfTestDocuments(), NUMBEROFTESTDOCUMENTS_BINDING);
protocolMarshaller.marshall(classifierMetadata.getEvaluationMetrics(), EVALUATIONMETRICS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ClassifierMetadata classifierMetadata, ProtocolMarshaller protocolMarshaller) {
if (classifierMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(classifierMetadata.getNumberOfLabels(), NUMBEROFLABELS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(classifierMetadata.getNumberOfTrainedDocuments(), NUMBEROFTRAINEDDOCUMENTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(classifierMetadata.getNumberOfTestDocuments(), NUMBEROFTESTDOCUMENTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(classifierMetadata.getEvaluationMetrics(), EVALUATIONMETRICS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void calculateMinimumScaleToFit() {
float minimumScaleX = getWidth() / (float) getContentWidth();
float minimumScaleY = getHeight() / (float) getContentHeight();
float recalculatedMinScale = computeMinimumScaleForMode(minimumScaleX, minimumScaleY);
if (recalculatedMinScale != mEffectiveMinScale) {
mEffectiveMinScale = recalculatedMinScale;
if (mScale < mEffectiveMinScale) {
setScale(mEffectiveMinScale);
}
}
} } | public class class_name {
private void calculateMinimumScaleToFit() {
float minimumScaleX = getWidth() / (float) getContentWidth();
float minimumScaleY = getHeight() / (float) getContentHeight();
float recalculatedMinScale = computeMinimumScaleForMode(minimumScaleX, minimumScaleY);
if (recalculatedMinScale != mEffectiveMinScale) {
mEffectiveMinScale = recalculatedMinScale; // depends on control dependency: [if], data = [none]
if (mScale < mEffectiveMinScale) {
setScale(mEffectiveMinScale); // depends on control dependency: [if], data = [mEffectiveMinScale)]
}
}
} } |
public class class_name {
public static void deleteFiles(File dir, FilenameFilter filter) {
// validations
if(dir == null) {
throw new DataUtilException("The delete directory parameter can not be a null value");
} else if(!dir.exists() || !dir.isDirectory()) {
throw new DataUtilException("The delete directory does not exist: " + dir.getAbsolutePath());
}
// delete files
File [] files;
if(filter == null) {
files = dir.listFiles();
} else {
files = dir.listFiles(filter);
}
if (files != null) {
for(File file : files) {
if(file.isFile()) {
if(!file.delete()) {
throw new DataUtilException("Failed to delete file: " + file.getAbsolutePath());
}
}
}
}
} } | public class class_name {
public static void deleteFiles(File dir, FilenameFilter filter) {
// validations
if(dir == null) {
throw new DataUtilException("The delete directory parameter can not be a null value");
} else if(!dir.exists() || !dir.isDirectory()) {
throw new DataUtilException("The delete directory does not exist: " + dir.getAbsolutePath());
}
// delete files
File [] files;
if(filter == null) {
files = dir.listFiles(); // depends on control dependency: [if], data = [none]
} else {
files = dir.listFiles(filter); // depends on control dependency: [if], data = [(filter]
}
if (files != null) {
for(File file : files) {
if(file.isFile()) {
if(!file.delete()) {
throw new DataUtilException("Failed to delete file: " + file.getAbsolutePath());
}
}
}
}
} } |
public class class_name {
public int getInMemorySize() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getInMemorySize");
// The fluffed size needs to be calculated if it hasn't already been set.
if (fluffedSize == -1) {
fluffedSize = guessFluffedSize();
}
// Add together the values for the approximate encoded length & the fluffed size.
// Use getApproximateLength() for the encoded length, so that we pick up any cached value.
int inMemorySize = getApproximateLength() + fluffedSize;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getInMemorySize", inMemorySize);
return inMemorySize;
} } | public class class_name {
public int getInMemorySize() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getInMemorySize");
// The fluffed size needs to be calculated if it hasn't already been set.
if (fluffedSize == -1) {
fluffedSize = guessFluffedSize(); // depends on control dependency: [if], data = [none]
}
// Add together the values for the approximate encoded length & the fluffed size.
// Use getApproximateLength() for the encoded length, so that we pick up any cached value.
int inMemorySize = getApproximateLength() + fluffedSize;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getInMemorySize", inMemorySize);
return inMemorySize;
} } |
public class class_name {
private synchronized static boolean isWorkingHost(String host) {
if (workerHost == null) {
workerHost = host;
return true;
} else {
return host.equals(workerHost);
}
} } | public class class_name {
private synchronized static boolean isWorkingHost(String host) {
if (workerHost == null) {
workerHost = host; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
} else {
return host.equals(workerHost); // depends on control dependency: [if], data = [(workerHost]
}
} } |
public class class_name {
private void parseExternalsConfig(final Node node,
final ConfigSettings config)
{
String name, value;
Node nnode;
NodeList list = node.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
nnode = list.item(i);
name = nnode.getNodeName().toUpperCase();
if (name.equals(KEY_SEVENZIP)) {
value = nnode.getChildNodes().item(0).getNodeValue();
value = value.substring(1, value.length() - 1);
config.setConfigParameter(ConfigurationKeys.PATH_PROGRAM_7ZIP,
value);
}
}
} } | public class class_name {
private void parseExternalsConfig(final Node node,
final ConfigSettings config)
{
String name, value;
Node nnode;
NodeList list = node.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
nnode = list.item(i); // depends on control dependency: [for], data = [i]
name = nnode.getNodeName().toUpperCase(); // depends on control dependency: [for], data = [none]
if (name.equals(KEY_SEVENZIP)) {
value = nnode.getChildNodes().item(0).getNodeValue(); // depends on control dependency: [if], data = [none]
value = value.substring(1, value.length() - 1); // depends on control dependency: [if], data = [none]
config.setConfigParameter(ConfigurationKeys.PATH_PROGRAM_7ZIP,
value); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void clear() {
lock.lock();
try {
currentControlTuple = null;
currentDataTuple = null;
outQueue.clear();
} finally {
lock.unlock();
}
} } | public class class_name {
public void clear() {
lock.lock();
try {
currentControlTuple = null; // depends on control dependency: [try], data = [none]
currentDataTuple = null; // depends on control dependency: [try], data = [none]
outQueue.clear(); // depends on control dependency: [try], data = [none]
} finally {
lock.unlock();
}
} } |
public class class_name {
private void initButtons()
{
JButton selectAll = new JButton("Select all");
selectAll.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
for (int i = 0; i < 22; i++) {
namespaces.getModel().setValueAt(new Boolean(true), i, 1);
}
}
});
selectAll.setBounds(380, 10, 120, 25);
this.add(selectAll);
JButton unselectAll = new JButton("Unselect all");
unselectAll.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
for (int i = 0; i < 22; i++) {
namespaces.getModel().setValueAt(new Boolean(false), i, 1);
}
}
});
unselectAll.setBounds(380, 40, 120, 25);
this.add(unselectAll);
} } | public class class_name {
private void initButtons()
{
JButton selectAll = new JButton("Select all");
selectAll.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
for (int i = 0; i < 22; i++) {
namespaces.getModel().setValueAt(new Boolean(true), i, 1); // depends on control dependency: [for], data = [i]
}
}
});
selectAll.setBounds(380, 10, 120, 25);
this.add(selectAll);
JButton unselectAll = new JButton("Unselect all");
unselectAll.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
for (int i = 0; i < 22; i++) {
namespaces.getModel().setValueAt(new Boolean(false), i, 1); // depends on control dependency: [for], data = [i]
}
}
});
unselectAll.setBounds(380, 40, 120, 25);
this.add(unselectAll);
} } |
public class class_name {
public static String getCanonicalName(final Object object, final String valueIfNull) {
if (object == null) {
return valueIfNull;
}
final String canonicalName = object.getClass().getCanonicalName();
return canonicalName == null ? valueIfNull : canonicalName;
} } | public class class_name {
public static String getCanonicalName(final Object object, final String valueIfNull) {
if (object == null) {
return valueIfNull; // depends on control dependency: [if], data = [none]
}
final String canonicalName = object.getClass().getCanonicalName();
return canonicalName == null ? valueIfNull : canonicalName;
} } |
public class class_name {
public void onBitmapRendered(PagePart part) {
if (part.isThumbnail()) {
cacheManager.cacheThumbnail(part);
} else {
cacheManager.cachePart(part);
}
invalidate();
} } | public class class_name {
public void onBitmapRendered(PagePart part) {
if (part.isThumbnail()) {
cacheManager.cacheThumbnail(part);
// depends on control dependency: [if], data = [none]
} else {
cacheManager.cachePart(part);
// depends on control dependency: [if], data = [none]
}
invalidate();
} } |
public class class_name {
public void setRequestUrl(String urlStr) {
// This looks a little confusing: We're trying to fixup an incoming
// request URL that starts with:
// "http(s):/www.archive.org"
// so it becomes:
// "http(s)://www.archive.org"
// (note the missing second "/" in the first)
//
// if that is not the case, then see if the incoming scheme
// is known, adding an implied "http://" scheme if there doesn't appear
// to be a scheme..
// TODO: make the default "http://" configurable.
if (!urlStr.startsWith(UrlOperations.HTTP_SCHEME) &&
!urlStr.startsWith(UrlOperations.HTTPS_SCHEME) &&
!urlStr.startsWith(UrlOperations.FTP_SCHEME) &&
!urlStr.startsWith(UrlOperations.FTPS_SCHEME)) {
if(urlStr.startsWith("http:/")) {
urlStr = UrlOperations.HTTP_SCHEME + urlStr.substring(6);
} else if(urlStr.startsWith("https:/")) {
urlStr = UrlOperations.HTTPS_SCHEME + urlStr.substring(7);
} else if(urlStr.startsWith("ftp:/")) {
urlStr = UrlOperations.FTP_SCHEME + urlStr.substring(5);
} else if(urlStr.startsWith("ftps:/")) {
urlStr = UrlOperations.FTPS_SCHEME + urlStr.substring(6);
} else {
if(UrlOperations.urlToScheme(urlStr) == null) {
urlStr = UrlOperations.HTTP_SCHEME + urlStr;
}
}
}
try {
String decodedUrlStr = URLDecoder.decode(urlStr, "UTF-8");
String idnEncodedHost = UsableURIFactory.getInstance(decodedUrlStr, "UTF-8").getHost();
if (idnEncodedHost != null) {
// If url is absolute, replace host with IDN-encoded host.
String unicodeEncodedHost = URLEncoder.encode(IDNA.toUnicode(idnEncodedHost), "UTF-8");
urlStr = urlStr.replace(unicodeEncodedHost, idnEncodedHost);
}
} catch (UnsupportedEncodingException ex) {
// Should never happen as UTF-8 is required to be present
throw new RuntimeException(ex);
} catch (URIException ex) {
throw new RuntimeException(ex);
}
put(REQUEST_URL, urlStr);
} } | public class class_name {
public void setRequestUrl(String urlStr) {
// This looks a little confusing: We're trying to fixup an incoming
// request URL that starts with:
// "http(s):/www.archive.org"
// so it becomes:
// "http(s)://www.archive.org"
// (note the missing second "/" in the first)
//
// if that is not the case, then see if the incoming scheme
// is known, adding an implied "http://" scheme if there doesn't appear
// to be a scheme..
// TODO: make the default "http://" configurable.
if (!urlStr.startsWith(UrlOperations.HTTP_SCHEME) &&
!urlStr.startsWith(UrlOperations.HTTPS_SCHEME) &&
!urlStr.startsWith(UrlOperations.FTP_SCHEME) &&
!urlStr.startsWith(UrlOperations.FTPS_SCHEME)) {
if(urlStr.startsWith("http:/")) {
urlStr = UrlOperations.HTTP_SCHEME + urlStr.substring(6); // depends on control dependency: [if], data = [none]
} else if(urlStr.startsWith("https:/")) {
urlStr = UrlOperations.HTTPS_SCHEME + urlStr.substring(7); // depends on control dependency: [if], data = [none]
} else if(urlStr.startsWith("ftp:/")) {
urlStr = UrlOperations.FTP_SCHEME + urlStr.substring(5); // depends on control dependency: [if], data = [none]
} else if(urlStr.startsWith("ftps:/")) {
urlStr = UrlOperations.FTPS_SCHEME + urlStr.substring(6); // depends on control dependency: [if], data = [none]
} else {
if(UrlOperations.urlToScheme(urlStr) == null) {
urlStr = UrlOperations.HTTP_SCHEME + urlStr; // depends on control dependency: [if], data = [none]
}
}
}
try {
String decodedUrlStr = URLDecoder.decode(urlStr, "UTF-8");
String idnEncodedHost = UsableURIFactory.getInstance(decodedUrlStr, "UTF-8").getHost();
if (idnEncodedHost != null) {
// If url is absolute, replace host with IDN-encoded host.
String unicodeEncodedHost = URLEncoder.encode(IDNA.toUnicode(idnEncodedHost), "UTF-8");
urlStr = urlStr.replace(unicodeEncodedHost, idnEncodedHost); // depends on control dependency: [if], data = [none]
}
} catch (UnsupportedEncodingException ex) {
// Should never happen as UTF-8 is required to be present
throw new RuntimeException(ex);
} catch (URIException ex) { // depends on control dependency: [catch], data = [none]
throw new RuntimeException(ex);
} // depends on control dependency: [catch], data = [none]
put(REQUEST_URL, urlStr);
} } |
public class class_name {
public static int indexOf(final String value, final String needle, int offset, boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.indexOf(needle, offset);
}
return value.toLowerCase().indexOf(needle.toLowerCase(), offset);
} } | public class class_name {
public static int indexOf(final String value, final String needle, int offset, boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.indexOf(needle, offset); // depends on control dependency: [if], data = [none]
}
return value.toLowerCase().indexOf(needle.toLowerCase(), offset);
} } |
public class class_name {
public static double ssReg(double[] residuals, double[] targetAttribute) {
double mean = sum(targetAttribute) / targetAttribute.length;
double ret = 0;
for (int i = 0; i < residuals.length; i++) {
ret += Math.pow(residuals[i] - mean, 2);
}
return ret;
} } | public class class_name {
public static double ssReg(double[] residuals, double[] targetAttribute) {
double mean = sum(targetAttribute) / targetAttribute.length;
double ret = 0;
for (int i = 0; i < residuals.length; i++) {
ret += Math.pow(residuals[i] - mean, 2); // depends on control dependency: [for], data = [i]
}
return ret;
} } |
public class class_name {
public <T extends JobProperty> T getProperty(Class<T> clazz) {
if (clazz == BuildDiscarderProperty.class && logRotator != null) {
return clazz.cast(new BuildDiscarderProperty(logRotator));
}
return _getProperty(clazz);
} } | public class class_name {
public <T extends JobProperty> T getProperty(Class<T> clazz) {
if (clazz == BuildDiscarderProperty.class && logRotator != null) {
return clazz.cast(new BuildDiscarderProperty(logRotator)); // depends on control dependency: [if], data = [none]
}
return _getProperty(clazz);
} } |
public class class_name {
public static String getRowKeyUIDRegex(
final List<byte[]> group_bys,
final ByteMap<byte[][]> row_key_literals,
final boolean explicit_tags,
final byte[] fuzzy_key,
final byte[] fuzzy_mask) {
if (group_bys != null) {
Collections.sort(group_bys, Bytes.MEMCMP);
}
final int prefix_width = Const.SALT_WIDTH() + TSDB.metrics_width() +
Const.TIMESTAMP_BYTES;
final short name_width = TSDB.tagk_width();
final short value_width = TSDB.tagv_width();
final short tagsize = (short) (name_width + value_width);
// Generate a regexp for our tags. Say we have 2 tags: { 0 0 1 0 0 2 }
// and { 4 5 6 9 8 7 }, the regexp will be:
// "^.{7}(?:.{6})*\\Q\000\000\001\000\000\002\\E(?:.{6})*\\Q\004\005\006\011\010\007\\E(?:.{6})*$"
final StringBuilder buf = new StringBuilder(
15 // "^.{N}" + "(?:.{M})*" + "$"
+ ((13 + tagsize) // "(?:.{M})*\\Q" + tagsize bytes + "\\E"
* ((row_key_literals == null ? 0 : row_key_literals.size()) +
(group_bys == null ? 0 : group_bys.size() * 3))));
// In order to avoid re-allocations, reserve a bit more w/ groups ^^^
// Alright, let's build this regexp. From the beginning...
buf.append("(?s)" // Ensure we use the DOTALL flag.
+ "^.{")
// ... start by skipping the salt, metric ID and timestamp.
.append(Const.SALT_WIDTH() + TSDB.metrics_width() + Const.TIMESTAMP_BYTES)
.append("}");
final Iterator<Entry<byte[], byte[][]>> it = row_key_literals == null ?
new ByteMap<byte[][]>().iterator() : row_key_literals.iterator();
int fuzzy_offset = Const.SALT_WIDTH() + TSDB.metrics_width();
if (fuzzy_mask != null) {
// make sure to skip the timestamp when scanning
while (fuzzy_offset < prefix_width) {
fuzzy_mask[fuzzy_offset++] = 1;
}
}
while(it.hasNext()) {
Entry<byte[], byte[][]> entry = it.hasNext() ? it.next() : null;
// TODO - This look ahead may be expensive. We need to get some data around
// whether it's faster for HBase to scan with a look ahead or simply pass
// the rows back to the TSD for filtering.
final boolean not_key =
entry.getValue() != null && entry.getValue().length == 0;
// Skip any number of tags.
if (!explicit_tags) {
buf.append("(?:.{").append(tagsize).append("})*");
} else if (fuzzy_mask != null) {
// TODO - see if we can figure out how to improve the fuzzy filter by
// setting explicit tag values whenever we can. In testing there was
// a conflict between the row key regex and fuzzy filter that prevented
// results from returning properly.
System.arraycopy(entry.getKey(), 0, fuzzy_key, fuzzy_offset, name_width);
fuzzy_offset += name_width;
for (int i = 0; i < value_width; i++) {
fuzzy_mask[fuzzy_offset++] = 1;
}
}
if (not_key) {
// start the lookahead as we have a key we explicitly do not want in the
// results
buf.append("(?!");
}
buf.append("\\Q");
addId(buf, entry.getKey(), true);
if (entry.getValue() != null && entry.getValue().length > 0) { // Add a group_by.
// We want specific IDs. List them: /(AAA|BBB|CCC|..)/
buf.append("(?:");
for (final byte[] value_id : entry.getValue()) {
if (value_id == null) {
continue;
}
buf.append("\\Q");
addId(buf, value_id, true);
buf.append('|');
}
// Replace the pipe of the last iteration.
buf.setCharAt(buf.length() - 1, ')');
} else {
buf.append(".{").append(value_width).append('}'); // Any value ID.
}
if (not_key) {
// be sure to close off the look ahead
buf.append(")");
}
}
// Skip any number of tags before the end.
if (!explicit_tags) {
buf.append("(?:.{").append(tagsize).append("})*");
}
buf.append("$");
return buf.toString();
} } | public class class_name {
public static String getRowKeyUIDRegex(
final List<byte[]> group_bys,
final ByteMap<byte[][]> row_key_literals,
final boolean explicit_tags,
final byte[] fuzzy_key,
final byte[] fuzzy_mask) {
if (group_bys != null) {
Collections.sort(group_bys, Bytes.MEMCMP); // depends on control dependency: [if], data = [(group_bys]
}
final int prefix_width = Const.SALT_WIDTH() + TSDB.metrics_width() +
Const.TIMESTAMP_BYTES;
final short name_width = TSDB.tagk_width();
final short value_width = TSDB.tagv_width();
final short tagsize = (short) (name_width + value_width);
// Generate a regexp for our tags. Say we have 2 tags: { 0 0 1 0 0 2 }
// and { 4 5 6 9 8 7 }, the regexp will be:
// "^.{7}(?:.{6})*\\Q\000\000\001\000\000\002\\E(?:.{6})*\\Q\004\005\006\011\010\007\\E(?:.{6})*$"
final StringBuilder buf = new StringBuilder(
15 // "^.{N}" + "(?:.{M})*" + "$"
+ ((13 + tagsize) // "(?:.{M})*\\Q" + tagsize bytes + "\\E"
* ((row_key_literals == null ? 0 : row_key_literals.size()) +
(group_bys == null ? 0 : group_bys.size() * 3))));
// In order to avoid re-allocations, reserve a bit more w/ groups ^^^
// Alright, let's build this regexp. From the beginning...
buf.append("(?s)" // Ensure we use the DOTALL flag.
+ "^.{")
// ... start by skipping the salt, metric ID and timestamp.
.append(Const.SALT_WIDTH() + TSDB.metrics_width() + Const.TIMESTAMP_BYTES)
.append("}");
final Iterator<Entry<byte[], byte[][]>> it = row_key_literals == null ?
new ByteMap<byte[][]>().iterator() : row_key_literals.iterator();
int fuzzy_offset = Const.SALT_WIDTH() + TSDB.metrics_width();
if (fuzzy_mask != null) {
// make sure to skip the timestamp when scanning
while (fuzzy_offset < prefix_width) {
fuzzy_mask[fuzzy_offset++] = 1; // depends on control dependency: [while], data = [none]
}
}
while(it.hasNext()) {
Entry<byte[], byte[][]> entry = it.hasNext() ? it.next() : null;
// TODO - This look ahead may be expensive. We need to get some data around
// whether it's faster for HBase to scan with a look ahead or simply pass
// the rows back to the TSD for filtering.
final boolean not_key =
entry.getValue() != null && entry.getValue().length == 0;
// Skip any number of tags.
if (!explicit_tags) {
buf.append("(?:.{").append(tagsize).append("})*"); // depends on control dependency: [if], data = [none]
} else if (fuzzy_mask != null) {
// TODO - see if we can figure out how to improve the fuzzy filter by
// setting explicit tag values whenever we can. In testing there was
// a conflict between the row key regex and fuzzy filter that prevented
// results from returning properly.
System.arraycopy(entry.getKey(), 0, fuzzy_key, fuzzy_offset, name_width); // depends on control dependency: [if], data = [none]
fuzzy_offset += name_width; // depends on control dependency: [if], data = [none]
for (int i = 0; i < value_width; i++) {
fuzzy_mask[fuzzy_offset++] = 1; // depends on control dependency: [for], data = [none]
}
}
if (not_key) {
// start the lookahead as we have a key we explicitly do not want in the
// results
buf.append("(?!"); // depends on control dependency: [if], data = [none]
}
buf.append("\\Q"); // depends on control dependency: [while], data = [none]
addId(buf, entry.getKey(), true); // depends on control dependency: [while], data = [none]
if (entry.getValue() != null && entry.getValue().length > 0) { // Add a group_by.
// We want specific IDs. List them: /(AAA|BBB|CCC|..)/
buf.append("(?:"); // depends on control dependency: [if], data = [none]
for (final byte[] value_id : entry.getValue()) {
if (value_id == null) {
continue;
}
buf.append("\\Q"); // depends on control dependency: [for], data = [none]
addId(buf, value_id, true); // depends on control dependency: [for], data = [value_id]
buf.append('|'); // depends on control dependency: [for], data = [none]
}
// Replace the pipe of the last iteration.
buf.setCharAt(buf.length() - 1, ')'); // depends on control dependency: [if], data = [none]
} else {
buf.append(".{").append(value_width).append('}'); // Any value ID. // depends on control dependency: [if], data = [none]
}
if (not_key) {
// be sure to close off the look ahead
buf.append(")"); // depends on control dependency: [if], data = [none]
}
}
// Skip any number of tags before the end.
if (!explicit_tags) {
buf.append("(?:.{").append(tagsize).append("})*"); // depends on control dependency: [if], data = [none]
}
buf.append("$");
return buf.toString();
} } |
public class class_name {
public static String capitalize(final String str) {
final int strLen;
if(str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuilder(strLen)
.append(String.valueOf(str.charAt(0)).toUpperCase())
.append(str.substring(1))
.toString();
} } | public class class_name {
public static String capitalize(final String str) {
final int strLen;
if(str == null || (strLen = str.length()) == 0) {
return str;
// depends on control dependency: [if], data = [none]
}
return new StringBuilder(strLen)
.append(String.valueOf(str.charAt(0)).toUpperCase())
.append(str.substring(1))
.toString();
} } |
public class class_name {
public static Date nextSecond(Date date, int second) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.SECOND, second);
return cal.getTime();
} } | public class class_name {
public static Date nextSecond(Date date, int second) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
// depends on control dependency: [if], data = [(date]
}
cal.add(Calendar.SECOND, second);
return cal.getTime();
} } |
public class class_name {
public void marshall(BatchItemError batchItemError, ProtocolMarshaller protocolMarshaller) {
if (batchItemError == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchItemError.getIndex(), INDEX_BINDING);
protocolMarshaller.marshall(batchItemError.getErrorCode(), ERRORCODE_BINDING);
protocolMarshaller.marshall(batchItemError.getErrorMessage(), ERRORMESSAGE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BatchItemError batchItemError, ProtocolMarshaller protocolMarshaller) {
if (batchItemError == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchItemError.getIndex(), INDEX_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchItemError.getErrorCode(), ERRORCODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchItemError.getErrorMessage(), ERRORMESSAGE_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 Shape getPlaceSubtitleShape (int type, Rectangle r)
{
switch (modeOf(type)) {
default:
case SPEAK: {
// rounded rectangle subtitle
Area a = new Area(r);
a.add(new Area(new Ellipse2D.Float(r.x - PAD, r.y, PAD * 2, r.height)));
a.add(new Area(new Ellipse2D.Float(r.x + r.width - PAD, r.y, PAD * 2, r.height)));
return a;
}
case THINK: {
r.grow(PAD / 2, 0);
Area a = new Area(r);
int dia = 8;
int num = (int) Math.ceil(r.height / ((float) dia));
int leftside = r.x - dia/2;
int rightside = r.x + r.width - dia/2 - 1;
int maxh = r.height - dia;
for (int ii=0; ii < num; ii++) {
int ypos = r.y + Math.min((r.height * ii) / num, maxh);
a.add(new Area(new Ellipse2D.Float(leftside, ypos, dia, dia)));
a.add(new Area(new Ellipse2D.Float(rightside, ypos, dia, dia)));
}
return a;
}
case SHOUT: {
r.grow(PAD / 2, 0);
Area a = new Area(r);
Polygon left = new Polygon();
Polygon right = new Polygon();
int spikehei = 8;
int num = (int) Math.ceil(r.height / ((float) spikehei));
left.addPoint(r.x, r.y);
left.addPoint(r.x - PAD, r.y + spikehei / 2);
left.addPoint(r.x, r.y + spikehei);
right.addPoint(r.x + r.width , r.y);
right.addPoint(r.x + r.width + PAD, r.y + spikehei / 2);
right.addPoint(r.x + r.width, r.y + spikehei);
int ypos = 0;
int maxpos = r.y + r.height - spikehei + 1;
for (int ii=0; ii < num; ii++) {
int newpos = Math.min((r.height * ii) / num, maxpos);
left.translate(0, newpos - ypos);
right.translate(0, newpos - ypos);
a.add(new Area(left));
a.add(new Area(right));
ypos = newpos;
}
return a;
}
case EMOTE: {
// a box that curves inward on the left and right
r.grow(PAD, 0);
Area a = new Area(r);
a.subtract(new Area(new Ellipse2D.Float(r.x - PAD / 2, r.y, PAD, r.height)));
a.subtract(new Area(new Ellipse2D.Float(r.x + r.width - PAD / 2, r.y, PAD, r.height)));
return a;
}
}
} } | public class class_name {
public Shape getPlaceSubtitleShape (int type, Rectangle r)
{
switch (modeOf(type)) {
default:
case SPEAK: {
// rounded rectangle subtitle
Area a = new Area(r);
a.add(new Area(new Ellipse2D.Float(r.x - PAD, r.y, PAD * 2, r.height)));
a.add(new Area(new Ellipse2D.Float(r.x + r.width - PAD, r.y, PAD * 2, r.height)));
return a;
}
case THINK: {
r.grow(PAD / 2, 0);
Area a = new Area(r);
int dia = 8;
int num = (int) Math.ceil(r.height / ((float) dia));
int leftside = r.x - dia/2;
int rightside = r.x + r.width - dia/2 - 1;
int maxh = r.height - dia;
for (int ii=0; ii < num; ii++) {
int ypos = r.y + Math.min((r.height * ii) / num, maxh);
a.add(new Area(new Ellipse2D.Float(leftside, ypos, dia, dia))); // depends on control dependency: [for], data = [none]
a.add(new Area(new Ellipse2D.Float(rightside, ypos, dia, dia))); // depends on control dependency: [for], data = [none]
}
return a;
}
case SHOUT: {
r.grow(PAD / 2, 0);
Area a = new Area(r);
Polygon left = new Polygon();
Polygon right = new Polygon();
int spikehei = 8;
int num = (int) Math.ceil(r.height / ((float) spikehei));
left.addPoint(r.x, r.y);
left.addPoint(r.x - PAD, r.y + spikehei / 2);
left.addPoint(r.x, r.y + spikehei);
right.addPoint(r.x + r.width , r.y);
right.addPoint(r.x + r.width + PAD, r.y + spikehei / 2);
right.addPoint(r.x + r.width, r.y + spikehei);
int ypos = 0;
int maxpos = r.y + r.height - spikehei + 1;
for (int ii=0; ii < num; ii++) {
int newpos = Math.min((r.height * ii) / num, maxpos);
left.translate(0, newpos - ypos); // depends on control dependency: [for], data = [none]
right.translate(0, newpos - ypos); // depends on control dependency: [for], data = [none]
a.add(new Area(left)); // depends on control dependency: [for], data = [none]
a.add(new Area(right)); // depends on control dependency: [for], data = [none]
ypos = newpos; // depends on control dependency: [for], data = [none]
}
return a;
}
case EMOTE: {
// a box that curves inward on the left and right
r.grow(PAD, 0);
Area a = new Area(r);
a.subtract(new Area(new Ellipse2D.Float(r.x - PAD / 2, r.y, PAD, r.height)));
a.subtract(new Area(new Ellipse2D.Float(r.x + r.width - PAD / 2, r.y, PAD, r.height)));
return a;
}
}
} } |
public class class_name {
public static String mapToPtPath(final String aBasePath, final String aID, final String aEncapsulatedName) {
final String ptPath;
Objects.requireNonNull(aID);
if (aEncapsulatedName == null) {
ptPath = concat(aBasePath, mapToPtPath(aID));
} else {
ptPath = concat(aBasePath, mapToPtPath(aID), encodeID(aEncapsulatedName));
}
return ptPath;
} } | public class class_name {
public static String mapToPtPath(final String aBasePath, final String aID, final String aEncapsulatedName) {
final String ptPath;
Objects.requireNonNull(aID);
if (aEncapsulatedName == null) {
ptPath = concat(aBasePath, mapToPtPath(aID)); // depends on control dependency: [if], data = [none]
} else {
ptPath = concat(aBasePath, mapToPtPath(aID), encodeID(aEncapsulatedName)); // depends on control dependency: [if], data = [(aEncapsulatedName]
}
return ptPath;
} } |
public class class_name {
public void stop() {
if (state.compareAndSet(RUNNING, STOPPING)){
log.debug("Stopping...");
if ( (StringUtils.isBlank(stopSqlCondition) || isInCondition(stopSqlCondition))
&& (StringUtils.isBlank(stopSqlConditionResource) || isInConditionResource(stopSqlConditionResource))
){
if (StringUtils.isNotBlank(stopSQL)){
executeSQL(stopSQL);
} else if (StringUtils.isNotBlank(stopSqlResource)){
executeSqlResource(stopSqlResource);
}
}
state.set(UNKNOWN);
}else{
log.warn("Stop request ignored. Current state is: " + stateNames[state.get()]);
}
} } | public class class_name {
public void stop() {
if (state.compareAndSet(RUNNING, STOPPING)){
log.debug("Stopping...");
// depends on control dependency: [if], data = [none]
if ( (StringUtils.isBlank(stopSqlCondition) || isInCondition(stopSqlCondition))
&& (StringUtils.isBlank(stopSqlConditionResource) || isInConditionResource(stopSqlConditionResource))
){
if (StringUtils.isNotBlank(stopSQL)){
executeSQL(stopSQL);
// depends on control dependency: [if], data = [none]
} else if (StringUtils.isNotBlank(stopSqlResource)){
executeSqlResource(stopSqlResource);
// depends on control dependency: [if], data = [none]
}
}
state.set(UNKNOWN);
// depends on control dependency: [if], data = [none]
}else{
log.warn("Stop request ignored. Current state is: " + stateNames[state.get()]);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean apply(final MappedField mappedField, final FilterOperator operator, final Object value,
final List<ValidationFailure> validationFailures) {
if (getOperator().equals(operator)) {
validate(mappedField, value, validationFailures);
return true;
}
return false;
} } | public class class_name {
public boolean apply(final MappedField mappedField, final FilterOperator operator, final Object value,
final List<ValidationFailure> validationFailures) {
if (getOperator().equals(operator)) {
validate(mappedField, value, validationFailures); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
private void processConfig(final HttpServerExchange exchange, final RequestData requestData) {
// Get the node builder
List<String> hosts = null;
List<String> contexts = null;
final Balancer.BalancerBuilder balancer = Balancer.builder();
final NodeConfig.NodeBuilder node = NodeConfig.builder(modCluster);
final Iterator<HttpString> i = requestData.iterator();
while (i.hasNext()) {
final HttpString name = i.next();
final String value = requestData.getFirst(name);
UndertowLogger.ROOT_LOGGER.mcmpKeyValue(name, value);
if (!checkString(value)) {
processError(TYPESYNTAX, SBADFLD + name + SBADFLD1, exchange);
return;
}
if (BALANCER.equals(name)) {
node.setBalancer(value);
balancer.setName(value);
} else if (MAXATTEMPTS.equals(name)) {
balancer.setMaxRetries(Integer.parseInt(value));
} else if (STICKYSESSION.equals(name)) {
if ("No".equalsIgnoreCase(value)) {
balancer.setStickySession(false);
}
} else if (STICKYSESSIONCOOKIE.equals(name)) {
balancer.setStickySessionCookie(value);
} else if (STICKYSESSIONPATH.equals(name)) {
balancer.setStickySessionPath(value);
} else if (STICKYSESSIONREMOVE.equals(name)) {
if ("Yes".equalsIgnoreCase(value)) {
balancer.setStickySessionRemove(true);
}
} else if (STICKYSESSIONFORCE.equals(name)) {
if ("no".equalsIgnoreCase(value)) {
balancer.setStickySessionForce(false);
}
} else if (JVMROUTE.equals(name)) {
node.setJvmRoute(value);
} else if (DOMAIN.equals(name)) {
node.setDomain(value);
} else if (HOST.equals(name)) {
node.setHostname(value);
} else if (PORT.equals(name)) {
node.setPort(Integer.parseInt(value));
} else if (TYPE.equals(name)) {
node.setType(value);
} else if (REVERSED.equals(name)) {
continue; // ignore
} else if (FLUSH_PACKET.equals(name)) {
if ("on".equalsIgnoreCase(value)) {
node.setFlushPackets(true);
} else if ("auto".equalsIgnoreCase(value)) {
node.setFlushPackets(true);
}
} else if (FLUSH_WAIT.equals(name)) {
node.setFlushwait(Integer.parseInt(value));
} else if (MCMPConstants.PING.equals(name)) {
node.setPing(Integer.parseInt(value));
} else if (SMAX.equals(name)) {
node.setSmax(Integer.parseInt(value));
} else if (TTL.equals(name)) {
node.setTtl(TimeUnit.SECONDS.toMillis(Long.parseLong(value)));
} else if (TIMEOUT.equals(name)) {
node.setTimeout(Integer.parseInt(value));
} else if (CONTEXT.equals(name)) {
final String[] context = value.split(",");
contexts = Arrays.asList(context);
} else if (ALIAS.equals(name)) {
final String[] alias = value.split(",");
hosts = Arrays.asList(alias);
} else if(WAITWORKER.equals(name)) {
node.setWaitWorker(Integer.parseInt(value));
} else {
processError(TYPESYNTAX, SBADFLD + name + SBADFLD1, exchange);
return;
}
}
final NodeConfig config;
try {
// Build the config
config = node.build();
if (container.addNode(config, balancer, exchange.getIoThread(), exchange.getConnection().getByteBufferPool())) {
// Apparently this is hard to do in the C part, so maybe we should just remove this
if (contexts != null && hosts != null) {
for (final String context : contexts) {
container.enableContext(context, config.getJvmRoute(), hosts);
}
}
processOK(exchange);
} else {
processError(MCMPErrorCode.NODE_STILL_EXISTS, exchange);
}
} catch (Exception e) {
processError(MCMPErrorCode.CANT_UPDATE_NODE, exchange);
}
} } | public class class_name {
private void processConfig(final HttpServerExchange exchange, final RequestData requestData) {
// Get the node builder
List<String> hosts = null;
List<String> contexts = null;
final Balancer.BalancerBuilder balancer = Balancer.builder();
final NodeConfig.NodeBuilder node = NodeConfig.builder(modCluster);
final Iterator<HttpString> i = requestData.iterator();
while (i.hasNext()) {
final HttpString name = i.next();
final String value = requestData.getFirst(name);
UndertowLogger.ROOT_LOGGER.mcmpKeyValue(name, value); // depends on control dependency: [while], data = [none]
if (!checkString(value)) {
processError(TYPESYNTAX, SBADFLD + name + SBADFLD1, exchange); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (BALANCER.equals(name)) {
node.setBalancer(value); // depends on control dependency: [if], data = [none]
balancer.setName(value); // depends on control dependency: [if], data = [none]
} else if (MAXATTEMPTS.equals(name)) {
balancer.setMaxRetries(Integer.parseInt(value)); // depends on control dependency: [if], data = [none]
} else if (STICKYSESSION.equals(name)) {
if ("No".equalsIgnoreCase(value)) {
balancer.setStickySession(false); // depends on control dependency: [if], data = [none]
}
} else if (STICKYSESSIONCOOKIE.equals(name)) {
balancer.setStickySessionCookie(value); // depends on control dependency: [if], data = [none]
} else if (STICKYSESSIONPATH.equals(name)) {
balancer.setStickySessionPath(value); // depends on control dependency: [if], data = [none]
} else if (STICKYSESSIONREMOVE.equals(name)) {
if ("Yes".equalsIgnoreCase(value)) {
balancer.setStickySessionRemove(true); // depends on control dependency: [if], data = [none]
}
} else if (STICKYSESSIONFORCE.equals(name)) {
if ("no".equalsIgnoreCase(value)) {
balancer.setStickySessionForce(false); // depends on control dependency: [if], data = [none]
}
} else if (JVMROUTE.equals(name)) {
node.setJvmRoute(value); // depends on control dependency: [if], data = [none]
} else if (DOMAIN.equals(name)) {
node.setDomain(value); // depends on control dependency: [if], data = [none]
} else if (HOST.equals(name)) {
node.setHostname(value); // depends on control dependency: [if], data = [none]
} else if (PORT.equals(name)) {
node.setPort(Integer.parseInt(value)); // depends on control dependency: [if], data = [none]
} else if (TYPE.equals(name)) {
node.setType(value); // depends on control dependency: [if], data = [none]
} else if (REVERSED.equals(name)) {
continue; // ignore
} else if (FLUSH_PACKET.equals(name)) {
if ("on".equalsIgnoreCase(value)) {
node.setFlushPackets(true); // depends on control dependency: [if], data = [none]
} else if ("auto".equalsIgnoreCase(value)) {
node.setFlushPackets(true); // depends on control dependency: [if], data = [none]
}
} else if (FLUSH_WAIT.equals(name)) {
node.setFlushwait(Integer.parseInt(value)); // depends on control dependency: [if], data = [none]
} else if (MCMPConstants.PING.equals(name)) {
node.setPing(Integer.parseInt(value)); // depends on control dependency: [if], data = [none]
} else if (SMAX.equals(name)) {
node.setSmax(Integer.parseInt(value)); // depends on control dependency: [if], data = [none]
} else if (TTL.equals(name)) {
node.setTtl(TimeUnit.SECONDS.toMillis(Long.parseLong(value))); // depends on control dependency: [if], data = [none]
} else if (TIMEOUT.equals(name)) {
node.setTimeout(Integer.parseInt(value)); // depends on control dependency: [if], data = [none]
} else if (CONTEXT.equals(name)) {
final String[] context = value.split(",");
contexts = Arrays.asList(context); // depends on control dependency: [if], data = [none]
} else if (ALIAS.equals(name)) {
final String[] alias = value.split(",");
hosts = Arrays.asList(alias); // depends on control dependency: [if], data = [none]
} else if(WAITWORKER.equals(name)) {
node.setWaitWorker(Integer.parseInt(value)); // depends on control dependency: [if], data = [none]
} else {
processError(TYPESYNTAX, SBADFLD + name + SBADFLD1, exchange); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
final NodeConfig config;
try {
// Build the config
config = node.build(); // depends on control dependency: [try], data = [none]
if (container.addNode(config, balancer, exchange.getIoThread(), exchange.getConnection().getByteBufferPool())) {
// Apparently this is hard to do in the C part, so maybe we should just remove this
if (contexts != null && hosts != null) {
for (final String context : contexts) {
container.enableContext(context, config.getJvmRoute(), hosts); // depends on control dependency: [for], data = [context]
}
}
processOK(exchange); // depends on control dependency: [if], data = [none]
} else {
processError(MCMPErrorCode.NODE_STILL_EXISTS, exchange); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
processError(MCMPErrorCode.CANT_UPDATE_NODE, exchange);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void generateClass(TreeLogger logger, GeneratorContext context, List<JClassType> subclasses) {
PrintWriter printWriter = context.tryCreate(logger, PACKAGE_NAME, CLASS_NAME);
if (printWriter == null) {
return;
}
ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(PACKAGE_NAME, CLASS_NAME);
composer.addImplementedInterface(INIT_INTERFACE_NAME);
SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
sourceWriter.println("public java.util.Map<String, " + COMMAND_INTERFACE + "> initCommands() {");
sourceWriter.indent();
sourceWriter.println(
"java.util.Map<String, "
+ COMMAND_INTERFACE
+ "> result=new java.util.HashMap<String, "
+ COMMAND_INTERFACE
+ ">();");
for (JClassType type : subclasses) {
sourceWriter.println(
"result.put(\""
+ type.getQualifiedSourceName()
+ "\","
+ type.getQualifiedSourceName()
+ "."
+ GET_COMMAND_METHOD
+ "());");
}
sourceWriter.println("return result;");
sourceWriter.outdent();
sourceWriter.println("}");
sourceWriter.outdent();
sourceWriter.println("}");
context.commit(logger, printWriter);
} } | public class class_name {
public void generateClass(TreeLogger logger, GeneratorContext context, List<JClassType> subclasses) {
PrintWriter printWriter = context.tryCreate(logger, PACKAGE_NAME, CLASS_NAME);
if (printWriter == null) {
return; // depends on control dependency: [if], data = [none]
}
ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(PACKAGE_NAME, CLASS_NAME);
composer.addImplementedInterface(INIT_INTERFACE_NAME);
SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
sourceWriter.println("public java.util.Map<String, " + COMMAND_INTERFACE + "> initCommands() {");
sourceWriter.indent();
sourceWriter.println(
"java.util.Map<String, "
+ COMMAND_INTERFACE
+ "> result=new java.util.HashMap<String, "
+ COMMAND_INTERFACE
+ ">();");
for (JClassType type : subclasses) {
sourceWriter.println(
"result.put(\""
+ type.getQualifiedSourceName()
+ "\","
+ type.getQualifiedSourceName()
+ "."
+ GET_COMMAND_METHOD
+ "());"); // depends on control dependency: [for], data = [none]
}
sourceWriter.println("return result;");
sourceWriter.outdent();
sourceWriter.println("}");
sourceWriter.outdent();
sourceWriter.println("}");
context.commit(logger, printWriter);
} } |
public class class_name {
private static AbstractField<?> createField(final String property) {
if (StringUtils.containsIgnoreCase(property,HIDDEN_FIELD_NAME)) {
return new PasswordField();
} else {
return new TextField();
}
} } | public class class_name {
private static AbstractField<?> createField(final String property) {
if (StringUtils.containsIgnoreCase(property,HIDDEN_FIELD_NAME)) {
return new PasswordField(); // depends on control dependency: [if], data = [none]
} else {
return new TextField(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public <T> Single<PollingState<T>> beginPostOrDeleteAsync(Observable<Response<ResponseBody>> observable, final LongRunningOperationOptions lroOptions, final Type resourceType) {
return observable.map(new Func1<Response<ResponseBody>, PollingState<T>>() {
@Override
public PollingState<T> call(Response<ResponseBody> response) {
RuntimeException exception = createExceptionFromResponse(response, 200, 202, 204);
if (exception != null) {
throw exception;
}
try {
final PollingState<T> pollingState = PollingState.create(response, lroOptions, longRunningOperationRetryTimeout(), resourceType, restClient().serializerAdapter());
pollingState.withPollingUrlFromResponse(response);
pollingState.withPollingRetryTimeoutFromResponse(response);
return pollingState;
} catch (IOException ioException) {
throw Exceptions.propagate(ioException);
}
}
}).toSingle();
} } | public class class_name {
public <T> Single<PollingState<T>> beginPostOrDeleteAsync(Observable<Response<ResponseBody>> observable, final LongRunningOperationOptions lroOptions, final Type resourceType) {
return observable.map(new Func1<Response<ResponseBody>, PollingState<T>>() {
@Override
public PollingState<T> call(Response<ResponseBody> response) {
RuntimeException exception = createExceptionFromResponse(response, 200, 202, 204);
if (exception != null) {
throw exception;
}
try {
final PollingState<T> pollingState = PollingState.create(response, lroOptions, longRunningOperationRetryTimeout(), resourceType, restClient().serializerAdapter());
pollingState.withPollingUrlFromResponse(response); // depends on control dependency: [try], data = [none]
pollingState.withPollingRetryTimeoutFromResponse(response); // depends on control dependency: [try], data = [none]
return pollingState; // depends on control dependency: [try], data = [none]
} catch (IOException ioException) {
throw Exceptions.propagate(ioException);
} // depends on control dependency: [catch], data = [none]
}
}).toSingle();
} } |
public class class_name {
public static String getLocalhostStr() {
InetAddress localhost = getLocalhost();
if (null != localhost) {
return localhost.getHostAddress();
}
return null;
} } | public class class_name {
public static String getLocalhostStr() {
InetAddress localhost = getLocalhost();
if (null != localhost) {
return localhost.getHostAddress();
// depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
private KeyStore getClientTruststore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
KeyStore ks = null;
if (_config.getTruststoreType() != null && !_config.getTruststoreType().isEmpty()) {
try {
ks = KeyStore.getInstance(_config.getTruststoreType());
} catch (KeyStoreException e) {
LOGGER.warn( "The specified truststore type [" + _config.getTruststoreType() + "] didn't work.", e);
throw e;
}
} else {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
}
// get user password and file input stream
char[] password = _config.getTruststorePassword().toCharArray();
java.io.FileInputStream fis = null;
try {
fis = new java.io.FileInputStream(_config.geTruststoreFilename());
ks.load(fis, password);
} finally {
if (fis != null) {
fis.close();
}
}
return ks;
} } | public class class_name {
private KeyStore getClientTruststore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
KeyStore ks = null;
if (_config.getTruststoreType() != null && !_config.getTruststoreType().isEmpty()) {
try {
ks = KeyStore.getInstance(_config.getTruststoreType()); // depends on control dependency: [try], data = [none]
} catch (KeyStoreException e) {
LOGGER.warn( "The specified truststore type [" + _config.getTruststoreType() + "] didn't work.", e);
throw e;
} // depends on control dependency: [catch], data = [none]
} else {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
}
// get user password and file input stream
char[] password = _config.getTruststorePassword().toCharArray();
java.io.FileInputStream fis = null;
try {
fis = new java.io.FileInputStream(_config.geTruststoreFilename());
ks.load(fis, password);
} finally {
if (fis != null) {
fis.close(); // depends on control dependency: [if], data = [none]
}
}
return ks;
} } |
public class class_name {
protected void getChecksumInfo(long blockLength) {
/*
* If bytesPerChecksum is very large, then the metadata file is mostly
* corrupted. For now just truncate bytesPerchecksum to blockLength.
*/
bytesPerChecksum = checksum.getBytesPerChecksum();
if (bytesPerChecksum > 10 * 1024 * 1024 && bytesPerChecksum > blockLength) {
checksum = DataChecksum.newDataChecksum(checksum.getChecksumType(),
Math.max((int) blockLength, 10 * 1024 * 1024));
bytesPerChecksum = checksum.getBytesPerChecksum();
}
checksumSize = checksum.getChecksumSize();
} } | public class class_name {
protected void getChecksumInfo(long blockLength) {
/*
* If bytesPerChecksum is very large, then the metadata file is mostly
* corrupted. For now just truncate bytesPerchecksum to blockLength.
*/
bytesPerChecksum = checksum.getBytesPerChecksum();
if (bytesPerChecksum > 10 * 1024 * 1024 && bytesPerChecksum > blockLength) {
checksum = DataChecksum.newDataChecksum(checksum.getChecksumType(),
Math.max((int) blockLength, 10 * 1024 * 1024)); // depends on control dependency: [if], data = [none]
bytesPerChecksum = checksum.getBytesPerChecksum(); // depends on control dependency: [if], data = [none]
}
checksumSize = checksum.getChecksumSize();
} } |
public class class_name {
public R addRepresentationHintGroup(String... hints) {
if(hints != null) {
mHintHeader.append("[");
mHintHeader.append(TextUtils.join(",", hints));
mHintHeader.append("]");
}
return (R) this;
} } | public class class_name {
public R addRepresentationHintGroup(String... hints) {
if(hints != null) {
mHintHeader.append("["); // depends on control dependency: [if], data = [none]
mHintHeader.append(TextUtils.join(",", hints)); // depends on control dependency: [if], data = [none]
mHintHeader.append("]"); // depends on control dependency: [if], data = [none]
}
return (R) this;
} } |
public class class_name {
@SuppressWarnings("unchecked")
@Override
public final DOMAIN get(Object o) {
try {
return apply((RANGE)o);
} catch (Exception e) {
throw Functor.<RuntimeException>rethrow(e);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
@Override
public final DOMAIN get(Object o) {
try {
return apply((RANGE)o); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw Functor.<RuntimeException>rethrow(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private FromHostPrimitiveResult < String > fromHostString(
CobolContext cobolContext, byte[] hostData, int start, int bytesLen) {
// Trim trailing low-values and, optionally, trailing spaces
int spaceCode = cobolContext.getHostSpaceCharCode();
boolean checkSpace = cobolContext.isTruncateHostStringsTrailingSpaces();
int end = start + bytesLen;
while (end > start) {
int code = hostData[end - 1] & 0xFF;
if (code != 0 && ((checkSpace && code != spaceCode) || !checkSpace)) {
break;
}
end--;
}
// Return early if this is an empty string
if (start == end) {
return new FromHostPrimitiveResult < String >("");
}
// Host strings are sometimes dirty
boolean isDirty = false;
for (int i = start; i < end; i++) {
if (hostData[i] == 0) {
isDirty = true;
break;
}
}
// Cleanup if needed then ask java to convert using the proper host
// character set
String result = null;
try {
if (isDirty) {
byte[] work = new byte[end - start];
for (int i = start; i < end; i++) {
work[i - start] = hostData[i] == 0 ? (byte) cobolContext
.getHostSpaceCharCode() : hostData[i];
}
result = new String(work, cobolContext.getHostCharsetName());
} else {
result = new String(hostData, start, end - start,
cobolContext.getHostCharsetName());
}
} catch (UnsupportedEncodingException e) {
return new FromHostPrimitiveResult < String >(
"Failed to use host character set "
+ cobolContext.getHostCharsetName(), hostData,
start, bytesLen);
}
return new FromHostPrimitiveResult < String >(result);
} } | public class class_name {
private FromHostPrimitiveResult < String > fromHostString(
CobolContext cobolContext, byte[] hostData, int start, int bytesLen) {
// Trim trailing low-values and, optionally, trailing spaces
int spaceCode = cobolContext.getHostSpaceCharCode();
boolean checkSpace = cobolContext.isTruncateHostStringsTrailingSpaces();
int end = start + bytesLen;
while (end > start) {
int code = hostData[end - 1] & 0xFF;
if (code != 0 && ((checkSpace && code != spaceCode) || !checkSpace)) {
break;
}
end--; // depends on control dependency: [while], data = [none]
}
// Return early if this is an empty string
if (start == end) {
return new FromHostPrimitiveResult < String >(""); // depends on control dependency: [if], data = [none]
}
// Host strings are sometimes dirty
boolean isDirty = false;
for (int i = start; i < end; i++) {
if (hostData[i] == 0) {
isDirty = true; // depends on control dependency: [if], data = [none]
break;
}
}
// Cleanup if needed then ask java to convert using the proper host
// character set
String result = null;
try {
if (isDirty) {
byte[] work = new byte[end - start];
for (int i = start; i < end; i++) {
work[i - start] = hostData[i] == 0 ? (byte) cobolContext
.getHostSpaceCharCode() : hostData[i]; // depends on control dependency: [for], data = [i]
}
result = new String(work, cobolContext.getHostCharsetName()); // depends on control dependency: [if], data = [none]
} else {
result = new String(hostData, start, end - start,
cobolContext.getHostCharsetName()); // depends on control dependency: [if], data = [none]
}
} catch (UnsupportedEncodingException e) {
return new FromHostPrimitiveResult < String >(
"Failed to use host character set "
+ cobolContext.getHostCharsetName(), hostData,
start, bytesLen);
} // depends on control dependency: [catch], data = [none]
return new FromHostPrimitiveResult < String >(result);
} } |
public class class_name {
public static void writeJsonToFile(String filename,
List<SemanticParserExampleLoss> losses, List<Map<String, Object>> annotations) {
Preconditions.checkArgument(annotations.size() == losses.size());
List<String> lines = Lists.newArrayList();
for (int i = 0; i < losses.size(); i++) {
lines.add(losses.get(i).toJson(annotations.get(i)));
}
IoUtils.writeLines(filename, lines);
} } | public class class_name {
public static void writeJsonToFile(String filename,
List<SemanticParserExampleLoss> losses, List<Map<String, Object>> annotations) {
Preconditions.checkArgument(annotations.size() == losses.size());
List<String> lines = Lists.newArrayList();
for (int i = 0; i < losses.size(); i++) {
lines.add(losses.get(i).toJson(annotations.get(i))); // depends on control dependency: [for], data = [i]
}
IoUtils.writeLines(filename, lines);
} } |
public class class_name {
void awaitRequests() {
if (!isWaitingForEnriching()) {
return;
}
for (int i = 0; i < NUMBER_OF_WAIT_LOOPS; i++) {
try {
Thread.sleep(THREAD_SLEEP);
if (!isEnrichmentAdvertised()) {
return;
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
throw new SettingRequestTimeoutException();
} } | public class class_name {
void awaitRequests() {
if (!isWaitingForEnriching()) {
return; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < NUMBER_OF_WAIT_LOOPS; i++) {
try {
Thread.sleep(THREAD_SLEEP); // depends on control dependency: [try], data = [none]
if (!isEnrichmentAdvertised()) {
return; // depends on control dependency: [if], data = [none]
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
}
throw new SettingRequestTimeoutException();
} } |
public class class_name {
public EClass getIfcObjectDefinition() {
if (ifcObjectDefinitionEClass == null) {
ifcObjectDefinitionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(328);
}
return ifcObjectDefinitionEClass;
} } | public class class_name {
public EClass getIfcObjectDefinition() {
if (ifcObjectDefinitionEClass == null) {
ifcObjectDefinitionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(328);
// depends on control dependency: [if], data = [none]
}
return ifcObjectDefinitionEClass;
} } |
public class class_name {
private void allowLoneBlock(Node parent) {
if (loneBlocks.isEmpty()) {
return;
}
if (loneBlocks.peek() == parent) {
loneBlocks.pop();
}
} } | public class class_name {
private void allowLoneBlock(Node parent) {
if (loneBlocks.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
if (loneBlocks.peek() == parent) {
loneBlocks.pop(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void fireAttributeRemovedEvent(String name, AttributeValue oldValue) {
if (this.listeners != null && isEventFirable()) {
final AttributeChangeEvent event = new AttributeChangeEvent(
//source
this,
//type
Type.REMOVAL,
//old name
name,
//old value
oldValue,
//current name
name,
//current value
oldValue);
for (final AttributeChangeListener listener : this.listeners) {
listener.onAttributeChangeEvent(event);
}
}
} } | public class class_name {
protected void fireAttributeRemovedEvent(String name, AttributeValue oldValue) {
if (this.listeners != null && isEventFirable()) {
final AttributeChangeEvent event = new AttributeChangeEvent(
//source
this,
//type
Type.REMOVAL,
//old name
name,
//old value
oldValue,
//current name
name,
//current value
oldValue);
for (final AttributeChangeListener listener : this.listeners) {
listener.onAttributeChangeEvent(event); // depends on control dependency: [for], data = [listener]
}
}
} } |
public class class_name {
private void notifyOnCanceled() {
for (Listener<DataType, KeyType, ViewType, ParamType> listener : listeners) {
listener.onCanceled(this);
}
} } | public class class_name {
private void notifyOnCanceled() {
for (Listener<DataType, KeyType, ViewType, ParamType> listener : listeners) {
listener.onCanceled(this); // depends on control dependency: [for], data = [listener]
}
} } |
public class class_name {
public static boolean isFinal(Class<?> expressionType) {
if (expressionType.isArray()) {
return isFinal(expressionType.getComponentType());
}
if (expressionType.isPrimitive()) {
return true;
}
return expressionType.isEnum()
|| Modifier.isFinal(expressionType.getModifiers());
} } | public class class_name {
public static boolean isFinal(Class<?> expressionType) {
if (expressionType.isArray()) {
return isFinal(expressionType.getComponentType()); // depends on control dependency: [if], data = [none]
}
if (expressionType.isPrimitive()) {
return true; // depends on control dependency: [if], data = [none]
}
return expressionType.isEnum()
|| Modifier.isFinal(expressionType.getModifiers());
} } |
public class class_name {
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public void disableFullScreen() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
setImeOptions(getImeOptions() | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
}
} } | public class class_name {
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public void disableFullScreen() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
setImeOptions(getImeOptions() | EditorInfo.IME_FLAG_NO_EXTRACT_UI); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public IPreferenceStore getWritablePreferenceStore(Object context) {
if (this.preferenceStore == null) {
this.preferenceStore = getPreferenceStoreAccess().getWritablePreferenceStore(context);
}
return this.preferenceStore;
} } | public class class_name {
public IPreferenceStore getWritablePreferenceStore(Object context) {
if (this.preferenceStore == null) {
this.preferenceStore = getPreferenceStoreAccess().getWritablePreferenceStore(context); // depends on control dependency: [if], data = [none]
}
return this.preferenceStore;
} } |
public class class_name {
private float getFloatInternal(String key, float defaultValue) {
float retVal = defaultValue;
try {
synchronized (this.confData) {
if (this.confData.containsKey(key)) {
retVal = Float.parseFloat(this.confData.get(key));
}
}
} catch (NumberFormatException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(StringUtils.stringifyException(e));
}
}
return retVal;
} } | public class class_name {
private float getFloatInternal(String key, float defaultValue) {
float retVal = defaultValue;
try {
synchronized (this.confData) { // depends on control dependency: [try], data = [none]
if (this.confData.containsKey(key)) {
retVal = Float.parseFloat(this.confData.get(key)); // depends on control dependency: [if], data = [none]
}
}
} catch (NumberFormatException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(StringUtils.stringifyException(e)); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
return retVal;
} } |
public class class_name {
public VelocityContext buildVelocityContext(Object bean) {
VelocityContext context_ = new VelocityContext();
ClassUtil.ClassInfo beanInfo = ClassUtil.getClassInfo(bean.getClass());
String name = null;
DateFormateMeta dataformat = null;
// String charset = null;
Object value = null;
// Class type = null;
// Method writeMethod = null;
List<ClassUtil.PropertieDescription> attributes = beanInfo.getPropertyDescriptors();
for (int i = 0; attributes != null && i < attributes.size(); i++) {
ClassUtil.PropertieDescription property = attributes.get(i);
ColumnWraper column = property.getColumn();
if (column != null && (column.ignoreCUDbind() || column.ignorebind()))
continue;
// type = property.getPropertyType();
try {
if (property.canread()) {
try {
value = property.getValue(bean);
} catch (InvocationTargetException e1) {
log.error("Failed to get attribute[" + beanInfo.getClazz().getName() + "." + property.getName() + "] value:", e1.getTargetException());
} catch (Exception e1) {
log.error("Failed to get attribute[" + beanInfo.getClazz().getName() + "." + property.getName() + "] value:", e1);
}
name = property.getName();
if (column != null) {
ColumnEditorInf editor = column.editor();
if (editor == null || editor instanceof ColumnToFieldEditor) {
dataformat = column.getDateFormateMeta();
// charset = column.charset();
} else {
Object cv = editor.toColumnValue(column, value);
if (cv == null)
throw new ElasticSearchException("转换属性[" + beanInfo.getClazz().getName() + "." + property.getName() + "]值失败:值为null时,转换器必须返回ColumnType类型的对象,用来指示表字段对应的java类型。");
if (!(cv instanceof ColumnType)) {
value = cv;
// type = value.getClass();
} else {
// type = ((ColumnType) cv).getType();
}
}
}
/**
* since 5.0.6.0,去掉vm模板解析时变量的转义,因此在模板中的使用$aaa模式变量的情况时,需要注意转义的问题,如果存在转义问题,请使用#[]模式变量
* 日期也不做格式化转换,使用$aaa模式变量的情况下需要注意日期格式问题,如果存在日期,则需要使用#[]模式变量,这样bboss会根据bean属性配置的格式,或者变量中指定的格式
* 对日期进行格式化,如果不指定格式采用默认的格式和时区进行处理
*/
/**
if (value == null) {
context_.put(name, null);
} else if (value instanceof Date) {
// if(dataformat != null)
context_.put(name, this.getDate((Date) value, dataformat));
// else {
//// context_.put(name, ((Date) value).getTime());
// context_.put(name, ((Date) value));
// }
} else if(value instanceof String){//提前转义
CharEscapeUtil charEscapeUtil = new CharEscapeUtil();
charEscapeUtil.writeString((String)value,false);
context_.put(name, charEscapeUtil.toString());
}
else {
context_.put(name, value);
}
*/
context_.put(name, value);
// params.addSQLParamWithDateFormateMeta(name, value, sqltype, dataformat,charset);
}
name = null;
value = null;
dataformat = null;
// charset = null;
} catch (SecurityException e) {
throw new ElasticSearchException(e);
} catch (IllegalArgumentException e) {
throw new ElasticSearchException(e);
}
// catch (InvocationTargetException e) {
// throw new ElasticSearchException(e.getTargetException());
// }
catch (Exception e) {
throw new ElasticSearchException(e);
}
}
return context_;
} } | public class class_name {
public VelocityContext buildVelocityContext(Object bean) {
VelocityContext context_ = new VelocityContext();
ClassUtil.ClassInfo beanInfo = ClassUtil.getClassInfo(bean.getClass());
String name = null;
DateFormateMeta dataformat = null;
// String charset = null;
Object value = null;
// Class type = null;
// Method writeMethod = null;
List<ClassUtil.PropertieDescription> attributes = beanInfo.getPropertyDescriptors();
for (int i = 0; attributes != null && i < attributes.size(); i++) {
ClassUtil.PropertieDescription property = attributes.get(i);
ColumnWraper column = property.getColumn();
if (column != null && (column.ignoreCUDbind() || column.ignorebind()))
continue;
// type = property.getPropertyType();
try {
if (property.canread()) {
try {
value = property.getValue(bean); // depends on control dependency: [try], data = [none]
} catch (InvocationTargetException e1) {
log.error("Failed to get attribute[" + beanInfo.getClazz().getName() + "." + property.getName() + "] value:", e1.getTargetException());
} catch (Exception e1) { // depends on control dependency: [catch], data = [none]
log.error("Failed to get attribute[" + beanInfo.getClazz().getName() + "." + property.getName() + "] value:", e1);
} // depends on control dependency: [catch], data = [none]
name = property.getName(); // depends on control dependency: [if], data = [none]
if (column != null) {
ColumnEditorInf editor = column.editor();
if (editor == null || editor instanceof ColumnToFieldEditor) {
dataformat = column.getDateFormateMeta(); // depends on control dependency: [if], data = [none]
// charset = column.charset();
} else {
Object cv = editor.toColumnValue(column, value);
if (cv == null)
throw new ElasticSearchException("转换属性[" + beanInfo.getClazz().getName() + "." + property.getName() + "]值失败:值为null时,转换器必须返回ColumnType类型的对象,用来指示表字段对应的java类型。");
if (!(cv instanceof ColumnType)) {
value = cv; // depends on control dependency: [if], data = [none]
// type = value.getClass();
} else {
// type = ((ColumnType) cv).getType();
}
}
}
/**
* since 5.0.6.0,去掉vm模板解析时变量的转义,因此在模板中的使用$aaa模式变量的情况时,需要注意转义的问题,如果存在转义问题,请使用#[]模式变量
* 日期也不做格式化转换,使用$aaa模式变量的情况下需要注意日期格式问题,如果存在日期,则需要使用#[]模式变量,这样bboss会根据bean属性配置的格式,或者变量中指定的格式
* 对日期进行格式化,如果不指定格式采用默认的格式和时区进行处理
*/
/**
if (value == null) {
context_.put(name, null);
} else if (value instanceof Date) {
// if(dataformat != null)
context_.put(name, this.getDate((Date) value, dataformat));
// else {
//// context_.put(name, ((Date) value).getTime());
// context_.put(name, ((Date) value));
// }
} else if(value instanceof String){//提前转义
CharEscapeUtil charEscapeUtil = new CharEscapeUtil();
charEscapeUtil.writeString((String)value,false);
context_.put(name, charEscapeUtil.toString());
}
else {
context_.put(name, value);
}
*/
context_.put(name, value); // depends on control dependency: [if], data = [none]
// params.addSQLParamWithDateFormateMeta(name, value, sqltype, dataformat,charset);
}
name = null; // depends on control dependency: [try], data = [none]
value = null; // depends on control dependency: [try], data = [none]
dataformat = null; // depends on control dependency: [try], data = [none]
// charset = null;
} catch (SecurityException e) {
throw new ElasticSearchException(e);
} catch (IllegalArgumentException e) { // depends on control dependency: [catch], data = [none]
throw new ElasticSearchException(e);
} // depends on control dependency: [catch], data = [none]
// catch (InvocationTargetException e) {
// throw new ElasticSearchException(e.getTargetException());
// }
catch (Exception e) {
throw new ElasticSearchException(e);
} // depends on control dependency: [catch], data = [none]
}
return context_;
} } |
public class class_name {
public boolean respondToDisconnect(int statusCode, String reasonPhrase) {
initErrorInfo();
if (parent.sendReply(transaction, statusCode, reasonPhrase, myTag, null, -1) != null) {
return true;
}
setReturnCode(parent.getReturnCode());
setException(parent.getException());
setErrorMessage("respondToDisconnect() - " + parent.getErrorMessage());
return false;
} } | public class class_name {
public boolean respondToDisconnect(int statusCode, String reasonPhrase) {
initErrorInfo();
if (parent.sendReply(transaction, statusCode, reasonPhrase, myTag, null, -1) != null) {
return true; // depends on control dependency: [if], data = [none]
}
setReturnCode(parent.getReturnCode());
setException(parent.getException());
setErrorMessage("respondToDisconnect() - " + parent.getErrorMessage());
return false;
} } |
public class class_name {
public ArrayList<ProteinSequence> getProteinCDSSequences() {
ArrayList<ProteinSequence> proteinSequenceList = new ArrayList<ProteinSequence>();
for (int i = 0; i < cdsSequenceList.size(); i++) {
CDSSequence cdsSequence = cdsSequenceList.get(i);
String codingSequence = cdsSequence.getCodingSequence();
// logger.debug("CDS {} {} = {}", getStrand(), cdsSequence.getPhase(), codingSequence);
if (this.getStrand() == Strand.NEGATIVE) {
if (cdsSequence.phase == 1) {
codingSequence = codingSequence.substring(1, codingSequence.length());
} else if (cdsSequence.phase == 2) {
codingSequence = codingSequence.substring(2, codingSequence.length());
}
if (i < cdsSequenceList.size() - 1) {
CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1);
if (nextCDSSequence.phase == 1) {
String nextCodingSequence = nextCDSSequence.getCodingSequence();
codingSequence = codingSequence + nextCodingSequence.substring(0, 1);
} else if (nextCDSSequence.phase == 2) {
String nextCodingSequence = nextCDSSequence.getCodingSequence();
codingSequence = codingSequence + nextCodingSequence.substring(0, 2);
}
}
} else {
if (cdsSequence.phase == 1) {
codingSequence = codingSequence.substring(1, codingSequence.length());
} else if (cdsSequence.phase == 2) {
codingSequence = codingSequence.substring(2, codingSequence.length());
}
if (i < cdsSequenceList.size() - 1) {
CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1);
if (nextCDSSequence.phase == 1) {
String nextCodingSequence = nextCDSSequence.getCodingSequence();
codingSequence = codingSequence + nextCodingSequence.substring(0, 1);
} else if (nextCDSSequence.phase == 2) {
String nextCodingSequence = nextCDSSequence.getCodingSequence();
codingSequence = codingSequence + nextCodingSequence.substring(0, 2);
}
}
}
// logger.debug("Coding Sequence: {}", codingSequence);
DNASequence dnaCodingSequence = null;
try {
dnaCodingSequence = new DNASequence(codingSequence.toUpperCase());
} catch (CompoundNotFoundException e) {
// if I understand this should not happen, please correct if I'm wrong - JD 2014-10-24
logger.error("Could not create DNA coding sequence, {}. This is most likely a bug.", e.getMessage());
}
RNASequence rnaCodingSequence = dnaCodingSequence.getRNASequence(TranscriptionEngine.getDefault());
ProteinSequence proteinSequence = rnaCodingSequence.getProteinSequence(TranscriptionEngine.getDefault());
proteinSequence.setAccession(new AccessionID(cdsSequence.getAccession().getID()));
proteinSequence.setParentDNASequence(cdsSequence, 1, cdsSequence.getLength());
proteinSequenceList.add(proteinSequence);
}
return proteinSequenceList;
} } | public class class_name {
public ArrayList<ProteinSequence> getProteinCDSSequences() {
ArrayList<ProteinSequence> proteinSequenceList = new ArrayList<ProteinSequence>();
for (int i = 0; i < cdsSequenceList.size(); i++) {
CDSSequence cdsSequence = cdsSequenceList.get(i);
String codingSequence = cdsSequence.getCodingSequence();
// logger.debug("CDS {} {} = {}", getStrand(), cdsSequence.getPhase(), codingSequence);
if (this.getStrand() == Strand.NEGATIVE) {
if (cdsSequence.phase == 1) {
codingSequence = codingSequence.substring(1, codingSequence.length()); // depends on control dependency: [if], data = [none]
} else if (cdsSequence.phase == 2) {
codingSequence = codingSequence.substring(2, codingSequence.length()); // depends on control dependency: [if], data = [none]
}
if (i < cdsSequenceList.size() - 1) {
CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1);
if (nextCDSSequence.phase == 1) {
String nextCodingSequence = nextCDSSequence.getCodingSequence();
codingSequence = codingSequence + nextCodingSequence.substring(0, 1); // depends on control dependency: [if], data = [1)]
} else if (nextCDSSequence.phase == 2) {
String nextCodingSequence = nextCDSSequence.getCodingSequence();
codingSequence = codingSequence + nextCodingSequence.substring(0, 2); // depends on control dependency: [if], data = [2)]
}
}
} else {
if (cdsSequence.phase == 1) {
codingSequence = codingSequence.substring(1, codingSequence.length()); // depends on control dependency: [if], data = [none]
} else if (cdsSequence.phase == 2) {
codingSequence = codingSequence.substring(2, codingSequence.length()); // depends on control dependency: [if], data = [none]
}
if (i < cdsSequenceList.size() - 1) {
CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1);
if (nextCDSSequence.phase == 1) {
String nextCodingSequence = nextCDSSequence.getCodingSequence();
codingSequence = codingSequence + nextCodingSequence.substring(0, 1); // depends on control dependency: [if], data = [1)]
} else if (nextCDSSequence.phase == 2) {
String nextCodingSequence = nextCDSSequence.getCodingSequence();
codingSequence = codingSequence + nextCodingSequence.substring(0, 2); // depends on control dependency: [if], data = [2)]
}
}
}
// logger.debug("Coding Sequence: {}", codingSequence);
DNASequence dnaCodingSequence = null;
try {
dnaCodingSequence = new DNASequence(codingSequence.toUpperCase()); // depends on control dependency: [try], data = [none]
} catch (CompoundNotFoundException e) {
// if I understand this should not happen, please correct if I'm wrong - JD 2014-10-24
logger.error("Could not create DNA coding sequence, {}. This is most likely a bug.", e.getMessage());
} // depends on control dependency: [catch], data = [none]
RNASequence rnaCodingSequence = dnaCodingSequence.getRNASequence(TranscriptionEngine.getDefault());
ProteinSequence proteinSequence = rnaCodingSequence.getProteinSequence(TranscriptionEngine.getDefault());
proteinSequence.setAccession(new AccessionID(cdsSequence.getAccession().getID())); // depends on control dependency: [for], data = [none]
proteinSequence.setParentDNASequence(cdsSequence, 1, cdsSequence.getLength()); // depends on control dependency: [for], data = [none]
proteinSequenceList.add(proteinSequence); // depends on control dependency: [for], data = [none]
}
return proteinSequenceList;
} } |
public class class_name {
public ValidationSessionInfo checkAuth(ValidationLoginInfo info, HttpServletRequest req, HttpServletResponse res) {
if (info.getToken() == null || info.getToken().isEmpty()) {
throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED);
}
if (this.validationConfig.getAuthToken() == null) {
throw new ValidationLibException("Sever authkey is not helper ", HttpStatus.INTERNAL_SERVER_ERROR);
}
if (validaitonSessionCheckAndRemake(info.getToken())) {
return this.createSession(req, res);
}
if (!this.validationConfig.getAuthToken().equals(info.getToken())) {
throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED);
}
req.getSession();
return this.createSession(req, res);
} } | public class class_name {
public ValidationSessionInfo checkAuth(ValidationLoginInfo info, HttpServletRequest req, HttpServletResponse res) {
if (info.getToken() == null || info.getToken().isEmpty()) {
throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED);
}
if (this.validationConfig.getAuthToken() == null) {
throw new ValidationLibException("Sever authkey is not helper ", HttpStatus.INTERNAL_SERVER_ERROR);
}
if (validaitonSessionCheckAndRemake(info.getToken())) {
return this.createSession(req, res); // depends on control dependency: [if], data = [none]
}
if (!this.validationConfig.getAuthToken().equals(info.getToken())) {
throw new ValidationLibException("UnAuthorization", HttpStatus.UNAUTHORIZED);
}
req.getSession();
return this.createSession(req, res);
} } |
public class class_name {
protected int findAndEliminateRedundant(int start, int firstOccuranceIndex,
ExpressionOwner firstOccuranceOwner,
ElemTemplateElement psuedoVarRecipient,
Vector paths)
throws org.w3c.dom.DOMException
{
MultistepExprHolder head = null;
MultistepExprHolder tail = null;
int numPathsFound = 0;
int n = paths.size();
Expression expr1 = firstOccuranceOwner.getExpression();
if(DEBUG)
assertIsLocPathIterator(expr1, firstOccuranceOwner);
boolean isGlobal = (paths == m_absPaths);
LocPathIterator lpi = (LocPathIterator)expr1;
int stepCount = countSteps(lpi);
for(int j = start; j < n; j++)
{
ExpressionOwner owner2 = (ExpressionOwner)paths.elementAt(j);
if(null != owner2)
{
Expression expr2 = owner2.getExpression();
boolean isEqual = expr2.deepEquals(lpi);
if(isEqual)
{
LocPathIterator lpi2 = (LocPathIterator)expr2;
if(null == head)
{
head = new MultistepExprHolder(firstOccuranceOwner, stepCount, null);
tail = head;
numPathsFound++;
}
tail.m_next = new MultistepExprHolder(owner2, stepCount, null);
tail = tail.m_next;
// Null out the occurance, so we don't have to test it again.
paths.setElementAt(null, j);
// foundFirst = true;
numPathsFound++;
}
}
}
// Change all globals in xsl:templates, etc, to global vars no matter what.
if((0 == numPathsFound) && isGlobal)
{
head = new MultistepExprHolder(firstOccuranceOwner, stepCount, null);
numPathsFound++;
}
if(null != head)
{
ElemTemplateElement root = isGlobal ? psuedoVarRecipient : findCommonAncestor(head);
LocPathIterator sharedIter = (LocPathIterator)head.m_exprOwner.getExpression();
ElemVariable var = createPseudoVarDecl(root, sharedIter, isGlobal);
if(DIAGNOSE_MULTISTEPLIST)
System.err.println("Created var: "+var.getName()+(isGlobal ? "(Global)" : ""));
QName uniquePseudoVarName = var.getName();
while(null != head)
{
ExpressionOwner owner = head.m_exprOwner;
if(DIAGNOSE_MULTISTEPLIST)
diagnoseLineNumber(owner.getExpression());
changeToVarRef(uniquePseudoVarName, owner, paths, root);
head = head.m_next;
}
// Replace the first occurance with the variable's XPath, so
// that further reduction may take place if needed.
paths.setElementAt(var.getSelect(), firstOccuranceIndex);
}
return numPathsFound;
} } | public class class_name {
protected int findAndEliminateRedundant(int start, int firstOccuranceIndex,
ExpressionOwner firstOccuranceOwner,
ElemTemplateElement psuedoVarRecipient,
Vector paths)
throws org.w3c.dom.DOMException
{
MultistepExprHolder head = null;
MultistepExprHolder tail = null;
int numPathsFound = 0;
int n = paths.size();
Expression expr1 = firstOccuranceOwner.getExpression();
if(DEBUG)
assertIsLocPathIterator(expr1, firstOccuranceOwner);
boolean isGlobal = (paths == m_absPaths);
LocPathIterator lpi = (LocPathIterator)expr1;
int stepCount = countSteps(lpi);
for(int j = start; j < n; j++)
{
ExpressionOwner owner2 = (ExpressionOwner)paths.elementAt(j);
if(null != owner2)
{
Expression expr2 = owner2.getExpression();
boolean isEqual = expr2.deepEquals(lpi);
if(isEqual)
{
LocPathIterator lpi2 = (LocPathIterator)expr2;
if(null == head)
{
head = new MultistepExprHolder(firstOccuranceOwner, stepCount, null); // depends on control dependency: [if], data = [none]
tail = head; // depends on control dependency: [if], data = [none]
numPathsFound++; // depends on control dependency: [if], data = [none]
}
tail.m_next = new MultistepExprHolder(owner2, stepCount, null); // depends on control dependency: [if], data = [none]
tail = tail.m_next; // depends on control dependency: [if], data = [none]
// Null out the occurance, so we don't have to test it again.
paths.setElementAt(null, j); // depends on control dependency: [if], data = [none]
// foundFirst = true;
numPathsFound++; // depends on control dependency: [if], data = [none]
}
}
}
// Change all globals in xsl:templates, etc, to global vars no matter what.
if((0 == numPathsFound) && isGlobal)
{
head = new MultistepExprHolder(firstOccuranceOwner, stepCount, null);
numPathsFound++;
}
if(null != head)
{
ElemTemplateElement root = isGlobal ? psuedoVarRecipient : findCommonAncestor(head);
LocPathIterator sharedIter = (LocPathIterator)head.m_exprOwner.getExpression();
ElemVariable var = createPseudoVarDecl(root, sharedIter, isGlobal);
if(DIAGNOSE_MULTISTEPLIST)
System.err.println("Created var: "+var.getName()+(isGlobal ? "(Global)" : ""));
QName uniquePseudoVarName = var.getName();
while(null != head)
{
ExpressionOwner owner = head.m_exprOwner;
if(DIAGNOSE_MULTISTEPLIST)
diagnoseLineNumber(owner.getExpression());
changeToVarRef(uniquePseudoVarName, owner, paths, root);
head = head.m_next;
}
// Replace the first occurance with the variable's XPath, so
// that further reduction may take place if needed.
paths.setElementAt(var.getSelect(), firstOccuranceIndex);
}
return numPathsFound;
} } |
public class class_name {
@Deprecated
@Override
protected int writeValueAndFinal(int i, boolean isFinal) {
if(0<=i && i<=CharsTrie.kMaxOneUnitValue) {
return write(i|(isFinal ? CharsTrie.kValueIsFinal : 0));
}
int length;
if(i<0 || i>CharsTrie.kMaxTwoUnitValue) {
intUnits[0]=(char)(CharsTrie.kThreeUnitValueLead);
intUnits[1]=(char)(i>>16);
intUnits[2]=(char)i;
length=3;
// } else if(i<=CharsTrie.kMaxOneUnitValue) {
// intUnits[0]=(char)(i);
// length=1;
} else {
intUnits[0]=(char)(CharsTrie.kMinTwoUnitValueLead+(i>>16));
intUnits[1]=(char)i;
length=2;
}
intUnits[0]=(char)(intUnits[0]|(isFinal ? CharsTrie.kValueIsFinal : 0));
return write(intUnits, length);
} } | public class class_name {
@Deprecated
@Override
protected int writeValueAndFinal(int i, boolean isFinal) {
if(0<=i && i<=CharsTrie.kMaxOneUnitValue) {
return write(i|(isFinal ? CharsTrie.kValueIsFinal : 0)); // depends on control dependency: [if], data = [none]
}
int length;
if(i<0 || i>CharsTrie.kMaxTwoUnitValue) {
intUnits[0]=(char)(CharsTrie.kThreeUnitValueLead); // depends on control dependency: [if], data = [none]
intUnits[1]=(char)(i>>16); // depends on control dependency: [if], data = [none]
intUnits[2]=(char)i; // depends on control dependency: [if], data = [none]
length=3; // depends on control dependency: [if], data = [none]
// } else if(i<=CharsTrie.kMaxOneUnitValue) {
// intUnits[0]=(char)(i);
// length=1;
} else {
intUnits[0]=(char)(CharsTrie.kMinTwoUnitValueLead+(i>>16)); // depends on control dependency: [if], data = [none]
intUnits[1]=(char)i; // depends on control dependency: [if], data = [none]
length=2; // depends on control dependency: [if], data = [none]
}
intUnits[0]=(char)(intUnits[0]|(isFinal ? CharsTrie.kValueIsFinal : 0));
return write(intUnits, length);
} } |
public class class_name {
public int getSeconds() {
// TODO ahai 如果当月时间未到呢?
Calendar cld = Calendar.getInstance();
cld.add(Calendar.MONTH, 1);
cld.set(Calendar.DAY_OF_MONTH, day);
cld.set(Calendar.HOUR_OF_DAY, this.hour);
cld.set(Calendar.MINUTE, this.minute);
cld.set(Calendar.SECOND, this.second);
long time = cld.getTimeInMillis();
long diff = time - System.currentTimeMillis();
if (diff <= 0) {// 一定要小于等于0
// 本周的时间已过,下周再执行
diff += 7 * 24 * 60 * 60 * 1000L;
}
int seconds = (int) (diff / 1000);
return seconds;
} } | public class class_name {
public int getSeconds() {
// TODO ahai 如果当月时间未到呢?
Calendar cld = Calendar.getInstance();
cld.add(Calendar.MONTH, 1);
cld.set(Calendar.DAY_OF_MONTH, day);
cld.set(Calendar.HOUR_OF_DAY, this.hour);
cld.set(Calendar.MINUTE, this.minute);
cld.set(Calendar.SECOND, this.second);
long time = cld.getTimeInMillis();
long diff = time - System.currentTimeMillis();
if (diff <= 0) {// 一定要小于等于0
// 本周的时间已过,下周再执行
diff += 7 * 24 * 60 * 60 * 1000L;
// depends on control dependency: [if], data = [none]
}
int seconds = (int) (diff / 1000);
return seconds;
} } |
public class class_name {
@Override
public CheckSum generateCheckSum() {
InputStream stream = null;
try {
stream = openSqlStream();
String sql = this.sql;
if ((stream == null) && (sql == null)) {
sql = "";
}
if (sql != null) {
stream = new ByteArrayInputStream(
sql.getBytes(
LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class)
.getOutputEncoding()
)
);
}
return CheckSum.compute(new NormalizingStream(this.getEndDelimiter(), this.isSplitStatements(), this.isStripComments(), stream), false);
} catch (IOException e) {
throw new UnexpectedLiquibaseException(e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Scope.getCurrentScope().getLog(getClass()).fine(LogType.LOG, "Error closing stream", e);
}
}
}
} } | public class class_name {
@Override
public CheckSum generateCheckSum() {
InputStream stream = null;
try {
stream = openSqlStream(); // depends on control dependency: [try], data = [none]
String sql = this.sql;
if ((stream == null) && (sql == null)) {
sql = ""; // depends on control dependency: [if], data = [none]
}
if (sql != null) {
stream = new ByteArrayInputStream(
sql.getBytes(
LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class)
.getOutputEncoding()
)
); // depends on control dependency: [if], data = [none]
}
return CheckSum.compute(new NormalizingStream(this.getEndDelimiter(), this.isSplitStatements(), this.isStripComments(), stream), false); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new UnexpectedLiquibaseException(e);
} finally { // depends on control dependency: [catch], data = [none]
if (stream != null) {
try {
stream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
Scope.getCurrentScope().getLog(getClass()).fine(LogType.LOG, "Error closing stream", e);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
public void marshall(Insight insight, ProtocolMarshaller protocolMarshaller) {
if (insight == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(insight.getInsightArn(), INSIGHTARN_BINDING);
protocolMarshaller.marshall(insight.getName(), NAME_BINDING);
protocolMarshaller.marshall(insight.getFilters(), FILTERS_BINDING);
protocolMarshaller.marshall(insight.getGroupByAttribute(), GROUPBYATTRIBUTE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Insight insight, ProtocolMarshaller protocolMarshaller) {
if (insight == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(insight.getInsightArn(), INSIGHTARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(insight.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(insight.getFilters(), FILTERS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(insight.getGroupByAttribute(), GROUPBYATTRIBUTE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static ArrayList<ArrayList<HashMap<String, String>>> getAutoEventDate(Map data, String[] pdates) {
ArrayList<ArrayList<HashMap<String, String>>> results = new ArrayList<ArrayList<HashMap<String, String>>>();
// If no more planting event is required
if (pdates.length < 1) {
LOG.error("There is no PDATE can be used for event generation.");
return results;
}
// Get Event date
ArrayList<HashMap<String, String>> events = MapUtil.getBucket(data, "management").getDataList();
while (results.size() < pdates.length) {
results.add(new ArrayList());
}
String orgPdate = getValueOr(data, "origin_pdate", "-99");
if (orgPdate.equals("")) {
LOG.error("The original PDATE is missing, can't calculate other event date");
} else if (orgPdate.equals("-99")) {
orgPdate = getFstPdate(data, "");
}
if (orgPdate.equals("")) {
LOG.warn("The original PDATE is missing, use first given PDATE {} as original one", pdates[0]);
orgPdate = pdates[0];
} else {
LOG.debug("Find original PDATE {}", orgPdate);
}
for (HashMap<String, String> event : events) {
// Get days after planting for current event date
String date = getValueOr(event, "date", "");
String orgDap = "";
String eventType = getValueOr(event, "event", "unknown");
// if it is a planting event
if (eventType.equals("planting")) {
orgDap = "0";
} else {
if (date.equals("")) {
LOG.debug("Original {} event has an invalid date: [{}].", eventType, date);
} else {
orgDap = calcDAP(date, orgPdate);
LOG.debug("Original {} event date: [{}].", eventType, date);
LOG.debug("Original {} event's DAP: [{}]", eventType, orgDap);
}
}
// Special handling for edate
String edate = getValueOr(event, "edate", "");
String orgEDap = "";
if (!edate.equals("")) {
orgEDap = calcDAP(edate, orgPdate);
LOG.debug("Original EDATE's DAP: [{}].", orgDap);
}
for (int j = 0; j < pdates.length; j++) {
HashMap<String, String> newEvent = new HashMap();
newEvent.putAll(event);
if (!date.equals("")) {
newEvent.put("date", dateOffset(pdates[j], orgDap));
}
if (!edate.equals("")) {
newEvent.put("edate", dateOffset(pdates[j], orgEDap));
}
results.get(j).add(newEvent);
}
}
return results;
} } | public class class_name {
public static ArrayList<ArrayList<HashMap<String, String>>> getAutoEventDate(Map data, String[] pdates) {
ArrayList<ArrayList<HashMap<String, String>>> results = new ArrayList<ArrayList<HashMap<String, String>>>();
// If no more planting event is required
if (pdates.length < 1) {
LOG.error("There is no PDATE can be used for event generation."); // depends on control dependency: [if], data = [none]
return results; // depends on control dependency: [if], data = [none]
}
// Get Event date
ArrayList<HashMap<String, String>> events = MapUtil.getBucket(data, "management").getDataList();
while (results.size() < pdates.length) {
results.add(new ArrayList()); // depends on control dependency: [while], data = [none]
}
String orgPdate = getValueOr(data, "origin_pdate", "-99");
if (orgPdate.equals("")) {
LOG.error("The original PDATE is missing, can't calculate other event date");
} else if (orgPdate.equals("-99")) {
orgPdate = getFstPdate(data, "");
}
if (orgPdate.equals("")) {
LOG.warn("The original PDATE is missing, use first given PDATE {} as original one", pdates[0]);
orgPdate = pdates[0];
} else {
LOG.debug("Find original PDATE {}", orgPdate);
}
for (HashMap<String, String> event : events) {
// Get days after planting for current event date
String date = getValueOr(event, "date", "");
String orgDap = "";
String eventType = getValueOr(event, "event", "unknown");
// if it is a planting event
if (eventType.equals("planting")) {
orgDap = "0";
} else {
if (date.equals("")) {
LOG.debug("Original {} event has an invalid date: [{}].", eventType, date);
} else {
orgDap = calcDAP(date, orgPdate);
LOG.debug("Original {} event date: [{}].", eventType, date);
LOG.debug("Original {} event's DAP: [{}]", eventType, orgDap); // depends on control dependency: [if], data = [none]
}
}
// Special handling for edate
String edate = getValueOr(event, "edate", "");
String orgEDap = "";
if (!edate.equals("")) {
orgEDap = calcDAP(edate, orgPdate);
LOG.debug("Original EDATE's DAP: [{}].", orgDap);
}
for (int j = 0; j < pdates.length; j++) {
HashMap<String, String> newEvent = new HashMap();
newEvent.putAll(event);
if (!date.equals("")) {
newEvent.put("date", dateOffset(pdates[j], orgDap)); // depends on control dependency: [if], data = [none]
}
if (!edate.equals("")) {
newEvent.put("edate", dateOffset(pdates[j], orgEDap)); // depends on control dependency: [if], data = [none]
}
results.get(j).add(newEvent);
}
}
return results;
} } |
public class class_name {
public static Optional<Key> buildRSAPublicKey(final String keyType, final BigInteger modulus,
final BigInteger exponent) {
try {
return of(KeyFactory.getInstance(keyType).generatePublic(new RSAPublicKeySpec(modulus, exponent)));
} catch (final NoSuchAlgorithmException | InvalidKeySpecException ex) {
LOGGER.error("Error generating RSA Key from JWKS entry", ex);
}
return empty();
} } | public class class_name {
public static Optional<Key> buildRSAPublicKey(final String keyType, final BigInteger modulus,
final BigInteger exponent) {
try {
return of(KeyFactory.getInstance(keyType).generatePublic(new RSAPublicKeySpec(modulus, exponent))); // depends on control dependency: [try], data = [none]
} catch (final NoSuchAlgorithmException | InvalidKeySpecException ex) {
LOGGER.error("Error generating RSA Key from JWKS entry", ex);
} // depends on control dependency: [catch], data = [none]
return empty();
} } |
public class class_name {
public void parseName(String cpeName) throws UnsupportedEncodingException {
if (cpeName != null && cpeName.length() > 7) {
final String cpeNameWithoutPrefix = cpeName.substring(7);
final String[] data = StringUtils.split(cpeNameWithoutPrefix, ':');
if (data.length >= 1) {
vendor = URLDecoder.decode(data[0].replace("+", "%2B"), StandardCharsets.UTF_8.name());
if (data.length >= 2) {
product = URLDecoder.decode(data[1].replace("+", "%2B"), StandardCharsets.UTF_8.name());
}
}
}
} } | public class class_name {
public void parseName(String cpeName) throws UnsupportedEncodingException {
if (cpeName != null && cpeName.length() > 7) {
final String cpeNameWithoutPrefix = cpeName.substring(7);
final String[] data = StringUtils.split(cpeNameWithoutPrefix, ':');
if (data.length >= 1) {
vendor = URLDecoder.decode(data[0].replace("+", "%2B"), StandardCharsets.UTF_8.name()); // depends on control dependency: [if], data = [none]
if (data.length >= 2) {
product = URLDecoder.decode(data[1].replace("+", "%2B"), StandardCharsets.UTF_8.name()); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public JSONWriter object() {
if (this.mode == INIT) {
this.mode = OBJECT;
}
if (this.mode == OBJECT || this.mode == ARRAY) {
this.append("{");
this.push(KEY);
this.comma = false;
return this;
}
throw new JSONException("Misplaced object: expected mode of INIT, OBJECT or ARRAY but was " + this.mode);
} } | public class class_name {
public JSONWriter object() {
if (this.mode == INIT) {
this.mode = OBJECT; // depends on control dependency: [if], data = [none]
}
if (this.mode == OBJECT || this.mode == ARRAY) {
this.append("{"); // depends on control dependency: [if], data = [none]
this.push(KEY); // depends on control dependency: [if], data = [none]
this.comma = false; // depends on control dependency: [if], data = [none]
return this; // depends on control dependency: [if], data = [none]
}
throw new JSONException("Misplaced object: expected mode of INIT, OBJECT or ARRAY but was " + this.mode);
} } |
public class class_name {
private Collection<SagaType> prepareTypesList() {
Collection<SagaType> sagaTypes = new ArrayList<>();
// search for other sagas started by timeouts
Collection<SagaType> sagasToExecute = typesForMessageMapper.getSagasForMessageType(Timeout.class);
for (SagaType type : sagasToExecute) {
if (type.isStartingNewSaga()) {
sagaTypes.add(type);
}
}
return sagaTypes;
} } | public class class_name {
private Collection<SagaType> prepareTypesList() {
Collection<SagaType> sagaTypes = new ArrayList<>();
// search for other sagas started by timeouts
Collection<SagaType> sagasToExecute = typesForMessageMapper.getSagasForMessageType(Timeout.class);
for (SagaType type : sagasToExecute) {
if (type.isStartingNewSaga()) {
sagaTypes.add(type); // depends on control dependency: [if], data = [none]
}
}
return sagaTypes;
} } |
public class class_name {
public void setRenderOrder (int renderOrder)
{
if (_renderOrder != renderOrder) {
_renderOrder = renderOrder;
if (_mgr != null) {
_mgr.renderOrderDidChange(this);
invalidate();
}
}
} } | public class class_name {
public void setRenderOrder (int renderOrder)
{
if (_renderOrder != renderOrder) {
_renderOrder = renderOrder; // depends on control dependency: [if], data = [none]
if (_mgr != null) {
_mgr.renderOrderDidChange(this); // depends on control dependency: [if], data = [none]
invalidate(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public Object resolveObject(String variable, int lineNumber, int startPosition) {
if (StringUtils.isBlank(variable)) {
return "";
}
if (WhitespaceUtils.isQuoted(variable)) {
return WhitespaceUtils.unquote(variable);
} else {
Object val = retraceVariable(variable, lineNumber, startPosition);
if (val == null) {
return variable;
}
return val;
}
} } | public class class_name {
public Object resolveObject(String variable, int lineNumber, int startPosition) {
if (StringUtils.isBlank(variable)) {
return ""; // depends on control dependency: [if], data = [none]
}
if (WhitespaceUtils.isQuoted(variable)) {
return WhitespaceUtils.unquote(variable); // depends on control dependency: [if], data = [none]
} else {
Object val = retraceVariable(variable, lineNumber, startPosition);
if (val == null) {
return variable; // depends on control dependency: [if], data = [none]
}
return val; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public T withSubItems(List<IDrawerItem> subItems) {
this.mSubItems = subItems;
for (IDrawerItem subItem : subItems) {
subItem.withParent(this);
}
return (T) this;
} } | public class class_name {
public T withSubItems(List<IDrawerItem> subItems) {
this.mSubItems = subItems;
for (IDrawerItem subItem : subItems) {
subItem.withParent(this); // depends on control dependency: [for], data = [subItem]
}
return (T) this;
} } |
public class class_name {
@Override
public EClass getListOfIfcParameterValue() {
if (listOfIfcParameterValueEClass == null) {
listOfIfcParameterValueEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1180);
}
return listOfIfcParameterValueEClass;
} } | public class class_name {
@Override
public EClass getListOfIfcParameterValue() {
if (listOfIfcParameterValueEClass == null) {
listOfIfcParameterValueEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1180);
// depends on control dependency: [if], data = [none]
}
return listOfIfcParameterValueEClass;
} } |
public class class_name {
public void putFunctionForId(String id, DifferentialFunction function) {
if (ops.containsKey(id) && ops.get(id).getOp() == null) {
throw new ND4JIllegalStateException("Function by id already exists!");
} else if (function instanceof SDVariable) {
throw new ND4JIllegalStateException("Function must not be a variable!");
}
if(ops.containsKey(id)){
} else {
ops.put(id, SameDiffOp.builder().name(id).op(function).build());
}
} } | public class class_name {
public void putFunctionForId(String id, DifferentialFunction function) {
if (ops.containsKey(id) && ops.get(id).getOp() == null) {
throw new ND4JIllegalStateException("Function by id already exists!");
} else if (function instanceof SDVariable) {
throw new ND4JIllegalStateException("Function must not be a variable!");
}
if(ops.containsKey(id)){
} else {
ops.put(id, SameDiffOp.builder().name(id).op(function).build()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static String getLoggingProfileName(final PathAddress address) {
for (PathElement pathElement : address) {
if (CommonAttributes.LOGGING_PROFILE.equals(pathElement.getKey())) {
return pathElement.getValue();
}
}
return null;
} } | public class class_name {
static String getLoggingProfileName(final PathAddress address) {
for (PathElement pathElement : address) {
if (CommonAttributes.LOGGING_PROFILE.equals(pathElement.getKey())) {
return pathElement.getValue(); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static NetworkAddress parse(String networkAddress) {
NetworkAddress address = null;
if (networkAddress != null) {
String[] split = networkAddress.split("/");
if (split.length == 2) {
byte[] network = parseDottedQuad(split[0]);
byte[] netmask = parseDottedQuad(split[1]);
address = toNetworkAddress(network, netmask);
}
else {
throw new IllegalArgumentException("Network address must be ip4Address/netMask");
}
}
return address;
} } | public class class_name {
public static NetworkAddress parse(String networkAddress) {
NetworkAddress address = null;
if (networkAddress != null) {
String[] split = networkAddress.split("/");
if (split.length == 2) {
byte[] network = parseDottedQuad(split[0]);
byte[] netmask = parseDottedQuad(split[1]);
address = toNetworkAddress(network, netmask); // depends on control dependency: [if], data = [none]
}
else {
throw new IllegalArgumentException("Network address must be ip4Address/netMask");
}
}
return address;
} } |
public class class_name {
@Deprecated
public static DatasetDescriptor fromDataMap(Map<String, String> dataMap) {
DatasetDescriptor descriptor = new DatasetDescriptor(dataMap.get(PLATFORM_KEY), dataMap.get(NAME_KEY));
dataMap.forEach((key, value) -> {
if (!key.equals(PLATFORM_KEY) && !key.equals(NAME_KEY)) {
descriptor.addMetadata(key, value);
}
});
return descriptor;
} } | public class class_name {
@Deprecated
public static DatasetDescriptor fromDataMap(Map<String, String> dataMap) {
DatasetDescriptor descriptor = new DatasetDescriptor(dataMap.get(PLATFORM_KEY), dataMap.get(NAME_KEY));
dataMap.forEach((key, value) -> {
if (!key.equals(PLATFORM_KEY) && !key.equals(NAME_KEY)) {
descriptor.addMetadata(key, value); // depends on control dependency: [if], data = [none]
}
});
return descriptor;
} } |
public class class_name {
@Override
@FFDCIgnore({ CredentialDestroyedException.class, CredentialExpiredException.class })
public boolean isSubjectValid(Subject subject) {
boolean valid = false;
try {
WSCredential wsCredential = getWSCredential(subject);
if (wsCredential != null) {
long credentialExpirationInMillis = wsCredential.getExpiration();
Date currentTime = new Date();
Date expirationTime = new Date(credentialExpirationInMillis);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Current time = " + currentTime + ", expiration time = " + expirationTime);
}
if (credentialExpirationInMillis == 0 || credentialExpirationInMillis == -1 ||
currentTime.before(expirationTime)) {
valid = true;
}
}
} catch (CredentialDestroyedException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "CredentialDestroyedException while determining the validity of the subject.", e);
}
} catch (CredentialExpiredException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "CredentialExpiredException while determining the validity of the subject.", e);
}
}
return valid;
} } | public class class_name {
@Override
@FFDCIgnore({ CredentialDestroyedException.class, CredentialExpiredException.class })
public boolean isSubjectValid(Subject subject) {
boolean valid = false;
try {
WSCredential wsCredential = getWSCredential(subject);
if (wsCredential != null) {
long credentialExpirationInMillis = wsCredential.getExpiration();
Date currentTime = new Date();
Date expirationTime = new Date(credentialExpirationInMillis);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Current time = " + currentTime + ", expiration time = " + expirationTime); // depends on control dependency: [if], data = [none]
}
if (credentialExpirationInMillis == 0 || credentialExpirationInMillis == -1 ||
currentTime.before(expirationTime)) {
valid = true; // depends on control dependency: [if], data = [none]
}
}
} catch (CredentialDestroyedException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "CredentialDestroyedException while determining the validity of the subject.", e); // depends on control dependency: [if], data = [none]
}
} catch (CredentialExpiredException e) { // depends on control dependency: [catch], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "CredentialExpiredException while determining the validity of the subject.", e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
return valid;
} } |
public class class_name {
private static boolean match(Belief belief, AQuery query) {
assert (belief != null);
assert (query != null);
if (belief.getBeliefset() != query.getBeliefset()) {
return false;
}
switch (query.getOp()) {
case EQ:
Object lhs = belief.getTuple()[query.getField()];
Object rhs = query.getValue();
// Match wildcard or exact string
return "*".equals(rhs) || lhs.equals(rhs);
case GT:
// TODO: Handle Operator.GT
case LT:
// TODO: Handle Operator.LT
default:
break;
}
return false;
} } | public class class_name {
private static boolean match(Belief belief, AQuery query) {
assert (belief != null);
assert (query != null);
if (belief.getBeliefset() != query.getBeliefset()) {
return false; // depends on control dependency: [if], data = [none]
}
switch (query.getOp()) {
case EQ:
Object lhs = belief.getTuple()[query.getField()];
Object rhs = query.getValue();
// Match wildcard or exact string
return "*".equals(rhs) || lhs.equals(rhs);
case GT:
// TODO: Handle Operator.GT
case LT:
// TODO: Handle Operator.LT
default:
break;
}
return false;
} } |
public class class_name {
@Override
public synchronized void cleanup() {
String pattern = MessageFormat.format(LOGGER_SYSTEM_FORMAT_PATTERN, this.loggerSystemName);
LogFilenameMatcher matcher = new LogFilenameMatcher(pattern);
LogFileTraverser.ICollectorCallback cb = new LogFileTraverser.ICollectorCallback() {
@Override
public void match(File file,
LogFilenameMatcher.LogFilenameParts parts) {
boolean success = file.delete();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deleting " + file + " success=" + success);
}
}
};
new LogFileTraverser(matcher,
FileChannelDataLoggerFactory.this.getLoggingDirectory(), cb);
} } | public class class_name {
@Override
public synchronized void cleanup() {
String pattern = MessageFormat.format(LOGGER_SYSTEM_FORMAT_PATTERN, this.loggerSystemName);
LogFilenameMatcher matcher = new LogFilenameMatcher(pattern);
LogFileTraverser.ICollectorCallback cb = new LogFileTraverser.ICollectorCallback() {
@Override
public void match(File file,
LogFilenameMatcher.LogFilenameParts parts) {
boolean success = file.delete();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deleting " + file + " success=" + success); // depends on control dependency: [if], data = [none]
}
}
};
new LogFileTraverser(matcher,
FileChannelDataLoggerFactory.this.getLoggingDirectory(), cb);
} } |
public class class_name {
public static String simpleTemplateToRegEx(String template) {
StringBuilder sb = new StringBuilder();
Matcher m = TEMPLATE_PATTERN.matcher(template);
int n = 0;
while(m.find(n)) {
if (m.start() != n) {
throw new IllegalArgumentException("Cannot tokenize [" + template + "]");
}
String match = m.group();
if (m.group(1) != null) {
sb.append(match);
}
else if (m.group(2) != null) {
sb.append("\\s+");
}
else if (m.group(3) != null) {
sb.append('\\').append(match);
}
else {
sb.append(match);
}
n = m.end();
}
return sb.toString();
} } | public class class_name {
public static String simpleTemplateToRegEx(String template) {
StringBuilder sb = new StringBuilder();
Matcher m = TEMPLATE_PATTERN.matcher(template);
int n = 0;
while(m.find(n)) {
if (m.start() != n) {
throw new IllegalArgumentException("Cannot tokenize [" + template + "]");
}
String match = m.group();
if (m.group(1) != null) {
sb.append(match); // depends on control dependency: [if], data = [none]
}
else if (m.group(2) != null) {
sb.append("\\s+"); // depends on control dependency: [if], data = [none]
}
else if (m.group(3) != null) {
sb.append('\\').append(match); // depends on control dependency: [if], data = [none]
}
else {
sb.append(match); // depends on control dependency: [if], data = [none]
}
n = m.end(); // depends on control dependency: [while], data = [none]
}
return sb.toString();
} } |
public class class_name {
public ValidationResults validate(T object, String propertyName) {
if (propertyName == null) {
results.clearMessages();
}
else {
results.clearMessages(propertyName);
}
addInvalidValues(doValidate(object, propertyName));
return results;
} } | public class class_name {
public ValidationResults validate(T object, String propertyName) {
if (propertyName == null) {
results.clearMessages(); // depends on control dependency: [if], data = [none]
}
else {
results.clearMessages(propertyName); // depends on control dependency: [if], data = [(propertyName]
}
addInvalidValues(doValidate(object, propertyName));
return results;
} } |
public class class_name {
public boolean process( double sampleRadius , Quadrilateral_F64 input ) {
work.set(input);
samples.reset();
estimator.process(work,false);
estimator.getWorldToCamera().invert(referenceCameraToWorld);
samples.reset();
createSamples(sampleRadius,work.a,input.a);
createSamples(sampleRadius,work.b,input.b);
createSamples(sampleRadius,work.c,input.c);
createSamples(sampleRadius,work.d,input.d);
if( samples.size() < 10 )
return false;
maxLocation = 0;
maxOrientation = 0;
for (int i = 0; i < samples.size(); i++) {
referenceCameraToWorld.concat(samples.get(i), difference);
ConvertRotation3D_F64.matrixToRodrigues(difference.getR(),rodrigues);
double theta = Math.abs(rodrigues.theta);
double d = difference.getT().norm();
if( theta > maxOrientation ) {
maxOrientation = theta;
}
if( d > maxLocation ) {
maxLocation = d;
}
}
return true;
} } | public class class_name {
public boolean process( double sampleRadius , Quadrilateral_F64 input ) {
work.set(input);
samples.reset();
estimator.process(work,false);
estimator.getWorldToCamera().invert(referenceCameraToWorld);
samples.reset();
createSamples(sampleRadius,work.a,input.a);
createSamples(sampleRadius,work.b,input.b);
createSamples(sampleRadius,work.c,input.c);
createSamples(sampleRadius,work.d,input.d);
if( samples.size() < 10 )
return false;
maxLocation = 0;
maxOrientation = 0;
for (int i = 0; i < samples.size(); i++) {
referenceCameraToWorld.concat(samples.get(i), difference); // depends on control dependency: [for], data = [i]
ConvertRotation3D_F64.matrixToRodrigues(difference.getR(),rodrigues); // depends on control dependency: [for], data = [none]
double theta = Math.abs(rodrigues.theta);
double d = difference.getT().norm();
if( theta > maxOrientation ) {
maxOrientation = theta; // depends on control dependency: [if], data = [none]
}
if( d > maxLocation ) {
maxLocation = d; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
private void adjustTree(IndexTreePath<E> subtree) {
final Logging log = getLogger();
if(log.isDebugging()) {
log.debugFine("Adjust tree " + subtree + "\n");
}
// get the root of the subtree
int nodeIndex = subtree.getIndex();
N node = getNode(subtree.getEntry());
// overflow in node; split the node
if(hasOverflow(node)) {
// do the split
Assignments<E> assignments = settings.splitStrategy.split(this, node);
final N newNode = node.isLeaf() ? createNewLeafNode() : createNewDirectoryNode();
List<E> entries1 = new ArrayList<>(assignments.getFirstAssignments().size());
List<E> entries2 = new ArrayList<>(assignments.getSecondAssignments().size());
// Store final parent distances:
for(DistanceEntry<E> ent : assignments.getFirstAssignments()) {
final E e = ent.getEntry();
e.setParentDistance(ent.getDistance());
entries1.add(e);
}
for(DistanceEntry<E> ent : assignments.getSecondAssignments()) {
final E e = ent.getEntry();
e.setParentDistance(ent.getDistance());
entries2.add(e);
}
node.splitTo(newNode, entries1, entries2);
// write changes to file
writeNode(node);
writeNode(newNode);
if(log.isDebuggingFine()) {
log.debugFine(new StringBuilder(1000)//
.append("Split Node ").append(node.getPageID()).append(" (").append(this.getClass()).append(')').append(FormatUtil.NEWLINE)//
.append(" newNode ").append(newNode.getPageID()).append(FormatUtil.NEWLINE)//
.append(" firstPromoted ").append(assignments.getFirstRoutingObject()).append(FormatUtil.NEWLINE)//
.append(" firstAssignments(").append(node.getPageID()).append(") ").append(assignments.getFirstAssignments()).append(FormatUtil.NEWLINE)//
.append(" firstCR ").append(assignments.computeFirstCover(node.isLeaf())).append(FormatUtil.NEWLINE)//
.append(" secondPromoted ").append(assignments.getSecondRoutingObject()).append(FormatUtil.NEWLINE)//
.append(" secondAssignments(").append(newNode.getPageID()).append(") ").append(assignments.getSecondAssignments()).append(FormatUtil.NEWLINE)//
.append(" secondCR ").append(assignments.computeSecondCover(node.isLeaf())).append(FormatUtil.NEWLINE));
}
// if root was split: create a new root that points the two split nodes
if(isRoot(node)) {
// FIXME: stimmen die parentDistance der Kinder in node & splitNode?
IndexTreePath<E> newRootPath = createNewRoot(node, newNode, assignments.getFirstRoutingObject(), assignments.getSecondRoutingObject());
adjustTree(newRootPath);
}
// node is not root
else {
// get the parent and add the new split node
E parentEntry = subtree.getParentPath().getEntry();
N parent = getNode(parentEntry);
if(log.isDebugging()) {
log.debugFine("parent " + parent);
}
double parentDistance2 = distance(parentEntry.getRoutingObjectID(), assignments.getSecondRoutingObject());
// logger.warning("parent: "+parent.toString()+" split: " +
// splitNode.toString()+ " dist:"+parentDistance2);
parent.addDirectoryEntry(createNewDirectoryEntry(newNode, assignments.getSecondRoutingObject(), parentDistance2));
// adjust the entry representing the (old) node, that has been split
double parentDistance1 = distance(parentEntry.getRoutingObjectID(), assignments.getFirstRoutingObject());
// logger.warning("parent: "+parent.toString()+" node: " +
// node.toString()+ " dist:"+parentDistance1);
node.adjustEntry(parent.getEntry(nodeIndex), assignments.getFirstRoutingObject(), parentDistance1, this);
// write changes in parent to file
writeNode(parent);
adjustTree(subtree.getParentPath());
}
}
// no overflow, only adjust parameters of the entry representing the node
else {
if(!isRoot(node)) {
E parentEntry = subtree.getParentPath().getEntry();
N parent = getNode(parentEntry);
E entry = parent.getEntry(subtree.getIndex());
boolean changed = node.adjustEntry(entry, entry.getRoutingObjectID(), entry.getParentDistance(), this);
// write changes in parent to file
if(changed) {
writeNode(parent);
adjustTree(subtree.getParentPath());
}
}
// root level is reached
else {
E rootEntry = getRootEntry();
node.adjustEntry(rootEntry, rootEntry.getRoutingObjectID(), rootEntry.getParentDistance(), this);
}
}
} } | public class class_name {
private void adjustTree(IndexTreePath<E> subtree) {
final Logging log = getLogger();
if(log.isDebugging()) {
log.debugFine("Adjust tree " + subtree + "\n"); // depends on control dependency: [if], data = [none]
}
// get the root of the subtree
int nodeIndex = subtree.getIndex();
N node = getNode(subtree.getEntry());
// overflow in node; split the node
if(hasOverflow(node)) {
// do the split
Assignments<E> assignments = settings.splitStrategy.split(this, node);
final N newNode = node.isLeaf() ? createNewLeafNode() : createNewDirectoryNode();
List<E> entries1 = new ArrayList<>(assignments.getFirstAssignments().size());
List<E> entries2 = new ArrayList<>(assignments.getSecondAssignments().size());
// Store final parent distances:
for(DistanceEntry<E> ent : assignments.getFirstAssignments()) {
final E e = ent.getEntry();
e.setParentDistance(ent.getDistance()); // depends on control dependency: [for], data = [ent]
entries1.add(e); // depends on control dependency: [for], data = [ent]
}
for(DistanceEntry<E> ent : assignments.getSecondAssignments()) {
final E e = ent.getEntry();
e.setParentDistance(ent.getDistance()); // depends on control dependency: [for], data = [ent]
entries2.add(e); // depends on control dependency: [for], data = [ent]
}
node.splitTo(newNode, entries1, entries2); // depends on control dependency: [if], data = [none]
// write changes to file
writeNode(node); // depends on control dependency: [if], data = [none]
writeNode(newNode); // depends on control dependency: [if], data = [none]
if(log.isDebuggingFine()) {
log.debugFine(new StringBuilder(1000)//
.append("Split Node ").append(node.getPageID()).append(" (").append(this.getClass()).append(')').append(FormatUtil.NEWLINE)//
.append(" newNode ").append(newNode.getPageID()).append(FormatUtil.NEWLINE)//
.append(" firstPromoted ").append(assignments.getFirstRoutingObject()).append(FormatUtil.NEWLINE)//
.append(" firstAssignments(").append(node.getPageID()).append(") ").append(assignments.getFirstAssignments()).append(FormatUtil.NEWLINE)//
.append(" firstCR ").append(assignments.computeFirstCover(node.isLeaf())).append(FormatUtil.NEWLINE)//
.append(" secondPromoted ").append(assignments.getSecondRoutingObject()).append(FormatUtil.NEWLINE)//
.append(" secondAssignments(").append(newNode.getPageID()).append(") ").append(assignments.getSecondAssignments()).append(FormatUtil.NEWLINE)//
.append(" secondCR ").append(assignments.computeSecondCover(node.isLeaf())).append(FormatUtil.NEWLINE)); // depends on control dependency: [if], data = [none]
}
// if root was split: create a new root that points the two split nodes
if(isRoot(node)) {
// FIXME: stimmen die parentDistance der Kinder in node & splitNode?
IndexTreePath<E> newRootPath = createNewRoot(node, newNode, assignments.getFirstRoutingObject(), assignments.getSecondRoutingObject());
adjustTree(newRootPath); // depends on control dependency: [if], data = [none]
}
// node is not root
else {
// get the parent and add the new split node
E parentEntry = subtree.getParentPath().getEntry();
N parent = getNode(parentEntry);
if(log.isDebugging()) {
log.debugFine("parent " + parent); // depends on control dependency: [if], data = [none]
}
double parentDistance2 = distance(parentEntry.getRoutingObjectID(), assignments.getSecondRoutingObject());
// logger.warning("parent: "+parent.toString()+" split: " +
// splitNode.toString()+ " dist:"+parentDistance2);
parent.addDirectoryEntry(createNewDirectoryEntry(newNode, assignments.getSecondRoutingObject(), parentDistance2)); // depends on control dependency: [if], data = [none]
// adjust the entry representing the (old) node, that has been split
double parentDistance1 = distance(parentEntry.getRoutingObjectID(), assignments.getFirstRoutingObject());
// logger.warning("parent: "+parent.toString()+" node: " +
// node.toString()+ " dist:"+parentDistance1);
node.adjustEntry(parent.getEntry(nodeIndex), assignments.getFirstRoutingObject(), parentDistance1, this); // depends on control dependency: [if], data = [none]
// write changes in parent to file
writeNode(parent); // depends on control dependency: [if], data = [none]
adjustTree(subtree.getParentPath()); // depends on control dependency: [if], data = [none]
}
}
// no overflow, only adjust parameters of the entry representing the node
else {
if(!isRoot(node)) {
E parentEntry = subtree.getParentPath().getEntry();
N parent = getNode(parentEntry);
E entry = parent.getEntry(subtree.getIndex());
boolean changed = node.adjustEntry(entry, entry.getRoutingObjectID(), entry.getParentDistance(), this);
// write changes in parent to file
if(changed) {
writeNode(parent); // depends on control dependency: [if], data = [none]
adjustTree(subtree.getParentPath()); // depends on control dependency: [if], data = [none]
}
}
// root level is reached
else {
E rootEntry = getRootEntry();
node.adjustEntry(rootEntry, rootEntry.getRoutingObjectID(), rootEntry.getParentDistance(), this); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
/* package private */ void log(
final LogLevel level,
final String event,
final String message,
final String[] dataKeys,
final Object[] dataValues,
final Throwable throwable) {
if (shouldLog(level)) {
final String[] augmentedDataKeys = Arrays.copyOf(dataKeys, dataKeys.length + 2);
final Object[] augmentedDataValues = Arrays.copyOf(dataValues, dataValues.length + 2);
augmentedDataKeys[augmentedDataKeys.length - 2] = "_skipped";
augmentedDataKeys[augmentedDataKeys.length - 1] = "_lastLogTime";
augmentedDataValues[augmentedDataValues.length - 2] = _skipped.getAndSet(0);
augmentedDataValues[augmentedDataValues.length - 1] = _lastLogTime.getAndSet(_clock.instant());
super.log(level, event, message, augmentedDataKeys, augmentedDataValues, throwable);
}
} } | public class class_name {
@Override
/* package private */ void log(
final LogLevel level,
final String event,
final String message,
final String[] dataKeys,
final Object[] dataValues,
final Throwable throwable) {
if (shouldLog(level)) {
final String[] augmentedDataKeys = Arrays.copyOf(dataKeys, dataKeys.length + 2);
final Object[] augmentedDataValues = Arrays.copyOf(dataValues, dataValues.length + 2);
augmentedDataKeys[augmentedDataKeys.length - 2] = "_skipped"; // depends on control dependency: [if], data = [none]
augmentedDataKeys[augmentedDataKeys.length - 1] = "_lastLogTime"; // depends on control dependency: [if], data = [none]
augmentedDataValues[augmentedDataValues.length - 2] = _skipped.getAndSet(0); // depends on control dependency: [if], data = [none]
augmentedDataValues[augmentedDataValues.length - 1] = _lastLogTime.getAndSet(_clock.instant()); // depends on control dependency: [if], data = [none]
super.log(level, event, message, augmentedDataKeys, augmentedDataValues, throwable); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void addClassInfo(final ClassInfo classInfo) {
if (classInfoSet == null) {
classInfoSet = new HashSet<>();
}
classInfoSet.add(classInfo);
} } | public class class_name {
void addClassInfo(final ClassInfo classInfo) {
if (classInfoSet == null) {
classInfoSet = new HashSet<>(); // depends on control dependency: [if], data = [none]
}
classInfoSet.add(classInfo);
} } |
public class class_name {
@Trivial
public void enactOpen(long openAt) {
String methodName = "enactOpen";
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled() ) {
Tr.debug(tc, methodName + " On [ " + path + " ] at [ " + toRelSec(initialAt, openAt) + " (s) ]");
}
if ( zipFileState == ZipFileState.OPEN ) { // OPEN -> OPEN
openDuration += openAt - lastOpenAt;
lastLastOpenAt = lastOpenAt;
lastOpenAt = openAt;
openCount++;
} else if ( zipFileState == ZipFileState.PENDING ) { // PENDING -> OPEN
long lastPendDuration = openAt - lastPendAt;
pendToOpenDuration += lastPendDuration;
pendToOpenCount++;
lastLastOpenAt = lastOpenAt;
lastOpenAt = openAt;
openCount++;
zipFileState = ZipFileState.OPEN;
if ( ZIP_REAPER_COLLECT_TIMINGS ) {
timing(" Pend Success [ " + toAbsSec(lastPendDuration) + " (s) ]");
}
} else if ( zipFileState == ZipFileState.FULLY_CLOSED ) { // FULLY_CLOSED -> OPEN
if ( firstOpenAt == -1L ) {
firstOpenAt = openAt;
} else {
long lastFullCloseDuration = openAt - lastFullCloseAt;
fullCloseToOpenDuration += lastFullCloseDuration;
if ( ZIP_REAPER_COLLECT_TIMINGS ) {
long lastPendDuration = ( (lastPendAt == -1L) ? 0 : (lastFullCloseAt - lastPendAt) );
timing(" Reopen; Pend [ " + toAbsSec(lastPendDuration) + " (s) ] " +
" Close [ " + toAbsSec(lastFullCloseDuration) + " (s) ]");
}
}
fullCloseToOpenCount++;
lastLastOpenAt = lastOpenAt;
lastOpenAt = openAt;
openCount++;
zipFileState = ZipFileState.OPEN;
} else {
throw unknownState();
}
if ( ZIP_REAPER_COLLECT_TIMINGS ) {
timing(" Open " + dualTiming(openAt, initialAt) + " " + openState());
}
} } | public class class_name {
@Trivial
public void enactOpen(long openAt) {
String methodName = "enactOpen";
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled() ) {
Tr.debug(tc, methodName + " On [ " + path + " ] at [ " + toRelSec(initialAt, openAt) + " (s) ]");
}
if ( zipFileState == ZipFileState.OPEN ) { // OPEN -> OPEN
openDuration += openAt - lastOpenAt; // depends on control dependency: [if], data = [none]
lastLastOpenAt = lastOpenAt; // depends on control dependency: [if], data = [none]
lastOpenAt = openAt; // depends on control dependency: [if], data = [none]
openCount++; // depends on control dependency: [if], data = [none]
} else if ( zipFileState == ZipFileState.PENDING ) { // PENDING -> OPEN
long lastPendDuration = openAt - lastPendAt;
pendToOpenDuration += lastPendDuration; // depends on control dependency: [if], data = [none]
pendToOpenCount++; // depends on control dependency: [if], data = [none]
lastLastOpenAt = lastOpenAt; // depends on control dependency: [if], data = [none]
lastOpenAt = openAt; // depends on control dependency: [if], data = [none]
openCount++; // depends on control dependency: [if], data = [none]
zipFileState = ZipFileState.OPEN; // depends on control dependency: [if], data = [none]
if ( ZIP_REAPER_COLLECT_TIMINGS ) {
timing(" Pend Success [ " + toAbsSec(lastPendDuration) + " (s) ]"); // depends on control dependency: [if], data = [none]
}
} else if ( zipFileState == ZipFileState.FULLY_CLOSED ) { // FULLY_CLOSED -> OPEN
if ( firstOpenAt == -1L ) {
firstOpenAt = openAt; // depends on control dependency: [if], data = [none]
} else {
long lastFullCloseDuration = openAt - lastFullCloseAt;
fullCloseToOpenDuration += lastFullCloseDuration; // depends on control dependency: [if], data = [none]
if ( ZIP_REAPER_COLLECT_TIMINGS ) {
long lastPendDuration = ( (lastPendAt == -1L) ? 0 : (lastFullCloseAt - lastPendAt) );
timing(" Reopen; Pend [ " + toAbsSec(lastPendDuration) + " (s) ] " +
" Close [ " + toAbsSec(lastFullCloseDuration) + " (s) ]");
}
}
fullCloseToOpenCount++; // depends on control dependency: [if], data = [none]
lastLastOpenAt = lastOpenAt; // depends on control dependency: [if], data = [none]
lastOpenAt = openAt; // depends on control dependency: [if], data = [none]
openCount++; // depends on control dependency: [if], data = [none]
zipFileState = ZipFileState.OPEN; // depends on control dependency: [if], data = [none]
} else {
throw unknownState();
}
if ( ZIP_REAPER_COLLECT_TIMINGS ) {
timing(" Open " + dualTiming(openAt, initialAt) + " " + openState()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void triggerResolveInit() {
Iterator<TransportResolverListener> iter = getListenersList().iterator();
while (iter.hasNext()) {
TransportResolverListener trl = iter.next();
if (trl instanceof TransportResolverListener.Resolver) {
TransportResolverListener.Resolver li = (TransportResolverListener.Resolver) trl;
li.init();
}
}
} } | public class class_name {
private void triggerResolveInit() {
Iterator<TransportResolverListener> iter = getListenersList().iterator();
while (iter.hasNext()) {
TransportResolverListener trl = iter.next();
if (trl instanceof TransportResolverListener.Resolver) {
TransportResolverListener.Resolver li = (TransportResolverListener.Resolver) trl;
li.init(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void setBootClassPath(Collection<File> bootClasspath) {
final JavaVersion version = JavaVersion.fromQualifier(getJavaSourceVersion());
if (version.isAtLeast(JavaVersion.JAVA9)) {
reportInternalWarning(MessageFormat.format(Messages.SarlBatchCompiler_63,
Joiner.on(File.pathSeparator).join(bootClasspath)));
}
if (bootClasspath == null || bootClasspath.isEmpty()) {
this.bootClasspath = null;
} else {
this.bootClasspath = new ArrayList<>(bootClasspath);
}
} } | public class class_name {
public void setBootClassPath(Collection<File> bootClasspath) {
final JavaVersion version = JavaVersion.fromQualifier(getJavaSourceVersion());
if (version.isAtLeast(JavaVersion.JAVA9)) {
reportInternalWarning(MessageFormat.format(Messages.SarlBatchCompiler_63,
Joiner.on(File.pathSeparator).join(bootClasspath))); // depends on control dependency: [if], data = [none]
}
if (bootClasspath == null || bootClasspath.isEmpty()) {
this.bootClasspath = null; // depends on control dependency: [if], data = [none]
} else {
this.bootClasspath = new ArrayList<>(bootClasspath); // depends on control dependency: [if], data = [(bootClasspath]
}
} } |
public class class_name {
@Override
protected void _transform(Dataframe newData) {
ModelParameters modelParameters = knowledgeBase.getModelParameters();
Map<Object, Double> minColumnValues = modelParameters.getMinColumnValues();
Map<Object, Double> maxColumnValues = modelParameters.getMaxColumnValues();
boolean scaleResponse = knowledgeBase.getTrainingParameters().getScaleResponse() && minColumnValues.containsKey(Dataframe.COLUMN_NAME_Y);
streamExecutor.forEach(StreamMethods.stream(newData.entries(), isParallelized()), e -> {
Record r = e.getValue();
AssociativeArray xData = r.getX().copy();
Object yData = r.getY();
boolean modified = false;
for(Object column : r.getX().keySet()) {
Double min = minColumnValues.get(column);
if(min == null) {
continue;
}
Object value = xData.remove(column);
if(value != null) {
Double max = maxColumnValues.get(column);
xData.put(column, scale(TypeInference.toDouble(value), min, max));
}
modified = true;
}
if(scaleResponse && yData != null) {
Double value = TypeInference.toDouble(yData);
Double min = minColumnValues.get(Dataframe.COLUMN_NAME_Y);
Double max = maxColumnValues.get(Dataframe.COLUMN_NAME_Y);
yData = scale(value, min, max);
modified = true;
}
if(modified) {
Integer rId = e.getKey();
Record newR = new Record(xData, yData, r.getYPredicted(), r.getYPredictedProbabilities());
//no modification on the actual columns takes place, safe to do.
newData._unsafe_set(rId, newR);
}
});
} } | public class class_name {
@Override
protected void _transform(Dataframe newData) {
ModelParameters modelParameters = knowledgeBase.getModelParameters();
Map<Object, Double> minColumnValues = modelParameters.getMinColumnValues();
Map<Object, Double> maxColumnValues = modelParameters.getMaxColumnValues();
boolean scaleResponse = knowledgeBase.getTrainingParameters().getScaleResponse() && minColumnValues.containsKey(Dataframe.COLUMN_NAME_Y);
streamExecutor.forEach(StreamMethods.stream(newData.entries(), isParallelized()), e -> {
Record r = e.getValue();
AssociativeArray xData = r.getX().copy();
Object yData = r.getY();
boolean modified = false;
for(Object column : r.getX().keySet()) {
Double min = minColumnValues.get(column);
if(min == null) {
continue;
}
Object value = xData.remove(column);
if(value != null) {
Double max = maxColumnValues.get(column);
xData.put(column, scale(TypeInference.toDouble(value), min, max)); // depends on control dependency: [if], data = [(value]
}
modified = true; // depends on control dependency: [for], data = [none]
}
if(scaleResponse && yData != null) {
Double value = TypeInference.toDouble(yData);
Double min = minColumnValues.get(Dataframe.COLUMN_NAME_Y);
Double max = maxColumnValues.get(Dataframe.COLUMN_NAME_Y);
yData = scale(value, min, max); // depends on control dependency: [if], data = [none]
modified = true; // depends on control dependency: [if], data = [none]
}
if(modified) {
Integer rId = e.getKey();
Record newR = new Record(xData, yData, r.getYPredicted(), r.getYPredictedProbabilities());
//no modification on the actual columns takes place, safe to do.
newData._unsafe_set(rId, newR); // depends on control dependency: [if], data = [none]
}
});
} } |
public class class_name {
private static PbDocument [] getPbDocs(final NodeList nl) {
List list = new ArrayList();
Element prevpb = null;
for (int i = 0; i < nl.getLength(); i++) {
Element pb = (Element) nl.item(i);
PbDocument pbdoc = new PbDocument(prevpb, pb);
list.add(pbdoc);
prevpb = pb;
if (i == (nl.getLength() - 1)) {
pbdoc = new PbDocument(pb, null);
list.add(pbdoc);
} // end if
} // end for
PbDocument array[] = new PbDocument[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = (PbDocument) list.get(i);
} // end for
return array;
} } | public class class_name {
private static PbDocument [] getPbDocs(final NodeList nl) {
List list = new ArrayList();
Element prevpb = null;
for (int i = 0; i < nl.getLength(); i++) {
Element pb = (Element) nl.item(i);
PbDocument pbdoc = new PbDocument(prevpb, pb);
list.add(pbdoc); // depends on control dependency: [for], data = [none]
prevpb = pb; // depends on control dependency: [for], data = [none]
if (i == (nl.getLength() - 1)) {
pbdoc = new PbDocument(pb, null); // depends on control dependency: [if], data = [none]
list.add(pbdoc); // depends on control dependency: [if], data = [none]
} // end if
} // end for
PbDocument array[] = new PbDocument[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = (PbDocument) list.get(i); // depends on control dependency: [for], data = [i]
} // end for
return array;
} } |
public class class_name {
protected NextJourney handleXmlResponse(XmlResponse response) {
// lazy because of same reason as HTML response (see the comment)
return createSelfContainedJourney(() -> {
adjustActionResponseJustBefore(response);
final ResponseManager responseManager = requestManager.getResponseManager();
setupActionResponseHeader(responseManager, response);
setupActionResponseHttpStatus(responseManager, response);
if (response.isReturnAsEmptyBody()) {
return;
}
final String xmlStr = response.getXmlStr();
keepOriginalBodyForInOutLoggingIfNeeds(xmlStr, "xml");
responseManager.writeAsXml(xmlStr, response.getEncoding());
});
} } | public class class_name {
protected NextJourney handleXmlResponse(XmlResponse response) {
// lazy because of same reason as HTML response (see the comment)
return createSelfContainedJourney(() -> {
adjustActionResponseJustBefore(response);
final ResponseManager responseManager = requestManager.getResponseManager();
setupActionResponseHeader(responseManager, response);
setupActionResponseHttpStatus(responseManager, response);
if (response.isReturnAsEmptyBody()) {
return; // depends on control dependency: [if], data = [none]
}
final String xmlStr = response.getXmlStr();
keepOriginalBodyForInOutLoggingIfNeeds(xmlStr, "xml");
responseManager.writeAsXml(xmlStr, response.getEncoding());
});
} } |
public class class_name {
private int stage5Parameter(final ProtoNetwork network,
Set<EquivalenceDataIndex> equivalences, final StringBuilder bldr) {
bldr.append("Equivalencing parameters");
stageOutput(bldr.toString());
ProtoNetwork ret = network;
int ct = 0;
try {
ct = p2.stage3EquivalenceParameters(ret, equivalences);
stageOutput("(" + ct + " equivalences)");
} catch (IOException ioex) {
final String err = ioex.getMessage();
fatal(err);
}
return ct;
} } | public class class_name {
private int stage5Parameter(final ProtoNetwork network,
Set<EquivalenceDataIndex> equivalences, final StringBuilder bldr) {
bldr.append("Equivalencing parameters");
stageOutput(bldr.toString());
ProtoNetwork ret = network;
int ct = 0;
try {
ct = p2.stage3EquivalenceParameters(ret, equivalences); // depends on control dependency: [try], data = [none]
stageOutput("(" + ct + " equivalences)"); // depends on control dependency: [try], data = [none]
} catch (IOException ioex) {
final String err = ioex.getMessage();
fatal(err);
} // depends on control dependency: [catch], data = [none]
return ct;
} } |
public class class_name {
public boolean evaluateDiscriminator(
String fullTopic,
String wildcardTopic,
Selector discriminatorTree)
throws SIDiscriminatorSyntaxException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc,
"evaluateDiscriminator",
new Object[] { fullTopic, wildcardTopic, discriminatorTree });
Object result = null;
boolean discriminatorMatches = false;
// Use the dummy evaluation cache, we don't need one here as we're not
// searching the MatchSpace
EvalCache cache = EvalCache.DUMMY;
try
{
Evaluator evaluator = Matching.getEvaluator();
MatchSpaceKey msk = new DiscriminatorMatchSpaceKey(fullTopic);
if(discriminatorTree == null)
discriminatorTree = parseDiscriminator(wildcardTopic);
// Evaluate message against discriminator tree
result = evaluator.eval(discriminatorTree, msk, cache, null, false);
if (result != null && ((Boolean) result).booleanValue())
{
discriminatorMatches = true;
}
}
catch (BadMessageFormatMatchingException qex)
{
FFDCFilter.processException(
qex,
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching.evaluateDiscriminator",
"1:2623:1.117.1.11",
this);
SibTr.exception(tc, qex);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "evaluateDiscriminator", "SICoreException");
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching",
"1:2633:1.117.1.11",
qex });
// For now, I'll throw a core exception, but in due course this (or something with a
// better name) will be externalised in the Core API.
throw new SIErrorException(
nls.getFormattedMessage(
"INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching",
"1:2643:1.117.1.11",
qex },
null),
qex);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "evaluateDiscriminator", Boolean.valueOf(discriminatorMatches));
return discriminatorMatches;
} } | public class class_name {
public boolean evaluateDiscriminator(
String fullTopic,
String wildcardTopic,
Selector discriminatorTree)
throws SIDiscriminatorSyntaxException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc,
"evaluateDiscriminator",
new Object[] { fullTopic, wildcardTopic, discriminatorTree });
Object result = null;
boolean discriminatorMatches = false;
// Use the dummy evaluation cache, we don't need one here as we're not
// searching the MatchSpace
EvalCache cache = EvalCache.DUMMY;
try
{
Evaluator evaluator = Matching.getEvaluator();
MatchSpaceKey msk = new DiscriminatorMatchSpaceKey(fullTopic);
if(discriminatorTree == null)
discriminatorTree = parseDiscriminator(wildcardTopic);
// Evaluate message against discriminator tree
result = evaluator.eval(discriminatorTree, msk, cache, null, false); // depends on control dependency: [try], data = [none]
if (result != null && ((Boolean) result).booleanValue())
{
discriminatorMatches = true; // depends on control dependency: [if], data = [none]
}
}
catch (BadMessageFormatMatchingException qex)
{
FFDCFilter.processException(
qex,
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching.evaluateDiscriminator",
"1:2623:1.117.1.11",
this);
SibTr.exception(tc, qex);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "evaluateDiscriminator", "SICoreException");
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching",
"1:2633:1.117.1.11",
qex });
// For now, I'll throw a core exception, but in due course this (or something with a
// better name) will be externalised in the Core API.
throw new SIErrorException(
nls.getFormattedMessage(
"INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching",
"1:2643:1.117.1.11",
qex },
null),
qex);
} // depends on control dependency: [catch], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "evaluateDiscriminator", Boolean.valueOf(discriminatorMatches));
return discriminatorMatches;
} } |
public class class_name {
@Override
public List<String> getAudiences() { // TODO needed for verifying the ID_TOKEN
List<String> audiences = new ArrayList<String>();
String clientId = getClientId();
if (clientId != null) {
audiences.add(clientId);
}
return audiences;
} } | public class class_name {
@Override
public List<String> getAudiences() { // TODO needed for verifying the ID_TOKEN
List<String> audiences = new ArrayList<String>();
String clientId = getClientId();
if (clientId != null) {
audiences.add(clientId); // depends on control dependency: [if], data = [(clientId]
}
return audiences;
} } |
public class class_name {
@Override
public Object get(String propName) {
if (propName.equals("mode")) {
return getMode();
}
return super.get(propName);
} } | public class class_name {
@Override
public Object get(String propName) {
if (propName.equals("mode")) {
return getMode(); // depends on control dependency: [if], data = [none]
}
return super.get(propName);
} } |
public class class_name {
@Override
public Cursor loadInBackground() {
final SQLiteDatabase db = Sprinkles.getDatabase();
Cursor cursor = db.rawQuery(mSql, null);
if (cursor != null) {
// Ensure the cursor window is filled
cursor.getCount();
if (mDependencies != null) {
cursor.registerContentObserver(mObserver);
for (Class<? extends Model> dependency : mDependencies) {
getContext().getContentResolver().registerContentObserver(
Utils.getNotificationUri(dependency), false, mObserver);
}
}
}
return cursor;
} } | public class class_name {
@Override
public Cursor loadInBackground() {
final SQLiteDatabase db = Sprinkles.getDatabase();
Cursor cursor = db.rawQuery(mSql, null);
if (cursor != null) {
// Ensure the cursor window is filled
cursor.getCount(); // depends on control dependency: [if], data = [none]
if (mDependencies != null) {
cursor.registerContentObserver(mObserver); // depends on control dependency: [if], data = [none]
for (Class<? extends Model> dependency : mDependencies) {
getContext().getContentResolver().registerContentObserver(
Utils.getNotificationUri(dependency), false, mObserver);
}
}
}
return cursor;
} } |
public class class_name {
@Nullable
public static String shortenURI(@Nullable final URI uri) {
if (uri == null) {
return null;
}
final String prefix = Data.namespaceToPrefix(uri.getNamespace(), Data.getNamespaceMap());
if (prefix != null) {
return prefix + ':' + uri.getLocalName();
}
final String ns = uri.getNamespace();
return "<.." + uri.stringValue().substring(ns.length() - 1) + ">";
// final int index = uri.stringValue().lastIndexOf('/');
// if (index >= 0) {
// return "<.." + uri.stringValue().substring(index) + ">";
// }
// return "<" + uri.stringValue() + ">";
} } | public class class_name {
@Nullable
public static String shortenURI(@Nullable final URI uri) {
if (uri == null) {
return null; // depends on control dependency: [if], data = [none]
}
final String prefix = Data.namespaceToPrefix(uri.getNamespace(), Data.getNamespaceMap());
if (prefix != null) {
return prefix + ':' + uri.getLocalName(); // depends on control dependency: [if], data = [none]
}
final String ns = uri.getNamespace();
return "<.." + uri.stringValue().substring(ns.length() - 1) + ">";
// final int index = uri.stringValue().lastIndexOf('/');
// if (index >= 0) {
// return "<.." + uri.stringValue().substring(index) + ">";
// }
// return "<" + uri.stringValue() + ">";
} } |
public class class_name {
public static long getValueAsLong(final byte[] key,
final Map<byte[], byte[]> taskValues) {
byte[] value = taskValues.get(key);
if (value != null) {
try {
long retValue = Bytes.toLong(value);
return retValue;
} catch (NumberFormatException nfe) {
LOG.error("Caught NFE while converting to long ", nfe);
return 0L;
} catch (IllegalArgumentException iae ) {
// for exceptions like java.lang.IllegalArgumentException:
// offset (0) + length (8) exceed the capacity of the array: 7
LOG.error("Caught IAE while converting to long ", iae);
return 0L;
}
} else {
return 0L;
}
} } | public class class_name {
public static long getValueAsLong(final byte[] key,
final Map<byte[], byte[]> taskValues) {
byte[] value = taskValues.get(key);
if (value != null) {
try {
long retValue = Bytes.toLong(value);
return retValue; // depends on control dependency: [try], data = [none]
} catch (NumberFormatException nfe) {
LOG.error("Caught NFE while converting to long ", nfe);
return 0L;
} catch (IllegalArgumentException iae ) { // depends on control dependency: [catch], data = [none]
// for exceptions like java.lang.IllegalArgumentException:
// offset (0) + length (8) exceed the capacity of the array: 7
LOG.error("Caught IAE while converting to long ", iae);
return 0L;
} // depends on control dependency: [catch], data = [none]
} else {
return 0L; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Ability recoverDB() {
return builder()
.name(RECOVER)
.locality(USER)
.privacy(CREATOR)
.input(0)
.action(ctx -> silent.forceReply(
getLocalizedMessage(ABILITY_RECOVER_MESSAGE, ctx.user().getLanguageCode()), ctx.chatId()))
.reply(update -> {
String replyToMsg = update.getMessage().getReplyToMessage().getText();
String recoverMessage = getLocalizedMessage(ABILITY_RECOVER_MESSAGE, AbilityUtils.getUser(update).getLanguageCode());
if (!replyToMsg.equals(recoverMessage))
return;
String fileId = update.getMessage().getDocument().getFileId();
try (FileReader reader = new FileReader(downloadFileWithId(fileId))) {
String backupData = IOUtils.toString(reader);
if (db.recover(backupData)) {
send(ABILITY_RECOVER_SUCCESS, update);
} else {
send(ABILITY_RECOVER_FAIL, update);
}
} catch (Exception e) {
BotLogger.error("Could not recover DB from backup", TAG, e);
send(ABILITY_RECOVER_ERROR, update);
}
}, MESSAGE, DOCUMENT, REPLY)
.build();
} } | public class class_name {
public Ability recoverDB() {
return builder()
.name(RECOVER)
.locality(USER)
.privacy(CREATOR)
.input(0)
.action(ctx -> silent.forceReply(
getLocalizedMessage(ABILITY_RECOVER_MESSAGE, ctx.user().getLanguageCode()), ctx.chatId()))
.reply(update -> {
String replyToMsg = update.getMessage().getReplyToMessage().getText();
String recoverMessage = getLocalizedMessage(ABILITY_RECOVER_MESSAGE, AbilityUtils.getUser(update).getLanguageCode());
if (!replyToMsg.equals(recoverMessage))
return;
String fileId = update.getMessage().getDocument().getFileId();
try (FileReader reader = new FileReader(downloadFileWithId(fileId))) {
String backupData = IOUtils.toString(reader);
if (db.recover(backupData)) {
send(ABILITY_RECOVER_SUCCESS, update); // depends on control dependency: [if], data = [none]
} else {
send(ABILITY_RECOVER_FAIL, update); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
BotLogger.error("Could not recover DB from backup", TAG, e);
send(ABILITY_RECOVER_ERROR, update);
}
}, MESSAGE, DOCUMENT, REPLY)
.build();
} } |
public class class_name {
private void transitionToFinalBatchStatus() {
BatchStatus currentBatchStatus = stepContext.getBatchStatus();
if (currentBatchStatus.equals(BatchStatus.STARTED)) {
updateBatchStatus(BatchStatus.COMPLETED);
} else if (currentBatchStatus.equals(BatchStatus.STOPPING)) {
updateBatchStatus(BatchStatus.STOPPED);
} else if (currentBatchStatus.equals(BatchStatus.FAILED)) {
updateBatchStatus(BatchStatus.FAILED); // Should have already been done but maybe better for possible code refactoring to have it here.
} else {
throw new IllegalStateException("Step batch status should not be in a " + currentBatchStatus.name() + " state");
}
} } | public class class_name {
private void transitionToFinalBatchStatus() {
BatchStatus currentBatchStatus = stepContext.getBatchStatus();
if (currentBatchStatus.equals(BatchStatus.STARTED)) {
updateBatchStatus(BatchStatus.COMPLETED);
// depends on control dependency: [if], data = [none]
} else if (currentBatchStatus.equals(BatchStatus.STOPPING)) {
updateBatchStatus(BatchStatus.STOPPED);
// depends on control dependency: [if], data = [none]
} else if (currentBatchStatus.equals(BatchStatus.FAILED)) {
updateBatchStatus(BatchStatus.FAILED); // Should have already been done but maybe better for possible code refactoring to have it here.
// depends on control dependency: [if], data = [none]
} else {
throw new IllegalStateException("Step batch status should not be in a " + currentBatchStatus.name() + " state");
}
} } |
public class class_name {
public <T> T get(ConfigKey key, T def) {
Object o = data.get(key);
if (null == o) {
o = key.val(raw);
if (null == o) {
o = null == def ? NULL : def;
}
data.put(key, o);
}
if (isDebugEnabled()) {
debug("config[%s] loaded: %s", key, o);
}
if (o == NULL) {
return null;
} else {
return (T) o;
}
} } | public class class_name {
public <T> T get(ConfigKey key, T def) {
Object o = data.get(key);
if (null == o) {
o = key.val(raw); // depends on control dependency: [if], data = [none]
if (null == o) {
o = null == def ? NULL : def; // depends on control dependency: [if], data = [none]
}
data.put(key, o); // depends on control dependency: [if], data = [o)]
}
if (isDebugEnabled()) {
debug("config[%s] loaded: %s", key, o); // depends on control dependency: [if], data = [none]
}
if (o == NULL) {
return null; // depends on control dependency: [if], data = [none]
} else {
return (T) o; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setDebugCacheDir(File cacheDir) {
if (sDebug) {
LogUtils.v(TAG, "setCacheDir() cacheDir=" + cacheDir);
}
mCacheDir = cacheDir;
checkCacheDir(false);
} } | public class class_name {
public void setDebugCacheDir(File cacheDir) {
if (sDebug) {
LogUtils.v(TAG, "setCacheDir() cacheDir=" + cacheDir); // depends on control dependency: [if], data = [none]
}
mCacheDir = cacheDir;
checkCacheDir(false);
} } |
public class class_name {
public static boolean or(final boolean... array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
}
if (array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
for (final boolean element : array) {
if (element) {
return true;
}
}
return false;
} } | public class class_name {
public static boolean or(final boolean... array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
}
if (array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
for (final boolean element : array) {
if (element) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
protected boolean selectAllParents(CmsTreeItem item, String path, List<String> result) {
// if this is a list view
if (m_listView) {
// check if the path contains the item path
if (path.contains(item.getId())) {
// add it to the list of selected categories
if (!result.contains(item.getId())) {
result.add(item.getId());
}
return true;
}
}
// if this is a tree view
else {
// check if the pach contains the item path
if (item.getId().equals(path)) {
// add it to the list of selected categories
if (!result.contains(item.getId())) {
result.add(item.getId());
}
return true;
} else {
// iterate about all children of this item
Iterator<Widget> it = item.getChildren().iterator();
while (it.hasNext()) {
if (selectAllParents((CmsTreeItem)it.next(), path, result)) {
if (!result.contains(item.getId())) {
result.add(item.getId());
}
return true;
}
}
}
}
return false;
} } | public class class_name {
protected boolean selectAllParents(CmsTreeItem item, String path, List<String> result) {
// if this is a list view
if (m_listView) {
// check if the path contains the item path
if (path.contains(item.getId())) {
// add it to the list of selected categories
if (!result.contains(item.getId())) {
result.add(item.getId());
// depends on control dependency: [if], data = [none]
}
return true;
// depends on control dependency: [if], data = [none]
}
}
// if this is a tree view
else {
// check if the pach contains the item path
if (item.getId().equals(path)) {
// add it to the list of selected categories
if (!result.contains(item.getId())) {
result.add(item.getId());
// depends on control dependency: [if], data = [none]
}
return true;
// depends on control dependency: [if], data = [none]
} else {
// iterate about all children of this item
Iterator<Widget> it = item.getChildren().iterator();
while (it.hasNext()) {
if (selectAllParents((CmsTreeItem)it.next(), path, result)) {
if (!result.contains(item.getId())) {
result.add(item.getId());
// depends on control dependency: [if], data = [none]
}
return true;
// depends on control dependency: [if], data = [none]
}
}
}
}
return false;
} } |
public class class_name {
private Object instantiateEntity(Class entityClass, Object entity)
{
try
{
if (entity == null)
{
return entityClass.newInstance();
}
return entity;
}
catch (InstantiationException e)
{
log.error("Error while instantiating " + entityClass + ", Caused by: ", e);
}
catch (IllegalAccessException e)
{
log.error("Error while instantiating " + entityClass + ", Caused by: ", e);
}
return null;
} } | public class class_name {
private Object instantiateEntity(Class entityClass, Object entity)
{
try
{
if (entity == null)
{
return entityClass.newInstance(); // depends on control dependency: [if], data = [none]
}
return entity; // depends on control dependency: [try], data = [none]
}
catch (InstantiationException e)
{
log.error("Error while instantiating " + entityClass + ", Caused by: ", e);
} // depends on control dependency: [catch], data = [none]
catch (IllegalAccessException e)
{
log.error("Error while instantiating " + entityClass + ", Caused by: ", e);
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
@Override
public void interruptJob(String jobGroup, String jobName) throws SchedulerException {
if (!config.isInterruptJobAllowed()) {
LOGGER.warn("not allowed to interrupt any job");
return;
}
JobKey jobKey = new JobKey(jobName, jobGroup);
if (isInteruptable(jobKey)) {
List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
for (JobExecutionContext jobExecutionContext : executingJobs) {
JobDetail execJobDetail = jobExecutionContext.getJobDetail();
if (execJobDetail.getKey().equals(jobDetail.getKey())) {
if (LOGGER.isDebugEnabled())
LOGGER.debug(String.format("interrupting job (%s, %s)", jobDetail.getKey().getGroup(),
jobDetail.getKey().getName()));
((InterruptableJob) jobExecutionContext.getJobInstance()).interrupt();
}
}
}
} } | public class class_name {
@Override
public void interruptJob(String jobGroup, String jobName) throws SchedulerException {
if (!config.isInterruptJobAllowed()) {
LOGGER.warn("not allowed to interrupt any job");
return;
}
JobKey jobKey = new JobKey(jobName, jobGroup);
if (isInteruptable(jobKey)) {
List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
for (JobExecutionContext jobExecutionContext : executingJobs) {
JobDetail execJobDetail = jobExecutionContext.getJobDetail();
if (execJobDetail.getKey().equals(jobDetail.getKey())) {
if (LOGGER.isDebugEnabled())
LOGGER.debug(String.format("interrupting job (%s, %s)", jobDetail.getKey().getGroup(),
jobDetail.getKey().getName()));
((InterruptableJob) jobExecutionContext.getJobInstance()).interrupt();
// depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public String[] getCodeBaseLoc(Permission perm) {
final Permission inPerm = perm;
return AccessController.doPrivileged(new java.security.PrivilegedAction<String[]>() {
@Override
public String[] run() {
Class<?>[] classes = getClassContext();
StringBuffer sb = new StringBuffer(classes.length * 100);
sb.append(lineSep);
// one for offending class and the other for code base
// location
String[] retMsg = new String[2];
for (int i = 0; i < classes.length; i++) {
Class<?> clazz = classes[i];
ProtectionDomain pd = clazz.getProtectionDomain();
// check for occurrence of checkPermission from stack
if (classes[i].getName().indexOf("com.ibm.ws.kernel.launch.internal.NoRethrowSecurityManager") != -1) {
// found SecurityManager, start to go through
// the stack starting next class
for (int j = i + 1; j < classes.length; j++) {
if (classes[j].getName().indexOf("java.lang.ClassLoader") != -1) {
if (tc.isDebugEnabled())
Tr.debug(tc, "Not printing AccessError since ClassLoader.getResource returns null per JavaDoc when privileges not there.");
String[] codebaseloc = new String[2];
codebaseloc[0] = "_nolog";
codebaseloc[1] = "";
return codebaseloc;
}
ProtectionDomain pd2 = classes[j].getProtectionDomain();
if (isOffendingClass(classes, j, pd2, inPerm)) {
retMsg[0] = lineSep + lineSep +
" " + classes[j].getName() + " in " + "{" + getCodeSource(pd2) + "}" +
lineSep +
lineSep;
break;
}
}
}
java.security.CodeSource cs = pd.getCodeSource();
String csStr = getCodeSource(pd);
// class name : location
sb.append(classes[i].getName()).append(" : ").append(csStr + lineSep);
sb.append(" ").append(permissionToString(cs, clazz.getClassLoader(), pd.getPermissions()))
.append(lineSep);
}
if (tc.isDebugEnabled())
Tr.debug(tc, "Permission Error Code is " + retMsg[0]);
if (tc.isDebugEnabled())
Tr.debug(tc, "Code Base Location: is " + sb.toString());
retMsg[1] = "";
return retMsg;
}
});
} } | public class class_name {
public String[] getCodeBaseLoc(Permission perm) {
final Permission inPerm = perm;
return AccessController.doPrivileged(new java.security.PrivilegedAction<String[]>() {
@Override
public String[] run() {
Class<?>[] classes = getClassContext();
StringBuffer sb = new StringBuffer(classes.length * 100);
sb.append(lineSep);
// one for offending class and the other for code base
// location
String[] retMsg = new String[2];
for (int i = 0; i < classes.length; i++) {
Class<?> clazz = classes[i];
ProtectionDomain pd = clazz.getProtectionDomain();
// check for occurrence of checkPermission from stack
if (classes[i].getName().indexOf("com.ibm.ws.kernel.launch.internal.NoRethrowSecurityManager") != -1) {
// found SecurityManager, start to go through
// the stack starting next class
for (int j = i + 1; j < classes.length; j++) {
if (classes[j].getName().indexOf("java.lang.ClassLoader") != -1) {
if (tc.isDebugEnabled())
Tr.debug(tc, "Not printing AccessError since ClassLoader.getResource returns null per JavaDoc when privileges not there.");
String[] codebaseloc = new String[2];
codebaseloc[0] = "_nolog"; // depends on control dependency: [if], data = [none]
codebaseloc[1] = ""; // depends on control dependency: [if], data = [none]
return codebaseloc; // depends on control dependency: [if], data = [none]
}
ProtectionDomain pd2 = classes[j].getProtectionDomain();
if (isOffendingClass(classes, j, pd2, inPerm)) {
retMsg[0] = lineSep + lineSep +
" " + classes[j].getName() + " in " + "{" + getCodeSource(pd2) + "}" +
lineSep +
lineSep; // depends on control dependency: [if], data = [none]
break;
}
}
}
java.security.CodeSource cs = pd.getCodeSource();
String csStr = getCodeSource(pd);
// class name : location
sb.append(classes[i].getName()).append(" : ").append(csStr + lineSep);
sb.append(" ").append(permissionToString(cs, clazz.getClassLoader(), pd.getPermissions()))
.append(lineSep);
}
if (tc.isDebugEnabled())
Tr.debug(tc, "Permission Error Code is " + retMsg[0]);
if (tc.isDebugEnabled())
Tr.debug(tc, "Code Base Location: is " + sb.toString());
retMsg[1] = "";
return retMsg;
}
});
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.