code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private List<SimulatorEvent> handleHeartbeatResponse(HeartbeatResponse response,
long now) {
if (LOG.isDebugEnabled()) {
LOG.debug("Handling heartbeat response " + response);
}
List<SimulatorEvent> events = new ArrayList<SimulatorEvent>();
TaskTrackerAction[] actions = response.getActions();
for (TaskTrackerAction action : actions) {
List<SimulatorEvent> actionEvents;
if (action instanceof SimulatorLaunchTaskAction) {
actionEvents = handleSimulatorLaunchTaskAction(
(SimulatorLaunchTaskAction)action, now);
} else if(action instanceof KillTaskAction) {
actionEvents = handleKillTaskAction((KillTaskAction)action, now);
} else if(action instanceof AllMapsCompletedTaskAction) {
// our extra task action for notifying the reducers
actionEvents = handleAllMapsCompletedTaskAction(
(AllMapsCompletedTaskAction)action, now);
} else {
// Should never get here.
// CommitTaskAction is not implemented in the simulator
// LaunchTaskAction has to be SimulatorLaunchTaskAction
throw new UnsupportedOperationException("Unimplemented TaskAction: "
+ action);
}
events.addAll(actionEvents);
}
return events;
} } | public class class_name {
private List<SimulatorEvent> handleHeartbeatResponse(HeartbeatResponse response,
long now) {
if (LOG.isDebugEnabled()) {
LOG.debug("Handling heartbeat response " + response); // depends on control dependency: [if], data = [none]
}
List<SimulatorEvent> events = new ArrayList<SimulatorEvent>();
TaskTrackerAction[] actions = response.getActions();
for (TaskTrackerAction action : actions) {
List<SimulatorEvent> actionEvents;
if (action instanceof SimulatorLaunchTaskAction) {
actionEvents = handleSimulatorLaunchTaskAction(
(SimulatorLaunchTaskAction)action, now); // depends on control dependency: [if], data = [none]
} else if(action instanceof KillTaskAction) {
actionEvents = handleKillTaskAction((KillTaskAction)action, now); // depends on control dependency: [if], data = [none]
} else if(action instanceof AllMapsCompletedTaskAction) {
// our extra task action for notifying the reducers
actionEvents = handleAllMapsCompletedTaskAction(
(AllMapsCompletedTaskAction)action, now); // depends on control dependency: [if], data = [none]
} else {
// Should never get here.
// CommitTaskAction is not implemented in the simulator
// LaunchTaskAction has to be SimulatorLaunchTaskAction
throw new UnsupportedOperationException("Unimplemented TaskAction: "
+ action);
}
events.addAll(actionEvents); // depends on control dependency: [for], data = [action]
}
return events;
} } |
public class class_name {
public static Boolean getBoolean(String propertyName, String envName, Boolean defaultValue) {
checkEnvName(envName);
Boolean propertyValue = BooleanUtil.toBooleanObject(System.getProperty(propertyName), null);
if (propertyValue != null) {
return propertyValue;
} else {
propertyValue = BooleanUtil.toBooleanObject(System.getenv(envName), null);
return propertyValue != null ? propertyValue : defaultValue;
}
} } | public class class_name {
public static Boolean getBoolean(String propertyName, String envName, Boolean defaultValue) {
checkEnvName(envName);
Boolean propertyValue = BooleanUtil.toBooleanObject(System.getProperty(propertyName), null);
if (propertyValue != null) {
return propertyValue; // depends on control dependency: [if], data = [none]
} else {
propertyValue = BooleanUtil.toBooleanObject(System.getenv(envName), null); // depends on control dependency: [if], data = [null)]
return propertyValue != null ? propertyValue : defaultValue; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
EditText generatePinBox(int i, int inputType) {
EditText editText = (EditText) LayoutInflater.from(getContext()).inflate(R.layout.partial_pin_box, this, false);
int generateViewId = PinViewUtils.generateViewId();
editText.setId(generateViewId);
editText.setTag(i);
if (inputType != -1) {
editText.setInputType(inputType);
}
setStylePinBox(editText);
editText.addTextChangedListener(this);
editText.setOnFocusChangeListener(this);
pinBoxesIds[i] = generateViewId;
return editText;
} } | public class class_name {
EditText generatePinBox(int i, int inputType) {
EditText editText = (EditText) LayoutInflater.from(getContext()).inflate(R.layout.partial_pin_box, this, false);
int generateViewId = PinViewUtils.generateViewId();
editText.setId(generateViewId);
editText.setTag(i);
if (inputType != -1) {
editText.setInputType(inputType); // depends on control dependency: [if], data = [(inputType]
}
setStylePinBox(editText);
editText.addTextChangedListener(this);
editText.setOnFocusChangeListener(this);
pinBoxesIds[i] = generateViewId;
return editText;
} } |
public class class_name {
public void synchronizeTokens(Endpoint tokenEndPoint) {
Integer subscriptionId = tokenEndPoint.getSubscriptionId();
String partnerAuthorizationToken = tokenEndPoint.getSubscription().getPartnerAuthorizationToken();
String lastSyncDate = getLastSyncDate(subscriptionId);
int totalCount = 1;
int numberRetrieved = 0;
Date startOfSync = new Date();
while (totalCount > numberRetrieved) {
String tokenUrl = tokenEndPoint.getUrl();
tokenUrl += "?offset=" + numberRetrieved + "&limit=" + PAGE_SIZE;
if (lastSyncDate != null) {
tokenUrl += "&date_from=" + lastSyncDate;
}
LOG.info("Get tokens at endpoint: " + tokenUrl);
TokenResponse tokenResponse = (TokenResponse) doRequest(new HttpGet(tokenUrl), partnerAuthorizationToken, TokenResponse.class);
if (tokenResponse.totalCount == null) {
break;
}
totalCount = tokenResponse.totalCount;
numberRetrieved += tokenResponse.data.size();
LOG.info("Inserting " + tokenResponse.data.size() + " tokens");
for (io.motown.ocpi.dto.Token token : tokenResponse.data) {
insertOrUpdateToken(token, subscriptionId);
}
}
updateLastSynchronizationDate(startOfSync, subscriptionId);
LOG.info("Number of tokens retrieved: " + numberRetrieved);
} } | public class class_name {
public void synchronizeTokens(Endpoint tokenEndPoint) {
Integer subscriptionId = tokenEndPoint.getSubscriptionId();
String partnerAuthorizationToken = tokenEndPoint.getSubscription().getPartnerAuthorizationToken();
String lastSyncDate = getLastSyncDate(subscriptionId);
int totalCount = 1;
int numberRetrieved = 0;
Date startOfSync = new Date();
while (totalCount > numberRetrieved) {
String tokenUrl = tokenEndPoint.getUrl();
tokenUrl += "?offset=" + numberRetrieved + "&limit=" + PAGE_SIZE; // depends on control dependency: [while], data = [none]
if (lastSyncDate != null) {
tokenUrl += "&date_from=" + lastSyncDate; // depends on control dependency: [if], data = [none]
}
LOG.info("Get tokens at endpoint: " + tokenUrl); // depends on control dependency: [while], data = [none]
TokenResponse tokenResponse = (TokenResponse) doRequest(new HttpGet(tokenUrl), partnerAuthorizationToken, TokenResponse.class);
if (tokenResponse.totalCount == null) {
break;
}
totalCount = tokenResponse.totalCount; // depends on control dependency: [while], data = [none]
numberRetrieved += tokenResponse.data.size(); // depends on control dependency: [while], data = [none]
LOG.info("Inserting " + tokenResponse.data.size() + " tokens"); // depends on control dependency: [while], data = [none]
for (io.motown.ocpi.dto.Token token : tokenResponse.data) {
insertOrUpdateToken(token, subscriptionId); // depends on control dependency: [for], data = [token]
}
}
updateLastSynchronizationDate(startOfSync, subscriptionId);
LOG.info("Number of tokens retrieved: " + numberRetrieved);
} } |
public class class_name {
@Override public void transactionCreated(AbstractTransaction transaction, CreatedBy createdBy) {
activeTransactionCountUpdater.incrementAndGet(this);
try {
transaction.registerSynchronization(this);
} catch (RollbackException | IllegalStateException e) {
// it means the transaction is marked for rollback, or is prepared for commit, at this point we cannot register synchronization
decrementTransactionCount();
} catch (SystemException e) {
decrementTransactionCount();
EjbLogger.ROOT_LOGGER.debug("Unexpected exception", e);
throw new RuntimeException(e);
}
} } | public class class_name {
@Override public void transactionCreated(AbstractTransaction transaction, CreatedBy createdBy) {
activeTransactionCountUpdater.incrementAndGet(this);
try {
transaction.registerSynchronization(this); // depends on control dependency: [try], data = [none]
} catch (RollbackException | IllegalStateException e) {
// it means the transaction is marked for rollback, or is prepared for commit, at this point we cannot register synchronization
decrementTransactionCount();
} catch (SystemException e) { // depends on control dependency: [catch], data = [none]
decrementTransactionCount();
EjbLogger.ROOT_LOGGER.debug("Unexpected exception", e);
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
static Object logModule(boolean quiet, boolean verbose) {
checkArgument(!(quiet && verbose), "quiet and verbose flags cannot be used at the same time!");
Logger.Level logLevel;
if (quiet) {
return null;
} else if (verbose) {
logLevel = Logger.Level.FULL;
} else {
logLevel = Logger.Level.BASIC;
}
return new LogModule(logLevel);
} } | public class class_name {
static Object logModule(boolean quiet, boolean verbose) {
checkArgument(!(quiet && verbose), "quiet and verbose flags cannot be used at the same time!");
Logger.Level logLevel;
if (quiet) {
return null; // depends on control dependency: [if], data = [none]
} else if (verbose) {
logLevel = Logger.Level.FULL; // depends on control dependency: [if], data = [none]
} else {
logLevel = Logger.Level.BASIC; // depends on control dependency: [if], data = [none]
}
return new LogModule(logLevel);
} } |
public class class_name {
private static boolean hasMoreTagsToResolve(ObjectType objectType) {
checkArgument(objectType.isUnknownType());
FunctionType ctor = objectType.getConstructor();
if (ctor != null) {
// interface extends interfaces
for (ObjectType interfaceType : ctor.getExtendedInterfaces()) {
if (!interfaceType.isResolved()) {
return true;
}
}
}
if (objectType.getImplicitPrototype() != null) {
// constructor extends class
return !objectType.getImplicitPrototype().isResolved();
}
return false;
} } | public class class_name {
private static boolean hasMoreTagsToResolve(ObjectType objectType) {
checkArgument(objectType.isUnknownType());
FunctionType ctor = objectType.getConstructor();
if (ctor != null) {
// interface extends interfaces
for (ObjectType interfaceType : ctor.getExtendedInterfaces()) {
if (!interfaceType.isResolved()) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
if (objectType.getImplicitPrototype() != null) {
// constructor extends class
return !objectType.getImplicitPrototype().isResolved(); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void marshall(GetDashboardEmbedUrlRequest getDashboardEmbedUrlRequest, ProtocolMarshaller protocolMarshaller) {
if (getDashboardEmbedUrlRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getAwsAccountId(), AWSACCOUNTID_BINDING);
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getDashboardId(), DASHBOARDID_BINDING);
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getIdentityType(), IDENTITYTYPE_BINDING);
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getSessionLifetimeInMinutes(), SESSIONLIFETIMEINMINUTES_BINDING);
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getUndoRedoDisabled(), UNDOREDODISABLED_BINDING);
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getResetDisabled(), RESETDISABLED_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetDashboardEmbedUrlRequest getDashboardEmbedUrlRequest, ProtocolMarshaller protocolMarshaller) {
if (getDashboardEmbedUrlRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getAwsAccountId(), AWSACCOUNTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getDashboardId(), DASHBOARDID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getIdentityType(), IDENTITYTYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getSessionLifetimeInMinutes(), SESSIONLIFETIMEINMINUTES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getUndoRedoDisabled(), UNDOREDODISABLED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getDashboardEmbedUrlRequest.getResetDisabled(), RESETDISABLED_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 Packet getNextPacket() {
Packet parsedPacket = parseNextPacketFromPdml();
if ( parsedPacket == null ) { // All packets have been read
return null;
}
parsedPacket = addTcpdumpInfoToPacket(parsedPacket);
return parsedPacket;
} } | public class class_name {
public Packet getNextPacket() {
Packet parsedPacket = parseNextPacketFromPdml();
if ( parsedPacket == null ) { // All packets have been read
return null; // depends on control dependency: [if], data = [none]
}
parsedPacket = addTcpdumpInfoToPacket(parsedPacket);
return parsedPacket;
} } |
public class class_name {
@PutMapping("/syncSwitch/{destination}/{status}")
public Result etl(@PathVariable String destination, @PathVariable String status) {
if (status.equals("on")) {
syncSwitch.on(destination);
logger.info("#Destination: {} sync on", destination);
return Result.createSuccess("实例: " + destination + " 开启同步成功");
} else if (status.equals("off")) {
syncSwitch.off(destination);
logger.info("#Destination: {} sync off", destination);
return Result.createSuccess("实例: " + destination + " 关闭同步成功");
} else {
Result result = new Result();
result.setCode(50000);
result.setMessage("实例: " + destination + " 操作失败");
return result;
}
} } | public class class_name {
@PutMapping("/syncSwitch/{destination}/{status}")
public Result etl(@PathVariable String destination, @PathVariable String status) {
if (status.equals("on")) {
syncSwitch.on(destination); // depends on control dependency: [if], data = [none]
logger.info("#Destination: {} sync on", destination); // depends on control dependency: [if], data = [none]
return Result.createSuccess("实例: " + destination + " 开启同步成功"); // depends on control dependency: [if], data = [none]
} else if (status.equals("off")) {
syncSwitch.off(destination); // depends on control dependency: [if], data = [none]
logger.info("#Destination: {} sync off", destination); // depends on control dependency: [if], data = [none]
return Result.createSuccess("实例: " + destination + " 关闭同步成功"); // depends on control dependency: [if], data = [none]
} else {
Result result = new Result();
result.setCode(50000); // depends on control dependency: [if], data = [none]
result.setMessage("实例: " + destination + " 操作失败"); // depends on control dependency: [if], data = [none]
return result; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private final int m() {
int n = 0;
int i = 0;
while (true) {
if (i > j) {
return n;
}
if (!isConsonant(i)) {
break;
}
i++;
}
i++;
while (true) {
while (true) {
if (i > j) {
return n;
}
if (isConsonant(i)) {
break;
}
i++;
}
i++;
n++;
while (true) {
if (i > j) {
return n;
}
if (!isConsonant(i)) {
break;
}
i++;
}
i++;
}
} } | public class class_name {
private final int m() {
int n = 0;
int i = 0;
while (true) {
if (i > j) {
return n; // depends on control dependency: [if], data = [none]
}
if (!isConsonant(i)) {
break;
}
i++; // depends on control dependency: [while], data = [none]
}
i++;
while (true) {
while (true) {
if (i > j) {
return n; // depends on control dependency: [if], data = [none]
}
if (isConsonant(i)) {
break;
}
i++; // depends on control dependency: [while], data = [none]
}
i++; // depends on control dependency: [while], data = [none]
n++; // depends on control dependency: [while], data = [none]
while (true) {
if (i > j) {
return n; // depends on control dependency: [if], data = [none]
}
if (!isConsonant(i)) {
break;
}
i++; // depends on control dependency: [while], data = [none]
}
i++; // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public void setListElementClass(Class<?> listElementClass) {
this.listElementClass = listElementClass;
if(listElementClass.isEnum()){
setPermittedValues(Arrays.asList(listElementClass.getEnumConstants()));
}
} } | public class class_name {
public void setListElementClass(Class<?> listElementClass) {
this.listElementClass = listElementClass;
if(listElementClass.isEnum()){
setPermittedValues(Arrays.asList(listElementClass.getEnumConstants()));
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Optional<Self> mergeWith(Self latter) {
if(latter.position == this.position + this.insertedLength()) {
S removedText = concat(this.removed, latter.removed);
S addedText = concat(this.inserted, latter.inserted);
return Optional.of(create(this.position, removedText, addedText));
} else if(latter.position + latter.removedLength() == this.position + this.insertedLength()) {
if(this.position <= latter.position) {
S addedText = concat(sub(this.inserted, 0, latter.position - this.position), latter.inserted);
return Optional.of(create(this.position, this.removed, addedText));
}
else {
S removedText = concat(sub(latter.removed, 0, this.position - latter.position), this.removed);
return Optional.of(create(latter.position, removedText, latter.inserted));
}
} else {
return Optional.empty();
}
} } | public class class_name {
public Optional<Self> mergeWith(Self latter) {
if(latter.position == this.position + this.insertedLength()) {
S removedText = concat(this.removed, latter.removed);
S addedText = concat(this.inserted, latter.inserted);
return Optional.of(create(this.position, removedText, addedText)); // depends on control dependency: [if], data = [none]
} else if(latter.position + latter.removedLength() == this.position + this.insertedLength()) {
if(this.position <= latter.position) {
S addedText = concat(sub(this.inserted, 0, latter.position - this.position), latter.inserted);
return Optional.of(create(this.position, this.removed, addedText)); // depends on control dependency: [if], data = [(this.position]
}
else {
S removedText = concat(sub(latter.removed, 0, this.position - latter.position), this.removed);
return Optional.of(create(latter.position, removedText, latter.inserted)); // depends on control dependency: [if], data = [none]
}
} else {
return Optional.empty(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> B option(ClientOptionValue<T> optionValue) {
requireNonNull(optionValue, "optionValue");
final ClientOption<?> opt = optionValue.option();
if (opt == ClientOption.DECORATION) {
final ClientDecoration d = (ClientDecoration) optionValue.value();
d.entries().forEach(e -> decoration.add0(e.requestType(), e.responseType(),
(Function) e.decorator()));
} else if (opt == ClientOption.HTTP_HEADERS) {
final HttpHeaders h = (HttpHeaders) optionValue.value();
setHttpHeaders(h);
} else {
options.put(opt, optionValue);
}
return self();
} } | public class class_name {
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> B option(ClientOptionValue<T> optionValue) {
requireNonNull(optionValue, "optionValue");
final ClientOption<?> opt = optionValue.option();
if (opt == ClientOption.DECORATION) {
final ClientDecoration d = (ClientDecoration) optionValue.value();
d.entries().forEach(e -> decoration.add0(e.requestType(), e.responseType(),
(Function) e.decorator())); // depends on control dependency: [if], data = [none]
} else if (opt == ClientOption.HTTP_HEADERS) {
final HttpHeaders h = (HttpHeaders) optionValue.value();
setHttpHeaders(h); // depends on control dependency: [if], data = [none]
} else {
options.put(opt, optionValue); // depends on control dependency: [if], data = [(opt]
}
return self();
} } |
public class class_name {
public Element endElementBuilder() {
final Element element = (Element) this.configurationStack.removeLast();
if ( this.characters != null ) {
element.appendChild( this.document.createTextNode( this.characters.toString() ) );
}
this.characters = null;
return element;
} } | public class class_name {
public Element endElementBuilder() {
final Element element = (Element) this.configurationStack.removeLast();
if ( this.characters != null ) {
element.appendChild( this.document.createTextNode( this.characters.toString() ) ); // depends on control dependency: [if], data = [( this.characters]
}
this.characters = null;
return element;
} } |
public class class_name {
public Bbox intersection(Bbox other) {
if (!this.intersects(other)) {
return null;
} else {
double minx = other.getX() > this.getX() ? other.getX() : this.getX();
double maxx = other.getEndPoint().getX() < this.getEndPoint().getX() ? other.getEndPoint().getX() : this
.getEndPoint().getX();
double miny = other.getY() > this.getY() ? other.getY() : this.getY();
double maxy = other.getEndPoint().getY() < this.getEndPoint().getY() ? other.getEndPoint().getY() : this
.getEndPoint().getY();
return new Bbox(minx, miny, (maxx - minx), (maxy - miny));
}
} } | public class class_name {
public Bbox intersection(Bbox other) {
if (!this.intersects(other)) {
return null; // depends on control dependency: [if], data = [none]
} else {
double minx = other.getX() > this.getX() ? other.getX() : this.getX();
double maxx = other.getEndPoint().getX() < this.getEndPoint().getX() ? other.getEndPoint().getX() : this
.getEndPoint().getX();
double miny = other.getY() > this.getY() ? other.getY() : this.getY();
double maxy = other.getEndPoint().getY() < this.getEndPoint().getY() ? other.getEndPoint().getY() : this
.getEndPoint().getY();
return new Bbox(minx, miny, (maxx - minx), (maxy - miny)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static String resolveEnvVar(String envVarName, String mode, boolean bc) {
final String envVarValue = System.getenv(envVarName);
if(envVarValue == null || envVarValue.isEmpty()) {
if(mode != null && mode.startsWith(":-") && mode.length() > 2) {
return bc?Hasher.hash(mode.substring(2).toCharArray()):mode.substring(2);
} else {
return null;
}
} else {
return bc?Hasher.hash(envVarValue.toCharArray()):envVarValue;
}
} } | public class class_name {
private static String resolveEnvVar(String envVarName, String mode, boolean bc) {
final String envVarValue = System.getenv(envVarName);
if(envVarValue == null || envVarValue.isEmpty()) {
if(mode != null && mode.startsWith(":-") && mode.length() > 2) {
return bc?Hasher.hash(mode.substring(2).toCharArray()):mode.substring(2); // depends on control dependency: [if], data = [(mode]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} else {
return bc?Hasher.hash(envVarValue.toCharArray()):envVarValue; // depends on control dependency: [if], data = [(envVarValue]
}
} } |
public class class_name {
public static CoreMap getMergedChunk(List<? extends CoreMap> chunkList,
int chunkIndexStart, int chunkIndexEnd,
Map<Class, CoreMapAttributeAggregator> aggregators)
{
CoreMap newChunk = new Annotation("");
for (Map.Entry<Class,CoreMapAttributeAggregator> entry:aggregators.entrySet()) {
if (chunkIndexEnd > chunkList.size()) {
assert(false);
}
Object value = entry.getValue().aggregate(entry.getKey(), chunkList.subList(chunkIndexStart, chunkIndexEnd));
newChunk.set(entry.getKey(), value);
}
return newChunk;
} } | public class class_name {
public static CoreMap getMergedChunk(List<? extends CoreMap> chunkList,
int chunkIndexStart, int chunkIndexEnd,
Map<Class, CoreMapAttributeAggregator> aggregators)
{
CoreMap newChunk = new Annotation("");
for (Map.Entry<Class,CoreMapAttributeAggregator> entry:aggregators.entrySet()) {
if (chunkIndexEnd > chunkList.size()) {
assert(false);
// depends on control dependency: [if], data = [none]
}
Object value = entry.getValue().aggregate(entry.getKey(), chunkList.subList(chunkIndexStart, chunkIndexEnd));
newChunk.set(entry.getKey(), value);
// depends on control dependency: [for], data = [entry]
}
return newChunk;
} } |
public class class_name {
@Override
void findReferencedClassNames(final Set<String> classNameListOut) {
for (final TypeParameter typeParameter : typeParameters) {
if (typeParameter != null) {
typeParameter.findReferencedClassNames(classNameListOut);
}
}
for (final TypeSignature typeSignature : parameterTypeSignatures) {
if (typeSignature != null) {
typeSignature.findReferencedClassNames(classNameListOut);
}
}
resultType.findReferencedClassNames(classNameListOut);
for (final ClassRefOrTypeVariableSignature typeSignature : throwsSignatures) {
if (typeSignature != null) {
typeSignature.findReferencedClassNames(classNameListOut);
}
}
} } | public class class_name {
@Override
void findReferencedClassNames(final Set<String> classNameListOut) {
for (final TypeParameter typeParameter : typeParameters) {
if (typeParameter != null) {
typeParameter.findReferencedClassNames(classNameListOut); // depends on control dependency: [if], data = [none]
}
}
for (final TypeSignature typeSignature : parameterTypeSignatures) {
if (typeSignature != null) {
typeSignature.findReferencedClassNames(classNameListOut); // depends on control dependency: [if], data = [none]
}
}
resultType.findReferencedClassNames(classNameListOut);
for (final ClassRefOrTypeVariableSignature typeSignature : throwsSignatures) {
if (typeSignature != null) {
typeSignature.findReferencedClassNames(classNameListOut); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public R quietCall() {
try {
return call();
} catch (ExecutionException e) {
log.error(e.getMessage(), e);
} catch (RetryException e) {
log.warn(e.getMessage());
}
return null;
} } | public class class_name {
public R quietCall() {
try {
return call(); // depends on control dependency: [try], data = [none]
} catch (ExecutionException e) {
log.error(e.getMessage(), e);
} catch (RetryException e) { // depends on control dependency: [catch], data = [none]
log.warn(e.getMessage());
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
@Override
public final boolean hasNext() {
resetToLastKey();
if (mFirst) {
mFirst = false;
moveTo(ROOT_NODE);
return true;
} else {
resetToStartKey();
return false;
}
} } | public class class_name {
@Override
public final boolean hasNext() {
resetToLastKey();
if (mFirst) {
mFirst = false; // depends on control dependency: [if], data = [none]
moveTo(ROOT_NODE); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
} else {
resetToStartKey(); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Observable<ServiceResponse<PolicyDefinitionInner>> getAtManagementGroupWithServiceResponseAsync(String policyDefinitionName, String managementGroupId) {
if (policyDefinitionName == null) {
throw new IllegalArgumentException("Parameter policyDefinitionName is required and cannot be null.");
}
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.getAtManagementGroup(policyDefinitionName, managementGroupId, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PolicyDefinitionInner>>>() {
@Override
public Observable<ServiceResponse<PolicyDefinitionInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PolicyDefinitionInner> clientResponse = getAtManagementGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<PolicyDefinitionInner>> getAtManagementGroupWithServiceResponseAsync(String policyDefinitionName, String managementGroupId) {
if (policyDefinitionName == null) {
throw new IllegalArgumentException("Parameter policyDefinitionName is required and cannot be null.");
}
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.getAtManagementGroup(policyDefinitionName, managementGroupId, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PolicyDefinitionInner>>>() {
@Override
public Observable<ServiceResponse<PolicyDefinitionInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PolicyDefinitionInner> clientResponse = getAtManagementGroupDelegate(response);
return Observable.just(clientResponse); // 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 double trace() {
double result = 0.0;
for (int i = 0; i < rows; i++) {
result += get(i, i);
}
return result;
} } | public class class_name {
public double trace() {
double result = 0.0;
for (int i = 0; i < rows; i++) {
result += get(i, i); // depends on control dependency: [for], data = [i]
}
return result;
} } |
public class class_name {
private Deferred<TreeMap<byte[], Span>> findSpans() throws HBaseException {
final short metric_width = tsdb.metrics.width();
final TreeMap<byte[], Span> spans = // The key is a row key from HBase.
new TreeMap<byte[], Span>(new SpanCmp(
(short)(Const.SALT_WIDTH() + metric_width)));
// Copy only the filters that should trigger a tag resolution. If this list
// is empty due to literals or a wildcard star, then we'll save a TON of
// UID lookups
final List<TagVFilter> scanner_filters;
if (filters != null) {
scanner_filters = new ArrayList<TagVFilter>(filters.size());
for (final TagVFilter filter : filters) {
if (filter.postScan()) {
scanner_filters.add(filter);
}
}
} else {
scanner_filters = null;
}
if (Const.SALT_WIDTH() > 0) {
final List<Scanner> scanners = new ArrayList<Scanner>(Const.SALT_BUCKETS());
for (int i = 0; i < Const.SALT_BUCKETS(); i++) {
scanners.add(getScanner(i));
}
scan_start_time = DateTime.nanoTime();
return new SaltScanner(tsdb, metric, scanners, spans, scanner_filters,
delete, rollup_query, query_stats, query_index, null,
max_bytes, max_data_points).scan();
} else {
final List<Scanner> scanners = new ArrayList<Scanner>(1);
scanners.add(getScanner(0));
scan_start_time = DateTime.nanoTime();
return new SaltScanner(tsdb, metric, scanners, spans, scanner_filters,
delete, rollup_query, query_stats, query_index, null, max_bytes,
max_data_points).scan();
}
} } | public class class_name {
private Deferred<TreeMap<byte[], Span>> findSpans() throws HBaseException {
final short metric_width = tsdb.metrics.width();
final TreeMap<byte[], Span> spans = // The key is a row key from HBase.
new TreeMap<byte[], Span>(new SpanCmp(
(short)(Const.SALT_WIDTH() + metric_width)));
// Copy only the filters that should trigger a tag resolution. If this list
// is empty due to literals or a wildcard star, then we'll save a TON of
// UID lookups
final List<TagVFilter> scanner_filters;
if (filters != null) {
scanner_filters = new ArrayList<TagVFilter>(filters.size());
for (final TagVFilter filter : filters) {
if (filter.postScan()) {
scanner_filters.add(filter); // depends on control dependency: [if], data = [none]
}
}
} else {
scanner_filters = null;
}
if (Const.SALT_WIDTH() > 0) {
final List<Scanner> scanners = new ArrayList<Scanner>(Const.SALT_BUCKETS());
for (int i = 0; i < Const.SALT_BUCKETS(); i++) {
scanners.add(getScanner(i));
}
scan_start_time = DateTime.nanoTime();
return new SaltScanner(tsdb, metric, scanners, spans, scanner_filters,
delete, rollup_query, query_stats, query_index, null,
max_bytes, max_data_points).scan();
} else {
final List<Scanner> scanners = new ArrayList<Scanner>(1);
scanners.add(getScanner(0));
scan_start_time = DateTime.nanoTime();
return new SaltScanner(tsdb, metric, scanners, spans, scanner_filters,
delete, rollup_query, query_stats, query_index, null, max_bytes,
max_data_points).scan();
}
} } |
public class class_name {
public ContextItems getMarshaledContext() {
ContextItems marshaledContext = new ContextItems();
for (IManagedContext<?> managedContext : managedContexts) {
marshaledContext.addItems(managedContext.getContextItems(false));
}
return marshaledContext;
} } | public class class_name {
public ContextItems getMarshaledContext() {
ContextItems marshaledContext = new ContextItems();
for (IManagedContext<?> managedContext : managedContexts) {
marshaledContext.addItems(managedContext.getContextItems(false)); // depends on control dependency: [for], data = [managedContext]
}
return marshaledContext;
} } |
public class class_name {
@Override
public void setRequireFeatureWithTolerates(Map<String, Collection<String>> features) {
// No need to copy (like we do in addRequireFeatureWithTolerates)
// as we are overwriting anyway
// need to allow for features being null, for legacy reasons
Collection<RequireFeatureWithTolerates> set = null;
Collection<String> collection = null;
if (features != null) {
set = new HashSet<RequireFeatureWithTolerates>();
collection = new HashSet<String>();
for (Map.Entry<String, Collection<String>> foo : features.entrySet()) {
RequireFeatureWithTolerates feature = new RequireFeatureWithTolerates();
feature.setFeature(foo.getKey());
feature.setTolerates(foo.getValue());
set.add(feature);
collection.add(foo.getKey());
}
}
_asset.getWlpInformation().setRequireFeatureWithTolerates(set);
_asset.getWlpInformation().setRequireFeature(collection);
} } | public class class_name {
@Override
public void setRequireFeatureWithTolerates(Map<String, Collection<String>> features) {
// No need to copy (like we do in addRequireFeatureWithTolerates)
// as we are overwriting anyway
// need to allow for features being null, for legacy reasons
Collection<RequireFeatureWithTolerates> set = null;
Collection<String> collection = null;
if (features != null) {
set = new HashSet<RequireFeatureWithTolerates>(); // depends on control dependency: [if], data = [none]
collection = new HashSet<String>(); // depends on control dependency: [if], data = [none]
for (Map.Entry<String, Collection<String>> foo : features.entrySet()) {
RequireFeatureWithTolerates feature = new RequireFeatureWithTolerates();
feature.setFeature(foo.getKey()); // depends on control dependency: [for], data = [foo]
feature.setTolerates(foo.getValue()); // depends on control dependency: [for], data = [foo]
set.add(feature); // depends on control dependency: [for], data = [none]
collection.add(foo.getKey()); // depends on control dependency: [for], data = [foo]
}
}
_asset.getWlpInformation().setRequireFeatureWithTolerates(set);
_asset.getWlpInformation().setRequireFeature(collection);
} } |
public class class_name {
private Iterable<PersistentNoSqlIdentifierGenerator> getPersistentGenerators() {
Map<String, EntityPersister> entityPersisters = factory.getMetamodel().entityPersisters();
Set<PersistentNoSqlIdentifierGenerator> persistentGenerators = new HashSet<PersistentNoSqlIdentifierGenerator>( entityPersisters.size() );
for ( EntityPersister persister : entityPersisters.values() ) {
if ( persister.getIdentifierGenerator() instanceof PersistentNoSqlIdentifierGenerator ) {
persistentGenerators.add( (PersistentNoSqlIdentifierGenerator) persister.getIdentifierGenerator() );
}
}
return persistentGenerators;
} } | public class class_name {
private Iterable<PersistentNoSqlIdentifierGenerator> getPersistentGenerators() {
Map<String, EntityPersister> entityPersisters = factory.getMetamodel().entityPersisters();
Set<PersistentNoSqlIdentifierGenerator> persistentGenerators = new HashSet<PersistentNoSqlIdentifierGenerator>( entityPersisters.size() );
for ( EntityPersister persister : entityPersisters.values() ) {
if ( persister.getIdentifierGenerator() instanceof PersistentNoSqlIdentifierGenerator ) {
persistentGenerators.add( (PersistentNoSqlIdentifierGenerator) persister.getIdentifierGenerator() ); // depends on control dependency: [if], data = [none]
}
}
return persistentGenerators;
} } |
public class class_name {
@Pure
public boolean intersects(Shape2d<?> rectangle) {
final Shape2d<?> bounds = getBoundingBox();
if (bounds == null) {
return false;
}
return bounds.intersects(rectangle);
} } | public class class_name {
@Pure
public boolean intersects(Shape2d<?> rectangle) {
final Shape2d<?> bounds = getBoundingBox();
if (bounds == null) {
return false; // depends on control dependency: [if], data = [none]
}
return bounds.intersects(rectangle);
} } |
public class class_name {
public void resets()
{
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"resets", "resets");
}
this.in = null;
} } | public class class_name {
public void resets()
{
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"resets", "resets"); // depends on control dependency: [if], data = [none]
}
this.in = null;
} } |
public class class_name {
private void onDataSetModifiedEvent(@Observes DataSetModifiedEvent event) {
checkNotNull("event",
event);
DataSetDef def = event.getDataSetDef();
String targetUUID = event.getDataSetDef().getUUID();
TimeAmount timeFrame = def.getRefreshTimeAmount();
boolean noRealTime = timeFrame == null || timeFrame.toMillis() > 60000;
if ((!def.isRefreshAlways() || noRealTime) && widget != null && widget.feedsFrom(targetUUID)) {
workbenchNotification.fire(new NotificationEvent(AppConstants.INSTANCE.gallerywidget_dataset_modif(),
INFO));
widget.redrawAll();
}
} } | public class class_name {
private void onDataSetModifiedEvent(@Observes DataSetModifiedEvent event) {
checkNotNull("event",
event);
DataSetDef def = event.getDataSetDef();
String targetUUID = event.getDataSetDef().getUUID();
TimeAmount timeFrame = def.getRefreshTimeAmount();
boolean noRealTime = timeFrame == null || timeFrame.toMillis() > 60000;
if ((!def.isRefreshAlways() || noRealTime) && widget != null && widget.feedsFrom(targetUUID)) {
workbenchNotification.fire(new NotificationEvent(AppConstants.INSTANCE.gallerywidget_dataset_modif(),
INFO)); // depends on control dependency: [if], data = [none]
widget.redrawAll(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void connect(final InetSocketAddress localEP, final InetSocketAddress serverCtrlEP,
final CRI cri, final boolean useNAT) throws KNXException, InterruptedException
{
if (state != CLOSED)
throw new IllegalStateException("open connection");
ctrlEndpt = serverCtrlEP;
if (ctrlEndpt.isUnresolved())
throw new KNXException("server control endpoint is unresolved: " + serverCtrlEP);
if (ctrlEndpt.getAddress().isMulticastAddress())
throw new KNXIllegalArgumentException("server control endpoint cannot be a multicast address ("
+ ctrlEndpt.getAddress().getHostAddress() + ")");
useNat = useNAT;
logger = LogService.getLogger("calimero.knxnetip." + getName());
// if we allow localEP to be null, we would create an unbound socket
if (localEP == null)
throw new KNXIllegalArgumentException("no local endpoint specified");
InetSocketAddress local = localEP;
try {
if (local.isUnresolved())
throw new KNXIllegalArgumentException("unresolved address " + local);
if (local.getAddress().isAnyLocalAddress()) {
final InetAddress addr = useNAT ? null
: Optional.ofNullable(serverCtrlEP.getAddress()).flatMap(this::onSameSubnet)
.orElse(InetAddress.getLocalHost());
local = new InetSocketAddress(addr, localEP.getPort());
}
socket = new DatagramSocket(local);
ctrlSocket = socket;
logger.info("establish connection from " + socket.getLocalSocketAddress() + " to " + ctrlEndpt);
// HPAI throws if wildcard local address (0.0.0.0) is supplied
final HPAI hpai = new HPAI(HPAI.IPV4_UDP,
useNat ? null : (InetSocketAddress) socket.getLocalSocketAddress());
final byte[] buf = PacketHelper.toPacket(new ConnectRequest(cri, hpai, hpai));
send(buf, ctrlEndpt);
}
catch (final UnknownHostException e) {
throw new KNXException("no local host address available", e);
}
catch (IOException | SecurityException e) {
if (socket != null)
socket.close();
logger.error("communication failure on connect", e);
if (local.getAddress().isLoopbackAddress())
logger.warn("local endpoint uses loopback address ({}), try with a different IP address",
local.getAddress());
throw new KNXException("connecting from " + local + " to " + serverCtrlEP + ": " + e.getMessage());
}
logger.debug("wait for connect response from " + ctrlEndpt + " ...");
startReceiver();
try {
final boolean changed = waitForStateChange(CLOSED, CONNECT_REQ_TIMEOUT);
if (state == OK) {
heartbeat = new HeartbeatMonitor();
heartbeat.start();
String optionalConnectionInfo = "";
if (tunnelingAddress != null)
optionalConnectionInfo = ", tunneling address " + tunnelingAddress;
logger.info("connection established (data endpoint {}:{}, channel {}{})",
dataEndpt.getAddress().getHostAddress(), dataEndpt.getPort(), channelId,
optionalConnectionInfo);
return;
}
final KNXException e;
if (!changed)
e = new KNXTimeoutException("timeout connecting to control endpoint " + ctrlEndpt);
else if (state == ACK_ERROR)
e = new KNXRemoteException("error response from control endpoint " + ctrlEndpt + ": " + status);
else
e = new KNXInvalidResponseException("invalid connect response from " + ctrlEndpt);
// quit, cleanup and notify user
connectCleanup(e);
throw e;
}
catch (final InterruptedException e) {
connectCleanup(e);
throw e;
}
} } | public class class_name {
protected void connect(final InetSocketAddress localEP, final InetSocketAddress serverCtrlEP,
final CRI cri, final boolean useNAT) throws KNXException, InterruptedException
{
if (state != CLOSED)
throw new IllegalStateException("open connection");
ctrlEndpt = serverCtrlEP;
if (ctrlEndpt.isUnresolved())
throw new KNXException("server control endpoint is unresolved: " + serverCtrlEP);
if (ctrlEndpt.getAddress().isMulticastAddress())
throw new KNXIllegalArgumentException("server control endpoint cannot be a multicast address ("
+ ctrlEndpt.getAddress().getHostAddress() + ")");
useNat = useNAT;
logger = LogService.getLogger("calimero.knxnetip." + getName());
// if we allow localEP to be null, we would create an unbound socket
if (localEP == null)
throw new KNXIllegalArgumentException("no local endpoint specified");
InetSocketAddress local = localEP;
try {
if (local.isUnresolved())
throw new KNXIllegalArgumentException("unresolved address " + local);
if (local.getAddress().isAnyLocalAddress()) {
final InetAddress addr = useNAT ? null
: Optional.ofNullable(serverCtrlEP.getAddress()).flatMap(this::onSameSubnet)
.orElse(InetAddress.getLocalHost());
local = new InetSocketAddress(addr, localEP.getPort()); // depends on control dependency: [if], data = [none]
}
socket = new DatagramSocket(local);
ctrlSocket = socket;
logger.info("establish connection from " + socket.getLocalSocketAddress() + " to " + ctrlEndpt);
// HPAI throws if wildcard local address (0.0.0.0) is supplied
final HPAI hpai = new HPAI(HPAI.IPV4_UDP,
useNat ? null : (InetSocketAddress) socket.getLocalSocketAddress());
final byte[] buf = PacketHelper.toPacket(new ConnectRequest(cri, hpai, hpai));
send(buf, ctrlEndpt);
}
catch (final UnknownHostException e) {
throw new KNXException("no local host address available", e);
}
catch (IOException | SecurityException e) {
if (socket != null)
socket.close();
logger.error("communication failure on connect", e);
if (local.getAddress().isLoopbackAddress())
logger.warn("local endpoint uses loopback address ({}), try with a different IP address",
local.getAddress());
throw new KNXException("connecting from " + local + " to " + serverCtrlEP + ": " + e.getMessage());
}
logger.debug("wait for connect response from " + ctrlEndpt + " ...");
startReceiver();
try {
final boolean changed = waitForStateChange(CLOSED, CONNECT_REQ_TIMEOUT);
if (state == OK) {
heartbeat = new HeartbeatMonitor(); // depends on control dependency: [if], data = [none]
heartbeat.start(); // depends on control dependency: [if], data = [none]
String optionalConnectionInfo = "";
if (tunnelingAddress != null)
optionalConnectionInfo = ", tunneling address " + tunnelingAddress;
logger.info("connection established (data endpoint {}:{}, channel {}{})",
dataEndpt.getAddress().getHostAddress(), dataEndpt.getPort(), channelId,
optionalConnectionInfo); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final KNXException e;
if (!changed)
e = new KNXTimeoutException("timeout connecting to control endpoint " + ctrlEndpt);
else if (state == ACK_ERROR)
e = new KNXRemoteException("error response from control endpoint " + ctrlEndpt + ": " + status);
else
e = new KNXInvalidResponseException("invalid connect response from " + ctrlEndpt);
// quit, cleanup and notify user
connectCleanup(e);
throw e;
}
catch (final InterruptedException e) {
connectCleanup(e);
throw e;
}
} } |
public class class_name {
static void forceSimplePom(File projectDir, IProgressMonitor monitor) throws IOException {
final File pomFile = new File(projectDir, POM_FILE);
if (pomFile.exists()) {
final SubMonitor submon = SubMonitor.convert(monitor, 4);
final File savedPomFile = new File(projectDir, POM_BACKUP_FILE);
if (savedPomFile.exists()) {
savedPomFile.delete();
}
submon.worked(1);
Files.copy(pomFile, savedPomFile);
submon.worked(1);
final StringBuilder content = new StringBuilder();
try (BufferedReader stream = new BufferedReader(new FileReader(pomFile))) {
String line = stream.readLine();
while (line != null) {
line = line.replaceAll("<extensions>\\s*true\\s*</extensions>", ""); //$NON-NLS-1$ //$NON-NLS-2$
content.append(line).append("\n"); //$NON-NLS-1$
line = stream.readLine();
}
}
submon.worked(1);
Files.write(content.toString().getBytes(), pomFile);
submon.worked(1);
}
} } | public class class_name {
static void forceSimplePom(File projectDir, IProgressMonitor monitor) throws IOException {
final File pomFile = new File(projectDir, POM_FILE);
if (pomFile.exists()) {
final SubMonitor submon = SubMonitor.convert(monitor, 4);
final File savedPomFile = new File(projectDir, POM_BACKUP_FILE);
if (savedPomFile.exists()) {
savedPomFile.delete();
}
submon.worked(1);
Files.copy(pomFile, savedPomFile);
submon.worked(1);
final StringBuilder content = new StringBuilder();
try (BufferedReader stream = new BufferedReader(new FileReader(pomFile))) {
String line = stream.readLine();
while (line != null) {
line = line.replaceAll("<extensions>\\s*true\\s*</extensions>", ""); //$NON-NLS-1$ //$NON-NLS-2$ // depends on control dependency: [while], data = [none]
content.append(line).append("\n"); //$NON-NLS-1$ // depends on control dependency: [while], data = [(line]
line = stream.readLine(); // depends on control dependency: [while], data = [none]
}
}
submon.worked(1);
Files.write(content.toString().getBytes(), pomFile);
submon.worked(1);
}
} } |
public class class_name {
public List<Meta> selectTermMeta(final long termId) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Meta> meta = Lists.newArrayListWithExpectedSize(8);
Timer.Context ctx = metrics.selectTermMetaTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(selectTermMetaSQL);
stmt.setLong(1, termId);
rs = stmt.executeQuery();
while(rs.next()) {
meta.add(new Meta(rs.getLong(1), rs.getString(2), rs.getString(3)));
}
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt, rs);
}
return meta;
} } | public class class_name {
public List<Meta> selectTermMeta(final long termId) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Meta> meta = Lists.newArrayListWithExpectedSize(8);
Timer.Context ctx = metrics.selectTermMetaTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(selectTermMetaSQL);
stmt.setLong(1, termId);
rs = stmt.executeQuery();
while(rs.next()) {
meta.add(new Meta(rs.getLong(1), rs.getString(2), rs.getString(3))); // depends on control dependency: [while], data = [none]
}
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt, rs);
}
return meta;
} } |
public class class_name {
public void logout(final BooleanCallback callback) {
GwtCommand command = new GwtCommand(logoutCommandName);
GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<SuccessCommandResponse>() {
public void execute(SuccessCommandResponse response) {
if (response.isSuccess()) {
userToken = null;
Authentication.this.userId = null;
if (callback != null) {
callback.execute(true);
}
GwtCommandDispatcher.getInstance().logout();
manager.fireEvent(new LogoutSuccessEvent());
} else {
if (callback != null) {
callback.execute(false);
}
manager.fireEvent(new LogoutFailureEvent());
}
}
});
} } | public class class_name {
public void logout(final BooleanCallback callback) {
GwtCommand command = new GwtCommand(logoutCommandName);
GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<SuccessCommandResponse>() {
public void execute(SuccessCommandResponse response) {
if (response.isSuccess()) {
userToken = null; // depends on control dependency: [if], data = [none]
Authentication.this.userId = null; // depends on control dependency: [if], data = [none]
if (callback != null) {
callback.execute(true); // depends on control dependency: [if], data = [none]
}
GwtCommandDispatcher.getInstance().logout(); // depends on control dependency: [if], data = [none]
manager.fireEvent(new LogoutSuccessEvent()); // depends on control dependency: [if], data = [none]
} else {
if (callback != null) {
callback.execute(false); // depends on control dependency: [if], data = [none]
}
manager.fireEvent(new LogoutFailureEvent()); // depends on control dependency: [if], data = [none]
}
}
});
} } |
public class class_name {
public Observable<ServiceResponse<List<VirtualMachineImageResourceInner>>> listPublishersWithServiceResponseAsync(String location) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() 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.listPublishers(location, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<VirtualMachineImageResourceInner>>>>() {
@Override
public Observable<ServiceResponse<List<VirtualMachineImageResourceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<VirtualMachineImageResourceInner>> clientResponse = listPublishersDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<List<VirtualMachineImageResourceInner>>> listPublishersWithServiceResponseAsync(String location) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() 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.listPublishers(location, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<VirtualMachineImageResourceInner>>>>() {
@Override
public Observable<ServiceResponse<List<VirtualMachineImageResourceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<VirtualMachineImageResourceInner>> clientResponse = listPublishersDelegate(response);
return Observable.just(clientResponse); // 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 Observable<ServiceResponse<DatabaseInner>> getByElasticPoolWithServiceResponseAsync(String resourceGroupName, String serverName, String elasticPoolName, String databaseName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serverName == null) {
throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
}
if (elasticPoolName == null) {
throw new IllegalArgumentException("Parameter elasticPoolName is required and cannot be null.");
}
if (databaseName == null) {
throw new IllegalArgumentException("Parameter databaseName 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.getByElasticPool(this.client.subscriptionId(), resourceGroupName, serverName, elasticPoolName, databaseName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<DatabaseInner>>>() {
@Override
public Observable<ServiceResponse<DatabaseInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<DatabaseInner> clientResponse = getByElasticPoolDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<DatabaseInner>> getByElasticPoolWithServiceResponseAsync(String resourceGroupName, String serverName, String elasticPoolName, String databaseName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serverName == null) {
throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
}
if (elasticPoolName == null) {
throw new IllegalArgumentException("Parameter elasticPoolName is required and cannot be null.");
}
if (databaseName == null) {
throw new IllegalArgumentException("Parameter databaseName 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.getByElasticPool(this.client.subscriptionId(), resourceGroupName, serverName, elasticPoolName, databaseName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<DatabaseInner>>>() {
@Override
public Observable<ServiceResponse<DatabaseInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<DatabaseInner> clientResponse = getByElasticPoolDelegate(response);
return Observable.just(clientResponse); // 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 String classNameToSignature(String name) {
int nameLength = name.length();
int colonPos = 1 + nameLength;
char[] buf = new char[colonPos + 1];
buf[0] = 'L';
buf[colonPos] = ';';
name.getChars(0, nameLength, buf, 1);
for (int i = 1; i != colonPos; ++i) {
if (buf[i] == '.') {
buf[i] = '/';
}
}
return new String(buf, 0, colonPos + 1);
} } | public class class_name {
public static String classNameToSignature(String name) {
int nameLength = name.length();
int colonPos = 1 + nameLength;
char[] buf = new char[colonPos + 1];
buf[0] = 'L';
buf[colonPos] = ';';
name.getChars(0, nameLength, buf, 1);
for (int i = 1; i != colonPos; ++i) {
if (buf[i] == '.') {
buf[i] = '/'; // depends on control dependency: [if], data = [none]
}
}
return new String(buf, 0, colonPos + 1);
} } |
public class class_name {
public static void buildSheetCommentFromAlias(Sheet sheet, List<TieCommandAlias> tieCommandAliasList) {
if ((tieCommandAliasList == null)||(tieCommandAliasList.isEmpty())) {
return;
}
for (Row row : sheet) {
for (Cell cell : row) {
buildCellCommentFromalias(tieCommandAliasList, cell);
}
}
} } | public class class_name {
public static void buildSheetCommentFromAlias(Sheet sheet, List<TieCommandAlias> tieCommandAliasList) {
if ((tieCommandAliasList == null)||(tieCommandAliasList.isEmpty())) {
return;
// depends on control dependency: [if], data = [none]
}
for (Row row : sheet) {
for (Cell cell : row) {
buildCellCommentFromalias(tieCommandAliasList, cell);
// depends on control dependency: [for], data = [cell]
}
}
} } |
public class class_name {
@SuppressWarnings("checkstyle:nestedifdepth")
protected void _computeTypes(SarlCastedExpression cast, ITypeComputationState state) {
if (state instanceof AbstractTypeComputationState) {
final JvmTypeReference type = cast.getType();
if (type != null) {
state.withNonVoidExpectation().computeTypes(cast.getTarget());
// Set the linked feature
try {
final AbstractTypeComputationState computationState = (AbstractTypeComputationState) state;
final CastedExpressionTypeComputationState astate = new CastedExpressionTypeComputationState(
cast,
computationState,
this.castOperationValidator);
astate.resetFeature(cast);
if (astate.isCastOperatorLinkingEnabled(cast)) {
final List<? extends ILinkingCandidate> candidates = astate.getLinkingCandidates(cast);
if (!candidates.isEmpty()) {
final ILinkingCandidate best = getBestCandidate(candidates);
if (best != null) {
best.applyToModel(computationState.getResolvedTypes());
}
}
}
} catch (Throwable exception) {
final Throwable cause = Throwables.getRootCause(exception);
state.addDiagnostic(new EObjectDiagnosticImpl(
Severity.ERROR,
IssueCodes.INTERNAL_ERROR,
cause.getLocalizedMessage(),
cast,
null,
-1,
null));
}
state.acceptActualType(state.getReferenceOwner().toLightweightTypeReference(type));
} else {
state.computeTypes(cast.getTarget());
}
} else {
super._computeTypes(cast, state);
}
} } | public class class_name {
@SuppressWarnings("checkstyle:nestedifdepth")
protected void _computeTypes(SarlCastedExpression cast, ITypeComputationState state) {
if (state instanceof AbstractTypeComputationState) {
final JvmTypeReference type = cast.getType();
if (type != null) {
state.withNonVoidExpectation().computeTypes(cast.getTarget()); // depends on control dependency: [if], data = [none]
// Set the linked feature
try {
final AbstractTypeComputationState computationState = (AbstractTypeComputationState) state;
final CastedExpressionTypeComputationState astate = new CastedExpressionTypeComputationState(
cast,
computationState,
this.castOperationValidator);
astate.resetFeature(cast); // depends on control dependency: [try], data = [none]
if (astate.isCastOperatorLinkingEnabled(cast)) {
final List<? extends ILinkingCandidate> candidates = astate.getLinkingCandidates(cast);
if (!candidates.isEmpty()) {
final ILinkingCandidate best = getBestCandidate(candidates);
if (best != null) {
best.applyToModel(computationState.getResolvedTypes()); // depends on control dependency: [if], data = [none]
}
}
}
} catch (Throwable exception) {
final Throwable cause = Throwables.getRootCause(exception);
state.addDiagnostic(new EObjectDiagnosticImpl(
Severity.ERROR,
IssueCodes.INTERNAL_ERROR,
cause.getLocalizedMessage(),
cast,
null,
-1,
null));
} // depends on control dependency: [catch], data = [none]
state.acceptActualType(state.getReferenceOwner().toLightweightTypeReference(type)); // depends on control dependency: [if], data = [(type]
} else {
state.computeTypes(cast.getTarget()); // depends on control dependency: [if], data = [none]
}
} else {
super._computeTypes(cast, state); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
final String getConnectionDescription() {
if(datasource != null) {
return name;
}
String description = connectionString;
int index = connectionString != null ? connectionString.indexOf('?') : 0;
if(index > 0) {
description = connectionString.substring(0, index);
}
if(!Strings.isNullOrEmpty(user)) {
return user + "@" + description;
} else {
return description;
}
} } | public class class_name {
final String getConnectionDescription() {
if(datasource != null) {
return name; // depends on control dependency: [if], data = [none]
}
String description = connectionString;
int index = connectionString != null ? connectionString.indexOf('?') : 0;
if(index > 0) {
description = connectionString.substring(0, index); // depends on control dependency: [if], data = [none]
}
if(!Strings.isNullOrEmpty(user)) {
return user + "@" + description; // depends on control dependency: [if], data = [none]
} else {
return description; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public CPDisplayLayout remove(Serializable primaryKey)
throws NoSuchCPDisplayLayoutException {
Session session = null;
try {
session = openSession();
CPDisplayLayout cpDisplayLayout = (CPDisplayLayout)session.get(CPDisplayLayoutImpl.class,
primaryKey);
if (cpDisplayLayout == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchCPDisplayLayoutException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(cpDisplayLayout);
}
catch (NoSuchCPDisplayLayoutException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} } | public class class_name {
@Override
public CPDisplayLayout remove(Serializable primaryKey)
throws NoSuchCPDisplayLayoutException {
Session session = null;
try {
session = openSession();
CPDisplayLayout cpDisplayLayout = (CPDisplayLayout)session.get(CPDisplayLayoutImpl.class,
primaryKey);
if (cpDisplayLayout == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey); // depends on control dependency: [if], data = [none]
}
throw new NoSuchCPDisplayLayoutException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(cpDisplayLayout);
}
catch (NoSuchCPDisplayLayoutException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} } |
public class class_name {
private static GeometryCollection convertCollection(JGeometry geometry) {
JGeometry[] elements = geometry.getElements();
if (elements == null || elements.length == 0) {
return GeometryCollection.createEmpty();
}
Geometry[] geometries = new Geometry[elements.length];
for (int i = 0; i < elements.length; i++) {
geometries[i] = convert(elements[i]);
}
return new GeometryCollection(geometries);
} } | public class class_name {
private static GeometryCollection convertCollection(JGeometry geometry) {
JGeometry[] elements = geometry.getElements();
if (elements == null || elements.length == 0) {
return GeometryCollection.createEmpty(); // depends on control dependency: [if], data = [none]
}
Geometry[] geometries = new Geometry[elements.length];
for (int i = 0; i < elements.length; i++) {
geometries[i] = convert(elements[i]); // depends on control dependency: [for], data = [i]
}
return new GeometryCollection(geometries);
} } |
public class class_name {
@GwtIncompatible("incompatible method")
public static byte[] uuidToByteArray(final UUID src, final byte[] dst, final int dstPos, final int nBytes) {
if (0 == nBytes) {
return dst;
}
if (nBytes > 16) {
throw new IllegalArgumentException("nBytes is greater than 16");
}
longToByteArray(src.getMostSignificantBits(), 0, dst, dstPos, nBytes > 8 ? 8 : nBytes);
if (nBytes >= 8) {
longToByteArray(src.getLeastSignificantBits(), 0, dst, dstPos + 8, nBytes - 8);
}
return dst;
} } | public class class_name {
@GwtIncompatible("incompatible method")
public static byte[] uuidToByteArray(final UUID src, final byte[] dst, final int dstPos, final int nBytes) {
if (0 == nBytes) {
return dst; // depends on control dependency: [if], data = [none]
}
if (nBytes > 16) {
throw new IllegalArgumentException("nBytes is greater than 16");
}
longToByteArray(src.getMostSignificantBits(), 0, dst, dstPos, nBytes > 8 ? 8 : nBytes);
if (nBytes >= 8) {
longToByteArray(src.getLeastSignificantBits(), 0, dst, dstPos + 8, nBytes - 8); // depends on control dependency: [if], data = [none]
}
return dst;
} } |
public class class_name {
void updateConfguration(Dictionary<String, Object> props, String defaultId) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "updateConfguration", props, defaultId);
}
String id = (String) props.get(SSLChannelProvider.SSL_CFG_REF);
synchronized (this) {
properties = props;
if (id == null || id.isEmpty()) {
useDefaultId = true;
id = sslRefId = defaultId;
properties.put(SSLChannelProvider.SSL_CFG_REF, defaultId);
} else {
sslRefId = id;
useDefaultId = false;
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "updateConfguration", id);
}
} } | public class class_name {
void updateConfguration(Dictionary<String, Object> props, String defaultId) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "updateConfguration", props, defaultId); // depends on control dependency: [if], data = [none]
}
String id = (String) props.get(SSLChannelProvider.SSL_CFG_REF);
synchronized (this) {
properties = props;
if (id == null || id.isEmpty()) {
useDefaultId = true; // depends on control dependency: [if], data = [none]
id = sslRefId = defaultId; // depends on control dependency: [if], data = [none]
properties.put(SSLChannelProvider.SSL_CFG_REF, defaultId); // depends on control dependency: [if], data = [none]
} else {
sslRefId = id; // depends on control dependency: [if], data = [none]
useDefaultId = false; // depends on control dependency: [if], data = [none]
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "updateConfguration", id); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public final Class<? extends T> enhanceClass(Class<T> baseClass) {
logger.info("Enhancing {}", baseClass);
CtClass original = null;
try {
original = pool.get(baseClass.getName());
TemplateHelper templateHelper = new TemplateHelper(pool);
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("_", templateHelper);
velocityContext.put("base", original);
velocityContext.put("getters", findGetters(original));
velocityContext.put("abstractMethods", findAbstractMethods(original));
Map<String, Object> contextItems = getAdditionalContextItems();
for (Map.Entry<String, Object> contextItem : contextItems.entrySet()) {
velocityContext.put(contextItem.getKey(), contextItem.getValue());
}
StringWriter writer = new StringWriter();
engine.getTemplate(getTemplateLocation()).merge(velocityContext, writer);
logger.debug("Enhanced {} to form new class {} with source:\n{}",
baseClass.getSimpleName(), templateHelper.clsName(), writer);
return ClassLoadingUtil.toClass(templateHelper.compile());
} catch (Exception e) {
logger.error("An error occurred while enhancing {}", baseClass);
throw ExceptionUtil.propagate(e);
} finally {
if (original != null) {
original.detach();
}
}
} } | public class class_name {
@Override
public final Class<? extends T> enhanceClass(Class<T> baseClass) {
logger.info("Enhancing {}", baseClass);
CtClass original = null;
try {
original = pool.get(baseClass.getName());
TemplateHelper templateHelper = new TemplateHelper(pool);
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("_", templateHelper);
velocityContext.put("base", original);
velocityContext.put("getters", findGetters(original));
velocityContext.put("abstractMethods", findAbstractMethods(original));
Map<String, Object> contextItems = getAdditionalContextItems();
for (Map.Entry<String, Object> contextItem : contextItems.entrySet()) {
velocityContext.put(contextItem.getKey(), contextItem.getValue()); // depends on control dependency: [for], data = [contextItem]
}
StringWriter writer = new StringWriter();
engine.getTemplate(getTemplateLocation()).merge(velocityContext, writer);
logger.debug("Enhanced {} to form new class {} with source:\n{}",
baseClass.getSimpleName(), templateHelper.clsName(), writer);
return ClassLoadingUtil.toClass(templateHelper.compile());
} catch (Exception e) {
logger.error("An error occurred while enhancing {}", baseClass);
throw ExceptionUtil.propagate(e);
} finally {
if (original != null) {
original.detach(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void traverseAndFilter(final TreeWalker walker, final String indent, final Metadata metadata,
final StringBuilder sb) {
final Node parend = walker.getCurrentNode();
final boolean isLogged = appendText(indent, (Element) parend, sb);
for (final Filter filter : filterList) {
if (filter.filter(metadata, walker)) {
appendText(" catched by: " + filter.getClass().getSimpleName(), sb);
break;
}
}
if (isLogged) {
appendText("\n", sb);
}
for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {
traverseAndFilter(walker, indent + " ", metadata, sb);
}
walker.setCurrentNode(parend);
} } | public class class_name {
public void traverseAndFilter(final TreeWalker walker, final String indent, final Metadata metadata,
final StringBuilder sb) {
final Node parend = walker.getCurrentNode();
final boolean isLogged = appendText(indent, (Element) parend, sb);
for (final Filter filter : filterList) {
if (filter.filter(metadata, walker)) {
appendText(" catched by: " + filter.getClass().getSimpleName(), sb); // depends on control dependency: [if], data = [none]
break;
}
}
if (isLogged) {
appendText("\n", sb); // depends on control dependency: [if], data = [none]
}
for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {
traverseAndFilter(walker, indent + " ", metadata, sb); // depends on control dependency: [for], data = [none]
}
walker.setCurrentNode(parend);
} } |
public class class_name {
public String getIdProperty(TableRef tableRef) {
TableMapping tableMapping = mappedClasses.get(tableRef);
if (tableMapping == null) {
return null;
}
ColumnMetaData identifierColumn = tableMapping.getIdentifierColumn();
return tableMapping.getColumnMapping(identifierColumn).getPropertyName();
} } | public class class_name {
public String getIdProperty(TableRef tableRef) {
TableMapping tableMapping = mappedClasses.get(tableRef);
if (tableMapping == null) {
return null; // depends on control dependency: [if], data = [none]
}
ColumnMetaData identifierColumn = tableMapping.getIdentifierColumn();
return tableMapping.getColumnMapping(identifierColumn).getPropertyName();
} } |
public class class_name {
public static String getConcreteBeanClassName(EnterpriseBean enterpriseBean)
{
String beanClassName = enterpriseBean.getEjbClassName();
String packageName = packageName(beanClassName);
String beanName = encodeBeanInterfacesName(enterpriseBean, true, false, false, false); // d147734
StringBuffer result = new StringBuffer();
if (packageName != null)
{
result.append(packageName);
result.append('.');
}
result.append(concreteBeanPrefix);
result.append(beanName);
return result.toString();
} } | public class class_name {
public static String getConcreteBeanClassName(EnterpriseBean enterpriseBean)
{
String beanClassName = enterpriseBean.getEjbClassName();
String packageName = packageName(beanClassName);
String beanName = encodeBeanInterfacesName(enterpriseBean, true, false, false, false); // d147734
StringBuffer result = new StringBuffer();
if (packageName != null)
{
result.append(packageName); // depends on control dependency: [if], data = [(packageName]
result.append('.'); // depends on control dependency: [if], data = [none]
}
result.append(concreteBeanPrefix);
result.append(beanName);
return result.toString();
} } |
public class class_name {
public BaseField setupField(int iFieldSeq)
{
BaseField field = null;
//if (iFieldSeq == 0)
//{
// field = new CounterField(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
// field.setHidden(true);
//}
//if (iFieldSeq == 1)
//{
// field = new RecordChangedField(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null);
// field.setHidden(true);
//}
//if (iFieldSeq == 2)
//{
// field = new BooleanField(this, DELETED, Constants.DEFAULT_FIELD_LENGTH, null, new Boolean(false));
// field.setHidden(true);
//}
if (iFieldSeq == 3)
field = new ProjectTaskField(this, PROJECT_TASK_ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
if (iFieldSeq == 4)
field = new ProjectTaskField(this, PROJECT_TASK_PREDECESSOR_ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
if (iFieldSeq == 5)
{
field = new PredecessorTypeField(this, PREDECESSOR_TYPE, Constants.DEFAULT_FIELD_LENGTH, null, null);
field.addListener(new InitOnceFieldHandler(null));
}
if (iFieldSeq == 6)
field = new IntegerField(this, PREDECESSOR_DELAY, Constants.DEFAULT_FIELD_LENGTH, null, null);
if (field == null)
field = super.setupField(iFieldSeq);
return field;
} } | public class class_name {
public BaseField setupField(int iFieldSeq)
{
BaseField field = null;
//if (iFieldSeq == 0)
//{
// field = new CounterField(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
// field.setHidden(true);
//}
//if (iFieldSeq == 1)
//{
// field = new RecordChangedField(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null);
// field.setHidden(true);
//}
//if (iFieldSeq == 2)
//{
// field = new BooleanField(this, DELETED, Constants.DEFAULT_FIELD_LENGTH, null, new Boolean(false));
// field.setHidden(true);
//}
if (iFieldSeq == 3)
field = new ProjectTaskField(this, PROJECT_TASK_ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
if (iFieldSeq == 4)
field = new ProjectTaskField(this, PROJECT_TASK_PREDECESSOR_ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
if (iFieldSeq == 5)
{
field = new PredecessorTypeField(this, PREDECESSOR_TYPE, Constants.DEFAULT_FIELD_LENGTH, null, null); // depends on control dependency: [if], data = [none]
field.addListener(new InitOnceFieldHandler(null)); // depends on control dependency: [if], data = [none]
}
if (iFieldSeq == 6)
field = new IntegerField(this, PREDECESSOR_DELAY, Constants.DEFAULT_FIELD_LENGTH, null, null);
if (field == null)
field = super.setupField(iFieldSeq);
return field;
} } |
public class class_name {
public void expandToQueue( PriorityQueue priQ, double minDistance ) {
boolean isComp1 = isComposite(boundable1);
boolean isComp2 = isComposite(boundable2);
/**
* HEURISTIC: If both boundable are composite,
* choose the one with largest area to expand.
* Otherwise, simply expand whichever is composite.
*/
if (isComp1 && isComp2) {
if (area(boundable1) > area(boundable2)) {
expand(boundable1, boundable2, priQ, minDistance);
return;
} else {
expand(boundable2, boundable1, priQ, minDistance);
return;
}
} else if (isComp1) {
expand(boundable1, boundable2, priQ, minDistance);
return;
} else if (isComp2) {
expand(boundable2, boundable1, priQ, minDistance);
return;
}
throw new IllegalArgumentException("neither boundable is composite");
} } | public class class_name {
public void expandToQueue( PriorityQueue priQ, double minDistance ) {
boolean isComp1 = isComposite(boundable1);
boolean isComp2 = isComposite(boundable2);
/**
* HEURISTIC: If both boundable are composite,
* choose the one with largest area to expand.
* Otherwise, simply expand whichever is composite.
*/
if (isComp1 && isComp2) {
if (area(boundable1) > area(boundable2)) {
expand(boundable1, boundable2, priQ, minDistance); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
} else {
expand(boundable2, boundable1, priQ, minDistance); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else if (isComp1) {
expand(boundable1, boundable2, priQ, minDistance); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
} else if (isComp2) {
expand(boundable2, boundable1, priQ, minDistance); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException("neither boundable is composite");
} } |
public class class_name {
@SuppressWarnings({"unchecked"})
protected <E> E prepareGetValue(final T t, final Class<E> destinationType) {
if (t == null) {
return null;
}
if (destinationType == null) {
return (E) t;
}
return TypeConverterManager.get().convertType(t, destinationType);
} } | public class class_name {
@SuppressWarnings({"unchecked"})
protected <E> E prepareGetValue(final T t, final Class<E> destinationType) {
if (t == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (destinationType == null) {
return (E) t; // depends on control dependency: [if], data = [none]
}
return TypeConverterManager.get().convertType(t, destinationType);
} } |
public class class_name {
private Map<String, Configuration> loadAllMessageFilesForRegisteredLanguages() {
Map<String, Configuration> langToKeyAndValuesMappingMutable = Maps.newHashMap();
// Load default messages:
Configuration defaultLanguage = loadLanguageConfiguration("conf/messages.properties");
// Make sure we got the file.
// Everything else does not make much sense.
if (defaultLanguage == null) {
throw new RuntimeException(
"Did not find conf/messages.properties. Please add a default language file.");
} else {
langToKeyAndValuesMappingMutable.put("", defaultLanguage);
}
// Get the languages from the application configuration.
String[] applicationLangs = ninjaProperties
.getStringArray(NinjaConstant.applicationLanguages);
// If we don't have any languages declared we just return.
// We'll use the default messages.properties file.
if (applicationLangs == null) {
return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable);
}
// Load each language into the HashMap containing the languages:
for (String lang : applicationLangs) {
// First step: Load complete language eg. en-US
Configuration configuration = loadLanguageConfiguration(String
.format("conf/messages_%s.properties", lang));
Configuration configurationLangOnly = null;
// If the language has a country code load the default values for
// the language, too. For instance missing variables in en-US will
// be
// Overwritten by the default languages.
if (lang.contains("-")) {
// get the lang
String langOnly = lang.split("-")[0];
// And load the configuraion
configurationLangOnly = loadLanguageConfiguration(String
.format("conf/messages_%s.properties", langOnly));
}
// This is strange. If you defined the language in application.conf
// it should be there propably.
if (configuration == null) {
logger.info(
"Did not find conf/messages_{}.properties but it was specified in application.conf. Using default language instead.",
lang);
} else {
// add new language, but combine with default language if stuff
// is missing...
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
// Add eg. "en-US"
compositeConfiguration.addConfiguration(configuration);
// Add eg. "en"
if (configurationLangOnly != null) {
compositeConfiguration
.addConfiguration(configurationLangOnly);
}
// Add messages.conf (default pack)
compositeConfiguration.addConfiguration(defaultLanguage);
// and add the composed configuration to the hashmap with the
// mapping.
langToKeyAndValuesMappingMutable.put(lang,
(Configuration) compositeConfiguration);
}
}
return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable);
} } | public class class_name {
private Map<String, Configuration> loadAllMessageFilesForRegisteredLanguages() {
Map<String, Configuration> langToKeyAndValuesMappingMutable = Maps.newHashMap();
// Load default messages:
Configuration defaultLanguage = loadLanguageConfiguration("conf/messages.properties");
// Make sure we got the file.
// Everything else does not make much sense.
if (defaultLanguage == null) {
throw new RuntimeException(
"Did not find conf/messages.properties. Please add a default language file.");
} else {
langToKeyAndValuesMappingMutable.put("", defaultLanguage); // depends on control dependency: [if], data = [none]
}
// Get the languages from the application configuration.
String[] applicationLangs = ninjaProperties
.getStringArray(NinjaConstant.applicationLanguages);
// If we don't have any languages declared we just return.
// We'll use the default messages.properties file.
if (applicationLangs == null) {
return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable); // depends on control dependency: [if], data = [none]
}
// Load each language into the HashMap containing the languages:
for (String lang : applicationLangs) {
// First step: Load complete language eg. en-US
Configuration configuration = loadLanguageConfiguration(String
.format("conf/messages_%s.properties", lang));
Configuration configurationLangOnly = null;
// If the language has a country code load the default values for
// the language, too. For instance missing variables in en-US will
// be
// Overwritten by the default languages.
if (lang.contains("-")) {
// get the lang
String langOnly = lang.split("-")[0];
// And load the configuraion
configurationLangOnly = loadLanguageConfiguration(String
.format("conf/messages_%s.properties", langOnly)); // depends on control dependency: [if], data = [none]
}
// This is strange. If you defined the language in application.conf
// it should be there propably.
if (configuration == null) {
logger.info(
"Did not find conf/messages_{}.properties but it was specified in application.conf. Using default language instead.",
lang); // depends on control dependency: [if], data = [none]
} else {
// add new language, but combine with default language if stuff
// is missing...
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
// Add eg. "en-US"
compositeConfiguration.addConfiguration(configuration); // depends on control dependency: [if], data = [(configuration]
// Add eg. "en"
if (configurationLangOnly != null) {
compositeConfiguration
.addConfiguration(configurationLangOnly); // depends on control dependency: [if], data = [none]
}
// Add messages.conf (default pack)
compositeConfiguration.addConfiguration(defaultLanguage); // depends on control dependency: [if], data = [none]
// and add the composed configuration to the hashmap with the
// mapping.
langToKeyAndValuesMappingMutable.put(lang,
(Configuration) compositeConfiguration); // depends on control dependency: [if], data = [none]
}
}
return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable);
} } |
public class class_name {
public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {
List<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );
for ( String name : pathWithoutAlias ) {
subPath.add( name );
if ( isAssociation( targetTypeName, subPath ) ) {
return subPath;
}
}
return null;
} } | public class class_name {
public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {
List<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );
for ( String name : pathWithoutAlias ) {
subPath.add( name ); // depends on control dependency: [for], data = [name]
if ( isAssociation( targetTypeName, subPath ) ) {
return subPath; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@Override
public InetSocketAddress getLocalAddress() {
if (ch == null) {
return null;
}
Socket socket = ch.socket();
if (socket == null) {
return null;
}
return (InetSocketAddress) socket.getLocalSocketAddress();
} } | public class class_name {
@Override
public InetSocketAddress getLocalAddress() {
if (ch == null) {
return null; // depends on control dependency: [if], data = [none]
}
Socket socket = ch.socket();
if (socket == null) {
return null; // depends on control dependency: [if], data = [none]
}
return (InetSocketAddress) socket.getLocalSocketAddress();
} } |
public class class_name {
public static String prettyPrint(String in, int lineLength, String delim) {
// make a guess about resulting length to minimize copying
StringBuilder sb = new StringBuilder(in.length() + in.length()/lineLength);
if (delim == null) {
delim = " ";
}
StringTokenizer st = new StringTokenizer(in, delim);
int charCount = 0;
while (st.hasMoreTokens()) {
String s = st.nextToken();
charCount = charCount + s.length();
if (charCount < lineLength) {
sb.append(s);
sb.append(' ');
charCount++;
} else {
sb.append('\n');
sb.append(s);
sb.append(' ');
charCount = s.length() + 1;
}
}
return sb.toString();
} } | public class class_name {
public static String prettyPrint(String in, int lineLength, String delim) {
// make a guess about resulting length to minimize copying
StringBuilder sb = new StringBuilder(in.length() + in.length()/lineLength);
if (delim == null) {
delim = " "; // depends on control dependency: [if], data = [none]
}
StringTokenizer st = new StringTokenizer(in, delim);
int charCount = 0;
while (st.hasMoreTokens()) {
String s = st.nextToken();
charCount = charCount + s.length(); // depends on control dependency: [while], data = [none]
if (charCount < lineLength) {
sb.append(s); // depends on control dependency: [if], data = [none]
sb.append(' '); // depends on control dependency: [if], data = [none]
charCount++; // depends on control dependency: [if], data = [none]
} else {
sb.append('\n'); // depends on control dependency: [if], data = [none]
sb.append(s); // depends on control dependency: [if], data = [none]
sb.append(' '); // depends on control dependency: [if], data = [none]
charCount = s.length() + 1; // depends on control dependency: [if], data = [none]
}
}
return sb.toString();
} } |
public class class_name {
public static boolean matchesQName(QName regQName, QName targetQName, boolean ignorePrefix) {
if (regQName == null || targetQName == null) {
return false;
}
if ("*".equals(getQNameString(regQName))) {
return true;
}
// if the name space or the prefix is not equal, just return false;
if (!(regQName.getNamespaceURI().equals(targetQName.getNamespaceURI())) ||
!(ignorePrefix || regQName.getPrefix().equals(targetQName.getPrefix()))) {
return false;
}
if (regQName.getLocalPart().contains("*")) {
return Pattern.matches(mapPattern(regQName.getLocalPart()), targetQName.getLocalPart());
} else if (regQName.getLocalPart().equals(targetQName.getLocalPart())) {
return true;
}
return false;
} } | public class class_name {
public static boolean matchesQName(QName regQName, QName targetQName, boolean ignorePrefix) {
if (regQName == null || targetQName == null) {
return false; // depends on control dependency: [if], data = [none]
}
if ("*".equals(getQNameString(regQName))) {
return true; // depends on control dependency: [if], data = [none]
}
// if the name space or the prefix is not equal, just return false;
if (!(regQName.getNamespaceURI().equals(targetQName.getNamespaceURI())) ||
!(ignorePrefix || regQName.getPrefix().equals(targetQName.getPrefix()))) {
return false; // depends on control dependency: [if], data = [none]
}
if (regQName.getLocalPart().contains("*")) {
return Pattern.matches(mapPattern(regQName.getLocalPart()), targetQName.getLocalPart()); // depends on control dependency: [if], data = [none]
} else if (regQName.getLocalPart().equals(targetQName.getLocalPart())) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
void renameProperties() {
int propsRenamed = 0;
int propsSkipped = 0;
int instancesRenamed = 0;
int instancesSkipped = 0;
int singleTypeProps = 0;
Set<String> reported = new HashSet<>();
for (Property prop : properties.values()) {
if (prop.shouldRename()) {
UnionFind<JSType> pTypes = prop.getTypes();
Map<JSType, String> propNames = buildPropNames(prop);
++propsRenamed;
prop.expandTypesToSkip();
// This loop has poor locality, because instead of walking the AST,
// we iterate over all accesses of a property, which can be in very
// different places in the code.
for (Map.Entry<Node, JSType> entry : prop.rootTypesByNode.entrySet()) {
Node node = entry.getKey();
JSType rootType = entry.getValue();
if (prop.shouldRename(rootType)) {
String newName = propNames.get(pTypes.find(rootType));
node.setString(newName);
compiler.reportChangeToEnclosingScope(node);
++instancesRenamed;
} else {
++instancesSkipped;
CheckLevel checkLevelForProp = propertiesToErrorFor.get(prop.name);
if (checkLevelForProp != null
&& checkLevelForProp != CheckLevel.OFF
&& !reported.contains(prop.name)) {
reported.add(prop.name);
compiler.report(JSError.make(
node,
checkLevelForProp,
Warnings.INVALIDATION_ON_TYPE, prop.name,
rootType.toString(), ""));
}
}
}
} else {
if (prop.skipRenaming) {
++propsSkipped;
} else {
++singleTypeProps;
}
}
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("Renamed " + instancesRenamed + " instances of "
+ propsRenamed + " properties.");
logger.fine("Skipped renaming " + instancesSkipped + " invalidated "
+ "properties, " + propsSkipped + " instances of properties "
+ "that were skipped for specific types and " + singleTypeProps
+ " properties that were referenced from only one type.");
}
} } | public class class_name {
void renameProperties() {
int propsRenamed = 0;
int propsSkipped = 0;
int instancesRenamed = 0;
int instancesSkipped = 0;
int singleTypeProps = 0;
Set<String> reported = new HashSet<>();
for (Property prop : properties.values()) {
if (prop.shouldRename()) {
UnionFind<JSType> pTypes = prop.getTypes();
Map<JSType, String> propNames = buildPropNames(prop);
++propsRenamed; // depends on control dependency: [if], data = [none]
prop.expandTypesToSkip(); // depends on control dependency: [if], data = [none]
// This loop has poor locality, because instead of walking the AST,
// we iterate over all accesses of a property, which can be in very
// different places in the code.
for (Map.Entry<Node, JSType> entry : prop.rootTypesByNode.entrySet()) {
Node node = entry.getKey();
JSType rootType = entry.getValue();
if (prop.shouldRename(rootType)) {
String newName = propNames.get(pTypes.find(rootType));
node.setString(newName); // depends on control dependency: [if], data = [none]
compiler.reportChangeToEnclosingScope(node); // depends on control dependency: [if], data = [none]
++instancesRenamed; // depends on control dependency: [if], data = [none]
} else {
++instancesSkipped; // depends on control dependency: [if], data = [none]
CheckLevel checkLevelForProp = propertiesToErrorFor.get(prop.name);
if (checkLevelForProp != null
&& checkLevelForProp != CheckLevel.OFF
&& !reported.contains(prop.name)) {
reported.add(prop.name); // depends on control dependency: [if], data = [none]
compiler.report(JSError.make(
node,
checkLevelForProp,
Warnings.INVALIDATION_ON_TYPE, prop.name,
rootType.toString(), "")); // depends on control dependency: [if], data = [none]
}
}
}
} else {
if (prop.skipRenaming) {
++propsSkipped; // depends on control dependency: [if], data = [none]
} else {
++singleTypeProps; // depends on control dependency: [if], data = [none]
}
}
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("Renamed " + instancesRenamed + " instances of "
+ propsRenamed + " properties."); // depends on control dependency: [if], data = [none]
logger.fine("Skipped renaming " + instancesSkipped + " invalidated "
+ "properties, " + propsSkipped + " instances of properties "
+ "that were skipped for specific types and " + singleTypeProps
+ " properties that were referenced from only one type."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected long getCacheDurationForServiceProvider(final SamlRegisteredService service, final MetadataResolver chainingMetadataResolver) {
try {
val set = new CriteriaSet();
set.add(new EntityIdCriterion(service.getServiceId()));
set.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
val entitySp = chainingMetadataResolver.resolveSingle(set);
if (entitySp != null && entitySp.getCacheDuration() != null) {
LOGGER.debug("Located cache duration [{}] specified in SP metadata for [{}]", entitySp.getCacheDuration(), entitySp.getEntityID());
return TimeUnit.MILLISECONDS.toNanos(entitySp.getCacheDuration());
}
set.clear();
set.add(new EntityIdCriterion(service.getServiceId()));
val entity = chainingMetadataResolver.resolveSingle(set);
if (entity != null && entity.getCacheDuration() != null) {
LOGGER.debug("Located cache duration [{}] specified in entity metadata for [{}]", entity.getCacheDuration(), entity.getEntityID());
return TimeUnit.MILLISECONDS.toNanos(entity.getCacheDuration());
}
} catch (final Exception e) {
LOGGER.debug(e.getMessage(), e);
}
return -1;
} } | public class class_name {
protected long getCacheDurationForServiceProvider(final SamlRegisteredService service, final MetadataResolver chainingMetadataResolver) {
try {
val set = new CriteriaSet();
set.add(new EntityIdCriterion(service.getServiceId())); // depends on control dependency: [try], data = [none]
set.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)); // depends on control dependency: [try], data = [none]
val entitySp = chainingMetadataResolver.resolveSingle(set);
if (entitySp != null && entitySp.getCacheDuration() != null) {
LOGGER.debug("Located cache duration [{}] specified in SP metadata for [{}]", entitySp.getCacheDuration(), entitySp.getEntityID()); // depends on control dependency: [if], data = [none]
return TimeUnit.MILLISECONDS.toNanos(entitySp.getCacheDuration()); // depends on control dependency: [if], data = [(entitySp]
}
set.clear(); // depends on control dependency: [try], data = [none]
set.add(new EntityIdCriterion(service.getServiceId())); // depends on control dependency: [try], data = [none]
val entity = chainingMetadataResolver.resolveSingle(set);
if (entity != null && entity.getCacheDuration() != null) {
LOGGER.debug("Located cache duration [{}] specified in entity metadata for [{}]", entity.getCacheDuration(), entity.getEntityID()); // depends on control dependency: [if], data = [none]
return TimeUnit.MILLISECONDS.toNanos(entity.getCacheDuration()); // depends on control dependency: [if], data = [(entity]
}
} catch (final Exception e) {
LOGGER.debug(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
return -1;
} } |
public class class_name {
public EEnum getResourceObjectIncludeObOrent() {
if (resourceObjectIncludeObOrentEEnum == null) {
resourceObjectIncludeObOrentEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(190);
}
return resourceObjectIncludeObOrentEEnum;
} } | public class class_name {
public EEnum getResourceObjectIncludeObOrent() {
if (resourceObjectIncludeObOrentEEnum == null) {
resourceObjectIncludeObOrentEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(190); // depends on control dependency: [if], data = [none]
}
return resourceObjectIncludeObOrentEEnum;
} } |
public class class_name {
public synchronized byte[] toByteArray() {
byte[] outBuff = new byte[count];
int pos = 0;
for (BufferPool.Buffer b: buffers) {
System.arraycopy(b.buf, 0, outBuff, pos, b.pos);
pos += b.pos;
}
return outBuff;
} } | public class class_name {
public synchronized byte[] toByteArray() {
byte[] outBuff = new byte[count];
int pos = 0;
for (BufferPool.Buffer b: buffers) {
System.arraycopy(b.buf, 0, outBuff, pos, b.pos); // depends on control dependency: [for], data = [b]
pos += b.pos; // depends on control dependency: [for], data = [b]
}
return outBuff;
} } |
public class class_name {
public static boolean isODataEntityCollectionType(Class<?> type,
Type genericType) {
if (ListResult.class != type) {
return false;
}
ParameterizedType pt = (ParameterizedType) genericType;
if (pt.getActualTypeArguments().length != 1) {
return false;
}
Class<?> typeClass = getCollectedType(genericType);
return isODataEntityType(typeClass);
} } | public class class_name {
public static boolean isODataEntityCollectionType(Class<?> type,
Type genericType) {
if (ListResult.class != type) {
return false; // depends on control dependency: [if], data = [none]
}
ParameterizedType pt = (ParameterizedType) genericType;
if (pt.getActualTypeArguments().length != 1) {
return false; // depends on control dependency: [if], data = [none]
}
Class<?> typeClass = getCollectedType(genericType);
return isODataEntityType(typeClass);
} } |
public class class_name {
@Check
@Override
@SuppressWarnings("checkstyle:cyclomaticcomplexity")
public void checkAbstract(XtendFunction function) {
final XtendTypeDeclaration declarator = function.getDeclaringType();
if (function.getExpression() == null || function.isAbstract()) {
if (declarator instanceof XtendClass || declarator.isAnonymous()
|| declarator instanceof SarlAgent || declarator instanceof SarlBehavior
|| declarator instanceof SarlSkill) {
if (function.isDispatch()) {
error(MessageFormat.format(
Messages.SARLValidator_80,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, DISPATCH_FUNCTIONS_MUST_NOT_BE_ABSTRACT);
return;
}
if (function.getCreateExtensionInfo() != null) {
error(MessageFormat.format(
Messages.SARLValidator_81,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, CREATE_FUNCTIONS_MUST_NOT_BE_ABSTRACT);
return;
}
if (declarator.isAnonymous()) {
error(MessageFormat.format(
Messages.SARLValidator_82,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, MISSING_ABSTRACT_IN_ANONYMOUS);
} else {
final boolean isAbstract;
if (declarator instanceof XtendClass) {
isAbstract = ((XtendClass) declarator).isAbstract();
} else if (declarator instanceof SarlAgent) {
isAbstract = ((SarlAgent) declarator).isAbstract();
} else if (declarator instanceof SarlBehavior) {
isAbstract = ((SarlBehavior) declarator).isAbstract();
} else if (declarator instanceof SarlSkill) {
isAbstract = ((SarlSkill) declarator).isAbstract();
} else {
return;
}
if (!isAbstract && !function.isNative()) {
error(MessageFormat.format(
Messages.SARLValidator_82,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, MISSING_ABSTRACT);
return;
}
}
if (!function.getModifiers().contains("abstract")) { //$NON-NLS-1$
warning(MessageFormat.format(
Messages.SARLValidator_84,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, MISSING_ABSTRACT,
function.getName(),
this.localClassAwareTypeNames.getReadableName(declarator));
}
} else if (declarator instanceof XtendInterface || declarator instanceof SarlCapacity) {
if (function.getCreateExtensionInfo() != null) {
error(MessageFormat.format(
Messages.SARLValidator_85,
function.getName()),
XTEND_FUNCTION__NAME, -1, CREATE_FUNCTIONS_MUST_NOT_BE_ABSTRACT);
return;
}
}
} else if (declarator instanceof XtendInterface || declarator instanceof SarlCapacity) {
if (!getGeneratorConfig(function).getJavaSourceVersion().isAtLeast(JAVA8)) {
error(Messages.SARLValidator_86, XTEND_FUNCTION__NAME, -1, ABSTRACT_METHOD_WITH_BODY);
return;
}
}
} } | public class class_name {
@Check
@Override
@SuppressWarnings("checkstyle:cyclomaticcomplexity")
public void checkAbstract(XtendFunction function) {
final XtendTypeDeclaration declarator = function.getDeclaringType();
if (function.getExpression() == null || function.isAbstract()) {
if (declarator instanceof XtendClass || declarator.isAnonymous()
|| declarator instanceof SarlAgent || declarator instanceof SarlBehavior
|| declarator instanceof SarlSkill) {
if (function.isDispatch()) {
error(MessageFormat.format(
Messages.SARLValidator_80,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, DISPATCH_FUNCTIONS_MUST_NOT_BE_ABSTRACT); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (function.getCreateExtensionInfo() != null) {
error(MessageFormat.format(
Messages.SARLValidator_81,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, CREATE_FUNCTIONS_MUST_NOT_BE_ABSTRACT); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (declarator.isAnonymous()) {
error(MessageFormat.format(
Messages.SARLValidator_82,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, MISSING_ABSTRACT_IN_ANONYMOUS); // depends on control dependency: [if], data = [none]
} else {
final boolean isAbstract;
if (declarator instanceof XtendClass) {
isAbstract = ((XtendClass) declarator).isAbstract(); // depends on control dependency: [if], data = [none]
} else if (declarator instanceof SarlAgent) {
isAbstract = ((SarlAgent) declarator).isAbstract(); // depends on control dependency: [if], data = [none]
} else if (declarator instanceof SarlBehavior) {
isAbstract = ((SarlBehavior) declarator).isAbstract(); // depends on control dependency: [if], data = [none]
} else if (declarator instanceof SarlSkill) {
isAbstract = ((SarlSkill) declarator).isAbstract(); // depends on control dependency: [if], data = [none]
} else {
return; // depends on control dependency: [if], data = [none]
}
if (!isAbstract && !function.isNative()) {
error(MessageFormat.format(
Messages.SARLValidator_82,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, MISSING_ABSTRACT); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
if (!function.getModifiers().contains("abstract")) { //$NON-NLS-1$
warning(MessageFormat.format(
Messages.SARLValidator_84,
function.getName(), this.localClassAwareTypeNames.getReadableName(declarator)),
XTEND_FUNCTION__NAME, -1, MISSING_ABSTRACT,
function.getName(),
this.localClassAwareTypeNames.getReadableName(declarator)); // depends on control dependency: [if], data = [none]
}
} else if (declarator instanceof XtendInterface || declarator instanceof SarlCapacity) {
if (function.getCreateExtensionInfo() != null) {
error(MessageFormat.format(
Messages.SARLValidator_85,
function.getName()),
XTEND_FUNCTION__NAME, -1, CREATE_FUNCTIONS_MUST_NOT_BE_ABSTRACT); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
} else if (declarator instanceof XtendInterface || declarator instanceof SarlCapacity) {
if (!getGeneratorConfig(function).getJavaSourceVersion().isAtLeast(JAVA8)) {
error(Messages.SARLValidator_86, XTEND_FUNCTION__NAME, -1, ABSTRACT_METHOD_WITH_BODY); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
void estimateTranslation( DMatrixRMaj R , List<AssociatedPair> points , Vector3D_F64 T )
{
final int N = points.size();
W.reshape(N*2,3);
y.reshape(N*2,1);
Wty.reshape(3,1);
DMatrix3x3 Rtmp = new DMatrix3x3();
ConvertDMatrixStruct.convert(R,Rtmp);
int indexY = 0,indexW = 0;
for (int i = 0; i < N; i++) {
AssociatedPair p = points.get(i);
// rotate into camera frame
double u1 = Rtmp.a11*p.p1.x + Rtmp.a12*p.p1.y;
double u2 = Rtmp.a21*p.p1.x + Rtmp.a22*p.p1.y;
double u3 = Rtmp.a31*p.p1.x + Rtmp.a32*p.p1.y;
W.data[indexW++] = 1;
W.data[indexW++] = 0;
W.data[indexW++] = -p.p2.x;
W.data[indexW++] = 0;
W.data[indexW++] = 1;
W.data[indexW++] = -p.p2.y;
y.data[indexY++] = p.p2.x*u3 - u1;
y.data[indexY++] = p.p2.y*u3 - u2;
}
//======= Compute Pseudo Inverse
// WW = inv(W^T*W)
CommonOps_DDRM.multTransA(W,W,WW);
CommonOps_DDRM.invert(WW);
// W^T*y
CommonOps_DDRM.multTransA(W,y,Wty);
// translation = inv(W^T*W)*W^T*y
W.reshape(3,1);
CommonOps_DDRM.mult(WW,Wty,W);
T.x = W.data[0];
T.y = W.data[1];
T.z = W.data[2];
} } | public class class_name {
void estimateTranslation( DMatrixRMaj R , List<AssociatedPair> points , Vector3D_F64 T )
{
final int N = points.size();
W.reshape(N*2,3);
y.reshape(N*2,1);
Wty.reshape(3,1);
DMatrix3x3 Rtmp = new DMatrix3x3();
ConvertDMatrixStruct.convert(R,Rtmp);
int indexY = 0,indexW = 0;
for (int i = 0; i < N; i++) {
AssociatedPair p = points.get(i);
// rotate into camera frame
double u1 = Rtmp.a11*p.p1.x + Rtmp.a12*p.p1.y;
double u2 = Rtmp.a21*p.p1.x + Rtmp.a22*p.p1.y;
double u3 = Rtmp.a31*p.p1.x + Rtmp.a32*p.p1.y;
W.data[indexW++] = 1; // depends on control dependency: [for], data = [none]
W.data[indexW++] = 0; // depends on control dependency: [for], data = [none]
W.data[indexW++] = -p.p2.x; // depends on control dependency: [for], data = [none]
W.data[indexW++] = 0; // depends on control dependency: [for], data = [none]
W.data[indexW++] = 1; // depends on control dependency: [for], data = [none]
W.data[indexW++] = -p.p2.y; // depends on control dependency: [for], data = [none]
y.data[indexY++] = p.p2.x*u3 - u1; // depends on control dependency: [for], data = [none]
y.data[indexY++] = p.p2.y*u3 - u2; // depends on control dependency: [for], data = [none]
}
//======= Compute Pseudo Inverse
// WW = inv(W^T*W)
CommonOps_DDRM.multTransA(W,W,WW);
CommonOps_DDRM.invert(WW);
// W^T*y
CommonOps_DDRM.multTransA(W,y,Wty);
// translation = inv(W^T*W)*W^T*y
W.reshape(3,1);
CommonOps_DDRM.mult(WW,Wty,W);
T.x = W.data[0];
T.y = W.data[1];
T.z = W.data[2];
} } |
public class class_name {
private void interiorPointExteriorPoint_(int cluster, int id_a, int id_b,
int predicate) {
if (m_matrix[predicate] == 0)
return;
int clusterParentage = m_topo_graph.getClusterParentage(cluster);
if ((clusterParentage & id_a) != 0 && (clusterParentage & id_b) == 0) {
m_matrix[predicate] = 0;
}
} } | public class class_name {
private void interiorPointExteriorPoint_(int cluster, int id_a, int id_b,
int predicate) {
if (m_matrix[predicate] == 0)
return;
int clusterParentage = m_topo_graph.getClusterParentage(cluster);
if ((clusterParentage & id_a) != 0 && (clusterParentage & id_b) == 0) {
m_matrix[predicate] = 0; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void flipVertical( GrayS32 input ) {
int h2 = input.height/2;
for( int y = 0; y < h2; y++ ) {
int index1 = input.getStartIndex() + y * input.getStride();
int index2 = input.getStartIndex() + (input.height - y - 1) * input.getStride();
int end = index1 + input.width;
while( index1 < end ) {
int tmp = input.data[index1];
input.data[index1++] = input.data[index2];
input.data[index2++] = (int)tmp;
}
}
} } | public class class_name {
public static void flipVertical( GrayS32 input ) {
int h2 = input.height/2;
for( int y = 0; y < h2; y++ ) {
int index1 = input.getStartIndex() + y * input.getStride();
int index2 = input.getStartIndex() + (input.height - y - 1) * input.getStride();
int end = index1 + input.width;
while( index1 < end ) {
int tmp = input.data[index1];
input.data[index1++] = input.data[index2]; // depends on control dependency: [while], data = [none]
input.data[index2++] = (int)tmp; // depends on control dependency: [while], data = [none]
}
}
} } |
public class class_name {
public void addFile(String filename) {
synchronized (files) {
if (!files.contains(filename)) {
files.add(filename);
}
}
} } | public class class_name {
public void addFile(String filename) {
synchronized (files) {
if (!files.contains(filename)) {
files.add(filename); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
@Ensures({
"lines == null ? result == null : isLineNumberList(result)"
})
static List<Long> getLineNumbers(Object lines) {
if (lines == null) {
return null;
}
ArrayList<Long> lineNumbers = new ArrayList<Long>();
if (lines.getClass().isArray()) {
for (long line : (long[]) lines) {
lineNumbers.add(line < 1 ? null : line);
}
} else {
for (Long line : (List<Long>) lines) {
lineNumbers.add(line < 1 ? null : line);
}
}
return lineNumbers;
} } | public class class_name {
@SuppressWarnings("unchecked")
@Ensures({
"lines == null ? result == null : isLineNumberList(result)"
})
static List<Long> getLineNumbers(Object lines) {
if (lines == null) {
return null; // depends on control dependency: [if], data = [none]
}
ArrayList<Long> lineNumbers = new ArrayList<Long>();
if (lines.getClass().isArray()) {
for (long line : (long[]) lines) {
lineNumbers.add(line < 1 ? null : line); // depends on control dependency: [for], data = [line]
}
} else {
for (Long line : (List<Long>) lines) {
lineNumbers.add(line < 1 ? null : line); // depends on control dependency: [for], data = [line]
}
}
return lineNumbers;
} } |
public class class_name {
public Observable<ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersCreateOrUpdateImmutabilityPolicyHeaders>> createOrUpdateImmutabilityPolicyWithServiceResponseAsync(String resourceGroupName, String accountName, String containerName, int immutabilityPeriodSinceCreationInDays) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (accountName == null) {
throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
}
if (containerName == null) {
throw new IllegalArgumentException("Parameter containerName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
final String immutabilityPolicyName = "default";
final String ifMatch = null;
ImmutabilityPolicyInner parameters = new ImmutabilityPolicyInner();
parameters.withImmutabilityPeriodSinceCreationInDays(immutabilityPeriodSinceCreationInDays);
return service.createOrUpdateImmutabilityPolicy(resourceGroupName, accountName, containerName, immutabilityPolicyName, this.client.subscriptionId(), this.client.apiVersion(), ifMatch, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersCreateOrUpdateImmutabilityPolicyHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersCreateOrUpdateImmutabilityPolicyHeaders>> call(Response<ResponseBody> response) {
try {
ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersCreateOrUpdateImmutabilityPolicyHeaders> clientResponse = createOrUpdateImmutabilityPolicyDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersCreateOrUpdateImmutabilityPolicyHeaders>> createOrUpdateImmutabilityPolicyWithServiceResponseAsync(String resourceGroupName, String accountName, String containerName, int immutabilityPeriodSinceCreationInDays) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (accountName == null) {
throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
}
if (containerName == null) {
throw new IllegalArgumentException("Parameter containerName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
final String immutabilityPolicyName = "default";
final String ifMatch = null;
ImmutabilityPolicyInner parameters = new ImmutabilityPolicyInner();
parameters.withImmutabilityPeriodSinceCreationInDays(immutabilityPeriodSinceCreationInDays);
return service.createOrUpdateImmutabilityPolicy(resourceGroupName, accountName, containerName, immutabilityPolicyName, this.client.subscriptionId(), this.client.apiVersion(), ifMatch, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersCreateOrUpdateImmutabilityPolicyHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersCreateOrUpdateImmutabilityPolicyHeaders>> call(Response<ResponseBody> response) {
try {
ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersCreateOrUpdateImmutabilityPolicyHeaders> clientResponse = createOrUpdateImmutabilityPolicyDelegate(response);
return Observable.just(clientResponse); // 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 {
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CellEditorListener.class) {
((CellEditorListener)listeners[i+1]).editingCanceled(new ChangeEvent(this));
}
}
} } | public class class_name {
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CellEditorListener.class) {
((CellEditorListener)listeners[i+1]).editingCanceled(new ChangeEvent(this)); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static Collection<InterfaceAddress> getAllIPAddresses() throws SocketException {
ArrayList<InterfaceAddress> direcciones = new ArrayList();
InterfaceAddress ipLoopback = null;
try {
Enumeration ifaces = NetworkInterface.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
for (InterfaceAddress ips : iface.getInterfaceAddresses())
{
InetAddress ia = ips.getAddress();
if (!ia.getHostAddress().contains(":")) {
if (ia.isLoopbackAddress()) {
ipLoopback = ips;
} else {
direcciones.add(ips);
}
}
}
}
if ((direcciones.isEmpty()) && (ipLoopback != null))
{
direcciones.add(ipLoopback);
}
} catch (SocketException e) {
throw e;
}
return direcciones;
} } | public class class_name {
public static Collection<InterfaceAddress> getAllIPAddresses() throws SocketException {
ArrayList<InterfaceAddress> direcciones = new ArrayList();
InterfaceAddress ipLoopback = null;
try {
Enumeration ifaces = NetworkInterface.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
for (InterfaceAddress ips : iface.getInterfaceAddresses())
{
InetAddress ia = ips.getAddress();
if (!ia.getHostAddress().contains(":")) {
if (ia.isLoopbackAddress()) {
ipLoopback = ips; // depends on control dependency: [if], data = [none]
} else {
direcciones.add(ips); // depends on control dependency: [if], data = [none]
}
}
}
}
if ((direcciones.isEmpty()) && (ipLoopback != null))
{
direcciones.add(ipLoopback); // depends on control dependency: [if], data = [none]
}
} catch (SocketException e) {
throw e;
}
return direcciones;
} } |
public class class_name {
protected void load(URL url) {
try {
config = configBuilder.properties(url);
} catch (ConfigurationException e) {
JK.throww(e);
}
} } | public class class_name {
protected void load(URL url) {
try {
config = configBuilder.properties(url);
// depends on control dependency: [try], data = [none]
} catch (ConfigurationException e) {
JK.throww(e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) {
for (Entry<String, String> param : headerParams.entrySet()) {
reqBuilder.header(param.getKey(), parameterToString(param.getValue()));
}
for (Entry<String, String> header : defaultHeaderMap.entrySet()) {
if (!headerParams.containsKey(header.getKey())) {
reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
}
}
} } | public class class_name {
public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) {
for (Entry<String, String> param : headerParams.entrySet()) {
reqBuilder.header(param.getKey(), parameterToString(param.getValue())); // depends on control dependency: [for], data = [param]
}
for (Entry<String, String> header : defaultHeaderMap.entrySet()) {
if (!headerParams.containsKey(header.getKey())) {
reqBuilder.header(header.getKey(), parameterToString(header.getValue())); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public Future<Void> startAsync() {
log.info("Session store / pubsub factory used: {}", configCopy.getStoreFactory());
initGroups();
pipelineFactory.start(configCopy, namespacesHub);
Class<? extends ServerChannel> channelClass = NioServerSocketChannel.class;
if (configCopy.isUseLinuxNativeEpoll()) {
channelClass = EpollServerSocketChannel.class;
}
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(channelClass)
.childHandler(pipelineFactory);
applyConnectionOptions(b);
InetSocketAddress addr = new InetSocketAddress(configCopy.getPort());
if (configCopy.getHostname() != null) {
addr = new InetSocketAddress(configCopy.getHostname(), configCopy.getPort());
}
return b.bind(addr).addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (future.isSuccess()) {
log.info("SocketIO server started at port: {}", configCopy.getPort());
} else {
log.error("SocketIO server start failed at port: {}!", configCopy.getPort());
}
}
});
} } | public class class_name {
public Future<Void> startAsync() {
log.info("Session store / pubsub factory used: {}", configCopy.getStoreFactory());
initGroups();
pipelineFactory.start(configCopy, namespacesHub);
Class<? extends ServerChannel> channelClass = NioServerSocketChannel.class;
if (configCopy.isUseLinuxNativeEpoll()) {
channelClass = EpollServerSocketChannel.class; // depends on control dependency: [if], data = [none]
}
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(channelClass)
.childHandler(pipelineFactory);
applyConnectionOptions(b);
InetSocketAddress addr = new InetSocketAddress(configCopy.getPort());
if (configCopy.getHostname() != null) {
addr = new InetSocketAddress(configCopy.getHostname(), configCopy.getPort()); // depends on control dependency: [if], data = [(configCopy.getHostname()]
}
return b.bind(addr).addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (future.isSuccess()) {
log.info("SocketIO server started at port: {}", configCopy.getPort());
} else {
log.error("SocketIO server start failed at port: {}!", configCopy.getPort());
}
}
});
} } |
public class class_name {
void setTransacted(boolean transacted) {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "setTransacted", Boolean
.valueOf(transacted));
}
_transacted = transacted;
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(this, TRACE, "setTransacted");
}
} } | public class class_name {
void setTransacted(boolean transacted) {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "setTransacted", Boolean
.valueOf(transacted)); // depends on control dependency: [if], data = [none]
}
_transacted = transacted;
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(this, TRACE, "setTransacted"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void findClassLoaderOrder(final ClassLoader classRealm, final ClassLoaderOrder classLoaderOrder) {
// From ClassRealm#loadClassFromImport(String) -> getImportClassLoader(String)
final Object foreignImports = ReflectionUtils.getFieldVal(classRealm, "foreignImports", false);
if (foreignImports != null) {
@SuppressWarnings("unchecked")
final SortedSet<Object> foreignImportEntries = (SortedSet<Object>) foreignImports;
for (final Object entry : foreignImportEntries) {
final ClassLoader foreignImportClassLoader = (ClassLoader) ReflectionUtils.invokeMethod(entry,
"getClassLoader", false);
// Treat foreign import classloader as if it is a parent classloader
classLoaderOrder.delegateTo(foreignImportClassLoader, /* isParent = */ true);
}
}
// Get delegation order -- different strategies have different delegation orders
final boolean isParentFirst = isParentFirstStrategy(classRealm);
// From ClassRealm#loadClassFromSelf(String) -> findLoadedClass(String) for self-first strategy
if (!isParentFirst) {
// Add self before parent
classLoaderOrder.add(classRealm);
}
// From ClassRealm#loadClassFromParent -- N.B. we are ignoring parentImports, which is used to filter
// a class name before deciding whether or not to call the parent classloader (so ClassGraph will be
// able to load classes by name that are not imported from the parent classloader).
final ClassLoader parentClassLoader = (ClassLoader) ReflectionUtils.invokeMethod(classRealm,
"getParentClassLoader", false);
classLoaderOrder.delegateTo(parentClassLoader, /* isParent = */ true);
classLoaderOrder.delegateTo(classRealm.getParent(), /* isParent = */ true);
// From ClassRealm#loadClassFromSelf(String) -> findLoadedClass(String) for parent-first strategy
if (isParentFirst) {
// Add self after parent
classLoaderOrder.add(classRealm);
}
} } | public class class_name {
public static void findClassLoaderOrder(final ClassLoader classRealm, final ClassLoaderOrder classLoaderOrder) {
// From ClassRealm#loadClassFromImport(String) -> getImportClassLoader(String)
final Object foreignImports = ReflectionUtils.getFieldVal(classRealm, "foreignImports", false);
if (foreignImports != null) {
@SuppressWarnings("unchecked")
final SortedSet<Object> foreignImportEntries = (SortedSet<Object>) foreignImports;
for (final Object entry : foreignImportEntries) {
final ClassLoader foreignImportClassLoader = (ClassLoader) ReflectionUtils.invokeMethod(entry,
"getClassLoader", false);
// Treat foreign import classloader as if it is a parent classloader
classLoaderOrder.delegateTo(foreignImportClassLoader, /* isParent = */ true); // depends on control dependency: [for], data = [none]
}
}
// Get delegation order -- different strategies have different delegation orders
final boolean isParentFirst = isParentFirstStrategy(classRealm);
// From ClassRealm#loadClassFromSelf(String) -> findLoadedClass(String) for self-first strategy
if (!isParentFirst) {
// Add self before parent
classLoaderOrder.add(classRealm); // depends on control dependency: [if], data = [none]
}
// From ClassRealm#loadClassFromParent -- N.B. we are ignoring parentImports, which is used to filter
// a class name before deciding whether or not to call the parent classloader (so ClassGraph will be
// able to load classes by name that are not imported from the parent classloader).
final ClassLoader parentClassLoader = (ClassLoader) ReflectionUtils.invokeMethod(classRealm,
"getParentClassLoader", false);
classLoaderOrder.delegateTo(parentClassLoader, /* isParent = */ true);
classLoaderOrder.delegateTo(classRealm.getParent(), /* isParent = */ true);
// From ClassRealm#loadClassFromSelf(String) -> findLoadedClass(String) for parent-first strategy
if (isParentFirst) {
// Add self after parent
classLoaderOrder.add(classRealm); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private boolean getIfCarbonIsHydrophobic(IAtomContainer ac, IAtom atom) {
List first = ac.getConnectedAtomsList(atom);
List second = null;
List third = null;
//org.openscience.cdk.interfaces.IAtom[] fourth = null;
if (first.size() > 0) {
for (int i = 0; i < first.size(); i++) {
IAtom firstAtom = (IAtom) first.get(i);
if (firstAtom.getSymbol().equals("C") || firstAtom.getSymbol().equals("H")) {
} else {
return false;
}
second = ac.getConnectedAtomsList(firstAtom);
if (second.size() > 0) {
for (int b = 0; b < second.size(); b++) {
IAtom secondAtom = (IAtom) second.get(b);
if (secondAtom.getSymbol().equals("C") || secondAtom.getSymbol().equals("H")) {
} else {
return false;
}
third = ac.getConnectedAtomsList(secondAtom);
if (third.size() > 0) {
for (int c = 0; c < third.size(); c++) {
IAtom thirdAtom = (IAtom) third.get(c);
if (thirdAtom.getSymbol().equals("C") || thirdAtom.getSymbol().equals("H")) {
} else {
return false;
}
//fourth = ac.getConnectedAtoms(third[c]);
//if (fourth.length > 0) {
// for (int d = 0; d < fourth.length; d++) {
// if (fourth[d].getSymbol().equals("C") || fourth[d].getSymbol().equals("H")) {
// } else {
// return false;
// }
// }
//} else {
// return false;
//}
}
} else {
return false;
}
}
} else {
return false;
}
}
} else {
return false;
}
return true;
} } | public class class_name {
private boolean getIfCarbonIsHydrophobic(IAtomContainer ac, IAtom atom) {
List first = ac.getConnectedAtomsList(atom);
List second = null;
List third = null;
//org.openscience.cdk.interfaces.IAtom[] fourth = null;
if (first.size() > 0) {
for (int i = 0; i < first.size(); i++) {
IAtom firstAtom = (IAtom) first.get(i);
if (firstAtom.getSymbol().equals("C") || firstAtom.getSymbol().equals("H")) {
} else {
return false; // depends on control dependency: [if], data = [none]
}
second = ac.getConnectedAtomsList(firstAtom); // depends on control dependency: [for], data = [none]
if (second.size() > 0) {
for (int b = 0; b < second.size(); b++) {
IAtom secondAtom = (IAtom) second.get(b);
if (secondAtom.getSymbol().equals("C") || secondAtom.getSymbol().equals("H")) {
} else {
return false; // depends on control dependency: [if], data = [none]
}
third = ac.getConnectedAtomsList(secondAtom); // depends on control dependency: [for], data = [none]
if (third.size() > 0) {
for (int c = 0; c < third.size(); c++) {
IAtom thirdAtom = (IAtom) third.get(c);
if (thirdAtom.getSymbol().equals("C") || thirdAtom.getSymbol().equals("H")) {
} else {
return false; // depends on control dependency: [if], data = [none]
}
//fourth = ac.getConnectedAtoms(third[c]);
//if (fourth.length > 0) {
// for (int d = 0; d < fourth.length; d++) {
// if (fourth[d].getSymbol().equals("C") || fourth[d].getSymbol().equals("H")) {
// } else {
// return false;
// }
// }
//} else {
// return false;
//}
}
} else {
return false; // depends on control dependency: [if], data = [none]
}
}
} else {
return false; // depends on control dependency: [if], data = [none]
}
}
} else {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public void generatExecuteTransactionRx(ClassName dataSourceName, String daoFactory, RxType rxType) {
String parameterName = "transaction";
ParameterizedTypeName returnTypeName = ParameterizedTypeName.get(ClassName.get(rxType.clazz),
TypeVariableName.get("T"));
ParameterizedTypeName observableTypeName = ParameterizedTypeName.get(TypeUtility
.className(rxType.clazz.getPackage().getName(), rxType.clazz.getSimpleName() + "OnSubscribe"),
TypeVariableName.get("T"));
ParameterizedTypeName emitterTypeName = ParameterizedTypeName.get(
TypeUtility.className(rxType.clazz.getPackage().getName(), rxType.clazz.getSimpleName() + "Emitter"),
TypeVariableName.get("T"));
TypeSpec innerEmitter = TypeSpec.anonymousClassBuilder("").addSuperinterface(observableTypeName)
.addMethod(MethodSpec.methodBuilder("subscribe").addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC).addParameter(emitterTypeName, "emitter").returns(Void.TYPE)
.addStatement("boolean needToOpened=!$L.this.isOpenInWriteMode()", dataSourceName.simpleName())
.addStatement("boolean success=false").addCode("@SuppressWarnings(\"resource\")\n")
.addStatement("$T connection=needToOpened ? openWritableDatabase() : database()",
SQLiteDatabase.class)
// support for live data
.addStatement("$L currentDaoFactory=_daoFactorySingleThread.bindToThread()",
DATA_SOURCE_SINGLE_THREAD_NAME)
.addStatement("currentDaoFactory.onSessionOpened()")
.beginControlFlow("try").addStatement("connection.beginTransaction()")
.beginControlFlow(
"if (transaction != null && $T.$L==transaction.onExecute(currentDaoFactory, emitter))",
TransactionResult.class, TransactionResult.COMMIT)
.addStatement("connection.setTransactionSuccessful()").addStatement("success=true")
.endControlFlow().addStatement(rxType.onComplete ? "emitter.onComplete()" : "// no onComplete")
.nextControlFlow("catch($T e)", Throwable.class)
.addStatement("$T.error(e.getMessage())", Logger.class).addStatement("e.printStackTrace()")
.addStatement("emitter.onError(e)")
// support for live data
.addStatement("currentDaoFactory.onSessionClear()").nextControlFlow("finally")
.beginControlFlow("try").addStatement("connection.endTransaction()")
.nextControlFlow("catch($T e)", Throwable.class).endControlFlow()
.addCode("if (needToOpened) { close(); }\n")
// support for live data
.addCode(
"if (success) { currentDaoFactory.onSessionClosed(); } else { currentDaoFactory.onSessionClear(); }\n")
.endControlFlow().addStatement("return").build())
.build();
{
MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC)
.addTypeVariable(TypeVariableName.get("T"))
.addParameter(
ParameterizedTypeName.get(TypeUtility.className(dataSourceName.toString(),
rxType.clazz.getSimpleName() + "Transaction"), TypeVariableName.get("T")),
parameterName, Modifier.FINAL)
.returns(returnTypeName);
executeMethod.addStatement("$T emitter=$L", observableTypeName, innerEmitter);
if (rxType == RxType.FLOWABLE) {
executeMethod.addStatement("$T result=$T.create(emitter, $T.BUFFER)", returnTypeName, rxType.clazz,
BackpressureStrategy.class);
} else {
executeMethod.addStatement("$T result=$T.create(emitter)", returnTypeName, rxType.clazz);
}
executeMethod.addStatement("if (globalSubscribeOn!=null) result.subscribeOn(globalSubscribeOn)");
executeMethod.addStatement("if (globalObserveOn!=null) result.observeOn(globalObserveOn)");
executeMethod.addStatement("return result");
classBuilder.addMethod(executeMethod.build());
}
} } | public class class_name {
public void generatExecuteTransactionRx(ClassName dataSourceName, String daoFactory, RxType rxType) {
String parameterName = "transaction";
ParameterizedTypeName returnTypeName = ParameterizedTypeName.get(ClassName.get(rxType.clazz),
TypeVariableName.get("T"));
ParameterizedTypeName observableTypeName = ParameterizedTypeName.get(TypeUtility
.className(rxType.clazz.getPackage().getName(), rxType.clazz.getSimpleName() + "OnSubscribe"),
TypeVariableName.get("T"));
ParameterizedTypeName emitterTypeName = ParameterizedTypeName.get(
TypeUtility.className(rxType.clazz.getPackage().getName(), rxType.clazz.getSimpleName() + "Emitter"),
TypeVariableName.get("T"));
TypeSpec innerEmitter = TypeSpec.anonymousClassBuilder("").addSuperinterface(observableTypeName)
.addMethod(MethodSpec.methodBuilder("subscribe").addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC).addParameter(emitterTypeName, "emitter").returns(Void.TYPE)
.addStatement("boolean needToOpened=!$L.this.isOpenInWriteMode()", dataSourceName.simpleName())
.addStatement("boolean success=false").addCode("@SuppressWarnings(\"resource\")\n")
.addStatement("$T connection=needToOpened ? openWritableDatabase() : database()",
SQLiteDatabase.class)
// support for live data
.addStatement("$L currentDaoFactory=_daoFactorySingleThread.bindToThread()",
DATA_SOURCE_SINGLE_THREAD_NAME)
.addStatement("currentDaoFactory.onSessionOpened()")
.beginControlFlow("try").addStatement("connection.beginTransaction()")
.beginControlFlow(
"if (transaction != null && $T.$L==transaction.onExecute(currentDaoFactory, emitter))",
TransactionResult.class, TransactionResult.COMMIT)
.addStatement("connection.setTransactionSuccessful()").addStatement("success=true")
.endControlFlow().addStatement(rxType.onComplete ? "emitter.onComplete()" : "// no onComplete")
.nextControlFlow("catch($T e)", Throwable.class)
.addStatement("$T.error(e.getMessage())", Logger.class).addStatement("e.printStackTrace()")
.addStatement("emitter.onError(e)")
// support for live data
.addStatement("currentDaoFactory.onSessionClear()").nextControlFlow("finally")
.beginControlFlow("try").addStatement("connection.endTransaction()")
.nextControlFlow("catch($T e)", Throwable.class).endControlFlow()
.addCode("if (needToOpened) { close(); }\n")
// support for live data
.addCode(
"if (success) { currentDaoFactory.onSessionClosed(); } else { currentDaoFactory.onSessionClear(); }\n")
.endControlFlow().addStatement("return").build())
.build();
{
MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC)
.addTypeVariable(TypeVariableName.get("T"))
.addParameter(
ParameterizedTypeName.get(TypeUtility.className(dataSourceName.toString(),
rxType.clazz.getSimpleName() + "Transaction"), TypeVariableName.get("T")),
parameterName, Modifier.FINAL)
.returns(returnTypeName);
executeMethod.addStatement("$T emitter=$L", observableTypeName, innerEmitter);
if (rxType == RxType.FLOWABLE) {
executeMethod.addStatement("$T result=$T.create(emitter, $T.BUFFER)", returnTypeName, rxType.clazz,
BackpressureStrategy.class); // depends on control dependency: [if], data = [none]
} else {
executeMethod.addStatement("$T result=$T.create(emitter)", returnTypeName, rxType.clazz); // depends on control dependency: [if], data = [none]
}
executeMethod.addStatement("if (globalSubscribeOn!=null) result.subscribeOn(globalSubscribeOn)");
executeMethod.addStatement("if (globalObserveOn!=null) result.observeOn(globalObserveOn)");
executeMethod.addStatement("return result");
classBuilder.addMethod(executeMethod.build());
}
} } |
public class class_name {
public void add(ApplicationWindow window) {
if (activeWindow == null) // first window will be set as activeWindow
setActiveWindow(window);
if (!windows.contains(window)) {
windows.add(window);
window.setWindowManager(this);
setChanged();
notifyObservers();
}
} } | public class class_name {
public void add(ApplicationWindow window) {
if (activeWindow == null) // first window will be set as activeWindow
setActiveWindow(window);
if (!windows.contains(window)) {
windows.add(window); // depends on control dependency: [if], data = [none]
window.setWindowManager(this); // depends on control dependency: [if], data = [none]
setChanged(); // depends on control dependency: [if], data = [none]
notifyObservers(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@UiHandler("m_selectButton")
public void onSelectClick(ClickEvent event) {
if (m_galleryMode == GalleryMode.editor) {
// note: the select button isn't necessarily visible in editor mode (depending on the WYSIWYG editor), but
// if it is, we want it to save the data and close the gallery dialog
if (getHandler().setDataInEditor()) {
// do this after a delay, so we don't get ugly Javascript errors when the iframe is closed.
Timer timer = new Timer() {
@Override
public void run() {
CmsPreviewUtil.closeDialog();
}
};
timer.schedule(1);
}
} else {
saveChanges(null);
getHandler().selectResource();
}
} } | public class class_name {
@UiHandler("m_selectButton")
public void onSelectClick(ClickEvent event) {
if (m_galleryMode == GalleryMode.editor) {
// note: the select button isn't necessarily visible in editor mode (depending on the WYSIWYG editor), but
// if it is, we want it to save the data and close the gallery dialog
if (getHandler().setDataInEditor()) {
// do this after a delay, so we don't get ugly Javascript errors when the iframe is closed.
Timer timer = new Timer() {
@Override
public void run() {
CmsPreviewUtil.closeDialog();
}
};
timer.schedule(1); // depends on control dependency: [if], data = [none]
}
} else {
saveChanges(null); // depends on control dependency: [if], data = [none]
getHandler().selectResource(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void report(ReportRequest req) {
startIfStopped();
statistics.totalReports.incrementAndGet();
statistics.reportedOperations.addAndGet(req.getOperationsCount());
Stopwatch w = Stopwatch.createStarted(ticker);
boolean reported = reportAggregator.report(req);
statistics.totalReportCacheUpdateTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS));
if (!reported) {
try {
statistics.directReports.incrementAndGet();
w.reset().start();
transport.services().report(serviceName, req).execute();
statistics.totalTransportedReportTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS));
} catch (IOException e) {
log.atSevere().withCause(e).log("direct send of a report request %s failed", req);
}
}
if (isRunningSchedulerDirectly()) {
try {
scheduler.run(false /* don't block */);
} catch (InterruptedException e) {
log.atSevere().withCause(e).log("direct run of scheduler failed");
}
}
logStatistics();
} } | public class class_name {
public void report(ReportRequest req) {
startIfStopped();
statistics.totalReports.incrementAndGet();
statistics.reportedOperations.addAndGet(req.getOperationsCount());
Stopwatch w = Stopwatch.createStarted(ticker);
boolean reported = reportAggregator.report(req);
statistics.totalReportCacheUpdateTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS));
if (!reported) {
try {
statistics.directReports.incrementAndGet(); // depends on control dependency: [try], data = [none]
w.reset().start(); // depends on control dependency: [try], data = [none]
transport.services().report(serviceName, req).execute(); // depends on control dependency: [try], data = [none]
statistics.totalTransportedReportTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
log.atSevere().withCause(e).log("direct send of a report request %s failed", req);
} // depends on control dependency: [catch], data = [none]
}
if (isRunningSchedulerDirectly()) {
try {
scheduler.run(false /* don't block */); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
log.atSevere().withCause(e).log("direct run of scheduler failed");
} // depends on control dependency: [catch], data = [none]
}
logStatistics();
} } |
public class class_name {
public void execute( EnforcerRuleHelper helper )
throws EnforcerRuleException
{
log = helper.getLog();
MavenProject project;
try
{
// get the various expressions out of the helper.
project = (MavenProject) helper.evaluate( "${project}" );
LifecycleExecutor life;
life = (LifecycleExecutor) helper.getComponent( LifecycleExecutor.class );
// The lifecycle API changed from Maven 2 to 3 so we have to do a hack to figure
// out which one we're using.
Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( "defaultLifeCycles", life.getClass() );
if ( field != null ) // Using Maven 3
{
Object defaultLifeCycles = ReflectionUtils.getValueIncludingSuperclasses( "defaultLifeCycles", life );
Map lifecyclesMap =
(Map) ReflectionUtils.getValueIncludingSuperclasses( "lifecycles", defaultLifeCycles );
lifecycles = lifecyclesMap.values();
}
else // Using Maven 2
{
lifecycles = (Collection) ReflectionUtils.getValueIncludingSuperclasses( "lifecycles", life );
}
session = (MavenSession) helper.evaluate( "${session}" );
pluginManager = (PluginManager) helper.getComponent( PluginManager.class );
factory = (ArtifactFactory) helper.getComponent( ArtifactFactory.class );
resolver = (ArtifactResolver) helper.getComponent( ArtifactResolver.class );
local = (ArtifactRepository) helper.evaluate( "${localRepository}" );
remoteRepositories = project.getRemoteArtifactRepositories();
utils = new EnforcerRuleUtils( helper );
// get all the plugins that are bound to the specified lifecycles
Set<Plugin> allPlugins = getBoundPlugins( life, project, phases );
// insert any additional plugins specified by the user.
allPlugins = addAdditionalPlugins( allPlugins, additionalPlugins );
allPlugins.addAll( getProfilePlugins( project ) );
// pull out any we should skip
allPlugins =
(Set) removeUncheckedPlugins( combineUncheckedPlugins( unCheckedPlugins, unCheckedPluginList ),
allPlugins );
// there's nothing to do here
if ( allPlugins.isEmpty() )
{
log.info( "No plugin bindings found." );
return;
}
else
{
log.debug( "All Plugins in use: " + allPlugins );
}
// get all the plugins that are mentioned in the pom (and parents)
List<PluginWrapper> pluginWrappers = getAllPluginEntries( project );
// now look for the versions that aren't valid and add to a list.
List<Plugin> failures = new ArrayList<Plugin>();
for ( Plugin plugin : allPlugins )
{
if ( !hasValidVersionSpecified( helper, plugin, pluginWrappers ) )
{
failures.add( plugin );
}
}
// if anything was found, log it then append the optional message.
if ( !failures.isEmpty() )
{
StringBuilder newMsg = new StringBuilder();
newMsg.append( "Some plugins are missing valid versions:" );
if ( banLatest || banRelease || banSnapshots || banTimestamps )
{
newMsg.append( "(" );
if ( banLatest )
{
newMsg.append( "LATEST " );
}
if ( banRelease )
{
newMsg.append( "RELEASE " );
}
if ( banSnapshots || banTimestamps )
{
newMsg.append( "SNAPSHOT " );
}
newMsg.append( "are not allowed )\n" );
}
for ( Plugin plugin : failures )
{
newMsg.append( plugin.getGroupId() );
newMsg.append( ":" );
newMsg.append( plugin.getArtifactId() );
try
{
newMsg.append( ". \tThe version currently in use is " );
Plugin currentPlugin = findCurrentPlugin( plugin, project );
if ( currentPlugin != null )
{
newMsg.append( currentPlugin.getVersion() );
}
else
{
newMsg.append( "unknown" );
}
}
catch ( Exception e )
{
// lots can go wrong here. Don't allow any issues trying to
// determine the issue stop me
log.debug( "Exception while determining plugin Version.", e );
newMsg.append( ". Unable to determine the plugin version." );
}
newMsg.append( "\n" );
}
String message = getMessage();
if ( StringUtils.isNotEmpty( message ) )
{
newMsg.append( message );
}
throw new EnforcerRuleException( newMsg.toString() );
}
}
catch ( ExpressionEvaluationException e )
{
throw new EnforcerRuleException( "Unable to Evaluate an Expression:" + e.getLocalizedMessage() );
}
catch ( ComponentLookupException e )
{
throw new EnforcerRuleException( "Unable to lookup a component:" + e.getLocalizedMessage() );
}
catch ( IllegalAccessException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( LifecycleExecutionException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( PluginNotFoundException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( ArtifactResolutionException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( ArtifactNotFoundException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( IOException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( XmlPullParserException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( MojoExecutionException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
} } | public class class_name {
public void execute( EnforcerRuleHelper helper )
throws EnforcerRuleException
{
log = helper.getLog();
MavenProject project;
try
{
// get the various expressions out of the helper.
project = (MavenProject) helper.evaluate( "${project}" );
LifecycleExecutor life;
life = (LifecycleExecutor) helper.getComponent( LifecycleExecutor.class );
// The lifecycle API changed from Maven 2 to 3 so we have to do a hack to figure
// out which one we're using.
Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( "defaultLifeCycles", life.getClass() );
if ( field != null ) // Using Maven 3
{
Object defaultLifeCycles = ReflectionUtils.getValueIncludingSuperclasses( "defaultLifeCycles", life );
Map lifecyclesMap =
(Map) ReflectionUtils.getValueIncludingSuperclasses( "lifecycles", defaultLifeCycles );
lifecycles = lifecyclesMap.values();
}
else // Using Maven 2
{
lifecycles = (Collection) ReflectionUtils.getValueIncludingSuperclasses( "lifecycles", life );
}
session = (MavenSession) helper.evaluate( "${session}" );
pluginManager = (PluginManager) helper.getComponent( PluginManager.class );
factory = (ArtifactFactory) helper.getComponent( ArtifactFactory.class );
resolver = (ArtifactResolver) helper.getComponent( ArtifactResolver.class );
local = (ArtifactRepository) helper.evaluate( "${localRepository}" );
remoteRepositories = project.getRemoteArtifactRepositories();
utils = new EnforcerRuleUtils( helper );
// get all the plugins that are bound to the specified lifecycles
Set<Plugin> allPlugins = getBoundPlugins( life, project, phases );
// insert any additional plugins specified by the user.
allPlugins = addAdditionalPlugins( allPlugins, additionalPlugins );
allPlugins.addAll( getProfilePlugins( project ) );
// pull out any we should skip
allPlugins =
(Set) removeUncheckedPlugins( combineUncheckedPlugins( unCheckedPlugins, unCheckedPluginList ),
allPlugins );
// there's nothing to do here
if ( allPlugins.isEmpty() )
{
log.info( "No plugin bindings found." );
return;
}
else
{
log.debug( "All Plugins in use: " + allPlugins );
}
// get all the plugins that are mentioned in the pom (and parents)
List<PluginWrapper> pluginWrappers = getAllPluginEntries( project );
// now look for the versions that aren't valid and add to a list.
List<Plugin> failures = new ArrayList<Plugin>();
for ( Plugin plugin : allPlugins )
{
if ( !hasValidVersionSpecified( helper, plugin, pluginWrappers ) )
{
failures.add( plugin ); // depends on control dependency: [if], data = [none]
}
}
// if anything was found, log it then append the optional message.
if ( !failures.isEmpty() )
{
StringBuilder newMsg = new StringBuilder();
newMsg.append( "Some plugins are missing valid versions:" );
if ( banLatest || banRelease || banSnapshots || banTimestamps )
{
newMsg.append( "(" );
if ( banLatest )
{
newMsg.append( "LATEST " ); // depends on control dependency: [if], data = [none]
}
if ( banRelease )
{
newMsg.append( "RELEASE " ); // depends on control dependency: [if], data = [none]
}
if ( banSnapshots || banTimestamps )
{
newMsg.append( "SNAPSHOT " ); // depends on control dependency: [if], data = [none]
}
newMsg.append( "are not allowed )\n" );
}
for ( Plugin plugin : failures )
{
newMsg.append( plugin.getGroupId() );
newMsg.append( ":" );
newMsg.append( plugin.getArtifactId() );
try
{
newMsg.append( ". \tThe version currently in use is " ); // depends on control dependency: [try], data = [none]
Plugin currentPlugin = findCurrentPlugin( plugin, project );
if ( currentPlugin != null )
{
newMsg.append( currentPlugin.getVersion() ); // depends on control dependency: [if], data = [( currentPlugin]
}
else
{
newMsg.append( "unknown" ); // depends on control dependency: [if], data = [none]
}
}
catch ( Exception e )
{
// lots can go wrong here. Don't allow any issues trying to
// determine the issue stop me
log.debug( "Exception while determining plugin Version.", e );
newMsg.append( ". Unable to determine the plugin version." );
} // depends on control dependency: [catch], data = [none]
newMsg.append( "\n" );
}
String message = getMessage();
if ( StringUtils.isNotEmpty( message ) )
{
newMsg.append( message );
}
throw new EnforcerRuleException( newMsg.toString() );
}
}
catch ( ExpressionEvaluationException e )
{
throw new EnforcerRuleException( "Unable to Evaluate an Expression:" + e.getLocalizedMessage() );
}
catch ( ComponentLookupException e )
{
throw new EnforcerRuleException( "Unable to lookup a component:" + e.getLocalizedMessage() );
}
catch ( IllegalAccessException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( LifecycleExecutionException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( PluginNotFoundException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( ArtifactResolutionException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( ArtifactNotFoundException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( IOException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( XmlPullParserException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
catch ( MojoExecutionException e )
{
throw new EnforcerRuleException( e.getLocalizedMessage() );
}
} } |
public class class_name {
public static File getFileFor(final URL anURL, final String encoding) {
// Check sanity
Validate.notNull(anURL, "anURL");
Validate.notNull(encoding, "encoding");
final String protocol = anURL.getProtocol();
File toReturn = null;
if ("file".equalsIgnoreCase(protocol)) {
try {
final String decodedPath = URLDecoder.decode(anURL.getPath(), encoding);
toReturn = new File(decodedPath);
} catch (Exception e) {
throw new IllegalArgumentException("Could not get the File for [" + anURL + "]", e);
}
} else if ("jar".equalsIgnoreCase(protocol)) {
try {
// Decode the JAR
final String tmp = URLDecoder.decode(anURL.getFile(), encoding);
// JAR URLs generally contain layered protocols, such as:
// jar:file:/some/path/to/nazgul-tools-validation-aspect-4.0.2.jar!/the/package/ValidationAspect.class
final URL innerURL = new URL(tmp);
// We can handle File protocol URLs here.
if ("file".equalsIgnoreCase(innerURL.getProtocol())) {
// Peel off the inner protocol
final String innerUrlPath = innerURL.getPath();
final String filePath = innerUrlPath.contains("!")
? innerUrlPath.substring(0, innerUrlPath.indexOf("!"))
: innerUrlPath;
toReturn = new File(URLDecoder.decode(filePath, encoding));
}
} catch (Exception e) {
throw new IllegalArgumentException("Could not get the File for [" + anURL + "]", e);
}
}
// All done.
return toReturn;
} } | public class class_name {
public static File getFileFor(final URL anURL, final String encoding) {
// Check sanity
Validate.notNull(anURL, "anURL");
Validate.notNull(encoding, "encoding");
final String protocol = anURL.getProtocol();
File toReturn = null;
if ("file".equalsIgnoreCase(protocol)) {
try {
final String decodedPath = URLDecoder.decode(anURL.getPath(), encoding);
toReturn = new File(decodedPath); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new IllegalArgumentException("Could not get the File for [" + anURL + "]", e);
} // depends on control dependency: [catch], data = [none]
} else if ("jar".equalsIgnoreCase(protocol)) {
try {
// Decode the JAR
final String tmp = URLDecoder.decode(anURL.getFile(), encoding);
// JAR URLs generally contain layered protocols, such as:
// jar:file:/some/path/to/nazgul-tools-validation-aspect-4.0.2.jar!/the/package/ValidationAspect.class
final URL innerURL = new URL(tmp);
// We can handle File protocol URLs here.
if ("file".equalsIgnoreCase(innerURL.getProtocol())) {
// Peel off the inner protocol
final String innerUrlPath = innerURL.getPath();
final String filePath = innerUrlPath.contains("!")
? innerUrlPath.substring(0, innerUrlPath.indexOf("!"))
: innerUrlPath;
toReturn = new File(URLDecoder.decode(filePath, encoding)); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
throw new IllegalArgumentException("Could not get the File for [" + anURL + "]", e);
} // depends on control dependency: [catch], data = [none]
}
// All done.
return toReturn;
} } |
public class class_name {
@Override
public String getCssText() {
final StringBuilder sb = new StringBuilder();
sb.append("@charset \"");
final String enc = getEncoding();
if (null != enc) {
sb.append(enc);
}
sb.append("\";");
return sb.toString();
} } | public class class_name {
@Override
public String getCssText() {
final StringBuilder sb = new StringBuilder();
sb.append("@charset \"");
final String enc = getEncoding();
if (null != enc) {
sb.append(enc); // depends on control dependency: [if], data = [enc)]
}
sb.append("\";");
return sb.toString();
} } |
public class class_name {
public String findSourceFile(StackTraceElement[] target, String defaultValue) {
for (StackTraceElement e : target) {
if (CLEANER.isIn(e)) {
return e.getFileName();
}
}
return defaultValue;
} } | public class class_name {
public String findSourceFile(StackTraceElement[] target, String defaultValue) {
for (StackTraceElement e : target) {
if (CLEANER.isIn(e)) {
return e.getFileName(); // depends on control dependency: [if], data = [none]
}
}
return defaultValue;
} } |
public class class_name {
public Object getESDataFromDmlData(ESMapping mapping, Map<String, Object> dmlData,
Map<String, Object> esFieldData) {
SchemaItem schemaItem = mapping.getSchemaItem();
String idFieldName = mapping.get_id() == null ? mapping.getPk() : mapping.get_id();
Object resultIdVal = null;
for (FieldItem fieldItem : schemaItem.getSelectFields().values()) {
String columnName = fieldItem.getColumnItems().iterator().next().getColumnName();
Object value = getValFromData(mapping, dmlData, fieldItem.getFieldName(), columnName);
if (fieldItem.getFieldName().equals(idFieldName)) {
resultIdVal = value;
}
if (!fieldItem.getFieldName().equals(mapping.get_id())
&& !mapping.getSkips().contains(fieldItem.getFieldName())) {
esFieldData.put(Util.cleanColumn(fieldItem.getFieldName()), value);
}
}
// 添加父子文档关联信息
putRelationData(mapping, schemaItem, dmlData, esFieldData);
return resultIdVal;
} } | public class class_name {
public Object getESDataFromDmlData(ESMapping mapping, Map<String, Object> dmlData,
Map<String, Object> esFieldData) {
SchemaItem schemaItem = mapping.getSchemaItem();
String idFieldName = mapping.get_id() == null ? mapping.getPk() : mapping.get_id();
Object resultIdVal = null;
for (FieldItem fieldItem : schemaItem.getSelectFields().values()) {
String columnName = fieldItem.getColumnItems().iterator().next().getColumnName();
Object value = getValFromData(mapping, dmlData, fieldItem.getFieldName(), columnName);
if (fieldItem.getFieldName().equals(idFieldName)) {
resultIdVal = value; // depends on control dependency: [if], data = [none]
}
if (!fieldItem.getFieldName().equals(mapping.get_id())
&& !mapping.getSkips().contains(fieldItem.getFieldName())) {
esFieldData.put(Util.cleanColumn(fieldItem.getFieldName()), value); // depends on control dependency: [if], data = [none]
}
}
// 添加父子文档关联信息
putRelationData(mapping, schemaItem, dmlData, esFieldData);
return resultIdVal;
} } |
public class class_name {
public void add(int[] itemset) {
numTransactions++;
int m = 0;
int t = itemset.length;
int[] o = new int[t];
for (int i = 0; i < t; i++) {
int item = itemset[i];
o[i] = order[item];
if (itemSupport[item] >= minSupport) {
m++;
}
}
if (m > 0) {
// Order all items in itemset in frequency descending order
// Note that some items may have same frequency. We have to make
// sure that items are in the same order of header table.
QuickSort.sort(o, itemset, t);
// Note that itemset may contain duplicated items. We should keep
// only one in case of getting incorrect support value.
for (int i = 1; i < m; i++) {
if (itemset[i] == itemset[i-1]) {
m--;
for (int j = i; j < m; j++) {
itemset[j] = itemset[j+1];
}
}
}
root.add(0, m, itemset, 1);
}
} } | public class class_name {
public void add(int[] itemset) {
numTransactions++;
int m = 0;
int t = itemset.length;
int[] o = new int[t];
for (int i = 0; i < t; i++) {
int item = itemset[i];
o[i] = order[item]; // depends on control dependency: [for], data = [i]
if (itemSupport[item] >= minSupport) {
m++; // depends on control dependency: [if], data = [none]
}
}
if (m > 0) {
// Order all items in itemset in frequency descending order
// Note that some items may have same frequency. We have to make
// sure that items are in the same order of header table.
QuickSort.sort(o, itemset, t); // depends on control dependency: [if], data = [none]
// Note that itemset may contain duplicated items. We should keep
// only one in case of getting incorrect support value.
for (int i = 1; i < m; i++) {
if (itemset[i] == itemset[i-1]) {
m--; // depends on control dependency: [if], data = [none]
for (int j = i; j < m; j++) {
itemset[j] = itemset[j+1]; // depends on control dependency: [for], data = [j]
}
}
}
root.add(0, m, itemset, 1); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private @Nullable FileInfo getShardFileInfo(File file) {
FileInfo info = FileInfo.fromFile(file);
if (info == null) {
return null; // file with incorrect name/extension
}
File expectedDirectory = getSubdirectory(info.resourceId);
boolean isCorrect = expectedDirectory.equals(file.getParentFile());
return isCorrect ? info : null;
} } | public class class_name {
private @Nullable FileInfo getShardFileInfo(File file) {
FileInfo info = FileInfo.fromFile(file);
if (info == null) {
return null; // file with incorrect name/extension // depends on control dependency: [if], data = [none]
}
File expectedDirectory = getSubdirectory(info.resourceId);
boolean isCorrect = expectedDirectory.equals(file.getParentFile());
return isCorrect ? info : null;
} } |
public class class_name {
public static base_responses update(nitro_service client, netprofile resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
netprofile updateresources[] = new netprofile[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new netprofile();
updateresources[i].name = resources[i].name;
updateresources[i].srcip = resources[i].srcip;
}
result = update_bulk_request(client, updateresources);
}
return result;
} } | public class class_name {
public static base_responses update(nitro_service client, netprofile resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
netprofile updateresources[] = new netprofile[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new netprofile(); // depends on control dependency: [for], data = [i]
updateresources[i].name = resources[i].name; // depends on control dependency: [for], data = [i]
updateresources[i].srcip = resources[i].srcip; // depends on control dependency: [for], data = [i]
}
result = update_bulk_request(client, updateresources);
}
return result;
} } |
public class class_name {
public static Method getBridgeMethodTarget(Method someMethod) {
TraitBridge annotation = someMethod.getAnnotation(TraitBridge.class);
if (annotation==null) {
return null;
}
Class aClass = annotation.traitClass();
String desc = annotation.desc();
for (Method method : aClass.getDeclaredMethods()) {
String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes());
if (desc.equals(methodDescriptor)) {
return method;
}
}
return null;
} } | public class class_name {
public static Method getBridgeMethodTarget(Method someMethod) {
TraitBridge annotation = someMethod.getAnnotation(TraitBridge.class);
if (annotation==null) {
return null; // depends on control dependency: [if], data = [none]
}
Class aClass = annotation.traitClass();
String desc = annotation.desc();
for (Method method : aClass.getDeclaredMethods()) {
String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes());
if (desc.equals(methodDescriptor)) {
return method; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static double Correlation(double[] p, double[] q) {
double x = 0;
double y = 0;
for (int i = 0; i < p.length; i++) {
x += -p[i];
y += -q[i];
}
x /= p.length;
y /= q.length;
double num = 0;
double den1 = 0;
double den2 = 0;
for (int i = 0; i < p.length; i++) {
num += (p[i] + x) * (q[i] + y);
den1 += Math.abs(Math.pow(p[i] + x, 2));
den2 += Math.abs(Math.pow(q[i] + x, 2));
}
return 1 - (num / (Math.sqrt(den1) * Math.sqrt(den2)));
} } | public class class_name {
public static double Correlation(double[] p, double[] q) {
double x = 0;
double y = 0;
for (int i = 0; i < p.length; i++) {
x += -p[i]; // depends on control dependency: [for], data = [i]
y += -q[i]; // depends on control dependency: [for], data = [i]
}
x /= p.length;
y /= q.length;
double num = 0;
double den1 = 0;
double den2 = 0;
for (int i = 0; i < p.length; i++) {
num += (p[i] + x) * (q[i] + y); // depends on control dependency: [for], data = [i]
den1 += Math.abs(Math.pow(p[i] + x, 2)); // depends on control dependency: [for], data = [i]
den2 += Math.abs(Math.pow(q[i] + x, 2)); // depends on control dependency: [for], data = [i]
}
return 1 - (num / (Math.sqrt(den1) * Math.sqrt(den2)));
} } |
public class class_name {
public ProcessorConfiguration createConfiguration(final CCTask task, final LinkType linkType,
final ProcessorDef baseDef, final TargetDef targetPlatform, final VersionInfo versionInfo) {
if (isReference()) {
return ((ProcessorDef) getCheckedRef(ProcessorDef.class, "ProcessorDef")).createConfiguration(task, linkType,
baseDef, targetPlatform, versionInfo);
}
final ProcessorDef[] defaultProviders = getDefaultProviders(baseDef);
final Processor proc = getProcessor(linkType);
return proc.createConfiguration(task, linkType, defaultProviders, this, targetPlatform, versionInfo);
} } | public class class_name {
public ProcessorConfiguration createConfiguration(final CCTask task, final LinkType linkType,
final ProcessorDef baseDef, final TargetDef targetPlatform, final VersionInfo versionInfo) {
if (isReference()) {
return ((ProcessorDef) getCheckedRef(ProcessorDef.class, "ProcessorDef")).createConfiguration(task, linkType,
baseDef, targetPlatform, versionInfo); // depends on control dependency: [if], data = [none]
}
final ProcessorDef[] defaultProviders = getDefaultProviders(baseDef);
final Processor proc = getProcessor(linkType);
return proc.createConfiguration(task, linkType, defaultProviders, this, targetPlatform, versionInfo);
} } |
public class class_name {
private <T> boolean processMethod(AnnotatedMethod<T> method, Class<?> clazz, Asynchronous classLevelAsync) {
FTEnablementConfig config = FaultToleranceCDIComponent.getEnablementConfig();
Method javaMethod = method.getJavaMember();
if (javaMethod.isBridge()) {
// Skip all validation for bridge methods
// Bridge methods are created when a class overrides a method but provides more specific return or parameter types
// (usually when implementing a generic interface)
// In these cases, the bridge method matches the signature of the overridden method after type erasure and delegates directly to the overriding method
// In some cases, the signature of the overriding method is valid for some microprofile annotation, but the signature of the bridge method is not
// However, the user's code is valid, and weld seems to make sure that any interceptors get called with the real method in the InvocationContext.
return false;
}
if (classLevelAsync != null) {
AsynchronousConfig asynchronous = annotationConfigFactory.createAsynchronousConfig(javaMethod, clazz, classLevelAsync);
asynchronous.validate();
}
boolean needsIntercepting = false;
Set<Annotation> annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
if (config.isFaultTolerance(annotation)) {
if (config.isAnnotationEnabled(annotation, clazz, method.getJavaMember())) {
needsIntercepting = true;
if (annotation.annotationType() == Asynchronous.class) {
AsynchronousConfig asynchronous = annotationConfigFactory.createAsynchronousConfig(javaMethod, clazz, (Asynchronous) annotation);
asynchronous.validate();
} else if (annotation.annotationType() == Fallback.class) {
FallbackConfig fallback = new FallbackConfig(javaMethod, clazz, (Fallback) annotation);
fallback.validate();
} else if (annotation.annotationType() == Retry.class) {
RetryConfig retry = new RetryConfig(javaMethod, clazz, (Retry) annotation);
retry.validate();
} else if (annotation.annotationType() == Timeout.class) {
TimeoutConfig timeout = new TimeoutConfig(javaMethod, clazz, (Timeout) annotation);
timeout.validate();
} else if (annotation.annotationType() == CircuitBreaker.class) {
CircuitBreakerConfig circuitBreaker = new CircuitBreakerConfig(javaMethod, clazz, (CircuitBreaker) annotation);
circuitBreaker.validate();
} else if (annotation.annotationType() == Bulkhead.class) {
BulkheadConfig bulkhead = new BulkheadConfig(javaMethod, clazz, (Bulkhead) annotation);
bulkhead.validate();
}
} else {
if (isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Annotation {0} on {1} was disabled and will be ignored", annotation.annotationType().getSimpleName(),
clazz.getCanonicalName() + "." + method.getJavaMember().getName());
}
}
}
}
return needsIntercepting;
} } | public class class_name {
private <T> boolean processMethod(AnnotatedMethod<T> method, Class<?> clazz, Asynchronous classLevelAsync) {
FTEnablementConfig config = FaultToleranceCDIComponent.getEnablementConfig();
Method javaMethod = method.getJavaMember();
if (javaMethod.isBridge()) {
// Skip all validation for bridge methods
// Bridge methods are created when a class overrides a method but provides more specific return or parameter types
// (usually when implementing a generic interface)
// In these cases, the bridge method matches the signature of the overridden method after type erasure and delegates directly to the overriding method
// In some cases, the signature of the overriding method is valid for some microprofile annotation, but the signature of the bridge method is not
// However, the user's code is valid, and weld seems to make sure that any interceptors get called with the real method in the InvocationContext.
return false; // depends on control dependency: [if], data = [none]
}
if (classLevelAsync != null) {
AsynchronousConfig asynchronous = annotationConfigFactory.createAsynchronousConfig(javaMethod, clazz, classLevelAsync);
asynchronous.validate(); // depends on control dependency: [if], data = [none]
}
boolean needsIntercepting = false;
Set<Annotation> annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
if (config.isFaultTolerance(annotation)) {
if (config.isAnnotationEnabled(annotation, clazz, method.getJavaMember())) {
needsIntercepting = true; // depends on control dependency: [if], data = [none]
if (annotation.annotationType() == Asynchronous.class) {
AsynchronousConfig asynchronous = annotationConfigFactory.createAsynchronousConfig(javaMethod, clazz, (Asynchronous) annotation);
asynchronous.validate(); // depends on control dependency: [if], data = [none]
} else if (annotation.annotationType() == Fallback.class) {
FallbackConfig fallback = new FallbackConfig(javaMethod, clazz, (Fallback) annotation);
fallback.validate(); // depends on control dependency: [if], data = [none]
} else if (annotation.annotationType() == Retry.class) {
RetryConfig retry = new RetryConfig(javaMethod, clazz, (Retry) annotation);
retry.validate(); // depends on control dependency: [if], data = [none]
} else if (annotation.annotationType() == Timeout.class) {
TimeoutConfig timeout = new TimeoutConfig(javaMethod, clazz, (Timeout) annotation);
timeout.validate(); // depends on control dependency: [if], data = [none]
} else if (annotation.annotationType() == CircuitBreaker.class) {
CircuitBreakerConfig circuitBreaker = new CircuitBreakerConfig(javaMethod, clazz, (CircuitBreaker) annotation);
circuitBreaker.validate(); // depends on control dependency: [if], data = [none]
} else if (annotation.annotationType() == Bulkhead.class) {
BulkheadConfig bulkhead = new BulkheadConfig(javaMethod, clazz, (Bulkhead) annotation);
bulkhead.validate(); // depends on control dependency: [if], data = [none]
}
} else {
if (isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Annotation {0} on {1} was disabled and will be ignored", annotation.annotationType().getSimpleName(),
clazz.getCanonicalName() + "." + method.getJavaMember().getName()); // depends on control dependency: [if], data = [none]
}
}
}
}
return needsIntercepting;
} } |
public class class_name {
private int bagSizePower() throws IOException
{
long avgObjectSize = (valuesOut.size() + numWritten - 1) / numWritten;
for (int i = 31; i >= 0; --i) {
if ((1L << i) * avgObjectSize <= fileSizeLimit) {
if (actuallyFits(i)) {
return i;
}
}
}
throw new ISE(
"no value split found with fileSizeLimit [%d], avgObjectSize [%d]",
fileSizeLimit,
avgObjectSize
);
} } | public class class_name {
private int bagSizePower() throws IOException
{
long avgObjectSize = (valuesOut.size() + numWritten - 1) / numWritten;
for (int i = 31; i >= 0; --i) {
if ((1L << i) * avgObjectSize <= fileSizeLimit) {
if (actuallyFits(i)) {
return i; // depends on control dependency: [if], data = [none]
}
}
}
throw new ISE(
"no value split found with fileSizeLimit [%d], avgObjectSize [%d]",
fileSizeLimit,
avgObjectSize
);
} } |
public class class_name {
public String readUntil (final char... aEndChars)
{
final StringBuilder aSB = new StringBuilder ();
int nPos = m_nPos;
while (nPos < m_sValue.length ())
{
final char ch = m_sValue.charAt (nPos);
if (ch == '\\' && nPos + 1 < m_sValue.length ())
{
final char c = m_sValue.charAt (nPos + 1);
if (MarkdownHelper.isEscapeChar (c))
{
aSB.append (c);
nPos++;
}
else
aSB.append (ch);
}
else
{
boolean bEndReached = false;
for (final char cElement : aEndChars)
if (ch == cElement)
{
bEndReached = true;
break;
}
if (bEndReached)
break;
aSB.append (ch);
}
nPos++;
}
final char ch = nPos < m_sValue.length () ? m_sValue.charAt (nPos) : '\n';
for (final char cElement : aEndChars)
if (ch == cElement)
{
m_nPos = nPos;
return aSB.toString ();
}
return null;
} } | public class class_name {
public String readUntil (final char... aEndChars)
{
final StringBuilder aSB = new StringBuilder ();
int nPos = m_nPos;
while (nPos < m_sValue.length ())
{
final char ch = m_sValue.charAt (nPos);
if (ch == '\\' && nPos + 1 < m_sValue.length ())
{
final char c = m_sValue.charAt (nPos + 1);
if (MarkdownHelper.isEscapeChar (c))
{
aSB.append (c); // depends on control dependency: [if], data = [none]
nPos++; // depends on control dependency: [if], data = [none]
}
else
aSB.append (ch);
}
else
{
boolean bEndReached = false;
for (final char cElement : aEndChars)
if (ch == cElement)
{
bEndReached = true; // depends on control dependency: [if], data = [none]
break;
}
if (bEndReached)
break;
aSB.append (ch); // depends on control dependency: [if], data = [(ch]
}
nPos++; // depends on control dependency: [while], data = [none]
}
final char ch = nPos < m_sValue.length () ? m_sValue.charAt (nPos) : '\n';
for (final char cElement : aEndChars)
if (ch == cElement)
{
m_nPos = nPos; // depends on control dependency: [if], data = [none]
return aSB.toString (); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
public T findOne(I id, QuerySpec querySpec) {
RegistryEntry entry = resourceRegistry.findEntry(resourceClass);
String idName = entry.getResourceInformation().getIdField().getUnderlyingName();
QuerySpec idQuerySpec = querySpec.duplicate();
idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idName), FilterOperator.EQ, id));
Iterable<T> iterable = findAll(idQuerySpec);
Iterator<T> iterator = iterable.iterator();
if (iterator.hasNext()) {
T resource = iterator.next();
PreconditionUtil.assertFalse("expected unique result", iterator.hasNext());
return resource;
} else {
throw new ResourceNotFoundException("resource not found");
}
} } | public class class_name {
@Override
public T findOne(I id, QuerySpec querySpec) {
RegistryEntry entry = resourceRegistry.findEntry(resourceClass);
String idName = entry.getResourceInformation().getIdField().getUnderlyingName();
QuerySpec idQuerySpec = querySpec.duplicate();
idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idName), FilterOperator.EQ, id));
Iterable<T> iterable = findAll(idQuerySpec);
Iterator<T> iterator = iterable.iterator();
if (iterator.hasNext()) {
T resource = iterator.next();
PreconditionUtil.assertFalse("expected unique result", iterator.hasNext()); // depends on control dependency: [if], data = [none]
return resource; // depends on control dependency: [if], data = [none]
} else {
throw new ResourceNotFoundException("resource not found");
}
} } |
public class class_name {
public Object doRemoteCommand(String strCommand, Map<String, Object> properties) throws RemoteException, DBException
{
int iRecordCount = m_vRecordList.getRecordCount();
int iOldMasterSlave = this.setMasterSlave(RecordOwner.SLAVE | RecordOwner.MASTER);
Record record = this.getMainRecord();
if (properties != null)
if (Boolean.TRUE.equals(properties.get(MenuConstants.CLONE)))
if (record.getClass().getName().equals(properties.get(DBParams.RECORD)))
{
try {
record = (Record)record.clone();
this.addRecord(record);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
record.readSameRecord(this.getMainRecord(), false, false);
}
Object objReturn = record.doRemoteCommand(strCommand, properties);
this.setMasterSlave(iOldMasterSlave);
if (record != this.getMainRecord())
{
record.free();
while (m_vRecordList.getRecordCount() > iRecordCount)
{ // Close all except the main record
m_vRecordList.getRecordAt(m_vRecordList.getRecordCount() - 1).free();
}
}
if (!Boolean.FALSE.equals(objReturn))
return objReturn;
return super.doRemoteCommand(strCommand, properties);
} } | public class class_name {
public Object doRemoteCommand(String strCommand, Map<String, Object> properties) throws RemoteException, DBException
{
int iRecordCount = m_vRecordList.getRecordCount();
int iOldMasterSlave = this.setMasterSlave(RecordOwner.SLAVE | RecordOwner.MASTER);
Record record = this.getMainRecord();
if (properties != null)
if (Boolean.TRUE.equals(properties.get(MenuConstants.CLONE)))
if (record.getClass().getName().equals(properties.get(DBParams.RECORD)))
{
try {
record = (Record)record.clone(); // depends on control dependency: [try], data = [none]
this.addRecord(record); // depends on control dependency: [try], data = [none]
} catch (CloneNotSupportedException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
record.readSameRecord(this.getMainRecord(), false, false);
}
Object objReturn = record.doRemoteCommand(strCommand, properties);
this.setMasterSlave(iOldMasterSlave);
if (record != this.getMainRecord())
{
record.free();
while (m_vRecordList.getRecordCount() > iRecordCount)
{ // Close all except the main record
m_vRecordList.getRecordAt(m_vRecordList.getRecordCount() - 1).free();
}
}
if (!Boolean.FALSE.equals(objReturn))
return objReturn;
return super.doRemoteCommand(strCommand, properties);
} } |
public class class_name {
@SuppressWarnings("rawtypes")
public final Map<String, MtasDataItemNumberComparator> getComparatorList()
throws IOException {
if (collectorType.equals(DataCollector.COLLECTOR_TYPE_LIST)) {
LinkedHashMap<String, MtasDataItemNumberComparator> comparatorList = new LinkedHashMap<>();
for (Entry<String, MtasDataItem<T1, T2>> entry : list.entrySet()) {
comparatorList.put(entry.getKey(),
entry.getValue().getComparableValue());
}
return comparatorList;
} else {
throw new IOException("type " + collectorType + " not supported");
}
} } | public class class_name {
@SuppressWarnings("rawtypes")
public final Map<String, MtasDataItemNumberComparator> getComparatorList()
throws IOException {
if (collectorType.equals(DataCollector.COLLECTOR_TYPE_LIST)) {
LinkedHashMap<String, MtasDataItemNumberComparator> comparatorList = new LinkedHashMap<>();
for (Entry<String, MtasDataItem<T1, T2>> entry : list.entrySet()) {
comparatorList.put(entry.getKey(),
entry.getValue().getComparableValue()); // depends on control dependency: [for], data = [entry]
}
return comparatorList;
} else {
throw new IOException("type " + collectorType + " not supported");
}
} } |
public class class_name {
protected String preprocessSql(String sqlString) {
// detects callable statement
if (sqlString.charAt(0) == '{') {
return sqlString;
}
// quickly detect if SQL string is a key
if (!CharUtil.isAlpha(sqlString.charAt(0))) {
sqlString = sqlString.substring(1);
}
else if (sqlString.indexOf(' ') != -1) {
return sqlString;
}
final String sqlFromMap = dbOom.queryMap().getQuery(sqlString);
if (sqlFromMap != null) {
sqlString = sqlFromMap.trim();
}
return sqlString;
} } | public class class_name {
protected String preprocessSql(String sqlString) {
// detects callable statement
if (sqlString.charAt(0) == '{') {
return sqlString; // depends on control dependency: [if], data = [none]
}
// quickly detect if SQL string is a key
if (!CharUtil.isAlpha(sqlString.charAt(0))) {
sqlString = sqlString.substring(1); // depends on control dependency: [if], data = [none]
}
else if (sqlString.indexOf(' ') != -1) {
return sqlString; // depends on control dependency: [if], data = [none]
}
final String sqlFromMap = dbOom.queryMap().getQuery(sqlString);
if (sqlFromMap != null) {
sqlString = sqlFromMap.trim(); // depends on control dependency: [if], data = [none]
}
return sqlString;
} } |
public class class_name {
public static String quote(String s, String delim)
{
if (s==null)
return null;
if (s.length()==0)
return "\"\"";
for (int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if (c=='"' ||
c=='\\' ||
c=='\'' ||
delim.indexOf(c)>=0)
{
StringBuffer b=new StringBuffer(s.length()+8);
quote(b,s);
return b.toString();
}
}
return s;
} } | public class class_name {
public static String quote(String s, String delim)
{
if (s==null)
return null;
if (s.length()==0)
return "\"\"";
for (int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if (c=='"' ||
c=='\\' ||
c=='\'' ||
delim.indexOf(c)>=0)
{
StringBuffer b=new StringBuffer(s.length()+8);
quote(b,s); // depends on control dependency: [if], data = [none]
return b.toString(); // depends on control dependency: [if], data = [none]
}
}
return s;
} } |
public class class_name {
public void addAnimations (Animation[] anims)
{
int acount = anims.length;
for (int ii = 0; ii < acount; ii++) {
addAnimation(anims[ii]);
}
} } | public class class_name {
public void addAnimations (Animation[] anims)
{
int acount = anims.length;
for (int ii = 0; ii < acount; ii++) {
addAnimation(anims[ii]); // depends on control dependency: [for], data = [ii]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.