code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private static int isIsolatedTashkeelChar(char ch){
if (ch >= 0xfe70 && ch <= 0xfe7f && ch != NEW_TAIL_CHAR && ch != 0xFE75){
return (1 - tashkeelMedial [ch - 0xFE70]);
} else if(ch >= 0xfc5e && ch <= 0xfc63){
return 1;
} else{
return 0;
}
} } | public class class_name {
private static int isIsolatedTashkeelChar(char ch){
if (ch >= 0xfe70 && ch <= 0xfe7f && ch != NEW_TAIL_CHAR && ch != 0xFE75){
return (1 - tashkeelMedial [ch - 0xFE70]); // depends on control dependency: [if], data = [none]
} else if(ch >= 0xfc5e && ch <= 0xfc63){
return 1; // depends on control dependency: [if], data = [none]
} else{
return 0; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(GetUsageRequest getUsageRequest, ProtocolMarshaller protocolMarshaller) {
if (getUsageRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getUsageRequest.getUsagePlanId(), USAGEPLANID_BINDING);
protocolMarshaller.marshall(getUsageRequest.getKeyId(), KEYID_BINDING);
protocolMarshaller.marshall(getUsageRequest.getStartDate(), STARTDATE_BINDING);
protocolMarshaller.marshall(getUsageRequest.getEndDate(), ENDDATE_BINDING);
protocolMarshaller.marshall(getUsageRequest.getPosition(), POSITION_BINDING);
protocolMarshaller.marshall(getUsageRequest.getLimit(), LIMIT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetUsageRequest getUsageRequest, ProtocolMarshaller protocolMarshaller) {
if (getUsageRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getUsageRequest.getUsagePlanId(), USAGEPLANID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getUsageRequest.getKeyId(), KEYID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getUsageRequest.getStartDate(), STARTDATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getUsageRequest.getEndDate(), ENDDATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getUsageRequest.getPosition(), POSITION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getUsageRequest.getLimit(), LIMIT_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private String readScript( File file) throws IOException {
if ( file == null) return null;
StringBuilder script = new StringBuilder();
BufferedReader in = new BufferedReader( new FileReader(file));
try {
String line;
while (( line = in.readLine()) != null) {
script.append( line);
script.append( "\n");
}
} finally {
in.close();
}
return script.toString();
} } | public class class_name {
private String readScript( File file) throws IOException {
if ( file == null) return null;
StringBuilder script = new StringBuilder();
BufferedReader in = new BufferedReader( new FileReader(file));
try {
String line;
while (( line = in.readLine()) != null) {
script.append( line); // depends on control dependency: [while], data = [none]
script.append( "\n"); // depends on control dependency: [while], data = [none]
}
} finally {
in.close();
}
return script.toString();
} } |
public class class_name {
private void buildCommunicationSummaryStatistics(Map<String, CommunicationSummaryStatistics> stats, String index,
Criteria criteria, boolean addMetrics) {
if (!refresh(index)) {
return;
}
// Don't specify target class, so that query provided that can be used with
// CommunicationDetails and CompletionTime
BoolQueryBuilder query = buildQuery(criteria, ElasticsearchUtil.TRANSACTION_FIELD, null);
// Only want external communications
query = query.mustNot(QueryBuilders.matchQuery("internal", "true"));
StatsBuilder latencyBuilder = AggregationBuilders
.stats("latency")
.field(ElasticsearchUtil.LATENCY_FIELD);
TermsBuilder targetBuilder = AggregationBuilders
.terms("target")
.field(ElasticsearchUtil.TARGET_FIELD)
.size(criteria.getMaxResponseSize())
.subAggregation(latencyBuilder);
TermsBuilder sourceBuilder = AggregationBuilders
.terms("source")
.field(ElasticsearchUtil.SOURCE_FIELD)
.size(criteria.getMaxResponseSize())
.subAggregation(targetBuilder);
SearchRequestBuilder request = getBaseSearchRequestBuilder(COMMUNICATION_DETAILS_TYPE, index, criteria, query, 0)
.addAggregation(sourceBuilder);
SearchResponse response = getSearchResponse(request);
for (Terms.Bucket sourceBucket : response.getAggregations().<Terms>get("source").getBuckets()) {
Terms targets = sourceBucket.getAggregations().get("target");
CommunicationSummaryStatistics css = stats.get(sourceBucket.getKey());
if (css == null) {
css = new CommunicationSummaryStatistics();
css.setId(sourceBucket.getKey());
css.setUri(EndpointUtil.decodeEndpointURI(css.getId()));
css.setOperation(EndpointUtil.decodeEndpointOperation(css.getId(), true));
stats.put(css.getId(), css);
}
if (addMetrics) {
css.setCount(sourceBucket.getDocCount());
}
for (Terms.Bucket targetBucket : targets.getBuckets()) {
Stats latency = targetBucket.getAggregations().get("latency");
String linkId = targetBucket.getKey();
ConnectionStatistics con = css.getOutbound().get(linkId);
if (con == null) {
con = new ConnectionStatistics();
css.getOutbound().put(linkId, con);
}
if (addMetrics) {
con.setMinimumLatency((long)latency.getMin());
con.setAverageLatency((long)latency.getAvg());
con.setMaximumLatency((long)latency.getMax());
con.setCount(targetBucket.getDocCount());
}
}
}
addNodeInformation(stats, index, criteria, addMetrics, false);
addNodeInformation(stats, index, criteria, addMetrics, true);
} } | public class class_name {
private void buildCommunicationSummaryStatistics(Map<String, CommunicationSummaryStatistics> stats, String index,
Criteria criteria, boolean addMetrics) {
if (!refresh(index)) {
return; // depends on control dependency: [if], data = [none]
}
// Don't specify target class, so that query provided that can be used with
// CommunicationDetails and CompletionTime
BoolQueryBuilder query = buildQuery(criteria, ElasticsearchUtil.TRANSACTION_FIELD, null);
// Only want external communications
query = query.mustNot(QueryBuilders.matchQuery("internal", "true"));
StatsBuilder latencyBuilder = AggregationBuilders
.stats("latency")
.field(ElasticsearchUtil.LATENCY_FIELD);
TermsBuilder targetBuilder = AggregationBuilders
.terms("target")
.field(ElasticsearchUtil.TARGET_FIELD)
.size(criteria.getMaxResponseSize())
.subAggregation(latencyBuilder);
TermsBuilder sourceBuilder = AggregationBuilders
.terms("source")
.field(ElasticsearchUtil.SOURCE_FIELD)
.size(criteria.getMaxResponseSize())
.subAggregation(targetBuilder);
SearchRequestBuilder request = getBaseSearchRequestBuilder(COMMUNICATION_DETAILS_TYPE, index, criteria, query, 0)
.addAggregation(sourceBuilder);
SearchResponse response = getSearchResponse(request);
for (Terms.Bucket sourceBucket : response.getAggregations().<Terms>get("source").getBuckets()) {
Terms targets = sourceBucket.getAggregations().get("target");
CommunicationSummaryStatistics css = stats.get(sourceBucket.getKey());
if (css == null) {
css = new CommunicationSummaryStatistics(); // depends on control dependency: [if], data = [none]
css.setId(sourceBucket.getKey()); // depends on control dependency: [if], data = [none]
css.setUri(EndpointUtil.decodeEndpointURI(css.getId())); // depends on control dependency: [if], data = [(css]
css.setOperation(EndpointUtil.decodeEndpointOperation(css.getId(), true)); // depends on control dependency: [if], data = [(css]
stats.put(css.getId(), css); // depends on control dependency: [if], data = [(css]
}
if (addMetrics) {
css.setCount(sourceBucket.getDocCount()); // depends on control dependency: [if], data = [none]
}
for (Terms.Bucket targetBucket : targets.getBuckets()) {
Stats latency = targetBucket.getAggregations().get("latency");
String linkId = targetBucket.getKey();
ConnectionStatistics con = css.getOutbound().get(linkId);
if (con == null) {
con = new ConnectionStatistics(); // depends on control dependency: [if], data = [none]
css.getOutbound().put(linkId, con); // depends on control dependency: [if], data = [none]
}
if (addMetrics) {
con.setMinimumLatency((long)latency.getMin()); // depends on control dependency: [if], data = [none]
con.setAverageLatency((long)latency.getAvg()); // depends on control dependency: [if], data = [none]
con.setMaximumLatency((long)latency.getMax()); // depends on control dependency: [if], data = [none]
con.setCount(targetBucket.getDocCount()); // depends on control dependency: [if], data = [none]
}
}
}
addNodeInformation(stats, index, criteria, addMetrics, false);
addNodeInformation(stats, index, criteria, addMetrics, true);
} } |
public class class_name {
public static int getSingleBondEquivalentSum(Iterator<IBond> bonds) {
int sum = 0;
while (bonds.hasNext()) {
IBond.Order order = bonds.next().getOrder();
if (order != null) {
sum += order.numeric();
}
}
return sum;
} } | public class class_name {
public static int getSingleBondEquivalentSum(Iterator<IBond> bonds) {
int sum = 0;
while (bonds.hasNext()) {
IBond.Order order = bonds.next().getOrder();
if (order != null) {
sum += order.numeric(); // depends on control dependency: [if], data = [none]
}
}
return sum;
} } |
public class class_name {
public void marshall(ParameterRanges parameterRanges, ProtocolMarshaller protocolMarshaller) {
if (parameterRanges == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(parameterRanges.getIntegerParameterRanges(), INTEGERPARAMETERRANGES_BINDING);
protocolMarshaller.marshall(parameterRanges.getContinuousParameterRanges(), CONTINUOUSPARAMETERRANGES_BINDING);
protocolMarshaller.marshall(parameterRanges.getCategoricalParameterRanges(), CATEGORICALPARAMETERRANGES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ParameterRanges parameterRanges, ProtocolMarshaller protocolMarshaller) {
if (parameterRanges == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(parameterRanges.getIntegerParameterRanges(), INTEGERPARAMETERRANGES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(parameterRanges.getContinuousParameterRanges(), CONTINUOUSPARAMETERRANGES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(parameterRanges.getCategoricalParameterRanges(), CATEGORICALPARAMETERRANGES_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void writeByteBuffer(WsByteBuffer[] buf) {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.entering(CLASS_NAME, "writeByteBuffer");
}
if (!committed)
{
if (!_hasFlushed && obs != null)
{
_hasFlushed = true;
obs.alertFirstFlush();
}
}
committed = true;
((ByteBufferWriter)out).writeByteBuffer(buf);
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.exiting(CLASS_NAME, "writeByteBuffer");
}
} } | public class class_name {
public void writeByteBuffer(WsByteBuffer[] buf) {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.entering(CLASS_NAME, "writeByteBuffer"); // depends on control dependency: [if], data = [none]
}
if (!committed)
{
if (!_hasFlushed && obs != null)
{
_hasFlushed = true; // depends on control dependency: [if], data = [none]
obs.alertFirstFlush(); // depends on control dependency: [if], data = [none]
}
}
committed = true;
((ByteBufferWriter)out).writeByteBuffer(buf);
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.exiting(CLASS_NAME, "writeByteBuffer"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out)
throws Exception {
boolean found = false;
boolean finished = false;
while (in.hasRemaining()) {
byte b = in.get();
if (!hasCR) {
if (b == CR) {
hasCR = true;
} else {
if (b == LF) {
found = true;
} else {
in.position(in.position() - 1);
found = false;
}
finished = true;
break;
}
} else {
if (b == LF) {
found = true;
finished = true;
break;
}
throw new ProtocolDecoderException(
"Expected LF after CR but was: " + (b & 0xff));
}
}
if (finished) {
hasCR = false;
return finishDecode(found, out);
}
return this;
} } | public class class_name {
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out)
throws Exception {
boolean found = false;
boolean finished = false;
while (in.hasRemaining()) {
byte b = in.get();
if (!hasCR) {
if (b == CR) {
hasCR = true; // depends on control dependency: [if], data = [none]
} else {
if (b == LF) {
found = true; // depends on control dependency: [if], data = [none]
} else {
in.position(in.position() - 1); // depends on control dependency: [if], data = [none]
found = false; // depends on control dependency: [if], data = [none]
}
finished = true; // depends on control dependency: [if], data = [none]
break;
}
} else {
if (b == LF) {
found = true; // depends on control dependency: [if], data = [none]
finished = true; // depends on control dependency: [if], data = [none]
break;
}
throw new ProtocolDecoderException(
"Expected LF after CR but was: " + (b & 0xff));
}
}
if (finished) {
hasCR = false;
return finishDecode(found, out);
}
return this;
} } |
public class class_name {
@Override
public void setAction(Context context, final SocializeAction action) {
try {
doSetAction(action);
}
catch (Exception e) {
setText("Error!");
if(logger != null) {
logger.error("Error rendering action text", e);
}
else {
SocializeLogger.e(e.getMessage(), e);
}
}
} } | public class class_name {
@Override
public void setAction(Context context, final SocializeAction action) {
try {
doSetAction(action); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
setText("Error!");
if(logger != null) {
logger.error("Error rendering action text", e); // depends on control dependency: [if], data = [none]
}
else {
SocializeLogger.e(e.getMessage(), e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
void commit(final boolean isJobCancelled)
throws IOException {
this.datasetStatesByUrns = Optional.of(computeDatasetStatesByUrns());
final boolean shouldCommitDataInJob = shouldCommitDataInJob(this.jobState);
final DeliverySemantics deliverySemantics = DeliverySemantics.parse(this.jobState);
final int numCommitThreads = numCommitThreads();
if (!shouldCommitDataInJob) {
this.logger.info("Job will not commit data since data are committed by tasks.");
}
try {
if (this.datasetStatesByUrns.isPresent()) {
this.logger.info("Persisting dataset urns.");
this.datasetStateStore.persistDatasetURNs(this.jobName, this.datasetStatesByUrns.get().keySet());
}
List<Either<Void, ExecutionException>> result = new IteratorExecutor<>(Iterables
.transform(this.datasetStatesByUrns.get().entrySet(),
new Function<Map.Entry<String, DatasetState>, Callable<Void>>() {
@Nullable
@Override
public Callable<Void> apply(final Map.Entry<String, DatasetState> entry) {
return createSafeDatasetCommit(shouldCommitDataInJob, isJobCancelled, deliverySemantics,
entry.getKey(), entry.getValue(), numCommitThreads > 1, JobContext.this);
}
}).iterator(), numCommitThreads,
ExecutorsUtils.newThreadFactory(Optional.of(this.logger), Optional.of("Commit-thread-%d")))
.executeAndGetResults();
IteratorExecutor.logFailures(result, LOG, 10);
if (!IteratorExecutor.verifyAllSuccessful(result)) {
this.jobState.setState(JobState.RunningState.FAILED);
throw new IOException("Failed to commit dataset state for some dataset(s) of job " + this.jobId);
}
} catch (InterruptedException exc) {
throw new IOException(exc);
}
this.jobState.setState(JobState.RunningState.COMMITTED);
} } | public class class_name {
void commit(final boolean isJobCancelled)
throws IOException {
this.datasetStatesByUrns = Optional.of(computeDatasetStatesByUrns());
final boolean shouldCommitDataInJob = shouldCommitDataInJob(this.jobState);
final DeliverySemantics deliverySemantics = DeliverySemantics.parse(this.jobState);
final int numCommitThreads = numCommitThreads();
if (!shouldCommitDataInJob) {
this.logger.info("Job will not commit data since data are committed by tasks.");
}
try {
if (this.datasetStatesByUrns.isPresent()) {
this.logger.info("Persisting dataset urns."); // depends on control dependency: [if], data = [none]
this.datasetStateStore.persistDatasetURNs(this.jobName, this.datasetStatesByUrns.get().keySet()); // depends on control dependency: [if], data = [none]
}
List<Either<Void, ExecutionException>> result = new IteratorExecutor<>(Iterables
.transform(this.datasetStatesByUrns.get().entrySet(),
new Function<Map.Entry<String, DatasetState>, Callable<Void>>() {
@Nullable
@Override
public Callable<Void> apply(final Map.Entry<String, DatasetState> entry) {
return createSafeDatasetCommit(shouldCommitDataInJob, isJobCancelled, deliverySemantics,
entry.getKey(), entry.getValue(), numCommitThreads > 1, JobContext.this);
}
}).iterator(), numCommitThreads,
ExecutorsUtils.newThreadFactory(Optional.of(this.logger), Optional.of("Commit-thread-%d")))
.executeAndGetResults();
IteratorExecutor.logFailures(result, LOG, 10);
if (!IteratorExecutor.verifyAllSuccessful(result)) {
this.jobState.setState(JobState.RunningState.FAILED); // depends on control dependency: [if], data = [none]
throw new IOException("Failed to commit dataset state for some dataset(s) of job " + this.jobId);
}
} catch (InterruptedException exc) {
throw new IOException(exc);
}
this.jobState.setState(JobState.RunningState.COMMITTED);
} } |
public class class_name {
@Override
public void aggregate(final ByteBuffer buf, final int position)
{
for (int i = 0; i < valueSelectors.length; i++) {
values[i] = valueSelectors[i].getDouble();
}
final IndexedInts keys = keySelector.getRow();
// Wrapping memory and ArrayOfDoublesSketch is inexpensive compared to sketch operations.
// Maintaining a cache of wrapped objects per buffer position like in Theta sketch aggregator
// might might be considered, but it would increase complexity including relocate() support.
final WritableMemory mem = WritableMemory.wrap(buf, ByteOrder.LITTLE_ENDIAN);
final WritableMemory region = mem.writableRegion(position, maxIntermediateSize);
final Lock lock = stripedLock.getAt(lockIndex(position)).writeLock();
lock.lock();
try {
final ArrayOfDoublesUpdatableSketch sketch = ArrayOfDoublesSketches.wrapUpdatableSketch(region);
for (int i = 0, keysSize = keys.size(); i < keysSize; i++) {
final String key = keySelector.lookupName(keys.get(i));
sketch.update(key, values);
}
}
finally {
lock.unlock();
}
} } | public class class_name {
@Override
public void aggregate(final ByteBuffer buf, final int position)
{
for (int i = 0; i < valueSelectors.length; i++) {
values[i] = valueSelectors[i].getDouble(); // depends on control dependency: [for], data = [i]
}
final IndexedInts keys = keySelector.getRow();
// Wrapping memory and ArrayOfDoublesSketch is inexpensive compared to sketch operations.
// Maintaining a cache of wrapped objects per buffer position like in Theta sketch aggregator
// might might be considered, but it would increase complexity including relocate() support.
final WritableMemory mem = WritableMemory.wrap(buf, ByteOrder.LITTLE_ENDIAN);
final WritableMemory region = mem.writableRegion(position, maxIntermediateSize);
final Lock lock = stripedLock.getAt(lockIndex(position)).writeLock();
lock.lock();
try {
final ArrayOfDoublesUpdatableSketch sketch = ArrayOfDoublesSketches.wrapUpdatableSketch(region);
for (int i = 0, keysSize = keys.size(); i < keysSize; i++) {
final String key = keySelector.lookupName(keys.get(i));
sketch.update(key, values); // depends on control dependency: [for], data = [none]
}
}
finally {
lock.unlock();
}
} } |
public class class_name {
private void obtainToolbarElevation() {
int elevation;
try {
elevation = ThemeUtil.getDimensionPixelSize(this, R.attr.toolbarElevation);
} catch (NotFoundException e) {
elevation = getResources().getDimensionPixelSize(R.dimen.toolbar_elevation);
}
setToolbarElevation(pixelsToDp(this, elevation));
} } | public class class_name {
private void obtainToolbarElevation() {
int elevation;
try {
elevation = ThemeUtil.getDimensionPixelSize(this, R.attr.toolbarElevation); // depends on control dependency: [try], data = [none]
} catch (NotFoundException e) {
elevation = getResources().getDimensionPixelSize(R.dimen.toolbar_elevation);
} // depends on control dependency: [catch], data = [none]
setToolbarElevation(pixelsToDp(this, elevation));
} } |
public class class_name {
protected void taggingWeightWithWordFrequency(List<Word> words1, List<Word> words2){
if(words1.get(0).getWeight() != null || words2.get(0).getWeight() != null){
if(LOGGER.isDebugEnabled()){
LOGGER.debug("词已经被指定权重,不再使用词频进行标注");
}
return;
}
//词频统计
Map<String, AtomicInteger> frequency1 = frequency(words1);
Map<String, AtomicInteger> frequency2 = frequency(words2);
//输出词频统计信息
if(LOGGER.isDebugEnabled()){
LOGGER.debug("词频统计1:\n{}", formatWordsFrequency(frequency1));
LOGGER.debug("词频统计2:\n{}", formatWordsFrequency(frequency2));
}
//权重标注
words1.parallelStream().forEach(word->{
word.setWeight(frequency1.get(word.getText()).floatValue());
});
words2.parallelStream().forEach(word->{
word.setWeight(frequency2.get(word.getText()).floatValue());
});
} } | public class class_name {
protected void taggingWeightWithWordFrequency(List<Word> words1, List<Word> words2){
if(words1.get(0).getWeight() != null || words2.get(0).getWeight() != null){
if(LOGGER.isDebugEnabled()){
LOGGER.debug("词已经被指定权重,不再使用词频进行标注"); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
//词频统计
Map<String, AtomicInteger> frequency1 = frequency(words1);
Map<String, AtomicInteger> frequency2 = frequency(words2);
//输出词频统计信息
if(LOGGER.isDebugEnabled()){
LOGGER.debug("词频统计1:\n{}", formatWordsFrequency(frequency1)); // depends on control dependency: [if], data = [none]
LOGGER.debug("词频统计2:\n{}", formatWordsFrequency(frequency2)); // depends on control dependency: [if], data = [none]
}
//权重标注
words1.parallelStream().forEach(word->{
word.setWeight(frequency1.get(word.getText()).floatValue());
});
words2.parallelStream().forEach(word->{
word.setWeight(frequency2.get(word.getText()).floatValue());
});
} } |
public class class_name {
public SchemaColumn copyAndReplaceWithTVE(int colIndex) {
TupleValueExpression newTve;
if (m_expression instanceof TupleValueExpression) {
newTve = (TupleValueExpression) m_expression.clone();
newTve.setColumnIndex(colIndex);
}
else {
newTve = new TupleValueExpression(m_tableName, m_tableAlias,
m_columnName, m_columnAlias,
m_expression, colIndex);
}
return new SchemaColumn(m_tableName, m_tableAlias,
m_columnName, m_columnAlias,
newTve, m_differentiator);
} } | public class class_name {
public SchemaColumn copyAndReplaceWithTVE(int colIndex) {
TupleValueExpression newTve;
if (m_expression instanceof TupleValueExpression) {
newTve = (TupleValueExpression) m_expression.clone(); // depends on control dependency: [if], data = [none]
newTve.setColumnIndex(colIndex); // depends on control dependency: [if], data = [none]
}
else {
newTve = new TupleValueExpression(m_tableName, m_tableAlias,
m_columnName, m_columnAlias,
m_expression, colIndex); // depends on control dependency: [if], data = [none]
}
return new SchemaColumn(m_tableName, m_tableAlias,
m_columnName, m_columnAlias,
newTve, m_differentiator);
} } |
public class class_name {
public void add(final AbstractHistogram otherHistogram) throws ArrayIndexOutOfBoundsException {
long highestRecordableValue = highestEquivalentValue(valueFromIndex(countsArrayLength - 1));
if (highestRecordableValue < otherHistogram.getMaxValue()) {
if (!isAutoResize()) {
throw new ArrayIndexOutOfBoundsException(
"The other histogram includes values that do not fit in this histogram's range.");
}
resize(otherHistogram.getMaxValue());
}
if ((bucketCount == otherHistogram.bucketCount) &&
(subBucketCount == otherHistogram.subBucketCount) &&
(unitMagnitude == otherHistogram.unitMagnitude) &&
(getNormalizingIndexOffset() == otherHistogram.getNormalizingIndexOffset())) {
// Counts arrays are of the same length and meaning, so we can just iterate and add directly:
long observedOtherTotalCount = 0;
for (int i = 0; i < otherHistogram.countsArrayLength; i++) {
long otherCount = otherHistogram.getCountAtIndex(i);
if (otherCount > 0) {
addToCountAtIndex(i, otherCount);
observedOtherTotalCount += otherCount;
}
}
setTotalCount(getTotalCount() + observedOtherTotalCount);
updatedMaxValue(Math.max(getMaxValue(), otherHistogram.getMaxValue()));
updateMinNonZeroValue(Math.min(getMinNonZeroValue(), otherHistogram.getMinNonZeroValue()));
} else {
// Arrays are not a direct match, so we can't just stream through and add them.
// Instead, go through the array and add each non-zero value found at it's proper value:
for (int i = 0; i < otherHistogram.countsArrayLength; i++) {
long otherCount = otherHistogram.getCountAtIndex(i);
if (otherCount > 0) {
recordValueWithCount(otherHistogram.valueFromIndex(i), otherCount);
}
}
}
setStartTimeStamp(Math.min(startTimeStampMsec, otherHistogram.startTimeStampMsec));
setEndTimeStamp(Math.max(endTimeStampMsec, otherHistogram.endTimeStampMsec));
} } | public class class_name {
public void add(final AbstractHistogram otherHistogram) throws ArrayIndexOutOfBoundsException {
long highestRecordableValue = highestEquivalentValue(valueFromIndex(countsArrayLength - 1));
if (highestRecordableValue < otherHistogram.getMaxValue()) {
if (!isAutoResize()) {
throw new ArrayIndexOutOfBoundsException(
"The other histogram includes values that do not fit in this histogram's range.");
}
resize(otherHistogram.getMaxValue());
}
if ((bucketCount == otherHistogram.bucketCount) &&
(subBucketCount == otherHistogram.subBucketCount) &&
(unitMagnitude == otherHistogram.unitMagnitude) &&
(getNormalizingIndexOffset() == otherHistogram.getNormalizingIndexOffset())) {
// Counts arrays are of the same length and meaning, so we can just iterate and add directly:
long observedOtherTotalCount = 0;
for (int i = 0; i < otherHistogram.countsArrayLength; i++) {
long otherCount = otherHistogram.getCountAtIndex(i);
if (otherCount > 0) {
addToCountAtIndex(i, otherCount); // depends on control dependency: [if], data = [none]
observedOtherTotalCount += otherCount; // depends on control dependency: [if], data = [none]
}
}
setTotalCount(getTotalCount() + observedOtherTotalCount);
updatedMaxValue(Math.max(getMaxValue(), otherHistogram.getMaxValue()));
updateMinNonZeroValue(Math.min(getMinNonZeroValue(), otherHistogram.getMinNonZeroValue()));
} else {
// Arrays are not a direct match, so we can't just stream through and add them.
// Instead, go through the array and add each non-zero value found at it's proper value:
for (int i = 0; i < otherHistogram.countsArrayLength; i++) {
long otherCount = otherHistogram.getCountAtIndex(i);
if (otherCount > 0) {
recordValueWithCount(otherHistogram.valueFromIndex(i), otherCount); // depends on control dependency: [if], data = [none]
}
}
}
setStartTimeStamp(Math.min(startTimeStampMsec, otherHistogram.startTimeStampMsec));
setEndTimeStamp(Math.max(endTimeStampMsec, otherHistogram.endTimeStampMsec));
} } |
public class class_name {
public static Map<CmsUUID, CmsUser> addExportUsersFromRoles(
CmsObject cms,
String ou,
List<String> roles,
Map<CmsUUID, CmsUser> exportUsers)
throws CmsException {
if ((roles != null) && (roles.size() > 0)) {
Iterator<String> itRoles = roles.iterator();
while (itRoles.hasNext()) {
List<CmsUser> roleUsers = OpenCms.getRoleManager().getUsersOfRole(
cms,
CmsRole.valueOfGroupName(itRoles.next()).forOrgUnit(ou),
true,
false);
Iterator<CmsUser> itRoleUsers = roleUsers.iterator();
while (itRoleUsers.hasNext()) {
CmsUser roleUser = itRoleUsers.next();
// contains
if (exportUsers.get(roleUser.getId()) == null) {
exportUsers.put(roleUser.getId(), roleUser);
}
}
}
}
return exportUsers;
} } | public class class_name {
public static Map<CmsUUID, CmsUser> addExportUsersFromRoles(
CmsObject cms,
String ou,
List<String> roles,
Map<CmsUUID, CmsUser> exportUsers)
throws CmsException {
if ((roles != null) && (roles.size() > 0)) {
Iterator<String> itRoles = roles.iterator();
while (itRoles.hasNext()) {
List<CmsUser> roleUsers = OpenCms.getRoleManager().getUsersOfRole(
cms,
CmsRole.valueOfGroupName(itRoles.next()).forOrgUnit(ou),
true,
false);
Iterator<CmsUser> itRoleUsers = roleUsers.iterator();
while (itRoleUsers.hasNext()) {
CmsUser roleUser = itRoleUsers.next();
// contains
if (exportUsers.get(roleUser.getId()) == null) {
exportUsers.put(roleUser.getId(), roleUser); // depends on control dependency: [if], data = [none]
}
}
}
}
return exportUsers;
} } |
public class class_name {
public void registerWorkerStatus(ZooKeeper zk, Plan plan, WorkerStatus s) throws WorkerDaoException{
String writeToPath = PLAN_WORKERS_ZK + "/" + plan.getName() + "/" + s.getWorkerUuid();
try {
Stat planBase = zk.exists(PLAN_WORKERS_ZK + "/" + plan.getName(), false);
if (planBase == null){
try {
zk.create(PLAN_WORKERS_ZK + "/" + plan.getName(), new byte [0] , Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception ignore){}
}
zk.create(writeToPath, MAPPER.writeValueAsBytes(s), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
LOGGER.debug("Registered as ephemeral " + writeToPath);
zk.exists(PLANS_ZK + "/" + plan.getName(), true); //watch job for events
} catch (KeeperException | InterruptedException | IOException e) {
LOGGER.warn(e);
throw new WorkerDaoException(e);
}
} } | public class class_name {
public void registerWorkerStatus(ZooKeeper zk, Plan plan, WorkerStatus s) throws WorkerDaoException{
String writeToPath = PLAN_WORKERS_ZK + "/" + plan.getName() + "/" + s.getWorkerUuid();
try {
Stat planBase = zk.exists(PLAN_WORKERS_ZK + "/" + plan.getName(), false);
if (planBase == null){
try {
zk.create(PLAN_WORKERS_ZK + "/" + plan.getName(), new byte [0] , Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); // depends on control dependency: [try], data = [none]
} catch (Exception ignore){} // depends on control dependency: [catch], data = [none]
}
zk.create(writeToPath, MAPPER.writeValueAsBytes(s), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
LOGGER.debug("Registered as ephemeral " + writeToPath);
zk.exists(PLANS_ZK + "/" + plan.getName(), true); //watch job for events
} catch (KeeperException | InterruptedException | IOException e) {
LOGGER.warn(e);
throw new WorkerDaoException(e);
}
} } |
public class class_name {
public void messagesAdded(int msgCount, BatchListener listener) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "messagesAdded","msgCount="+msgCount+",listener="+listener);
boolean completeBatch = false;
try
{
synchronized(this) // lock the state against other readers
{
_currentBatchSize += msgCount;
if((listener != null) && (!_listeners.contains(listener)))
{
// Remember that this listener needs calling when the batch completes
_listeners.add(listener);
}
if(_currentBatchSize >= _batchSize) // Full batch, commit all updates
{
completeBatch = true; // We can't do this under the synchronize as the exclusive lock
// we need will deadlock with reader's trying to get this
} // synchronize before these release their shared lock
else if ((_currentBatchSize - msgCount) == 0) // New batch so ensure a timer is running
{
startTimer();
}
}
}
finally
{
_readWriteLock.unlock(); // release the read lock we took in registerInBatch
}
// Now we hold no locks we can try to complete he batch (this takes an exclusive lock
if(completeBatch)
{
completeBatch(false); // false = only complete a full batch
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "messagesAdded");
} } | public class class_name {
public void messagesAdded(int msgCount, BatchListener listener) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "messagesAdded","msgCount="+msgCount+",listener="+listener);
boolean completeBatch = false;
try
{
synchronized(this) // lock the state against other readers
{
_currentBatchSize += msgCount;
if((listener != null) && (!_listeners.contains(listener)))
{
// Remember that this listener needs calling when the batch completes
_listeners.add(listener); // depends on control dependency: [if], data = [none]
}
if(_currentBatchSize >= _batchSize) // Full batch, commit all updates
{
completeBatch = true; // We can't do this under the synchronize as the exclusive lock // depends on control dependency: [if], data = [none]
// we need will deadlock with reader's trying to get this
} // synchronize before these release their shared lock
else if ((_currentBatchSize - msgCount) == 0) // New batch so ensure a timer is running
{
startTimer(); // depends on control dependency: [if], data = [none]
}
}
}
finally
{
_readWriteLock.unlock(); // release the read lock we took in registerInBatch
}
// Now we hold no locks we can try to complete he batch (this takes an exclusive lock
if(completeBatch)
{
completeBatch(false); // false = only complete a full batch
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "messagesAdded");
} } |
public class class_name {
@InterfaceStability.Unstable
public synchronized String[] getPropertySources(String name) {
if (properties == null) {
// If properties is null, it means a resource was newly added
// but the props were cleared so as to load it upon future
// requests. So lets force a load by asking a properties list.
getProps();
}
// Return a null right away if our properties still
// haven't loaded or the resource mapping isn't defined
if (properties == null || updatingResource == null) {
return null;
} else {
String[] source = updatingResource.get(name);
if(source == null) {
return null;
} else {
return Arrays.copyOf(source, source.length);
}
}
} } | public class class_name {
@InterfaceStability.Unstable
public synchronized String[] getPropertySources(String name) {
if (properties == null) {
// If properties is null, it means a resource was newly added
// but the props were cleared so as to load it upon future
// requests. So lets force a load by asking a properties list.
getProps(); // depends on control dependency: [if], data = [none]
}
// Return a null right away if our properties still
// haven't loaded or the resource mapping isn't defined
if (properties == null || updatingResource == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
String[] source = updatingResource.get(name);
if(source == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
return Arrays.copyOf(source, source.length); // depends on control dependency: [if], data = [(source]
}
}
} } |
public class class_name {
@SuppressWarnings({ "unchecked", "null" })
public void update(final Sketch<S> sketchIn) {
final boolean isFirstCall = isFirstCall_;
isFirstCall_ = false;
if (sketchIn == null) {
isEmpty_ = true;
sketch_ = null;
return;
}
theta_ = min(theta_, sketchIn.getThetaLong());
isEmpty_ |= sketchIn.isEmpty();
if (isEmpty_ || (sketchIn.getRetainedEntries() == 0)) {
sketch_ = null;
return;
}
// assumes that constructor of QuickSelectSketch bumps the requested size up to the nearest power of 2
if (isFirstCall) {
sketch_ = new QuickSelectSketch<>(sketchIn.getRetainedEntries(), ResizeFactor.X1.lg(), null);
final SketchIterator<S> it = sketchIn.iterator();
while (it.next()) {
final S summary = (S)it.getSummary().copy();
sketch_.insert(it.getKey(), summary);
}
} else {
if (sketch_ == null) {
return;
}
final int matchSize = min(sketch_.getRetainedEntries(), sketchIn.getRetainedEntries());
final long[] matchKeys = new long[matchSize];
S[] matchSummaries = null;
int matchCount = 0;
final SketchIterator<S> it = sketchIn.iterator();
while (it.next()) {
final S summary = sketch_.find(it.getKey());
if (summary != null) {
matchKeys[matchCount] = it.getKey();
if (matchSummaries == null) {
matchSummaries = (S[]) Array.newInstance(summary.getClass(), matchSize);
}
matchSummaries[matchCount] =
summarySetOps_.intersection(summary, it.getSummary());
matchCount++;
}
}
sketch_ = null;
if (matchCount > 0) {
sketch_ = new QuickSelectSketch<>(matchCount, ResizeFactor.X1.lg(), null);
for (int i = 0; i < matchCount; i++) {
sketch_.insert(matchKeys[i], matchSummaries[i]);
}
}
}
if (sketch_ != null) {
sketch_.setThetaLong(theta_);
sketch_.setNotEmpty();
}
} } | public class class_name {
@SuppressWarnings({ "unchecked", "null" })
public void update(final Sketch<S> sketchIn) {
final boolean isFirstCall = isFirstCall_;
isFirstCall_ = false;
if (sketchIn == null) {
isEmpty_ = true; // depends on control dependency: [if], data = [none]
sketch_ = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
theta_ = min(theta_, sketchIn.getThetaLong());
isEmpty_ |= sketchIn.isEmpty();
if (isEmpty_ || (sketchIn.getRetainedEntries() == 0)) {
sketch_ = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// assumes that constructor of QuickSelectSketch bumps the requested size up to the nearest power of 2
if (isFirstCall) {
sketch_ = new QuickSelectSketch<>(sketchIn.getRetainedEntries(), ResizeFactor.X1.lg(), null); // depends on control dependency: [if], data = [none]
final SketchIterator<S> it = sketchIn.iterator();
while (it.next()) {
final S summary = (S)it.getSummary().copy();
sketch_.insert(it.getKey(), summary); // depends on control dependency: [while], data = [none]
}
} else {
if (sketch_ == null) {
return; // depends on control dependency: [if], data = [none]
}
final int matchSize = min(sketch_.getRetainedEntries(), sketchIn.getRetainedEntries());
final long[] matchKeys = new long[matchSize];
S[] matchSummaries = null;
int matchCount = 0;
final SketchIterator<S> it = sketchIn.iterator();
while (it.next()) {
final S summary = sketch_.find(it.getKey());
if (summary != null) {
matchKeys[matchCount] = it.getKey(); // depends on control dependency: [if], data = [none]
if (matchSummaries == null) {
matchSummaries = (S[]) Array.newInstance(summary.getClass(), matchSize); // depends on control dependency: [if], data = [none]
}
matchSummaries[matchCount] =
summarySetOps_.intersection(summary, it.getSummary()); // depends on control dependency: [if], data = [none]
matchCount++; // depends on control dependency: [if], data = [none]
}
}
sketch_ = null; // depends on control dependency: [if], data = [none]
if (matchCount > 0) {
sketch_ = new QuickSelectSketch<>(matchCount, ResizeFactor.X1.lg(), null); // depends on control dependency: [if], data = [(matchCount]
for (int i = 0; i < matchCount; i++) {
sketch_.insert(matchKeys[i], matchSummaries[i]); // depends on control dependency: [for], data = [i]
}
}
}
if (sketch_ != null) {
sketch_.setThetaLong(theta_); // depends on control dependency: [if], data = [none]
sketch_.setNotEmpty(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(ListRobotsRequest listRobotsRequest, ProtocolMarshaller protocolMarshaller) {
if (listRobotsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listRobotsRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listRobotsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(listRobotsRequest.getFilters(), FILTERS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListRobotsRequest listRobotsRequest, ProtocolMarshaller protocolMarshaller) {
if (listRobotsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listRobotsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listRobotsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listRobotsRequest.getFilters(), FILTERS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static LocalizedMessages getInstance(Locale locale)
{
LocalizedMessages instance = null;
if (locale == null)
{
locale = Locale.getDefault();
}
String localeKey = locale.getLanguage();
if (localizedMessages.containsKey(localeKey))
{
instance = localizedMessages.get(localeKey);
}
else
{
synchronized (LocalizedMessages.class)
{
if (instance == null)
{
instance = new LocalizedMessages(locale);
localizedMessages.put(localeKey, instance);
}
}
}
return instance;
} } | public class class_name {
public static LocalizedMessages getInstance(Locale locale)
{
LocalizedMessages instance = null;
if (locale == null)
{
locale = Locale.getDefault(); // depends on control dependency: [if], data = [none]
}
String localeKey = locale.getLanguage();
if (localizedMessages.containsKey(localeKey))
{
instance = localizedMessages.get(localeKey); // depends on control dependency: [if], data = [none]
}
else
{
synchronized (LocalizedMessages.class) // depends on control dependency: [if], data = [none]
{
if (instance == null)
{
instance = new LocalizedMessages(locale); // depends on control dependency: [if], data = [none]
localizedMessages.put(localeKey, instance); // depends on control dependency: [if], data = [none]
}
}
}
return instance;
} } |
public class class_name {
public static ImList<Class> registerClasses(Class... cs) {
if (cs == null) {
throw new IllegalArgumentException("Can't register a null type array");
}
if (cs.length == 0) {
throw new IllegalArgumentException("Can't register a zero-length type array");
}
for (Class c : cs) {
if (c == null) {
throw new IllegalArgumentException("There shouldn't be any null types in this array!");
}
}
ArrayHolder<Class> ah = new ArrayHolder<>(cs);
ImList<Class> registeredTypes;
synchronized (Lock.INSTANCE) {
registeredTypes = typeMap.get(ah);
if (registeredTypes == null) {
ImList<Class> vecCs = vec(cs);
typeMap.put(ah, vecCs);
registeredTypes = vecCs;
}
}
// We are returning the original array. If we returned our safe copy, it could be modified!
return registeredTypes;
} } | public class class_name {
public static ImList<Class> registerClasses(Class... cs) {
if (cs == null) {
throw new IllegalArgumentException("Can't register a null type array");
}
if (cs.length == 0) {
throw new IllegalArgumentException("Can't register a zero-length type array");
}
for (Class c : cs) {
if (c == null) {
throw new IllegalArgumentException("There shouldn't be any null types in this array!");
}
}
ArrayHolder<Class> ah = new ArrayHolder<>(cs);
ImList<Class> registeredTypes;
synchronized (Lock.INSTANCE) {
registeredTypes = typeMap.get(ah);
if (registeredTypes == null) {
ImList<Class> vecCs = vec(cs);
typeMap.put(ah, vecCs); // depends on control dependency: [if], data = [none]
registeredTypes = vecCs; // depends on control dependency: [if], data = [none]
}
}
// We are returning the original array. If we returned our safe copy, it could be modified!
return registeredTypes;
} } |
public class class_name {
public static String[] nullToEmpty(String[] array) {
if (array == null || array.length == 0) {
return EMPTY_STRING_ARRAY;
}
return array;
} } | public class class_name {
public static String[] nullToEmpty(String[] array) {
if (array == null || array.length == 0) {
return EMPTY_STRING_ARRAY; // depends on control dependency: [if], data = [none]
}
return array;
} } |
public class class_name {
@Override
public void onActivityStopped(final Activity activity) {
if (foregroundActivities.decrementAndGet() < 0) {
ApptentiveLog.e("Incorrect number of foreground Activities encountered. Resetting to 0.");
foregroundActivities.set(0);
}
if (checkFgBgRoutine != null) {
delayedChecker.removeCallbacks(checkFgBgRoutine);
}
/* When one activity transits to another one, there is a brief period during which the former
* is paused but the latter has not yet resumed. To prevent false negative, check routine is
* delayed
*/
delayedChecker.postDelayed(checkFgBgRoutine = new Runnable() {
@Override
public void run() {
try {
if (foregroundActivities.get() == 0 && isAppForeground) {
appEnteredBackground();
isAppForeground = false;
}
} catch (Exception e) {
ApptentiveLog.e(e, "Exception in delayed checking");
ErrorMetrics.logException(e);
}
}
}, CHECK_DELAY_SHORT);
dispatchOnConversationQueue(new DispatchTask() {
@Override
protected void execute() {
ApptentiveNotificationCenter.defaultCenter()
.postNotification(NOTIFICATION_ACTIVITY_STOPPED, NOTIFICATION_KEY_ACTIVITY, activity);
}
});
} } | public class class_name {
@Override
public void onActivityStopped(final Activity activity) {
if (foregroundActivities.decrementAndGet() < 0) {
ApptentiveLog.e("Incorrect number of foreground Activities encountered. Resetting to 0."); // depends on control dependency: [if], data = [none]
foregroundActivities.set(0); // depends on control dependency: [if], data = [0)]
}
if (checkFgBgRoutine != null) {
delayedChecker.removeCallbacks(checkFgBgRoutine); // depends on control dependency: [if], data = [(checkFgBgRoutine]
}
/* When one activity transits to another one, there is a brief period during which the former
* is paused but the latter has not yet resumed. To prevent false negative, check routine is
* delayed
*/
delayedChecker.postDelayed(checkFgBgRoutine = new Runnable() {
@Override
public void run() {
try {
if (foregroundActivities.get() == 0 && isAppForeground) {
appEnteredBackground(); // depends on control dependency: [if], data = [none]
isAppForeground = false; // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
ApptentiveLog.e(e, "Exception in delayed checking");
ErrorMetrics.logException(e);
} // depends on control dependency: [catch], data = [none]
}
}, CHECK_DELAY_SHORT);
dispatchOnConversationQueue(new DispatchTask() {
@Override
protected void execute() {
ApptentiveNotificationCenter.defaultCenter()
.postNotification(NOTIFICATION_ACTIVITY_STOPPED, NOTIFICATION_KEY_ACTIVITY, activity);
}
});
} } |
public class class_name {
@Override
public CPInstance fetchByC_NotST_First(long CPDefinitionId, int status,
OrderByComparator<CPInstance> orderByComparator) {
List<CPInstance> list = findByC_NotST(CPDefinitionId, status, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
} } | public class class_name {
@Override
public CPInstance fetchByC_NotST_First(long CPDefinitionId, int status,
OrderByComparator<CPInstance> orderByComparator) {
List<CPInstance> list = findByC_NotST(CPDefinitionId, status, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public void encodeData(AsnOutputStream asnOs) throws MAPException {
try {
if (this.choice == null)
throw new MAPException("Error while encoding the " + _PrimitiveName + ": choice is not defined");
if ((this.choice == PSSubscriberStateChoice.psPDPActiveNotReachableForPaging || this.choice == PSSubscriberStateChoice.psPDPActiveReachableForPaging)
&& this.pdpContextInfoList == null)
throw new MAPException(
"Error while encoding the "
+ _PrimitiveName
+ ": for choice psPDPActiveNotReachableForPaging or psPDPActiveReachableForPaging - pdpContextInfoList must not be null");
if ((this.choice == PSSubscriberStateChoice.netDetNotReachable) && this.netDetNotReachable == null)
throw new MAPException("Error while encoding the " + _PrimitiveName
+ ": for choice netDetNotReachable - netDetNotReachable must not be null");
switch (this.choice) {
case notProvidedFromSGSNorMME:
case psDetached:
case psAttachedNotReachableForPaging:
case psAttachedReachableForPaging:
asnOs.writeNullData();
break;
case psPDPActiveNotReachableForPaging:
case psPDPActiveReachableForPaging:
if (this.pdpContextInfoList.size() < 1 || this.pdpContextInfoList.size() > 50)
throw new MAPException("Error while encoding " + _PrimitiveName
+ ": pdpContextInfoList size must be from 1 to 50");
for (PDPContextInfo cii : this.pdpContextInfoList) {
PDPContextInfoImpl ci = (PDPContextInfoImpl) cii;
ci.encodeAll(asnOs);
}
break;
case netDetNotReachable:
asnOs.writeIntegerData(this.netDetNotReachable.getCode());
break;
}
} catch (IOException e) {
throw new MAPException("IOException when encoding " + _PrimitiveName + ": " + e.getMessage(), e);
}
} } | public class class_name {
public void encodeData(AsnOutputStream asnOs) throws MAPException {
try {
if (this.choice == null)
throw new MAPException("Error while encoding the " + _PrimitiveName + ": choice is not defined");
if ((this.choice == PSSubscriberStateChoice.psPDPActiveNotReachableForPaging || this.choice == PSSubscriberStateChoice.psPDPActiveReachableForPaging)
&& this.pdpContextInfoList == null)
throw new MAPException(
"Error while encoding the "
+ _PrimitiveName
+ ": for choice psPDPActiveNotReachableForPaging or psPDPActiveReachableForPaging - pdpContextInfoList must not be null");
if ((this.choice == PSSubscriberStateChoice.netDetNotReachable) && this.netDetNotReachable == null)
throw new MAPException("Error while encoding the " + _PrimitiveName
+ ": for choice netDetNotReachable - netDetNotReachable must not be null");
switch (this.choice) {
case notProvidedFromSGSNorMME:
case psDetached:
case psAttachedNotReachableForPaging:
case psAttachedReachableForPaging:
asnOs.writeNullData();
break;
case psPDPActiveNotReachableForPaging:
case psPDPActiveReachableForPaging:
if (this.pdpContextInfoList.size() < 1 || this.pdpContextInfoList.size() > 50)
throw new MAPException("Error while encoding " + _PrimitiveName
+ ": pdpContextInfoList size must be from 1 to 50");
for (PDPContextInfo cii : this.pdpContextInfoList) {
PDPContextInfoImpl ci = (PDPContextInfoImpl) cii;
ci.encodeAll(asnOs); // depends on control dependency: [for], data = [none]
}
break;
case netDetNotReachable:
asnOs.writeIntegerData(this.netDetNotReachable.getCode());
break;
}
} catch (IOException e) {
throw new MAPException("IOException when encoding " + _PrimitiveName + ": " + e.getMessage(), e);
}
} } |
public class class_name {
public static ClassSymbol outermostClass(Symbol symbol) {
ClassSymbol curr = symbol.enclClass();
while (curr.owner != null) {
ClassSymbol encl = curr.owner.enclClass();
if (encl == null) {
break;
}
curr = encl;
}
return curr;
} } | public class class_name {
public static ClassSymbol outermostClass(Symbol symbol) {
ClassSymbol curr = symbol.enclClass();
while (curr.owner != null) {
ClassSymbol encl = curr.owner.enclClass();
if (encl == null) {
break;
}
curr = encl; // depends on control dependency: [while], data = [none]
}
return curr;
} } |
public class class_name {
private void setName(Thread thread, String name) {
try {
thread.setName(name);
} catch (SecurityException se) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Failed to set the thread name.", se);
}
}
} } | public class class_name {
private void setName(Thread thread, String name) {
try {
thread.setName(name); // depends on control dependency: [try], data = [none]
} catch (SecurityException se) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Failed to set the thread name.", se); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void _generate(SarlAnnotationType annotation, IExtraLanguageGeneratorContext context) {
final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(annotation);
final PyAppendable appendable = createAppendable(jvmType, context);
if (generateTypeDeclaration(
this.qualifiedNameProvider.getFullyQualifiedName(annotation).toString(),
annotation.getName(), false, Collections.emptyList(),
getTypeBuilder().getDocumentation(annotation),
true,
annotation.getMembers(), appendable, context, null)) {
final QualifiedName name = getQualifiedNameProvider().getFullyQualifiedName(annotation);
writeFile(name, appendable, context);
}
} } | public class class_name {
protected void _generate(SarlAnnotationType annotation, IExtraLanguageGeneratorContext context) {
final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(annotation);
final PyAppendable appendable = createAppendable(jvmType, context);
if (generateTypeDeclaration(
this.qualifiedNameProvider.getFullyQualifiedName(annotation).toString(),
annotation.getName(), false, Collections.emptyList(),
getTypeBuilder().getDocumentation(annotation),
true,
annotation.getMembers(), appendable, context, null)) {
final QualifiedName name = getQualifiedNameProvider().getFullyQualifiedName(annotation);
writeFile(name, appendable, context); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <T> T[] transform(T[] array, Transformer<T> transformer) {
Assert.notNull(array, "Array is required");
Assert.notNull(transformer, "Transformer is required");
for (int index = 0; index < array.length; index++) {
array[index] = transformer.transform(array[index]);
}
return array;
} } | public class class_name {
public static <T> T[] transform(T[] array, Transformer<T> transformer) {
Assert.notNull(array, "Array is required");
Assert.notNull(transformer, "Transformer is required");
for (int index = 0; index < array.length; index++) {
array[index] = transformer.transform(array[index]); // depends on control dependency: [for], data = [index]
}
return array;
} } |
public class class_name {
public Namer getManyToOneNamer(Attribute fromAttribute, Namer targetEntityNamer) {
// configuration
Namer result = getManyToOneNamerFromConf(fromAttribute.getColumnConfig(), targetEntityNamer);
// fall back
if (result == null) {
result = getXToOneNamerFallBack(fromAttribute, targetEntityNamer);
}
return result;
} } | public class class_name {
public Namer getManyToOneNamer(Attribute fromAttribute, Namer targetEntityNamer) {
// configuration
Namer result = getManyToOneNamerFromConf(fromAttribute.getColumnConfig(), targetEntityNamer);
// fall back
if (result == null) {
result = getXToOneNamerFallBack(fromAttribute, targetEntityNamer); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public static JvmType filterActiveProcessorType(JvmType type, CommonTypeComputationServices services) {
if (AccessorsProcessor.class.getName().equals(type.getQualifiedName())) {
return services.getTypeReferences().findDeclaredType(SarlAccessorsProcessor.class, type);
}
return type;
} } | public class class_name {
public static JvmType filterActiveProcessorType(JvmType type, CommonTypeComputationServices services) {
if (AccessorsProcessor.class.getName().equals(type.getQualifiedName())) {
return services.getTypeReferences().findDeclaredType(SarlAccessorsProcessor.class, type); // depends on control dependency: [if], data = [none]
}
return type;
} } |
public class class_name {
public int nextCaseMapCP() {
int c;
if(cpLimit<limit) {
cpStart=cpLimit;
c=rep.char32At(cpLimit);
cpLimit+=UTF16.getCharCount(c);
return c;
} else {
return -1;
}
} } | public class class_name {
public int nextCaseMapCP() {
int c;
if(cpLimit<limit) {
cpStart=cpLimit; // depends on control dependency: [if], data = [none]
c=rep.char32At(cpLimit); // depends on control dependency: [if], data = [(cpLimit]
cpLimit+=UTF16.getCharCount(c); // depends on control dependency: [if], data = [none]
return c; // depends on control dependency: [if], data = [none]
} else {
return -1; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void saveSequenceFile(String path, JavaRDD<List<Writable>> rdd, Integer maxOutputFiles) {
path = FilenameUtils.normalize(path, true);
if (maxOutputFiles != null) {
rdd = rdd.coalesce(maxOutputFiles);
}
JavaPairRDD<List<Writable>, Long> dataIndexPairs = rdd.zipWithUniqueId(); //Note: Long values are unique + NOT contiguous; more efficient than zipWithIndex
JavaPairRDD<LongWritable, RecordWritable> keyedByIndex =
dataIndexPairs.mapToPair(new RecordSavePrepPairFunction());
keyedByIndex.saveAsNewAPIHadoopFile(path, LongWritable.class, RecordWritable.class,
SequenceFileOutputFormat.class);
} } | public class class_name {
public static void saveSequenceFile(String path, JavaRDD<List<Writable>> rdd, Integer maxOutputFiles) {
path = FilenameUtils.normalize(path, true);
if (maxOutputFiles != null) {
rdd = rdd.coalesce(maxOutputFiles); // depends on control dependency: [if], data = [(maxOutputFiles]
}
JavaPairRDD<List<Writable>, Long> dataIndexPairs = rdd.zipWithUniqueId(); //Note: Long values are unique + NOT contiguous; more efficient than zipWithIndex
JavaPairRDD<LongWritable, RecordWritable> keyedByIndex =
dataIndexPairs.mapToPair(new RecordSavePrepPairFunction());
keyedByIndex.saveAsNewAPIHadoopFile(path, LongWritable.class, RecordWritable.class,
SequenceFileOutputFormat.class);
} } |
public class class_name {
public boolean isBeforeRange(Range<T> otherRange) {
if (otherRange == null) { return false; }
return isBefore(otherRange.min);
} } | public class class_name {
public boolean isBeforeRange(Range<T> otherRange) {
if (otherRange == null) { return false; } // depends on control dependency: [if], data = [none]
return isBefore(otherRange.min);
} } |
public class class_name {
public static String urlFormEncode(final String s)
{
if (StringUtils.isBlank(s))
{
LOG.warn("Could not encode blank string");
throw new IllegalArgumentException("Blank string");
}
try
{
return URLEncoder.encode(s, "UTF-8");
}
catch (final UnsupportedEncodingException e)
{
LOG.error ("Could not encode: " + s, e);
return s;
}
} } | public class class_name {
public static String urlFormEncode(final String s)
{
if (StringUtils.isBlank(s))
{
LOG.warn("Could not encode blank string"); // depends on control dependency: [if], data = [none]
throw new IllegalArgumentException("Blank string");
}
try
{
return URLEncoder.encode(s, "UTF-8"); // depends on control dependency: [try], data = [none]
}
catch (final UnsupportedEncodingException e)
{
LOG.error ("Could not encode: " + s, e);
return s;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private String generateVersionEleStr() {
StringBuilder sb = new StringBuilder();
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(this.versionColumn));
sb.append(" = ");
sb.append("#{version,jdbcType=");
sb.append(this.versionColumn.getJdbcTypeName());
if (StringUtility.stringHasValue(this.versionColumn.getTypeHandler())) {
sb.append(",typeHandler=");
sb.append(this.versionColumn.getTypeHandler());
}
sb.append("}");
return sb.toString();
} } | public class class_name {
private String generateVersionEleStr() {
StringBuilder sb = new StringBuilder();
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(this.versionColumn));
sb.append(" = ");
sb.append("#{version,jdbcType=");
sb.append(this.versionColumn.getJdbcTypeName());
if (StringUtility.stringHasValue(this.versionColumn.getTypeHandler())) {
sb.append(",typeHandler="); // depends on control dependency: [if], data = [none]
sb.append(this.versionColumn.getTypeHandler()); // depends on control dependency: [if], data = [none]
}
sb.append("}");
return sb.toString();
} } |
public class class_name {
private Expression partToPartExpression(SoyMsgPart part) {
if (part instanceof SoyMsgPlaceholderPart) {
return SOY_MSG_PLACEHOLDER_PART.construct(
constant(((SoyMsgPlaceholderPart) part).getPlaceholderName()), constantNull(STRING_TYPE));
} else if (part instanceof SoyMsgPluralPart) {
SoyMsgPluralPart pluralPart = (SoyMsgPluralPart) part;
List<Expression> caseExprs = new ArrayList<>(pluralPart.getCases().size());
for (Case<SoyMsgPluralCaseSpec> item : pluralPart.getCases()) {
Expression spec;
if (item.spec().getType() == Type.EXPLICIT) {
spec = SOY_MSG_PLURAL_CASE_SPEC_LONG.construct(constant(item.spec().getExplicitValue()));
} else {
spec =
SOY_MSG_PLURAL_CASE_SPEC_TYPE.construct(
FieldRef.enumReference(item.spec().getType()).accessor());
}
caseExprs.add(CASE_CREATE.invoke(spec, partsToPartsList(item.parts())));
}
return SOY_MSG_PURAL_PART.construct(
constant(pluralPart.getPluralVarName()),
constant(pluralPart.getOffset()),
BytecodeUtils.asList(caseExprs));
} else if (part instanceof SoyMsgPluralRemainderPart) {
return SOY_MSG_PLURAL_REMAINDER_PART.construct(
constant(((SoyMsgPluralRemainderPart) part).getPluralVarName()));
} else if (part instanceof SoyMsgRawTextPart) {
return SOY_MSG_RAW_TEXT_PART_OF.invoke(
constant(((SoyMsgRawTextPart) part).getRawText(), variables));
} else if (part instanceof SoyMsgSelectPart) {
SoyMsgSelectPart selectPart = (SoyMsgSelectPart) part;
List<Expression> caseExprs = new ArrayList<>(selectPart.getCases().size());
for (Case<String> item : selectPart.getCases()) {
caseExprs.add(
CASE_CREATE.invoke(
item.spec() == null ? constantNull(STRING_TYPE) : constant(item.spec()),
partsToPartsList(item.parts())));
}
return SOY_MSG_SELECT_PART.construct(
constant(selectPart.getSelectVarName()), BytecodeUtils.asList(caseExprs));
} else {
throw new AssertionError("unrecognized part: " + part);
}
} } | public class class_name {
private Expression partToPartExpression(SoyMsgPart part) {
if (part instanceof SoyMsgPlaceholderPart) {
return SOY_MSG_PLACEHOLDER_PART.construct(
constant(((SoyMsgPlaceholderPart) part).getPlaceholderName()), constantNull(STRING_TYPE)); // depends on control dependency: [if], data = [none]
} else if (part instanceof SoyMsgPluralPart) {
SoyMsgPluralPart pluralPart = (SoyMsgPluralPart) part;
List<Expression> caseExprs = new ArrayList<>(pluralPart.getCases().size());
for (Case<SoyMsgPluralCaseSpec> item : pluralPart.getCases()) {
Expression spec;
if (item.spec().getType() == Type.EXPLICIT) {
spec = SOY_MSG_PLURAL_CASE_SPEC_LONG.construct(constant(item.spec().getExplicitValue())); // depends on control dependency: [if], data = [none]
} else {
spec =
SOY_MSG_PLURAL_CASE_SPEC_TYPE.construct(
FieldRef.enumReference(item.spec().getType()).accessor()); // depends on control dependency: [if], data = [none]
}
caseExprs.add(CASE_CREATE.invoke(spec, partsToPartsList(item.parts()))); // depends on control dependency: [for], data = [item]
}
return SOY_MSG_PURAL_PART.construct(
constant(pluralPart.getPluralVarName()),
constant(pluralPart.getOffset()),
BytecodeUtils.asList(caseExprs)); // depends on control dependency: [if], data = [none]
} else if (part instanceof SoyMsgPluralRemainderPart) {
return SOY_MSG_PLURAL_REMAINDER_PART.construct(
constant(((SoyMsgPluralRemainderPart) part).getPluralVarName())); // depends on control dependency: [if], data = [none]
} else if (part instanceof SoyMsgRawTextPart) {
return SOY_MSG_RAW_TEXT_PART_OF.invoke(
constant(((SoyMsgRawTextPart) part).getRawText(), variables)); // depends on control dependency: [if], data = [none]
} else if (part instanceof SoyMsgSelectPart) {
SoyMsgSelectPart selectPart = (SoyMsgSelectPart) part;
List<Expression> caseExprs = new ArrayList<>(selectPart.getCases().size());
for (Case<String> item : selectPart.getCases()) {
caseExprs.add(
CASE_CREATE.invoke(
item.spec() == null ? constantNull(STRING_TYPE) : constant(item.spec()),
partsToPartsList(item.parts()))); // depends on control dependency: [for], data = [none]
}
return SOY_MSG_SELECT_PART.construct(
constant(selectPart.getSelectVarName()), BytecodeUtils.asList(caseExprs)); // depends on control dependency: [if], data = [none]
} else {
throw new AssertionError("unrecognized part: " + part);
}
} } |
public class class_name {
public com.google.privacy.dlp.v2.ReplaceWithInfoTypeConfig getReplaceWithInfoTypeConfig() {
if (transformationCase_ == 7) {
return (com.google.privacy.dlp.v2.ReplaceWithInfoTypeConfig) transformation_;
}
return com.google.privacy.dlp.v2.ReplaceWithInfoTypeConfig.getDefaultInstance();
} } | public class class_name {
public com.google.privacy.dlp.v2.ReplaceWithInfoTypeConfig getReplaceWithInfoTypeConfig() {
if (transformationCase_ == 7) {
return (com.google.privacy.dlp.v2.ReplaceWithInfoTypeConfig) transformation_; // depends on control dependency: [if], data = [none]
}
return com.google.privacy.dlp.v2.ReplaceWithInfoTypeConfig.getDefaultInstance();
} } |
public class class_name {
private static Integer safeInteger(String input) {
try {
return Integer.valueOf(input);
} catch (Exception e) {
return null;
}
} } | public class class_name {
private static Integer safeInteger(String input) {
try {
return Integer.valueOf(input); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(DeleteApplicationCloudWatchLoggingOptionRequest deleteApplicationCloudWatchLoggingOptionRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteApplicationCloudWatchLoggingOptionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteApplicationCloudWatchLoggingOptionRequest.getApplicationName(), APPLICATIONNAME_BINDING);
protocolMarshaller.marshall(deleteApplicationCloudWatchLoggingOptionRequest.getCurrentApplicationVersionId(), CURRENTAPPLICATIONVERSIONID_BINDING);
protocolMarshaller.marshall(deleteApplicationCloudWatchLoggingOptionRequest.getCloudWatchLoggingOptionId(), CLOUDWATCHLOGGINGOPTIONID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeleteApplicationCloudWatchLoggingOptionRequest deleteApplicationCloudWatchLoggingOptionRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteApplicationCloudWatchLoggingOptionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteApplicationCloudWatchLoggingOptionRequest.getApplicationName(), APPLICATIONNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deleteApplicationCloudWatchLoggingOptionRequest.getCurrentApplicationVersionId(), CURRENTAPPLICATIONVERSIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deleteApplicationCloudWatchLoggingOptionRequest.getCloudWatchLoggingOptionId(), CLOUDWATCHLOGGINGOPTIONID_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 DescribeSchemasResult withSchemas(String... schemas) {
if (this.schemas == null) {
setSchemas(new java.util.ArrayList<String>(schemas.length));
}
for (String ele : schemas) {
this.schemas.add(ele);
}
return this;
} } | public class class_name {
public DescribeSchemasResult withSchemas(String... schemas) {
if (this.schemas == null) {
setSchemas(new java.util.ArrayList<String>(schemas.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : schemas) {
this.schemas.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
protected Collection<? extends GrantedAuthority> loadUserAuthorities(
DirContextOperations userData, String username, String password) {
String[] groups = userData.getStringAttributes("memberOf");
if (groups == null) {
logger.debug("No values for 'memberOf' attribute.");
return AuthorityUtils.NO_AUTHORITIES;
}
if (logger.isDebugEnabled()) {
logger.debug("'memberOf' attribute values: " + Arrays.asList(groups));
}
ArrayList<GrantedAuthority> authorities = new ArrayList<>(
groups.length);
for (String group : groups) {
authorities.add(new SimpleGrantedAuthority(new DistinguishedName(group)
.removeLast().getValue()));
}
return authorities;
} } | public class class_name {
@Override
protected Collection<? extends GrantedAuthority> loadUserAuthorities(
DirContextOperations userData, String username, String password) {
String[] groups = userData.getStringAttributes("memberOf");
if (groups == null) {
logger.debug("No values for 'memberOf' attribute.");
return AuthorityUtils.NO_AUTHORITIES;
}
if (logger.isDebugEnabled()) {
logger.debug("'memberOf' attribute values: " + Arrays.asList(groups)); // depends on control dependency: [if], data = [none]
}
ArrayList<GrantedAuthority> authorities = new ArrayList<>(
groups.length);
for (String group : groups) {
authorities.add(new SimpleGrantedAuthority(new DistinguishedName(group)
.removeLast().getValue())); // depends on control dependency: [for], data = [none]
}
return authorities;
} } |
public class class_name {
public String parse() {
Map<String, ClassConstraints> classNameToValidationRulesMap = new HashMap<>();
for (Class clazz : classpathScanner.findClassesToParse()) {
if (clazz != null) {
ClassConstraints classValidationRules = new AnnotatedClass(clazz, options.getExcludedFields(),
allRelevantAnnotationClasses).extractValidationRules();
if (classValidationRules.size() > 0) {
String name = options.getOutputFullTypeName() ? clazz.getName() : clazz.getSimpleName();
classNameToValidationRulesMap.put(name, classValidationRules);
}
}
}
return toJson(classNameToValidationRulesMap);
} } | public class class_name {
public String parse() {
Map<String, ClassConstraints> classNameToValidationRulesMap = new HashMap<>();
for (Class clazz : classpathScanner.findClassesToParse()) {
if (clazz != null) {
ClassConstraints classValidationRules = new AnnotatedClass(clazz, options.getExcludedFields(),
allRelevantAnnotationClasses).extractValidationRules();
if (classValidationRules.size() > 0) {
String name = options.getOutputFullTypeName() ? clazz.getName() : clazz.getSimpleName();
classNameToValidationRulesMap.put(name, classValidationRules); // depends on control dependency: [if], data = [none]
}
}
}
return toJson(classNameToValidationRulesMap);
} } |
public class class_name {
public final void mSTRING_LITERAL() throws RecognitionException {
try {
int _type = STRING_LITERAL;
int _channel = DEFAULT_TOKEN_CHANNEL;
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:5: ( '\"' ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )* '\"' )
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:9: '\"' ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )* '\"'
{
match('\"');
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:13: ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )*
loop17:
do {
int alt17=3;
int LA17_0 = input.LA(1);
if ( (LA17_0=='\\') ) {
alt17=1;
}
else if ( ((LA17_0>='\u0000' && LA17_0<='!')||(LA17_0>='#' && LA17_0<='[')||(LA17_0>=']' && LA17_0<='\uFFFF')) ) {
alt17=2;
}
switch (alt17) {
case 1 :
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:15: ESC_SEQ
{
mESC_SEQ();
}
break;
case 2 :
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:25: ~ ( '\\\\' | '\"' )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop17;
}
} while (true);
match('\"');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
} } | public class class_name {
public final void mSTRING_LITERAL() throws RecognitionException {
try {
int _type = STRING_LITERAL;
int _channel = DEFAULT_TOKEN_CHANNEL;
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:5: ( '\"' ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )* '\"' )
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:9: '\"' ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )* '\"'
{
match('\"');
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:13: ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )*
loop17:
do {
int alt17=3;
int LA17_0 = input.LA(1);
if ( (LA17_0=='\\') ) {
alt17=1; // depends on control dependency: [if], data = [none]
}
else if ( ((LA17_0>='\u0000' && LA17_0<='!')||(LA17_0>='#' && LA17_0<='[')||(LA17_0>=']' && LA17_0<='\uFFFF')) ) {
alt17=2; // depends on control dependency: [if], data = [none]
}
switch (alt17) {
case 1 :
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:15: ESC_SEQ
{
mESC_SEQ();
}
break;
case 2 :
// com/dyuproject/protostuff/parser/ProtoLexer.g:272:25: ~ ( '\\\\' | '\"' )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) {
input.consume(); // depends on control dependency: [if], data = [none]
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse); // depends on control dependency: [if], data = [none]
throw mse;}
}
break;
default :
break loop17;
}
} while (true);
match('\"');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
} } |
public class class_name {
public static void bindDragHandle(final RecyclerView.ViewHolder holder, final IExtendedDraggable item) {
// if necessary, init the drag handle, which will start the drag when touched
if (item.getTouchHelper() != null && item.getDragView(holder) != null) {
item.getDragView(holder).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
if (item.isDraggable())
item.getTouchHelper().startDrag(holder);
}
return false;
}
});
}
} } | public class class_name {
public static void bindDragHandle(final RecyclerView.ViewHolder holder, final IExtendedDraggable item) {
// if necessary, init the drag handle, which will start the drag when touched
if (item.getTouchHelper() != null && item.getDragView(holder) != null) {
item.getDragView(holder).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
if (item.isDraggable())
item.getTouchHelper().startDrag(holder);
}
return false;
}
}); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
protected static String derivePattern(String path) {
String pattern;
if ("/".equals(path)) {
pattern = "/**";
} else {
String patternBase = path;
if (patternBase.endsWith("/")) {
patternBase = path.substring(0, path.length() - 1);
}
pattern = path + "," + path + "/**";
}
return pattern;
} } | public class class_name {
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
protected static String derivePattern(String path) {
String pattern;
if ("/".equals(path)) {
pattern = "/**"; // depends on control dependency: [if], data = [none]
} else {
String patternBase = path;
if (patternBase.endsWith("/")) {
patternBase = path.substring(0, path.length() - 1); // depends on control dependency: [if], data = [none]
}
pattern = path + "," + path + "/**"; // depends on control dependency: [if], data = [none]
}
return pattern;
} } |
public class class_name {
public void setAccountIdsToAdd(java.util.Collection<String> accountIdsToAdd) {
if (accountIdsToAdd == null) {
this.accountIdsToAdd = null;
return;
}
this.accountIdsToAdd = new com.amazonaws.internal.SdkInternalList<String>(accountIdsToAdd);
} } | public class class_name {
public void setAccountIdsToAdd(java.util.Collection<String> accountIdsToAdd) {
if (accountIdsToAdd == null) {
this.accountIdsToAdd = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.accountIdsToAdd = new com.amazonaws.internal.SdkInternalList<String>(accountIdsToAdd);
} } |
public class class_name {
@Override
public WroModel create() {
WroModel newModel = null;
try {
newModel = super.create();
} catch (final WroRuntimeException e) {
LOG.error("Error while creating the model", e);
}
if (newModel == null) {
LOG.warn("Couldn't load new model, reusing last Valid Model!");
if (lastValidModel == null) {
throw new WroRuntimeException("No valid model was found!");
}
return lastValidModel;
}
lastValidModel = newModel;
return lastValidModel;
} } | public class class_name {
@Override
public WroModel create() {
WroModel newModel = null;
try {
newModel = super.create();
// depends on control dependency: [try], data = [none]
} catch (final WroRuntimeException e) {
LOG.error("Error while creating the model", e);
}
// depends on control dependency: [catch], data = [none]
if (newModel == null) {
LOG.warn("Couldn't load new model, reusing last Valid Model!");
// depends on control dependency: [if], data = [none]
if (lastValidModel == null) {
throw new WroRuntimeException("No valid model was found!");
}
return lastValidModel;
// depends on control dependency: [if], data = [none]
}
lastValidModel = newModel;
return lastValidModel;
} } |
public class class_name {
public ServiceBroker use(Collection<Middleware> middlewares) {
if (serviceRegistry == null) {
// Apply middlewares later
this.middlewares.addAll(middlewares);
} else {
// Apply middlewares now
serviceRegistry.use(middlewares);
}
return this;
} } | public class class_name {
public ServiceBroker use(Collection<Middleware> middlewares) {
if (serviceRegistry == null) {
// Apply middlewares later
this.middlewares.addAll(middlewares); // depends on control dependency: [if], data = [none]
} else {
// Apply middlewares now
serviceRegistry.use(middlewares); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public String convert(BufferedImage image, boolean favicon) {
// Reset statistics before anything
statsArray = new int[12];
// Begin the timer
dStart = System.nanoTime();
// Scale the image
image = scale(image, favicon);
// The +1 is for the newline characters
StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());
for (int y = 0; y < image.getHeight(); y++) {
// At the end of each line, add a newline character
if (sb.length() != 0) sb.append("\n");
for (int x = 0; x < image.getWidth(); x++) {
//
Color pixelColor = new Color(image.getRGB(x, y), true);
int alpha = pixelColor.getAlpha();
boolean isTransient = alpha < 0.1;
double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);
final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);
sb.append(s);
}
}
imgArray = sb.toString().toCharArray();
dEnd = System.nanoTime();
return sb.toString();
} } | public class class_name {
public String convert(BufferedImage image, boolean favicon) {
// Reset statistics before anything
statsArray = new int[12];
// Begin the timer
dStart = System.nanoTime();
// Scale the image
image = scale(image, favicon);
// The +1 is for the newline characters
StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());
for (int y = 0; y < image.getHeight(); y++) {
// At the end of each line, add a newline character
if (sb.length() != 0) sb.append("\n");
for (int x = 0; x < image.getWidth(); x++) {
//
Color pixelColor = new Color(image.getRGB(x, y), true);
int alpha = pixelColor.getAlpha();
boolean isTransient = alpha < 0.1;
double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);
final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);
sb.append(s); // depends on control dependency: [for], data = [none]
}
}
imgArray = sb.toString().toCharArray();
dEnd = System.nanoTime();
return sb.toString();
} } |
public class class_name {
@Override
protected Double boundaryForSegment(String segmentName) throws IOException {
if (segmentRegistration.equals(SEGMENT_SORT_ASC)
|| segmentRegistration.equals(SEGMENT_SORT_DESC)) {
Double thisLast = segmentValueTopListLast.get(segmentName);
if (thisLast == null) {
return null;
} else if (segmentRegistration.equals(SEGMENT_SORT_ASC)) {
return thisLast * segmentNumber;
} else {
return thisLast / segmentNumber;
}
} else {
throw new IOException("can't compute boundary for segmentRegistration "
+ segmentRegistration);
}
} } | public class class_name {
@Override
protected Double boundaryForSegment(String segmentName) throws IOException {
if (segmentRegistration.equals(SEGMENT_SORT_ASC)
|| segmentRegistration.equals(SEGMENT_SORT_DESC)) {
Double thisLast = segmentValueTopListLast.get(segmentName);
if (thisLast == null) {
return null; // depends on control dependency: [if], data = [none]
} else if (segmentRegistration.equals(SEGMENT_SORT_ASC)) {
return thisLast * segmentNumber; // depends on control dependency: [if], data = [none]
} else {
return thisLast / segmentNumber; // depends on control dependency: [if], data = [none]
}
} else {
throw new IOException("can't compute boundary for segmentRegistration "
+ segmentRegistration);
}
} } |
public class class_name {
protected final void beforeDelivery(MessageEndpoint endpoint) {
if (TRACE.isEntryEnabled()) {
final String methodName = "beforeDelivery";
SibTr.entry(this, TRACE, methodName, endpoint);
SibTr.exit(this, TRACE, methodName);
}
} } | public class class_name {
protected final void beforeDelivery(MessageEndpoint endpoint) {
if (TRACE.isEntryEnabled()) {
final String methodName = "beforeDelivery";
SibTr.entry(this, TRACE, methodName, endpoint); // depends on control dependency: [if], data = [none]
SibTr.exit(this, TRACE, methodName); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public long size() {
if (this.isDirectory()) {
return -1L;
}
final Asset asset = this.getArchive().get(this.path.toString()).getAsset();
final InputStream stream = asset.openStream();
int totalRead = 0;
final byte[] buffer = new byte[1024 * 4];
int read = 0;
try {
while ((read = stream.read(buffer, 0, buffer.length)) != -1) {
totalRead += read;
}
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
return totalRead;
} } | public class class_name {
@Override
public long size() {
if (this.isDirectory()) {
return -1L; // depends on control dependency: [if], data = [none]
}
final Asset asset = this.getArchive().get(this.path.toString()).getAsset();
final InputStream stream = asset.openStream();
int totalRead = 0;
final byte[] buffer = new byte[1024 * 4];
int read = 0;
try {
while ((read = stream.read(buffer, 0, buffer.length)) != -1) {
totalRead += read; // depends on control dependency: [while], data = [none]
}
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
} // depends on control dependency: [catch], data = [none]
return totalRead;
} } |
public class class_name {
protected Set<Radio> getRadioChildren(final Widget widget, final Set<Radio> c) {
Set<Radio> children = c;
if (children == null) {
children = new HashSet<Radio>();
}
if (widget instanceof Radio) {
children.add((Radio) widget);
} else if (widget instanceof HasOneWidget) {
children = getRadioChildren(((HasOneWidget) widget).getWidget(), children);
} else if (widget instanceof HasWidgets) {
for (Widget w : (HasWidgets) widget) {
if (w instanceof Radio) {
children.add((Radio) w);
} else {
children = getRadioChildren(w, children);
}
}
}
return children;
} } | public class class_name {
protected Set<Radio> getRadioChildren(final Widget widget, final Set<Radio> c) {
Set<Radio> children = c;
if (children == null) {
children = new HashSet<Radio>(); // depends on control dependency: [if], data = [none]
}
if (widget instanceof Radio) {
children.add((Radio) widget); // depends on control dependency: [if], data = [none]
} else if (widget instanceof HasOneWidget) {
children = getRadioChildren(((HasOneWidget) widget).getWidget(), children); // depends on control dependency: [if], data = [none]
} else if (widget instanceof HasWidgets) {
for (Widget w : (HasWidgets) widget) {
if (w instanceof Radio) {
children.add((Radio) w); // depends on control dependency: [if], data = [none]
} else {
children = getRadioChildren(w, children); // depends on control dependency: [if], data = [none]
}
}
}
return children;
} } |
public class class_name {
public void setLaunchTemplates(java.util.Collection<LaunchTemplate> launchTemplates) {
if (launchTemplates == null) {
this.launchTemplates = null;
return;
}
this.launchTemplates = new com.amazonaws.internal.SdkInternalList<LaunchTemplate>(launchTemplates);
} } | public class class_name {
public void setLaunchTemplates(java.util.Collection<LaunchTemplate> launchTemplates) {
if (launchTemplates == null) {
this.launchTemplates = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.launchTemplates = new com.amazonaws.internal.SdkInternalList<LaunchTemplate>(launchTemplates);
} } |
public class class_name {
public static <S1, S2, I, T1, T2, SP, TP, A extends MutableDeterministic<S2, I, T2, SP, TP>> A toDeterministic(
PaigeTarjan pt,
AutomatonCreator<A, I> creator,
Alphabet<I> inputs,
DeterministicAutomaton<S1, I, T1> original,
StateIDs<S1> origIds,
Function<? super S1, ? extends SP> spExtractor,
Function<? super T1, ? extends TP> tpExtractor,
boolean pruneUnreachable) {
final Function<? super S1, ? extends SP> safeSpExtractor = FunctionsUtil.safeDefault(spExtractor);
final Function<? super T1, ? extends TP> safeTpExtractor = FunctionsUtil.safeDefault(tpExtractor);
if (pruneUnreachable) {
return toDeterministicPruned(pt, creator, inputs, original, origIds, safeSpExtractor, safeTpExtractor);
}
return toDeterministicUnpruned(pt, creator, inputs, original, origIds, safeSpExtractor, safeTpExtractor);
} } | public class class_name {
public static <S1, S2, I, T1, T2, SP, TP, A extends MutableDeterministic<S2, I, T2, SP, TP>> A toDeterministic(
PaigeTarjan pt,
AutomatonCreator<A, I> creator,
Alphabet<I> inputs,
DeterministicAutomaton<S1, I, T1> original,
StateIDs<S1> origIds,
Function<? super S1, ? extends SP> spExtractor,
Function<? super T1, ? extends TP> tpExtractor,
boolean pruneUnreachable) {
final Function<? super S1, ? extends SP> safeSpExtractor = FunctionsUtil.safeDefault(spExtractor);
final Function<? super T1, ? extends TP> safeTpExtractor = FunctionsUtil.safeDefault(tpExtractor);
if (pruneUnreachable) {
return toDeterministicPruned(pt, creator, inputs, original, origIds, safeSpExtractor, safeTpExtractor); // depends on control dependency: [if], data = [none]
}
return toDeterministicUnpruned(pt, creator, inputs, original, origIds, safeSpExtractor, safeTpExtractor);
} } |
public class class_name {
private void checkColumnSize(Column<?> newColumn) {
if (columnCount() != 0) {
Preconditions.checkArgument(newColumn.size() == rowCount(),
"Column " + newColumn.name() +
" does not have the same number of rows as the other columns in the table.");
}
} } | public class class_name {
private void checkColumnSize(Column<?> newColumn) {
if (columnCount() != 0) {
Preconditions.checkArgument(newColumn.size() == rowCount(),
"Column " + newColumn.name() +
" does not have the same number of rows as the other columns in the table."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public long addNextFile(SourceFile source)
{
String strPath = source.getFilePath();
long lStreamLength = source.getStreamLength();
InputStream inStream = source.makeInStream();
long lLength = 0;
try {
if (m_lMaxZipFileSize > 0)
//? if (lLength != File.OL)
{ // Check to make sure this file will fit
if (m_lCurrentLength + lStreamLength > m_lMaxZipFileSize)
{ // Writing this file would push me past the file length limit
try {
m_outZip.flush();
m_outZip.close();
m_lCurrentLength = 0;
m_iFileNumber++;
int iPosDot = m_strZipFilename.lastIndexOf('.');
if (iPosDot == -1)
iPosDot = m_strZipFilename.length();
String strZipFilename = m_strZipFilename.substring(0, iPosDot);
strZipFilename += Integer.toString(m_iFileNumber);
if (iPosDot != m_strZipFilename.length())
strZipFilename += m_strZipFilename.substring(iPosDot);
FileOutputStream outStream = new FileOutputStream(strZipFilename);
m_outZip = new ZipOutputStream(outStream);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
ZipEntry zipEntry = new ZipEntry(strPath);
if (DEBUG)
System.out.println(strPath);
m_outZip.putNextEntry(zipEntry);
lLength = Util.copyStream(inStream, m_outZip);
m_lCurrentLength += lLength;
} catch (IOException ex) {
ex.printStackTrace();
}
return lLength;
} } | public class class_name {
public long addNextFile(SourceFile source)
{
String strPath = source.getFilePath();
long lStreamLength = source.getStreamLength();
InputStream inStream = source.makeInStream();
long lLength = 0;
try {
if (m_lMaxZipFileSize > 0)
//? if (lLength != File.OL)
{ // Check to make sure this file will fit
if (m_lCurrentLength + lStreamLength > m_lMaxZipFileSize)
{ // Writing this file would push me past the file length limit
try {
m_outZip.flush(); // depends on control dependency: [try], data = [none]
m_outZip.close(); // depends on control dependency: [try], data = [none]
m_lCurrentLength = 0; // depends on control dependency: [try], data = [none]
m_iFileNumber++; // depends on control dependency: [try], data = [none]
int iPosDot = m_strZipFilename.lastIndexOf('.');
if (iPosDot == -1)
iPosDot = m_strZipFilename.length();
String strZipFilename = m_strZipFilename.substring(0, iPosDot);
strZipFilename += Integer.toString(m_iFileNumber); // depends on control dependency: [try], data = [none]
if (iPosDot != m_strZipFilename.length())
strZipFilename += m_strZipFilename.substring(iPosDot);
FileOutputStream outStream = new FileOutputStream(strZipFilename);
m_outZip = new ZipOutputStream(outStream); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) { // depends on control dependency: [catch], data = [none]
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
}
ZipEntry zipEntry = new ZipEntry(strPath);
if (DEBUG)
System.out.println(strPath);
m_outZip.putNextEntry(zipEntry); // depends on control dependency: [try], data = [none]
lLength = Util.copyStream(inStream, m_outZip); // depends on control dependency: [try], data = [none]
m_lCurrentLength += lLength; // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
return lLength;
} } |
public class class_name {
public static final synchronized Date parseTime(String time) {
try {
return timeFormat.parse(time);
} catch(ParseException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static final synchronized Date parseTime(String time) {
try {
return timeFormat.parse(time); // depends on control dependency: [try], data = [none]
} catch(ParseException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public int append(ReadableByteChannel channel) throws IOException {
assert invariant(true);
int totalRead = 0;
try {
boolean done;
// precondition: the channel has data
do {
ByteBuffer dest = writableBuf();
int space = dest.remaining();
assert space > 0;
int read = channel.read(dest);
if (read >= 0) {
totalRead += read;
} else {
// end of stream (e.g. the other end closed the connection)
removeLastBufferIfEmpty();
sizeChanged();
assert invariant(true);
return -1;
}
// if buffer wasn't filled -> no data is available in channel
done = read < space;
} while (!done);
} finally {
removeLastBufferIfEmpty();
sizeChanged();
assert invariant(true);
}
return totalRead;
} } | public class class_name {
@Override
public int append(ReadableByteChannel channel) throws IOException {
assert invariant(true);
int totalRead = 0;
try {
boolean done;
// precondition: the channel has data
do {
ByteBuffer dest = writableBuf();
int space = dest.remaining();
assert space > 0;
int read = channel.read(dest);
if (read >= 0) {
totalRead += read; // depends on control dependency: [if], data = [none]
} else {
// end of stream (e.g. the other end closed the connection)
removeLastBufferIfEmpty(); // depends on control dependency: [if], data = [none]
sizeChanged(); // depends on control dependency: [if], data = [none]
assert invariant(true); // depends on control dependency: [if], data = [none]
return -1; // depends on control dependency: [if], data = [none]
}
// if buffer wasn't filled -> no data is available in channel
done = read < space;
} while (!done);
} finally {
removeLastBufferIfEmpty();
sizeChanged();
assert invariant(true);
}
return totalRead;
} } |
public class class_name {
public static void rcvCreateDurableSub(CommsByteBuffer request, Conversation conversation,
int requestNumber,
boolean allocatedFromBufferPool,
boolean partOfExchange)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvCreateDurableSub",
new Object[]
{
request,
conversation,
""+requestNumber,
""+allocatedFromBufferPool
});
ConversationState convState = (ConversationState) conversation.getAttachment();
short connectionObjectID = request.getShort(); // BIT16 ConnectionObjectId
short consumerFlags = request.getShort(); // BIT16 Consumer Flags
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "ConnectionObjectId:", connectionObjectID);
SibTr.debug(tc, "ConsumerFlags:", consumerFlags);
}
/**************************************************************/
/* Consumer flags */
/**************************************************************/
// Check if the flags are valid
if (consumerFlags > 0x07)
{
// The flags appear to be invalid
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Consumer flags ("+consumerFlags+") > 0x07");
SIErrorException e = new SIErrorException(
nls.getFormattedMessage("INVALID_PROP_SICO8014", new Object[] {""+consumerFlags }, null)
);
FFDCFilter.processException(e, CLASS_NAME + ".rcvCreateDurableSub",
CommsConstants.STATICCATSUBSCRIPTION_CREATE_03);
}
boolean noLocal = (consumerFlags & 0x02) != 0;
boolean supportMultipleConsumers = (consumerFlags & 0x04) != 0;
/**************************************************************/
/* Destination Info */
/**************************************************************/
SIDestinationAddress destAddress = request.getSIDestinationAddress(conversation.getHandshakeProperties().getFapLevel());
/**************************************************************/
/* Subscription Name */
/**************************************************************/
String subscriptionName = request.getString();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Subscription Name:", subscriptionName);
/**************************************************************/
/* Subscription Home */
/**************************************************************/
String subscriptionHome = request.getString();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Subscription Home:", subscriptionHome);
/**************************************************************/
/* SelectionCriteria */
/**************************************************************/
SelectionCriteria criteria = request.getSelectionCriteria();
SICoreConnection connection =
((CATConnection) convState.getObject(connectionObjectID)).getSICoreConnection();
/**************************************************************/
/* Alternate User Id */
/**************************************************************/
String alternateUser = request.getString();
try
{
connection.createDurableSubscription(subscriptionName,
subscriptionHome,
destAddress,
criteria,
supportMultipleConsumers,
noLocal,
alternateUser);
try
{
conversation.send(poolManager.allocate(),
JFapChannelConstants.SEG_CREATE_DURABLE_SUB_R,
requestNumber,
JFapChannelConstants.PRIORITY_MEDIUM,
true,
ThrottlingPolicy.BLOCK_THREAD,
null);
}
catch (SIException e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".rcvCreateDurableSub",
CommsConstants.STATICCATSUBSCRIPTION_CREATE_01);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, e.getMessage(), e);
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2025", e);
}
}
catch (SINotAuthorizedException e)
{
// No FFDC Code Needed
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, e.getMessage(), e);
StaticCATHelper.sendExceptionToClient(e,
null,
conversation, requestNumber);
}
catch (SIException e)
{
//No FFDC code needed
//Only FFDC if we haven't received a meTerminated event.
if(!convState.hasMETerminated())
{
FFDCFilter.processException(e,
CLASS_NAME + ".rcvCreateDurableSub",
CommsConstants.STATICCATSUBSCRIPTION_CREATE_02);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, e.getMessage(), e);
StaticCATHelper.sendExceptionToClient(e,
CommsConstants.STATICCATSUBSCRIPTION_CREATE_02, // d186970
conversation, requestNumber); // f172297
}
request.release(allocatedFromBufferPool);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvCreateDurableSub");
} } | public class class_name {
public static void rcvCreateDurableSub(CommsByteBuffer request, Conversation conversation,
int requestNumber,
boolean allocatedFromBufferPool,
boolean partOfExchange)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvCreateDurableSub",
new Object[]
{
request,
conversation,
""+requestNumber,
""+allocatedFromBufferPool
});
ConversationState convState = (ConversationState) conversation.getAttachment();
short connectionObjectID = request.getShort(); // BIT16 ConnectionObjectId
short consumerFlags = request.getShort(); // BIT16 Consumer Flags
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "ConnectionObjectId:", connectionObjectID); // depends on control dependency: [if], data = [none]
SibTr.debug(tc, "ConsumerFlags:", consumerFlags); // depends on control dependency: [if], data = [none]
}
/**************************************************************/
/* Consumer flags */
/**************************************************************/
// Check if the flags are valid
if (consumerFlags > 0x07)
{
// The flags appear to be invalid
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Consumer flags ("+consumerFlags+") > 0x07");
SIErrorException e = new SIErrorException(
nls.getFormattedMessage("INVALID_PROP_SICO8014", new Object[] {""+consumerFlags }, null)
);
FFDCFilter.processException(e, CLASS_NAME + ".rcvCreateDurableSub",
CommsConstants.STATICCATSUBSCRIPTION_CREATE_03); // depends on control dependency: [if], data = [none]
}
boolean noLocal = (consumerFlags & 0x02) != 0;
boolean supportMultipleConsumers = (consumerFlags & 0x04) != 0;
/**************************************************************/
/* Destination Info */
/**************************************************************/
SIDestinationAddress destAddress = request.getSIDestinationAddress(conversation.getHandshakeProperties().getFapLevel());
/**************************************************************/
/* Subscription Name */
/**************************************************************/
String subscriptionName = request.getString();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Subscription Name:", subscriptionName);
/**************************************************************/
/* Subscription Home */
/**************************************************************/
String subscriptionHome = request.getString();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Subscription Home:", subscriptionHome);
/**************************************************************/
/* SelectionCriteria */
/**************************************************************/
SelectionCriteria criteria = request.getSelectionCriteria();
SICoreConnection connection =
((CATConnection) convState.getObject(connectionObjectID)).getSICoreConnection();
/**************************************************************/
/* Alternate User Id */
/**************************************************************/
String alternateUser = request.getString();
try
{
connection.createDurableSubscription(subscriptionName,
subscriptionHome,
destAddress,
criteria,
supportMultipleConsumers,
noLocal,
alternateUser); // depends on control dependency: [try], data = [none]
try
{
conversation.send(poolManager.allocate(),
JFapChannelConstants.SEG_CREATE_DURABLE_SUB_R,
requestNumber,
JFapChannelConstants.PRIORITY_MEDIUM,
true,
ThrottlingPolicy.BLOCK_THREAD,
null); // depends on control dependency: [try], data = [none]
}
catch (SIException e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".rcvCreateDurableSub",
CommsConstants.STATICCATSUBSCRIPTION_CREATE_01);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, e.getMessage(), e);
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2025", e);
} // depends on control dependency: [catch], data = [none]
}
catch (SINotAuthorizedException e)
{
// No FFDC Code Needed
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, e.getMessage(), e);
StaticCATHelper.sendExceptionToClient(e,
null,
conversation, requestNumber);
} // depends on control dependency: [catch], data = [none]
catch (SIException e)
{
//No FFDC code needed
//Only FFDC if we haven't received a meTerminated event.
if(!convState.hasMETerminated())
{
FFDCFilter.processException(e,
CLASS_NAME + ".rcvCreateDurableSub",
CommsConstants.STATICCATSUBSCRIPTION_CREATE_02); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, e.getMessage(), e);
StaticCATHelper.sendExceptionToClient(e,
CommsConstants.STATICCATSUBSCRIPTION_CREATE_02, // d186970
conversation, requestNumber); // f172297
} // depends on control dependency: [catch], data = [none]
request.release(allocatedFromBufferPool);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvCreateDurableSub");
} } |
public class class_name {
private char retrieveWrappingQuoteTypeOfJsonMemberNames(String jsonString) {
char quote = '\"'; // the default quote character used to specify json member names and string value according to the json specification
for (char c : jsonString.toCharArray()) {
if (c == '\'' || c == '\"') {
quote = c;
break;
}
}
return quote;
} } | public class class_name {
private char retrieveWrappingQuoteTypeOfJsonMemberNames(String jsonString) {
char quote = '\"'; // the default quote character used to specify json member names and string value according to the json specification
for (char c : jsonString.toCharArray()) {
if (c == '\'' || c == '\"') {
quote = c; // depends on control dependency: [if], data = [none]
break;
}
}
return quote;
} } |
public class class_name {
public final void setHintTextColor(final ColorStateList colors) {
this.hintColor = colors;
if (getAdapter() != null) {
ProxySpinnerAdapter proxyAdapter = (ProxySpinnerAdapter) getAdapter();
setAdapter(proxyAdapter.getAdapter());
}
} } | public class class_name {
public final void setHintTextColor(final ColorStateList colors) {
this.hintColor = colors;
if (getAdapter() != null) {
ProxySpinnerAdapter proxyAdapter = (ProxySpinnerAdapter) getAdapter();
setAdapter(proxyAdapter.getAdapter()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setS3(java.util.Collection<CodeGenNodeArg> s3) {
if (s3 == null) {
this.s3 = null;
return;
}
this.s3 = new java.util.ArrayList<CodeGenNodeArg>(s3);
} } | public class class_name {
public void setS3(java.util.Collection<CodeGenNodeArg> s3) {
if (s3 == null) {
this.s3 = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.s3 = new java.util.ArrayList<CodeGenNodeArg>(s3);
} } |
public class class_name {
public void marshall(DeleteVoiceConnectorTerminationCredentialsRequest deleteVoiceConnectorTerminationCredentialsRequest,
ProtocolMarshaller protocolMarshaller) {
if (deleteVoiceConnectorTerminationCredentialsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteVoiceConnectorTerminationCredentialsRequest.getVoiceConnectorId(), VOICECONNECTORID_BINDING);
protocolMarshaller.marshall(deleteVoiceConnectorTerminationCredentialsRequest.getUsernames(), USERNAMES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeleteVoiceConnectorTerminationCredentialsRequest deleteVoiceConnectorTerminationCredentialsRequest,
ProtocolMarshaller protocolMarshaller) {
if (deleteVoiceConnectorTerminationCredentialsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteVoiceConnectorTerminationCredentialsRequest.getVoiceConnectorId(), VOICECONNECTORID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deleteVoiceConnectorTerminationCredentialsRequest.getUsernames(), USERNAMES_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T extends Throwable> T assertThrows(String message, Class<T> expectedThrowable,
ThrowingRunnable runnable) {
try {
runnable.run();
} catch (Throwable actualThrown) {
if (expectedThrowable.isInstance(actualThrown)) {
@SuppressWarnings("unchecked") T retVal = (T) actualThrown;
return retVal;
} else {
String expected = formatClass(expectedThrowable);
Class<? extends Throwable> actualThrowable = actualThrown.getClass();
String actual = formatClass(actualThrowable);
if (expected.equals(actual)) {
// There must be multiple class loaders. Add the identity hash code so the message
// doesn't say "expected: java.lang.String<my.package.MyException> ..."
expected += "@" + Integer.toHexString(System.identityHashCode(expectedThrowable));
actual += "@" + Integer.toHexString(System.identityHashCode(actualThrowable));
}
String mismatchMessage = buildPrefix(message)
+ format("unexpected exception type thrown;", expected, actual);
// The AssertionError(String, Throwable) ctor is only available on JDK7.
AssertionError assertionError = new AssertionError(mismatchMessage);
assertionError.initCause(actualThrown);
throw assertionError;
}
}
String notThrownMessage = buildPrefix(message) + String
.format("expected %s to be thrown, but nothing was thrown",
formatClass(expectedThrowable));
throw new AssertionError(notThrownMessage);
} } | public class class_name {
public static <T extends Throwable> T assertThrows(String message, Class<T> expectedThrowable,
ThrowingRunnable runnable) {
try {
runnable.run(); // depends on control dependency: [try], data = [none]
} catch (Throwable actualThrown) {
if (expectedThrowable.isInstance(actualThrown)) {
@SuppressWarnings("unchecked") T retVal = (T) actualThrown;
return retVal; // depends on control dependency: [if], data = [none]
} else {
String expected = formatClass(expectedThrowable);
Class<? extends Throwable> actualThrowable = actualThrown.getClass();
String actual = formatClass(actualThrowable);
if (expected.equals(actual)) {
// There must be multiple class loaders. Add the identity hash code so the message
// doesn't say "expected: java.lang.String<my.package.MyException> ..."
expected += "@" + Integer.toHexString(System.identityHashCode(expectedThrowable)); // depends on control dependency: [if], data = [none]
actual += "@" + Integer.toHexString(System.identityHashCode(actualThrowable)); // depends on control dependency: [if], data = [none]
}
String mismatchMessage = buildPrefix(message)
+ format("unexpected exception type thrown;", expected, actual);
// The AssertionError(String, Throwable) ctor is only available on JDK7.
AssertionError assertionError = new AssertionError(mismatchMessage);
assertionError.initCause(actualThrown); // depends on control dependency: [if], data = [none]
throw assertionError;
}
} // depends on control dependency: [catch], data = [none]
String notThrownMessage = buildPrefix(message) + String
.format("expected %s to be thrown, but nothing was thrown",
formatClass(expectedThrowable));
throw new AssertionError(notThrownMessage);
} } |
public class class_name {
private void moveToFirst(List<ImageFormat> v, int format){
for(ImageFormat i : v)
if(i.getIndex()==format){
v.remove(i);
v.add(0, i);
break;
}
} } | public class class_name {
private void moveToFirst(List<ImageFormat> v, int format){
for(ImageFormat i : v)
if(i.getIndex()==format){
v.remove(i); // depends on control dependency: [if], data = [none]
v.add(0, i); // depends on control dependency: [if], data = [none]
break;
}
} } |
public class class_name {
public int getIndex() {
if (parent != null) {
for (int i = 0; i < parent.children.size(); i++) {
if (parent.children.get(i) == this) {
return i;
}
}
}
return -1;
} } | public class class_name {
public int getIndex() {
if (parent != null) {
for (int i = 0; i < parent.children.size(); i++) {
if (parent.children.get(i) == this) {
return i; // depends on control dependency: [if], data = [none]
}
}
}
return -1;
} } |
public class class_name {
private void convertLink2Record(final int iIndex) {
if (ridOnly || !autoConvertToRecord)
// PRECONDITIONS
return;
final OIdentifiable o = super.get(iIndex);
if (contentType == MULTIVALUE_CONTENT_TYPE.ALL_RECORDS && !o.getIdentity().isNew())
// ALL RECORDS AND THE OBJECT IS NOT NEW, DO NOTHING
return;
if (o != null && o instanceof ORecordId) {
final ORecordId rid = (ORecordId) o;
marshalling = true;
try {
super.set(iIndex, rid.getRecord());
} catch (ORecordNotFoundException e) {
// IGNORE THIS
} finally {
marshalling = false;
}
}
} } | public class class_name {
private void convertLink2Record(final int iIndex) {
if (ridOnly || !autoConvertToRecord)
// PRECONDITIONS
return;
final OIdentifiable o = super.get(iIndex);
if (contentType == MULTIVALUE_CONTENT_TYPE.ALL_RECORDS && !o.getIdentity().isNew())
// ALL RECORDS AND THE OBJECT IS NOT NEW, DO NOTHING
return;
if (o != null && o instanceof ORecordId) {
final ORecordId rid = (ORecordId) o;
marshalling = true;
// depends on control dependency: [if], data = [none]
try {
super.set(iIndex, rid.getRecord());
// depends on control dependency: [try], data = [none]
} catch (ORecordNotFoundException e) {
// IGNORE THIS
} finally {
// depends on control dependency: [catch], data = [none]
marshalling = false;
}
}
} } |
public class class_name {
private synchronized File getWorkingDirectory() {
if (workingDirectory == null) {
try {
workingDirectory =
Files.createTempDirectory(TEMP_DIRECTORY_PREFIX).toFile();
} catch (IOException e) {
throw new UnexpectedException(e);
}
}
return workingDirectory;
} } | public class class_name {
private synchronized File getWorkingDirectory() {
if (workingDirectory == null) {
try {
workingDirectory =
Files.createTempDirectory(TEMP_DIRECTORY_PREFIX).toFile(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new UnexpectedException(e);
} // depends on control dependency: [catch], data = [none]
}
return workingDirectory;
} } |
public class class_name {
Throwable externalCause()
{
IdentityHashMap<Throwable, Throwable> seen =
new IdentityHashMap<Throwable, Throwable>();
Throwable cause = getCause();
while (cause instanceof IonException)
{
if (seen.put(cause, cause) != null) // cycle check
{
return null;
}
cause = cause.getCause();
}
return cause;
} } | public class class_name {
Throwable externalCause()
{
IdentityHashMap<Throwable, Throwable> seen =
new IdentityHashMap<Throwable, Throwable>();
Throwable cause = getCause();
while (cause instanceof IonException)
{
if (seen.put(cause, cause) != null) // cycle check
{
return null; // depends on control dependency: [if], data = [none]
}
cause = cause.getCause(); // depends on control dependency: [while], data = [none]
}
return cause;
} } |
public class class_name {
private static <E> Collection<E> checkElements(
Collection<E> elements, Constraint<? super E> constraint) {
Collection<E> copy = Lists.newArrayList(elements);
for (E element : copy) {
constraint.checkElement(element);
}
return copy;
} } | public class class_name {
private static <E> Collection<E> checkElements(
Collection<E> elements, Constraint<? super E> constraint) {
Collection<E> copy = Lists.newArrayList(elements);
for (E element : copy) {
constraint.checkElement(element); // depends on control dependency: [for], data = [element]
}
return copy;
} } |
public class class_name {
@Override
public void drawText(Graphics2D graphics, int width, int height) {
if(StringUtils.isBlank(text) || StringUtils.isBlank(domainName)) {
return ;
}
int x = 0, y = 0;
int fontsize = ((int)(width * textWidthPercent)) / domainName.length();
if (fontsize < minFontSize) {
return;
}
float fsize = (float)fontsize;
Font font = domainFont.deriveFont(fsize);
graphics.setFont(font);
FontRenderContext context = graphics.getFontRenderContext();
int sw = (int) font.getStringBounds(domainName, context).getWidth();
x = width - sw - fontsize;
y = height - fontsize;
if(x <= 0 || y <= 0) {
return ;
}
if (fontShadowColor != null) {
graphics.setColor(fontShadowColor);
graphics.drawString(domainName, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize));
}
graphics.setColor(fontColor);
graphics.drawString(domainName, x, y);
//draw company name
fsize = (float)fontsize;
font = defaultFont.deriveFont(fsize);
graphics.setFont(font);
context = graphics.getFontRenderContext();
sw = (int) font.getStringBounds(text, context).getWidth();
x = width - sw - fontsize;
y = height - (int)(fontsize * 2.5);
if(x <= 0 || y <= 0) {
return ;
}
if (fontShadowColor != null) {
graphics.setColor(fontShadowColor);
graphics.drawString(text, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize));
}
graphics.setColor(fontColor);
graphics.drawString(text, x, y);
} } | public class class_name {
@Override
public void drawText(Graphics2D graphics, int width, int height) {
if(StringUtils.isBlank(text) || StringUtils.isBlank(domainName)) {
return ; // depends on control dependency: [if], data = [none]
}
int x = 0, y = 0;
int fontsize = ((int)(width * textWidthPercent)) / domainName.length();
if (fontsize < minFontSize) {
return; // depends on control dependency: [if], data = [none]
}
float fsize = (float)fontsize;
Font font = domainFont.deriveFont(fsize);
graphics.setFont(font);
FontRenderContext context = graphics.getFontRenderContext();
int sw = (int) font.getStringBounds(domainName, context).getWidth();
x = width - sw - fontsize;
y = height - fontsize;
if(x <= 0 || y <= 0) {
return ; // depends on control dependency: [if], data = [none]
}
if (fontShadowColor != null) {
graphics.setColor(fontShadowColor); // depends on control dependency: [if], data = [(fontShadowColor]
graphics.drawString(domainName, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize)); // depends on control dependency: [if], data = [none]
}
graphics.setColor(fontColor);
graphics.drawString(domainName, x, y);
//draw company name
fsize = (float)fontsize;
font = defaultFont.deriveFont(fsize);
graphics.setFont(font);
context = graphics.getFontRenderContext();
sw = (int) font.getStringBounds(text, context).getWidth();
x = width - sw - fontsize;
y = height - (int)(fontsize * 2.5);
if(x <= 0 || y <= 0) {
return ; // depends on control dependency: [if], data = [none]
}
if (fontShadowColor != null) {
graphics.setColor(fontShadowColor); // depends on control dependency: [if], data = [(fontShadowColor]
graphics.drawString(text, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize)); // depends on control dependency: [if], data = [none]
}
graphics.setColor(fontColor);
graphics.drawString(text, x, y);
} } |
public class class_name {
public static List<TraceEvent> filterCCMEvents(List<TraceEvent> data) throws Exception
{
List<TraceEvent> result = new ArrayList<TraceEvent>();
for (TraceEvent te : data)
{
if (te.getType() == TraceEvent.PUSH_CCM_CONTEXT ||
te.getType() == TraceEvent.POP_CCM_CONTEXT)
{
result.add(te);
}
}
return result;
} } | public class class_name {
public static List<TraceEvent> filterCCMEvents(List<TraceEvent> data) throws Exception
{
List<TraceEvent> result = new ArrayList<TraceEvent>();
for (TraceEvent te : data)
{
if (te.getType() == TraceEvent.PUSH_CCM_CONTEXT ||
te.getType() == TraceEvent.POP_CCM_CONTEXT)
{
result.add(te); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public static @CheckForNull @CheckReturnValue
TypeQualifierAnnotation getDirectTypeQualifierAnnotation(XMethod xmethod, int parameter, TypeQualifierValue<?> typeQualifierValue) {
XMethod bridge = xmethod.bridgeTo();
if (bridge != null) {
xmethod = bridge;
}
Set<TypeQualifierAnnotation> applications = new HashSet<>();
getDirectApplications(applications, xmethod, parameter);
if (DEBUG_METHOD != null && DEBUG_METHOD.equals(xmethod.getName())) {
System.out.println(" Direct applications are: " + applications);
}
return findMatchingTypeQualifierAnnotation(applications, typeQualifierValue);
} } | public class class_name {
public static @CheckForNull @CheckReturnValue
TypeQualifierAnnotation getDirectTypeQualifierAnnotation(XMethod xmethod, int parameter, TypeQualifierValue<?> typeQualifierValue) {
XMethod bridge = xmethod.bridgeTo();
if (bridge != null) {
xmethod = bridge; // depends on control dependency: [if], data = [none]
}
Set<TypeQualifierAnnotation> applications = new HashSet<>();
getDirectApplications(applications, xmethod, parameter);
if (DEBUG_METHOD != null && DEBUG_METHOD.equals(xmethod.getName())) {
System.out.println(" Direct applications are: " + applications); // depends on control dependency: [if], data = [none]
}
return findMatchingTypeQualifierAnnotation(applications, typeQualifierValue);
} } |
public class class_name {
private String getStringValue(Node node) {
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE:
case Node.TEXT_NODE:
return node.getNodeValue();
default: {
try {
Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), new StreamResult(buffer));
return buffer.toString();
} catch (Exception e) {
}
return null;
}
}
} } | public class class_name {
private String getStringValue(Node node) {
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE:
case Node.TEXT_NODE:
return node.getNodeValue();
default: {
try {
Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // depends on control dependency: [try], data = [none]
transformer.transform(new DOMSource(node), new StreamResult(buffer)); // depends on control dependency: [try], data = [none]
return buffer.toString(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
} // depends on control dependency: [catch], data = [none]
return null;
}
}
} } |
public class class_name {
@SuppressWarnings({ "unchecked",
"PMD.AvoidThrowingNewInstanceOfSameException" })
public static <T extends Error> T duplicate(T event) {
try {
return (T) event.getClass().getConstructor(event.getClass())
.newInstance(event);
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalArgumentException(e);
}
} } | public class class_name {
@SuppressWarnings({ "unchecked",
"PMD.AvoidThrowingNewInstanceOfSameException" })
public static <T extends Error> T duplicate(T event) {
try {
return (T) event.getClass().getConstructor(event.getClass())
.newInstance(event); // depends on control dependency: [try], data = [none]
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalArgumentException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Date getCreationDateTime() {
long time = 0;
if (createtime != null) {
time = createtime.longValue() * 1000;
}
if (createtime_nano != null) {
time += (createtime_nano.longValue() / 1000000);
}
return new Date(time);
} } | public class class_name {
public Date getCreationDateTime() {
long time = 0;
if (createtime != null) {
time = createtime.longValue() * 1000; // depends on control dependency: [if], data = [none]
}
if (createtime_nano != null) {
time += (createtime_nano.longValue() / 1000000); // depends on control dependency: [if], data = [(createtime_nano]
}
return new Date(time);
} } |
public class class_name {
public java.util.List<SingleInstanceHealth> getInstanceHealthList() {
if (instanceHealthList == null) {
instanceHealthList = new com.amazonaws.internal.SdkInternalList<SingleInstanceHealth>();
}
return instanceHealthList;
} } | public class class_name {
public java.util.List<SingleInstanceHealth> getInstanceHealthList() {
if (instanceHealthList == null) {
instanceHealthList = new com.amazonaws.internal.SdkInternalList<SingleInstanceHealth>(); // depends on control dependency: [if], data = [none]
}
return instanceHealthList;
} } |
public class class_name {
private static void println(StringBuilder buf, int width, String data) {
for(String line : FormatUtil.splitAtLastBlank(data, width)) {
buf.append(line);
if(!line.endsWith(FormatUtil.NEWLINE)) {
buf.append(FormatUtil.NEWLINE);
}
}
} } | public class class_name {
private static void println(StringBuilder buf, int width, String data) {
for(String line : FormatUtil.splitAtLastBlank(data, width)) {
buf.append(line); // depends on control dependency: [for], data = [line]
if(!line.endsWith(FormatUtil.NEWLINE)) {
buf.append(FormatUtil.NEWLINE); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Nonnull
public ByteBuffer getAsNewByteBuffer (@Nonnull final String sSource)
{
// Optimized for 1 byte per character strings (ASCII)
ByteBuffer ret = ByteBuffer.allocate (sSource.length () + BUFFER_EXTRA_BYTES);
while (encode (sSource, ret).isContinue ())
{
// need a larger buffer
// estimate the average bytes per character from the current sample
final int nCharsConverted = _getCharsConverted ();
double dBytesPerChar;
if (nCharsConverted > 0)
{
dBytesPerChar = ret.position () / (double) nCharsConverted;
}
else
{
// charsConverted can be 0 if the initial buffer is smaller than one
// character
dBytesPerChar = m_aEncoder.averageBytesPerChar ();
}
final int nCharsRemaining = sSource.length () - nCharsConverted;
assert nCharsRemaining > 0;
final int nBytesRemaining = (int) (nCharsRemaining * dBytesPerChar + 0.5);
final int nPos = ret.position ();
final ByteBuffer aNewBuffer = ByteBuffer.allocate (ret.position () + nBytesRemaining + BUFFER_EXTRA_BYTES);
ret.flip ();
aNewBuffer.put (ret);
aNewBuffer.position (nPos);
ret = aNewBuffer;
}
// Set the buffer for reading and finish
ret.flip ();
return ret;
} } | public class class_name {
@Nonnull
public ByteBuffer getAsNewByteBuffer (@Nonnull final String sSource)
{
// Optimized for 1 byte per character strings (ASCII)
ByteBuffer ret = ByteBuffer.allocate (sSource.length () + BUFFER_EXTRA_BYTES);
while (encode (sSource, ret).isContinue ())
{
// need a larger buffer
// estimate the average bytes per character from the current sample
final int nCharsConverted = _getCharsConverted ();
double dBytesPerChar;
if (nCharsConverted > 0)
{
dBytesPerChar = ret.position () / (double) nCharsConverted; // depends on control dependency: [if], data = [none]
}
else
{
// charsConverted can be 0 if the initial buffer is smaller than one
// character
dBytesPerChar = m_aEncoder.averageBytesPerChar (); // depends on control dependency: [if], data = [none]
}
final int nCharsRemaining = sSource.length () - nCharsConverted;
assert nCharsRemaining > 0;
final int nBytesRemaining = (int) (nCharsRemaining * dBytesPerChar + 0.5);
final int nPos = ret.position ();
final ByteBuffer aNewBuffer = ByteBuffer.allocate (ret.position () + nBytesRemaining + BUFFER_EXTRA_BYTES);
ret.flip (); // depends on control dependency: [while], data = [none]
aNewBuffer.put (ret); // depends on control dependency: [while], data = [none]
aNewBuffer.position (nPos); // depends on control dependency: [while], data = [none]
ret = aNewBuffer; // depends on control dependency: [while], data = [none]
}
// Set the buffer for reading and finish
ret.flip ();
return ret;
} } |
public class class_name {
protected StringPropertyEditor getRDFCommentEditor(BioPAXElement bpe)
{
StringPropertyEditor editor;
Class<? extends BioPAXElement> inter = bpe.getModelInterface();
if (this.getLevel().equals(BioPAXLevel.L3))
{
editor = (StringPropertyEditor) this.getEditorMap().getEditorForProperty("comment", inter);
} else
{
editor = (StringPropertyEditor) this.getEditorMap().getEditorForProperty("COMMENT", inter);
}
return editor;
} } | public class class_name {
protected StringPropertyEditor getRDFCommentEditor(BioPAXElement bpe)
{
StringPropertyEditor editor;
Class<? extends BioPAXElement> inter = bpe.getModelInterface();
if (this.getLevel().equals(BioPAXLevel.L3))
{
editor = (StringPropertyEditor) this.getEditorMap().getEditorForProperty("comment", inter); // depends on control dependency: [if], data = [none]
} else
{
editor = (StringPropertyEditor) this.getEditorMap().getEditorForProperty("COMMENT", inter); // depends on control dependency: [if], data = [none]
}
return editor;
} } |
public class class_name {
@SuppressWarnings("unchecked")
private boolean hasPropertiesConfiguration(Dictionary properties) {
HashMap<Object, Object> mapProperties = new HashMap<Object, Object>(properties.size());
for (Object key : Collections.list(properties.keys())) {
mapProperties.put(key, properties.get(key));
}
mapProperties.remove(Constants.SERVICE_PID);
mapProperties.remove("service.factoryPid");
return !mapProperties.isEmpty();
} } | public class class_name {
@SuppressWarnings("unchecked")
private boolean hasPropertiesConfiguration(Dictionary properties) {
HashMap<Object, Object> mapProperties = new HashMap<Object, Object>(properties.size());
for (Object key : Collections.list(properties.keys())) {
mapProperties.put(key, properties.get(key)); // depends on control dependency: [for], data = [key]
}
mapProperties.remove(Constants.SERVICE_PID);
mapProperties.remove("service.factoryPid");
return !mapProperties.isEmpty();
} } |
public class class_name {
public synchronized void start() {
for (final AttributeCache cache : attributeCacheMap.values()) {
cache.startRefresh(POLLING_POOL);
}
for (final CommandCache cache : commandCacheMap.values()) {
cache.startRefresh(POLLING_POOL);
}
if (stateCache != null) {
stateCache.startRefresh(POLLING_POOL);
}
if (statusCache != null) {
statusCache.startRefresh(POLLING_POOL);
}
} } | public class class_name {
public synchronized void start() {
for (final AttributeCache cache : attributeCacheMap.values()) {
cache.startRefresh(POLLING_POOL); // depends on control dependency: [for], data = [cache]
}
for (final CommandCache cache : commandCacheMap.values()) {
cache.startRefresh(POLLING_POOL); // depends on control dependency: [for], data = [cache]
}
if (stateCache != null) {
stateCache.startRefresh(POLLING_POOL); // depends on control dependency: [if], data = [none]
}
if (statusCache != null) {
statusCache.startRefresh(POLLING_POOL); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public synchronized void entering(long fnr2)
{
int fnr = (int) fnr2; // Here the long value is casted into in to be used as index to the arrays.
requesting(fnr);// the #req counter is changed to add one to it.
try
{
if (!instance.evaluatePP(fnr).booleanValue()) // the first evaluation of the permition predicate.
{
waiting(fnr, +1);// if the permission predicate is false. It add one to the #waiting counter.
while (!instance.evaluatePP(fnr).booleanValue())// reevaluation of the permission predicate.
{
this.wait(); // actual thread wait method. This freeze the thread waiting for the execution of its
// method.
}
waiting(fnr, -1); // if predicate changes to true, #waiting is changed to remove one.
}
} catch (InterruptedException e)
{
}
activating(fnr);// the #act and the #active counters are change to add one to them
} } | public class class_name {
public synchronized void entering(long fnr2)
{
int fnr = (int) fnr2; // Here the long value is casted into in to be used as index to the arrays.
requesting(fnr);// the #req counter is changed to add one to it.
try
{
if (!instance.evaluatePP(fnr).booleanValue()) // the first evaluation of the permition predicate.
{
waiting(fnr, +1);// if the permission predicate is false. It add one to the #waiting counter. // depends on control dependency: [if], data = [none]
while (!instance.evaluatePP(fnr).booleanValue())// reevaluation of the permission predicate.
{
this.wait(); // actual thread wait method. This freeze the thread waiting for the execution of its // depends on control dependency: [while], data = [none]
// method.
}
waiting(fnr, -1); // if predicate changes to true, #waiting is changed to remove one. // depends on control dependency: [if], data = [none]
}
} catch (InterruptedException e)
{
} // depends on control dependency: [catch], data = [none]
activating(fnr);// the #act and the #active counters are change to add one to them
} } |
public class class_name {
public Object get(Object key, int version) {
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET], key + " " + version);
}
String id = (String) key;
Object obj = getSession(id, version, true); //update the last access time?
return obj;
} } | public class class_name {
public Object get(Object key, int version) {
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET], key + " " + version); // depends on control dependency: [if], data = [none]
}
String id = (String) key;
Object obj = getSession(id, version, true); //update the last access time?
return obj;
} } |
public class class_name {
protected void checkMethods(Class<?> itfClass) {
ConcurrentHashMap<String, Boolean> methodsLimit = new ConcurrentHashMap<String, Boolean>();
for (Method method : itfClass.getMethods()) {
String methodName = method.getName();
if (methodsLimit.containsKey(methodName)) {
// 重名的方法
if (LOGGER.isWarnEnabled(providerConfig.getAppName())) {
LOGGER.warnWithApp(providerConfig.getAppName(), "Method with same name \"" + itfClass.getName()
+ "." + methodName + "\" exists ! The usage of overloading method in rpc is deprecated.");
}
}
// 判断服务下方法的黑白名单
Boolean include = methodsLimit.get(methodName);
if (include == null) {
include = inList(providerConfig.getInclude(), providerConfig.getExclude(), methodName); // 检查是否在黑白名单中
methodsLimit.putIfAbsent(methodName, include);
}
providerConfig.setMethodsLimit(methodsLimit);
}
} } | public class class_name {
protected void checkMethods(Class<?> itfClass) {
ConcurrentHashMap<String, Boolean> methodsLimit = new ConcurrentHashMap<String, Boolean>();
for (Method method : itfClass.getMethods()) {
String methodName = method.getName();
if (methodsLimit.containsKey(methodName)) {
// 重名的方法
if (LOGGER.isWarnEnabled(providerConfig.getAppName())) {
LOGGER.warnWithApp(providerConfig.getAppName(), "Method with same name \"" + itfClass.getName()
+ "." + methodName + "\" exists ! The usage of overloading method in rpc is deprecated."); // depends on control dependency: [if], data = [none]
}
}
// 判断服务下方法的黑白名单
Boolean include = methodsLimit.get(methodName);
if (include == null) {
include = inList(providerConfig.getInclude(), providerConfig.getExclude(), methodName); // 检查是否在黑白名单中 // depends on control dependency: [if], data = [none]
methodsLimit.putIfAbsent(methodName, include); // depends on control dependency: [if], data = [none]
}
providerConfig.setMethodsLimit(methodsLimit); // depends on control dependency: [for], data = [method]
}
} } |
public class class_name {
public static String getResourceVersion(HasMetadata entity) {
if (entity != null) {
ObjectMeta metadata = entity.getMetadata();
if (metadata != null) {
String resourceVersion = metadata.getResourceVersion();
if (StringUtils.isNotBlank(resourceVersion)) {
return resourceVersion;
}
}
}
return null;
} } | public class class_name {
public static String getResourceVersion(HasMetadata entity) {
if (entity != null) {
ObjectMeta metadata = entity.getMetadata();
if (metadata != null) {
String resourceVersion = metadata.getResourceVersion();
if (StringUtils.isNotBlank(resourceVersion)) {
return resourceVersion; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public ServletContext getServletContext() {
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletContext();
} } | public class class_name {
public ServletContext getServletContext() {
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletContext(); // depends on control dependency: [if], data = [none]
} } |
public class class_name {
@Override
public Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {
if(!isMultiple()) {
return new Iterator<IPAddressSeqRange>() {
IPAddressSeqRange orig = IPAddressSeqRange.this;
@Override
public boolean hasNext() {
return orig != null;
}
@Override
public IPAddressSeqRange next() {
if(orig == null) {
throw new NoSuchElementException();
}
IPAddressSeqRange result = orig;
orig = null;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
return new Iterator<IPAddressSeqRange>() {
Iterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);
private boolean first = true;
@Override
public boolean hasNext() {
return prefixBlockIterator.hasNext();
}
@Override
public IPAddressSeqRange next() {
IPAddress next = prefixBlockIterator.next();
if(first) {
first = false;
// next is a prefix block
IPAddress lower = getLower();
if(hasNext()) {
if(!lower.includesZeroHost(prefixLength)) {
return create(lower, next.getUpper());
}
} else {
IPAddress upper = getUpper();
if(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {
return create(lower, upper);
}
}
} else if(!hasNext()) {
IPAddress upper = getUpper();
if(!upper.includesMaxHost(prefixLength)) {
return create(next.getLower(), upper);
}
}
return next.toSequentialRange();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} } | public class class_name {
@Override
public Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {
if(!isMultiple()) {
return new Iterator<IPAddressSeqRange>() {
IPAddressSeqRange orig = IPAddressSeqRange.this;
@Override
public boolean hasNext() {
return orig != null;
}
@Override
public IPAddressSeqRange next() {
if(orig == null) {
throw new NoSuchElementException();
}
IPAddressSeqRange result = orig;
orig = null;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}; // depends on control dependency: [if], data = [none]
}
return new Iterator<IPAddressSeqRange>() {
Iterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);
private boolean first = true;
@Override
public boolean hasNext() {
return prefixBlockIterator.hasNext();
}
@Override
public IPAddressSeqRange next() {
IPAddress next = prefixBlockIterator.next();
if(first) {
first = false; // depends on control dependency: [if], data = [none]
// next is a prefix block
IPAddress lower = getLower();
if(hasNext()) {
if(!lower.includesZeroHost(prefixLength)) {
return create(lower, next.getUpper()); // depends on control dependency: [if], data = [none]
}
} else {
IPAddress upper = getUpper();
if(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {
return create(lower, upper); // depends on control dependency: [if], data = [none]
}
}
} else if(!hasNext()) {
IPAddress upper = getUpper();
if(!upper.includesMaxHost(prefixLength)) {
return create(next.getLower(), upper); // depends on control dependency: [if], data = [none]
}
}
return next.toSequentialRange();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} } |
public class class_name {
public String buildCurrentPermissions() {
StringBuffer result = new StringBuffer(
dialogToggleStart(
key(Messages.GUI_PERMISSION_USER_0),
"userpermissions",
getSettings().getUserSettings().getDialogExpandUserPermissions()));
result.append(dialogWhiteBoxStart());
try {
result.append(buildPermissionEntryForm(
getSettings().getUser().getId(),
buildPermissionsForCurrentUser(),
false,
false));
} catch (CmsException e) {
// should never happen
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
}
result.append(dialogWhiteBoxEnd());
result.append("</div>\n");
return result.toString();
} } | public class class_name {
public String buildCurrentPermissions() {
StringBuffer result = new StringBuffer(
dialogToggleStart(
key(Messages.GUI_PERMISSION_USER_0),
"userpermissions",
getSettings().getUserSettings().getDialogExpandUserPermissions()));
result.append(dialogWhiteBoxStart());
try {
result.append(buildPermissionEntryForm(
getSettings().getUser().getId(),
buildPermissionsForCurrentUser(),
false,
false)); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// should never happen
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
result.append(dialogWhiteBoxEnd());
result.append("</div>\n");
return result.toString();
} } |
public class class_name {
public void computeNonEdgeForces(int pointIndex, double theta, INDArray negativeForce, AtomicDouble sumQ) {
// Make sure that we spend no time on empty nodes or self-interactions
if (cumSize == 0 || (isLeaf() && size == 1 && index[0] == pointIndex))
return;
// Compute distance between point and center-of-mass
buf.assign(data.slice(pointIndex)).subi(centerOfMass);
double D = Nd4j.getBlasWrapper().dot(buf, buf);
// Check whether we can use this node as a "summary"
if (isLeaf || FastMath.max(boundary.getHh(), boundary.getHw()) / FastMath.sqrt(D) < theta) {
// Compute and add t-SNE force between point and current node
double Q = 1.0 / (1.0 + D);
double mult = cumSize * Q;
sumQ.addAndGet(mult);
mult *= Q;
negativeForce.addi(buf.mul(mult));
} else {
// Recursively apply Barnes-Hut to children
northWest.computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ);
northEast.computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ);
southWest.computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ);
southEast.computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ);
}
} } | public class class_name {
public void computeNonEdgeForces(int pointIndex, double theta, INDArray negativeForce, AtomicDouble sumQ) {
// Make sure that we spend no time on empty nodes or self-interactions
if (cumSize == 0 || (isLeaf() && size == 1 && index[0] == pointIndex))
return;
// Compute distance between point and center-of-mass
buf.assign(data.slice(pointIndex)).subi(centerOfMass);
double D = Nd4j.getBlasWrapper().dot(buf, buf);
// Check whether we can use this node as a "summary"
if (isLeaf || FastMath.max(boundary.getHh(), boundary.getHw()) / FastMath.sqrt(D) < theta) {
// Compute and add t-SNE force between point and current node
double Q = 1.0 / (1.0 + D);
double mult = cumSize * Q;
sumQ.addAndGet(mult); // depends on control dependency: [if], data = [none]
mult *= Q; // depends on control dependency: [if], data = [none]
negativeForce.addi(buf.mul(mult)); // depends on control dependency: [if], data = [none]
} else {
// Recursively apply Barnes-Hut to children
northWest.computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ); // depends on control dependency: [if], data = [none]
northEast.computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ); // depends on control dependency: [if], data = [none]
southWest.computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ); // depends on control dependency: [if], data = [none]
southEast.computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void startRecording(String line, DispatchCallback callback) {
OutputFile outputFile = sqlLine.getRecordOutputFile();
if (outputFile != null) {
callback.setToFailure();
sqlLine.error(sqlLine.loc("record-already-running", outputFile));
return;
}
String filename;
if (line.length() == "record".length()
|| (filename =
sqlLine.dequote(line.substring("record".length() + 1))) == null) {
sqlLine.error("Usage: record <file name>");
callback.setToFailure();
return;
}
try {
outputFile = new OutputFile(expand(filename));
sqlLine.setRecordOutputFile(outputFile);
sqlLine.output(sqlLine.loc("record-started", outputFile));
callback.setToSuccess();
} catch (Exception e) {
callback.setToFailure();
sqlLine.error(e);
}
} } | public class class_name {
private void startRecording(String line, DispatchCallback callback) {
OutputFile outputFile = sqlLine.getRecordOutputFile();
if (outputFile != null) {
callback.setToFailure(); // depends on control dependency: [if], data = [none]
sqlLine.error(sqlLine.loc("record-already-running", outputFile)); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
String filename;
if (line.length() == "record".length()
|| (filename =
sqlLine.dequote(line.substring("record".length() + 1))) == null) {
sqlLine.error("Usage: record <file name>"); // depends on control dependency: [if], data = [none]
callback.setToFailure(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
try {
outputFile = new OutputFile(expand(filename)); // depends on control dependency: [try], data = [none]
sqlLine.setRecordOutputFile(outputFile); // depends on control dependency: [try], data = [none]
sqlLine.output(sqlLine.loc("record-started", outputFile)); // depends on control dependency: [try], data = [none]
callback.setToSuccess(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
callback.setToFailure();
sqlLine.error(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static List<MainType> getMainTypesBySize(final int typeSize)
{
final List<MainType> l = new ArrayList<>();
for (final Iterator<MainType> i = map.values().iterator(); i.hasNext();) {
final MainType type = i.next();
try {
final String dptId = type.getSubTypes().keySet().iterator().next();
final int size = type.createTranslator(dptId).getTypeSize();
if (size == typeSize)
l.add(type);
}
catch (final KNXException e) {}
}
return l;
} } | public class class_name {
public static List<MainType> getMainTypesBySize(final int typeSize)
{
final List<MainType> l = new ArrayList<>();
for (final Iterator<MainType> i = map.values().iterator(); i.hasNext();) {
final MainType type = i.next();
try {
final String dptId = type.getSubTypes().keySet().iterator().next();
final int size = type.createTranslator(dptId).getTypeSize();
if (size == typeSize)
l.add(type);
}
catch (final KNXException e) {} // depends on control dependency: [catch], data = [none]
}
return l;
} } |
public class class_name {
public void mouseDragged(MouseEvent e)
{
if (pressed)
{
int deltaY = e.getYOnScreen() - lastY;
lastY = e.getYOnScreen();
int deltaX = e.getXOnScreen() - lastX;
lastX = e.getXOnScreen();
boolean revalidate = false;
if (deltaY != 0)
{
resizeable.deltaY(-deltaY);
revalidate = true;
}
if (deltaX != 0)
{
resizeable.deltaX(-deltaX);
revalidate = true;
}
if (revalidate)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
gripComponent.getParent().revalidate();
}
});
}
}
} } | public class class_name {
public void mouseDragged(MouseEvent e)
{
if (pressed)
{
int deltaY = e.getYOnScreen() - lastY;
lastY = e.getYOnScreen(); // depends on control dependency: [if], data = [none]
int deltaX = e.getXOnScreen() - lastX;
lastX = e.getXOnScreen(); // depends on control dependency: [if], data = [none]
boolean revalidate = false;
if (deltaY != 0)
{
resizeable.deltaY(-deltaY); // depends on control dependency: [if], data = [none]
revalidate = true; // depends on control dependency: [if], data = [none]
}
if (deltaX != 0)
{
resizeable.deltaX(-deltaX); // depends on control dependency: [if], data = [none]
revalidate = true; // depends on control dependency: [if], data = [none]
}
if (revalidate)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
gripComponent.getParent().revalidate();
}
}); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static boolean isInstance(Object obj, String interfaceClazzName) {
for (Class<?> clazz = obj.getClass(); clazz != null
&& !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> itf : interfaces) {
if (itf.getName().equals(interfaceClazzName)) {
return true;
}
}
}
return false;
} } | public class class_name {
public static boolean isInstance(Object obj, String interfaceClazzName) {
for (Class<?> clazz = obj.getClass(); clazz != null
&& !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> itf : interfaces) {
if (itf.getName().equals(interfaceClazzName)) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
private void closeFreshSelectConnections(Connection lastSelectConnect,
List<Connection> serviceOffConnections)
throws InterruptedException {
if (null != lastSelectConnect) {
if (lastSelectConnect.isInvokeFutureMapFinish()) {
serviceOffConnections.add(lastSelectConnect);
} else {
Thread.sleep(RETRY_DETECT_PERIOD);
if (lastSelectConnect.isInvokeFutureMapFinish()) {
serviceOffConnections.add(lastSelectConnect);
} else {
if (logger.isInfoEnabled()) {
logger.info("Address={} won't close at this schedule turn",
RemotingUtil.parseRemoteAddress(lastSelectConnect.getChannel()));
}
}
}
}
} } | public class class_name {
private void closeFreshSelectConnections(Connection lastSelectConnect,
List<Connection> serviceOffConnections)
throws InterruptedException {
if (null != lastSelectConnect) {
if (lastSelectConnect.isInvokeFutureMapFinish()) {
serviceOffConnections.add(lastSelectConnect); // depends on control dependency: [if], data = [none]
} else {
Thread.sleep(RETRY_DETECT_PERIOD); // depends on control dependency: [if], data = [none]
if (lastSelectConnect.isInvokeFutureMapFinish()) {
serviceOffConnections.add(lastSelectConnect); // depends on control dependency: [if], data = [none]
} else {
if (logger.isInfoEnabled()) {
logger.info("Address={} won't close at this schedule turn",
RemotingUtil.parseRemoteAddress(lastSelectConnect.getChannel())); // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
public synchronized void closeConnection( int code, String message, boolean remote ) {
if( readyState == ReadyState.CLOSED ) {
return;
}
//Methods like eot() call this method without calling onClose(). Due to that reason we have to adjust the ReadyState manually
if( readyState == ReadyState.OPEN ) {
if( code == CloseFrame.ABNORMAL_CLOSE ) {
readyState = ReadyState.CLOSING;
}
}
if( key != null ) {
// key.attach( null ); //see issue #114
key.cancel();
}
if( channel != null ) {
try {
channel.close();
} catch ( IOException e ) {
if( e.getMessage().equals( "Broken pipe" ) ) {
log.trace( "Caught IOException: Broken pipe during closeConnection()", e );
} else {
log.error("Exception during channel.close()", e);
wsl.onWebsocketError( this, e );
}
}
}
try {
this.wsl.onWebsocketClose( this, code, message, remote );
} catch ( RuntimeException e ) {
wsl.onWebsocketError( this, e );
}
if( draft != null )
draft.reset();
handshakerequest = null;
readyState = ReadyState.CLOSED;
} } | public class class_name {
public synchronized void closeConnection( int code, String message, boolean remote ) {
if( readyState == ReadyState.CLOSED ) {
return; // depends on control dependency: [if], data = [none]
}
//Methods like eot() call this method without calling onClose(). Due to that reason we have to adjust the ReadyState manually
if( readyState == ReadyState.OPEN ) {
if( code == CloseFrame.ABNORMAL_CLOSE ) {
readyState = ReadyState.CLOSING; // depends on control dependency: [if], data = [none]
}
}
if( key != null ) {
// key.attach( null ); //see issue #114
key.cancel(); // depends on control dependency: [if], data = [none]
}
if( channel != null ) {
try {
channel.close(); // depends on control dependency: [try], data = [none]
} catch ( IOException e ) {
if( e.getMessage().equals( "Broken pipe" ) ) {
log.trace( "Caught IOException: Broken pipe during closeConnection()", e ); // depends on control dependency: [if], data = [none]
} else {
log.error("Exception during channel.close()", e); // depends on control dependency: [if], data = [none]
wsl.onWebsocketError( this, e ); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
try {
this.wsl.onWebsocketClose( this, code, message, remote ); // depends on control dependency: [try], data = [none]
} catch ( RuntimeException e ) {
wsl.onWebsocketError( this, e );
} // depends on control dependency: [catch], data = [none]
if( draft != null )
draft.reset();
handshakerequest = null;
readyState = ReadyState.CLOSED;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.