code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
Node tryOptimizeBlock(Node n) {
// Remove any useless children
for (Node c = n.getFirstChild(); c != null; ) {
Node next = c.getNext(); // save c.next, since 'c' may be removed
if (!isUnremovableNode(c) && !mayHaveSideEffects(c)) {
checkNormalization(!NodeUtil.isFunctionDeclaration(n), "function declaration");
// TODO(johnlenz): determine what this is actually removing. Candidates
// include: EMPTY nodes, control structures without children
// (removing infinite loops), empty try blocks. What else?
n.removeChild(c);
reportChangeToEnclosingScope(n);
markFunctionsDeleted(c);
} else {
tryOptimizeConditionalAfterAssign(c);
}
c = next;
}
if (n.isSyntheticBlock() || n.isScript() || n.getParent() == null) {
return n;
}
// Try to remove the block.
Node parent = n.getParent();
if (NodeUtil.tryMergeBlock(n, false)) {
reportChangeToEnclosingScope(parent);
return null;
}
return n;
} } | public class class_name {
Node tryOptimizeBlock(Node n) {
// Remove any useless children
for (Node c = n.getFirstChild(); c != null; ) {
Node next = c.getNext(); // save c.next, since 'c' may be removed
if (!isUnremovableNode(c) && !mayHaveSideEffects(c)) {
checkNormalization(!NodeUtil.isFunctionDeclaration(n), "function declaration"); // depends on control dependency: [if], data = [none]
// TODO(johnlenz): determine what this is actually removing. Candidates
// include: EMPTY nodes, control structures without children
// (removing infinite loops), empty try blocks. What else?
n.removeChild(c); // depends on control dependency: [if], data = [none]
reportChangeToEnclosingScope(n); // depends on control dependency: [if], data = [none]
markFunctionsDeleted(c); // depends on control dependency: [if], data = [none]
} else {
tryOptimizeConditionalAfterAssign(c); // depends on control dependency: [if], data = [none]
}
c = next; // depends on control dependency: [for], data = [c]
}
if (n.isSyntheticBlock() || n.isScript() || n.getParent() == null) {
return n; // depends on control dependency: [if], data = [none]
}
// Try to remove the block.
Node parent = n.getParent();
if (NodeUtil.tryMergeBlock(n, false)) {
reportChangeToEnclosingScope(parent); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
return n;
} } |
public class class_name {
protected String getSingleStringAttribute(MBeanServerExecutor pMBeanServerExecutor, String pMBeanName, String pAttribute) {
Set<ObjectName> serverMBeanNames = searchMBeans(pMBeanServerExecutor, pMBeanName);
if (serverMBeanNames.size() == 0) {
return null;
}
Set<String> attributeValues = new HashSet<String>();
for (ObjectName oName : serverMBeanNames) {
String val = getAttributeValue(pMBeanServerExecutor, oName, pAttribute);
if (val != null) {
attributeValues.add(val);
}
}
if (attributeValues.size() == 0 || attributeValues.size() > 1) {
return null;
}
return attributeValues.iterator().next();
} } | public class class_name {
protected String getSingleStringAttribute(MBeanServerExecutor pMBeanServerExecutor, String pMBeanName, String pAttribute) {
Set<ObjectName> serverMBeanNames = searchMBeans(pMBeanServerExecutor, pMBeanName);
if (serverMBeanNames.size() == 0) {
return null; // depends on control dependency: [if], data = [none]
}
Set<String> attributeValues = new HashSet<String>();
for (ObjectName oName : serverMBeanNames) {
String val = getAttributeValue(pMBeanServerExecutor, oName, pAttribute);
if (val != null) {
attributeValues.add(val); // depends on control dependency: [if], data = [(val]
}
}
if (attributeValues.size() == 0 || attributeValues.size() > 1) {
return null; // depends on control dependency: [if], data = [none]
}
return attributeValues.iterator().next();
} } |
public class class_name {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/{alertId}/notifications/{notificationId}/triggers/{triggerId}")
@Description(
"Associates the trigger having the given ID to the given notification ID. Both the trigger and notification must be owned by the alert."
)
public TriggerDto addTriggerToNotification(@Context HttpServletRequest req,
@PathParam("alertId") BigInteger alertId,
@PathParam("notificationId") BigInteger notificationId,
@PathParam("triggerId") BigInteger triggerId) {
if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
if (notificationId == null || notificationId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Notification Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
if (triggerId == null || triggerId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Trigger Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
Notification notification = null;
Trigger alertTrigger = null;
Alert alert = alertService.findAlertByPrimaryKey(alertId);
if (alert == null) {
throw new WebApplicationException(Status.NOT_FOUND.getReasonPhrase(), Status.NOT_FOUND);
}
validateResourceAuthorization(req, alert.getOwner(), getRemoteUser(req));
for (Notification tempNotification : alert.getNotifications()) {
if (tempNotification.getId().equals(notificationId)) {
notification = tempNotification;
break;
}
}
if (notification == null) {
throw new WebApplicationException("Notification Id does not exist for this alert.", Status.BAD_REQUEST);
}
for (Trigger tempTrigger : alert.getTriggers()) {
if (tempTrigger.getId().equals(triggerId)) {
alertTrigger = tempTrigger;
break;
}
}
if (alertTrigger == null) {
throw new WebApplicationException("Trigger Id does not exist for this alert. Create a trigger first then add it to the notification",
Status.BAD_REQUEST);
}
// Make sure that the notification does not have this trigger.
for (Trigger tempTrigger : notification.getTriggers()) {
if (tempTrigger.getId().equals(triggerId)) {
throw new WebApplicationException("This trigger already exists for the notification.", Status.BAD_REQUEST);
}
}
List<Trigger> list = new ArrayList<Trigger>(notification.getTriggers());
list.add(alertTrigger);
notification.setTriggers(list);
alert.setModifiedBy(getRemoteUser(req));
alert = alertService.updateAlert(alert);
for (Notification tempNotification : alert.getNotifications()) {
if (tempNotification.getId().equals(notificationId)) {
for (Trigger tempTrigger : notification.getTriggers()) {
if (tempTrigger.getId().equals(triggerId)) {
return TriggerDto.transformToDto(tempTrigger);
}
}
}
}
throw new WebApplicationException("Trigger update failed.", Status.INTERNAL_SERVER_ERROR);
} } | public class class_name {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/{alertId}/notifications/{notificationId}/triggers/{triggerId}")
@Description(
"Associates the trigger having the given ID to the given notification ID. Both the trigger and notification must be owned by the alert."
)
public TriggerDto addTriggerToNotification(@Context HttpServletRequest req,
@PathParam("alertId") BigInteger alertId,
@PathParam("notificationId") BigInteger notificationId,
@PathParam("triggerId") BigInteger triggerId) {
if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
if (notificationId == null || notificationId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Notification Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
if (triggerId == null || triggerId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Trigger Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
Notification notification = null;
Trigger alertTrigger = null;
Alert alert = alertService.findAlertByPrimaryKey(alertId);
if (alert == null) {
throw new WebApplicationException(Status.NOT_FOUND.getReasonPhrase(), Status.NOT_FOUND);
}
validateResourceAuthorization(req, alert.getOwner(), getRemoteUser(req));
for (Notification tempNotification : alert.getNotifications()) {
if (tempNotification.getId().equals(notificationId)) {
notification = tempNotification; // depends on control dependency: [if], data = [none]
break;
}
}
if (notification == null) {
throw new WebApplicationException("Notification Id does not exist for this alert.", Status.BAD_REQUEST);
}
for (Trigger tempTrigger : alert.getTriggers()) {
if (tempTrigger.getId().equals(triggerId)) {
alertTrigger = tempTrigger; // depends on control dependency: [if], data = [none]
break;
}
}
if (alertTrigger == null) {
throw new WebApplicationException("Trigger Id does not exist for this alert. Create a trigger first then add it to the notification",
Status.BAD_REQUEST);
}
// Make sure that the notification does not have this trigger.
for (Trigger tempTrigger : notification.getTriggers()) {
if (tempTrigger.getId().equals(triggerId)) {
throw new WebApplicationException("This trigger already exists for the notification.", Status.BAD_REQUEST);
}
}
List<Trigger> list = new ArrayList<Trigger>(notification.getTriggers());
list.add(alertTrigger);
notification.setTriggers(list);
alert.setModifiedBy(getRemoteUser(req));
alert = alertService.updateAlert(alert);
for (Notification tempNotification : alert.getNotifications()) {
if (tempNotification.getId().equals(notificationId)) {
for (Trigger tempTrigger : notification.getTriggers()) {
if (tempTrigger.getId().equals(triggerId)) {
return TriggerDto.transformToDto(tempTrigger); // depends on control dependency: [if], data = [none]
}
}
}
}
throw new WebApplicationException("Trigger update failed.", Status.INTERNAL_SERVER_ERROR);
} } |
public class class_name {
public static @DottedClassName
String extractPackageName(@DottedClassName String className) {
int i = className.lastIndexOf('.');
if (i < 0) {
return "";
}
return className.substring(0, i);
} } | public class class_name {
public static @DottedClassName
String extractPackageName(@DottedClassName String className) {
int i = className.lastIndexOf('.');
if (i < 0) {
return ""; // depends on control dependency: [if], data = [none]
}
return className.substring(0, i);
} } |
public class class_name {
public boolean buildData(String[] data) {
final int length = data.length;
for (int i = 0; i < length; i++) {
addAddressToList(data[i]);
}
return true;
} } | public class class_name {
public boolean buildData(String[] data) {
final int length = data.length;
for (int i = 0; i < length; i++) {
addAddressToList(data[i]); // depends on control dependency: [for], data = [i]
}
return true;
} } |
public class class_name {
private double radicalInverse(long i) {
double digit = 1.0 / (double) base;
double radical = digit;
double inverse = 0.0;
while(i > 0) {
inverse += digit * (double) (i % base);
digit *= radical;
i /= base;
}
return inverse;
} } | public class class_name {
private double radicalInverse(long i) {
double digit = 1.0 / (double) base;
double radical = digit;
double inverse = 0.0;
while(i > 0) {
inverse += digit * (double) (i % base); // depends on control dependency: [while], data = [(i]
digit *= radical; // depends on control dependency: [while], data = [none]
i /= base; // depends on control dependency: [while], data = [none]
}
return inverse;
} } |
public class class_name {
public static base_responses add(nitro_service client, pqpolicy resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
pqpolicy addresources[] = new pqpolicy[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new pqpolicy();
addresources[i].policyname = resources[i].policyname;
addresources[i].rule = resources[i].rule;
addresources[i].priority = resources[i].priority;
addresources[i].weight = resources[i].weight;
addresources[i].qdepth = resources[i].qdepth;
addresources[i].polqdepth = resources[i].polqdepth;
}
result = add_bulk_request(client, addresources);
}
return result;
} } | public class class_name {
public static base_responses add(nitro_service client, pqpolicy resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
pqpolicy addresources[] = new pqpolicy[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new pqpolicy(); // depends on control dependency: [for], data = [i]
addresources[i].policyname = resources[i].policyname; // depends on control dependency: [for], data = [i]
addresources[i].rule = resources[i].rule; // depends on control dependency: [for], data = [i]
addresources[i].priority = resources[i].priority; // depends on control dependency: [for], data = [i]
addresources[i].weight = resources[i].weight; // depends on control dependency: [for], data = [i]
addresources[i].qdepth = resources[i].qdepth; // depends on control dependency: [for], data = [i]
addresources[i].polqdepth = resources[i].polqdepth; // depends on control dependency: [for], data = [i]
}
result = add_bulk_request(client, addresources);
}
return result;
} } |
public class class_name {
public static JulianChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) {
if (zone == null) {
zone = DateTimeZone.getDefault();
}
JulianChronology chrono;
JulianChronology[] chronos = cCache.get(zone);
if (chronos == null) {
chronos = new JulianChronology[7];
JulianChronology[] oldChronos = cCache.putIfAbsent(zone, chronos);
if (oldChronos != null) {
chronos = oldChronos;
}
}
try {
chrono = chronos[minDaysInFirstWeek - 1];
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException
("Invalid min days in first week: " + minDaysInFirstWeek);
}
if (chrono == null) {
synchronized (chronos) {
chrono = chronos[minDaysInFirstWeek - 1];
if (chrono == null) {
if (zone == DateTimeZone.UTC) {
chrono = new JulianChronology(null, null, minDaysInFirstWeek);
} else {
chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek);
chrono = new JulianChronology
(ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek);
}
chronos[minDaysInFirstWeek - 1] = chrono;
}
}
}
return chrono;
} } | public class class_name {
public static JulianChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) {
if (zone == null) {
zone = DateTimeZone.getDefault(); // depends on control dependency: [if], data = [none]
}
JulianChronology chrono;
JulianChronology[] chronos = cCache.get(zone);
if (chronos == null) {
chronos = new JulianChronology[7]; // depends on control dependency: [if], data = [none]
JulianChronology[] oldChronos = cCache.putIfAbsent(zone, chronos);
if (oldChronos != null) {
chronos = oldChronos; // depends on control dependency: [if], data = [none]
}
}
try {
chrono = chronos[minDaysInFirstWeek - 1]; // depends on control dependency: [try], data = [none]
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException
("Invalid min days in first week: " + minDaysInFirstWeek);
} // depends on control dependency: [catch], data = [none]
if (chrono == null) {
synchronized (chronos) { // depends on control dependency: [if], data = [(chrono]
chrono = chronos[minDaysInFirstWeek - 1];
if (chrono == null) {
if (zone == DateTimeZone.UTC) {
chrono = new JulianChronology(null, null, minDaysInFirstWeek); // depends on control dependency: [if], data = [none]
} else {
chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); // depends on control dependency: [if], data = [none]
chrono = new JulianChronology
(ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); // depends on control dependency: [if], data = [none]
}
chronos[minDaysInFirstWeek - 1] = chrono; // depends on control dependency: [if], data = [none]
}
}
}
return chrono;
} } |
public class class_name {
protected <T extends DataSiftResult, A extends DataSiftResult> void unwrapFuture(FutureData<T> futureToUnwrap,
final FutureData<A>
futureReturnedToUser,
final A expectedInstance,
final FutureResponse<T>
responseToExecuteOnSuccess
) {
futureToUnwrap.onData(new FutureResponse<T>() {
public void apply(T stream) {
if (stream.isSuccessful()) {
responseToExecuteOnSuccess.apply(stream);
} else {
expectedInstance.setResponse(stream.getResponse());
futureReturnedToUser.received(expectedInstance);
}
}
});
} } | public class class_name {
protected <T extends DataSiftResult, A extends DataSiftResult> void unwrapFuture(FutureData<T> futureToUnwrap,
final FutureData<A>
futureReturnedToUser,
final A expectedInstance,
final FutureResponse<T>
responseToExecuteOnSuccess
) {
futureToUnwrap.onData(new FutureResponse<T>() {
public void apply(T stream) {
if (stream.isSuccessful()) {
responseToExecuteOnSuccess.apply(stream); // depends on control dependency: [if], data = [none]
} else {
expectedInstance.setResponse(stream.getResponse()); // depends on control dependency: [if], data = [none]
futureReturnedToUser.received(expectedInstance); // depends on control dependency: [if], data = [none]
}
}
});
} } |
public class class_name {
public BaseServerResponseException addResponseHeader(String theName, String theValue) {
Validate.notBlank(theName, "theName must not be null or empty");
Validate.notBlank(theValue, "theValue must not be null or empty");
if (getResponseHeaders().containsKey(theName) == false) {
getResponseHeaders().put(theName, new ArrayList<>());
}
getResponseHeaders().get(theName).add(theValue);
return this;
} } | public class class_name {
public BaseServerResponseException addResponseHeader(String theName, String theValue) {
Validate.notBlank(theName, "theName must not be null or empty");
Validate.notBlank(theValue, "theValue must not be null or empty");
if (getResponseHeaders().containsKey(theName) == false) {
getResponseHeaders().put(theName, new ArrayList<>()); // depends on control dependency: [if], data = [none]
}
getResponseHeaders().get(theName).add(theValue);
return this;
} } |
public class class_name {
@Override
public Object visit(Before before, Object extraData) {
String propertyName = getPropertyName(before.getExpression1());
String finalName = parsePropertyName(propertyName, before);
Object literal = getLiteralValue(before.getExpression2());
if (literal instanceof Date) {
return Restrictions.lt(finalName, literal);
} else {
throw new UnsupportedOperationException("visit(Object userData)");
}
} } | public class class_name {
@Override
public Object visit(Before before, Object extraData) {
String propertyName = getPropertyName(before.getExpression1());
String finalName = parsePropertyName(propertyName, before);
Object literal = getLiteralValue(before.getExpression2());
if (literal instanceof Date) {
return Restrictions.lt(finalName, literal); // depends on control dependency: [if], data = [none]
} else {
throw new UnsupportedOperationException("visit(Object userData)");
}
} } |
public class class_name {
public void marshall(EyeOpen eyeOpen, ProtocolMarshaller protocolMarshaller) {
if (eyeOpen == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(eyeOpen.getValue(), VALUE_BINDING);
protocolMarshaller.marshall(eyeOpen.getConfidence(), CONFIDENCE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(EyeOpen eyeOpen, ProtocolMarshaller protocolMarshaller) {
if (eyeOpen == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(eyeOpen.getValue(), VALUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eyeOpen.getConfidence(), CONFIDENCE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void showTracking(Formatter format) {
if (track == null) return;
List<Tracker> all = new ArrayList<>(track.size());
for (Tracker val : track.values()) all.add(val);
Collections.sort(all); // LOOK what should we sort by ??
int count = 0;
int countAll = 0;
format.format("%nTrack of all files in FileCacheARC%n");
format.format(" seq accum hit miss file%n");
for (Tracker t : all) {
count++;
countAll += t.hit + t.miss;
format.format("%6d %6d : %5d %5d %s%n", count, countAll, t.hit, t.miss, t.key);
}
format.format("%n");
} } | public class class_name {
public void showTracking(Formatter format) {
if (track == null) return;
List<Tracker> all = new ArrayList<>(track.size());
for (Tracker val : track.values()) all.add(val);
Collections.sort(all); // LOOK what should we sort by ??
int count = 0;
int countAll = 0;
format.format("%nTrack of all files in FileCacheARC%n");
format.format(" seq accum hit miss file%n");
for (Tracker t : all) {
count++; // depends on control dependency: [for], data = [t]
countAll += t.hit + t.miss; // depends on control dependency: [for], data = [t]
format.format("%6d %6d : %5d %5d %s%n", count, countAll, t.hit, t.miss, t.key); // depends on control dependency: [for], data = [t]
}
format.format("%n");
} } |
public class class_name {
protected ObjectOutputStream getObjectOutputStream (FramingOutputStream fout)
{
// we're lazy about creating our output stream because we may be inheriting it from our
// authing connection and we don't want to unnecessarily create it in that case
if (_oout == null) {
_oout = new ObjectOutputStream(fout);
}
return _oout;
} } | public class class_name {
protected ObjectOutputStream getObjectOutputStream (FramingOutputStream fout)
{
// we're lazy about creating our output stream because we may be inheriting it from our
// authing connection and we don't want to unnecessarily create it in that case
if (_oout == null) {
_oout = new ObjectOutputStream(fout); // depends on control dependency: [if], data = [none]
}
return _oout;
} } |
public class class_name {
@Override
public NamespaceGroup convert(XBELNamespaceGroup source) {
if (source == null) return null;
String defaultResourceLocation = source.getDefaultResourceLocation();
List<XBELNamespace> xbelnamespaces = source.getNamespace();
NamespaceGroup dest = new NamespaceGroup();
int size = xbelnamespaces.size();
final List<Namespace> namespaces = new ArrayList<Namespace>(size);
NamespaceConverter nsConverter = new NamespaceConverter();
for (final XBELNamespace xns : xbelnamespaces) {
// Defer to NamespaceConverter
namespaces.add(nsConverter.convert(xns));
}
dest.setDefaultResourceLocation(defaultResourceLocation);
dest.setNamespaces(namespaces);
return dest;
} } | public class class_name {
@Override
public NamespaceGroup convert(XBELNamespaceGroup source) {
if (source == null) return null;
String defaultResourceLocation = source.getDefaultResourceLocation();
List<XBELNamespace> xbelnamespaces = source.getNamespace();
NamespaceGroup dest = new NamespaceGroup();
int size = xbelnamespaces.size();
final List<Namespace> namespaces = new ArrayList<Namespace>(size);
NamespaceConverter nsConverter = new NamespaceConverter();
for (final XBELNamespace xns : xbelnamespaces) {
// Defer to NamespaceConverter
namespaces.add(nsConverter.convert(xns)); // depends on control dependency: [for], data = [xns]
}
dest.setDefaultResourceLocation(defaultResourceLocation);
dest.setNamespaces(namespaces);
return dest;
} } |
public class class_name {
public void setUsers(final List<User> users)
{
synchronized(this.getUsers())
{
if(users != this.getUsers())
{
this.getUsers().clear();
if(users != null)
{
this.getUsers().addAll(users);
}
}
}
} } | public class class_name {
public void setUsers(final List<User> users)
{
synchronized(this.getUsers())
{
if(users != this.getUsers())
{
this.getUsers().clear(); // depends on control dependency: [if], data = [none]
if(users != null)
{
this.getUsers().addAll(users); // depends on control dependency: [if], data = [(users]
}
}
}
} } |
public class class_name {
@Override
public Header getResponseHeader(String headerName) {
if (headerName == null) {
return null;
} else {
return getResponseHeaderGroup().getCondensedHeader(headerName);
}
} } | public class class_name {
@Override
public Header getResponseHeader(String headerName) {
if (headerName == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
return getResponseHeaderGroup().getCondensedHeader(headerName); // depends on control dependency: [if], data = [(headerName]
}
} } |
public class class_name {
public boolean reverseTransformPacket(RawPacket pkt) {
int seqNo = pkt.getSequenceNumber();
if (!seqNumSet) {
seqNumSet = true;
seqNum = seqNo;
}
// Guess the SRTP index (48 bit), see rFC 3711, 3.3.1
// Stores the guessed roc in this.guessedROC
long guessedIndex = guessIndex(seqNo);
// Replay control
if (!checkReplay(seqNo, guessedIndex)) {
return false;
}
// Authenticate packet
if (policy.getAuthType() != SRTPPolicy.NULL_AUTHENTICATION) {
int tagLength = policy.getAuthTagLength();
// get original authentication and store in tempStore
pkt.readRegionToBuff(pkt.getLength() - tagLength, tagLength, tempStore);
pkt.shrink(tagLength);
// save computed authentication in tagStore
authenticatePacketHMCSHA1(pkt, guessedROC);
for (int i = 0; i < tagLength; i++) {
if ((tempStore[i] & 0xff) != (tagStore[i] & 0xff)) {
return false;
}
}
}
// Decrypt packet
switch (policy.getEncType()) {
case SRTPPolicy.AESCM_ENCRYPTION:
case SRTPPolicy.TWOFISH_ENCRYPTION:
// using Counter Mode encryption
processPacketAESCM(pkt);
break;
case SRTPPolicy.AESF8_ENCRYPTION:
case SRTPPolicy.TWOFISHF8_ENCRYPTION:
// using F8 Mode encryption
processPacketAESF8(pkt);
break;
default:
return false;
}
update(seqNo, guessedIndex);
return true;
} } | public class class_name {
public boolean reverseTransformPacket(RawPacket pkt) {
int seqNo = pkt.getSequenceNumber();
if (!seqNumSet) {
seqNumSet = true; // depends on control dependency: [if], data = [none]
seqNum = seqNo; // depends on control dependency: [if], data = [none]
}
// Guess the SRTP index (48 bit), see rFC 3711, 3.3.1
// Stores the guessed roc in this.guessedROC
long guessedIndex = guessIndex(seqNo);
// Replay control
if (!checkReplay(seqNo, guessedIndex)) {
return false; // depends on control dependency: [if], data = [none]
}
// Authenticate packet
if (policy.getAuthType() != SRTPPolicy.NULL_AUTHENTICATION) {
int tagLength = policy.getAuthTagLength();
// get original authentication and store in tempStore
pkt.readRegionToBuff(pkt.getLength() - tagLength, tagLength, tempStore); // depends on control dependency: [if], data = [none]
pkt.shrink(tagLength); // depends on control dependency: [if], data = [none]
// save computed authentication in tagStore
authenticatePacketHMCSHA1(pkt, guessedROC); // depends on control dependency: [if], data = [none]
for (int i = 0; i < tagLength; i++) {
if ((tempStore[i] & 0xff) != (tagStore[i] & 0xff)) {
return false; // depends on control dependency: [if], data = [none]
}
}
}
// Decrypt packet
switch (policy.getEncType()) {
case SRTPPolicy.AESCM_ENCRYPTION:
case SRTPPolicy.TWOFISH_ENCRYPTION:
// using Counter Mode encryption
processPacketAESCM(pkt);
break;
case SRTPPolicy.AESF8_ENCRYPTION:
case SRTPPolicy.TWOFISHF8_ENCRYPTION:
// using F8 Mode encryption
processPacketAESF8(pkt);
break;
default:
return false;
}
update(seqNo, guessedIndex);
return true;
} } |
public class class_name {
public void unreferenceSSTables()
{
Set<SSTableReader> notCompacting;
View currentView, newView;
do
{
currentView = view.get();
notCompacting = currentView.nonCompactingSStables();
newView = currentView.replace(notCompacting, Collections.<SSTableReader>emptySet());
}
while (!view.compareAndSet(currentView, newView));
if (notCompacting.isEmpty())
{
// notifySSTablesChanged -> LeveledManifest.promote doesn't like a no-op "promotion"
return;
}
notifySSTablesChanged(notCompacting, Collections.<SSTableReader>emptySet(), OperationType.UNKNOWN);
removeOldSSTablesSize(notCompacting);
releaseReferences(notCompacting, true);
} } | public class class_name {
public void unreferenceSSTables()
{
Set<SSTableReader> notCompacting;
View currentView, newView;
do
{
currentView = view.get();
notCompacting = currentView.nonCompactingSStables();
newView = currentView.replace(notCompacting, Collections.<SSTableReader>emptySet());
}
while (!view.compareAndSet(currentView, newView));
if (notCompacting.isEmpty())
{
// notifySSTablesChanged -> LeveledManifest.promote doesn't like a no-op "promotion"
return; // depends on control dependency: [if], data = [none]
}
notifySSTablesChanged(notCompacting, Collections.<SSTableReader>emptySet(), OperationType.UNKNOWN);
removeOldSSTablesSize(notCompacting);
releaseReferences(notCompacting, true);
} } |
public class class_name {
public static List<String> get(String name, @Nullable Path file) {
if (file != null) {
if (!file.toString().isEmpty()) {
return Arrays.asList("--" + name + "=" + file.toString());
}
}
return Collections.emptyList();
} } | public class class_name {
public static List<String> get(String name, @Nullable Path file) {
if (file != null) {
if (!file.toString().isEmpty()) {
return Arrays.asList("--" + name + "=" + file.toString()); // depends on control dependency: [if], data = [none]
}
}
return Collections.emptyList();
} } |
public class class_name {
private String getAvailableLocalVariant(String path, String baseName) {
//First look for a bundle with the locale of the folder..
try {
CmsProperty propLoc = m_clonedCms.readPropertyObject(path, CmsPropertyDefinition.PROPERTY_LOCALE, true);
if (!propLoc.isNullProperty()) {
if (m_clonedCms.existsResource(path + baseName + "_" + propLoc.getValue())) {
return baseName + "_" + propLoc.getValue();
}
}
} catch (CmsException e) {
LOG.error("Can not read locale property", e);
}
//If no bundle was found with the locale of the folder, or the property was not set, search for other locales
A_CmsUI.get();
List<String> localVariations = CmsLocaleManager.getLocaleVariants(
baseName,
UI.getCurrent().getLocale(),
false,
true);
for (String name : localVariations) {
if (m_clonedCms.existsResource(path + name)) {
return name;
}
}
return null;
} } | public class class_name {
private String getAvailableLocalVariant(String path, String baseName) {
//First look for a bundle with the locale of the folder..
try {
CmsProperty propLoc = m_clonedCms.readPropertyObject(path, CmsPropertyDefinition.PROPERTY_LOCALE, true);
if (!propLoc.isNullProperty()) {
if (m_clonedCms.existsResource(path + baseName + "_" + propLoc.getValue())) {
return baseName + "_" + propLoc.getValue(); // depends on control dependency: [if], data = [none]
}
}
} catch (CmsException e) {
LOG.error("Can not read locale property", e);
} // depends on control dependency: [catch], data = [none]
//If no bundle was found with the locale of the folder, or the property was not set, search for other locales
A_CmsUI.get();
List<String> localVariations = CmsLocaleManager.getLocaleVariants(
baseName,
UI.getCurrent().getLocale(),
false,
true);
for (String name : localVariations) {
if (m_clonedCms.existsResource(path + name)) {
return name; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static <T> Stream<T> makeRef(AbstractPipeline<?, T, ?> upstream,
long skip, long limit) {
if (skip < 0)
throw new IllegalArgumentException("Skip must be non-negative: " + skip);
return new ReferencePipeline.StatefulOp<T, T>(upstream, StreamShape.REFERENCE,
flags(limit)) {
Spliterator<T> unorderedSkipLimitSpliterator(Spliterator<T> s,
long skip, long limit, long sizeIfKnown) {
if (skip <= sizeIfKnown) {
// Use just the limit if the number of elements
// to skip is <= the known pipeline size
limit = limit >= 0 ? Math.min(limit, sizeIfKnown - skip) : sizeIfKnown - skip;
skip = 0;
}
return new StreamSpliterators.UnorderedSliceSpliterator.OfRef<>(s, skip, limit);
}
@Override
public <P_IN> Spliterator<T> opEvaluateParallelLazy(PipelineHelper<T> helper, Spliterator<P_IN> spliterator) {
long size = helper.exactOutputSizeIfKnown(spliterator);
if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
return new StreamSpliterators.SliceSpliterator.OfRef<>(
helper.wrapSpliterator(spliterator),
skip,
calcSliceFence(skip, limit));
} else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
return unorderedSkipLimitSpliterator(
helper.wrapSpliterator(spliterator),
skip, limit, size);
}
else {
// @@@ OOMEs will occur for LongStream.longs().filter(i -> true).limit(n)
// regardless of the value of n
// Need to adjust the target size of splitting for the
// SliceTask from say (size / k) to say min(size / k, 1 << 14)
// This will limit the size of the buffers created at the leaf nodes
// cancellation will be more aggressive cancelling later tasks
// if the target slice size has been reached from a given task,
// cancellation should also clear local results if any
return new SliceTask<>(this, helper, spliterator, castingArray(), skip, limit).
invoke().spliterator();
}
}
@Override
public <P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper,
Spliterator<P_IN> spliterator,
IntFunction<T[]> generator) {
long size = helper.exactOutputSizeIfKnown(spliterator);
if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
// Because the pipeline is SIZED the slice spliterator
// can be created from the source, this requires matching
// to shape of the source, and is potentially more efficient
// than creating the slice spliterator from the pipeline
// wrapping spliterator
Spliterator<P_IN> s = sliceSpliterator(helper.getSourceShape(), spliterator, skip, limit);
return Nodes.collect(helper, s, true, generator);
} else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
Spliterator<T> s = unorderedSkipLimitSpliterator(
helper.wrapSpliterator(spliterator),
skip, limit, size);
// Collect using this pipeline, which is empty and therefore
// can be used with the pipeline wrapping spliterator
// Note that we cannot create a slice spliterator from
// the source spliterator if the pipeline is not SIZED
return Nodes.collect(this, s, true, generator);
}
else {
return new SliceTask<>(this, helper, spliterator, generator, skip, limit).
invoke();
}
}
@Override
public Sink<T> opWrapSink(int flags, Sink<T> sink) {
return new Sink.ChainedReference<T, T>(sink) {
long n = skip;
long m = limit >= 0 ? limit : Long.MAX_VALUE;
@Override
public void begin(long size) {
downstream.begin(calcSize(size, skip, m));
}
@Override
public void accept(T t) {
if (n == 0) {
if (m > 0) {
m--;
downstream.accept(t);
}
}
else {
n--;
}
}
@Override
public boolean cancellationRequested() {
return m == 0 || downstream.cancellationRequested();
}
};
}
};
} } | public class class_name {
public static <T> Stream<T> makeRef(AbstractPipeline<?, T, ?> upstream,
long skip, long limit) {
if (skip < 0)
throw new IllegalArgumentException("Skip must be non-negative: " + skip);
return new ReferencePipeline.StatefulOp<T, T>(upstream, StreamShape.REFERENCE,
flags(limit)) {
Spliterator<T> unorderedSkipLimitSpliterator(Spliterator<T> s,
long skip, long limit, long sizeIfKnown) {
if (skip <= sizeIfKnown) {
// Use just the limit if the number of elements
// to skip is <= the known pipeline size
limit = limit >= 0 ? Math.min(limit, sizeIfKnown - skip) : sizeIfKnown - skip; // depends on control dependency: [if], data = [none]
skip = 0; // depends on control dependency: [if], data = [none]
}
return new StreamSpliterators.UnorderedSliceSpliterator.OfRef<>(s, skip, limit);
}
@Override
public <P_IN> Spliterator<T> opEvaluateParallelLazy(PipelineHelper<T> helper, Spliterator<P_IN> spliterator) {
long size = helper.exactOutputSizeIfKnown(spliterator);
if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
return new StreamSpliterators.SliceSpliterator.OfRef<>(
helper.wrapSpliterator(spliterator),
skip,
calcSliceFence(skip, limit)); // depends on control dependency: [if], data = [none]
} else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
return unorderedSkipLimitSpliterator(
helper.wrapSpliterator(spliterator),
skip, limit, size); // depends on control dependency: [if], data = [none]
}
else {
// @@@ OOMEs will occur for LongStream.longs().filter(i -> true).limit(n)
// regardless of the value of n
// Need to adjust the target size of splitting for the
// SliceTask from say (size / k) to say min(size / k, 1 << 14)
// This will limit the size of the buffers created at the leaf nodes
// cancellation will be more aggressive cancelling later tasks
// if the target slice size has been reached from a given task,
// cancellation should also clear local results if any
return new SliceTask<>(this, helper, spliterator, castingArray(), skip, limit).
invoke().spliterator(); // depends on control dependency: [if], data = [none]
}
}
@Override
public <P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper,
Spliterator<P_IN> spliterator,
IntFunction<T[]> generator) {
long size = helper.exactOutputSizeIfKnown(spliterator);
if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
// Because the pipeline is SIZED the slice spliterator
// can be created from the source, this requires matching
// to shape of the source, and is potentially more efficient
// than creating the slice spliterator from the pipeline
// wrapping spliterator
Spliterator<P_IN> s = sliceSpliterator(helper.getSourceShape(), spliterator, skip, limit);
return Nodes.collect(helper, s, true, generator); // depends on control dependency: [if], data = [none]
} else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
Spliterator<T> s = unorderedSkipLimitSpliterator(
helper.wrapSpliterator(spliterator),
skip, limit, size);
// Collect using this pipeline, which is empty and therefore
// can be used with the pipeline wrapping spliterator
// Note that we cannot create a slice spliterator from
// the source spliterator if the pipeline is not SIZED
return Nodes.collect(this, s, true, generator); // depends on control dependency: [if], data = [none]
}
else {
return new SliceTask<>(this, helper, spliterator, generator, skip, limit).
invoke(); // depends on control dependency: [if], data = [none]
}
}
@Override
public Sink<T> opWrapSink(int flags, Sink<T> sink) {
return new Sink.ChainedReference<T, T>(sink) {
long n = skip;
long m = limit >= 0 ? limit : Long.MAX_VALUE;
@Override
public void begin(long size) {
downstream.begin(calcSize(size, skip, m));
}
@Override
public void accept(T t) {
if (n == 0) {
if (m > 0) {
m--; // depends on control dependency: [if], data = [none]
downstream.accept(t); // depends on control dependency: [if], data = [none]
}
}
else {
n--; // depends on control dependency: [if], data = [none]
}
}
@Override
public boolean cancellationRequested() {
return m == 0 || downstream.cancellationRequested();
}
};
}
};
} } |
public class class_name {
static final long[] compactCachePart(final long[] srcCache, final int lgArrLongs,
final int curCount, final long thetaLong, final boolean dstOrdered) {
if (curCount == 0) {
return new long[0];
}
final long[] cacheOut = new long[curCount];
final int len = 1 << lgArrLongs;
int j = 0;
for (int i = 0; i < len; i++) {
final long v = srcCache[i];
if ((v <= 0L) || (v >= thetaLong) ) { continue; }
cacheOut[j++] = v;
}
assert curCount == j;
if (dstOrdered) {
Arrays.sort(cacheOut);
}
return cacheOut;
} } | public class class_name {
static final long[] compactCachePart(final long[] srcCache, final int lgArrLongs,
final int curCount, final long thetaLong, final boolean dstOrdered) {
if (curCount == 0) {
return new long[0]; // depends on control dependency: [if], data = [none]
}
final long[] cacheOut = new long[curCount];
final int len = 1 << lgArrLongs;
int j = 0;
for (int i = 0; i < len; i++) {
final long v = srcCache[i];
if ((v <= 0L) || (v >= thetaLong) ) { continue; }
cacheOut[j++] = v; // depends on control dependency: [for], data = [none]
}
assert curCount == j;
if (dstOrdered) {
Arrays.sort(cacheOut); // depends on control dependency: [if], data = [none]
}
return cacheOut;
} } |
public class class_name {
@Override
public void resolve(final ValueStack values) throws Exception
{
if (values.size() < 2)
throw new Exception("missing operands for " + toString());
try
{
final String tableName = values.popString();
final Double baseAmount = values.popDouble();
if (baseAmount.doubleValue() == 0)
{
values.push(new Double(0D));
return;
}
final EquationSupport model = getEqu().getSupport();
final Hashtable<Double, Double> rateTable = model.resolveRate(tableName, getEqu().getBaseDate(), baseAmount
.doubleValue());
double blendedRate = 0;
double previousLimit = 0;
double previousRate = 0;
/*
* only the last key in the table is used for tiered rates
*/
for (final Enumeration<Double> limits = rateTable.keys(); limits.hasMoreElements();)
{
final Double limit = limits.nextElement();
final Double rate = rateTable.get(limit);
if (previousRate > 0)
blendedRate += (previousRate * ((limit.doubleValue() - previousLimit) / baseAmount.doubleValue()));
previousRate = rate.doubleValue();
previousLimit = limit.doubleValue();
}
if (previousRate > 0)
blendedRate += (previousRate * ((baseAmount.doubleValue() - previousLimit) / baseAmount.doubleValue()));
values.push(new Double(blendedRate));
} catch (final ParseException e)
{
e.fillInStackTrace();
throw new Exception(toString() + "; " + e.getMessage(), e);
}
} } | public class class_name {
@Override
public void resolve(final ValueStack values) throws Exception
{
if (values.size() < 2)
throw new Exception("missing operands for " + toString());
try
{
final String tableName = values.popString();
final Double baseAmount = values.popDouble();
if (baseAmount.doubleValue() == 0)
{
values.push(new Double(0D)); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final EquationSupport model = getEqu().getSupport();
final Hashtable<Double, Double> rateTable = model.resolveRate(tableName, getEqu().getBaseDate(), baseAmount
.doubleValue());
double blendedRate = 0;
double previousLimit = 0;
double previousRate = 0;
/*
* only the last key in the table is used for tiered rates
*/
for (final Enumeration<Double> limits = rateTable.keys(); limits.hasMoreElements();)
{
final Double limit = limits.nextElement();
final Double rate = rateTable.get(limit);
if (previousRate > 0)
blendedRate += (previousRate * ((limit.doubleValue() - previousLimit) / baseAmount.doubleValue()));
previousRate = rate.doubleValue(); // depends on control dependency: [for], data = [none]
previousLimit = limit.doubleValue(); // depends on control dependency: [for], data = [none]
}
if (previousRate > 0)
blendedRate += (previousRate * ((baseAmount.doubleValue() - previousLimit) / baseAmount.doubleValue()));
values.push(new Double(blendedRate));
} catch (final ParseException e)
{
e.fillInStackTrace();
throw new Exception(toString() + "; " + e.getMessage(), e);
}
} } |
public class class_name {
@Override
public TimeZoneTransition getNextTransition(long base, boolean inclusive) {
complete();
if (historicTransitions == null) {
return null;
}
boolean isFinal = false;
TimeZoneTransition result;
TimeZoneTransition tzt = historicTransitions.get(0);
long tt = tzt.getTime();
if (tt > base || (inclusive && tt == base)) {
result = tzt;
} else {
int idx = historicTransitions.size() - 1;
tzt = historicTransitions.get(idx);
tt = tzt.getTime();
if (inclusive && tt == base) {
result = tzt;
} else if (tt <= base) {
if (finalRules != null) {
// Find a transion time with finalRules
Date start0 = finalRules[0].getNextStart(base,
finalRules[1].getRawOffset(), finalRules[1].getDSTSavings(), inclusive);
Date start1 = finalRules[1].getNextStart(base,
finalRules[0].getRawOffset(), finalRules[0].getDSTSavings(), inclusive);
if (start1.after(start0)) {
tzt = new TimeZoneTransition(start0.getTime(), finalRules[1], finalRules[0]);
} else {
tzt = new TimeZoneTransition(start1.getTime(), finalRules[0], finalRules[1]);
}
result = tzt;
isFinal = true;
} else {
return null;
}
} else {
// Find a transition within the historic transitions
idx--;
TimeZoneTransition prev = tzt;
while (idx > 0) {
tzt = historicTransitions.get(idx);
tt = tzt.getTime();
if (tt < base || (!inclusive && tt == base)) {
break;
}
idx--;
prev = tzt;
}
result = prev;
}
}
// For now, this implementation ignore transitions with only zone name changes.
TimeZoneRule from = result.getFrom();
TimeZoneRule to = result.getTo();
if (from.getRawOffset() == to.getRawOffset()
&& from.getDSTSavings() == to.getDSTSavings()) {
// No offset changes. Try next one if not final
if (isFinal) {
return null;
} else {
result = getNextTransition(result.getTime(), false /* always exclusive */);
}
}
return result;
} } | public class class_name {
@Override
public TimeZoneTransition getNextTransition(long base, boolean inclusive) {
complete();
if (historicTransitions == null) {
return null; // depends on control dependency: [if], data = [none]
}
boolean isFinal = false;
TimeZoneTransition result;
TimeZoneTransition tzt = historicTransitions.get(0);
long tt = tzt.getTime();
if (tt > base || (inclusive && tt == base)) {
result = tzt; // depends on control dependency: [if], data = [none]
} else {
int idx = historicTransitions.size() - 1;
tzt = historicTransitions.get(idx); // depends on control dependency: [if], data = [none]
tt = tzt.getTime(); // depends on control dependency: [if], data = [none]
if (inclusive && tt == base) {
result = tzt; // depends on control dependency: [if], data = [none]
} else if (tt <= base) {
if (finalRules != null) {
// Find a transion time with finalRules
Date start0 = finalRules[0].getNextStart(base,
finalRules[1].getRawOffset(), finalRules[1].getDSTSavings(), inclusive);
Date start1 = finalRules[1].getNextStart(base,
finalRules[0].getRawOffset(), finalRules[0].getDSTSavings(), inclusive);
if (start1.after(start0)) {
tzt = new TimeZoneTransition(start0.getTime(), finalRules[1], finalRules[0]); // depends on control dependency: [if], data = [none]
} else {
tzt = new TimeZoneTransition(start1.getTime(), finalRules[0], finalRules[1]); // depends on control dependency: [if], data = [none]
}
result = tzt; // depends on control dependency: [if], data = [none]
isFinal = true; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} else {
// Find a transition within the historic transitions
idx--; // depends on control dependency: [if], data = [none]
TimeZoneTransition prev = tzt;
while (idx > 0) {
tzt = historicTransitions.get(idx); // depends on control dependency: [while], data = [(idx]
tt = tzt.getTime(); // depends on control dependency: [while], data = [none]
if (tt < base || (!inclusive && tt == base)) {
break;
}
idx--; // depends on control dependency: [while], data = [none]
prev = tzt; // depends on control dependency: [while], data = [none]
}
result = prev; // depends on control dependency: [if], data = [none]
}
}
// For now, this implementation ignore transitions with only zone name changes.
TimeZoneRule from = result.getFrom();
TimeZoneRule to = result.getTo();
if (from.getRawOffset() == to.getRawOffset()
&& from.getDSTSavings() == to.getDSTSavings()) {
// No offset changes. Try next one if not final
if (isFinal) {
return null; // depends on control dependency: [if], data = [none]
} else {
result = getNextTransition(result.getTime(), false /* always exclusive */); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public DrawerBuilder addStickyDrawerItems(@NonNull IDrawerItem... stickyDrawerItems) {
if (this.mStickyDrawerItems == null) {
this.mStickyDrawerItems = new ArrayList<>();
}
Collections.addAll(this.mStickyDrawerItems, stickyDrawerItems);
return this;
} } | public class class_name {
public DrawerBuilder addStickyDrawerItems(@NonNull IDrawerItem... stickyDrawerItems) {
if (this.mStickyDrawerItems == null) {
this.mStickyDrawerItems = new ArrayList<>(); // depends on control dependency: [if], data = [none]
}
Collections.addAll(this.mStickyDrawerItems, stickyDrawerItems);
return this;
} } |
public class class_name {
@GwtIncompatible // NavigableSet
public static <E> NavigableSet<E> unmodifiableNavigableSet(NavigableSet<E> set) {
if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) {
return set;
}
return new UnmodifiableNavigableSet<E>(set);
} } | public class class_name {
@GwtIncompatible // NavigableSet
public static <E> NavigableSet<E> unmodifiableNavigableSet(NavigableSet<E> set) {
if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) {
return set; // depends on control dependency: [if], data = [none]
}
return new UnmodifiableNavigableSet<E>(set);
} } |
public class class_name {
public GroupMember getMemberFor(String commandId) {
for (Iterator it = members.iterator(); it.hasNext();) {
GroupMember member = (GroupMember)it.next();
if (member.managesCommand(commandId)) {
return member;
}
}
return null;
} } | public class class_name {
public GroupMember getMemberFor(String commandId) {
for (Iterator it = members.iterator(); it.hasNext();) {
GroupMember member = (GroupMember)it.next();
if (member.managesCommand(commandId)) {
return member; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public CachedMethods withItems(Method... items) {
com.amazonaws.internal.SdkInternalList<String> itemsCopy = new com.amazonaws.internal.SdkInternalList<String>(items.length);
for (Method value : items) {
itemsCopy.add(value.toString());
}
if (getItems() == null) {
setItems(itemsCopy);
} else {
getItems().addAll(itemsCopy);
}
return this;
} } | public class class_name {
public CachedMethods withItems(Method... items) {
com.amazonaws.internal.SdkInternalList<String> itemsCopy = new com.amazonaws.internal.SdkInternalList<String>(items.length);
for (Method value : items) {
itemsCopy.add(value.toString()); // depends on control dependency: [for], data = [value]
}
if (getItems() == null) {
setItems(itemsCopy); // depends on control dependency: [if], data = [none]
} else {
getItems().addAll(itemsCopy); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public static Set<XMethod> resolveMethodCallTargets(ReferenceType receiverType, InvokeInstruction invokeInstruction,
ConstantPoolGen cpg, boolean receiverTypeIsExact) throws ClassNotFoundException {
if (invokeInstruction.getOpcode() == Const.INVOKESTATIC) {
throw new IllegalArgumentException();
}
String methodName = invokeInstruction.getName(cpg);
String methodSig = invokeInstruction.getSignature(cpg);
// Array method calls aren't virtual.
// They should just resolve to Object methods.
if (receiverType instanceof ArrayType) {
try {
return Util.emptyOrNonnullSingleton(getXClass(objectDescriptor).findMethod(methodName, methodSig, false));
} catch (CheckedAnalysisException e) {
return Collections.<XMethod> emptySet();
}
}
if (receiverType instanceof ObjectType) {
// Get the receiver class.
String receiverClassName = ((ObjectType) receiverType).getClassName();
return resolveVirtualMethodCallTargets(receiverClassName, methodName, methodSig, receiverTypeIsExact,
invokeInstruction instanceof INVOKESPECIAL);
}
assert receiverType instanceof NullType;
return Collections.<XMethod> emptySet();
} } | public class class_name {
public static Set<XMethod> resolveMethodCallTargets(ReferenceType receiverType, InvokeInstruction invokeInstruction,
ConstantPoolGen cpg, boolean receiverTypeIsExact) throws ClassNotFoundException {
if (invokeInstruction.getOpcode() == Const.INVOKESTATIC) {
throw new IllegalArgumentException();
}
String methodName = invokeInstruction.getName(cpg);
String methodSig = invokeInstruction.getSignature(cpg);
// Array method calls aren't virtual.
// They should just resolve to Object methods.
if (receiverType instanceof ArrayType) {
try {
return Util.emptyOrNonnullSingleton(getXClass(objectDescriptor).findMethod(methodName, methodSig, false)); // depends on control dependency: [try], data = [none]
} catch (CheckedAnalysisException e) {
return Collections.<XMethod> emptySet();
} // depends on control dependency: [catch], data = [none]
}
if (receiverType instanceof ObjectType) {
// Get the receiver class.
String receiverClassName = ((ObjectType) receiverType).getClassName();
return resolveVirtualMethodCallTargets(receiverClassName, methodName, methodSig, receiverTypeIsExact,
invokeInstruction instanceof INVOKESPECIAL);
}
assert receiverType instanceof NullType;
return Collections.<XMethod> emptySet();
} } |
public class class_name {
public String toPlainString() {
if(scale==0) {
if(intCompact!=INFLATED) {
return Long.toString(intCompact);
} else {
return intVal.toString();
}
}
if(this.scale<0) { // No decimal point
if(signum()==0) {
return "0";
}
int tailingZeros = checkScaleNonZero((-(long)scale));
StringBuilder buf;
if(intCompact!=INFLATED) {
buf = new StringBuilder(20+tailingZeros);
buf.append(intCompact);
} else {
String str = intVal.toString();
buf = new StringBuilder(str.length()+tailingZeros);
buf.append(str);
}
for (int i = 0; i < tailingZeros; i++)
buf.append('0');
return buf.toString();
}
String str ;
if(intCompact!=INFLATED) {
str = Long.toString(Math.abs(intCompact));
} else {
str = intVal.abs().toString();
}
return getValueString(signum(), str, scale);
} } | public class class_name {
public String toPlainString() {
if(scale==0) {
if(intCompact!=INFLATED) {
return Long.toString(intCompact); // depends on control dependency: [if], data = [(intCompact]
} else {
return intVal.toString(); // depends on control dependency: [if], data = [none]
}
}
if(this.scale<0) { // No decimal point
if(signum()==0) {
return "0"; // depends on control dependency: [if], data = [none]
}
int tailingZeros = checkScaleNonZero((-(long)scale));
StringBuilder buf;
if(intCompact!=INFLATED) {
buf = new StringBuilder(20+tailingZeros); // depends on control dependency: [if], data = [none]
buf.append(intCompact); // depends on control dependency: [if], data = [(intCompact]
} else {
String str = intVal.toString();
buf = new StringBuilder(str.length()+tailingZeros); // depends on control dependency: [if], data = [none]
buf.append(str); // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < tailingZeros; i++)
buf.append('0');
return buf.toString(); // depends on control dependency: [if], data = [none]
}
String str ;
if(intCompact!=INFLATED) {
str = Long.toString(Math.abs(intCompact)); // depends on control dependency: [if], data = [(intCompact]
} else {
str = intVal.abs().toString(); // depends on control dependency: [if], data = [none]
}
return getValueString(signum(), str, scale);
} } |
public class class_name {
public RandomVariableInterface[] getInitialValue() {
RandomVariableInterface[] initialState = getInitialState();
RandomVariableInterface[] value = new RandomVariableInterface[initialState.length];
for(int i= 0; i<value.length; i++) {
value[i] = applyStateSpaceTransform(i,initialState[i]);
}
return value;
} } | public class class_name {
public RandomVariableInterface[] getInitialValue() {
RandomVariableInterface[] initialState = getInitialState();
RandomVariableInterface[] value = new RandomVariableInterface[initialState.length];
for(int i= 0; i<value.length; i++) {
value[i] = applyStateSpaceTransform(i,initialState[i]); // depends on control dependency: [for], data = [i]
}
return value;
} } |
public class class_name {
public static Resource getFileResource(String filePath) {
String path;
if (filePath.contains(FILE_PATH_CHARSET_PARAMETER)) {
path = filePath.substring(0, filePath.indexOf(FileUtils.FILE_PATH_CHARSET_PARAMETER));
} else {
path = filePath;
}
if (path.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
return new FileSystemResource(path.substring(ResourceUtils.FILE_URL_PREFIX.length() - 1));
} else if (path.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
return new PathMatchingResourcePatternResolver().getResource(path);
}
Resource file = new FileSystemResource(path);
if (!file.exists()) {
return new PathMatchingResourcePatternResolver().getResource(path);
}
return file;
} } | public class class_name {
public static Resource getFileResource(String filePath) {
String path;
if (filePath.contains(FILE_PATH_CHARSET_PARAMETER)) {
path = filePath.substring(0, filePath.indexOf(FileUtils.FILE_PATH_CHARSET_PARAMETER)); // depends on control dependency: [if], data = [none]
} else {
path = filePath; // depends on control dependency: [if], data = [none]
}
if (path.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
return new FileSystemResource(path.substring(ResourceUtils.FILE_URL_PREFIX.length() - 1)); // depends on control dependency: [if], data = [none]
} else if (path.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
return new PathMatchingResourcePatternResolver().getResource(path); // depends on control dependency: [if], data = [none]
}
Resource file = new FileSystemResource(path);
if (!file.exists()) {
return new PathMatchingResourcePatternResolver().getResource(path); // depends on control dependency: [if], data = [none]
}
return file;
} } |
public class class_name {
public static String getArtefactDirectory(String path) {
if (path != null) {
final Matcher matcher = RESOURCE_PATH_PATTERN.matcher(path);
if (matcher.find()) {
return matcher.group(1);
}
}
return null;
} } | public class class_name {
public static String getArtefactDirectory(String path) {
if (path != null) {
final Matcher matcher = RESOURCE_PATH_PATTERN.matcher(path);
if (matcher.find()) {
return matcher.group(1); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public int compareTo(Object obj) {
if (obj == this) return 0;
if (obj == null) throw new NullPointerException();
if (obj.getClass() == this.getClass()) {
return ((CongestionControlNotification) obj).localAddress.compareTo(this.localAddress);
}
else {
return -1;
}
} } | public class class_name {
public int compareTo(Object obj) {
if (obj == this) return 0;
if (obj == null) throw new NullPointerException();
if (obj.getClass() == this.getClass()) {
return ((CongestionControlNotification) obj).localAddress.compareTo(this.localAddress); // depends on control dependency: [if], data = [none]
}
else {
return -1; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void register(final MBeanServer mbs, final Object obj)
{
final ObjectName mBeanName = JmxUtils.getObjectName(obj.getClass());
try
{
mbs.registerMBean(obj, mBeanName);
}
catch (final InstanceAlreadyExistsException e)
{
LOG.error("Could not start JMX", e);
}
catch (final MBeanRegistrationException e)
{
LOG.error("Could not register", e);
}
catch (final NotCompliantMBeanException e)
{
LOG.error("MBean error", e);
}
} } | public class class_name {
public static void register(final MBeanServer mbs, final Object obj)
{
final ObjectName mBeanName = JmxUtils.getObjectName(obj.getClass());
try
{
mbs.registerMBean(obj, mBeanName); // depends on control dependency: [try], data = [none]
}
catch (final InstanceAlreadyExistsException e)
{
LOG.error("Could not start JMX", e);
} // depends on control dependency: [catch], data = [none]
catch (final MBeanRegistrationException e)
{
LOG.error("Could not register", e);
} // depends on control dependency: [catch], data = [none]
catch (final NotCompliantMBeanException e)
{
LOG.error("MBean error", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static Optional<StopEvent> createStopEvent(Identification source) {
try {
StopEvent stopRequest = new StopEvent(source);
return Optional.of(stopRequest);
} catch (IllegalArgumentException e) {
return Optional.empty();
}
} } | public class class_name {
public static Optional<StopEvent> createStopEvent(Identification source) {
try {
StopEvent stopRequest = new StopEvent(source);
return Optional.of(stopRequest); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
return Optional.empty();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public int getHeight() {
int levels = 0;
N node = getRoot();
while(!node.isLeaf()) {
if(node.getNumEntries() > 0) {
node = getNode(node.getEntry(0));
levels++;
}
}
return levels;
} } | public class class_name {
public int getHeight() {
int levels = 0;
N node = getRoot();
while(!node.isLeaf()) {
if(node.getNumEntries() > 0) {
node = getNode(node.getEntry(0)); // depends on control dependency: [if], data = [0)]
levels++; // depends on control dependency: [if], data = [none]
}
}
return levels;
} } |
public class class_name {
public void updateStreams (float time)
{
// iterate backwards through the list so that streams can dispose of themselves during
// their update
for (int ii = _streams.size() - 1; ii >= 0; ii--) {
_streams.get(ii).update(time);
}
// delete any finalized objects
deleteFinalizedObjects();
} } | public class class_name {
public void updateStreams (float time)
{
// iterate backwards through the list so that streams can dispose of themselves during
// their update
for (int ii = _streams.size() - 1; ii >= 0; ii--) {
_streams.get(ii).update(time); // depends on control dependency: [for], data = [ii]
}
// delete any finalized objects
deleteFinalizedObjects();
} } |
public class class_name {
public double getRewardTotal() {
double rewards = 0.0;
for (Map.Entry<Integer, Float> entry : this.map.entrySet()) {
rewards += entry.getValue();
}
return rewards;
} } | public class class_name {
public double getRewardTotal() {
double rewards = 0.0;
for (Map.Entry<Integer, Float> entry : this.map.entrySet()) {
rewards += entry.getValue(); // depends on control dependency: [for], data = [entry]
}
return rewards;
} } |
public class class_name {
protected byte[] getGetProcessingOptions(final byte[] pPdol) throws CommunicationException {
// List Tag and length from PDOL
List<TagAndLength> list = TlvUtil.parseTagAndLength(pPdol);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(EmvTags.COMMAND_TEMPLATE.getTagBytes()); // COMMAND
// TEMPLATE
out.write(TlvUtil.getLength(list)); // ADD total length
if (list != null) {
for (TagAndLength tl : list) {
out.write(template.get().getTerminal().constructValue(tl));
}
}
} catch (IOException ioe) {
LOGGER.error("Construct GPO Command:" + ioe.getMessage(), ioe);
}
return template.get().getProvider().transceive(new CommandApdu(CommandEnum.GPO, out.toByteArray(), 0).toBytes());
} } | public class class_name {
protected byte[] getGetProcessingOptions(final byte[] pPdol) throws CommunicationException {
// List Tag and length from PDOL
List<TagAndLength> list = TlvUtil.parseTagAndLength(pPdol);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(EmvTags.COMMAND_TEMPLATE.getTagBytes()); // COMMAND
// TEMPLATE
out.write(TlvUtil.getLength(list)); // ADD total length
if (list != null) {
for (TagAndLength tl : list) {
out.write(template.get().getTerminal().constructValue(tl)); // depends on control dependency: [for], data = [tl]
}
}
} catch (IOException ioe) {
LOGGER.error("Construct GPO Command:" + ioe.getMessage(), ioe);
}
return template.get().getProvider().transceive(new CommandApdu(CommandEnum.GPO, out.toByteArray(), 0).toBytes());
} } |
public class class_name {
public VirtualFlowHit<C> hit(double x, double y) {
double bOff = orientation.getX(x, y);
double lOff = orientation.getY(x, y);
bOff += breadthOffset0.getValue();
if(items.isEmpty()) {
return orientation.hitAfterCells(bOff, lOff);
}
layout();
int firstVisible = getFirstVisibleIndex();
firstVisible = navigator.fillBackwardFrom0(firstVisible, lOff);
C firstCell = cellPositioner.getVisibleCell(firstVisible);
int lastVisible = getLastVisibleIndex();
lastVisible = navigator.fillForwardFrom0(lastVisible, lOff);
C lastCell = cellPositioner.getVisibleCell(lastVisible);
if(lOff < orientation.minY(firstCell)) {
return orientation.hitBeforeCells(bOff, lOff - orientation.minY(firstCell));
} else if(lOff >= orientation.maxY(lastCell)) {
return orientation.hitAfterCells(bOff, lOff - orientation.maxY(lastCell));
} else {
for(int i = firstVisible; i <= lastVisible; ++i) {
C cell = cellPositioner.getVisibleCell(i);
if(lOff < orientation.maxY(cell)) {
return orientation.cellHit(i, cell, bOff, lOff - orientation.minY(cell));
}
}
throw new AssertionError("unreachable code");
}
} } | public class class_name {
public VirtualFlowHit<C> hit(double x, double y) {
double bOff = orientation.getX(x, y);
double lOff = orientation.getY(x, y);
bOff += breadthOffset0.getValue();
if(items.isEmpty()) {
return orientation.hitAfterCells(bOff, lOff); // depends on control dependency: [if], data = [none]
}
layout();
int firstVisible = getFirstVisibleIndex();
firstVisible = navigator.fillBackwardFrom0(firstVisible, lOff);
C firstCell = cellPositioner.getVisibleCell(firstVisible);
int lastVisible = getLastVisibleIndex();
lastVisible = navigator.fillForwardFrom0(lastVisible, lOff);
C lastCell = cellPositioner.getVisibleCell(lastVisible);
if(lOff < orientation.minY(firstCell)) {
return orientation.hitBeforeCells(bOff, lOff - orientation.minY(firstCell)); // depends on control dependency: [if], data = [orientation.minY(firstCell))]
} else if(lOff >= orientation.maxY(lastCell)) {
return orientation.hitAfterCells(bOff, lOff - orientation.maxY(lastCell)); // depends on control dependency: [if], data = [none]
} else {
for(int i = firstVisible; i <= lastVisible; ++i) {
C cell = cellPositioner.getVisibleCell(i);
if(lOff < orientation.maxY(cell)) {
return orientation.cellHit(i, cell, bOff, lOff - orientation.minY(cell)); // depends on control dependency: [if], data = [none]
}
}
throw new AssertionError("unreachable code");
}
} } |
public class class_name {
public void setUserGroup(String userGroup) {
CmsGroup group = checkGroup(userGroup);
if (group != null) {
m_project.setGroupId(group.getId());
}
} } | public class class_name {
public void setUserGroup(String userGroup) {
CmsGroup group = checkGroup(userGroup);
if (group != null) {
m_project.setGroupId(group.getId()); // depends on control dependency: [if], data = [(group]
}
} } |
public class class_name {
private int getByteLength(final Object val) {
if (val == null) {
return 0;
}
String str = val.toString();
try {
return str.getBytes(System.getProperty("file.encoding")).length;
} catch (UnsupportedEncodingException ex) {
return 1;
}
} } | public class class_name {
private int getByteLength(final Object val) {
if (val == null) {
return 0; // depends on control dependency: [if], data = [none]
}
String str = val.toString();
try {
return str.getBytes(System.getProperty("file.encoding")).length;
} catch (UnsupportedEncodingException ex) {
return 1;
}
} } |
public class class_name {
public void marshall(CreateThreatIntelSetRequest createThreatIntelSetRequest, ProtocolMarshaller protocolMarshaller) {
if (createThreatIntelSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createThreatIntelSetRequest.getActivate(), ACTIVATE_BINDING);
protocolMarshaller.marshall(createThreatIntelSetRequest.getClientToken(), CLIENTTOKEN_BINDING);
protocolMarshaller.marshall(createThreatIntelSetRequest.getDetectorId(), DETECTORID_BINDING);
protocolMarshaller.marshall(createThreatIntelSetRequest.getFormat(), FORMAT_BINDING);
protocolMarshaller.marshall(createThreatIntelSetRequest.getLocation(), LOCATION_BINDING);
protocolMarshaller.marshall(createThreatIntelSetRequest.getName(), NAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateThreatIntelSetRequest createThreatIntelSetRequest, ProtocolMarshaller protocolMarshaller) {
if (createThreatIntelSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createThreatIntelSetRequest.getActivate(), ACTIVATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createThreatIntelSetRequest.getClientToken(), CLIENTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createThreatIntelSetRequest.getDetectorId(), DETECTORID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createThreatIntelSetRequest.getFormat(), FORMAT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createThreatIntelSetRequest.getLocation(), LOCATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createThreatIntelSetRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void run() {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "run : async method " + methodInfos[ivMethodId].getMethodName() + " : " + this);
// F743-22763
// Add this methods wait time to the PMI statistics and decrement
// the queue size if PMI is enabled and startTime was successfully set.
if ((ivPmiBean != null) && (ivStartTime > 0)) {
ivPmiBean.finalTime(EJBPMICollaborator.ASYNC_WAIT_TIME, ivStartTime);
ivPmiBean.asyncQueSizeDecrement();
}
// Result from the async method call
Future<?> theResult = null;
EJBMethodInfoImpl methodInfo = methodInfos[ivMethodId];
Method theMethod = methodInfo.ivMethod;
EJSDeployedSupport s = new EJSDeployedSupport();
// Provide the server result to the method context to support
// EJBContext.wasCancelled().
s.ivAsyncResult = ivServerFuture;
boolean isVoidReturnType = (theMethod.getReturnType() == Void.TYPE); // F743-22763
// F743761.CodRv - Void methods do not throw application exceptions.
s.ivIgnoreApplicationExceptions = isVoidReturnType;
AbstractEJBRuntime rt = (AbstractEJBRuntime) super.container.getEJBRuntime();
// If the server is stopping, don't invoke the async method
if (rt.isStopping()) {
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Async method " + methodInfo.getBeanClassName() + "." + methodInfo.getMethodName() + " will not be invoked because server is stopping");
} else {
try {
try {
Object theBean = container.EjbPreInvoke(this, ivMethodId, s, ivArgs);
// If preInvoke did not have an exception, continue on and invoke the
// bean's method, using the reflection object or via interceptors.
// F743-24429
if (methodInfo.getAroundInterceptorProxies() == null) {
try {
theResult = (Future<?>) theMethod.invoke(theBean, ivArgs); // d650178
} catch (InvocationTargetException ite) {
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Caught InvocationTargetException, unwrapping : " + ite);
throw ite.getCause(); // PI13514
}
} else {
theResult = (Future<?>) container.invoke(s, (Timer) null); // d650178
}
// Note: results are not set in the server result future yet,
// as there may still be an exception during postInvoke.
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Async method completed successfully");
} catch (Throwable ex) {
// For void methods, metadata validation has already ensured that
// the throws clause is empty, so declared will always be false.
boolean declared = isApplicationException(ex, methodInfo); // d660332
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Caught Throwable (declared=" + declared + "): " + ex);
// Update deployed support so postInvoke will handle the exception.
if (declared) {
// F743-761 - Simulate synchronous wrappers by calling
// setCheckedException for exceptions on the throws clause.
s.setCheckedException((Exception) ex);
throw ex;
}
// For void methods, ivIgnoreApplicationExceptions is true, so
// setUncheckedLocalException will always log this exception and
// then throw EJBException.
s.setUncheckedLocalException(ex);
} finally {
try {
container.postInvoke(this, ivMethodId, s);
} catch (RemoteException re) {
// This should never occur, but must be caught, since
// RemoteException is on the throws clause of postInvoke.
FFDCFilter.processException(re, CLASS_NAME + ".run", "242", this);
s.setUncheckedLocalException(re);
}
}
} catch (Throwable ex) {
// Unchecked Exceptions will have already been logged with FFDC
// above, no need to repeat that here.
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Async method completed with exception : " + ex);
// If there is a server-side future object set the exception there
// too. FireAndForget async methods will not have a server-side
// future object so the exception cannot be reported.
if (ivServerFuture != null) {
// This wrapper class has to act like a stub class. In the remote
// code path, the container has already mapped RemoteException to
// SystemException for it to be sent to the ORB
// (OrbUtilsImpl.mapException). Since the resulting exception will
// never go through the ORB directly (we're catching it here, and
// RemoteAsyncResultImpl will wrap it in ExecutionException), we
// need to do the reverse operation and map from SystemException
// back to RemoteException just like a generated stub would do.
ex = mapSystemExceptionBackToRemoteException(ex);
ivServerFuture.setException(ex);
}
// F743-22763
// For fire and forget methods, if PMI statistics are being collected
// increment the number of fire and forget methods failed counter
if ((ivPmiBean != null) && isVoidReturnType) {
ivPmiBean.asyncFNFFailed();
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "run : " + ex);
return;
}
}
// If a server-side future object is present, the async method is
// supposed to return results. Otherwise, it is a "fire-and-forget"
// type method, where no results are returned. Note: null is a
// valid method result so we can't use a result == null check here
// to identify a "fire-and-forget" type method.
if (ivServerFuture != null) {
ivServerFuture.setResult(theResult);
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "run");
} } | public class class_name {
@Override
public void run() {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "run : async method " + methodInfos[ivMethodId].getMethodName() + " : " + this);
// F743-22763
// Add this methods wait time to the PMI statistics and decrement
// the queue size if PMI is enabled and startTime was successfully set.
if ((ivPmiBean != null) && (ivStartTime > 0)) {
ivPmiBean.finalTime(EJBPMICollaborator.ASYNC_WAIT_TIME, ivStartTime); // depends on control dependency: [if], data = [none]
ivPmiBean.asyncQueSizeDecrement(); // depends on control dependency: [if], data = [none]
}
// Result from the async method call
Future<?> theResult = null;
EJBMethodInfoImpl methodInfo = methodInfos[ivMethodId];
Method theMethod = methodInfo.ivMethod;
EJSDeployedSupport s = new EJSDeployedSupport();
// Provide the server result to the method context to support
// EJBContext.wasCancelled().
s.ivAsyncResult = ivServerFuture;
boolean isVoidReturnType = (theMethod.getReturnType() == Void.TYPE); // F743-22763
// F743761.CodRv - Void methods do not throw application exceptions.
s.ivIgnoreApplicationExceptions = isVoidReturnType;
AbstractEJBRuntime rt = (AbstractEJBRuntime) super.container.getEJBRuntime();
// If the server is stopping, don't invoke the async method
if (rt.isStopping()) {
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Async method " + methodInfo.getBeanClassName() + "." + methodInfo.getMethodName() + " will not be invoked because server is stopping");
} else {
try {
try {
Object theBean = container.EjbPreInvoke(this, ivMethodId, s, ivArgs);
// If preInvoke did not have an exception, continue on and invoke the
// bean's method, using the reflection object or via interceptors.
// F743-24429
if (methodInfo.getAroundInterceptorProxies() == null) {
try {
theResult = (Future<?>) theMethod.invoke(theBean, ivArgs); // d650178 // depends on control dependency: [try], data = [none]
} catch (InvocationTargetException ite) {
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Caught InvocationTargetException, unwrapping : " + ite);
throw ite.getCause(); // PI13514
} // depends on control dependency: [catch], data = [none]
} else {
theResult = (Future<?>) container.invoke(s, (Timer) null); // d650178 // depends on control dependency: [if], data = [null)]
}
// Note: results are not set in the server result future yet,
// as there may still be an exception during postInvoke.
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Async method completed successfully");
} catch (Throwable ex) {
// For void methods, metadata validation has already ensured that
// the throws clause is empty, so declared will always be false.
boolean declared = isApplicationException(ex, methodInfo); // d660332
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Caught Throwable (declared=" + declared + "): " + ex);
// Update deployed support so postInvoke will handle the exception.
if (declared) {
// F743-761 - Simulate synchronous wrappers by calling
// setCheckedException for exceptions on the throws clause.
s.setCheckedException((Exception) ex); // depends on control dependency: [if], data = [none]
throw ex;
}
// For void methods, ivIgnoreApplicationExceptions is true, so
// setUncheckedLocalException will always log this exception and
// then throw EJBException.
s.setUncheckedLocalException(ex);
} finally { // depends on control dependency: [catch], data = [none]
try {
container.postInvoke(this, ivMethodId, s); // depends on control dependency: [try], data = [none]
} catch (RemoteException re) {
// This should never occur, but must be caught, since
// RemoteException is on the throws clause of postInvoke.
FFDCFilter.processException(re, CLASS_NAME + ".run", "242", this);
s.setUncheckedLocalException(re);
} // depends on control dependency: [catch], data = [none]
}
} catch (Throwable ex) {
// Unchecked Exceptions will have already been logged with FFDC
// above, no need to repeat that here.
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Async method completed with exception : " + ex);
// If there is a server-side future object set the exception there
// too. FireAndForget async methods will not have a server-side
// future object so the exception cannot be reported.
if (ivServerFuture != null) {
// This wrapper class has to act like a stub class. In the remote
// code path, the container has already mapped RemoteException to
// SystemException for it to be sent to the ORB
// (OrbUtilsImpl.mapException). Since the resulting exception will
// never go through the ORB directly (we're catching it here, and
// RemoteAsyncResultImpl will wrap it in ExecutionException), we
// need to do the reverse operation and map from SystemException
// back to RemoteException just like a generated stub would do.
ex = mapSystemExceptionBackToRemoteException(ex); // depends on control dependency: [if], data = [none]
ivServerFuture.setException(ex); // depends on control dependency: [if], data = [none]
}
// F743-22763
// For fire and forget methods, if PMI statistics are being collected
// increment the number of fire and forget methods failed counter
if ((ivPmiBean != null) && isVoidReturnType) {
ivPmiBean.asyncFNFFailed(); // depends on control dependency: [if], data = [none]
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "run : " + ex);
return;
} // depends on control dependency: [catch], data = [none]
}
// If a server-side future object is present, the async method is
// supposed to return results. Otherwise, it is a "fire-and-forget"
// type method, where no results are returned. Note: null is a
// valid method result so we can't use a result == null check here
// to identify a "fire-and-forget" type method.
if (ivServerFuture != null) {
ivServerFuture.setResult(theResult); // depends on control dependency: [if], data = [none]
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "run");
} } |
public class class_name {
public static Optional<SaltVersion> parse(String versionString) {
Matcher matcher = SALT_VERSION_REGEX.matcher(versionString);
if (matcher.matches()) {
int year = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(2));
int bugfix = Integer.parseInt(matcher.group(3));
Optional<Integer> rc = Optional.ofNullable(matcher.group(5))
.map(Integer::parseInt);
return Optional.of(new SaltVersion(year, month, bugfix, rc));
} else {
return Optional.empty();
}
} } | public class class_name {
public static Optional<SaltVersion> parse(String versionString) {
Matcher matcher = SALT_VERSION_REGEX.matcher(versionString);
if (matcher.matches()) {
int year = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(2));
int bugfix = Integer.parseInt(matcher.group(3));
Optional<Integer> rc = Optional.ofNullable(matcher.group(5))
.map(Integer::parseInt);
return Optional.of(new SaltVersion(year, month, bugfix, rc)); // depends on control dependency: [if], data = [none]
} else {
return Optional.empty(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public DirectoryOperation copyLocalDirectory(String localdir,
String remotedir, boolean recurse, boolean sync, boolean commit,
FileTransferProgress progress) throws FileNotFoundException,
SftpStatusException, SshException, TransferCancelledException {
DirectoryOperation op = new DirectoryOperation();
// Record the previous
// String pwd = pwd();
// String lpwd = lpwd();
File local = resolveLocalPath(localdir);
remotedir = resolveRemotePath(remotedir);
remotedir += (remotedir.endsWith("/") ? "" : "/");
// Setup the remote directory if were committing
if (commit) {
try {
sftp.getAttributes(remotedir);
} catch (SftpStatusException ex) {
mkdirs(remotedir);
}
}
// List the local files and verify against the remote server
String[] ls = local.list();
File source;
if (ls != null) {
for (int i = 0; i < ls.length; i++) {
source = new File(local, ls[i]);
if (source.isDirectory() && !source.getName().equals(".")
&& !source.getName().equals("..")) {
if (recurse) {
// File f = new File(local, source.getName());
op.addDirectoryOperation(
copyLocalDirectory(source.getAbsolutePath(),
remotedir + source.getName(), recurse,
sync, commit, progress), source);
}
} else if (source.isFile()) {
boolean newFile = false;
boolean unchangedFile = false;
try {
SftpFileAttributes attrs = sftp.getAttributes(remotedir
+ source.getName());
unchangedFile = ((source.length() == attrs.getSize()
.longValue()) && ((source.lastModified() / 1000) == attrs
.getModifiedTime().longValue()));
} catch (SftpStatusException ex) {
newFile = true;
}
try {
if (commit && !unchangedFile) { // BPS - Added
// !unChangedFile test.
// Why would want to
// copy that has been
// determined to be
// unchanged?
put(source.getAbsolutePath(),
remotedir + source.getName(), progress);
SftpFileAttributes attrs = sftp
.getAttributes(remotedir + source.getName());
attrs.setTimes(
new UnsignedInteger64(
source.lastModified() / 1000),
new UnsignedInteger64(
source.lastModified() / 1000));
sftp.setAttributes(remotedir + source.getName(),
attrs);
}
if (unchangedFile) {
op.addUnchangedFile(source);
} else if (!newFile) {
op.addUpdatedFile(source);
} else {
op.addNewFile(source);
}
} catch (SftpStatusException ex) {
op.addFailedTransfer(source, ex);
}
}
}
}
if (sync) {
// List the contents of the new remote directory and remove any
// files/directories that were not updated
try {
SftpFile[] files = ls(remotedir);
SftpFile file;
File f;
for (int i = 0; i < files.length; i++) {
file = files[i];
// Create a local file object to test for its existence
f = new File(local, file.getFilename());
if (!op.containsFile(f) && !file.getFilename().equals(".")
&& !file.getFilename().equals("..")) {
op.addDeletedFile(file);
if (commit) {
if (file.isDirectory()) {
// Recurse through the directory, deleting stuff
recurseMarkForDeletion(file, op);
if (commit) {
rm(file.getAbsolutePath(), true, true);
}
} else if (file.isFile()) {
rm(file.getAbsolutePath());
}
}
}
}
} catch (SftpStatusException ex2) {
// Ignore since if it does not exist we cant delete it
}
}
// Return the operation details
return op;
} } | public class class_name {
public DirectoryOperation copyLocalDirectory(String localdir,
String remotedir, boolean recurse, boolean sync, boolean commit,
FileTransferProgress progress) throws FileNotFoundException,
SftpStatusException, SshException, TransferCancelledException {
DirectoryOperation op = new DirectoryOperation();
// Record the previous
// String pwd = pwd();
// String lpwd = lpwd();
File local = resolveLocalPath(localdir);
remotedir = resolveRemotePath(remotedir);
remotedir += (remotedir.endsWith("/") ? "" : "/");
// Setup the remote directory if were committing
if (commit) {
try {
sftp.getAttributes(remotedir); // depends on control dependency: [try], data = [none]
} catch (SftpStatusException ex) {
mkdirs(remotedir);
} // depends on control dependency: [catch], data = [none]
}
// List the local files and verify against the remote server
String[] ls = local.list();
File source;
if (ls != null) {
for (int i = 0; i < ls.length; i++) {
source = new File(local, ls[i]);
if (source.isDirectory() && !source.getName().equals(".")
&& !source.getName().equals("..")) {
if (recurse) {
// File f = new File(local, source.getName());
op.addDirectoryOperation(
copyLocalDirectory(source.getAbsolutePath(),
remotedir + source.getName(), recurse,
sync, commit, progress), source); // depends on control dependency: [if], data = [none]
}
} else if (source.isFile()) {
boolean newFile = false;
boolean unchangedFile = false;
try {
SftpFileAttributes attrs = sftp.getAttributes(remotedir
+ source.getName());
unchangedFile = ((source.length() == attrs.getSize()
.longValue()) && ((source.lastModified() / 1000) == attrs
.getModifiedTime().longValue()));
} catch (SftpStatusException ex) {
newFile = true;
}
try {
if (commit && !unchangedFile) { // BPS - Added
// !unChangedFile test.
// Why would want to
// copy that has been
// determined to be
// unchanged?
put(source.getAbsolutePath(),
remotedir + source.getName(), progress); // depends on control dependency: [if], data = [none]
SftpFileAttributes attrs = sftp
.getAttributes(remotedir + source.getName());
attrs.setTimes(
new UnsignedInteger64(
source.lastModified() / 1000),
new UnsignedInteger64(
source.lastModified() / 1000)); // depends on control dependency: [if], data = [none]
sftp.setAttributes(remotedir + source.getName(),
attrs); // depends on control dependency: [if], data = [none]
}
if (unchangedFile) {
op.addUnchangedFile(source); // depends on control dependency: [if], data = [none]
} else if (!newFile) {
op.addUpdatedFile(source); // depends on control dependency: [if], data = [none]
} else {
op.addNewFile(source); // depends on control dependency: [if], data = [none]
}
} catch (SftpStatusException ex) {
op.addFailedTransfer(source, ex);
}
}
}
}
if (sync) {
// List the contents of the new remote directory and remove any
// files/directories that were not updated
try {
SftpFile[] files = ls(remotedir);
SftpFile file;
File f;
for (int i = 0; i < files.length; i++) {
file = files[i];
// Create a local file object to test for its existence
f = new File(local, file.getFilename());
if (!op.containsFile(f) && !file.getFilename().equals(".")
&& !file.getFilename().equals("..")) {
op.addDeletedFile(file);
if (commit) {
if (file.isDirectory()) {
// Recurse through the directory, deleting stuff
recurseMarkForDeletion(file, op);
if (commit) {
rm(file.getAbsolutePath(), true, true);
}
} else if (file.isFile()) {
rm(file.getAbsolutePath());
}
}
}
}
} catch (SftpStatusException ex2) {
// Ignore since if it does not exist we cant delete it
}
}
// Return the operation details
return op;
} } |
public class class_name {
public static boolean copyFile(String srcFile, String destFile) {
boolean flag = false;
FileInputStream fin = null;
FileOutputStream fout = null;
FileChannel fcin = null;
FileChannel fcout = null;
try {
// 获取源文件和目标文件的输入输出流
fin = new FileInputStream(srcFile);
fout = new FileOutputStream(destFile);
// 获取输入输出通道
fcin = fin.getChannel();
fcout = fout.getChannel();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
// clear方法重设缓冲区,使它可以接受读入的数据
buffer.clear();
// 从输入通道中将数据读到缓冲区
int r = fcin.read(buffer);
// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
if (r == -1) {
flag = true;
break;
}
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.flip();
// 从输出通道中将数据写入缓冲区
fcout.write(buffer);
}
fout.flush();
} catch (IOException e) {
LogUtil.writeErrorLog("CopyFile fail", e);
} finally {
try {
if (null != fin)
fin.close();
if (null != fout)
fout.close();
if (null != fcin)
fcin.close();
if (null != fcout)
fcout.close();
} catch (IOException ex) {
LogUtil.writeErrorLog("Releases any system resources fail", ex);
}
}
return flag;
} } | public class class_name {
public static boolean copyFile(String srcFile, String destFile) {
boolean flag = false;
FileInputStream fin = null;
FileOutputStream fout = null;
FileChannel fcin = null;
FileChannel fcout = null;
try {
// 获取源文件和目标文件的输入输出流
fin = new FileInputStream(srcFile); // depends on control dependency: [try], data = [none]
fout = new FileOutputStream(destFile); // depends on control dependency: [try], data = [none]
// 获取输入输出通道
fcin = fin.getChannel(); // depends on control dependency: [try], data = [none]
fcout = fout.getChannel(); // depends on control dependency: [try], data = [none]
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
// clear方法重设缓冲区,使它可以接受读入的数据
buffer.clear(); // depends on control dependency: [while], data = [none]
// 从输入通道中将数据读到缓冲区
int r = fcin.read(buffer);
// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
if (r == -1) {
flag = true; // depends on control dependency: [if], data = [none]
break;
}
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.flip(); // depends on control dependency: [while], data = [none]
// 从输出通道中将数据写入缓冲区
fcout.write(buffer); // depends on control dependency: [while], data = [none]
}
fout.flush(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
LogUtil.writeErrorLog("CopyFile fail", e);
} finally { // depends on control dependency: [catch], data = [none]
try {
if (null != fin)
fin.close();
if (null != fout)
fout.close();
if (null != fcin)
fcin.close();
if (null != fcout)
fcout.close();
} catch (IOException ex) {
LogUtil.writeErrorLog("Releases any system resources fail", ex);
} // depends on control dependency: [catch], data = [none]
}
return flag;
} } |
public class class_name {
public void setResponseDescription(Element value) {
Element child = getLastChild(root, "responsedescription"); //$NON-NLS-1$
if (child != null)
root.removeChild(child);
if (value == null) {
child = setChild(root, "responsedescription", childNames, false); //$NON-NLS-1$
child.appendChild(value);
}
} } | public class class_name {
public void setResponseDescription(Element value) {
Element child = getLastChild(root, "responsedescription"); //$NON-NLS-1$
if (child != null)
root.removeChild(child);
if (value == null) {
child = setChild(root, "responsedescription", childNames, false); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
child.appendChild(value); // depends on control dependency: [if], data = [(value]
}
} } |
public class class_name {
private int parseVersion( String uri ) {
if( uri.length() <= 1 || uri.charAt(0) != '/' ) // If not a leading slash, then I am confused
return (0<<16)|LATEST_VERSION;
if( uri.startsWith("/latest") )
return (("/latest".length())<<16)|LATEST_VERSION;
int idx=1; // Skip the leading slash
int version=0;
char c = uri.charAt(idx); // Allow both /### and /v###
if( c=='v' ) c = uri.charAt(++idx);
while( idx < uri.length() && '0' <= c && c <= '9' ) {
version = version*10+(c-'0');
c = uri.charAt(++idx);
}
if( idx > 10 || version > LATEST_VERSION || version < 1 || uri.charAt(idx) != '/' )
return (0<<16)|LATEST_VERSION; // Failed number parse or baloney version
// Happy happy version
return (idx<<16)|version;
} } | public class class_name {
private int parseVersion( String uri ) {
if( uri.length() <= 1 || uri.charAt(0) != '/' ) // If not a leading slash, then I am confused
return (0<<16)|LATEST_VERSION;
if( uri.startsWith("/latest") )
return (("/latest".length())<<16)|LATEST_VERSION;
int idx=1; // Skip the leading slash
int version=0;
char c = uri.charAt(idx); // Allow both /### and /v###
if( c=='v' ) c = uri.charAt(++idx);
while( idx < uri.length() && '0' <= c && c <= '9' ) {
version = version*10+(c-'0'); // depends on control dependency: [while], data = [none]
c = uri.charAt(++idx); // depends on control dependency: [while], data = [none]
}
if( idx > 10 || version > LATEST_VERSION || version < 1 || uri.charAt(idx) != '/' )
return (0<<16)|LATEST_VERSION; // Failed number parse or baloney version
// Happy happy version
return (idx<<16)|version;
} } |
public class class_name {
public static synchronized void setTraceMemoryDestination(String location, long maxSize) {
LogRepositoryWriter old = getBinaryHandler().getTraceWriter();
LogRepositoryWriterCBuffImpl writer;
// Check if trace writer need to be changed.
if (location == null && old instanceof LogRepositoryWriterCBuffImpl) {
writer = (LogRepositoryWriterCBuffImpl) old;
} else {
// Get the repository manager to use for the dump writer.
LogRepositoryManager manager = null;
if (location == null && old != null) {
manager = old.getLogRepositoryManager();
} else if (location != null) {
if (svSuperPid != null)
manager = new LogRepositorySubManagerImpl(new File(location,
LogRepositoryManagerImpl.TRACE_LOCATION), svPid, svLabel, svSuperPid);
else
manager = new LogRepositoryManagerImpl(new File(location,
LogRepositoryManagerImpl.TRACE_LOCATION), svPid, svLabel, true);
}
if (manager == null) {
throw new IllegalArgumentException(
"Argument 'location' can't be null if log writer was not setup by this class.");
}
writer = new LogRepositoryWriterCBuffImpl(
new LogRepositoryWriterImpl(manager));
}
if (maxSize > 0) {
((LogRepositoryWriterCBuffImpl) writer).setMaxSize(maxSize);
} else {
// Stop new writer before throwing exception.
if (old != writer) {
writer.stop();
}
throw new IllegalArgumentException("Argument 'maxSize' should be more than zero");
}
// Stop old manager only after successful configuration of the new writer.
if (old != null) {
LogRepositoryManager oldManager = old.getLogRepositoryManager();
if (oldManager != null && oldManager != writer.getLogRepositoryManager()) {
// Stop old writer before stopping its manager
if (old != writer) {
old.stop();
}
oldManager.stop();
}
}
// Update writer as a last call after all data verification is done.
getBinaryHandler().setTraceWriter(writer);
} } | public class class_name {
public static synchronized void setTraceMemoryDestination(String location, long maxSize) {
LogRepositoryWriter old = getBinaryHandler().getTraceWriter();
LogRepositoryWriterCBuffImpl writer;
// Check if trace writer need to be changed.
if (location == null && old instanceof LogRepositoryWriterCBuffImpl) {
writer = (LogRepositoryWriterCBuffImpl) old; // depends on control dependency: [if], data = [none]
} else {
// Get the repository manager to use for the dump writer.
LogRepositoryManager manager = null;
if (location == null && old != null) {
manager = old.getLogRepositoryManager(); // depends on control dependency: [if], data = [none]
} else if (location != null) {
if (svSuperPid != null)
manager = new LogRepositorySubManagerImpl(new File(location,
LogRepositoryManagerImpl.TRACE_LOCATION), svPid, svLabel, svSuperPid);
else
manager = new LogRepositoryManagerImpl(new File(location,
LogRepositoryManagerImpl.TRACE_LOCATION), svPid, svLabel, true);
}
if (manager == null) {
throw new IllegalArgumentException(
"Argument 'location' can't be null if log writer was not setup by this class.");
}
writer = new LogRepositoryWriterCBuffImpl(
new LogRepositoryWriterImpl(manager)); // depends on control dependency: [if], data = [none]
}
if (maxSize > 0) {
((LogRepositoryWriterCBuffImpl) writer).setMaxSize(maxSize); // depends on control dependency: [if], data = [(maxSize]
} else {
// Stop new writer before throwing exception.
if (old != writer) {
writer.stop(); // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException("Argument 'maxSize' should be more than zero");
}
// Stop old manager only after successful configuration of the new writer.
if (old != null) {
LogRepositoryManager oldManager = old.getLogRepositoryManager();
if (oldManager != null && oldManager != writer.getLogRepositoryManager()) {
// Stop old writer before stopping its manager
if (old != writer) {
old.stop(); // depends on control dependency: [if], data = [none]
}
oldManager.stop(); // depends on control dependency: [if], data = [none]
}
}
// Update writer as a last call after all data verification is done.
getBinaryHandler().setTraceWriter(writer);
} } |
public class class_name {
@Override
public void addAppender(Appender newAppender) {
if (aai == null) {
synchronized (this) {
if (aai == null) {
aai = new NFAppenderAttachableImpl();
}
}
}
aai.addAppender(newAppender);
repository.fireAddAppenderEvent(this, newAppender);
} } | public class class_name {
@Override
public void addAppender(Appender newAppender) {
if (aai == null) {
synchronized (this) { // depends on control dependency: [if], data = [none]
if (aai == null) {
aai = new NFAppenderAttachableImpl(); // depends on control dependency: [if], data = [none]
}
}
}
aai.addAppender(newAppender);
repository.fireAddAppenderEvent(this, newAppender);
} } |
public class class_name {
public String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuilder stringBuilder = new StringBuilder(getElementType().getClassName());
for (int i = getDimensions(); i > 0; --i) {
stringBuilder.append("[]");
}
return stringBuilder.toString();
case OBJECT:
case INTERNAL:
return valueBuffer.substring(valueBegin, valueEnd).replace('/', '.');
default:
throw new AssertionError();
}
} } | public class class_name {
public String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuilder stringBuilder = new StringBuilder(getElementType().getClassName());
for (int i = getDimensions(); i > 0; --i) {
stringBuilder.append("[]"); // depends on control dependency: [for], data = [none]
}
return stringBuilder.toString();
case OBJECT:
case INTERNAL:
return valueBuffer.substring(valueBegin, valueEnd).replace('/', '.');
default:
throw new AssertionError();
}
} } |
public class class_name {
private List<String> getSchemaGeneratorSourceFiles(final List<URL> sources)
throws IOException, MojoExecutionException {
final SortedMap<String, String> className2SourcePath = new TreeMap<String, String>();
final File baseDir = getProject().getBasedir();
final File userDir = new File(System.getProperty("user.dir"));
final String encoding = getEncoding(true);
// 1) Find/add all sources available in the compilation unit.
for (URL current : sources) {
final File sourceCodeFile = FileSystemUtilities.getFileFor(current, encoding);
// Calculate the relative path for the current source
final String relativePath = FileSystemUtilities.relativize(
FileSystemUtilities.getCanonicalPath(sourceCodeFile),
userDir,
true);
if (getLog().isDebugEnabled()) {
getLog().debug("SourceCodeFile ["
+ FileSystemUtilities.getCanonicalPath(sourceCodeFile)
+ "] and userDir [" + FileSystemUtilities.getCanonicalPath(userDir)
+ "] ==> relativePath: "
+ relativePath
+ ". (baseDir: " + FileSystemUtilities.getCanonicalPath(baseDir) + "]");
}
// Find the Java class(es) within the source.
final JavaProjectBuilder builder = new JavaProjectBuilder();
builder.setEncoding(encoding);
//
// Ensure that we include package-info.java classes in the SchemaGen compilation.
//
if (sourceCodeFile.getName().trim().equalsIgnoreCase(PACKAGE_INFO_FILENAME)) {
// For some reason, QDox requires the package-info.java to be added as a URL instead of a File.
builder.addSource(current);
final Collection<JavaPackage> packages = builder.getPackages();
if (packages.size() != 1) {
throw new MojoExecutionException("Exactly one package should be present in file ["
+ sourceCodeFile.getPath() + "]");
}
// Make the key indicate that this is the package-info.java file.
final JavaPackage javaPackage = packages.iterator().next();
className2SourcePath.put("package-info for (" + javaPackage.getName() + ")", relativePath);
continue;
}
// This is not a package-info.java file, so QDox lets us add this as a File.
builder.addSource(sourceCodeFile);
// Map any found FQCN to the relativized path of its source file.
for (JavaSource currentJavaSource : builder.getSources()) {
for (JavaClass currentJavaClass : currentJavaSource.getClasses()) {
final String className = currentJavaClass.getFullyQualifiedName();
if (className2SourcePath.containsKey(className)) {
if (getLog().isWarnEnabled()) {
getLog().warn("Already mapped. Source class [" + className + "] within ["
+ className2SourcePath.get(className)
+ "]. Not overwriting with [" + relativePath + "]");
}
} else {
className2SourcePath.put(className, relativePath);
}
}
}
}
/*
// 2) Find any bytecode available in the compilation unit, and add its file as a SchemaGen argument.
//
// The algorithm is:
// 1) Add bytecode classpath unless its class is already added in source form.
// 2) SchemaGen cannot handle directory arguments, so any bytecode files in classpath directories
// must be resolved.
// 3) All JARs in the classpath should be added as arguments to SchemaGen.
//
// .... Gosh ...
//
for (URL current : getCompiledClassNames()) {
getLog().debug(" (compiled ClassName) --> " + current.toExternalForm());
}
Filters.initialize(getLog(), CLASS_INCLUDE_FILTERS);
final List<URL> classPathURLs = new ArrayList<URL>();
for (String current : getClasspath()) {
final File currentFile = new File(current);
if (FileSystemUtilities.EXISTING_FILE.accept(currentFile)) {
// This is a file/JAR. Simply add its path to SchemaGen's arguments.
classPathURLs.add(FileSystemUtilities.getUrlFor(currentFile));
} else if (FileSystemUtilities.EXISTING_DIRECTORY.accept(currentFile)) {
// Resolve all bytecode files within this directory.
// FileSystemUtilities.filterFiles(baseDir, )
if (getLog().isDebugEnabled()) {
getLog().debug("TODO: Resolve and add bytecode files within: ["
+ FileSystemUtilities.getCanonicalPath(currentFile) + "]");
}
// Find the byte code files within the current directory.
final List<File> byteCodeFiles = new ArrayList<File>();
for(File currentResolvedFile : FileSystemUtilities.resolveRecursively(
Arrays.asList(currentFile), null, getLog())) {
if(Filters.matchAtLeastOnce(currentResolvedFile, CLASS_INCLUDE_FILTERS)) {
byteCodeFiles.add(currentResolvedFile);
}
}
for(File currentByteCodeFile : byteCodeFiles) {
final String currentCanonicalPath = FileSystemUtilities.getCanonicalPath(
currentByteCodeFile.getAbsoluteFile());
final String relativized = FileSystemUtilities.relativize(currentCanonicalPath,
FileSystemUtilities.getCanonicalFile(currentFile.getAbsoluteFile()));
final String pathFromUserDir = FileSystemUtilities.relativize(currentCanonicalPath, userDir);
final String className = relativized.substring(0, relativized.indexOf(".class"))
.replace("/", ".")
.replace(File.separator, ".");
if(!className2SourcePath.containsKey(className)) {
className2SourcePath.put(className, pathFromUserDir);
if(getLog().isDebugEnabled()) {
getLog().debug("Adding ByteCode [" + className + "] at relativized path ["
+ pathFromUserDir + "]");
}
} else {
if(getLog().isDebugEnabled()) {
getLog().debug("ByteCode [" + className + "] already added. Not re-adding.");
}
}
}
} else if (getLog().isWarnEnabled()) {
final String suffix = !currentFile.exists() ? " nonexistent" : " was neither a File nor a Directory";
getLog().warn("Classpath part [" + current + "] " + suffix + ". Ignoring it.");
}
}
/*
for (URL current : getCompiledClassNames()) {
// TODO: FIX THIS!
// Get the class information data from the supplied URL
for (String currentClassPathElement : getClasspath()) {
if(getLog().isDebugEnabled()) {
getLog().debug("Checking class path element: [" + currentClassPathElement + "]");
}
}
if(getLog().isDebugEnabled()) {
getLog().debug("Processing compiledClassName: [" + current + "]");
}
// Find the Java class(es) within the source.
final JavaProjectBuilder builder = new JavaProjectBuilder();
builder.setEncoding(getEncoding(true));
builder.addSource(current);
for (JavaSource currentSource : builder.getSources()) {
for (JavaClass currentClass : currentSource.getClasses()) {
final String className = currentClass.getFullyQualifiedName();
if (className2SourcePath.containsKey(className)) {
if (getLog().isWarnEnabled()) {
getLog().warn("Already mapped. Source class [" + className + "] within ["
+ className2SourcePath.get(className)
+ "]. Not overwriting with [" + className + "]");
}
} else {
className2SourcePath.put(className, className);
}
}
}
}
*/
if (getLog().isDebugEnabled()) {
final int size = className2SourcePath.size();
getLog().debug("[ClassName-2-SourcePath Map (size: " + size + ")] ...");
int i = 0;
for (Map.Entry<String, String> current : className2SourcePath.entrySet()) {
getLog().debug(" " + (++i) + "/" + size + ": [" + current.getKey() + "]: "
+ current.getValue());
}
getLog().debug("... End [ClassName-2-SourcePath Map]");
}
// Sort the source paths and place them first in the argument array
final ArrayList<String> toReturn = new ArrayList<String>(className2SourcePath.values());
Collections.sort(toReturn);
// All Done.
return toReturn;
} } | public class class_name {
private List<String> getSchemaGeneratorSourceFiles(final List<URL> sources)
throws IOException, MojoExecutionException {
final SortedMap<String, String> className2SourcePath = new TreeMap<String, String>();
final File baseDir = getProject().getBasedir();
final File userDir = new File(System.getProperty("user.dir"));
final String encoding = getEncoding(true);
// 1) Find/add all sources available in the compilation unit.
for (URL current : sources) {
final File sourceCodeFile = FileSystemUtilities.getFileFor(current, encoding);
// Calculate the relative path for the current source
final String relativePath = FileSystemUtilities.relativize(
FileSystemUtilities.getCanonicalPath(sourceCodeFile),
userDir,
true);
if (getLog().isDebugEnabled()) {
getLog().debug("SourceCodeFile ["
+ FileSystemUtilities.getCanonicalPath(sourceCodeFile)
+ "] and userDir [" + FileSystemUtilities.getCanonicalPath(userDir)
+ "] ==> relativePath: "
+ relativePath
+ ". (baseDir: " + FileSystemUtilities.getCanonicalPath(baseDir) + "]");
}
// Find the Java class(es) within the source.
final JavaProjectBuilder builder = new JavaProjectBuilder();
builder.setEncoding(encoding);
//
// Ensure that we include package-info.java classes in the SchemaGen compilation.
//
if (sourceCodeFile.getName().trim().equalsIgnoreCase(PACKAGE_INFO_FILENAME)) {
// For some reason, QDox requires the package-info.java to be added as a URL instead of a File.
builder.addSource(current);
final Collection<JavaPackage> packages = builder.getPackages();
if (packages.size() != 1) {
throw new MojoExecutionException("Exactly one package should be present in file ["
+ sourceCodeFile.getPath() + "]");
}
// Make the key indicate that this is the package-info.java file.
final JavaPackage javaPackage = packages.iterator().next();
className2SourcePath.put("package-info for (" + javaPackage.getName() + ")", relativePath);
continue;
}
// This is not a package-info.java file, so QDox lets us add this as a File.
builder.addSource(sourceCodeFile);
// Map any found FQCN to the relativized path of its source file.
for (JavaSource currentJavaSource : builder.getSources()) {
for (JavaClass currentJavaClass : currentJavaSource.getClasses()) {
final String className = currentJavaClass.getFullyQualifiedName();
if (className2SourcePath.containsKey(className)) {
if (getLog().isWarnEnabled()) {
getLog().warn("Already mapped. Source class [" + className + "] within ["
+ className2SourcePath.get(className)
+ "]. Not overwriting with [" + relativePath + "]");
}
} else {
className2SourcePath.put(className, relativePath);
}
}
}
}
/*
// 2) Find any bytecode available in the compilation unit, and add its file as a SchemaGen argument.
//
// The algorithm is:
// 1) Add bytecode classpath unless its class is already added in source form.
// 2) SchemaGen cannot handle directory arguments, so any bytecode files in classpath directories
// must be resolved.
// 3) All JARs in the classpath should be added as arguments to SchemaGen.
//
// .... Gosh ...
//
for (URL current : getCompiledClassNames()) {
getLog().debug(" (compiled ClassName) --> " + current.toExternalForm());
}
Filters.initialize(getLog(), CLASS_INCLUDE_FILTERS);
final List<URL> classPathURLs = new ArrayList<URL>();
for (String current : getClasspath()) {
final File currentFile = new File(current);
if (FileSystemUtilities.EXISTING_FILE.accept(currentFile)) {
// This is a file/JAR. Simply add its path to SchemaGen's arguments.
classPathURLs.add(FileSystemUtilities.getUrlFor(currentFile));
} else if (FileSystemUtilities.EXISTING_DIRECTORY.accept(currentFile)) {
// Resolve all bytecode files within this directory.
// FileSystemUtilities.filterFiles(baseDir, )
if (getLog().isDebugEnabled()) {
getLog().debug("TODO: Resolve and add bytecode files within: ["
+ FileSystemUtilities.getCanonicalPath(currentFile) + "]");
}
// Find the byte code files within the current directory.
final List<File> byteCodeFiles = new ArrayList<File>();
for(File currentResolvedFile : FileSystemUtilities.resolveRecursively(
Arrays.asList(currentFile), null, getLog())) {
if(Filters.matchAtLeastOnce(currentResolvedFile, CLASS_INCLUDE_FILTERS)) {
byteCodeFiles.add(currentResolvedFile);
}
}
for(File currentByteCodeFile : byteCodeFiles) {
final String currentCanonicalPath = FileSystemUtilities.getCanonicalPath(
currentByteCodeFile.getAbsoluteFile());
final String relativized = FileSystemUtilities.relativize(currentCanonicalPath,
FileSystemUtilities.getCanonicalFile(currentFile.getAbsoluteFile()));
final String pathFromUserDir = FileSystemUtilities.relativize(currentCanonicalPath, userDir);
final String className = relativized.substring(0, relativized.indexOf(".class"))
.replace("/", ".")
.replace(File.separator, ".");
if(!className2SourcePath.containsKey(className)) {
className2SourcePath.put(className, pathFromUserDir);
if(getLog().isDebugEnabled()) {
getLog().debug("Adding ByteCode [" + className + "] at relativized path ["
+ pathFromUserDir + "]");
}
} else {
if(getLog().isDebugEnabled()) {
getLog().debug("ByteCode [" + className + "] already added. Not re-adding.");
}
}
}
} else if (getLog().isWarnEnabled()) {
final String suffix = !currentFile.exists() ? " nonexistent" : " was neither a File nor a Directory";
getLog().warn("Classpath part [" + current + "] " + suffix + ". Ignoring it.");
}
}
/*
for (URL current : getCompiledClassNames()) {
// TODO: FIX THIS!
// Get the class information data from the supplied URL
for (String currentClassPathElement : getClasspath()) {
if(getLog().isDebugEnabled()) {
getLog().debug("Checking class path element: [" + currentClassPathElement + "]");
}
}
if(getLog().isDebugEnabled()) {
getLog().debug("Processing compiledClassName: [" + current + "]");
}
// Find the Java class(es) within the source.
final JavaProjectBuilder builder = new JavaProjectBuilder();
builder.setEncoding(getEncoding(true));
builder.addSource(current);
for (JavaSource currentSource : builder.getSources()) {
for (JavaClass currentClass : currentSource.getClasses()) {
final String className = currentClass.getFullyQualifiedName();
if (className2SourcePath.containsKey(className)) {
if (getLog().isWarnEnabled()) {
getLog().warn("Already mapped. Source class [" + className + "] within ["
+ className2SourcePath.get(className)
+ "]. Not overwriting with [" + className + "]");
}
} else {
className2SourcePath.put(className, className);
}
}
}
}
*/
if (getLog().isDebugEnabled()) {
final int size = className2SourcePath.size();
getLog().debug("[ClassName-2-SourcePath Map (size: " + size + ")] ...");
int i = 0;
for (Map.Entry<String, String> current : className2SourcePath.entrySet()) {
getLog().debug(" " + (++i) + "/" + size + ": [" + current.getKey() + "]: "
+ current.getValue());
}
getLog().debug("... End [ClassName-2-SourcePath Map]");
}
// Sort the source paths and place them first in the argument array
final ArrayList<String> toReturn = new ArrayList<String>(className2SourcePath.values());
Collections.sort(toReturn);
// All Done.
return toReturn; // depends on control dependency: [if], data = [none]
} } |
public class class_name {
protected EntityManagerFactory lookupEntityManagerFactory(OpenEntityManager openEntityManager) {
String emfBeanName = openEntityManager.name();
String puName = openEntityManager.unitName();
if (StringUtils.hasLength(emfBeanName)) {
return this.applicationContext.getBean(emfBeanName, EntityManagerFactory.class);
} else if (!StringUtils.hasLength(puName)
&& this.applicationContext.containsBean(
OpenEntityManagerInViewFilter.DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
return this.applicationContext.getBean(
OpenEntityManagerInViewFilter.DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME,
EntityManagerFactory.class);
} else {
// Includes fallback search for single EntityManagerFactory bean by type.
return EntityManagerFactoryUtils.findEntityManagerFactory(
this.applicationContext, puName);
}
} } | public class class_name {
protected EntityManagerFactory lookupEntityManagerFactory(OpenEntityManager openEntityManager) {
String emfBeanName = openEntityManager.name();
String puName = openEntityManager.unitName();
if (StringUtils.hasLength(emfBeanName)) {
return this.applicationContext.getBean(emfBeanName, EntityManagerFactory.class); // depends on control dependency: [if], data = [none]
} else if (!StringUtils.hasLength(puName)
&& this.applicationContext.containsBean(
OpenEntityManagerInViewFilter.DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
return this.applicationContext.getBean(
OpenEntityManagerInViewFilter.DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME,
EntityManagerFactory.class); // depends on control dependency: [if], data = [none]
} else {
// Includes fallback search for single EntityManagerFactory bean by type.
return EntityManagerFactoryUtils.findEntityManagerFactory(
this.applicationContext, puName); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Observable<ServiceResponse<Page<PolicyDefinitionInner>>> listByManagementGroupSinglePageAsync(final String managementGroupId) {
if (managementGroupId == null) {
throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listByManagementGroup(managementGroupId, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<PolicyDefinitionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PolicyDefinitionInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<PolicyDefinitionInner>> result = listByManagementGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<PolicyDefinitionInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<PolicyDefinitionInner>>> listByManagementGroupSinglePageAsync(final String managementGroupId) {
if (managementGroupId == null) {
throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listByManagementGroup(managementGroupId, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<PolicyDefinitionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PolicyDefinitionInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<PolicyDefinitionInner>> result = listByManagementGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<PolicyDefinitionInner>>(result.body(), result.response())); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public static boolean areRightLinksConsistent(CalendarHashChain calendarHashChain1,
CalendarHashChain calendarHashChain2) {
notNull(calendarHashChain1, "CalendarHashChain");
notNull(calendarHashChain2, "CalendarHashChain");
List<CalendarHashChainLink> rightLinks1 = getRightLinks(calendarHashChain1);
List<CalendarHashChainLink> rightLinks2 = getRightLinks(calendarHashChain2);
if (rightLinks1.size() != rightLinks2.size()) {
logger.info("Calendar hash chains have different amount of right links: {} vs {}",
rightLinks1.size(), rightLinks2.size());
return false;
}
for (int i = 0; i < rightLinks2.size(); i++) {
CalendarHashChainLink link1 = rightLinks2.get(i);
CalendarHashChainLink link2 = rightLinks1.get(i);
if (!link1.getDataHash().equals(link2.getDataHash())) {
logger.info("Calendar hash chain right links do not match at right link number {}", i + 1);
return false;
}
}
return true;
} } | public class class_name {
public static boolean areRightLinksConsistent(CalendarHashChain calendarHashChain1,
CalendarHashChain calendarHashChain2) {
notNull(calendarHashChain1, "CalendarHashChain");
notNull(calendarHashChain2, "CalendarHashChain");
List<CalendarHashChainLink> rightLinks1 = getRightLinks(calendarHashChain1);
List<CalendarHashChainLink> rightLinks2 = getRightLinks(calendarHashChain2);
if (rightLinks1.size() != rightLinks2.size()) {
logger.info("Calendar hash chains have different amount of right links: {} vs {}",
rightLinks1.size(), rightLinks2.size()); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < rightLinks2.size(); i++) {
CalendarHashChainLink link1 = rightLinks2.get(i);
CalendarHashChainLink link2 = rightLinks1.get(i);
if (!link1.getDataHash().equals(link2.getDataHash())) {
logger.info("Calendar hash chain right links do not match at right link number {}", i + 1); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public static String extractDDLToken(String sql)
{
String ddlToken = null;
Matcher ddlMatcher = PAT_ANY_DDL_FIRST_TOKEN.matcher(sql);
if (ddlMatcher.find()) {
ddlToken = ddlMatcher.group(1).toLowerCase();
}
return ddlToken;
} } | public class class_name {
public static String extractDDLToken(String sql)
{
String ddlToken = null;
Matcher ddlMatcher = PAT_ANY_DDL_FIRST_TOKEN.matcher(sql);
if (ddlMatcher.find()) {
ddlToken = ddlMatcher.group(1).toLowerCase(); // depends on control dependency: [if], data = [none]
}
return ddlToken;
} } |
public class class_name {
@Override
public boolean addAll(Collection<? extends BooleanTerm> terms) {
boolean modified = false;
// a null booleanTerms means that the expression is
// already true, so no need to modify it
if (terms == null) {
modified = booleanTerms != null;
booleanTerms = null;
} else if (booleanTerms != null) {
for (BooleanTerm term : terms) {
modified |= add(term);
}
}
return modified;
} } | public class class_name {
@Override
public boolean addAll(Collection<? extends BooleanTerm> terms) {
boolean modified = false;
// a null booleanTerms means that the expression is
// already true, so no need to modify it
if (terms == null) {
modified = booleanTerms != null;
// depends on control dependency: [if], data = [none]
booleanTerms = null;
// depends on control dependency: [if], data = [none]
} else if (booleanTerms != null) {
for (BooleanTerm term : terms) {
modified |= add(term);
// depends on control dependency: [for], data = [term]
}
}
return modified;
} } |
public class class_name {
@Override
public int compareTo(ChildData rhs)
{
if ( this == rhs )
{
return 0;
}
if ( rhs == null || getClass() != rhs.getClass() )
{
return -1;
}
return path.compareTo(rhs.path);
} } | public class class_name {
@Override
public int compareTo(ChildData rhs)
{
if ( this == rhs )
{
return 0; // depends on control dependency: [if], data = [none]
}
if ( rhs == null || getClass() != rhs.getClass() )
{
return -1; // depends on control dependency: [if], data = [none]
}
return path.compareTo(rhs.path);
} } |
public class class_name {
public String categoryAndFunction(String category) {
if (category == null) {
return null;
}
String catFunc = category;
int i = lastIndexOfNumericTag(catFunc);
while (i >= 0) {
catFunc = catFunc.substring(0, i);
i = lastIndexOfNumericTag(catFunc);
}
return catFunc;
} } | public class class_name {
public String categoryAndFunction(String category) {
if (category == null) {
return null;
// depends on control dependency: [if], data = [none]
}
String catFunc = category;
int i = lastIndexOfNumericTag(catFunc);
while (i >= 0) {
catFunc = catFunc.substring(0, i);
// depends on control dependency: [while], data = [none]
i = lastIndexOfNumericTag(catFunc);
// depends on control dependency: [while], data = [none]
}
return catFunc;
} } |
public class class_name {
@Override
public void keyReleased(KeyEvent e){
int code = e.getKeyCode();
//String s = e.getKeyText(code);
//System.out.println(s);
if (( code == KeyEvent.VK_UP ) ||
( code == KeyEvent.VK_KP_UP)) {
// go one back in history;
if ( historyPosition > 0){
historyPosition= historyPosition-1;
}
} else if (( code == KeyEvent.VK_DOWN ) ||
( code == KeyEvent.VK_KP_DOWN)) {
if ( historyPosition < (history.size()-1) ){
historyPosition++;
} else {
// clear command if at beginning of history
textfield.setText("");
historyPosition=history.size();
return;
}
} else if ( code == KeyEvent.VK_PAGE_UP) {
if ( historyPosition > 0) {
historyPosition = 0;
}
} else if ( code == KeyEvent.VK_PAGE_DOWN) {
if ( historyPosition >= 0) {
historyPosition = history.size()-1;
}
} else {
// some other key has been pressed, do nothing
return;
}
if ( historyPosition >= 0) {
String txt = history.get(historyPosition);
textfield.setText(txt);
}
} } | public class class_name {
@Override
public void keyReleased(KeyEvent e){
int code = e.getKeyCode();
//String s = e.getKeyText(code);
//System.out.println(s);
if (( code == KeyEvent.VK_UP ) ||
( code == KeyEvent.VK_KP_UP)) {
// go one back in history;
if ( historyPosition > 0){
historyPosition= historyPosition-1; // depends on control dependency: [if], data = [none]
}
} else if (( code == KeyEvent.VK_DOWN ) ||
( code == KeyEvent.VK_KP_DOWN)) {
if ( historyPosition < (history.size()-1) ){
historyPosition++; // depends on control dependency: [if], data = [none]
} else {
// clear command if at beginning of history
textfield.setText(""); // depends on control dependency: [if], data = [none]
historyPosition=history.size(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else if ( code == KeyEvent.VK_PAGE_UP) {
if ( historyPosition > 0) {
historyPosition = 0; // depends on control dependency: [if], data = [none]
}
} else if ( code == KeyEvent.VK_PAGE_DOWN) {
if ( historyPosition >= 0) {
historyPosition = history.size()-1; // depends on control dependency: [if], data = [none]
}
} else {
// some other key has been pressed, do nothing
return; // depends on control dependency: [if], data = [none]
}
if ( historyPosition >= 0) {
String txt = history.get(historyPosition);
textfield.setText(txt); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public int indexOf(String label) {
T token = tokenFor(label);
if (token != null) {
return token.getIndex();
} else
return -2;
} } | public class class_name {
@Override
public int indexOf(String label) {
T token = tokenFor(label);
if (token != null) {
return token.getIndex(); // depends on control dependency: [if], data = [none]
} else
return -2;
} } |
public class class_name {
private void injectDependencies(TypeElement component,
ComponentInjectedDependenciesBuilder dependenciesBuilder,
MethodSpec.Builder createdMethodBuilder) {
if (!dependenciesBuilder.hasInjectedDependencies()) {
return;
}
createDependenciesInstance(component, createdMethodBuilder);
copyDependenciesFields(dependenciesBuilder, createdMethodBuilder);
callMethodsWithDependencies(dependenciesBuilder, createdMethodBuilder);
} } | public class class_name {
private void injectDependencies(TypeElement component,
ComponentInjectedDependenciesBuilder dependenciesBuilder,
MethodSpec.Builder createdMethodBuilder) {
if (!dependenciesBuilder.hasInjectedDependencies()) {
return; // depends on control dependency: [if], data = [none]
}
createDependenciesInstance(component, createdMethodBuilder);
copyDependenciesFields(dependenciesBuilder, createdMethodBuilder);
callMethodsWithDependencies(dependenciesBuilder, createdMethodBuilder);
} } |
public class class_name {
private void addPostParams(final Request request) {
if (roleSid != null) {
request.addPostParam("RoleSid", roleSid);
}
if (lastConsumedMessageIndex != null) {
request.addPostParam("LastConsumedMessageIndex", lastConsumedMessageIndex.toString());
}
} } | public class class_name {
private void addPostParams(final Request request) {
if (roleSid != null) {
request.addPostParam("RoleSid", roleSid); // depends on control dependency: [if], data = [none]
}
if (lastConsumedMessageIndex != null) {
request.addPostParam("LastConsumedMessageIndex", lastConsumedMessageIndex.toString()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static long[] parseRange(String rangeValue) {
int phyphen = rangeValue.indexOf('-');
if (phyphen == -1) {
// this is a syntax error.
return null;
}
try {
if (phyphen == 0) {
// -N (suffix-byte-range-spec)
long end = Long.parseLong(rangeValue.substring(1));
if (end <= 0) return null;
return new long[] { -end, -1 };
}
if (phyphen == rangeValue.length() - 1) {
// M- (byte-range-spec without last-byte-pos)
long start = Long.parseLong(rangeValue.substring(0, phyphen));
return new long[] { start, -1 };
}
// M-N (byte-range-spec)
long start = Long.parseLong(rangeValue.substring(0, phyphen));
long end = Long.parseLong(rangeValue.substring(phyphen + 1));
if (start > end) return null;
return new long[] { start, end + 1 };
} catch (NumberFormatException ex) {
return null;
}
} } | public class class_name {
public static long[] parseRange(String rangeValue) {
int phyphen = rangeValue.indexOf('-');
if (phyphen == -1) {
// this is a syntax error.
return null; // depends on control dependency: [if], data = [none]
}
try {
if (phyphen == 0) {
// -N (suffix-byte-range-spec)
long end = Long.parseLong(rangeValue.substring(1));
if (end <= 0) return null;
return new long[] { -end, -1 }; // depends on control dependency: [if], data = [none]
}
if (phyphen == rangeValue.length() - 1) {
// M- (byte-range-spec without last-byte-pos)
long start = Long.parseLong(rangeValue.substring(0, phyphen));
return new long[] { start, -1 }; // depends on control dependency: [if], data = [none]
}
// M-N (byte-range-spec)
long start = Long.parseLong(rangeValue.substring(0, phyphen));
long end = Long.parseLong(rangeValue.substring(phyphen + 1));
if (start > end) return null;
return new long[] { start, end + 1 }; // depends on control dependency: [try], data = [none]
} catch (NumberFormatException ex) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Nonnull
public static Charset getCharsetFromName (@Nonnull @Nonempty final String sCharsetName)
{
ValueEnforcer.notNull (sCharsetName, "CharsetName");
try
{
return Charset.forName (sCharsetName);
}
catch (final IllegalCharsetNameException ex)
{
// Not supported in any version
throw new IllegalArgumentException ("Charset '" + sCharsetName + "' unsupported in Java", ex);
}
catch (final UnsupportedCharsetException ex)
{
// Unsupported on this platform
throw new IllegalArgumentException ("Charset '" + sCharsetName + "' unsupported on this platform", ex);
}
} } | public class class_name {
@Nonnull
public static Charset getCharsetFromName (@Nonnull @Nonempty final String sCharsetName)
{
ValueEnforcer.notNull (sCharsetName, "CharsetName");
try
{
return Charset.forName (sCharsetName); // depends on control dependency: [try], data = [none]
}
catch (final IllegalCharsetNameException ex)
{
// Not supported in any version
throw new IllegalArgumentException ("Charset '" + sCharsetName + "' unsupported in Java", ex);
} // depends on control dependency: [catch], data = [none]
catch (final UnsupportedCharsetException ex)
{
// Unsupported on this platform
throw new IllegalArgumentException ("Charset '" + sCharsetName + "' unsupported on this platform", ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Deprecated
public static String toPlainText(String text, int offset, int capacity)
{
PlainTextState state = PlainTextState.TEXT;
StringBuilder plainText = new StringBuilder();
for(int i = offset; i < text.length() && plainText.length() <= capacity; ++i) {
int c = text.charAt(i);
switch(state) {
case TEXT:
if(c == '<') {
state = PlainTextState.START_TAG;
break;
}
plainText.append((char)c);
break;
case START_TAG:
if(c == '/') {
state = PlainTextState.END_TAG;
break;
}
if(c == '>') {
state = PlainTextState.TEXT;
}
break;
case END_TAG:
if(c == 'p') {
plainText.append("\r\n");
}
if(c == '>') {
state = PlainTextState.TEXT;
}
break;
}
}
return plainText.toString();
} } | public class class_name {
@Deprecated
public static String toPlainText(String text, int offset, int capacity)
{
PlainTextState state = PlainTextState.TEXT;
StringBuilder plainText = new StringBuilder();
for(int i = offset; i < text.length() && plainText.length() <= capacity; ++i) {
int c = text.charAt(i);
switch(state) {
case TEXT:
if(c == '<') {
state = PlainTextState.START_TAG;
// depends on control dependency: [if], data = [none]
break;
}
plainText.append((char)c);
break;
case START_TAG:
if(c == '/') {
state = PlainTextState.END_TAG;
// depends on control dependency: [if], data = [none]
break;
}
if(c == '>') {
state = PlainTextState.TEXT;
// depends on control dependency: [if], data = [none]
}
break;
case END_TAG:
if(c == 'p') {
plainText.append("\r\n");
// depends on control dependency: [if], data = [none]
}
if(c == '>') {
state = PlainTextState.TEXT;
// depends on control dependency: [if], data = [none]
}
break;
}
}
return plainText.toString();
} } |
public class class_name {
public static ILoggerFactory getILoggerFactory() {
if (INITIALIZATION_STATE == UNINITIALIZED) {
synchronized (LoggerFactory.class) {
if (INITIALIZATION_STATE == UNINITIALIZED) {
INITIALIZATION_STATE = ONGOING_INITIALIZATION;
performInitialization();
}
}
}
switch (INITIALIZATION_STATE) {
case SUCCESSFUL_INITIALIZATION:
return StaticLoggerBinder.getSingleton().getLoggerFactory();
case NOP_FALLBACK_INITIALIZATION:
return NOP_FALLBACK_FACTORY;
case FAILED_INITIALIZATION:
throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
case ONGOING_INITIALIZATION:
// support re-entrant behavior.
// See also http://jira.qos.ch/browse/SLF4J-97
return SUBST_FACTORY;
}
throw new IllegalStateException("Unreachable code");
} } | public class class_name {
public static ILoggerFactory getILoggerFactory() {
if (INITIALIZATION_STATE == UNINITIALIZED) {
synchronized (LoggerFactory.class) {
// depends on control dependency: [if], data = [none]
if (INITIALIZATION_STATE == UNINITIALIZED) {
INITIALIZATION_STATE = ONGOING_INITIALIZATION;
// depends on control dependency: [if], data = [none]
performInitialization();
// depends on control dependency: [if], data = [none]
}
}
}
switch (INITIALIZATION_STATE) {
case SUCCESSFUL_INITIALIZATION:
return StaticLoggerBinder.getSingleton().getLoggerFactory();
case NOP_FALLBACK_INITIALIZATION:
return NOP_FALLBACK_FACTORY;
case FAILED_INITIALIZATION:
throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
case ONGOING_INITIALIZATION:
// support re-entrant behavior.
// See also http://jira.qos.ch/browse/SLF4J-97
return SUBST_FACTORY;
}
throw new IllegalStateException("Unreachable code");
} } |
public class class_name {
private UnicodeSet add_unchecked(int start, int end) {
if (start < MIN_VALUE || start > MAX_VALUE) {
throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));
}
if (end < MIN_VALUE || end > MAX_VALUE) {
throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));
}
if (start < end) {
add(range(start, end), 2, 0);
} else if (start == end) {
add(start);
}
return this;
} } | public class class_name {
private UnicodeSet add_unchecked(int start, int end) {
if (start < MIN_VALUE || start > MAX_VALUE) {
throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(start, 6));
}
if (end < MIN_VALUE || end > MAX_VALUE) {
throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(end, 6));
}
if (start < end) {
add(range(start, end), 2, 0); // depends on control dependency: [if], data = [(start]
} else if (start == end) {
add(start); // depends on control dependency: [if], data = [(start]
}
return this;
} } |
public class class_name {
public int[] cwaArray() {
int[] arr = new int[numSamples()];
for (int recall = 1; recall <= numSamples(); recall++) {
arr[recall - 1] = logPrecision(recall);
}
return arr;
} } | public class class_name {
public int[] cwaArray() {
int[] arr = new int[numSamples()];
for (int recall = 1; recall <= numSamples(); recall++) {
arr[recall - 1] = logPrecision(recall);
// depends on control dependency: [for], data = [recall]
}
return arr;
} } |
public class class_name {
@Nonnull
public EContinue encode (@Nonnull final String sSource, @Nonnull final ByteBuffer aDestBuffer)
{
ValueEnforcer.notNull (sSource, "Source");
ValueEnforcer.notNull (aDestBuffer, "DestBuffer");
// We need to special case the empty string
if (sSource.length () == 0)
return EContinue.BREAK;
// read data in, if needed
if (!m_aInChar.hasRemaining () && m_nReadOffset < sSource.length ())
_readInputChunk (sSource);
// if flush() overflows the destination, skip the encode loop and re-try the
// flush()
if (m_aInChar.hasRemaining ())
{
while (true)
{
assert m_aInChar.hasRemaining ();
final boolean bEndOfInput = m_nReadOffset == sSource.length ();
final CoderResult aResult = m_aEncoder.encode (m_aInChar, aDestBuffer, bEndOfInput);
if (aResult == CoderResult.OVERFLOW)
{
// NOTE: destination could space remaining, in case of a multi-byte
// sequence
if (aDestBuffer.remaining () >= m_aEncoder.maxBytesPerChar ())
throw new IllegalStateException ();
return EContinue.CONTINUE;
}
assert aResult == CoderResult.UNDERFLOW;
// If we split a surrogate char (inBuffer.remaining() == 1), back up and
// re-copy
// from the source. avoid a branch by always subtracting
assert m_aInChar.remaining () <= 1;
m_nReadOffset -= m_aInChar.remaining ();
assert m_nReadOffset > 0;
// If we are done, break. Otherwise, read the next chunk
if (m_nReadOffset == sSource.length ())
break;
_readInputChunk (sSource);
}
}
if (m_aInChar.hasRemaining ())
throw new IllegalStateException ();
assert m_nReadOffset == sSource.length ();
final CoderResult aResult = m_aEncoder.flush (aDestBuffer);
if (aResult == CoderResult.OVERFLOW)
{
// I don't think this can happen. If it does, assert so we can figure it
// out
assert false;
// We attempt to handle it anyway
return EContinue.CONTINUE;
}
assert aResult == CoderResult.UNDERFLOW;
// done!
reset ();
return EContinue.BREAK;
} } | public class class_name {
@Nonnull
public EContinue encode (@Nonnull final String sSource, @Nonnull final ByteBuffer aDestBuffer)
{
ValueEnforcer.notNull (sSource, "Source");
ValueEnforcer.notNull (aDestBuffer, "DestBuffer");
// We need to special case the empty string
if (sSource.length () == 0)
return EContinue.BREAK;
// read data in, if needed
if (!m_aInChar.hasRemaining () && m_nReadOffset < sSource.length ())
_readInputChunk (sSource);
// if flush() overflows the destination, skip the encode loop and re-try the
// flush()
if (m_aInChar.hasRemaining ())
{
while (true)
{
assert m_aInChar.hasRemaining ();
final boolean bEndOfInput = m_nReadOffset == sSource.length ();
final CoderResult aResult = m_aEncoder.encode (m_aInChar, aDestBuffer, bEndOfInput);
if (aResult == CoderResult.OVERFLOW)
{
// NOTE: destination could space remaining, in case of a multi-byte
// sequence
if (aDestBuffer.remaining () >= m_aEncoder.maxBytesPerChar ())
throw new IllegalStateException ();
return EContinue.CONTINUE; // depends on control dependency: [if], data = [none]
}
assert aResult == CoderResult.UNDERFLOW;
// If we split a surrogate char (inBuffer.remaining() == 1), back up and
// re-copy
// from the source. avoid a branch by always subtracting
assert m_aInChar.remaining () <= 1;
m_nReadOffset -= m_aInChar.remaining (); // depends on control dependency: [while], data = [none]
assert m_nReadOffset > 0;
// If we are done, break. Otherwise, read the next chunk
if (m_nReadOffset == sSource.length ())
break;
_readInputChunk (sSource); // depends on control dependency: [while], data = [none]
}
}
if (m_aInChar.hasRemaining ())
throw new IllegalStateException ();
assert m_nReadOffset == sSource.length ();
final CoderResult aResult = m_aEncoder.flush (aDestBuffer);
if (aResult == CoderResult.OVERFLOW)
{
// I don't think this can happen. If it does, assert so we can figure it
// out
assert false;
// We attempt to handle it anyway
return EContinue.CONTINUE; // depends on control dependency: [if], data = [none]
}
assert aResult == CoderResult.UNDERFLOW;
// done!
reset ();
return EContinue.BREAK;
} } |
public class class_name {
public static double distanceInMeters(@Nonnull final Point p1, @Nonnull final Point p2) {
checkNonnull("p1", p1);
checkNonnull("p2", p2);
final Point from;
final Point to;
if (p1.getLonDeg() <= p2.getLonDeg()) {
from = p1;
to = p2;
} else {
from = p2;
to = p1;
}
// Calculate mid point of 2 latitudes.
final double avgLat = (from.getLatDeg() + to.getLatDeg()) / 2.0;
final double deltaLatDeg = Math.abs(to.getLatDeg() - from.getLatDeg());
final double deltaLonDeg360 = Math.abs(to.getLonDeg() - from.getLonDeg());
final double deltaLonDeg = ((deltaLonDeg360 <= 180.0) ? deltaLonDeg360 : (360.0 - deltaLonDeg360));
// Meters per longitude is fixed; per latitude requires * cos(avg(lat)).
final double deltaXMeters = degreesLonToMetersAtLat(deltaLonDeg, avgLat);
final double deltaYMeters = degreesLatToMeters(deltaLatDeg);
// Calculate length through Earth. This is an approximation, but works fine for short distances.
return Math.sqrt((deltaXMeters * deltaXMeters) + (deltaYMeters * deltaYMeters));
} } | public class class_name {
public static double distanceInMeters(@Nonnull final Point p1, @Nonnull final Point p2) {
checkNonnull("p1", p1);
checkNonnull("p2", p2);
final Point from;
final Point to;
if (p1.getLonDeg() <= p2.getLonDeg()) {
from = p1; // depends on control dependency: [if], data = [none]
to = p2; // depends on control dependency: [if], data = [none]
} else {
from = p2; // depends on control dependency: [if], data = [none]
to = p1; // depends on control dependency: [if], data = [none]
}
// Calculate mid point of 2 latitudes.
final double avgLat = (from.getLatDeg() + to.getLatDeg()) / 2.0;
final double deltaLatDeg = Math.abs(to.getLatDeg() - from.getLatDeg());
final double deltaLonDeg360 = Math.abs(to.getLonDeg() - from.getLonDeg());
final double deltaLonDeg = ((deltaLonDeg360 <= 180.0) ? deltaLonDeg360 : (360.0 - deltaLonDeg360));
// Meters per longitude is fixed; per latitude requires * cos(avg(lat)).
final double deltaXMeters = degreesLonToMetersAtLat(deltaLonDeg, avgLat);
final double deltaYMeters = degreesLatToMeters(deltaLatDeg);
// Calculate length through Earth. This is an approximation, but works fine for short distances.
return Math.sqrt((deltaXMeters * deltaXMeters) + (deltaYMeters * deltaYMeters));
} } |
public class class_name {
public static List<ExcelHeader> getHeaderList(Class<?> clz) throws Excel4JException {
List<ExcelHeader> headers = new ArrayList<>();
List<Field> fields = new ArrayList<>();
for (Class<?> clazz = clz; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
// 是否使用ExcelField注解
if (field.isAnnotationPresent(ExcelField.class)) {
ExcelField er = field.getAnnotation(ExcelField.class);
try {
headers.add(new ExcelHeader(
er.title(),
er.order(),
er.writeConverter().newInstance(),
er.readConverter().newInstance(),
field.getName(),
field.getType()
));
} catch (InstantiationException | IllegalAccessException e) {
throw new Excel4JException(e);
}
}
}
Collections.sort(headers);
return headers;
} } | public class class_name {
public static List<ExcelHeader> getHeaderList(Class<?> clz) throws Excel4JException {
List<ExcelHeader> headers = new ArrayList<>();
List<Field> fields = new ArrayList<>();
for (Class<?> clazz = clz; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
// 是否使用ExcelField注解
if (field.isAnnotationPresent(ExcelField.class)) {
ExcelField er = field.getAnnotation(ExcelField.class);
try {
headers.add(new ExcelHeader(
er.title(),
er.order(),
er.writeConverter().newInstance(),
er.readConverter().newInstance(),
field.getName(),
field.getType()
)); // depends on control dependency: [try], data = [none]
} catch (InstantiationException | IllegalAccessException e) {
throw new Excel4JException(e);
} // depends on control dependency: [catch], data = [none]
}
}
Collections.sort(headers);
return headers;
} } |
public class class_name {
public void marshall(RemoveAllResourcePermissionsRequest removeAllResourcePermissionsRequest, ProtocolMarshaller protocolMarshaller) {
if (removeAllResourcePermissionsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(removeAllResourcePermissionsRequest.getAuthenticationToken(), AUTHENTICATIONTOKEN_BINDING);
protocolMarshaller.marshall(removeAllResourcePermissionsRequest.getResourceId(), RESOURCEID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(RemoveAllResourcePermissionsRequest removeAllResourcePermissionsRequest, ProtocolMarshaller protocolMarshaller) {
if (removeAllResourcePermissionsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(removeAllResourcePermissionsRequest.getAuthenticationToken(), AUTHENTICATIONTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(removeAllResourcePermissionsRequest.getResourceId(), RESOURCEID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void revokeToken() {
URL url = null;
try {
url = new URL(this.revokeURL);
} catch (MalformedURLException e) {
assert false : "An invalid refresh URL indicates a bug in the SDK.";
throw new RuntimeException("An invalid refresh URL indicates a bug in the SDK.", e);
}
String urlParameters = String.format("token=%s&client_id=%s&client_secret=%s",
this.accessToken, this.clientID, this.clientSecret);
BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
request.shouldAuthenticate(false);
request.setBody(urlParameters);
try {
request.send();
} catch (BoxAPIException e) {
throw e;
}
} } | public class class_name {
public void revokeToken() {
URL url = null;
try {
url = new URL(this.revokeURL); // depends on control dependency: [try], data = [none]
} catch (MalformedURLException e) {
assert false : "An invalid refresh URL indicates a bug in the SDK.";
throw new RuntimeException("An invalid refresh URL indicates a bug in the SDK.", e);
} // depends on control dependency: [catch], data = [none]
String urlParameters = String.format("token=%s&client_id=%s&client_secret=%s",
this.accessToken, this.clientID, this.clientSecret);
BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
request.shouldAuthenticate(false);
request.setBody(urlParameters);
try {
request.send(); // depends on control dependency: [try], data = [none]
} catch (BoxAPIException e) {
throw e;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void zipFiles(final File file, ZipOutputStream zos) throws IOException
{
if (file.isDirectory())
{
File[] fList;
List<File> foundedFiles;
if (null != this.fileFilter)
{
final File[] tmpfList = file.listFiles(this.fileFilter);
final List<File> foundedDirs = FileSearchExtensions.listDirs(file);
if (0 < foundedDirs.size())
{
final List<File> tmp = Arrays.asList(tmpfList);
foundedDirs.addAll(tmp);
foundedFiles = foundedDirs;
}
else
{
final List<File> tmp = Arrays.asList(tmpfList);
foundedFiles = tmp;
}
}
else
{
fList = file.listFiles();
final List<File> tmp = Arrays.asList(fList);
foundedFiles = tmp;
}
for (final File foundedFile : foundedFiles)
{
this.zipFiles(foundedFile, zos);
}
}
else
{
this.fileLength += file.length();
this.fileCounter++;
final String absolutePath = file.getAbsolutePath();
if (this.dirToStart == null)
{
this.dirToStart = this.directoryToZip.getName();
}
final int index = absolutePath.indexOf(this.dirToStart);
final String zipEntryName = absolutePath.substring(index, absolutePath.length());
final byte[] b = new byte[(int)file.length()];
final ZipEntry cpZipEntry = new ZipEntry(zipEntryName);
zos.putNextEntry(cpZipEntry);
zos.write(b, 0, (int)file.length());
zos.closeEntry();
}
} } | public class class_name {
private void zipFiles(final File file, ZipOutputStream zos) throws IOException
{
if (file.isDirectory())
{
File[] fList;
List<File> foundedFiles;
if (null != this.fileFilter)
{
final File[] tmpfList = file.listFiles(this.fileFilter);
final List<File> foundedDirs = FileSearchExtensions.listDirs(file);
if (0 < foundedDirs.size())
{
final List<File> tmp = Arrays.asList(tmpfList);
foundedDirs.addAll(tmp); // depends on control dependency: [if], data = [none]
foundedFiles = foundedDirs; // depends on control dependency: [if], data = [none]
}
else
{
final List<File> tmp = Arrays.asList(tmpfList);
foundedFiles = tmp; // depends on control dependency: [if], data = [none]
}
}
else
{
fList = file.listFiles();
final List<File> tmp = Arrays.asList(fList);
foundedFiles = tmp;
}
for (final File foundedFile : foundedFiles)
{
this.zipFiles(foundedFile, zos);
}
}
else
{
this.fileLength += file.length();
this.fileCounter++;
final String absolutePath = file.getAbsolutePath();
if (this.dirToStart == null)
{
this.dirToStart = this.directoryToZip.getName();
}
final int index = absolutePath.indexOf(this.dirToStart);
final String zipEntryName = absolutePath.substring(index, absolutePath.length());
final byte[] b = new byte[(int)file.length()];
final ZipEntry cpZipEntry = new ZipEntry(zipEntryName);
zos.putNextEntry(cpZipEntry);
zos.write(b, 0, (int)file.length());
zos.closeEntry();
}
} } |
public class class_name {
public V getAndRemove(String key) {
try {
V objToShare = retrieveSharedQueue(key).take();
mediations.remove(key);
return objToShare;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public V getAndRemove(String key) {
try {
V objToShare = retrieveSharedQueue(key).take();
mediations.remove(key); // depends on control dependency: [try], data = [none]
return objToShare; // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void setValue(int newPosition, T1 valueSum, T2 valueSumOfLogs,
T1 valueSumOfSquares, T1 valueMin, T1 valueMax, long valueN,
boolean currentExisting) {
if (valueN > 0) {
if (currentExisting) {
newAdvancedValueSumList[newPosition] = operations
.add11(newAdvancedValueSumList[newPosition], valueSum);
newAdvancedValueSumOfLogsList[newPosition] = operations
.add22(newAdvancedValueSumOfLogsList[newPosition], valueSumOfLogs);
newAdvancedValueSumOfSquaresList[newPosition] = operations.add11(
newAdvancedValueSumOfSquaresList[newPosition], valueSumOfSquares);
newAdvancedValueMinList[newPosition] = operations
.min11(newAdvancedValueMinList[newPosition], valueMin);
newAdvancedValueMaxList[newPosition] = operations
.max11(newAdvancedValueMaxList[newPosition], valueMax);
newAdvancedValueNList[newPosition] += valueN;
} else {
newAdvancedValueSumList[newPosition] = valueSum;
newAdvancedValueSumOfLogsList[newPosition] = valueSumOfLogs;
newAdvancedValueSumOfSquaresList[newPosition] = valueSumOfSquares;
newAdvancedValueMinList[newPosition] = valueMin;
newAdvancedValueMaxList[newPosition] = valueMax;
newAdvancedValueNList[newPosition] = valueN;
}
}
} } | public class class_name {
private void setValue(int newPosition, T1 valueSum, T2 valueSumOfLogs,
T1 valueSumOfSquares, T1 valueMin, T1 valueMax, long valueN,
boolean currentExisting) {
if (valueN > 0) {
if (currentExisting) {
newAdvancedValueSumList[newPosition] = operations
.add11(newAdvancedValueSumList[newPosition], valueSum); // depends on control dependency: [if], data = [none]
newAdvancedValueSumOfLogsList[newPosition] = operations
.add22(newAdvancedValueSumOfLogsList[newPosition], valueSumOfLogs); // depends on control dependency: [if], data = [none]
newAdvancedValueSumOfSquaresList[newPosition] = operations.add11(
newAdvancedValueSumOfSquaresList[newPosition], valueSumOfSquares); // depends on control dependency: [if], data = [none]
newAdvancedValueMinList[newPosition] = operations
.min11(newAdvancedValueMinList[newPosition], valueMin); // depends on control dependency: [if], data = [none]
newAdvancedValueMaxList[newPosition] = operations
.max11(newAdvancedValueMaxList[newPosition], valueMax); // depends on control dependency: [if], data = [none]
newAdvancedValueNList[newPosition] += valueN; // depends on control dependency: [if], data = [none]
} else {
newAdvancedValueSumList[newPosition] = valueSum; // depends on control dependency: [if], data = [none]
newAdvancedValueSumOfLogsList[newPosition] = valueSumOfLogs; // depends on control dependency: [if], data = [none]
newAdvancedValueSumOfSquaresList[newPosition] = valueSumOfSquares; // depends on control dependency: [if], data = [none]
newAdvancedValueMinList[newPosition] = valueMin; // depends on control dependency: [if], data = [none]
newAdvancedValueMaxList[newPosition] = valueMax; // depends on control dependency: [if], data = [none]
newAdvancedValueNList[newPosition] = valueN; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public @CheckForNull Plugin getPlugin(String artifactId, @CheckForNull VersionNumber minVersion) {
if (minVersion == null) {
return getPlugin(artifactId);
}
for (UpdateSite s : sites) {
Plugin p = s.getPlugin(artifactId);
if (p!=null) {
if (minVersion.isNewerThan(new VersionNumber(p.version))) continue;
return p;
}
}
return null;
} } | public class class_name {
public @CheckForNull Plugin getPlugin(String artifactId, @CheckForNull VersionNumber minVersion) {
if (minVersion == null) {
return getPlugin(artifactId); // depends on control dependency: [if], data = [none]
}
for (UpdateSite s : sites) {
Plugin p = s.getPlugin(artifactId);
if (p!=null) {
if (minVersion.isNewerThan(new VersionNumber(p.version))) continue;
return p; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public void update(int[] goldIndex, int[] predictIndex)
{
for (int i = 0; i < goldIndex.length; ++i)
{
if (goldIndex[i] == predictIndex[i])
continue;
else // 预测与答案不一致
{
parameter[goldIndex[i]]++; // 奖励正确的特征函数(将它的权值加一)
if (predictIndex[i] >= 0 && predictIndex[i] < parameter.length)
parameter[predictIndex[i]]--; // 惩罚招致错误的特征函数(将它的权值减一)
else
{
throw new IllegalArgumentException("更新参数时传入了非法的下标");
}
}
}
} } | public class class_name {
public void update(int[] goldIndex, int[] predictIndex)
{
for (int i = 0; i < goldIndex.length; ++i)
{
if (goldIndex[i] == predictIndex[i])
continue;
else // 预测与答案不一致
{
parameter[goldIndex[i]]++; // 奖励正确的特征函数(将它的权值加一) // depends on control dependency: [if], data = [none]
if (predictIndex[i] >= 0 && predictIndex[i] < parameter.length)
parameter[predictIndex[i]]--; // 惩罚招致错误的特征函数(将它的权值减一)
else
{
throw new IllegalArgumentException("更新参数时传入了非法的下标");
}
}
}
} } |
public class class_name {
@Deprecated
public boolean skeletonsAreSimilar(String id, String skeleton) {
if (id.equals(skeleton)) {
return true; // fast path
}
// must clone array, make sure items are in same order.
TreeSet<String> parser1 = getSet(id);
TreeSet<String> parser2 = getSet(skeleton);
if (parser1.size() != parser2.size()) {
return false;
}
Iterator<String> it2 = parser2.iterator();
for (String item : parser1) {
int index1 = getCanonicalIndex(item, false);
String item2 = it2.next(); // same length so safe
int index2 = getCanonicalIndex(item2, false);
if (types[index1][1] != types[index2][1]) {
return false;
}
}
return true;
} } | public class class_name {
@Deprecated
public boolean skeletonsAreSimilar(String id, String skeleton) {
if (id.equals(skeleton)) {
return true; // fast path // depends on control dependency: [if], data = [none]
}
// must clone array, make sure items are in same order.
TreeSet<String> parser1 = getSet(id);
TreeSet<String> parser2 = getSet(skeleton);
if (parser1.size() != parser2.size()) {
return false; // depends on control dependency: [if], data = [none]
}
Iterator<String> it2 = parser2.iterator();
for (String item : parser1) {
int index1 = getCanonicalIndex(item, false);
String item2 = it2.next(); // same length so safe
int index2 = getCanonicalIndex(item2, false);
if (types[index1][1] != types[index2][1]) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public static String recommend(BitmapStatistics s) {
if (s.containerCount() == 0) {
return "Empty statistics, cannot recommend.";
}
StringBuilder sb = new StringBuilder();
containerCountRecommendations(s, sb);
double acFraction = s.containerFraction(s.getArrayContainersStats().getContainersCount());
if (acFraction > ArrayContainersDomination) {
if (s.getArrayContainersStats().averageCardinality() < WorthUsingArraysCardinalityThreshold) {
arrayContainerRecommendations(s, sb);
} else {
denseArrayWarning(sb);
constantMemoryRecommendation(s, sb);
}
} else if (s.containerFraction(s.getRunContainerCount()) > RunContainersDomination) {
runContainerRecommendations(sb);
} else {
constantMemoryRecommendation(s, sb);
}
return sb.toString();
} } | public class class_name {
public static String recommend(BitmapStatistics s) {
if (s.containerCount() == 0) {
return "Empty statistics, cannot recommend."; // depends on control dependency: [if], data = [none]
}
StringBuilder sb = new StringBuilder();
containerCountRecommendations(s, sb);
double acFraction = s.containerFraction(s.getArrayContainersStats().getContainersCount());
if (acFraction > ArrayContainersDomination) {
if (s.getArrayContainersStats().averageCardinality() < WorthUsingArraysCardinalityThreshold) {
arrayContainerRecommendations(s, sb); // depends on control dependency: [if], data = [none]
} else {
denseArrayWarning(sb); // depends on control dependency: [if], data = [none]
constantMemoryRecommendation(s, sb); // depends on control dependency: [if], data = [none]
}
} else if (s.containerFraction(s.getRunContainerCount()) > RunContainersDomination) {
runContainerRecommendations(sb); // depends on control dependency: [if], data = [none]
} else {
constantMemoryRecommendation(s, sb); // depends on control dependency: [if], data = [none]
}
return sb.toString();
} } |
public class class_name {
public static IDocTypeProcessor wrap(final IDocTypeProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new DocTypeProcessorWrapper(processor, dialect);
} } | public class class_name {
public static IDocTypeProcessor wrap(final IDocTypeProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null; // depends on control dependency: [if], data = [none]
}
return new DocTypeProcessorWrapper(processor, dialect);
} } |
public class class_name {
private List<String> existingRWPaths() {
String[] lines = mountReader();
List<String> pathsFound = new ArrayList<>();
for (String line : lines) {
// Split lines into parts
String[] args = line.split(" ");
if (args.length < 4){
// If we don't have enough options per line, skip this and log an error
Log.e(TAG, String.format("Error formatting mount: %s", line));
continue;
}
String mountPoint = args[1];
String mountOptions = args[3];
for (String pathToCheck : PATHS_THAT_SHOULD_NOT_BE_WRITABLE) {
if (mountPoint.equalsIgnoreCase(pathToCheck)) {
// Split options out and compare against "rw" to avoid false positives
for (String option : mountOptions.split(",")){
if (option.equalsIgnoreCase("rw")){
pathsFound.add(pathToCheck);
break;
}
}
}
}
}
return pathsFound;
} } | public class class_name {
private List<String> existingRWPaths() {
String[] lines = mountReader();
List<String> pathsFound = new ArrayList<>();
for (String line : lines) {
// Split lines into parts
String[] args = line.split(" ");
if (args.length < 4){
// If we don't have enough options per line, skip this and log an error
Log.e(TAG, String.format("Error formatting mount: %s", line)); // depends on control dependency: [if], data = [none]
continue;
}
String mountPoint = args[1];
String mountOptions = args[3];
for (String pathToCheck : PATHS_THAT_SHOULD_NOT_BE_WRITABLE) {
if (mountPoint.equalsIgnoreCase(pathToCheck)) {
// Split options out and compare against "rw" to avoid false positives
for (String option : mountOptions.split(",")){
if (option.equalsIgnoreCase("rw")){
pathsFound.add(pathToCheck); // depends on control dependency: [if], data = [none]
break;
}
}
}
}
}
return pathsFound;
} } |
public class class_name {
private void printBanner() {
if (null != blade.bannerText()) {
System.out.println(blade.bannerText());
} else {
String text = Const.BANNER_TEXT + NEW_LINE +
StringKit.padLeft(" :: Blade :: (v", Const.BANNER_PADDING - 9) + Const.VERSION + ") " + NEW_LINE;
System.out.println(Ansi.Magenta.format(text));
}
} } | public class class_name {
private void printBanner() {
if (null != blade.bannerText()) {
System.out.println(blade.bannerText()); // depends on control dependency: [if], data = [blade.bannerText())]
} else {
String text = Const.BANNER_TEXT + NEW_LINE +
StringKit.padLeft(" :: Blade :: (v", Const.BANNER_PADDING - 9) + Const.VERSION + ") " + NEW_LINE;
System.out.println(Ansi.Magenta.format(text));
}
} } |
public class class_name {
protected synchronized void startWatchingFiles() {
famList.clear();
FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
FileChangeListener wurflListener = new WurflFileListener();
fam.addListener(wurflFile, wurflListener);
fam.start();
famList.add(fam);
logger.debug("watching " + wurflFile.getAbsolutePath());
for (File patchFile : wurflPatchFiles) {
fam = new FilesystemAlterationMonitor();
FileChangeListener wurflPatchListener = new WurflFileListener();
fam.addListener(patchFile, wurflPatchListener);
fam.start();
famList.add(fam);
logger.debug("watching " + patchFile.getAbsolutePath());
}
} } | public class class_name {
protected synchronized void startWatchingFiles() {
famList.clear();
FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
FileChangeListener wurflListener = new WurflFileListener();
fam.addListener(wurflFile, wurflListener);
fam.start();
famList.add(fam);
logger.debug("watching " + wurflFile.getAbsolutePath());
for (File patchFile : wurflPatchFiles) {
fam = new FilesystemAlterationMonitor(); // depends on control dependency: [for], data = [none]
FileChangeListener wurflPatchListener = new WurflFileListener();
fam.addListener(patchFile, wurflPatchListener); // depends on control dependency: [for], data = [patchFile]
fam.start(); // depends on control dependency: [for], data = [none]
famList.add(fam); // depends on control dependency: [for], data = [none]
logger.debug("watching " + patchFile.getAbsolutePath()); // depends on control dependency: [for], data = [patchFile]
}
} } |
public class class_name {
public AwsSecurityFindingFilters withNetworkProtocol(StringFilter... networkProtocol) {
if (this.networkProtocol == null) {
setNetworkProtocol(new java.util.ArrayList<StringFilter>(networkProtocol.length));
}
for (StringFilter ele : networkProtocol) {
this.networkProtocol.add(ele);
}
return this;
} } | public class class_name {
public AwsSecurityFindingFilters withNetworkProtocol(StringFilter... networkProtocol) {
if (this.networkProtocol == null) {
setNetworkProtocol(new java.util.ArrayList<StringFilter>(networkProtocol.length)); // depends on control dependency: [if], data = [none]
}
for (StringFilter ele : networkProtocol) {
this.networkProtocol.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private ProtoNetwork stage4(final ProtoNetwork pn) {
beginStage(PHASE3_STAGE4_HDR, "4", NUM_PHASES);
if (!getPhaseConfiguration().getInjectOrthology()) {
final StringBuilder bldr = new StringBuilder();
bldr.append(ORTHO_INJECTION_DISABLED);
markEndStage(bldr);
stageOutput(bldr.toString());
return pn;
}
// create output directory for orthologized proto network
artifactPath = createDirectoryArtifact(outputDirectory, DIR_ARTIFACT);
final Index index = ResourceIndex.INSTANCE.getIndex();
final Set<ResourceLocation> resources = index.getOrthologyResources();
if (noItems(resources)) {
final StringBuilder bldr = new StringBuilder();
bldr.append("No orthology documents included.");
markEndStage(bldr);
stageOutput(bldr.toString());
return pn;
}
// equivalence network first, before pruning
Set<EquivalenceDataIndex> equivs;
try {
equivs = p2.stage2LoadNamespaceEquivalences();
} catch (EquivalenceMapResolutionFailure e) {
stageError(e.getUserFacingMessage());
equivs = emptySet();
}
try {
p2.stage3EquivalenceParameters(pn, equivs);
} catch (IOException e) {
}
final Iterator<ResourceLocation> it = resources.iterator();
final ResourceLocation first = it.next();
final ProtoNetwork orthoMerge = pruneResource(pn, first);
while (it.hasNext()) {
final ResourceLocation resource = it.next();
final ProtoNetwork opn = pruneResource(pn, resource);
try {
p3.merge(orthoMerge, opn);
} catch (ProtoNetworkError e) {
e.printStackTrace();
}
}
try {
runPhaseThree(orthoMerge);
} catch (ProtoNetworkError e) {
stageError(e.getUserFacingMessage());
bail(ExitCode.GENERAL_FAILURE);
}
try {
p3.merge(pn, orthoMerge);
} catch (ProtoNetworkError e) {
stageError(e.getUserFacingMessage());
bail(ExitCode.GENERAL_FAILURE);
}
return pn;
} } | public class class_name {
private ProtoNetwork stage4(final ProtoNetwork pn) {
beginStage(PHASE3_STAGE4_HDR, "4", NUM_PHASES);
if (!getPhaseConfiguration().getInjectOrthology()) {
final StringBuilder bldr = new StringBuilder();
bldr.append(ORTHO_INJECTION_DISABLED); // depends on control dependency: [if], data = [none]
markEndStage(bldr); // depends on control dependency: [if], data = [none]
stageOutput(bldr.toString()); // depends on control dependency: [if], data = [none]
return pn; // depends on control dependency: [if], data = [none]
}
// create output directory for orthologized proto network
artifactPath = createDirectoryArtifact(outputDirectory, DIR_ARTIFACT);
final Index index = ResourceIndex.INSTANCE.getIndex();
final Set<ResourceLocation> resources = index.getOrthologyResources();
if (noItems(resources)) {
final StringBuilder bldr = new StringBuilder();
bldr.append("No orthology documents included."); // depends on control dependency: [if], data = [none]
markEndStage(bldr); // depends on control dependency: [if], data = [none]
stageOutput(bldr.toString()); // depends on control dependency: [if], data = [none]
return pn; // depends on control dependency: [if], data = [none]
}
// equivalence network first, before pruning
Set<EquivalenceDataIndex> equivs;
try {
equivs = p2.stage2LoadNamespaceEquivalences(); // depends on control dependency: [try], data = [none]
} catch (EquivalenceMapResolutionFailure e) {
stageError(e.getUserFacingMessage());
equivs = emptySet();
} // depends on control dependency: [catch], data = [none]
try {
p2.stage3EquivalenceParameters(pn, equivs); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
} // depends on control dependency: [catch], data = [none]
final Iterator<ResourceLocation> it = resources.iterator();
final ResourceLocation first = it.next();
final ProtoNetwork orthoMerge = pruneResource(pn, first);
while (it.hasNext()) {
final ResourceLocation resource = it.next();
final ProtoNetwork opn = pruneResource(pn, resource);
try {
p3.merge(orthoMerge, opn); // depends on control dependency: [try], data = [none]
} catch (ProtoNetworkError e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
try {
runPhaseThree(orthoMerge); // depends on control dependency: [try], data = [none]
} catch (ProtoNetworkError e) {
stageError(e.getUserFacingMessage());
bail(ExitCode.GENERAL_FAILURE);
} // depends on control dependency: [catch], data = [none]
try {
p3.merge(pn, orthoMerge); // depends on control dependency: [try], data = [none]
} catch (ProtoNetworkError e) {
stageError(e.getUserFacingMessage());
bail(ExitCode.GENERAL_FAILURE);
} // depends on control dependency: [catch], data = [none]
return pn;
} } |
public class class_name {
public SimpleBitSet get(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
checkInvariants();
int len = length();
// If no set bits in range return empty bitset
if (len <= fromIndex || fromIndex == toIndex)
return new SimpleBitSet(0);
// An optimization
if (toIndex > len)
toIndex = len;
SimpleBitSet result = new SimpleBitSet(toIndex - fromIndex);
int targetWords = wordIndex(toIndex - fromIndex - 1) + 1;
int sourceIndex = wordIndex(fromIndex);
boolean wordAligned = ((fromIndex & BIT_INDEX_MASK) == 0);
// Process all words but the last word
for (int i = 0; i < targetWords - 1; i++, sourceIndex++) {
result.words[i] = (wordAligned ? words[sourceIndex]
: (words[sourceIndex] >>> fromIndex)
| (words[sourceIndex + 1] << -fromIndex));
}
// Process the last word
long lastWordMask = (WORD_MASK >>> -toIndex);
result.words[targetWords - 1] = (((toIndex - 1) & BIT_INDEX_MASK) < (fromIndex & BIT_INDEX_MASK)
? ((words[sourceIndex] >>> fromIndex) | (words[sourceIndex + 1] & lastWordMask) << -fromIndex)
: ((words[sourceIndex] & lastWordMask) >>> fromIndex));
// Set wordsInUse correctly
result.wordsInUse = targetWords;
result.recalculateWordsInUse();
result.checkInvariants();
return result;
} } | public class class_name {
public SimpleBitSet get(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
checkInvariants();
int len = length();
// If no set bits in range return empty bitset
if (len <= fromIndex || fromIndex == toIndex)
return new SimpleBitSet(0);
// An optimization
if (toIndex > len)
toIndex = len;
SimpleBitSet result = new SimpleBitSet(toIndex - fromIndex);
int targetWords = wordIndex(toIndex - fromIndex - 1) + 1;
int sourceIndex = wordIndex(fromIndex);
boolean wordAligned = ((fromIndex & BIT_INDEX_MASK) == 0);
// Process all words but the last word
for (int i = 0; i < targetWords - 1; i++, sourceIndex++) {
result.words[i] = (wordAligned ? words[sourceIndex]
: (words[sourceIndex] >>> fromIndex)
| (words[sourceIndex + 1] << -fromIndex)); // depends on control dependency: [for], data = [i]
}
// Process the last word
long lastWordMask = (WORD_MASK >>> -toIndex);
result.words[targetWords - 1] = (((toIndex - 1) & BIT_INDEX_MASK) < (fromIndex & BIT_INDEX_MASK)
? ((words[sourceIndex] >>> fromIndex) | (words[sourceIndex + 1] & lastWordMask) << -fromIndex)
: ((words[sourceIndex] & lastWordMask) >>> fromIndex));
// Set wordsInUse correctly
result.wordsInUse = targetWords;
result.recalculateWordsInUse();
result.checkInvariants();
return result;
} } |
public class class_name {
public IPv6AddressPool allocate()
{
if (!isExhausted())
{
// get the first range of free subnets, and take the first subnet of that range
final IPv6AddressRange firstFreeRange = freeRanges.first();
final IPv6Network allocated = IPv6Network.fromAddressAndMask(firstFreeRange.getFirst(), allocationSubnetSize);
return doAllocate(allocated, firstFreeRange);
}
else
{
// exhausted
return null;
}
} } | public class class_name {
public IPv6AddressPool allocate()
{
if (!isExhausted())
{
// get the first range of free subnets, and take the first subnet of that range
final IPv6AddressRange firstFreeRange = freeRanges.first();
final IPv6Network allocated = IPv6Network.fromAddressAndMask(firstFreeRange.getFirst(), allocationSubnetSize);
return doAllocate(allocated, firstFreeRange); // depends on control dependency: [if], data = [none]
}
else
{
// exhausted
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private DateColumn fillWith(int count, Iterator<LocalDate> iterator, Consumer<LocalDate> acceptor) {
for (int r = 0; r < count; r++) {
if (!iterator.hasNext()) {
break;
}
acceptor.accept(iterator.next());
}
return this;
} } | public class class_name {
private DateColumn fillWith(int count, Iterator<LocalDate> iterator, Consumer<LocalDate> acceptor) {
for (int r = 0; r < count; r++) {
if (!iterator.hasNext()) {
break;
}
acceptor.accept(iterator.next()); // depends on control dependency: [for], data = [none]
}
return this;
} } |
public class class_name {
public static String replaceTokens(String template, Pattern pattern,
Map<String, String> replacements) {
StringBuffer sb = new StringBuffer();
Matcher matcher = pattern.matcher(template);
while (matcher.find()) {
String replacement = replacements.get(matcher.group(1));
if (replacement == null) {
replacement = "";
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(sb);
return sb.toString();
} } | public class class_name {
public static String replaceTokens(String template, Pattern pattern,
Map<String, String> replacements) {
StringBuffer sb = new StringBuffer();
Matcher matcher = pattern.matcher(template);
while (matcher.find()) {
String replacement = replacements.get(matcher.group(1));
if (replacement == null) {
replacement = ""; // depends on control dependency: [if], data = [none]
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement)); // depends on control dependency: [while], data = [none]
}
matcher.appendTail(sb);
return sb.toString();
} } |
public class class_name {
public SipURI getLocalSipURI(String transport) {
checkState();
SipUri sipURI = localSipURIs.get(transport);
if (sipURI == null) {
ListeningPoint lp = getListeningPoint(transport);
if (lp != null) {
sipURI = new SipUri();
try {
sipURI.setHost(lp.getIPAddress());
sipURI.setTransportParam(transport);
} catch (ParseException e) {
tracer.severe("Failed to create local sip uri for transport "+transport,e);
}
sipURI.setPort(lp.getPort());
localSipURIs.put(transport, sipURI);
}
}
return sipURI;
} } | public class class_name {
public SipURI getLocalSipURI(String transport) {
checkState();
SipUri sipURI = localSipURIs.get(transport);
if (sipURI == null) {
ListeningPoint lp = getListeningPoint(transport);
if (lp != null) {
sipURI = new SipUri(); // depends on control dependency: [if], data = [none]
try {
sipURI.setHost(lp.getIPAddress()); // depends on control dependency: [try], data = [none]
sipURI.setTransportParam(transport); // depends on control dependency: [try], data = [none]
} catch (ParseException e) {
tracer.severe("Failed to create local sip uri for transport "+transport,e);
} // depends on control dependency: [catch], data = [none]
sipURI.setPort(lp.getPort()); // depends on control dependency: [if], data = [(lp]
localSipURIs.put(transport, sipURI); // depends on control dependency: [if], data = [none]
}
}
return sipURI;
} } |
public class class_name {
private final V finish_removal(BinTreeNode<K,V> node, BinTreeNode<K,V> prev,
int son, BinTreeNode<K,V> m) {
if(m != null) { // set up the links for m
m.left = node.left;
m.right = node.right;
}
if(prev == null)
root = m;
else {
if(son == 0)
prev.left = m;
else
prev.right = m;
}
return node.value;
} } | public class class_name {
private final V finish_removal(BinTreeNode<K,V> node, BinTreeNode<K,V> prev,
int son, BinTreeNode<K,V> m) {
if(m != null) { // set up the links for m
m.left = node.left; // depends on control dependency: [if], data = [none]
m.right = node.right; // depends on control dependency: [if], data = [none]
}
if(prev == null)
root = m;
else {
if(son == 0)
prev.left = m;
else
prev.right = m;
}
return node.value;
} } |
public class class_name {
public Attribute getAttribute(final int index) {
if (attributes == null) {
return null;
}
if ((index < 0) || (index >= attributes.size())) {
return null;
}
return attributes.get(index);
} } | public class class_name {
public Attribute getAttribute(final int index) {
if (attributes == null) {
return null; // depends on control dependency: [if], data = [none]
}
if ((index < 0) || (index >= attributes.size())) {
return null; // depends on control dependency: [if], data = [none]
}
return attributes.get(index);
} } |
public class class_name {
@SuppressWarnings("unchecked")
private Spliterator<?> sourceSpliterator(int terminalFlags) {
// Get the source spliterator of the pipeline
Spliterator<?> spliterator = null;
if (sourceStage.sourceSpliterator != null) {
spliterator = sourceStage.sourceSpliterator;
sourceStage.sourceSpliterator = null;
}
else if (sourceStage.sourceSupplier != null) {
spliterator = (Spliterator<?>) sourceStage.sourceSupplier.get();
sourceStage.sourceSupplier = null;
}
else {
throw new IllegalStateException(MSG_CONSUMED);
}
if (isParallel() && sourceStage.sourceAnyStateful) {
// Adapt the source spliterator, evaluating each stateful op
// in the pipeline up to and including this pipeline stage.
// The depth and flags of each pipeline stage are adjusted accordingly.
int depth = 1;
for (@SuppressWarnings("rawtypes") AbstractPipeline u = sourceStage, p = sourceStage.nextStage, e = this;
u != e;
u = p, p = p.nextStage) {
int thisOpFlags = p.sourceOrOpFlags;
if (p.opIsStateful()) {
depth = 0;
if (StreamOpFlag.SHORT_CIRCUIT.isKnown(thisOpFlags)) {
// Clear the short circuit flag for next pipeline stage
// This stage encapsulates short-circuiting, the next
// stage may not have any short-circuit operations, and
// if so spliterator.forEachRemaining should be used
// for traversal
thisOpFlags = thisOpFlags & ~StreamOpFlag.IS_SHORT_CIRCUIT;
}
spliterator = p.opEvaluateParallelLazy(u, spliterator);
// Inject or clear SIZED on the source pipeline stage
// based on the stage's spliterator
thisOpFlags = spliterator.hasCharacteristics(Spliterator.SIZED)
? (thisOpFlags & ~StreamOpFlag.NOT_SIZED) | StreamOpFlag.IS_SIZED
: (thisOpFlags & ~StreamOpFlag.IS_SIZED) | StreamOpFlag.NOT_SIZED;
}
p.depth = depth++;
p.combinedFlags = StreamOpFlag.combineOpFlags(thisOpFlags, u.combinedFlags);
}
}
if (terminalFlags != 0) {
// Apply flags from the terminal operation to last pipeline stage
combinedFlags = StreamOpFlag.combineOpFlags(terminalFlags, combinedFlags);
}
return spliterator;
} } | public class class_name {
@SuppressWarnings("unchecked")
private Spliterator<?> sourceSpliterator(int terminalFlags) {
// Get the source spliterator of the pipeline
Spliterator<?> spliterator = null;
if (sourceStage.sourceSpliterator != null) {
spliterator = sourceStage.sourceSpliterator; // depends on control dependency: [if], data = [none]
sourceStage.sourceSpliterator = null; // depends on control dependency: [if], data = [none]
}
else if (sourceStage.sourceSupplier != null) {
spliterator = (Spliterator<?>) sourceStage.sourceSupplier.get(); // depends on control dependency: [if], data = [none]
sourceStage.sourceSupplier = null; // depends on control dependency: [if], data = [none]
}
else {
throw new IllegalStateException(MSG_CONSUMED);
}
if (isParallel() && sourceStage.sourceAnyStateful) {
// Adapt the source spliterator, evaluating each stateful op
// in the pipeline up to and including this pipeline stage.
// The depth and flags of each pipeline stage are adjusted accordingly.
int depth = 1;
for (@SuppressWarnings("rawtypes") AbstractPipeline u = sourceStage, p = sourceStage.nextStage, e = this;
u != e;
u = p, p = p.nextStage) {
int thisOpFlags = p.sourceOrOpFlags;
if (p.opIsStateful()) {
depth = 0; // depends on control dependency: [if], data = [none]
if (StreamOpFlag.SHORT_CIRCUIT.isKnown(thisOpFlags)) {
// Clear the short circuit flag for next pipeline stage
// This stage encapsulates short-circuiting, the next
// stage may not have any short-circuit operations, and
// if so spliterator.forEachRemaining should be used
// for traversal
thisOpFlags = thisOpFlags & ~StreamOpFlag.IS_SHORT_CIRCUIT; // depends on control dependency: [if], data = [none]
}
spliterator = p.opEvaluateParallelLazy(u, spliterator); // depends on control dependency: [if], data = [none]
// Inject or clear SIZED on the source pipeline stage
// based on the stage's spliterator
thisOpFlags = spliterator.hasCharacteristics(Spliterator.SIZED)
? (thisOpFlags & ~StreamOpFlag.NOT_SIZED) | StreamOpFlag.IS_SIZED
: (thisOpFlags & ~StreamOpFlag.IS_SIZED) | StreamOpFlag.NOT_SIZED; // depends on control dependency: [if], data = [none]
}
p.depth = depth++; // depends on control dependency: [for], data = [none]
p.combinedFlags = StreamOpFlag.combineOpFlags(thisOpFlags, u.combinedFlags); // depends on control dependency: [for], data = [u]
}
}
if (terminalFlags != 0) {
// Apply flags from the terminal operation to last pipeline stage
combinedFlags = StreamOpFlag.combineOpFlags(terminalFlags, combinedFlags); // depends on control dependency: [if], data = [(terminalFlags]
}
return spliterator;
} } |
public class class_name {
public void setFilters(java.util.Collection<InventoryFilter> filters) {
if (filters == null) {
this.filters = null;
return;
}
this.filters = new java.util.ArrayList<InventoryFilter>(filters);
} } | public class class_name {
public void setFilters(java.util.Collection<InventoryFilter> filters) {
if (filters == null) {
this.filters = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.filters = new java.util.ArrayList<InventoryFilter>(filters);
} } |
public class class_name {
public Routes add(Routes routes) {
routes.config();
/**
* 如果子 Routes 没有配置 mappingSuperClass,则使用顶层 Routes 的配置
* 主要是为了让 jfinal weixin 用户有更好的体验
*
* 因为顶层 Routes 和模块级 Routes 配置都可以生效,减少学习成本
*/
if (routes.mappingSuperClass == null) {
routes.mappingSuperClass = this.mappingSuperClass;
}
routesList.add(routes);
return this;
} } | public class class_name {
public Routes add(Routes routes) {
routes.config();
/**
* 如果子 Routes 没有配置 mappingSuperClass,则使用顶层 Routes 的配置
* 主要是为了让 jfinal weixin 用户有更好的体验
*
* 因为顶层 Routes 和模块级 Routes 配置都可以生效,减少学习成本
*/
if (routes.mappingSuperClass == null) {
routes.mappingSuperClass = this.mappingSuperClass;
// depends on control dependency: [if], data = [none]
}
routesList.add(routes);
return this;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.