code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public String[] getContext(CharSequence sb, int position) {
/**
* String preceding the eos character in the eos token.
*/
String prefix;
/**
* Space delimited token preceding token containing eos character.
*/
String previous;
/**
* String following the eos character in the eos token.
*/
String suffix;
/**
* Space delimited token following token containing eos character.
*/
String next;
int lastIndex = sb.length() - 1;
{ // compute space previous and space next features.
if (position > 0 && StringUtil.isWhitespace(sb.charAt(position - 1)))
collectFeats.add("sp");
if (position < lastIndex
&& StringUtil.isWhitespace(sb.charAt(position + 1)))
collectFeats.add("sn");
collectFeats.add("eos=" + sb.charAt(position));
}
int prefixStart = previousSpaceIndex(sb, position);
int c = position;
{ // /assign prefix, stop if you run into a period though otherwise stop at
// space
while (--c > prefixStart) {
for (int eci = 0, ecl = eosCharacters.length; eci < ecl; eci++) {
if (sb.charAt(c) == eosCharacters[eci]) {
prefixStart = c;
c++; // this gets us out of while loop.
break;
}
}
}
prefix = new StringBuffer(sb.subSequence(prefixStart, position))
.toString().trim();
}
int prevStart = previousSpaceIndex(sb, prefixStart);
previous = new StringBuffer(sb.subSequence(prevStart, prefixStart))
.toString().trim();
int suffixEnd = nextSpaceIndex(sb, position, lastIndex);
{
c = position;
while (++c < suffixEnd) {
for (int eci = 0, ecl = eosCharacters.length; eci < ecl; eci++) {
if (sb.charAt(c) == eosCharacters[eci]) {
suffixEnd = c;
c--; // this gets us out of while loop.
break;
}
}
}
}
int nextEnd = nextSpaceIndex(sb, suffixEnd + 1, lastIndex + 1);
if (position == lastIndex) {
suffix = "";
next = "";
} else {
suffix = new StringBuilder(sb.subSequence(position + 1, suffixEnd))
.toString().trim();
next = new StringBuilder(sb.subSequence(suffixEnd + 1, nextEnd))
.toString().trim();
}
collectFeatures(prefix, suffix, previous, next, sb.charAt(position));
int sentEnd = Math.max(position + 1, suffixEnd);
collectFeats.addAll(getSentenceContext(sb.subSequence(prefixStart, sentEnd)
.toString(), position - prefixStart));
String[] context = new String[collectFeats.size()];
context = collectFeats.toArray(context);
collectFeats.clear();
return context;
} } | public class class_name {
public String[] getContext(CharSequence sb, int position) {
/**
* String preceding the eos character in the eos token.
*/
String prefix;
/**
* Space delimited token preceding token containing eos character.
*/
String previous;
/**
* String following the eos character in the eos token.
*/
String suffix;
/**
* Space delimited token following token containing eos character.
*/
String next;
int lastIndex = sb.length() - 1;
{ // compute space previous and space next features.
if (position > 0 && StringUtil.isWhitespace(sb.charAt(position - 1)))
collectFeats.add("sp");
if (position < lastIndex
&& StringUtil.isWhitespace(sb.charAt(position + 1)))
collectFeats.add("sn");
collectFeats.add("eos=" + sb.charAt(position));
}
int prefixStart = previousSpaceIndex(sb, position);
int c = position;
{ // /assign prefix, stop if you run into a period though otherwise stop at
// space
while (--c > prefixStart) {
for (int eci = 0, ecl = eosCharacters.length; eci < ecl; eci++) {
if (sb.charAt(c) == eosCharacters[eci]) {
prefixStart = c; // depends on control dependency: [if], data = [none]
c++; // this gets us out of while loop. // depends on control dependency: [if], data = [none]
break;
}
}
}
prefix = new StringBuffer(sb.subSequence(prefixStart, position))
.toString().trim();
}
int prevStart = previousSpaceIndex(sb, prefixStart);
previous = new StringBuffer(sb.subSequence(prevStart, prefixStart))
.toString().trim();
int suffixEnd = nextSpaceIndex(sb, position, lastIndex);
{
c = position;
while (++c < suffixEnd) {
for (int eci = 0, ecl = eosCharacters.length; eci < ecl; eci++) {
if (sb.charAt(c) == eosCharacters[eci]) {
suffixEnd = c; // depends on control dependency: [if], data = [none]
c--; // this gets us out of while loop. // depends on control dependency: [if], data = [none]
break;
}
}
}
}
int nextEnd = nextSpaceIndex(sb, suffixEnd + 1, lastIndex + 1);
if (position == lastIndex) {
suffix = "";
next = ""; // depends on control dependency: [if], data = [none]
} else {
suffix = new StringBuilder(sb.subSequence(position + 1, suffixEnd))
.toString().trim(); // depends on control dependency: [if], data = [none]
next = new StringBuilder(sb.subSequence(suffixEnd + 1, nextEnd))
.toString().trim(); // depends on control dependency: [if], data = [none]
}
collectFeatures(prefix, suffix, previous, next, sb.charAt(position));
int sentEnd = Math.max(position + 1, suffixEnd);
collectFeats.addAll(getSentenceContext(sb.subSequence(prefixStart, sentEnd)
.toString(), position - prefixStart));
String[] context = new String[collectFeats.size()];
context = collectFeats.toArray(context);
collectFeats.clear();
return context;
} } |
public class class_name {
public SessionHandle openSession(TProtocolVersion protocol, String username, String password, String ipAddress,
Map<String, String> sessionConf, boolean withImpersonation, String delegationToken)
throws HiveSQLException {
HiveSession session;
// If doAs is set to true for HiveServer2, we will create a proxy object for the session impl.
// Within the proxy object, we wrap the method call in a UserGroupInformation#doAs
if (withImpersonation) {
HiveSessionImplwithUGI sessionWithUGI = new HiveSessionImplwithUGI(protocol, username, password,
hiveConf, ipAddress, delegationToken);
session = HiveSessionProxy.getProxy(sessionWithUGI, sessionWithUGI.getSessionUgi());
sessionWithUGI.setProxySession(session);
} else {
session = new HiveSessionImpl(protocol, username, password, hiveConf, ipAddress);
}
session.setSessionManager(this);
session.setOperationManager(operationManager);
try {
session.open(sessionConf);
} catch (Exception e) {
try {
session.close();
} catch (Throwable t) {
LOG.warn("Error closing session", t);
}
session = null;
throw new HiveSQLException("Failed to open new session: " + e, e);
}
if (isOperationLogEnabled) {
session.setOperationLogSessionDir(operationLogRootDir);
}
handleToSession.put(session.getSessionHandle(), session);
return session.getSessionHandle();
} } | public class class_name {
public SessionHandle openSession(TProtocolVersion protocol, String username, String password, String ipAddress,
Map<String, String> sessionConf, boolean withImpersonation, String delegationToken)
throws HiveSQLException {
HiveSession session;
// If doAs is set to true for HiveServer2, we will create a proxy object for the session impl.
// Within the proxy object, we wrap the method call in a UserGroupInformation#doAs
if (withImpersonation) {
HiveSessionImplwithUGI sessionWithUGI = new HiveSessionImplwithUGI(protocol, username, password,
hiveConf, ipAddress, delegationToken);
session = HiveSessionProxy.getProxy(sessionWithUGI, sessionWithUGI.getSessionUgi());
sessionWithUGI.setProxySession(session);
} else {
session = new HiveSessionImpl(protocol, username, password, hiveConf, ipAddress);
}
session.setSessionManager(this);
session.setOperationManager(operationManager);
try {
session.open(sessionConf);
} catch (Exception e) {
try {
session.close(); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
LOG.warn("Error closing session", t);
} // depends on control dependency: [catch], data = [none]
session = null;
throw new HiveSQLException("Failed to open new session: " + e, e);
}
if (isOperationLogEnabled) {
session.setOperationLogSessionDir(operationLogRootDir);
}
handleToSession.put(session.getSessionHandle(), session);
return session.getSessionHandle();
} } |
public class class_name {
private static String getDocumentName(final DocumentStatusContainer document) {
if ("prop".equalsIgnoreCase(document.getDocument().getDocumentType())) {
return "Proposition";
} else if (document.getDocument().getSubType() != null && document.getDocument().getSubType().length() > "motion".length()) {
return document.getDocument().getSubType();
} else {
return "Motion";
}
} } | public class class_name {
private static String getDocumentName(final DocumentStatusContainer document) {
if ("prop".equalsIgnoreCase(document.getDocument().getDocumentType())) {
return "Proposition"; // depends on control dependency: [if], data = [none]
} else if (document.getDocument().getSubType() != null && document.getDocument().getSubType().length() > "motion".length()) {
return document.getDocument().getSubType(); // depends on control dependency: [if], data = [none]
} else {
return "Motion"; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Parser<Void> isChar(final CharPredicate predicate) {
return new Parser<Void>() {
final String name = predicate.toString();
@Override boolean apply(ParseContext ctxt) {
if (ctxt.isEof()) {
ctxt.missing(name);
return false;
}
char c = ctxt.peekChar();
if (predicate.isChar(c)) {
ctxt.next();
ctxt.result = null;
return true;
}
ctxt.missing(name);
return false;
}
@Override public String toString() {
return name;
}
};
} } | public class class_name {
public static Parser<Void> isChar(final CharPredicate predicate) {
return new Parser<Void>() {
final String name = predicate.toString();
@Override boolean apply(ParseContext ctxt) {
if (ctxt.isEof()) {
ctxt.missing(name); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
char c = ctxt.peekChar();
if (predicate.isChar(c)) {
ctxt.next(); // depends on control dependency: [if], data = [none]
ctxt.result = null; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
ctxt.missing(name);
return false;
}
@Override public String toString() {
return name;
}
};
} } |
public class class_name {
public void prepareParameter(Map<String, Object> extra) {
if (from != null)
{
from.prepareParameter(extra);
}
} } | public class class_name {
public void prepareParameter(Map<String, Object> extra) {
if (from != null)
{
from.prepareParameter(extra); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void disposeAllOperators() {
if (operatorChain != null) {
for (StreamOperator<?> operator : operatorChain.getAllOperators()) {
try {
if (operator != null) {
operator.dispose();
}
}
catch (Throwable t) {
LOG.error("Error during disposal of stream operator.", t);
}
}
}
} } | public class class_name {
private void disposeAllOperators() {
if (operatorChain != null) {
for (StreamOperator<?> operator : operatorChain.getAllOperators()) {
try {
if (operator != null) {
operator.dispose(); // depends on control dependency: [if], data = [none]
}
}
catch (Throwable t) {
LOG.error("Error during disposal of stream operator.", t);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
protected static void log(Level level, Object message, Throwable throwable, Object... args) {
Message payload = payload(message, args, throwable);
payload.getFormattedMessage(); // preformat message (cached), so formating has processed and added fields to MetaContext
if (MetaContext.hasMeta()) {
// serialize metacontext map to json, which is put into a designated threadcontext field
ThreadContext.put(JSON_FIELD, MetaContext.toJson());
MetaContext.clear();
}
determineLogger().log(level, payload, payload.getThrowable());
if (ThreadContext.getContext() != null && ThreadContext.containsKey(JSON_FIELD)) {
ThreadContext.remove(JSON_FIELD);
}
} } | public class class_name {
protected static void log(Level level, Object message, Throwable throwable, Object... args) {
Message payload = payload(message, args, throwable);
payload.getFormattedMessage(); // preformat message (cached), so formating has processed and added fields to MetaContext
if (MetaContext.hasMeta()) {
// serialize metacontext map to json, which is put into a designated threadcontext field
ThreadContext.put(JSON_FIELD, MetaContext.toJson()); // depends on control dependency: [if], data = [none]
MetaContext.clear(); // depends on control dependency: [if], data = [none]
}
determineLogger().log(level, payload, payload.getThrowable());
if (ThreadContext.getContext() != null && ThreadContext.containsKey(JSON_FIELD)) {
ThreadContext.remove(JSON_FIELD); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected List<Map<URI, List<AttributeValue>>> getSubjects(SOAPMessageContext context) {
// setup the id and value for the requesting subject
List<Map<URI, List<AttributeValue>>> subjects =
new ArrayList<Map<URI, List<AttributeValue>>>();
if (getUser(context) == null
|| getUser(context).trim().isEmpty()) {
return subjects;
}
String[] fedoraRole = getUserRoles(context);
Map<URI, List<AttributeValue>> subAttr = null;
List<AttributeValue> attrList = null;
subAttr = new HashMap<URI, List<AttributeValue>>();
attrList = new ArrayList<AttributeValue>();
attrList.add(new StringAttribute(getUser(context)));
subAttr.put(Constants.SUBJECT.LOGIN_ID.getURI(), attrList);
if (fedoraRole != null && fedoraRole.length > 0) {
attrList = new ArrayList<AttributeValue>();
for (String r : fedoraRole) {
attrList.add(new StringAttribute(r));
}
subAttr.put(Constants.SUBJECT.ROLE.getURI(), attrList);
}
subjects.add(subAttr);
subAttr = new HashMap<URI, List<AttributeValue>>();
attrList = new ArrayList<AttributeValue>();
attrList.add(new StringAttribute(getUser(context)));
subAttr.put(Constants.SUBJECT.USER_REPRESENTED.getURI(), attrList);
if (fedoraRole != null && fedoraRole.length > 0) {
attrList = new ArrayList<AttributeValue>();
for (String r : fedoraRole) {
attrList.add(new StringAttribute(r));
}
subAttr.put(Constants.SUBJECT.ROLE.getURI(), attrList);
}
subjects.add(subAttr);
subAttr = new HashMap<URI, List<AttributeValue>>();
attrList = new ArrayList<AttributeValue>();
attrList.add(new StringAttribute(getUser(context)));
subAttr.put(Constants.XACML1_SUBJECT.ID.getURI(), attrList);
if (fedoraRole != null && fedoraRole.length > 0) {
attrList = new ArrayList<AttributeValue>();
for (String r : fedoraRole) {
attrList.add(new StringAttribute(r));
}
subAttr.put(Constants.SUBJECT.ROLE.getURI(), attrList);
}
subjects.add(subAttr);
return subjects;
} } | public class class_name {
protected List<Map<URI, List<AttributeValue>>> getSubjects(SOAPMessageContext context) {
// setup the id and value for the requesting subject
List<Map<URI, List<AttributeValue>>> subjects =
new ArrayList<Map<URI, List<AttributeValue>>>();
if (getUser(context) == null
|| getUser(context).trim().isEmpty()) {
return subjects; // depends on control dependency: [if], data = [none]
}
String[] fedoraRole = getUserRoles(context);
Map<URI, List<AttributeValue>> subAttr = null;
List<AttributeValue> attrList = null;
subAttr = new HashMap<URI, List<AttributeValue>>();
attrList = new ArrayList<AttributeValue>();
attrList.add(new StringAttribute(getUser(context)));
subAttr.put(Constants.SUBJECT.LOGIN_ID.getURI(), attrList);
if (fedoraRole != null && fedoraRole.length > 0) {
attrList = new ArrayList<AttributeValue>(); // depends on control dependency: [if], data = [none]
for (String r : fedoraRole) {
attrList.add(new StringAttribute(r)); // depends on control dependency: [for], data = [r]
}
subAttr.put(Constants.SUBJECT.ROLE.getURI(), attrList); // depends on control dependency: [if], data = [none]
}
subjects.add(subAttr);
subAttr = new HashMap<URI, List<AttributeValue>>();
attrList = new ArrayList<AttributeValue>();
attrList.add(new StringAttribute(getUser(context)));
subAttr.put(Constants.SUBJECT.USER_REPRESENTED.getURI(), attrList);
if (fedoraRole != null && fedoraRole.length > 0) {
attrList = new ArrayList<AttributeValue>(); // depends on control dependency: [if], data = [none]
for (String r : fedoraRole) {
attrList.add(new StringAttribute(r)); // depends on control dependency: [for], data = [r]
}
subAttr.put(Constants.SUBJECT.ROLE.getURI(), attrList); // depends on control dependency: [if], data = [none]
}
subjects.add(subAttr);
subAttr = new HashMap<URI, List<AttributeValue>>();
attrList = new ArrayList<AttributeValue>();
attrList.add(new StringAttribute(getUser(context)));
subAttr.put(Constants.XACML1_SUBJECT.ID.getURI(), attrList);
if (fedoraRole != null && fedoraRole.length > 0) {
attrList = new ArrayList<AttributeValue>(); // depends on control dependency: [if], data = [none]
for (String r : fedoraRole) {
attrList.add(new StringAttribute(r)); // depends on control dependency: [for], data = [r]
}
subAttr.put(Constants.SUBJECT.ROLE.getURI(), attrList); // depends on control dependency: [if], data = [none]
}
subjects.add(subAttr);
return subjects;
} } |
public class class_name {
private int order(String value1, String value2) {
int result = -1;
if (value1 == value2) {
result = 0;
} else if (value1 != null) {
if (value2 != null) {
result = value1.compareTo(value2);
} else {
result = 1;
}
} else {
result = -1;
}
return result;
} } | public class class_name {
private int order(String value1, String value2) {
int result = -1;
if (value1 == value2) {
result = 0; // depends on control dependency: [if], data = [none]
} else if (value1 != null) {
if (value2 != null) {
result = value1.compareTo(value2); // depends on control dependency: [if], data = [(value2]
} else {
result = 1; // depends on control dependency: [if], data = [none]
}
} else {
result = -1; // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public long[] toPrimitiveArray(long[] array) {
for (int i = 0, j = 0; i < array.length; ++i) {
int index = -1;
if (j < indices.length && (index = indices[j]) == i) {
array[i] = values[j];
j++;
}
else
array[i] = 0;
}
return array;
} } | public class class_name {
public long[] toPrimitiveArray(long[] array) {
for (int i = 0, j = 0; i < array.length; ++i) {
int index = -1;
if (j < indices.length && (index = indices[j]) == i) {
array[i] = values[j]; // depends on control dependency: [if], data = [none]
j++; // depends on control dependency: [if], data = [none]
}
else
array[i] = 0;
}
return array;
} } |
public class class_name {
public String[] getReportSamples() {
final Map<String, String> sampleValues = new HashMap<>();
sampleValues.put("name1", "Secure Transpiler Mars");
sampleValues.put("version1", "4.7.0");
sampleValues.put("name2", "Secure Transpiler Bounty");
sampleValues.put("version2", "5.0.0");
sampleValues.put("license", "CDDL-1.1");
sampleValues.put("name", "Secure Pretender");
sampleValues.put("version", "2.7.0");
sampleValues.put("organization", "Axway");
return ReportsRegistry.allReports()
.stream()
.map(report -> ReportUtils.generateSampleRequest(report, sampleValues))
.map(request -> {
try {
String desc = "";
final Optional<Report> byId = ReportsRegistry.findById(request.getReportId());
if(byId.isPresent()) {
desc = byId.get().getDescription() + "<br/><br/>";
}
return String.format(TWO_PLACES, desc, JsonUtils.serialize(request));
} catch(IOException e) {
return "Error " + e.getMessage();
}
})
.collect(Collectors.toList())
.toArray(new String[] {});
} } | public class class_name {
public String[] getReportSamples() {
final Map<String, String> sampleValues = new HashMap<>();
sampleValues.put("name1", "Secure Transpiler Mars");
sampleValues.put("version1", "4.7.0");
sampleValues.put("name2", "Secure Transpiler Bounty");
sampleValues.put("version2", "5.0.0");
sampleValues.put("license", "CDDL-1.1");
sampleValues.put("name", "Secure Pretender");
sampleValues.put("version", "2.7.0");
sampleValues.put("organization", "Axway");
return ReportsRegistry.allReports()
.stream()
.map(report -> ReportUtils.generateSampleRequest(report, sampleValues))
.map(request -> {
try {
String desc = "";
final Optional<Report> byId = ReportsRegistry.findById(request.getReportId());
if(byId.isPresent()) {
desc = byId.get().getDescription() + "<br/><br/>"; // depends on control dependency: [if], data = [none]
}
return String.format(TWO_PLACES, desc, JsonUtils.serialize(request));
} catch(IOException e) {
return "Error " + e.getMessage();
}
})
.collect(Collectors.toList())
.toArray(new String[] {});
} } |
public class class_name {
public void statistics(Statistic stats) {
if(stats != null) {
log(Level.STATISTICS, stats.getKey() + ": " + stats.formatValue());
}
} } | public class class_name {
public void statistics(Statistic stats) {
if(stats != null) {
log(Level.STATISTICS, stats.getKey() + ": " + stats.formatValue()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static int getNumberCode(int length) {//-2147483648~2147483647
if(length > 9)
new Exception("The number is too big");
Random random = new Random();
StringBuffer max = new StringBuffer().append("8");
StringBuffer min = new StringBuffer().append("1");
while (max.length() <= length - 1) {
max.append("9");
min.append("0");
}
int maxNumber = Integer.parseInt(max.toString());
int minNumber = Integer.parseInt(min.toString());
return random.nextInt(maxNumber) + minNumber;
} } | public class class_name {
public static int getNumberCode(int length) {//-2147483648~2147483647
if(length > 9)
new Exception("The number is too big");
Random random = new Random();
StringBuffer max = new StringBuffer().append("8");
StringBuffer min = new StringBuffer().append("1");
while (max.length() <= length - 1) {
max.append("9"); // depends on control dependency: [while], data = [none]
min.append("0"); // depends on control dependency: [while], data = [none]
}
int maxNumber = Integer.parseInt(max.toString());
int minNumber = Integer.parseInt(min.toString());
return random.nextInt(maxNumber) + minNumber;
} } |
public class class_name {
public static PCollection<Read> getReadsFromBAMFilesSharded(
Pipeline p,
PipelineOptions pipelineOptions,
OfflineAuth auth,
final List<Contig> contigs,
ReaderOptions options,
String bamFileListOrGlob,
final ShardingPolicy shardingPolicy) throws IOException, URISyntaxException {
ReadBAMTransform readBAMSTransform = new ReadBAMTransform(options);
readBAMSTransform.setAuth(auth);
List<String> prefixes = null;
File f = new File(bamFileListOrGlob);
if (f.exists() && !f.isDirectory()) {
String fileContents = Files.toString(f, Charset.defaultCharset());
prefixes = ImmutableSet
.<String>builder()
.addAll(
Splitter.on(CharMatcher.breakingWhitespace()).omitEmptyStrings().trimResults()
.split(fileContents))
.build().asList();
} else {
prefixes = ImmutableSet
.<String>builder()
.add(bamFileListOrGlob)
.build()
.asList();
}
Set<String> uris = new HashSet<>();
GcsUtil gcsUtil = pipelineOptions.as(GcsOptions.class).getGcsUtil();
for (String prefix : prefixes) {
URI absoluteUri = new URI(prefix);
URI gcsUriGlob = new URI(
absoluteUri.getScheme(),
absoluteUri.getAuthority(),
absoluteUri.getPath() + "*",
absoluteUri.getQuery(),
absoluteUri.getFragment());
for (GcsPath entry : gcsUtil.expand(GcsPath.fromUri(gcsUriGlob))) {
// Even if provided with an exact match to a particular BAM file, the glob operation will
// still look for any files with that prefix, therefore also finding the corresponding
// .bai file. Ensure only BAMs are added to the list.
if (entry.toString().endsWith(BAMIO.BAM_FILE_SUFFIX)) {
uris.add(entry.toString());
}
}
}
// Perform all sharding and reading in a distributed fashion, using the BreakFusion
// transforms to ensure that work is auto-scalable based on the number of shards.
return p
.apply(Create.of(uris))
.apply("Break BAM file fusion", new BreakFusionTransform<String>())
.apply("BamsToShards", ParDo.of(new DoFn<String, BAMShard>() {
Storage.Objects storage;
@StartBundle
public void startBundle(DoFn<String, BAMShard>.StartBundleContext c) throws IOException {
storage = Transport.newStorageClient(c.getPipelineOptions().as(GCSOptions.class)).build().objects();
}
@DoFn.ProcessElement
public void processElement(DoFn<String, BAMShard>.ProcessContext c) {
List<BAMShard> shardsList = null;
try {
shardsList = Sharder.shardBAMFile(storage, c.element(), contigs, shardingPolicy);
LOG.info("Sharding BAM " + c.element());
Metrics.counter(ReadBAMTransform.class, "BAM files").inc();
Metrics.counter(ReadBAMTransform.class, "BAM file shards").inc(shardsList.size());
} catch (IOException e) {
throw new RuntimeException(e);
}
for (BAMShard shard : shardsList) {
c.output(shard);
}
}
}))
// We need a BreakFusionTransform here but BAMShard does not have a deterministic coder, a
// requirement for values that are keys. Send it as a value instead.
.apply("Break BAMShard fusion - group", ParDo.of(new DoFn<BAMShard, KV<String, BAMShard>>() {
@DoFn.ProcessElement
public void processElement(DoFn<BAMShard, KV<String, BAMShard>>.ProcessContext c) throws Exception {
c.output(KV.of(c.element().toString(), c.element()));
}
}))
.apply("Break BAMShard fusion - shuffle", GroupByKey.<String, BAMShard>create())
.apply("Break BAMShard fusion - ungroup", ParDo.of(new DoFn<KV<String, Iterable<BAMShard>>, BAMShard>() {
@DoFn.ProcessElement
public void processElement(DoFn<KV<String, Iterable<BAMShard>>, BAMShard>.ProcessContext c) {
for (BAMShard shard : c.element().getValue()) {
c.output(shard);
}
}
}))
.apply(readBAMSTransform);
} } | public class class_name {
public static PCollection<Read> getReadsFromBAMFilesSharded(
Pipeline p,
PipelineOptions pipelineOptions,
OfflineAuth auth,
final List<Contig> contigs,
ReaderOptions options,
String bamFileListOrGlob,
final ShardingPolicy shardingPolicy) throws IOException, URISyntaxException {
ReadBAMTransform readBAMSTransform = new ReadBAMTransform(options);
readBAMSTransform.setAuth(auth);
List<String> prefixes = null;
File f = new File(bamFileListOrGlob);
if (f.exists() && !f.isDirectory()) {
String fileContents = Files.toString(f, Charset.defaultCharset());
prefixes = ImmutableSet
.<String>builder()
.addAll(
Splitter.on(CharMatcher.breakingWhitespace()).omitEmptyStrings().trimResults()
.split(fileContents))
.build().asList();
} else {
prefixes = ImmutableSet
.<String>builder()
.add(bamFileListOrGlob)
.build()
.asList();
}
Set<String> uris = new HashSet<>();
GcsUtil gcsUtil = pipelineOptions.as(GcsOptions.class).getGcsUtil();
for (String prefix : prefixes) {
URI absoluteUri = new URI(prefix);
URI gcsUriGlob = new URI(
absoluteUri.getScheme(),
absoluteUri.getAuthority(),
absoluteUri.getPath() + "*",
absoluteUri.getQuery(),
absoluteUri.getFragment());
for (GcsPath entry : gcsUtil.expand(GcsPath.fromUri(gcsUriGlob))) {
// Even if provided with an exact match to a particular BAM file, the glob operation will
// still look for any files with that prefix, therefore also finding the corresponding
// .bai file. Ensure only BAMs are added to the list.
if (entry.toString().endsWith(BAMIO.BAM_FILE_SUFFIX)) {
uris.add(entry.toString()); // depends on control dependency: [if], data = [none]
}
}
}
// Perform all sharding and reading in a distributed fashion, using the BreakFusion
// transforms to ensure that work is auto-scalable based on the number of shards.
return p
.apply(Create.of(uris))
.apply("Break BAM file fusion", new BreakFusionTransform<String>())
.apply("BamsToShards", ParDo.of(new DoFn<String, BAMShard>() {
Storage.Objects storage;
@StartBundle
public void startBundle(DoFn<String, BAMShard>.StartBundleContext c) throws IOException {
storage = Transport.newStorageClient(c.getPipelineOptions().as(GCSOptions.class)).build().objects();
}
@DoFn.ProcessElement
public void processElement(DoFn<String, BAMShard>.ProcessContext c) {
List<BAMShard> shardsList = null;
try {
shardsList = Sharder.shardBAMFile(storage, c.element(), contigs, shardingPolicy); // depends on control dependency: [try], data = [none]
LOG.info("Sharding BAM " + c.element()); // depends on control dependency: [try], data = [none]
Metrics.counter(ReadBAMTransform.class, "BAM files").inc(); // depends on control dependency: [try], data = [none]
Metrics.counter(ReadBAMTransform.class, "BAM file shards").inc(shardsList.size()); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
for (BAMShard shard : shardsList) {
c.output(shard); // depends on control dependency: [for], data = [shard]
}
}
}))
// We need a BreakFusionTransform here but BAMShard does not have a deterministic coder, a
// requirement for values that are keys. Send it as a value instead.
.apply("Break BAMShard fusion - group", ParDo.of(new DoFn<BAMShard, KV<String, BAMShard>>() {
@DoFn.ProcessElement
public void processElement(DoFn<BAMShard, KV<String, BAMShard>>.ProcessContext c) throws Exception {
c.output(KV.of(c.element().toString(), c.element()));
}
}))
.apply("Break BAMShard fusion - shuffle", GroupByKey.<String, BAMShard>create())
.apply("Break BAMShard fusion - ungroup", ParDo.of(new DoFn<KV<String, Iterable<BAMShard>>, BAMShard>() {
@DoFn.ProcessElement
public void processElement(DoFn<KV<String, Iterable<BAMShard>>, BAMShard>.ProcessContext c) {
for (BAMShard shard : c.element().getValue()) {
c.output(shard);
}
}
}))
.apply(readBAMSTransform);
} } |
public class class_name {
@SuppressWarnings({ "unchecked", "rawtypes" })
public Table aggregate(ListMultimap<String, AggregateFunction<?,?>> functions) {
Preconditions.checkArgument(!getSlices().isEmpty());
Table groupTable = summaryTableName(sourceTable);
StringColumn groupColumn = StringColumn.create("Group");
groupTable.addColumns(groupColumn);
for (Map.Entry<String, Collection<AggregateFunction<?,?>>> entry : functions.asMap().entrySet()) {
String columnName = entry.getKey();
int functionCount = 0;
for (AggregateFunction function : entry.getValue()) {
String colName = aggregateColumnName(columnName, function.functionName());
ColumnType type = function.returnType();
Column resultColumn = type.create(colName);
for (TableSlice subTable : getSlices()) {
Object result = function.summarize(subTable.column(columnName));
if (functionCount == 0) {
groupColumn.append(subTable.name());
}
if (result instanceof Number) {
Number number = (Number) result;
resultColumn.append(number.doubleValue());
} else {
resultColumn.append(result);
}
}
groupTable.addColumns(resultColumn);
functionCount++;
}
}
return splitGroupingColumn(groupTable);
} } | public class class_name {
@SuppressWarnings({ "unchecked", "rawtypes" })
public Table aggregate(ListMultimap<String, AggregateFunction<?,?>> functions) {
Preconditions.checkArgument(!getSlices().isEmpty());
Table groupTable = summaryTableName(sourceTable);
StringColumn groupColumn = StringColumn.create("Group");
groupTable.addColumns(groupColumn);
for (Map.Entry<String, Collection<AggregateFunction<?,?>>> entry : functions.asMap().entrySet()) {
String columnName = entry.getKey();
int functionCount = 0;
for (AggregateFunction function : entry.getValue()) {
String colName = aggregateColumnName(columnName, function.functionName());
ColumnType type = function.returnType();
Column resultColumn = type.create(colName);
for (TableSlice subTable : getSlices()) {
Object result = function.summarize(subTable.column(columnName));
if (functionCount == 0) {
groupColumn.append(subTable.name()); // depends on control dependency: [if], data = [none]
}
if (result instanceof Number) {
Number number = (Number) result;
resultColumn.append(number.doubleValue()); // depends on control dependency: [if], data = [none]
} else {
resultColumn.append(result); // depends on control dependency: [if], data = [none]
}
}
groupTable.addColumns(resultColumn);
functionCount++;
}
}
return splitGroupingColumn(groupTable);
} } |
public class class_name {
public static boolean isEquals(final double x, final double y, final int maxUlps) {
final long xInt = Double.doubleToRawLongBits(x);
final long yInt = Double.doubleToRawLongBits(y);
final boolean isEqual;
if (((xInt ^ yInt) & SGN_MASK) == 0L) {
// number have same sign, there is no risk of overflow
isEqual = Math.abs(xInt - yInt) <= maxUlps;
} else {
// number have opposite signs, take care of overflow
final long deltaPlus;
final long deltaMinus;
if (xInt < yInt) {
deltaPlus = yInt - POSITIVE_ZERO_DOUBLE_BITS;
deltaMinus = xInt - NEGATIVE_ZERO_DOUBLE_BITS;
} else {
deltaPlus = xInt - POSITIVE_ZERO_DOUBLE_BITS;
deltaMinus = yInt - NEGATIVE_ZERO_DOUBLE_BITS;
}
if (deltaPlus > maxUlps) {
isEqual = false;
} else {
isEqual = deltaMinus <= (maxUlps - deltaPlus);
}
}
return isEqual && !Double.isNaN(x) && !Double.isNaN(y);
} } | public class class_name {
public static boolean isEquals(final double x, final double y, final int maxUlps) {
final long xInt = Double.doubleToRawLongBits(x);
final long yInt = Double.doubleToRawLongBits(y);
final boolean isEqual;
if (((xInt ^ yInt) & SGN_MASK) == 0L) {
// number have same sign, there is no risk of overflow
isEqual = Math.abs(xInt - yInt) <= maxUlps; // depends on control dependency: [if], data = [none]
} else {
// number have opposite signs, take care of overflow
final long deltaPlus;
final long deltaMinus;
if (xInt < yInt) {
deltaPlus = yInt - POSITIVE_ZERO_DOUBLE_BITS; // depends on control dependency: [if], data = [none]
deltaMinus = xInt - NEGATIVE_ZERO_DOUBLE_BITS; // depends on control dependency: [if], data = [none]
} else {
deltaPlus = xInt - POSITIVE_ZERO_DOUBLE_BITS; // depends on control dependency: [if], data = [none]
deltaMinus = yInt - NEGATIVE_ZERO_DOUBLE_BITS; // depends on control dependency: [if], data = [none]
}
if (deltaPlus > maxUlps) {
isEqual = false; // depends on control dependency: [if], data = [none]
} else {
isEqual = deltaMinus <= (maxUlps - deltaPlus); // depends on control dependency: [if], data = [none]
}
}
return isEqual && !Double.isNaN(x) && !Double.isNaN(y);
} } |
public class class_name {
@Override
int guessFluffedSize() {
// Get the contribution from the superclass(es)
int total = super.guessFluffedSize();
// Add the basic additional size for being a JMS message.
total += FLUFFED_JMS_BASE_SIZE;
// If there is a body in the message.....
if (jmo.getPayloadPart().getChoiceField(JsPayloadAccess.PAYLOAD) != JsPayloadAccess.IS_PAYLOAD_EMPTY) {
// Add in the extra overhead for having a fluffed body
total += FLUFFED_PAYLOAD_BASE_SIZE;
// And call the method to get the size of the fluffed data
total += guessFluffedDataSize();
}
return total;
} } | public class class_name {
@Override
int guessFluffedSize() {
// Get the contribution from the superclass(es)
int total = super.guessFluffedSize();
// Add the basic additional size for being a JMS message.
total += FLUFFED_JMS_BASE_SIZE;
// If there is a body in the message.....
if (jmo.getPayloadPart().getChoiceField(JsPayloadAccess.PAYLOAD) != JsPayloadAccess.IS_PAYLOAD_EMPTY) {
// Add in the extra overhead for having a fluffed body
total += FLUFFED_PAYLOAD_BASE_SIZE; // depends on control dependency: [if], data = [none]
// And call the method to get the size of the fluffed data
total += guessFluffedDataSize(); // depends on control dependency: [if], data = [none]
}
return total;
} } |
public class class_name {
private List<String> getHeaderValues(String name) {
List<String> values = headers.get(name);
if (values == null) {
values = new ArrayList<String>();
headers.put(name, values);
}
return values;
} } | public class class_name {
private List<String> getHeaderValues(String name) {
List<String> values = headers.get(name);
if (values == null) {
values = new ArrayList<String>(); // depends on control dependency: [if], data = [none]
headers.put(name, values); // depends on control dependency: [if], data = [none]
}
return values;
} } |
public class class_name {
public void marshall(UpdateOriginEndpointRequest updateOriginEndpointRequest, ProtocolMarshaller protocolMarshaller) {
if (updateOriginEndpointRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateOriginEndpointRequest.getCmafPackage(), CMAFPACKAGE_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getDashPackage(), DASHPACKAGE_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getHlsPackage(), HLSPACKAGE_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getId(), ID_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getManifestName(), MANIFESTNAME_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getMssPackage(), MSSPACKAGE_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getStartoverWindowSeconds(), STARTOVERWINDOWSECONDS_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getTimeDelaySeconds(), TIMEDELAYSECONDS_BINDING);
protocolMarshaller.marshall(updateOriginEndpointRequest.getWhitelist(), WHITELIST_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UpdateOriginEndpointRequest updateOriginEndpointRequest, ProtocolMarshaller protocolMarshaller) {
if (updateOriginEndpointRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateOriginEndpointRequest.getCmafPackage(), CMAFPACKAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getDashPackage(), DASHPACKAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getHlsPackage(), HLSPACKAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getId(), ID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getManifestName(), MANIFESTNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getMssPackage(), MSSPACKAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getStartoverWindowSeconds(), STARTOVERWINDOWSECONDS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getTimeDelaySeconds(), TIMEDELAYSECONDS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateOriginEndpointRequest.getWhitelist(), WHITELIST_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 JScoreElement getScoreElementAt(Point location) {
JScoreElement scoreEl = null;
for (int i=0; i<m_staffLines.size(); i++) {
scoreEl = ((JStaffLine)m_staffLines.elementAt(i)).getScoreElementAt(location);
if (scoreEl!=null)
return scoreEl;
scoreEl = null;
}
return scoreEl;
} } | public class class_name {
public JScoreElement getScoreElementAt(Point location) {
JScoreElement scoreEl = null;
for (int i=0; i<m_staffLines.size(); i++) {
scoreEl = ((JStaffLine)m_staffLines.elementAt(i)).getScoreElementAt(location);
// depends on control dependency: [for], data = [i]
if (scoreEl!=null)
return scoreEl;
scoreEl = null;
// depends on control dependency: [for], data = [none]
}
return scoreEl;
} } |
public class class_name {
public static Deferred<Leaf> parseFromStorage(final TSDB tsdb,
final KeyValue column, final boolean load_uids) {
if (column.value() == null) {
throw new IllegalArgumentException("Leaf column value was null");
}
// qualifier has the TSUID in the format "leaf:<display_name.hashCode()>"
// and we should only be here if the qualifier matched on "leaf:"
final Leaf leaf = JSON.parseToObject(column.value(), Leaf.class);
// if there was an error with the data and the tsuid is missing, dump it
if (leaf.tsuid == null || leaf.tsuid.isEmpty()) {
LOG.warn("Invalid leaf object in row: " + Branch.idToString(column.key()));
return Deferred.fromResult(null);
}
// if we don't need to load UIDs, then return now
if (!load_uids) {
return Deferred.fromResult(leaf);
}
// split the TSUID to get the tags
final List<byte[]> parsed_tags = UniqueId.getTagsFromTSUID(leaf.tsuid);
// initialize the with empty objects, otherwise the "set" operations in
// the callback won't work.
final ArrayList<String> tags = new ArrayList<String>(parsed_tags.size());
for (int i = 0; i < parsed_tags.size(); i++) {
tags.add("");
}
// setup an array of deferreds to wait on so we can return the leaf only
// after all of the name fetches have completed
final ArrayList<Deferred<Object>> uid_group =
new ArrayList<Deferred<Object>>(parsed_tags.size() + 1);
/**
* Callback executed after the UID name has been retrieved successfully.
* The {@code index} determines where the result is stored: -1 means metric,
* >= 0 means tag
*/
final class UIDNameCB implements Callback<Object, String> {
final int index;
public UIDNameCB(final int index) {
this.index = index;
}
@Override
public Object call(final String name) throws Exception {
if (index < 0) {
leaf.metric = name;
} else {
tags.set(index, name);
}
return null;
}
}
// fetch the metric name first
final byte[] metric_uid = UniqueId.stringToUid(
leaf.tsuid.substring(0, TSDB.metrics_width() * 2));
uid_group.add(tsdb.getUidName(UniqueIdType.METRIC, metric_uid).addCallback(
new UIDNameCB(-1)));
int idx = 0;
for (byte[] tag : parsed_tags) {
if (idx % 2 == 0) {
uid_group.add(tsdb.getUidName(UniqueIdType.TAGK, tag)
.addCallback(new UIDNameCB(idx)));
} else {
uid_group.add(tsdb.getUidName(UniqueIdType.TAGV, tag)
.addCallback(new UIDNameCB(idx)));
}
idx++;
}
/**
* Called after all of the UID name fetches have completed and parses the
* tag name/value list into name/value pairs for proper display
*/
final class CollateUIDsCB implements Callback<Deferred<Leaf>,
ArrayList<Object>> {
/**
* @return A valid Leaf object loaded with UID names
*/
@Override
public Deferred<Leaf> call(final ArrayList<Object> name_calls)
throws Exception {
int idx = 0;
String tagk = "";
leaf.tags = new HashMap<String, String>(tags.size() / 2);
for (String name : tags) {
if (idx % 2 == 0) {
tagk = name;
} else {
leaf.tags.put(tagk, name);
}
idx++;
}
return Deferred.fromResult(leaf);
}
}
// wait for all of the UID name fetches in the group to complete before
// returning the leaf
return Deferred.group(uid_group).addCallbackDeferring(new CollateUIDsCB());
} } | public class class_name {
public static Deferred<Leaf> parseFromStorage(final TSDB tsdb,
final KeyValue column, final boolean load_uids) {
if (column.value() == null) {
throw new IllegalArgumentException("Leaf column value was null");
}
// qualifier has the TSUID in the format "leaf:<display_name.hashCode()>"
// and we should only be here if the qualifier matched on "leaf:"
final Leaf leaf = JSON.parseToObject(column.value(), Leaf.class);
// if there was an error with the data and the tsuid is missing, dump it
if (leaf.tsuid == null || leaf.tsuid.isEmpty()) {
LOG.warn("Invalid leaf object in row: " + Branch.idToString(column.key())); // depends on control dependency: [if], data = [none]
return Deferred.fromResult(null); // depends on control dependency: [if], data = [none]
}
// if we don't need to load UIDs, then return now
if (!load_uids) {
return Deferred.fromResult(leaf); // depends on control dependency: [if], data = [none]
}
// split the TSUID to get the tags
final List<byte[]> parsed_tags = UniqueId.getTagsFromTSUID(leaf.tsuid);
// initialize the with empty objects, otherwise the "set" operations in
// the callback won't work.
final ArrayList<String> tags = new ArrayList<String>(parsed_tags.size());
for (int i = 0; i < parsed_tags.size(); i++) {
tags.add(""); // depends on control dependency: [for], data = [none]
}
// setup an array of deferreds to wait on so we can return the leaf only
// after all of the name fetches have completed
final ArrayList<Deferred<Object>> uid_group =
new ArrayList<Deferred<Object>>(parsed_tags.size() + 1);
/**
* Callback executed after the UID name has been retrieved successfully.
* The {@code index} determines where the result is stored: -1 means metric,
* >= 0 means tag
*/
final class UIDNameCB implements Callback<Object, String> {
final int index;
public UIDNameCB(final int index) {
this.index = index;
}
@Override
public Object call(final String name) throws Exception {
if (index < 0) {
leaf.metric = name;
} else {
tags.set(index, name);
}
return null;
}
}
// fetch the metric name first
final byte[] metric_uid = UniqueId.stringToUid(
leaf.tsuid.substring(0, TSDB.metrics_width() * 2));
uid_group.add(tsdb.getUidName(UniqueIdType.METRIC, metric_uid).addCallback(
new UIDNameCB(-1)));
int idx = 0;
for (byte[] tag : parsed_tags) {
if (idx % 2 == 0) {
uid_group.add(tsdb.getUidName(UniqueIdType.TAGK, tag)
.addCallback(new UIDNameCB(idx)));
} else {
uid_group.add(tsdb.getUidName(UniqueIdType.TAGV, tag)
.addCallback(new UIDNameCB(idx)));
}
idx++;
}
/**
* Called after all of the UID name fetches have completed and parses the
* tag name/value list into name/value pairs for proper display
*/
final class CollateUIDsCB implements Callback<Deferred<Leaf>,
ArrayList<Object>> {
/**
* @return A valid Leaf object loaded with UID names
*/
@Override
public Deferred<Leaf> call(final ArrayList<Object> name_calls)
throws Exception {
int idx = 0;
String tagk = "";
leaf.tags = new HashMap<String, String>(tags.size() / 2);
for (String name : tags) {
if (idx % 2 == 0) {
tagk = name; // depends on control dependency: [if], data = [none]
} else {
leaf.tags.put(tagk, name); // depends on control dependency: [if], data = [none]
}
idx++;
}
return Deferred.fromResult(leaf);
}
}
// wait for all of the UID name fetches in the group to complete before
// returning the leaf
return Deferred.group(uid_group).addCallbackDeferring(new CollateUIDsCB());
} } |
public class class_name {
@Bench(runs = RUNS, beforeEachRun = "arrayListAdd")
public void arrayListGet() {
for (int i = 0; i < list.size(); i++) {
arrayList.get(i);
}
} } | public class class_name {
@Bench(runs = RUNS, beforeEachRun = "arrayListAdd")
public void arrayListGet() {
for (int i = 0; i < list.size(); i++) {
arrayList.get(i); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
static boolean isFieldUnitIgnored(String pattern, int field) {
int fieldLevel = CALENDAR_FIELD_TO_LEVEL[field];
int level;
char ch;
boolean inQuote = false;
char prevCh = 0;
int count = 0;
for (int i = 0; i < pattern.length(); ++i) {
ch = pattern.charAt(i);
if (ch != prevCh && count > 0) {
level = getLevelFromChar(prevCh);
if (fieldLevel <= level) {
return false;
}
count = 0;
}
if (ch == '\'') {
if ((i+1) < pattern.length() && pattern.charAt(i+1) == '\'') {
++i;
} else {
inQuote = ! inQuote;
}
} else if (!inQuote && isSyntaxChar(ch)) {
prevCh = ch;
++count;
}
}
if (count > 0) {
// last item
level = getLevelFromChar(prevCh);
if (fieldLevel <= level) {
return false;
}
}
return true;
} } | public class class_name {
static boolean isFieldUnitIgnored(String pattern, int field) {
int fieldLevel = CALENDAR_FIELD_TO_LEVEL[field];
int level;
char ch;
boolean inQuote = false;
char prevCh = 0;
int count = 0;
for (int i = 0; i < pattern.length(); ++i) {
ch = pattern.charAt(i); // depends on control dependency: [for], data = [i]
if (ch != prevCh && count > 0) {
level = getLevelFromChar(prevCh); // depends on control dependency: [if], data = [none]
if (fieldLevel <= level) {
return false; // depends on control dependency: [if], data = [none]
}
count = 0; // depends on control dependency: [if], data = [none]
}
if (ch == '\'') {
if ((i+1) < pattern.length() && pattern.charAt(i+1) == '\'') {
++i; // depends on control dependency: [if], data = [none]
} else {
inQuote = ! inQuote; // depends on control dependency: [if], data = [none]
}
} else if (!inQuote && isSyntaxChar(ch)) {
prevCh = ch; // depends on control dependency: [if], data = [none]
++count; // depends on control dependency: [if], data = [none]
}
}
if (count > 0) {
// last item
level = getLevelFromChar(prevCh); // depends on control dependency: [if], data = [none]
if (fieldLevel <= level) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
private int[] getColumnList(OrderedHashSet set, Table table) {
if (set == null) {
return null;
}
return table.getColumnIndexes(set);
} } | public class class_name {
private int[] getColumnList(OrderedHashSet set, Table table) {
if (set == null) {
return null; // depends on control dependency: [if], data = [none]
}
return table.getColumnIndexes(set);
} } |
public class class_name {
@Override
public void runIsolatedAsynch(boolean deliverImmediately) throws SIIncorrectCallException, SISessionUnavailableException, SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "runIsolatedAsynch", new Object[] { this, Boolean.valueOf(deliverImmediately) });
synchronized (_asynchConsumerBusyLock)
{
// Lock the consumer session while we check that it is in a valid
// state
this.lock();
try
{
// Only valid if the consumer session is still open
checkNotClosed();
//if there is no callback registered, throw an exception
if (!_asynchConsumerRegistered)
{
SIIncorrectCallException e =
new SIIncorrectCallException(
nls.getFormattedMessage(
"ASYNCH_CONSUMER_ERROR_CWSIP0175",
new Object[] { _consumerDispatcher.getDestination().getName(),
_messageProcessor.getMessagingEngineName() },
null));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", e);
throw e;
}
// we can't do an isolated run if the LCP is not in a stopped state
// so throw an exception
if (!_stopped)
{
SIIncorrectCallException e =
new SIIncorrectCallException(
nls.getFormattedMessage(
"ASYNCH_CONSUMER_RUN_ERROR_CWSIP0176",
new Object[] { _consumerDispatcher.getDestination().getName(),
_consumerDispatcher.getMessageProcessor().getMessagingEngineName() },
null));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", e);
throw e;
}
// If the consumer has been stopped because the destination is not
// allowing consumers to get messages then we simply return.
if (_stoppedForReceiveAllowed)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", "Receive not allowed");
return;
}
} // synchronized (this)
finally
{
this.unlock();
}
} // synchronized (asynchConsumer)
//if we get this far then if deliverImmediately is set then this
//implies that the callback should be inline
if (deliverImmediately)
{
//run the asynch inline
try
{
runAsynchConsumer(true);
} catch (Throwable e)
{
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.JSLocalConsumerPoint.runIsolatedAsynch",
"1:3182:1.22.5.1",
this);
SibTr.exception(tc, e);
try
{
// Since the asynchConsumer has experienced an error of some kind, the best form
// of cleanup is to close down the session. This ensures any listeners get notified
// and can retry at some point later.
_consumerSession.close();
// don't notify asynchconsumer as we are been called inline
} catch (Exception ee)
{
// No FFDC code needed
SibTr.exception(tc, ee);
}
if (e instanceof ThreadDeath)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", e);
throw (ThreadDeath) e;
}
SISessionDroppedException sessionDroppedException = new SISessionDroppedException(
nls.getFormattedMessage("CONSUMER_CLOSED_ERROR_CWSIP0177"
, new Object[] { _consumerDispatcher.getDestination().getName(),
_messageProcessor.getMessagingEngineName() }
, null), e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", sessionDroppedException);
//inline call so throwing exception rather than notifying
throw sessionDroppedException;
}
}
else
{
//start up a new thread (from the MP's thread pool)
//to deliver the message asynchronously
try
{
_messageProcessor.startNewThread(new AsynchThread(this, true));
} catch (InterruptedException e)
{
// No FFDC code needed
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "runIsolatedAsynch", e);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch");
} } | public class class_name {
@Override
public void runIsolatedAsynch(boolean deliverImmediately) throws SIIncorrectCallException, SISessionUnavailableException, SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "runIsolatedAsynch", new Object[] { this, Boolean.valueOf(deliverImmediately) });
synchronized (_asynchConsumerBusyLock)
{
// Lock the consumer session while we check that it is in a valid
// state
this.lock();
try
{
// Only valid if the consumer session is still open
checkNotClosed(); // depends on control dependency: [try], data = [none]
//if there is no callback registered, throw an exception
if (!_asynchConsumerRegistered)
{
SIIncorrectCallException e =
new SIIncorrectCallException(
nls.getFormattedMessage(
"ASYNCH_CONSUMER_ERROR_CWSIP0175",
new Object[] { _consumerDispatcher.getDestination().getName(),
_messageProcessor.getMessagingEngineName() },
null));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", e);
throw e;
}
// we can't do an isolated run if the LCP is not in a stopped state
// so throw an exception
if (!_stopped)
{
SIIncorrectCallException e =
new SIIncorrectCallException(
nls.getFormattedMessage(
"ASYNCH_CONSUMER_RUN_ERROR_CWSIP0176",
new Object[] { _consumerDispatcher.getDestination().getName(),
_consumerDispatcher.getMessageProcessor().getMessagingEngineName() },
null));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", e);
throw e;
}
// If the consumer has been stopped because the destination is not
// allowing consumers to get messages then we simply return.
if (_stoppedForReceiveAllowed)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", "Receive not allowed");
return; // depends on control dependency: [if], data = [none]
}
} // synchronized (this)
finally
{
this.unlock();
}
} // synchronized (asynchConsumer)
//if we get this far then if deliverImmediately is set then this
//implies that the callback should be inline
if (deliverImmediately)
{
//run the asynch inline
try
{
runAsynchConsumer(true); // depends on control dependency: [try], data = [none]
} catch (Throwable e)
{
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.JSLocalConsumerPoint.runIsolatedAsynch",
"1:3182:1.22.5.1",
this);
SibTr.exception(tc, e);
try
{
// Since the asynchConsumer has experienced an error of some kind, the best form
// of cleanup is to close down the session. This ensures any listeners get notified
// and can retry at some point later.
_consumerSession.close(); // depends on control dependency: [try], data = [none]
// don't notify asynchconsumer as we are been called inline
} catch (Exception ee)
{
// No FFDC code needed
SibTr.exception(tc, ee);
} // depends on control dependency: [catch], data = [none]
if (e instanceof ThreadDeath)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", e);
throw (ThreadDeath) e;
}
SISessionDroppedException sessionDroppedException = new SISessionDroppedException(
nls.getFormattedMessage("CONSUMER_CLOSED_ERROR_CWSIP0177"
, new Object[] { _consumerDispatcher.getDestination().getName(),
_messageProcessor.getMessagingEngineName() }
, null), e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch", sessionDroppedException);
//inline call so throwing exception rather than notifying
throw sessionDroppedException;
} // depends on control dependency: [catch], data = [none]
}
else
{
//start up a new thread (from the MP's thread pool)
//to deliver the message asynchronously
try
{
_messageProcessor.startNewThread(new AsynchThread(this, true)); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e)
{
// No FFDC code needed
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "runIsolatedAsynch", e);
} // depends on control dependency: [catch], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "runIsolatedAsynch");
} } |
public class class_name {
public AssociationOverride<Entity<T>> getOrCreateAssociationOverride()
{
List<Node> nodeList = childNode.get("association-override");
if (nodeList != null && nodeList.size() > 0)
{
return new AssociationOverrideImpl<Entity<T>>(this, "association-override", childNode, nodeList.get(0));
}
return createAssociationOverride();
} } | public class class_name {
public AssociationOverride<Entity<T>> getOrCreateAssociationOverride()
{
List<Node> nodeList = childNode.get("association-override");
if (nodeList != null && nodeList.size() > 0)
{
return new AssociationOverrideImpl<Entity<T>>(this, "association-override", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createAssociationOverride();
} } |
public class class_name {
public void stop() {
Collection<List<DefaultPageMounter>> values;
synchronized (mountPointRegistrations) {
values = new ArrayList<List<DefaultPageMounter>>(mountPointRegistrations.values());
mountPointRegistrations.clear();
}
for (List<DefaultPageMounter> bundleMounters : values) {
for (DefaultPageMounter pageMounter : bundleMounters) {
pageMounter.dispose();
}
}
} } | public class class_name {
public void stop() {
Collection<List<DefaultPageMounter>> values;
synchronized (mountPointRegistrations) {
values = new ArrayList<List<DefaultPageMounter>>(mountPointRegistrations.values());
mountPointRegistrations.clear();
}
for (List<DefaultPageMounter> bundleMounters : values) {
for (DefaultPageMounter pageMounter : bundleMounters) {
pageMounter.dispose(); // depends on control dependency: [for], data = [pageMounter]
}
}
} } |
public class class_name {
public void listen(MFPPushNotificationListener notificationListener) {
if (!onMessageReceiverRegistered) {
appContext.registerReceiver(onMessage, new IntentFilter(
getIntentPrefix(appContext) + GCM_MESSAGE));
onMessageReceiverRegistered = true;
this.notificationListener = notificationListener;
setAppForeground(true);
boolean gotSavedMessages;
if (pushNotificationIntent != null) {
gotSavedMessages = getMessagesFromSharedPreferences(pushNotificationIntent.getIntExtra("notificationId", 0));
pushNotificationIntent = null;
} else {
gotSavedMessages = getMessagesFromSharedPreferences(0);
}
if (!isFromNotificationBar) {
if (gotSavedMessages) {
dispatchPending();
}
cancelAllNotification();
} else {
if (messageFromBar != null) {
isFromNotificationBar = false;
sendNotificationToListener(messageFromBar);
cancelNotification(messageFromBar);
messageFromBar = null;
}
}
} else {
logger.info("MFPPush:listen() - onMessage broadcast listener has already been registered.");
}
} } | public class class_name {
public void listen(MFPPushNotificationListener notificationListener) {
if (!onMessageReceiverRegistered) {
appContext.registerReceiver(onMessage, new IntentFilter(
getIntentPrefix(appContext) + GCM_MESSAGE)); // depends on control dependency: [if], data = [none]
onMessageReceiverRegistered = true; // depends on control dependency: [if], data = [none]
this.notificationListener = notificationListener; // depends on control dependency: [if], data = [none]
setAppForeground(true); // depends on control dependency: [if], data = [none]
boolean gotSavedMessages;
if (pushNotificationIntent != null) {
gotSavedMessages = getMessagesFromSharedPreferences(pushNotificationIntent.getIntExtra("notificationId", 0)); // depends on control dependency: [if], data = [(pushNotificationIntent]
pushNotificationIntent = null; // depends on control dependency: [if], data = [none]
} else {
gotSavedMessages = getMessagesFromSharedPreferences(0); // depends on control dependency: [if], data = [none]
}
if (!isFromNotificationBar) {
if (gotSavedMessages) {
dispatchPending(); // depends on control dependency: [if], data = [none]
}
cancelAllNotification(); // depends on control dependency: [if], data = [none]
} else {
if (messageFromBar != null) {
isFromNotificationBar = false; // depends on control dependency: [if], data = [none]
sendNotificationToListener(messageFromBar); // depends on control dependency: [if], data = [(messageFromBar]
cancelNotification(messageFromBar); // depends on control dependency: [if], data = [(messageFromBar]
messageFromBar = null; // depends on control dependency: [if], data = [none]
}
}
} else {
logger.info("MFPPush:listen() - onMessage broadcast listener has already been registered."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public DynaFormRow createExtendedRow() {
if (extendedRows == null) {
extendedRows = new ArrayList<DynaFormRow>();
}
final DynaFormRow dynaFormRow = new DynaFormRow(extendedRows.size() + 1, true, this);
extendedRows.add(dynaFormRow);
return dynaFormRow;
} } | public class class_name {
public DynaFormRow createExtendedRow() {
if (extendedRows == null) {
extendedRows = new ArrayList<DynaFormRow>(); // depends on control dependency: [if], data = [none]
}
final DynaFormRow dynaFormRow = new DynaFormRow(extendedRows.size() + 1, true, this);
extendedRows.add(dynaFormRow);
return dynaFormRow;
} } |
public class class_name {
private List<Node> addComplexObserverReflectionCalls(final PolymerClassDefinition cls) {
List<Node> propertySinkStatements = new ArrayList<>();
Node classMembers = NodeUtil.getClassMembers(cls.definition);
Node getter = NodeUtil.getFirstGetterMatchingKey(classMembers, "observers");
if (getter != null) {
Node complexObservers = null;
for (Node child : NodeUtil.getFunctionBody(getter.getFirstChild()).children()) {
if (child.isReturn()) {
if (child.hasChildren() && child.getFirstChild().isArrayLit()) {
complexObservers = child.getFirstChild();
break;
}
}
}
if (complexObservers != null) {
for (Node complexObserver : complexObservers.children()) {
if (complexObserver.isString()) {
propertySinkStatements.addAll(
replaceMethodStringWithReflectedCalls(cls.target, complexObserver));
}
}
}
}
return propertySinkStatements;
} } | public class class_name {
private List<Node> addComplexObserverReflectionCalls(final PolymerClassDefinition cls) {
List<Node> propertySinkStatements = new ArrayList<>();
Node classMembers = NodeUtil.getClassMembers(cls.definition);
Node getter = NodeUtil.getFirstGetterMatchingKey(classMembers, "observers");
if (getter != null) {
Node complexObservers = null;
for (Node child : NodeUtil.getFunctionBody(getter.getFirstChild()).children()) {
if (child.isReturn()) {
if (child.hasChildren() && child.getFirstChild().isArrayLit()) {
complexObservers = child.getFirstChild(); // depends on control dependency: [if], data = [none]
break;
}
}
}
if (complexObservers != null) {
for (Node complexObserver : complexObservers.children()) {
if (complexObserver.isString()) {
propertySinkStatements.addAll(
replaceMethodStringWithReflectedCalls(cls.target, complexObserver)); // depends on control dependency: [if], data = [none]
}
}
}
}
return propertySinkStatements;
} } |
public class class_name {
protected void addAllClassLoaderJarRoots(ClassLoader classLoader, Set<Resource> result) {
if (classLoader instanceof URLClassLoader) {
try {
for (URL url : ((URLClassLoader) classLoader).getURLs()) {
if (ResourceUtils.isJarFileURL(url)) {
try {
UrlResource jarResource = new UrlResource(
ResourceUtils.JAR_URL_PREFIX + url.toString() + ResourceUtils.JAR_URL_SEPARATOR);
if (jarResource.exists()) {
result.add(jarResource);
}
}
catch (MalformedURLException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Cannot search for matching files underneath [" + url +
"] because it cannot be converted to a valid 'jar:' URL: " + ex.getMessage());
}
}
}
}
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("Cannot introspect jar files since ClassLoader [" + classLoader +
"] does not support 'getURLs()': " + ex);
}
}
}
if (classLoader != null) {
try {
addAllClassLoaderJarRoots(classLoader.getParent(), result);
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("Cannot introspect jar files in parent ClassLoader since [" + classLoader +
"] does not support 'getParent()': " + ex);
}
}
}
} } | public class class_name {
protected void addAllClassLoaderJarRoots(ClassLoader classLoader, Set<Resource> result) {
if (classLoader instanceof URLClassLoader) {
try {
for (URL url : ((URLClassLoader) classLoader).getURLs()) {
if (ResourceUtils.isJarFileURL(url)) {
try {
UrlResource jarResource = new UrlResource(
ResourceUtils.JAR_URL_PREFIX + url.toString() + ResourceUtils.JAR_URL_SEPARATOR);
if (jarResource.exists()) {
result.add(jarResource); // depends on control dependency: [if], data = [none]
}
}
catch (MalformedURLException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Cannot search for matching files underneath [" + url +
"] because it cannot be converted to a valid 'jar:' URL: " + ex.getMessage()); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
}
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("Cannot introspect jar files since ClassLoader [" + classLoader +
"] does not support 'getURLs()': " + ex); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
if (classLoader != null) {
try {
addAllClassLoaderJarRoots(classLoader.getParent(), result); // depends on control dependency: [try], data = [none]
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("Cannot introspect jar files in parent ClassLoader since [" + classLoader +
"] does not support 'getParent()': " + ex); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@Override
public int compareTo(final DomainSpecificValue other) {
int order = other.ordering - this.ordering;
if (order == 0) {
if (changeSet != null && other.changeSet != null) {
int changeSetCompare = other.changeSet.compareTo(changeSet);
if (changeSetCompare != 0)
return changeSetCompare;
else
return patternStr.compareTo(other.patternStr);
}
if (changeSet != null) { // other.changeSet is null here
return -1;
}
if (other.changeSet != null) { // changeSet is null here
return 1;
}
return patternStr.compareTo(other.patternStr);
}
return order;
} } | public class class_name {
@Override
public int compareTo(final DomainSpecificValue other) {
int order = other.ordering - this.ordering;
if (order == 0) {
if (changeSet != null && other.changeSet != null) {
int changeSetCompare = other.changeSet.compareTo(changeSet);
if (changeSetCompare != 0)
return changeSetCompare;
else
return patternStr.compareTo(other.patternStr);
}
if (changeSet != null) { // other.changeSet is null here
return -1; // depends on control dependency: [if], data = [none]
}
if (other.changeSet != null) { // changeSet is null here
return 1; // depends on control dependency: [if], data = [none]
}
return patternStr.compareTo(other.patternStr); // depends on control dependency: [if], data = [none]
}
return order;
} } |
public class class_name {
private static CompletionStage<?> toCompletionStage(Object obj) {
if (obj instanceof CompletionStage) {
return (CompletionStage<?>) obj;
}
return CompletableFuture.completedFuture(obj);
} } | public class class_name {
private static CompletionStage<?> toCompletionStage(Object obj) {
if (obj instanceof CompletionStage) {
return (CompletionStage<?>) obj; // depends on control dependency: [if], data = [none]
}
return CompletableFuture.completedFuture(obj);
} } |
public class class_name {
private static List<WComponent> copyChildren(final List<WComponent> children) {
ArrayList<WComponent> copy;
if (children == null) {
copy = new ArrayList<>(1);
} else {
copy = new ArrayList<>(children);
}
return copy;
} } | public class class_name {
private static List<WComponent> copyChildren(final List<WComponent> children) {
ArrayList<WComponent> copy;
if (children == null) {
copy = new ArrayList<>(1); // depends on control dependency: [if], data = [none]
} else {
copy = new ArrayList<>(children); // depends on control dependency: [if], data = [(children]
}
return copy;
} } |
public class class_name {
public byte[] toByteArray() {
final byte[] bytes = new byte[getSerializedSizeBytes()];
final boolean isSingleItem = n_ == 1;
bytes[PREAMBLE_INTS_BYTE] = (byte) (isEmpty() || isSingleItem ? PREAMBLE_INTS_SHORT : PREAMBLE_INTS_FULL);
bytes[SER_VER_BYTE] = isSingleItem ? serialVersionUID2 : serialVersionUID1;
bytes[FAMILY_BYTE] = (byte) Family.KLL.getID();
bytes[FLAGS_BYTE] = (byte) (
(isEmpty() ? 1 << Flags.IS_EMPTY.ordinal() : 0)
| (isLevelZeroSorted_ ? 1 << Flags.IS_LEVEL_ZERO_SORTED.ordinal() : 0)
| (isSingleItem ? 1 << Flags.IS_SINGLE_ITEM.ordinal() : 0)
);
ByteArrayUtil.putShortLE(bytes, K_SHORT, (short) k_);
bytes[M_BYTE] = (byte) m_;
if (isEmpty()) { return bytes; }
int offset = DATA_START_SINGLE_ITEM;
if (!isSingleItem) {
ByteArrayUtil.putLongLE(bytes, N_LONG, n_);
ByteArrayUtil.putShortLE(bytes, MIN_K_SHORT, (short) minK_);
bytes[NUM_LEVELS_BYTE] = (byte) numLevels_;
offset = DATA_START;
// the last integer in levels_ is not serialized because it can be derived
for (int i = 0; i < numLevels_; i++) {
ByteArrayUtil.putIntLE(bytes, offset, levels_[i]);
offset += Integer.BYTES;
}
ByteArrayUtil.putFloatLE(bytes, offset, minValue_);
offset += Float.BYTES;
ByteArrayUtil.putFloatLE(bytes, offset, maxValue_);
offset += Float.BYTES;
}
final int numItems = getNumRetained();
for (int i = 0; i < numItems; i++) {
ByteArrayUtil.putFloatLE(bytes, offset, items_[levels_[0] + i]);
offset += Float.BYTES;
}
return bytes;
} } | public class class_name {
public byte[] toByteArray() {
final byte[] bytes = new byte[getSerializedSizeBytes()];
final boolean isSingleItem = n_ == 1;
bytes[PREAMBLE_INTS_BYTE] = (byte) (isEmpty() || isSingleItem ? PREAMBLE_INTS_SHORT : PREAMBLE_INTS_FULL);
bytes[SER_VER_BYTE] = isSingleItem ? serialVersionUID2 : serialVersionUID1;
bytes[FAMILY_BYTE] = (byte) Family.KLL.getID();
bytes[FLAGS_BYTE] = (byte) (
(isEmpty() ? 1 << Flags.IS_EMPTY.ordinal() : 0)
| (isLevelZeroSorted_ ? 1 << Flags.IS_LEVEL_ZERO_SORTED.ordinal() : 0)
| (isSingleItem ? 1 << Flags.IS_SINGLE_ITEM.ordinal() : 0)
);
ByteArrayUtil.putShortLE(bytes, K_SHORT, (short) k_);
bytes[M_BYTE] = (byte) m_;
if (isEmpty()) { return bytes; } // depends on control dependency: [if], data = [none]
int offset = DATA_START_SINGLE_ITEM;
if (!isSingleItem) {
ByteArrayUtil.putLongLE(bytes, N_LONG, n_); // depends on control dependency: [if], data = [none]
ByteArrayUtil.putShortLE(bytes, MIN_K_SHORT, (short) minK_); // depends on control dependency: [if], data = [none]
bytes[NUM_LEVELS_BYTE] = (byte) numLevels_; // depends on control dependency: [if], data = [none]
offset = DATA_START; // depends on control dependency: [if], data = [none]
// the last integer in levels_ is not serialized because it can be derived
for (int i = 0; i < numLevels_; i++) {
ByteArrayUtil.putIntLE(bytes, offset, levels_[i]); // depends on control dependency: [for], data = [i]
offset += Integer.BYTES; // depends on control dependency: [for], data = [none]
}
ByteArrayUtil.putFloatLE(bytes, offset, minValue_); // depends on control dependency: [if], data = [none]
offset += Float.BYTES; // depends on control dependency: [if], data = [none]
ByteArrayUtil.putFloatLE(bytes, offset, maxValue_); // depends on control dependency: [if], data = [none]
offset += Float.BYTES; // depends on control dependency: [if], data = [none]
}
final int numItems = getNumRetained();
for (int i = 0; i < numItems; i++) {
ByteArrayUtil.putFloatLE(bytes, offset, items_[levels_[0] + i]); // depends on control dependency: [for], data = [i]
offset += Float.BYTES; // depends on control dependency: [for], data = [none]
}
return bytes;
} } |
public class class_name {
private static byte[] getByteArray(BufferedImage image) {
checkNotNull(image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", stream);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return stream.toByteArray();
} } | public class class_name {
private static byte[] getByteArray(BufferedImage image) {
checkNotNull(image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", stream); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
return stream.toByteArray();
} } |
public class class_name {
public static String sha1(URL url) {
InputStream is = null;
try {
is = url.openStream();
return sha1(is);
} catch (IOException ioe) {
log.warn("Error occourred while reading from URL: " + url, ioe);
throw new RuntimeIOException(ioe);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ioe) {
log.warn("Failed to close stream for URL: " + url, ioe);
throw new RuntimeIOException(ioe);
}
}
}
} } | public class class_name {
public static String sha1(URL url) {
InputStream is = null;
try {
is = url.openStream(); // depends on control dependency: [try], data = [none]
return sha1(is); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
log.warn("Error occourred while reading from URL: " + url, ioe);
throw new RuntimeIOException(ioe);
} finally { // depends on control dependency: [catch], data = [none]
if (is != null) {
try {
is.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
log.warn("Failed to close stream for URL: " + url, ioe);
throw new RuntimeIOException(ioe);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
public boolean remove( LocalSession localSession , TransactionItem[] items ) throws JMSException
{
checkNotClosed();
checkTransactionLock();
int volatileCommitted = 0;
int persistentCommitted = 0;
synchronized (storeLock)
{
for (int n = 0 ; n < items.length ; n++)
{
TransactionItem transactionItem = items[n];
if (transactionItem.getDestination() != this)
continue;
if (traceEnabled)
log.trace(localSession+" COMMIT "+transactionItem.getMessageId());
// Delete message from store
if (transactionItem.getDeliveryMode() == DeliveryMode.PERSISTENT)
{
persistentStore.delete(transactionItem.getHandle());
persistentCommitted++;
}
else
{
volatileStore.delete(transactionItem.getHandle());
volatileCommitted++;
}
}
}
acknowledgedGetCount.addAndGet(volatileCommitted + persistentCommitted);
if (persistentCommitted > 0 && requiresTransactionalUpdate())
{
pendingChanges = true;
return true;
}
else
return false;
} } | public class class_name {
public boolean remove( LocalSession localSession , TransactionItem[] items ) throws JMSException
{
checkNotClosed();
checkTransactionLock();
int volatileCommitted = 0;
int persistentCommitted = 0;
synchronized (storeLock)
{
for (int n = 0 ; n < items.length ; n++)
{
TransactionItem transactionItem = items[n];
if (transactionItem.getDestination() != this)
continue;
if (traceEnabled)
log.trace(localSession+" COMMIT "+transactionItem.getMessageId());
// Delete message from store
if (transactionItem.getDeliveryMode() == DeliveryMode.PERSISTENT)
{
persistentStore.delete(transactionItem.getHandle()); // depends on control dependency: [if], data = [none]
persistentCommitted++; // depends on control dependency: [if], data = [none]
}
else
{
volatileStore.delete(transactionItem.getHandle()); // depends on control dependency: [if], data = [none]
volatileCommitted++; // depends on control dependency: [if], data = [none]
}
}
}
acknowledgedGetCount.addAndGet(volatileCommitted + persistentCommitted);
if (persistentCommitted > 0 && requiresTransactionalUpdate())
{
pendingChanges = true;
return true;
}
else
return false;
} } |
public class class_name {
private List<Lr0State> lpgAccess(Lr0State state, Item item)
{
Set<Lr0State> result = new NumSet<>();
result.add(state);
for (int i = item.getDot(); i > 0; i--)
{
Set<Lr0State> nset = new NumSet<>();
for (Lr0State st : result)
{
Set<Lr0State> in = st.getInStates();
if (in != null)
{
nset.addAll(in);
}
}
result = nset;
}
// this is just for getting similar states as jikes do
List<Lr0State> list = new ArrayList<>();
list.addAll(result);
Collections.sort(list);
Collections.reverse(list);
return list;
} } | public class class_name {
private List<Lr0State> lpgAccess(Lr0State state, Item item)
{
Set<Lr0State> result = new NumSet<>();
result.add(state);
for (int i = item.getDot(); i > 0; i--)
{
Set<Lr0State> nset = new NumSet<>();
for (Lr0State st : result)
{
Set<Lr0State> in = st.getInStates();
if (in != null)
{
nset.addAll(in);
// depends on control dependency: [if], data = [(in]
}
}
result = nset;
// depends on control dependency: [for], data = [none]
}
// this is just for getting similar states as jikes do
List<Lr0State> list = new ArrayList<>();
list.addAll(result);
Collections.sort(list);
Collections.reverse(list);
return list;
} } |
public class class_name {
public void marshall(NodePropertiesSummary nodePropertiesSummary, ProtocolMarshaller protocolMarshaller) {
if (nodePropertiesSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(nodePropertiesSummary.getIsMainNode(), ISMAINNODE_BINDING);
protocolMarshaller.marshall(nodePropertiesSummary.getNumNodes(), NUMNODES_BINDING);
protocolMarshaller.marshall(nodePropertiesSummary.getNodeIndex(), NODEINDEX_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(NodePropertiesSummary nodePropertiesSummary, ProtocolMarshaller protocolMarshaller) {
if (nodePropertiesSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(nodePropertiesSummary.getIsMainNode(), ISMAINNODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(nodePropertiesSummary.getNumNodes(), NUMNODES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(nodePropertiesSummary.getNodeIndex(), NODEINDEX_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 Long getLong(String name) {
//let it fail in the more general case where it isn't actually a number
Number number = (Number) content.get(name);
if (number == null) {
return null;
} else if (number instanceof Long) {
return (Long) number;
} else {
return number.longValue(); //autoboxing to Long
}
} } | public class class_name {
public Long getLong(String name) {
//let it fail in the more general case where it isn't actually a number
Number number = (Number) content.get(name);
if (number == null) {
return null; // depends on control dependency: [if], data = [none]
} else if (number instanceof Long) {
return (Long) number; // depends on control dependency: [if], data = [none]
} else {
return number.longValue(); //autoboxing to Long // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean processDetail(Record parent, String strSourcePath, String strDestPath)
{
boolean bSubsExist = false;
String strName;
Script recReplication = new Script(this);
recReplication.setKeyArea(Script.PARENT_FOLDER_ID_KEY);
recReplication.addListener(new SubFileFilter(parent));
try {
strName = parent.getField(Script.NAME).toString();
while (recReplication.hasNext())
{ // Read through the pictures and create an index
recReplication.next();
bSubsExist = true;
strName = recReplication.getField(Script.NAME).toString();
String strSource = recReplication.getField(Script.SOURCE_PARAM).toString();
String strDestination = recReplication.getField(Script.DESTINATION_PARAM).toString();
strSource = strSourcePath + strSource;
strDestination = strDestPath + strDestination;
this.processDetail(recReplication, strSource, strDestination);
}
recReplication.close();
} catch (DBException ex) {
ex.printStackTrace();
}
if (strSourcePath.length() > 0)
if (Character.isLetterOrDigit(strSourcePath.charAt(strSourcePath.length() - 1)))
{
System.out.println("From: " + strSourcePath + " To: " + strDestPath);
File fileSource = new File(strSourcePath);
File fileDest = new File(strDestPath);
if (fileSource.exists())
{
if (fileDest.exists())
fileDest.delete();
else
System.out.println("Target doesn't exist: " + strSourcePath);
try {
FileInputStream inStream = new FileInputStream(fileSource);
FileOutputStream outStream = new FileOutputStream(fileDest);
org.jbundle.jbackup.util.Util.copyStream(inStream, outStream);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return bSubsExist;
} } | public class class_name {
public boolean processDetail(Record parent, String strSourcePath, String strDestPath)
{
boolean bSubsExist = false;
String strName;
Script recReplication = new Script(this);
recReplication.setKeyArea(Script.PARENT_FOLDER_ID_KEY);
recReplication.addListener(new SubFileFilter(parent));
try {
strName = parent.getField(Script.NAME).toString(); // depends on control dependency: [try], data = [none]
while (recReplication.hasNext())
{ // Read through the pictures and create an index
recReplication.next(); // depends on control dependency: [while], data = [none]
bSubsExist = true; // depends on control dependency: [while], data = [none]
strName = recReplication.getField(Script.NAME).toString(); // depends on control dependency: [while], data = [none]
String strSource = recReplication.getField(Script.SOURCE_PARAM).toString();
String strDestination = recReplication.getField(Script.DESTINATION_PARAM).toString();
strSource = strSourcePath + strSource; // depends on control dependency: [while], data = [none]
strDestination = strDestPath + strDestination; // depends on control dependency: [while], data = [none]
this.processDetail(recReplication, strSource, strDestination); // depends on control dependency: [while], data = [none]
}
recReplication.close(); // depends on control dependency: [try], data = [none]
} catch (DBException ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
if (strSourcePath.length() > 0)
if (Character.isLetterOrDigit(strSourcePath.charAt(strSourcePath.length() - 1)))
{
System.out.println("From: " + strSourcePath + " To: " + strDestPath); // depends on control dependency: [if], data = [none]
File fileSource = new File(strSourcePath);
File fileDest = new File(strDestPath);
if (fileSource.exists())
{
if (fileDest.exists())
fileDest.delete();
else
System.out.println("Target doesn't exist: " + strSourcePath);
try {
FileInputStream inStream = new FileInputStream(fileSource);
FileOutputStream outStream = new FileOutputStream(fileDest);
org.jbundle.jbackup.util.Util.copyStream(inStream, 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]
}
}
return bSubsExist;
} } |
public class class_name {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2018-10-12T02:52:47+02:00", comments = "JAXB RI v2.2.11")
public Boolean getTeilungsversteigerung() {
if (teilungsversteigerung == null) {
return false;
} else {
return teilungsversteigerung;
}
} } | public class class_name {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2018-10-12T02:52:47+02:00", comments = "JAXB RI v2.2.11")
public Boolean getTeilungsversteigerung() {
if (teilungsversteigerung == null) {
return false; // depends on control dependency: [if], data = [none]
} else {
return teilungsversteigerung; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static MetricFamilySamples createMetricFamilySamples(Metric metric, String namespace) {
MetricDescriptor metricDescriptor = metric.getMetricDescriptor();
String name = getNamespacedName(metricDescriptor.getName(), namespace);
Type type = getType(metricDescriptor.getType());
List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys());
List<Sample> samples = Lists.newArrayList();
for (io.opencensus.metrics.export.TimeSeries timeSeries : metric.getTimeSeriesList()) {
for (io.opencensus.metrics.export.Point point : timeSeries.getPoints()) {
samples.addAll(getSamples(name, labelNames, timeSeries.getLabelValues(), point.getValue()));
}
}
return new MetricFamilySamples(name, type, metricDescriptor.getDescription(), samples);
} } | public class class_name {
static MetricFamilySamples createMetricFamilySamples(Metric metric, String namespace) {
MetricDescriptor metricDescriptor = metric.getMetricDescriptor();
String name = getNamespacedName(metricDescriptor.getName(), namespace);
Type type = getType(metricDescriptor.getType());
List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys());
List<Sample> samples = Lists.newArrayList();
for (io.opencensus.metrics.export.TimeSeries timeSeries : metric.getTimeSeriesList()) {
for (io.opencensus.metrics.export.Point point : timeSeries.getPoints()) {
samples.addAll(getSamples(name, labelNames, timeSeries.getLabelValues(), point.getValue())); // depends on control dependency: [for], data = [point]
}
}
return new MetricFamilySamples(name, type, metricDescriptor.getDescription(), samples);
} } |
public class class_name {
public void setOrderableDBInstanceOptions(java.util.Collection<OrderableDBInstanceOption> orderableDBInstanceOptions) {
if (orderableDBInstanceOptions == null) {
this.orderableDBInstanceOptions = null;
return;
}
this.orderableDBInstanceOptions = new com.amazonaws.internal.SdkInternalList<OrderableDBInstanceOption>(orderableDBInstanceOptions);
} } | public class class_name {
public void setOrderableDBInstanceOptions(java.util.Collection<OrderableDBInstanceOption> orderableDBInstanceOptions) {
if (orderableDBInstanceOptions == null) {
this.orderableDBInstanceOptions = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.orderableDBInstanceOptions = new com.amazonaws.internal.SdkInternalList<OrderableDBInstanceOption>(orderableDBInstanceOptions);
} } |
public class class_name {
public boolean isQueryPageArchived(QueryPage queryPage) {
if (queryPage.getArchived()) {
return true;
}
QuerySection querySection = queryPage.getQuerySection();
if (querySection.getArchived()) {
return true;
}
return isQueryArchived(querySection.getQuery());
} } | public class class_name {
public boolean isQueryPageArchived(QueryPage queryPage) {
if (queryPage.getArchived()) {
return true; // depends on control dependency: [if], data = [none]
}
QuerySection querySection = queryPage.getQuerySection();
if (querySection.getArchived()) {
return true; // depends on control dependency: [if], data = [none]
}
return isQueryArchived(querySection.getQuery());
} } |
public class class_name {
public void addChildToList(Node n, String prefix, ArrayList<String> list) {
if (n.getChildren().size() > 0) {
for (Node child : n.getChildren()) {
if (prefix != null && "-".equals(child.getToken())) {
if (!list.contains(prefix)) {
list.add(prefix);
}
return;
}
String text = (prefix == null ? "" : prefix + " ") + child.getToken();
// list.add(text);
addChildToList(child,text,list);
}
} else {
if (!list.contains(prefix)) {
list.add(prefix);
}
}
} } | public class class_name {
public void addChildToList(Node n, String prefix, ArrayList<String> list) {
if (n.getChildren().size() > 0) {
for (Node child : n.getChildren()) {
if (prefix != null && "-".equals(child.getToken())) {
if (!list.contains(prefix)) {
list.add(prefix); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
String text = (prefix == null ? "" : prefix + " ") + child.getToken();
// list.add(text);
addChildToList(child,text,list); // depends on control dependency: [for], data = [child]
}
} else {
if (!list.contains(prefix)) {
list.add(prefix); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public final String getFor(final Class<?> pClass, final String pThingName) {
if ("list".equals(pThingName)) {
return "waPrcEntitiesPage";
}
return null;
} } | public class class_name {
@Override
public final String getFor(final Class<?> pClass, final String pThingName) {
if ("list".equals(pThingName)) {
return "waPrcEntitiesPage"; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public final void changeEndDate(LocalDate date, boolean keepDuration) {
requireNonNull(date);
Interval interval = getInterval();
LocalDateTime newEndDateTime = getEndAsLocalDateTime().with(date);
LocalDateTime startDateTime = getStartAsLocalDateTime();
if (keepDuration) {
startDateTime = newEndDateTime.minus(getDuration());
setInterval(startDateTime, newEndDateTime, getZoneId());
} else {
/*
* We might have a problem if the new end time is BEFORE the current start time.
*/
if (newEndDateTime.isBefore(startDateTime)) {
interval = interval.withStartDateTime(newEndDateTime.minus(interval.getDuration()));
}
setInterval(interval.withEndDate(date));
}
} } | public class class_name {
public final void changeEndDate(LocalDate date, boolean keepDuration) {
requireNonNull(date);
Interval interval = getInterval();
LocalDateTime newEndDateTime = getEndAsLocalDateTime().with(date);
LocalDateTime startDateTime = getStartAsLocalDateTime();
if (keepDuration) {
startDateTime = newEndDateTime.minus(getDuration()); // depends on control dependency: [if], data = [none]
setInterval(startDateTime, newEndDateTime, getZoneId()); // depends on control dependency: [if], data = [none]
} else {
/*
* We might have a problem if the new end time is BEFORE the current start time.
*/
if (newEndDateTime.isBefore(startDateTime)) {
interval = interval.withStartDateTime(newEndDateTime.minus(interval.getDuration())); // depends on control dependency: [if], data = [none]
}
setInterval(interval.withEndDate(date)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void evaluate(DoubleSolution solution) {
int numberOfVariables_ = solution.getNumberOfVariables();
int numberOfObjectives_ = solution.getNumberOfObjectives();
double[] x = new double[numberOfVariables_];
double[] f = new double[numberOfObjectives_];
for (int i = 0; i < numberOfVariables_; i++) {
x[i] = solution.getVariableValue(i);
}
// evaluate zi,t1i,t2i,t3i,t4i,yi
double[] z = new double[numberOfVariables_];
double[] t1 = new double[numberOfVariables_];
double[] t2 = new double[numberOfVariables_];
double[] t3 = new double[numberOfVariables_];
double[] t4 = new double[numberOfObjectives_];
double[] y = new double[numberOfObjectives_];
double sub1 = 0, sub2 = 0;
int lb = 0, ub = 0;
for (int i = 0; i < K10; i++) {
z[i] = x[i] / (2 * i + 2);
t1[i] = z[i];
t2[i] = t1[i];
t3[i] = Math.pow(t2[i], 0.02);
}
for (int i = K10; i < numberOfVariables_; i++) {
z[i] = x[i] / (2 * i + 2);
t1[i] = Math.abs(z[i] - 0.35) / (Math.abs(Math.floor(0.35 - z[i]) + 0.35));
t2[i] = 0.8 + 0.8 * (0.75 - t1[i]) * Math.min(0, Math.floor(t1[i] - 0.75)) / 0.75
- 0.2 * (t1[i] - 0.85) * Math.min(0, Math.floor(0.85 - t1[i])) / 0.15;
t2[i] = Math.round(t2[i] * 1000000) / 1000000.0;
t3[i] = Math.pow(t2[i], 0.02);
}
for (int i = 0; i < numberOfObjectives_ - 1; i++) {
sub1 = 0;
sub2 = 0;
lb = i * K10 / (numberOfObjectives_ - 1) + 1;
ub = (i + 1) * K10 / (numberOfObjectives_ - 1);
for (int j = lb - 1; j < ub; j++) {
sub1 += (2 * (j + 1) * t3[j]);
sub2 += (2 * (j + 1));
}
t4[i] = sub1 / sub2;
}
lb = K10 + 1;
ub = numberOfVariables_;
sub1 = 0;
sub2 = 0;
for (int j = lb - 1; j < ub; j++) {
sub1 += (2 * (j + 1) * t3[j]);
sub2 += (2 * (j + 1));
}
t4[numberOfObjectives_ - 1] = sub1 / sub2;
for (int i = 0; i < numberOfObjectives_ - 1; i++) {
y[i] = (t4[i] - 0.5) * Math.max(1, t4[numberOfObjectives_ - 1]) + 0.5;
}
y[numberOfObjectives_ - 1] = t4[numberOfObjectives_ - 1];
// evaluate fm,fm-1,...,2,f1
double subf1 = 1;
f[numberOfObjectives_ - 1] = y[numberOfObjectives_ - 1] + 2 * numberOfObjectives_ * (1 - y[0]
- Math.cos(10 * Math.PI * y[0] + Math.PI / 2) / (10 * Math.PI));
for (int i = numberOfObjectives_ - 2; i > 0; i--) {
subf1 *= (1 - Math.cos(Math.PI * y[numberOfObjectives_ - i - 2] / 2));
f[i] = y[numberOfObjectives_ - 1] + 2 * (i + 1) * subf1 * (1 - Math
.sin(Math.PI * y[numberOfObjectives_ - i - 1] / 2));
}
f[0] = y[numberOfObjectives_ - 1] + 2 * subf1 * (1 - Math
.cos(Math.PI * y[numberOfObjectives_ - 2] / 2));
for (int i = 0; i < numberOfObjectives_; i++) {
solution.setObjective(i, f[i]);
}
} } | public class class_name {
@Override
public void evaluate(DoubleSolution solution) {
int numberOfVariables_ = solution.getNumberOfVariables();
int numberOfObjectives_ = solution.getNumberOfObjectives();
double[] x = new double[numberOfVariables_];
double[] f = new double[numberOfObjectives_];
for (int i = 0; i < numberOfVariables_; i++) {
x[i] = solution.getVariableValue(i);
// depends on control dependency: [for], data = [i]
}
// evaluate zi,t1i,t2i,t3i,t4i,yi
double[] z = new double[numberOfVariables_];
double[] t1 = new double[numberOfVariables_];
double[] t2 = new double[numberOfVariables_];
double[] t3 = new double[numberOfVariables_];
double[] t4 = new double[numberOfObjectives_];
double[] y = new double[numberOfObjectives_];
double sub1 = 0, sub2 = 0;
int lb = 0, ub = 0;
for (int i = 0; i < K10; i++) {
z[i] = x[i] / (2 * i + 2);
// depends on control dependency: [for], data = [i]
t1[i] = z[i];
// depends on control dependency: [for], data = [i]
t2[i] = t1[i];
// depends on control dependency: [for], data = [i]
t3[i] = Math.pow(t2[i], 0.02);
// depends on control dependency: [for], data = [i]
}
for (int i = K10; i < numberOfVariables_; i++) {
z[i] = x[i] / (2 * i + 2);
// depends on control dependency: [for], data = [i]
t1[i] = Math.abs(z[i] - 0.35) / (Math.abs(Math.floor(0.35 - z[i]) + 0.35));
// depends on control dependency: [for], data = [i]
t2[i] = 0.8 + 0.8 * (0.75 - t1[i]) * Math.min(0, Math.floor(t1[i] - 0.75)) / 0.75
- 0.2 * (t1[i] - 0.85) * Math.min(0, Math.floor(0.85 - t1[i])) / 0.15;
// depends on control dependency: [for], data = [i]
t2[i] = Math.round(t2[i] * 1000000) / 1000000.0;
// depends on control dependency: [for], data = [i]
t3[i] = Math.pow(t2[i], 0.02);
// depends on control dependency: [for], data = [i]
}
for (int i = 0; i < numberOfObjectives_ - 1; i++) {
sub1 = 0;
// depends on control dependency: [for], data = [none]
sub2 = 0;
// depends on control dependency: [for], data = [none]
lb = i * K10 / (numberOfObjectives_ - 1) + 1;
// depends on control dependency: [for], data = [i]
ub = (i + 1) * K10 / (numberOfObjectives_ - 1);
// depends on control dependency: [for], data = [i]
for (int j = lb - 1; j < ub; j++) {
sub1 += (2 * (j + 1) * t3[j]);
// depends on control dependency: [for], data = [j]
sub2 += (2 * (j + 1));
// depends on control dependency: [for], data = [j]
}
t4[i] = sub1 / sub2;
// depends on control dependency: [for], data = [i]
}
lb = K10 + 1;
ub = numberOfVariables_;
sub1 = 0;
sub2 = 0;
for (int j = lb - 1; j < ub; j++) {
sub1 += (2 * (j + 1) * t3[j]);
// depends on control dependency: [for], data = [j]
sub2 += (2 * (j + 1));
// depends on control dependency: [for], data = [j]
}
t4[numberOfObjectives_ - 1] = sub1 / sub2;
for (int i = 0; i < numberOfObjectives_ - 1; i++) {
y[i] = (t4[i] - 0.5) * Math.max(1, t4[numberOfObjectives_ - 1]) + 0.5;
// depends on control dependency: [for], data = [i]
}
y[numberOfObjectives_ - 1] = t4[numberOfObjectives_ - 1];
// evaluate fm,fm-1,...,2,f1
double subf1 = 1;
f[numberOfObjectives_ - 1] = y[numberOfObjectives_ - 1] + 2 * numberOfObjectives_ * (1 - y[0]
- Math.cos(10 * Math.PI * y[0] + Math.PI / 2) / (10 * Math.PI));
for (int i = numberOfObjectives_ - 2; i > 0; i--) {
subf1 *= (1 - Math.cos(Math.PI * y[numberOfObjectives_ - i - 2] / 2));
// depends on control dependency: [for], data = [i]
f[i] = y[numberOfObjectives_ - 1] + 2 * (i + 1) * subf1 * (1 - Math
.sin(Math.PI * y[numberOfObjectives_ - i - 1] / 2));
// depends on control dependency: [for], data = [i]
}
f[0] = y[numberOfObjectives_ - 1] + 2 * subf1 * (1 - Math
.cos(Math.PI * y[numberOfObjectives_ - 2] / 2));
for (int i = 0; i < numberOfObjectives_; i++) {
solution.setObjective(i, f[i]);
// depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
@Override
@GraphTransaction
public void deleteTrait(String guid, String traitNameToBeDeleted) throws TraitNotFoundException, EntityNotFoundException, RepositoryException {
LOG.debug("Deleting trait={} from entity={}", traitNameToBeDeleted, guid);
GraphTransactionInterceptor.lockObjectAndReleasePostCommit(guid);
AtlasVertex instanceVertex = graphHelper.getVertexForGUID(guid);
List<String> traitNames = GraphHelper.getTraitNames(instanceVertex);
if (!traitNames.contains(traitNameToBeDeleted)) {
throw new TraitNotFoundException(
"Could not find trait=" + traitNameToBeDeleted + " in the repository for entity: " + guid);
}
try {
final String entityTypeName = GraphHelper.getTypeName(instanceVertex);
String relationshipLabel = GraphHelper.getTraitLabel(entityTypeName, traitNameToBeDeleted);
AtlasEdge edge = graphHelper.getEdgeForLabel(instanceVertex, relationshipLabel);
if(edge != null) {
deleteHandler.deleteEdgeReference(edge, DataTypes.TypeCategory.TRAIT, false, true);
}
// update the traits in entity once trait removal is successful
traitNames.remove(traitNameToBeDeleted);
updateTraits(instanceVertex, traitNames);
} catch (Exception e) {
throw new RepositoryException(e);
}
} } | public class class_name {
@Override
@GraphTransaction
public void deleteTrait(String guid, String traitNameToBeDeleted) throws TraitNotFoundException, EntityNotFoundException, RepositoryException {
LOG.debug("Deleting trait={} from entity={}", traitNameToBeDeleted, guid);
GraphTransactionInterceptor.lockObjectAndReleasePostCommit(guid);
AtlasVertex instanceVertex = graphHelper.getVertexForGUID(guid);
List<String> traitNames = GraphHelper.getTraitNames(instanceVertex);
if (!traitNames.contains(traitNameToBeDeleted)) {
throw new TraitNotFoundException(
"Could not find trait=" + traitNameToBeDeleted + " in the repository for entity: " + guid);
}
try {
final String entityTypeName = GraphHelper.getTypeName(instanceVertex);
String relationshipLabel = GraphHelper.getTraitLabel(entityTypeName, traitNameToBeDeleted);
AtlasEdge edge = graphHelper.getEdgeForLabel(instanceVertex, relationshipLabel);
if(edge != null) {
deleteHandler.deleteEdgeReference(edge, DataTypes.TypeCategory.TRAIT, false, true); // depends on control dependency: [if], data = [(edge]
}
// update the traits in entity once trait removal is successful
traitNames.remove(traitNameToBeDeleted);
updateTraits(instanceVertex, traitNames);
} catch (Exception e) {
throw new RepositoryException(e);
}
} } |
public class class_name {
public boolean offer(T element) {
if (size < capacity) {
put(element);
return true;
} else if (size > 0 && !lessThan(element, peek())) {
heap[1] = element;
adjustTop();
return true;
} else {
return false;
}
} } | public class class_name {
public boolean offer(T element) {
if (size < capacity) {
put(element); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
} else if (size > 0 && !lessThan(element, peek())) {
heap[1] = element; // depends on control dependency: [if], data = [none]
adjustTop(); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
} else {
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static DateTime of(Date date) {
if (date instanceof DateTime) {
return (DateTime) date;
}
return new DateTime(date);
} } | public class class_name {
public static DateTime of(Date date) {
if (date instanceof DateTime) {
return (DateTime) date;
// depends on control dependency: [if], data = [none]
}
return new DateTime(date);
} } |
public class class_name {
@Deprecated
private static IAtomContainer removeHydrogens(IAtomContainer ac, List<IAtom> preserve) {
Map<IAtom, IAtom> map = new HashMap<IAtom, IAtom>();
// maps original atoms to clones.
List<IAtom> remove = new ArrayList<IAtom>();
// lists removed Hs.
// Clone atoms except those to be removed.
IAtomContainer mol = ac.getBuilder().newInstance(IAtomContainer.class);
int count = ac.getAtomCount();
for (int i = 0; i < count; i++) {
// Clone/remove this atom?
IAtom atom = ac.getAtom(i);
if (!suppressibleHydrogen(ac, atom) || preserve.contains(atom)) {
IAtom a = null;
try {
a = (IAtom) atom.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
a.setImplicitHydrogenCount(0);
mol.addAtom(a);
map.put(atom, a);
} else {
remove.add(atom);
// maintain list of removed H.
}
}
// Clone bonds except those involving removed atoms.
count = ac.getBondCount();
for (int i = 0; i < count; i++) {
// Check bond.
final IBond bond = ac.getBond(i);
IAtom atom0 = bond.getBegin();
IAtom atom1 = bond.getEnd();
boolean remove_bond = false;
for (IAtom atom : bond.atoms()) {
if (remove.contains(atom)) {
remove_bond = true;
break;
}
}
// Clone/remove this bond?
if (!remove_bond) {
// if (!remove.contains(atoms[0]) && !remove.contains(atoms[1]))
IBond clone = null;
try {
clone = (IBond) ac.getBond(i).clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
clone.setAtoms(new IAtom[]{map.get(atom0), map.get(atom1)});
mol.addBond(clone);
}
}
// Recompute hydrogen counts of neighbours of removed Hydrogens.
for (IAtom removeAtom : remove) {
// Process neighbours.
for (IAtom neighbor : ac.getConnectedAtomsList(removeAtom)) {
final IAtom neighb = map.get(neighbor);
neighb.setImplicitHydrogenCount(neighb.getImplicitHydrogenCount() + 1);
}
}
return (mol);
} } | public class class_name {
@Deprecated
private static IAtomContainer removeHydrogens(IAtomContainer ac, List<IAtom> preserve) {
Map<IAtom, IAtom> map = new HashMap<IAtom, IAtom>();
// maps original atoms to clones.
List<IAtom> remove = new ArrayList<IAtom>();
// lists removed Hs.
// Clone atoms except those to be removed.
IAtomContainer mol = ac.getBuilder().newInstance(IAtomContainer.class);
int count = ac.getAtomCount();
for (int i = 0; i < count; i++) {
// Clone/remove this atom?
IAtom atom = ac.getAtom(i);
if (!suppressibleHydrogen(ac, atom) || preserve.contains(atom)) {
IAtom a = null;
try {
a = (IAtom) atom.clone(); // depends on control dependency: [try], data = [none]
} catch (CloneNotSupportedException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
a.setImplicitHydrogenCount(0); // depends on control dependency: [if], data = [none]
mol.addAtom(a); // depends on control dependency: [if], data = [none]
map.put(atom, a); // depends on control dependency: [if], data = [none]
} else {
remove.add(atom); // depends on control dependency: [if], data = [none]
// maintain list of removed H.
}
}
// Clone bonds except those involving removed atoms.
count = ac.getBondCount();
for (int i = 0; i < count; i++) {
// Check bond.
final IBond bond = ac.getBond(i);
IAtom atom0 = bond.getBegin();
IAtom atom1 = bond.getEnd();
boolean remove_bond = false;
for (IAtom atom : bond.atoms()) {
if (remove.contains(atom)) {
remove_bond = true; // depends on control dependency: [if], data = [none]
break;
}
}
// Clone/remove this bond?
if (!remove_bond) {
// if (!remove.contains(atoms[0]) && !remove.contains(atoms[1]))
IBond clone = null;
try {
clone = (IBond) ac.getBond(i).clone(); // depends on control dependency: [try], data = [none]
} catch (CloneNotSupportedException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
clone.setAtoms(new IAtom[]{map.get(atom0), map.get(atom1)}); // depends on control dependency: [if], data = [none]
mol.addBond(clone); // depends on control dependency: [if], data = [none]
}
}
// Recompute hydrogen counts of neighbours of removed Hydrogens.
for (IAtom removeAtom : remove) {
// Process neighbours.
for (IAtom neighbor : ac.getConnectedAtomsList(removeAtom)) {
final IAtom neighb = map.get(neighbor);
neighb.setImplicitHydrogenCount(neighb.getImplicitHydrogenCount() + 1); // depends on control dependency: [for], data = [none]
}
}
return (mol);
} } |
public class class_name {
@Override
public boolean isShowing() {
if (markedAsVisible) {
if (viewPort.getResolution() >= wmsConfig.getMinimumResolution() && viewPort.getResolution() <
wmsConfig.getMaximumResolution()) {
return true;
}
}
return false;
} } | public class class_name {
@Override
public boolean isShowing() {
if (markedAsVisible) {
if (viewPort.getResolution() >= wmsConfig.getMinimumResolution() && viewPort.getResolution() <
wmsConfig.getMaximumResolution()) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
int addPathFromMultiPath(MultiPath multi_path, int ipath, boolean as_polygon) {
int newgeom = createGeometry(as_polygon ? Geometry.Type.Polygon
: Geometry.Type.Polyline, multi_path.getDescription());
MultiPathImpl mp_impl = (MultiPathImpl) multi_path._getImpl();
if (multi_path.getPathSize(ipath) < 2)
return newgeom; //return empty geometry
// m_vertices->reserve_rounded(m_vertices->get_point_count() +
// multi_path.get_path_size(ipath));//ensure reallocation happens by
// blocks so that already allocated vertices do not get reallocated.
m_vertices_mp.add(multi_path, multi_path.getPathStart(ipath),
mp_impl.getPathEnd(ipath));
m_xy_stream = (AttributeStreamOfDbl) m_vertices
.getAttributeStreamRef(VertexDescription.Semantics.POSITION);
int path = insertPath(newgeom, -1);
setClosedPath(path, mp_impl.isClosedPath(ipath) || as_polygon);
boolean b_some_segments = m_segments != null
&& mp_impl.getSegmentFlagsStreamRef() != null;
for (int ivertex = mp_impl.getPathStart(ipath), iend = mp_impl
.getPathEnd(ipath); ivertex < iend; ivertex++) {
int vertex = insertVertex_(path, -1, null);
if (b_some_segments) {
int vindex = getVertexIndex(vertex);
if ((mp_impl.getSegmentFlags(ivertex) & SegmentFlags.enumLineSeg) != 0) {
setSegmentToIndex_(vindex, null);
} else {
SegmentBuffer seg_buffer = new SegmentBuffer();
mp_impl.getSegment(ivertex, seg_buffer, true);
setSegmentToIndex_(vindex, seg_buffer.get());
}
}
}
return newgeom;
} } | public class class_name {
int addPathFromMultiPath(MultiPath multi_path, int ipath, boolean as_polygon) {
int newgeom = createGeometry(as_polygon ? Geometry.Type.Polygon
: Geometry.Type.Polyline, multi_path.getDescription());
MultiPathImpl mp_impl = (MultiPathImpl) multi_path._getImpl();
if (multi_path.getPathSize(ipath) < 2)
return newgeom; //return empty geometry
// m_vertices->reserve_rounded(m_vertices->get_point_count() +
// multi_path.get_path_size(ipath));//ensure reallocation happens by
// blocks so that already allocated vertices do not get reallocated.
m_vertices_mp.add(multi_path, multi_path.getPathStart(ipath),
mp_impl.getPathEnd(ipath));
m_xy_stream = (AttributeStreamOfDbl) m_vertices
.getAttributeStreamRef(VertexDescription.Semantics.POSITION);
int path = insertPath(newgeom, -1);
setClosedPath(path, mp_impl.isClosedPath(ipath) || as_polygon);
boolean b_some_segments = m_segments != null
&& mp_impl.getSegmentFlagsStreamRef() != null;
for (int ivertex = mp_impl.getPathStart(ipath), iend = mp_impl
.getPathEnd(ipath); ivertex < iend; ivertex++) {
int vertex = insertVertex_(path, -1, null);
if (b_some_segments) {
int vindex = getVertexIndex(vertex);
if ((mp_impl.getSegmentFlags(ivertex) & SegmentFlags.enumLineSeg) != 0) {
setSegmentToIndex_(vindex, null); // depends on control dependency: [if], data = [none]
} else {
SegmentBuffer seg_buffer = new SegmentBuffer();
mp_impl.getSegment(ivertex, seg_buffer, true); // depends on control dependency: [if], data = [none]
setSegmentToIndex_(vindex, seg_buffer.get()); // depends on control dependency: [if], data = [none]
}
}
}
return newgeom;
} } |
public class class_name {
public void setPreserveLibModules(String preserveLibModules) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(preserveLibModules)) {
String[] modules = preserveLibModules.split(",");
m_preserveLibModules = Arrays.asList(modules);
} else {
m_preserveLibModules = Collections.emptyList();
}
} } | public class class_name {
public void setPreserveLibModules(String preserveLibModules) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(preserveLibModules)) {
String[] modules = preserveLibModules.split(",");
m_preserveLibModules = Arrays.asList(modules); // depends on control dependency: [if], data = [none]
} else {
m_preserveLibModules = Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void checkThatApplicationSecretIsSet(
boolean isProd,
String baseDirWithoutTrailingSlash,
PropertiesConfiguration defaultConfiguration,
Configuration compositeConfiguration) {
String applicationSecret = compositeConfiguration.getString(NinjaConstant.applicationSecret);
if (applicationSecret == null
|| applicationSecret.isEmpty()) {
// If in production we stop the startup process. It simply does not make
// sense to run in production if the secret is not set.
if (isProd) {
String errorMessage = "Fatal error. Key application.secret not set. Please fix that.";
logger.error(errorMessage);
throw new RuntimeException(errorMessage);
}
logger.info("Key application.secret not set. Generating new one and setting in conf/application.conf.");
// generate new secret
String secret = SecretGenerator.generateSecret();
// set in overall composite configuration => this enables this instance to
// start immediately. Otherwise we would have another build cycle.
compositeConfiguration.setProperty(NinjaConstant.applicationSecret, secret);
// defaultConfiguration is: conf/application.conf (not prefixed)
defaultConfiguration.setProperty(NinjaConstant.applicationSecret, secret);
try {
// STEP 1: Save in source directories:
// save to compiled version => in src/main/target/
String pathToApplicationConfInSrcDir = baseDirWithoutTrailingSlash + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + NinjaProperties.CONF_FILE_LOCATION_BY_CONVENTION;
Files.createParentDirs(new File(pathToApplicationConfInSrcDir));
// save to source
defaultConfiguration.save(pathToApplicationConfInSrcDir);
// STEP 2: Save in classes dir (target/classes or similar).
// save in target directory (compiled version aka war aka classes dir)
defaultConfiguration.save();
} catch (ConfigurationException e) {
logger.error("Error while saving new secret to application.conf.", e);
} catch (IOException e) {
logger.error("Error while saving new secret to application.conf.", e);
}
}
} } | public class class_name {
public static void checkThatApplicationSecretIsSet(
boolean isProd,
String baseDirWithoutTrailingSlash,
PropertiesConfiguration defaultConfiguration,
Configuration compositeConfiguration) {
String applicationSecret = compositeConfiguration.getString(NinjaConstant.applicationSecret);
if (applicationSecret == null
|| applicationSecret.isEmpty()) {
// If in production we stop the startup process. It simply does not make
// sense to run in production if the secret is not set.
if (isProd) {
String errorMessage = "Fatal error. Key application.secret not set. Please fix that.";
logger.error(errorMessage); // depends on control dependency: [if], data = [none]
throw new RuntimeException(errorMessage);
}
logger.info("Key application.secret not set. Generating new one and setting in conf/application.conf."); // depends on control dependency: [if], data = [none]
// generate new secret
String secret = SecretGenerator.generateSecret();
// set in overall composite configuration => this enables this instance to
// start immediately. Otherwise we would have another build cycle.
compositeConfiguration.setProperty(NinjaConstant.applicationSecret, secret); // depends on control dependency: [if], data = [none]
// defaultConfiguration is: conf/application.conf (not prefixed)
defaultConfiguration.setProperty(NinjaConstant.applicationSecret, secret); // depends on control dependency: [if], data = [none]
try {
// STEP 1: Save in source directories:
// save to compiled version => in src/main/target/
String pathToApplicationConfInSrcDir = baseDirWithoutTrailingSlash + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + NinjaProperties.CONF_FILE_LOCATION_BY_CONVENTION;
Files.createParentDirs(new File(pathToApplicationConfInSrcDir)); // depends on control dependency: [try], data = [none]
// save to source
defaultConfiguration.save(pathToApplicationConfInSrcDir); // depends on control dependency: [try], data = [none]
// STEP 2: Save in classes dir (target/classes or similar).
// save in target directory (compiled version aka war aka classes dir)
defaultConfiguration.save(); // depends on control dependency: [try], data = [none]
} catch (ConfigurationException e) {
logger.error("Error while saving new secret to application.conf.", e);
} catch (IOException e) { // depends on control dependency: [catch], data = [none]
logger.error("Error while saving new secret to application.conf.", e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public List<List<String>> asStructured() {
if (values.isEmpty()) {
return Collections.emptyList();
}
JsonValue first = values.get(0);
//["request-status", {}, "text", ["2.0", "Success"] ]
List<JsonValue> array = first.getArray();
if (array != null) {
List<List<String>> components = new ArrayList<List<String>>(array.size());
for (JsonValue value : array) {
if (value.isNull()) {
components.add(Arrays.<String> asList());
continue;
}
Object obj = value.getValue();
if (obj != null) {
String s = obj.toString();
List<String> component = (s.length() == 0) ? Arrays.<String> asList() : Arrays.asList(s);
components.add(component);
continue;
}
List<JsonValue> subArray = value.getArray();
if (subArray != null) {
List<String> component = new ArrayList<String>(subArray.size());
for (JsonValue subArrayValue : subArray) {
if (subArrayValue.isNull()) {
component.add("");
continue;
}
obj = subArrayValue.getValue();
if (obj != null) {
component.add(obj.toString());
continue;
}
}
if (component.size() == 1 && component.get(0).length() == 0) {
component.clear();
}
components.add(component);
}
}
return components;
}
//get the first value if it's not enclosed in an array
//["request-status", {}, "text", "2.0"]
Object obj = first.getValue();
if (obj != null) {
List<List<String>> components = new ArrayList<List<String>>(1);
String s = obj.toString();
List<String> component = (s.length() == 0) ? Arrays.<String> asList() : Arrays.asList(s);
components.add(component);
return components;
}
//["request-status", {}, "text", null]
if (first.isNull()) {
List<List<String>> components = new ArrayList<List<String>>(1);
components.add(Arrays.<String> asList());
return components;
}
return Collections.emptyList();
} } | public class class_name {
public List<List<String>> asStructured() {
if (values.isEmpty()) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
JsonValue first = values.get(0);
//["request-status", {}, "text", ["2.0", "Success"] ]
List<JsonValue> array = first.getArray();
if (array != null) {
List<List<String>> components = new ArrayList<List<String>>(array.size());
for (JsonValue value : array) {
if (value.isNull()) {
components.add(Arrays.<String> asList()); // depends on control dependency: [if], data = [none]
continue;
}
Object obj = value.getValue();
if (obj != null) {
String s = obj.toString();
List<String> component = (s.length() == 0) ? Arrays.<String> asList() : Arrays.asList(s);
components.add(component); // depends on control dependency: [if], data = [none]
continue;
}
List<JsonValue> subArray = value.getArray();
if (subArray != null) {
List<String> component = new ArrayList<String>(subArray.size());
for (JsonValue subArrayValue : subArray) {
if (subArrayValue.isNull()) {
component.add(""); // depends on control dependency: [if], data = [none]
continue;
}
obj = subArrayValue.getValue(); // depends on control dependency: [for], data = [subArrayValue]
if (obj != null) {
component.add(obj.toString()); // depends on control dependency: [if], data = [(obj]
continue;
}
}
if (component.size() == 1 && component.get(0).length() == 0) {
component.clear(); // depends on control dependency: [if], data = [none]
}
components.add(component); // depends on control dependency: [if], data = [none]
}
}
return components; // depends on control dependency: [if], data = [none]
}
//get the first value if it's not enclosed in an array
//["request-status", {}, "text", "2.0"]
Object obj = first.getValue();
if (obj != null) {
List<List<String>> components = new ArrayList<List<String>>(1);
String s = obj.toString();
List<String> component = (s.length() == 0) ? Arrays.<String> asList() : Arrays.asList(s);
components.add(component); // depends on control dependency: [if], data = [none]
return components; // depends on control dependency: [if], data = [none]
}
//["request-status", {}, "text", null]
if (first.isNull()) {
List<List<String>> components = new ArrayList<List<String>>(1);
components.add(Arrays.<String> asList()); // depends on control dependency: [if], data = [none]
return components; // depends on control dependency: [if], data = [none]
}
return Collections.emptyList();
} } |
public class class_name {
private String getEmailAddresses() {
List<String> emails = new ArrayList<String>();
Iterator<String> itGroups = getGroups().iterator();
while (itGroups.hasNext()) {
String groupName = itGroups.next();
try {
Iterator<CmsUser> itUsers = getCms().getUsersOfGroup(groupName, true).iterator();
while (itUsers.hasNext()) {
CmsUser user = itUsers.next();
String emailAddress = user.getEmail();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(emailAddress) && !emails.contains(emailAddress)) {
emails.add(emailAddress);
}
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
StringBuffer result = new StringBuffer(256);
Iterator<String> itEmails = emails.iterator();
while (itEmails.hasNext()) {
result.append(itEmails.next());
if (itEmails.hasNext()) {
result.append("; ");
}
}
return result.toString();
} } | public class class_name {
private String getEmailAddresses() {
List<String> emails = new ArrayList<String>();
Iterator<String> itGroups = getGroups().iterator();
while (itGroups.hasNext()) {
String groupName = itGroups.next();
try {
Iterator<CmsUser> itUsers = getCms().getUsersOfGroup(groupName, true).iterator();
while (itUsers.hasNext()) {
CmsUser user = itUsers.next();
String emailAddress = user.getEmail();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(emailAddress) && !emails.contains(emailAddress)) {
emails.add(emailAddress); // depends on control dependency: [if], data = [none]
}
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
StringBuffer result = new StringBuffer(256);
Iterator<String> itEmails = emails.iterator();
while (itEmails.hasNext()) {
result.append(itEmails.next()); // depends on control dependency: [while], data = [none]
if (itEmails.hasNext()) {
result.append("; "); // depends on control dependency: [if], data = [none]
}
}
return result.toString();
} } |
public class class_name {
public final void emit(UUID eventSource, Event event, Scope<Address> scope) {
assert event != null;
ensureEventSource(eventSource, event);
assert getSpaceID().equals(event.getSource().getSpaceID()) : "The source address must belong to this space"; //$NON-NLS-1$
try {
final Scope<Address> scopeInstance = (scope == null) ? Scopes.<Address>allParticipants() : scope;
try {
this.network.publish(scopeInstance, event);
} catch (Throwable e) {
this.logger.getKernelLogger().severe(MessageFormat.format(Messages.AbstractEventSpace_2, event, scope, e));
}
doEmit(event, scopeInstance);
} catch (Throwable e) {
this.logger.getKernelLogger().severe(MessageFormat.format(Messages.AbstractEventSpace_0, event, scope, e));
}
} } | public class class_name {
public final void emit(UUID eventSource, Event event, Scope<Address> scope) {
assert event != null;
ensureEventSource(eventSource, event);
assert getSpaceID().equals(event.getSource().getSpaceID()) : "The source address must belong to this space"; //$NON-NLS-1$
try {
final Scope<Address> scopeInstance = (scope == null) ? Scopes.<Address>allParticipants() : scope;
try {
this.network.publish(scopeInstance, event); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
this.logger.getKernelLogger().severe(MessageFormat.format(Messages.AbstractEventSpace_2, event, scope, e));
} // depends on control dependency: [catch], data = [none]
doEmit(event, scopeInstance); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
this.logger.getKernelLogger().severe(MessageFormat.format(Messages.AbstractEventSpace_0, event, scope, e));
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Deprecated
public void setIsGuestUser(boolean isGuestUser) {
UserInfo userInfo = getUserInfo(UserHandle.myUserId());
if (isGuestUser) {
userInfo.flags |= UserInfo.FLAG_GUEST;
} else {
userInfo.flags &= ~UserInfo.FLAG_GUEST;
}
} } | public class class_name {
@Deprecated
public void setIsGuestUser(boolean isGuestUser) {
UserInfo userInfo = getUserInfo(UserHandle.myUserId());
if (isGuestUser) {
userInfo.flags |= UserInfo.FLAG_GUEST; // depends on control dependency: [if], data = [none]
} else {
userInfo.flags &= ~UserInfo.FLAG_GUEST; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public CharSequence format() {
if (formatted == null) {
if (!keysToValues.keySet().containsAll(keys)) {
Set<String> missingKeys = new HashSet<String>(keys);
missingKeys.removeAll(keysToValues.keySet());
throw new IllegalArgumentException("Missing keys: " + missingKeys);
}
// Copy the original pattern to preserve all spans, such as bold, italic, etc.
SpannableStringBuilder sb = new SpannableStringBuilder(pattern);
for (Token t = head; t != null; t = t.next) {
t.expand(sb, keysToValues);
}
formatted = sb;
}
return formatted;
} } | public class class_name {
public CharSequence format() {
if (formatted == null) {
if (!keysToValues.keySet().containsAll(keys)) {
Set<String> missingKeys = new HashSet<String>(keys);
missingKeys.removeAll(keysToValues.keySet()); // depends on control dependency: [if], data = [none]
throw new IllegalArgumentException("Missing keys: " + missingKeys);
}
// Copy the original pattern to preserve all spans, such as bold, italic, etc.
SpannableStringBuilder sb = new SpannableStringBuilder(pattern);
for (Token t = head; t != null; t = t.next) {
t.expand(sb, keysToValues); // depends on control dependency: [for], data = [t]
}
formatted = sb; // depends on control dependency: [if], data = [none]
}
return formatted;
} } |
public class class_name {
private static String getRegisterName(final Code obj, final int reg) {
LocalVariableTable lvt = obj.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = lvt.getLocalVariable(reg, 0);
if (lv != null) {
return lv.getName();
}
}
return String.valueOf(reg);
} } | public class class_name {
private static String getRegisterName(final Code obj, final int reg) {
LocalVariableTable lvt = obj.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = lvt.getLocalVariable(reg, 0);
if (lv != null) {
return lv.getName(); // depends on control dependency: [if], data = [none]
}
}
return String.valueOf(reg);
} } |
public class class_name {
static public void visitElements( XMLNode root, String path, ElementVisitor ev )
{
// Get last element in path
int idx = path.lastIndexOf( '<' );
String head = path.substring( 0, idx );
String tag = path.substring( idx + 1, path.length() - 1 );
XMLNode elem = findElementPath( root, head );
if ( elem == null )
{
return;
}
// Iterate through all child nodes
XMLNode n = elem.getNested();
while ( n != null )
{
if ( n.isElement() && n.getName().equals( tag ) )
{
ev.visitElement( n );
}
n = n.getNext();
}
} } | public class class_name {
static public void visitElements( XMLNode root, String path, ElementVisitor ev )
{
// Get last element in path
int idx = path.lastIndexOf( '<' );
String head = path.substring( 0, idx );
String tag = path.substring( idx + 1, path.length() - 1 );
XMLNode elem = findElementPath( root, head );
if ( elem == null )
{
return; // depends on control dependency: [if], data = [none]
}
// Iterate through all child nodes
XMLNode n = elem.getNested();
while ( n != null )
{
if ( n.isElement() && n.getName().equals( tag ) )
{
ev.visitElement( n ); // depends on control dependency: [if], data = [none]
}
n = n.getNext(); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public static double findMaxCol(final int blockLength , final DSubmatrixD1 Y , final int col )
{
final int width = Math.min(blockLength,Y.col1-Y.col0);
final double dataY[] = Y.original.data;
double max = 0;
for( int i = Y.row0; i < Y.row1; i += blockLength ) {
int height = Math.min( blockLength , Y.row1 - i );
int index = i*Y.original.numCols + height*Y.col0 + col;
if( i == Y.row0 ) {
index += width*col;
for( int k = col; k < height; k++ , index += width ) {
double v = Math.abs(dataY[index]);
if( v > max ) {
max = v;
}
}
} else {
for( int k = 0; k < height; k++ , index += width ) {
double v = Math.abs(dataY[index]);
if( v > max ) {
max = v;
}
}
}
}
return max;
} } | public class class_name {
public static double findMaxCol(final int blockLength , final DSubmatrixD1 Y , final int col )
{
final int width = Math.min(blockLength,Y.col1-Y.col0);
final double dataY[] = Y.original.data;
double max = 0;
for( int i = Y.row0; i < Y.row1; i += blockLength ) {
int height = Math.min( blockLength , Y.row1 - i );
int index = i*Y.original.numCols + height*Y.col0 + col;
if( i == Y.row0 ) {
index += width*col; // depends on control dependency: [if], data = [none]
for( int k = col; k < height; k++ , index += width ) {
double v = Math.abs(dataY[index]);
if( v > max ) {
max = v; // depends on control dependency: [if], data = [none]
}
}
} else {
for( int k = 0; k < height; k++ , index += width ) {
double v = Math.abs(dataY[index]);
if( v > max ) {
max = v; // depends on control dependency: [if], data = [none]
}
}
}
}
return max;
} } |
public class class_name {
@Override
public boolean drawImage(Image img, AffineTransform xform,
ImageObserver obs) {
AffineTransform savedTransform = getTransform();
if (xform != null) {
transform(xform);
}
boolean result = drawImage(img, 0, 0, obs);
if (xform != null) {
setTransform(savedTransform);
}
return result;
} } | public class class_name {
@Override
public boolean drawImage(Image img, AffineTransform xform,
ImageObserver obs) {
AffineTransform savedTransform = getTransform();
if (xform != null) {
transform(xform); // depends on control dependency: [if], data = [(xform]
}
boolean result = drawImage(img, 0, 0, obs);
if (xform != null) {
setTransform(savedTransform); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public final void enumConstant() throws RecognitionException {
int enumConstant_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 14) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:5: ( ( annotations )? Identifier ( arguments )? ( classBody )? )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:7: ( annotations )? Identifier ( arguments )? ( classBody )?
{
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:7: ( annotations )?
int alt23=2;
int LA23_0 = input.LA(1);
if ( (LA23_0==58) ) {
alt23=1;
}
switch (alt23) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:7: annotations
{
pushFollow(FOLLOW_annotations_in_enumConstant491);
annotations();
state._fsp--;
if (state.failed) return;
}
break;
}
match(input,Identifier,FOLLOW_Identifier_in_enumConstant494); if (state.failed) return;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:31: ( arguments )?
int alt24=2;
int LA24_0 = input.LA(1);
if ( (LA24_0==36) ) {
alt24=1;
}
switch (alt24) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:32: arguments
{
pushFollow(FOLLOW_arguments_in_enumConstant497);
arguments();
state._fsp--;
if (state.failed) return;
}
break;
}
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:44: ( classBody )?
int alt25=2;
int LA25_0 = input.LA(1);
if ( (LA25_0==121) ) {
alt25=1;
}
switch (alt25) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:45: classBody
{
pushFollow(FOLLOW_classBody_in_enumConstant502);
classBody();
state._fsp--;
if (state.failed) return;
}
break;
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
if ( state.backtracking>0 ) { memoize(input, 14, enumConstant_StartIndex); }
}
} } | public class class_name {
public final void enumConstant() throws RecognitionException {
int enumConstant_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 14) ) { return; } // depends on control dependency: [if], data = [none]
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:5: ( ( annotations )? Identifier ( arguments )? ( classBody )? )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:7: ( annotations )? Identifier ( arguments )? ( classBody )?
{
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:7: ( annotations )?
int alt23=2;
int LA23_0 = input.LA(1);
if ( (LA23_0==58) ) {
alt23=1; // depends on control dependency: [if], data = [none]
}
switch (alt23) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:7: annotations
{
pushFollow(FOLLOW_annotations_in_enumConstant491);
annotations();
state._fsp--;
if (state.failed) return;
}
break;
}
match(input,Identifier,FOLLOW_Identifier_in_enumConstant494); if (state.failed) return;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:31: ( arguments )?
int alt24=2;
int LA24_0 = input.LA(1);
if ( (LA24_0==36) ) {
alt24=1; // depends on control dependency: [if], data = [none]
}
switch (alt24) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:32: arguments
{
pushFollow(FOLLOW_arguments_in_enumConstant497);
arguments();
state._fsp--;
if (state.failed) return;
}
break;
}
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:44: ( classBody )?
int alt25=2;
int LA25_0 = input.LA(1);
if ( (LA25_0==121) ) {
alt25=1; // depends on control dependency: [if], data = [none]
}
switch (alt25) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:330:45: classBody
{
pushFollow(FOLLOW_classBody_in_enumConstant502);
classBody();
state._fsp--;
if (state.failed) return;
}
break;
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
if ( state.backtracking>0 ) { memoize(input, 14, enumConstant_StartIndex); } // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String genRequestPath() {
//首先解析方法上的路径
String[] httpMthodAndPath = getHttpMethodAndPath(this.method);
this.httpMethod = httpMthodAndPath[0];
String methodPath = httpMthodAndPath[1];
if(StrUtil.isNotEmpty(methodPath) && methodPath.startsWith(StrUtil.SLASH)){
return methodPath;
}else{
httpMthodAndPath = getHttpMethodAndPath(this.action.getClass());
if(StrUtil.isBlank(this.httpMethod)){
httpMethod = httpMthodAndPath[0];
}
final String actionPath = httpMthodAndPath[1];
//Action路径
return StrUtil.format("{}/{}", fixFirstSlash(actionPath), methodPath);
}
} } | public class class_name {
private String genRequestPath() {
//首先解析方法上的路径
String[] httpMthodAndPath = getHttpMethodAndPath(this.method);
this.httpMethod = httpMthodAndPath[0];
String methodPath = httpMthodAndPath[1];
if(StrUtil.isNotEmpty(methodPath) && methodPath.startsWith(StrUtil.SLASH)){
return methodPath;
// depends on control dependency: [if], data = [none]
}else{
httpMthodAndPath = getHttpMethodAndPath(this.action.getClass());
// depends on control dependency: [if], data = [none]
if(StrUtil.isBlank(this.httpMethod)){
httpMethod = httpMthodAndPath[0];
// depends on control dependency: [if], data = [none]
}
final String actionPath = httpMthodAndPath[1];
//Action路径
return StrUtil.format("{}/{}", fixFirstSlash(actionPath), methodPath);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public GameSessionPlacement withPlayerLatencies(PlayerLatency... playerLatencies) {
if (this.playerLatencies == null) {
setPlayerLatencies(new java.util.ArrayList<PlayerLatency>(playerLatencies.length));
}
for (PlayerLatency ele : playerLatencies) {
this.playerLatencies.add(ele);
}
return this;
} } | public class class_name {
public GameSessionPlacement withPlayerLatencies(PlayerLatency... playerLatencies) {
if (this.playerLatencies == null) {
setPlayerLatencies(new java.util.ArrayList<PlayerLatency>(playerLatencies.length)); // depends on control dependency: [if], data = [none]
}
for (PlayerLatency ele : playerLatencies) {
this.playerLatencies.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private String readDocumentation() {
String result = null;
while (true) {
skipWhitespace(false);
if (pos == data.length || data[pos] != '/') {
return result != null ? result : "";
}
String comment = readComment();
result = (result == null) ? comment : (result + "\n" + comment);
}
} } | public class class_name {
private String readDocumentation() {
String result = null;
while (true) {
skipWhitespace(false); // depends on control dependency: [while], data = [none]
if (pos == data.length || data[pos] != '/') {
return result != null ? result : ""; // depends on control dependency: [if], data = [none]
}
String comment = readComment();
result = (result == null) ? comment : (result + "\n" + comment); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Observable<T> skipLast(int count) {
if (count < 0) {
throw new IndexOutOfBoundsException("count >= 0 required but it was " + count);
}
if (count == 0) {
return RxJavaPlugins.onAssembly(this);
}
return RxJavaPlugins.onAssembly(new ObservableSkipLast<T>(this, count));
} } | public class class_name {
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Observable<T> skipLast(int count) {
if (count < 0) {
throw new IndexOutOfBoundsException("count >= 0 required but it was " + count);
}
if (count == 0) {
return RxJavaPlugins.onAssembly(this); // depends on control dependency: [if], data = [none]
}
return RxJavaPlugins.onAssembly(new ObservableSkipLast<T>(this, count));
} } |
public class class_name {
public void setWakeUpFlag(boolean wakeup) {
int wakeUpSensorMask = reflector(_Sensor_.class).getWakeUpSensorFlag();
if (wakeup) {
setMask(wakeUpSensorMask);
} else {
clearMask(wakeUpSensorMask);
}
} } | public class class_name {
public void setWakeUpFlag(boolean wakeup) {
int wakeUpSensorMask = reflector(_Sensor_.class).getWakeUpSensorFlag();
if (wakeup) {
setMask(wakeUpSensorMask); // depends on control dependency: [if], data = [none]
} else {
clearMask(wakeUpSensorMask); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void storeEmits(int position, int currentState, List<Hit<V>> collectedEmits)
{
int[] hitArray = output[currentState];
if (hitArray != null)
{
for (int hit : hitArray)
{
collectedEmits.add(new Hit<V>(position - l[hit], position, v[hit]));
}
}
} } | public class class_name {
private void storeEmits(int position, int currentState, List<Hit<V>> collectedEmits)
{
int[] hitArray = output[currentState];
if (hitArray != null)
{
for (int hit : hitArray)
{
collectedEmits.add(new Hit<V>(position - l[hit], position, v[hit])); // depends on control dependency: [for], data = [hit]
}
}
} } |
public class class_name {
public org.apache.commons.configuration.Configuration getConfiguration(ConfigurationWrapper wrapper) {
// get input streams
List<ISource> sources = this.locate(wrapper);
// create configuration combiner
OverrideCombiner combiner = new OverrideCombiner();
CombinedConfiguration combined = new CombinedConfiguration(combiner);
// combine configurations
for(ISource source : sources) {
// determine mime type in order to create proper commons object
SupportedType type = MimeGuesser.guess(source);
// if the source isn't available, continue
if(!source.available()) {
continue;
}
InputStream stream = source.stream();
// load properties based on MIME type
// todo: update for more commons-configuration
// supported mime types
if(SupportedType.XML.equals(type)) {
XMLConfiguration xmlConfiguration = new XMLConfiguration();
try {
xmlConfiguration.load(stream);
combined.addConfiguration(xmlConfiguration);
} catch(ConfigurationException e) {
this.logger.error("An error occurred while reading XML properties: {}", e.getMessage());
}
} else {
PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
try {
propertiesConfiguration.load(stream);
combined.addConfiguration(propertiesConfiguration);
} catch (ConfigurationException e) {
this.logger.error("An error occurred while reading properties: {}", e.getMessage());
}
}
// close stream
try {
stream.close();
} catch (IOException e) {
this.logger.trace("Could not close old stream: {}", stream);
}
// leave on first loop if merge is on
if(!wrapper.merge()) {
break;
}
}
// return configuration
return combined;
} } | public class class_name {
public org.apache.commons.configuration.Configuration getConfiguration(ConfigurationWrapper wrapper) {
// get input streams
List<ISource> sources = this.locate(wrapper);
// create configuration combiner
OverrideCombiner combiner = new OverrideCombiner();
CombinedConfiguration combined = new CombinedConfiguration(combiner);
// combine configurations
for(ISource source : sources) {
// determine mime type in order to create proper commons object
SupportedType type = MimeGuesser.guess(source);
// if the source isn't available, continue
if(!source.available()) {
continue;
}
InputStream stream = source.stream();
// load properties based on MIME type
// todo: update for more commons-configuration
// supported mime types
if(SupportedType.XML.equals(type)) {
XMLConfiguration xmlConfiguration = new XMLConfiguration();
try {
xmlConfiguration.load(stream); // depends on control dependency: [try], data = [none]
combined.addConfiguration(xmlConfiguration); // depends on control dependency: [try], data = [none]
} catch(ConfigurationException e) {
this.logger.error("An error occurred while reading XML properties: {}", e.getMessage());
} // depends on control dependency: [catch], data = [none]
} else {
PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
try {
propertiesConfiguration.load(stream); // depends on control dependency: [try], data = [none]
combined.addConfiguration(propertiesConfiguration); // depends on control dependency: [try], data = [none]
} catch (ConfigurationException e) {
this.logger.error("An error occurred while reading properties: {}", e.getMessage());
} // depends on control dependency: [catch], data = [none]
}
// close stream
try {
stream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
this.logger.trace("Could not close old stream: {}", stream);
} // depends on control dependency: [catch], data = [none]
// leave on first loop if merge is on
if(!wrapper.merge()) {
break;
}
}
// return configuration
return combined;
} } |
public class class_name {
public String[] tokenize(String string, String token) {
String[] result;
try {
StringTokenizer st = new StringTokenizer(string, token);
List<String> list = new ArrayList<String>();
while (st.hasMoreTokens()) {
list.add(st.nextToken());
}
result = list.toArray(new String[list.size()]);
} catch (Exception e) {
result = null;
}
return result;
} } | public class class_name {
public String[] tokenize(String string, String token) {
String[] result;
try {
StringTokenizer st = new StringTokenizer(string, token);
List<String> list = new ArrayList<String>();
while (st.hasMoreTokens()) {
list.add(st.nextToken()); // depends on control dependency: [while], data = [none]
}
result = list.toArray(new String[list.size()]); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
result = null;
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
public void setLocale(final String locale) {
if (locale == null && this.locale == null) {
return;
} else if (locale == null) {
removeChild(this.locale);
this.locale = null;
} else if (this.locale == null) {
this.locale = new KeyValueNode<String>(CommonConstants.CS_LOCALE_TITLE, locale);
appendChild(this.locale, false);
} else {
this.locale.setValue(locale);
}
} } | public class class_name {
public void setLocale(final String locale) {
if (locale == null && this.locale == null) {
return; // depends on control dependency: [if], data = [none]
} else if (locale == null) {
removeChild(this.locale); // depends on control dependency: [if], data = [none]
this.locale = null; // depends on control dependency: [if], data = [none]
} else if (this.locale == null) {
this.locale = new KeyValueNode<String>(CommonConstants.CS_LOCALE_TITLE, locale); // depends on control dependency: [if], data = [none]
appendChild(this.locale, false); // depends on control dependency: [if], data = [(this.locale]
} else {
this.locale.setValue(locale); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public List getControlsFor(Command command) {
List controlsForCommand = new ArrayList();
for (Iterator it = commands.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Control key = (Control) entry.getKey();
Command value = (Command) entry.getValue();
if (value == command) {
controlsForCommand.add(key);
}
}
return controlsForCommand;
} } | public class class_name {
public List getControlsFor(Command command) {
List controlsForCommand = new ArrayList();
for (Iterator it = commands.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Control key = (Control) entry.getKey();
Command value = (Command) entry.getValue();
if (value == command) {
controlsForCommand.add(key); // depends on control dependency: [if], data = [none]
}
}
return controlsForCommand;
} } |
public class class_name {
static Transliterator getBasicInstance(String id, String canonID) {
StringBuffer s = new StringBuffer();
Transliterator t = registry.get(id, s);
if (s.length() != 0) {
// assert(t==0);
// Instantiate an alias
t = getInstance(s.toString(), FORWARD);
}
if (t != null && canonID != null) {
t.setID(canonID);
}
return t;
} } | public class class_name {
static Transliterator getBasicInstance(String id, String canonID) {
StringBuffer s = new StringBuffer();
Transliterator t = registry.get(id, s);
if (s.length() != 0) {
// assert(t==0);
// Instantiate an alias
t = getInstance(s.toString(), FORWARD); // depends on control dependency: [if], data = [none]
}
if (t != null && canonID != null) {
t.setID(canonID); // depends on control dependency: [if], data = [none]
}
return t;
} } |
public class class_name {
public void marshall(ListGlobalTablesRequest listGlobalTablesRequest, ProtocolMarshaller protocolMarshaller) {
if (listGlobalTablesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listGlobalTablesRequest.getExclusiveStartGlobalTableName(), EXCLUSIVESTARTGLOBALTABLENAME_BINDING);
protocolMarshaller.marshall(listGlobalTablesRequest.getLimit(), LIMIT_BINDING);
protocolMarshaller.marshall(listGlobalTablesRequest.getRegionName(), REGIONNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListGlobalTablesRequest listGlobalTablesRequest, ProtocolMarshaller protocolMarshaller) {
if (listGlobalTablesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listGlobalTablesRequest.getExclusiveStartGlobalTableName(), EXCLUSIVESTARTGLOBALTABLENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listGlobalTablesRequest.getLimit(), LIMIT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listGlobalTablesRequest.getRegionName(), REGIONNAME_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 static void addMethod(Set<MethodEntry> methods,
MethodEntry method) {
if (!method.isBridged()) {
methods.remove(method);
methods.add(method);
}
else if (!methods.contains(method)) {
methods.add(method);
}
} } | public class class_name {
private static void addMethod(Set<MethodEntry> methods,
MethodEntry method) {
if (!method.isBridged()) {
methods.remove(method); // depends on control dependency: [if], data = [none]
methods.add(method); // depends on control dependency: [if], data = [none]
}
else if (!methods.contains(method)) {
methods.add(method); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void removeByUuid_C(String uuid, long companyId) {
for (CPDefinitionInventory cpDefinitionInventory : findByUuid_C(uuid,
companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpDefinitionInventory);
}
} } | public class class_name {
@Override
public void removeByUuid_C(String uuid, long companyId) {
for (CPDefinitionInventory cpDefinitionInventory : findByUuid_C(uuid,
companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpDefinitionInventory); // depends on control dependency: [for], data = [cpDefinitionInventory]
}
} } |
public class class_name {
public void setShowMoreTimeItems(boolean enable) {
if(enable && !showMoreTimeItems) {
// create the noon and late night item:
final Resources res = getResources();
// switch the afternoon item to 2pm:
insertAdapterItem(new TimeItem(res.getString(R.string.time_afternoon_2), formatTime(14, 0), 14, 0, R.id.time_afternoon_2), 2);
removeAdapterItemById(R.id.time_afternoon);
// noon item:
insertAdapterItem(new TimeItem(res.getString(R.string.time_noon), formatTime(12, 0), 12, 0, R.id.time_noon), 1);
// late night item:
addAdapterItem(new TimeItem(res.getString(R.string.time_late_night), formatTime(23, 0), 23, 0, R.id.time_late_night));
}
else if(!enable && showMoreTimeItems) {
// switch back the afternoon item:
insertAdapterItem(new TimeItem(getResources().getString(R.string.time_afternoon), formatTime(13, 0), 13, 0, R.id.time_afternoon), 3);
removeAdapterItemById(R.id.time_afternoon_2);
removeAdapterItemById(R.id.time_noon);
removeAdapterItemById(R.id.time_late_night);
}
showMoreTimeItems = enable;
} } | public class class_name {
public void setShowMoreTimeItems(boolean enable) {
if(enable && !showMoreTimeItems) {
// create the noon and late night item:
final Resources res = getResources();
// switch the afternoon item to 2pm:
insertAdapterItem(new TimeItem(res.getString(R.string.time_afternoon_2), formatTime(14, 0), 14, 0, R.id.time_afternoon_2), 2); // depends on control dependency: [if], data = [none]
removeAdapterItemById(R.id.time_afternoon); // depends on control dependency: [if], data = [none]
// noon item:
insertAdapterItem(new TimeItem(res.getString(R.string.time_noon), formatTime(12, 0), 12, 0, R.id.time_noon), 1); // depends on control dependency: [if], data = [none]
// late night item:
addAdapterItem(new TimeItem(res.getString(R.string.time_late_night), formatTime(23, 0), 23, 0, R.id.time_late_night)); // depends on control dependency: [if], data = [none]
}
else if(!enable && showMoreTimeItems) {
// switch back the afternoon item:
insertAdapterItem(new TimeItem(getResources().getString(R.string.time_afternoon), formatTime(13, 0), 13, 0, R.id.time_afternoon), 3); // depends on control dependency: [if], data = [none]
removeAdapterItemById(R.id.time_afternoon_2); // depends on control dependency: [if], data = [none]
removeAdapterItemById(R.id.time_noon); // depends on control dependency: [if], data = [none]
removeAdapterItemById(R.id.time_late_night); // depends on control dependency: [if], data = [none]
}
showMoreTimeItems = enable;
} } |
public class class_name {
public final void mIdentifier() throws RecognitionException {
try {
int _type = Identifier;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1373:2: ( JavaLetter ( JavaLetterOrDigit )* )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1373:4: JavaLetter ( JavaLetterOrDigit )*
{
mJavaLetter();
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1373:15: ( JavaLetterOrDigit )*
loop26:
while (true) {
int alt26=2;
int LA26_0 = input.LA(1);
if ( (LA26_0=='$'||(LA26_0 >= '0' && LA26_0 <= '9')||(LA26_0 >= 'A' && LA26_0 <= 'Z')||LA26_0=='_'||(LA26_0 >= 'a' && LA26_0 <= 'z')||(LA26_0 >= '\u0080' && LA26_0 <= '\uFFFF')) ) {
alt26=1;
}
switch (alt26) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1373:15: JavaLetterOrDigit
{
mJavaLetterOrDigit();
}
break;
default :
break loop26;
}
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } | public class class_name {
public final void mIdentifier() throws RecognitionException {
try {
int _type = Identifier;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1373:2: ( JavaLetter ( JavaLetterOrDigit )* )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1373:4: JavaLetter ( JavaLetterOrDigit )*
{
mJavaLetter();
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1373:15: ( JavaLetterOrDigit )*
loop26:
while (true) {
int alt26=2;
int LA26_0 = input.LA(1);
if ( (LA26_0=='$'||(LA26_0 >= '0' && LA26_0 <= '9')||(LA26_0 >= 'A' && LA26_0 <= 'Z')||LA26_0=='_'||(LA26_0 >= 'a' && LA26_0 <= 'z')||(LA26_0 >= '\u0080' && LA26_0 <= '\uFFFF')) ) {
alt26=1; // depends on control dependency: [if], data = [none]
}
switch (alt26) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1373:15: JavaLetterOrDigit
{
mJavaLetterOrDigit();
}
break;
default :
break loop26;
}
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } |
public class class_name {
public byte[] transform(byte[] classfileBuffer, Configuration configuration) {
InstrumentationActions instrumentationActions = calculateTransformationParameters(classfileBuffer, configuration);
if (!instrumentationActions.includeClass) {
return classfileBuffer;
}
return transform(classfileBuffer, instrumentationActions);
} } | public class class_name {
public byte[] transform(byte[] classfileBuffer, Configuration configuration) {
InstrumentationActions instrumentationActions = calculateTransformationParameters(classfileBuffer, configuration);
if (!instrumentationActions.includeClass) {
return classfileBuffer; // depends on control dependency: [if], data = [none]
}
return transform(classfileBuffer, instrumentationActions);
} } |
public class class_name {
private boolean changed(Address leader, Collection<Address> servers) {
Assert.notNull(servers, "servers");
Assert.argNot(servers.isEmpty(), "servers list cannot be empty");
if (this.leader != null && leader == null) {
return true;
} else if (this.leader == null && leader != null) {
Assert.arg(servers.contains(leader), "leader must be present in servers list");
return true;
} else if (this.leader != null && !this.leader.equals(leader)) {
Assert.arg(servers.contains(leader), "leader must be present in servers list");
return true;
} else if (!matches(this.servers, servers)) {
return true;
}
return false;
} } | public class class_name {
private boolean changed(Address leader, Collection<Address> servers) {
Assert.notNull(servers, "servers");
Assert.argNot(servers.isEmpty(), "servers list cannot be empty");
if (this.leader != null && leader == null) {
return true; // depends on control dependency: [if], data = [none]
} else if (this.leader == null && leader != null) {
Assert.arg(servers.contains(leader), "leader must be present in servers list"); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
} else if (this.leader != null && !this.leader.equals(leader)) {
Assert.arg(servers.contains(leader), "leader must be present in servers list"); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
} else if (!matches(this.servers, servers)) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
protected Object toMap(final LiquibaseSerializable object) {
if (object instanceof DatabaseObject) {
if (alreadySerializingObject) {
String snapshotId = ((DatabaseObject) object).getSnapshotId();
if (snapshotId == null) {
String name = ((DatabaseObject) object).getName();
Object table = ((DatabaseObject) object).getAttribute("table", Object.class);
if (table == null) {
table = ((DatabaseObject) object).getAttribute("relation", Object.class);
}
if (table != null) {
name = table.toString() + "." + name;
}
if (((DatabaseObject) object).getSchema() != null) {
name = ((DatabaseObject) object).getSchema().toString() + "." + name;
}
throw new UnexpectedLiquibaseException("Found a null snapshotId for " + StringUtil.lowerCaseFirst(object.getClass().getSimpleName()) + " " + name);
}
return ((DatabaseObject) object).getClass().getName() + "#" + snapshotId;
} else {
alreadySerializingObject = true;
Object map = super.toMap(object);
alreadySerializingObject = false;
return map;
}
}
if (object instanceof DatabaseObjectCollection) {
SortedMap<String, Object> returnMap = new TreeMap<>();
for (Map.Entry<Class<? extends DatabaseObject>, Set<? extends DatabaseObject>> entry : ((DatabaseObjectCollection) object).toMap().entrySet()) {
ArrayList value = new ArrayList(entry.getValue());
Collections.sort(value, new DatabaseObjectComparator());
returnMap.put(entry.getKey().getName(), value);
}
return returnMap;
}
return super.toMap(object);
} } | public class class_name {
@Override
protected Object toMap(final LiquibaseSerializable object) {
if (object instanceof DatabaseObject) {
if (alreadySerializingObject) {
String snapshotId = ((DatabaseObject) object).getSnapshotId();
if (snapshotId == null) {
String name = ((DatabaseObject) object).getName();
Object table = ((DatabaseObject) object).getAttribute("table", Object.class);
if (table == null) {
table = ((DatabaseObject) object).getAttribute("relation", Object.class); // depends on control dependency: [if], data = [none]
}
if (table != null) {
name = table.toString() + "." + name; // depends on control dependency: [if], data = [none]
}
if (((DatabaseObject) object).getSchema() != null) {
name = ((DatabaseObject) object).getSchema().toString() + "." + name; // depends on control dependency: [if], data = [none]
}
throw new UnexpectedLiquibaseException("Found a null snapshotId for " + StringUtil.lowerCaseFirst(object.getClass().getSimpleName()) + " " + name);
}
return ((DatabaseObject) object).getClass().getName() + "#" + snapshotId; // depends on control dependency: [if], data = [none]
} else {
alreadySerializingObject = true; // depends on control dependency: [if], data = [none]
Object map = super.toMap(object);
alreadySerializingObject = false; // depends on control dependency: [if], data = [none]
return map; // depends on control dependency: [if], data = [none]
}
}
if (object instanceof DatabaseObjectCollection) {
SortedMap<String, Object> returnMap = new TreeMap<>();
for (Map.Entry<Class<? extends DatabaseObject>, Set<? extends DatabaseObject>> entry : ((DatabaseObjectCollection) object).toMap().entrySet()) {
ArrayList value = new ArrayList(entry.getValue());
Collections.sort(value, new DatabaseObjectComparator());
returnMap.put(entry.getKey().getName(), value);
}
return returnMap;
}
return super.toMap(object);
} } |
public class class_name {
public void setDynamoDBTargets(java.util.Collection<DynamoDBTarget> dynamoDBTargets) {
if (dynamoDBTargets == null) {
this.dynamoDBTargets = null;
return;
}
this.dynamoDBTargets = new java.util.ArrayList<DynamoDBTarget>(dynamoDBTargets);
} } | public class class_name {
public void setDynamoDBTargets(java.util.Collection<DynamoDBTarget> dynamoDBTargets) {
if (dynamoDBTargets == null) {
this.dynamoDBTargets = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.dynamoDBTargets = new java.util.ArrayList<DynamoDBTarget>(dynamoDBTargets);
} } |
public class class_name {
static Class<?> getClassFromAttribute(FacesContext facesContext,
Object attribute) throws FacesException
{
// Attention!
// This code is duplicated in shared renderkit package.
// If you change something here please do the same in the other class!
Class<?> type = null;
// if there is a value, it must be a ...
// ... a ValueExpression that evaluates to a String or a Class
if (attribute instanceof ValueExpression)
{
// get the value of the ValueExpression
attribute = ((ValueExpression) attribute)
.getValue(facesContext.getELContext());
}
// ... String that is a fully qualified Java class name
if (attribute instanceof String)
{
try
{
type = Class.forName((String) attribute);
}
catch (ClassNotFoundException cnfe)
{
throw new FacesException(
"Unable to find class "
+ attribute
+ " on the classpath.", cnfe);
}
}
// ... a Class object
else if (attribute instanceof Class)
{
type = (Class<?>) attribute;
}
return type;
} } | public class class_name {
static Class<?> getClassFromAttribute(FacesContext facesContext,
Object attribute) throws FacesException
{
// Attention!
// This code is duplicated in shared renderkit package.
// If you change something here please do the same in the other class!
Class<?> type = null;
// if there is a value, it must be a ...
// ... a ValueExpression that evaluates to a String or a Class
if (attribute instanceof ValueExpression)
{
// get the value of the ValueExpression
attribute = ((ValueExpression) attribute)
.getValue(facesContext.getELContext());
}
// ... String that is a fully qualified Java class name
if (attribute instanceof String)
{
try
{
type = Class.forName((String) attribute); // depends on control dependency: [try], data = [none]
}
catch (ClassNotFoundException cnfe)
{
throw new FacesException(
"Unable to find class "
+ attribute
+ " on the classpath.", cnfe);
} // depends on control dependency: [catch], data = [none]
}
// ... a Class object
else if (attribute instanceof Class)
{
type = (Class<?>) attribute;
}
return type;
} } |
public class class_name {
public byte[] createSecret (PublicKeyCredentials pkcred, PrivateKey key, int length)
{
_data = new AuthResponseData();
byte[] clientSecret = pkcred.getSecret(key);
if (clientSecret == null) {
_data.code = FAILED_TO_SECURE;
return null;
}
byte[] secret = SecureUtil.createRandomKey(length);
_data.code = StringUtil.hexlate(SecureUtil.xorBytes(secret, clientSecret));
return secret;
} } | public class class_name {
public byte[] createSecret (PublicKeyCredentials pkcred, PrivateKey key, int length)
{
_data = new AuthResponseData();
byte[] clientSecret = pkcred.getSecret(key);
if (clientSecret == null) {
_data.code = FAILED_TO_SECURE; // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
byte[] secret = SecureUtil.createRandomKey(length);
_data.code = StringUtil.hexlate(SecureUtil.xorBytes(secret, clientSecret));
return secret;
} } |
public class class_name {
private Object processPropertyValue(Entity entity, String propName, final String dataType, final String syntax, Object ldapValue) throws WIMException {
if (DATA_TYPE_STRING.equals(dataType)) {
boolean octet = LDAP_ATTR_SYNTAX_OCTETSTRING.equalsIgnoreCase(syntax);
return getString(octet, ldapValue);
} else if (DATA_TYPE_DATE_TIME.equals(dataType)) {
return getDateString(ldapValue);
} else if (DATA_TYPE_DATE.equals(dataType)) {
return getDateObject(ldapValue);
} else if (DATA_TYPE_INT.equals(dataType)) {
return Integer.parseInt(ldapValue.toString());
} else if (DATA_TYPE_IDENTIFIER_TYPE.equals(dataType)) {
try {
String stringValue = (String) ldapValue;
LdapEntry ldapEntry = iLdapConn.getEntityByIdentifier(stringValue, null, null, null, null, false, false);
return createIdentiferFromLdapEntry(ldapEntry);
} catch (WIMException we) {
if (WIMMessageKey.LDAP_ENTRY_NOT_FOUND.equalsIgnoreCase(we.getMessageKey())) {
String msg = Tr.formatMessage(tc, WIMMessageKey.INVALID_PROPERTY_VALUE, WIMMessageHelper.generateMsgParms(propName, entity.getIdentifier().getExternalName()));
throw new WIMSystemException(WIMMessageKey.INVALID_PROPERTY_VALUE, msg);
} else {
throw we;
}
}
} else if (DATA_TYPE_BASE_64_BINARY.equals(dataType)) {
return ldapValue;
} else if (DATA_TYPE_LANG_TYPE.equals(dataType)) {
LangType lang = new LangType();
lang.setValue(String.valueOf(ldapValue));
return lang;
} else if (DATA_TYPE_BOOLEAN.equals(dataType)) {
return Boolean.parseBoolean(ldapValue.toString());
} else if (DATA_TYPE_LONG.equals(dataType)) { //PI05723
return Long.parseLong(ldapValue.toString());
} else {
if (tc.isEventEnabled()) {
Tr.event(tc, "Datatype for " + propName + " was null, process without casting");
}
return ldapValue;
}
} } | public class class_name {
private Object processPropertyValue(Entity entity, String propName, final String dataType, final String syntax, Object ldapValue) throws WIMException {
if (DATA_TYPE_STRING.equals(dataType)) {
boolean octet = LDAP_ATTR_SYNTAX_OCTETSTRING.equalsIgnoreCase(syntax);
return getString(octet, ldapValue);
} else if (DATA_TYPE_DATE_TIME.equals(dataType)) {
return getDateString(ldapValue);
} else if (DATA_TYPE_DATE.equals(dataType)) {
return getDateObject(ldapValue);
} else if (DATA_TYPE_INT.equals(dataType)) {
return Integer.parseInt(ldapValue.toString());
} else if (DATA_TYPE_IDENTIFIER_TYPE.equals(dataType)) {
try {
String stringValue = (String) ldapValue;
LdapEntry ldapEntry = iLdapConn.getEntityByIdentifier(stringValue, null, null, null, null, false, false);
return createIdentiferFromLdapEntry(ldapEntry); // depends on control dependency: [try], data = [none]
} catch (WIMException we) {
if (WIMMessageKey.LDAP_ENTRY_NOT_FOUND.equalsIgnoreCase(we.getMessageKey())) {
String msg = Tr.formatMessage(tc, WIMMessageKey.INVALID_PROPERTY_VALUE, WIMMessageHelper.generateMsgParms(propName, entity.getIdentifier().getExternalName()));
throw new WIMSystemException(WIMMessageKey.INVALID_PROPERTY_VALUE, msg);
} else {
throw we;
}
} // depends on control dependency: [catch], data = [none]
} else if (DATA_TYPE_BASE_64_BINARY.equals(dataType)) {
return ldapValue;
} else if (DATA_TYPE_LANG_TYPE.equals(dataType)) {
LangType lang = new LangType();
lang.setValue(String.valueOf(ldapValue));
return lang;
} else if (DATA_TYPE_BOOLEAN.equals(dataType)) {
return Boolean.parseBoolean(ldapValue.toString());
} else if (DATA_TYPE_LONG.equals(dataType)) { //PI05723
return Long.parseLong(ldapValue.toString());
} else {
if (tc.isEventEnabled()) {
Tr.event(tc, "Datatype for " + propName + " was null, process without casting"); // depends on control dependency: [if], data = [none]
}
return ldapValue;
}
} } |
public class class_name {
private IncompatibleTypes compareTypes(Type expectedType, Type actualType, boolean ignoreBaseType) {
// XXX equality not implemented for GenericObjectType
// if (parmType.equals(argType)) return true;
if (expectedType == actualType) {
return IncompatibleTypes.SEEMS_OK;
}
// Compare type signatures instead
String expectedString = GenericUtilities.getString(expectedType);
String actualString = GenericUtilities.getString(actualType);
if (expectedString.equals(actualString)) {
return IncompatibleTypes.SEEMS_OK;
}
if (expectedType.equals(Type.OBJECT))
{
return IncompatibleTypes.SEEMS_OK;
// if either type is java.lang.Object, then automatically true!
// again compare strings...
}
String objString = GenericUtilities.getString(Type.OBJECT);
if (expectedString.equals(objString)) {
return IncompatibleTypes.SEEMS_OK;
}
// get a category for each type
TypeCategory expectedCat = GenericUtilities.getTypeCategory(expectedType);
TypeCategory argCat = GenericUtilities.getTypeCategory(actualType);
if (actualString.equals(objString) && expectedCat == TypeCategory.TYPE_VARIABLE) {
return IncompatibleTypes.SEEMS_OK;
}
if (expectedCat == TypeCategory.WILDCARD) {
return IncompatibleTypes.SEEMS_OK;
}
if (ignoreBaseType) {
if (expectedCat == TypeCategory.PARAMETERIZED && argCat == TypeCategory.PARAMETERIZED) {
GenericObjectType parmGeneric = (GenericObjectType) expectedType;
GenericObjectType argGeneric = (GenericObjectType) actualType;
return compareTypeParameters(parmGeneric, argGeneric);
}
return IncompatibleTypes.SEEMS_OK;
}
if (actualType.equals(Type.OBJECT) && expectedCat == TypeCategory.ARRAY_TYPE) {
return IncompatibleTypes.ARRAY_AND_OBJECT;
}
// -~- plain objects are easy
if (expectedCat == TypeCategory.PLAIN_OBJECT_TYPE && argCat == TypeCategory.PLAIN_OBJECT_TYPE) {
return IncompatibleTypes.getPriorityForAssumingCompatible(expectedType, actualType, false);
}
if (expectedCat == TypeCategory.PARAMETERIZED && argCat == TypeCategory.PLAIN_OBJECT_TYPE) {
return IncompatibleTypes.getPriorityForAssumingCompatible((GenericObjectType) expectedType, actualType);
}
if (expectedCat == TypeCategory.PLAIN_OBJECT_TYPE && argCat == TypeCategory.PARAMETERIZED) {
return IncompatibleTypes.getPriorityForAssumingCompatible((GenericObjectType) actualType, expectedType);
}
// -~- parmType is: "? extends Another Type" OR "? super Another Type"
if (expectedCat == TypeCategory.WILDCARD_EXTENDS || expectedCat == TypeCategory.WILDCARD_SUPER) {
return compareTypes(((GenericObjectType) expectedType).getExtension(), actualType, ignoreBaseType);
}
// -~- Not handling type variables
if (expectedCat == TypeCategory.TYPE_VARIABLE || argCat == TypeCategory.TYPE_VARIABLE) {
return IncompatibleTypes.SEEMS_OK;
}
// -~- Array Types: compare dimensions, then base type
if (expectedCat == TypeCategory.ARRAY_TYPE && argCat == TypeCategory.ARRAY_TYPE) {
ArrayType parmArray = (ArrayType) expectedType;
ArrayType argArray = (ArrayType) actualType;
if (parmArray.getDimensions() != argArray.getDimensions()) {
return IncompatibleTypes.ARRAY_AND_NON_ARRAY;
}
return compareTypes(parmArray.getBasicType(), argArray.getBasicType(), ignoreBaseType);
}
// If one is an Array Type and the other is not, then they
// are incompatible. (We already know neither is java.lang.Object)
if (expectedCat == TypeCategory.ARRAY_TYPE ^ argCat == TypeCategory.ARRAY_TYPE) {
return IncompatibleTypes.ARRAY_AND_NON_ARRAY;
}
// -~- Parameter Types: compare base type then parameters
if (expectedCat == TypeCategory.PARAMETERIZED && argCat == TypeCategory.PARAMETERIZED) {
GenericObjectType parmGeneric = (GenericObjectType) expectedType;
GenericObjectType argGeneric = (GenericObjectType) actualType;
// base types should be related
{
IncompatibleTypes result = compareTypes(parmGeneric.getObjectType(), argGeneric.getObjectType(), ignoreBaseType);
if (!result.equals(IncompatibleTypes.SEEMS_OK)) {
return result;
}
}
return compareTypeParameters(parmGeneric, argGeneric);
// XXX More to come
}
// -~- Wildcard e.g. List<*>.contains(...)
if (expectedCat == TypeCategory.WILDCARD) {
return IncompatibleTypes.SEEMS_OK;
}
// -~- Non Reference types
// if ( parmCat == TypeCategory.NON_REFERENCE_TYPE ||
// argCat == TypeCategory.NON_REFERENCE_TYPE )
if (expectedType instanceof BasicType || actualType instanceof BasicType) {
// this should not be possible, compiler will complain (pre 1.5)
// or autobox primitive types (1.5 +)
throw new IllegalArgumentException("checking for compatibility of " + expectedType + " with " + actualType);
}
return IncompatibleTypes.SEEMS_OK;
} } | public class class_name {
private IncompatibleTypes compareTypes(Type expectedType, Type actualType, boolean ignoreBaseType) {
// XXX equality not implemented for GenericObjectType
// if (parmType.equals(argType)) return true;
if (expectedType == actualType) {
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
}
// Compare type signatures instead
String expectedString = GenericUtilities.getString(expectedType);
String actualString = GenericUtilities.getString(actualType);
if (expectedString.equals(actualString)) {
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
}
if (expectedType.equals(Type.OBJECT))
{
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
// if either type is java.lang.Object, then automatically true!
// again compare strings...
}
String objString = GenericUtilities.getString(Type.OBJECT);
if (expectedString.equals(objString)) {
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
}
// get a category for each type
TypeCategory expectedCat = GenericUtilities.getTypeCategory(expectedType);
TypeCategory argCat = GenericUtilities.getTypeCategory(actualType);
if (actualString.equals(objString) && expectedCat == TypeCategory.TYPE_VARIABLE) {
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
}
if (expectedCat == TypeCategory.WILDCARD) {
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
}
if (ignoreBaseType) {
if (expectedCat == TypeCategory.PARAMETERIZED && argCat == TypeCategory.PARAMETERIZED) {
GenericObjectType parmGeneric = (GenericObjectType) expectedType;
GenericObjectType argGeneric = (GenericObjectType) actualType;
return compareTypeParameters(parmGeneric, argGeneric); // depends on control dependency: [if], data = [none]
}
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
}
if (actualType.equals(Type.OBJECT) && expectedCat == TypeCategory.ARRAY_TYPE) {
return IncompatibleTypes.ARRAY_AND_OBJECT; // depends on control dependency: [if], data = [none]
}
// -~- plain objects are easy
if (expectedCat == TypeCategory.PLAIN_OBJECT_TYPE && argCat == TypeCategory.PLAIN_OBJECT_TYPE) {
return IncompatibleTypes.getPriorityForAssumingCompatible(expectedType, actualType, false); // depends on control dependency: [if], data = [none]
}
if (expectedCat == TypeCategory.PARAMETERIZED && argCat == TypeCategory.PLAIN_OBJECT_TYPE) {
return IncompatibleTypes.getPriorityForAssumingCompatible((GenericObjectType) expectedType, actualType); // depends on control dependency: [if], data = [none]
}
if (expectedCat == TypeCategory.PLAIN_OBJECT_TYPE && argCat == TypeCategory.PARAMETERIZED) {
return IncompatibleTypes.getPriorityForAssumingCompatible((GenericObjectType) actualType, expectedType); // depends on control dependency: [if], data = [none]
}
// -~- parmType is: "? extends Another Type" OR "? super Another Type"
if (expectedCat == TypeCategory.WILDCARD_EXTENDS || expectedCat == TypeCategory.WILDCARD_SUPER) {
return compareTypes(((GenericObjectType) expectedType).getExtension(), actualType, ignoreBaseType); // depends on control dependency: [if], data = [none]
}
// -~- Not handling type variables
if (expectedCat == TypeCategory.TYPE_VARIABLE || argCat == TypeCategory.TYPE_VARIABLE) {
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
}
// -~- Array Types: compare dimensions, then base type
if (expectedCat == TypeCategory.ARRAY_TYPE && argCat == TypeCategory.ARRAY_TYPE) {
ArrayType parmArray = (ArrayType) expectedType;
ArrayType argArray = (ArrayType) actualType;
if (parmArray.getDimensions() != argArray.getDimensions()) {
return IncompatibleTypes.ARRAY_AND_NON_ARRAY; // depends on control dependency: [if], data = [none]
}
return compareTypes(parmArray.getBasicType(), argArray.getBasicType(), ignoreBaseType); // depends on control dependency: [if], data = [none]
}
// If one is an Array Type and the other is not, then they
// are incompatible. (We already know neither is java.lang.Object)
if (expectedCat == TypeCategory.ARRAY_TYPE ^ argCat == TypeCategory.ARRAY_TYPE) {
return IncompatibleTypes.ARRAY_AND_NON_ARRAY; // depends on control dependency: [if], data = [none]
}
// -~- Parameter Types: compare base type then parameters
if (expectedCat == TypeCategory.PARAMETERIZED && argCat == TypeCategory.PARAMETERIZED) {
GenericObjectType parmGeneric = (GenericObjectType) expectedType;
GenericObjectType argGeneric = (GenericObjectType) actualType;
// base types should be related
{
IncompatibleTypes result = compareTypes(parmGeneric.getObjectType(), argGeneric.getObjectType(), ignoreBaseType);
if (!result.equals(IncompatibleTypes.SEEMS_OK)) {
return result; // depends on control dependency: [if], data = [none]
}
}
return compareTypeParameters(parmGeneric, argGeneric); // depends on control dependency: [if], data = [none]
// XXX More to come
}
// -~- Wildcard e.g. List<*>.contains(...)
if (expectedCat == TypeCategory.WILDCARD) {
return IncompatibleTypes.SEEMS_OK; // depends on control dependency: [if], data = [none]
}
// -~- Non Reference types
// if ( parmCat == TypeCategory.NON_REFERENCE_TYPE ||
// argCat == TypeCategory.NON_REFERENCE_TYPE )
if (expectedType instanceof BasicType || actualType instanceof BasicType) {
// this should not be possible, compiler will complain (pre 1.5)
// or autobox primitive types (1.5 +)
throw new IllegalArgumentException("checking for compatibility of " + expectedType + " with " + actualType);
}
return IncompatibleTypes.SEEMS_OK;
} } |
public class class_name {
@Override
public void delete(final String counterName)
{
Preconditions.checkNotNull(counterName);
Preconditions.checkArgument(!StringUtils.isBlank(counterName));
// Delete the main counter in a new TX...
ObjectifyService.ofy().transactNew(new VoidWork()
{
@Override
public void vrun()
{
// Load in a TX so that two threads don't mark the counter as deleted at the same time.
final Key<CounterData> counterDataKey = CounterData.key(counterName);
final CounterData counterData = ObjectifyService.ofy().load().key(counterDataKey).now();
if (counterData == null)
{
// We throw an exception here so that callers can be aware that the deletion failed. In the
// task-queue, however, no exception is thrown since failing to delete something that's not there
// can be treated the same as succeeding at deleting something that's there.
throw new NoCounterExistsException(counterName);
}
Queue queue;
if (config.getDeleteCounterShardQueueName() == null)
{
queue = QueueFactory.getDefaultQueue();
}
else
{
queue = QueueFactory.getQueue(config.getDeleteCounterShardQueueName());
}
// The TaskQueue will delete the counter once all shards are deleted.
counterData.setCounterStatus(CounterData.CounterStatus.DELETING);
// Call this Async so that the rest of the thread can
// continue. Everything will block till commit is called.
ObjectifyService.ofy().save().entity(counterData);
// Transactionally enqueue this task to the path specified in the constructor (if this is null, then the
// default queue will be used).
TaskOptions taskOptions = TaskOptions.Builder.withParam(COUNTER_NAME, counterName);
if (config.getRelativeUrlPathForDeleteTaskQueue() != null)
{
taskOptions = taskOptions.url(config.getRelativeUrlPathForDeleteTaskQueue());
}
// Kick off a Task to delete the Shards for this CounterData and the CounterData itself, but only if the
// overall TX commit succeeds
queue.add(taskOptions);
}
});
} } | public class class_name {
@Override
public void delete(final String counterName)
{
Preconditions.checkNotNull(counterName);
Preconditions.checkArgument(!StringUtils.isBlank(counterName));
// Delete the main counter in a new TX...
ObjectifyService.ofy().transactNew(new VoidWork()
{
@Override
public void vrun()
{
// Load in a TX so that two threads don't mark the counter as deleted at the same time.
final Key<CounterData> counterDataKey = CounterData.key(counterName);
final CounterData counterData = ObjectifyService.ofy().load().key(counterDataKey).now();
if (counterData == null)
{
// We throw an exception here so that callers can be aware that the deletion failed. In the
// task-queue, however, no exception is thrown since failing to delete something that's not there
// can be treated the same as succeeding at deleting something that's there.
throw new NoCounterExistsException(counterName);
}
Queue queue;
if (config.getDeleteCounterShardQueueName() == null)
{
queue = QueueFactory.getDefaultQueue(); // depends on control dependency: [if], data = [none]
}
else
{
queue = QueueFactory.getQueue(config.getDeleteCounterShardQueueName()); // depends on control dependency: [if], data = [(config.getDeleteCounterShardQueueName()]
}
// The TaskQueue will delete the counter once all shards are deleted.
counterData.setCounterStatus(CounterData.CounterStatus.DELETING);
// Call this Async so that the rest of the thread can
// continue. Everything will block till commit is called.
ObjectifyService.ofy().save().entity(counterData);
// Transactionally enqueue this task to the path specified in the constructor (if this is null, then the
// default queue will be used).
TaskOptions taskOptions = TaskOptions.Builder.withParam(COUNTER_NAME, counterName);
if (config.getRelativeUrlPathForDeleteTaskQueue() != null)
{
taskOptions = taskOptions.url(config.getRelativeUrlPathForDeleteTaskQueue()); // depends on control dependency: [if], data = [(config.getRelativeUrlPathForDeleteTaskQueue()]
}
// Kick off a Task to delete the Shards for this CounterData and the CounterData itself, but only if the
// overall TX commit succeeds
queue.add(taskOptions);
}
});
} } |
public class class_name {
public RemoteIterator<LocatedFileStatus> listPathWithLocation(
final String src) throws IOException {
checkOpen();
try {
if (namenodeProtocolProxy == null) {
return versionBasedListPathWithLocation(src);
}
return methodBasedListPathWithLocation(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class);
}
} } | public class class_name {
public RemoteIterator<LocatedFileStatus> listPathWithLocation(
final String src) throws IOException {
checkOpen();
try {
if (namenodeProtocolProxy == null) {
return versionBasedListPathWithLocation(src); // depends on control dependency: [if], data = [none]
}
return methodBasedListPathWithLocation(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class);
}
} } |
public class class_name {
protected void regenerateMetrics() {
// Set up the metrics that are enabled regardless of instrumentation
this.recordsIn = this.metricContext.meter(MetricNames.DataWriterMetrics.RECORDS_IN_METER);
this.recordsAttempted = this.metricContext.meter(MetricNames.DataWriterMetrics.RECORDS_ATTEMPTED_METER);
this.recordsSuccess = this.metricContext.meter(MetricNames.DataWriterMetrics.SUCCESSFUL_WRITES_METER);
this.recordsFailed = this.metricContext.meter(MetricNames.DataWriterMetrics.FAILED_WRITES_METER);
this.bytesWritten = this.metricContext.meter(MetricNames.DataWriterMetrics.BYTES_WRITTEN_METER);
if (isInstrumentationEnabled()) {
this.dataWriterTimer = Optional.<Timer>of(this.metricContext.timer(MetricNames.DataWriterMetrics.WRITE_TIMER));
} else {
this.dataWriterTimer = Optional.absent();
}
} } | public class class_name {
protected void regenerateMetrics() {
// Set up the metrics that are enabled regardless of instrumentation
this.recordsIn = this.metricContext.meter(MetricNames.DataWriterMetrics.RECORDS_IN_METER);
this.recordsAttempted = this.metricContext.meter(MetricNames.DataWriterMetrics.RECORDS_ATTEMPTED_METER);
this.recordsSuccess = this.metricContext.meter(MetricNames.DataWriterMetrics.SUCCESSFUL_WRITES_METER);
this.recordsFailed = this.metricContext.meter(MetricNames.DataWriterMetrics.FAILED_WRITES_METER);
this.bytesWritten = this.metricContext.meter(MetricNames.DataWriterMetrics.BYTES_WRITTEN_METER);
if (isInstrumentationEnabled()) {
this.dataWriterTimer = Optional.<Timer>of(this.metricContext.timer(MetricNames.DataWriterMetrics.WRITE_TIMER)); // depends on control dependency: [if], data = [none]
} else {
this.dataWriterTimer = Optional.absent(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static ZMsg recvMsg(Socket socket, int flag)
{
if (socket == null) {
throw new IllegalArgumentException("socket is null");
}
ZMsg msg = new ZMsg();
while (true) {
ZFrame f = ZFrame.recvFrame(socket, flag);
if (f == null) {
// If receive failed or was interrupted
msg.destroy();
msg = null;
break;
}
msg.add(f);
if (!f.hasMore()) {
break;
}
}
return msg;
} } | public class class_name {
public static ZMsg recvMsg(Socket socket, int flag)
{
if (socket == null) {
throw new IllegalArgumentException("socket is null");
}
ZMsg msg = new ZMsg();
while (true) {
ZFrame f = ZFrame.recvFrame(socket, flag);
if (f == null) {
// If receive failed or was interrupted
msg.destroy(); // depends on control dependency: [if], data = [none]
msg = null; // depends on control dependency: [if], data = [none]
break;
}
msg.add(f); // depends on control dependency: [while], data = [none]
if (!f.hasMore()) {
break;
}
}
return msg;
} } |
public class class_name {
public void lookupDataSet(final DataSetDef def,
final DataSetLookup request,
final DataSetReadyCallback listener) throws Exception {
if (dataSetLookupServices != null) {
try {
dataSetLookupServices.call(
new RemoteCallback<DataSet>() {
public void callback(DataSet result) {
if (result == null) {
listener.notFound();
} else {
listener.callback(result);
}
}
},
new ErrorCallback<Message>() {
@Override
public boolean error(Message message,
Throwable throwable) {
return listener.onError(new ClientRuntimeError(throwable));
}
})
.lookupDataSet(def,
request);
} catch (Exception e) {
listener.onError(new ClientRuntimeError(e));
}
}
// Data set not found on client.
else {
listener.notFound();
}
} } | public class class_name {
public void lookupDataSet(final DataSetDef def,
final DataSetLookup request,
final DataSetReadyCallback listener) throws Exception {
if (dataSetLookupServices != null) {
try {
dataSetLookupServices.call(
new RemoteCallback<DataSet>() {
public void callback(DataSet result) {
if (result == null) {
listener.notFound(); // depends on control dependency: [if], data = [none]
} else {
listener.callback(result); // depends on control dependency: [if], data = [(result]
}
}
},
new ErrorCallback<Message>() {
@Override
public boolean error(Message message,
Throwable throwable) {
return listener.onError(new ClientRuntimeError(throwable));
}
})
.lookupDataSet(def,
request);
} catch (Exception e) {
listener.onError(new ClientRuntimeError(e));
}
}
// Data set not found on client.
else {
listener.notFound();
}
} } |
public class class_name {
public Selector parseSelector(String selectorString,
SelectorDomain domain)
throws SISelectorSyntaxException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "parseSelector", new Object[] { selectorString, domain });
Selector selectorTree = null;
Transformer transformer = Matching.getTransformer();
Resolver resolver = null;
try
{
// Synchronization block to protect the parser object from being reset
// whilst in use.
synchronized (this)
{
MatchParser parser = null;
if(domain.equals(SelectorDomain.JMS))
{
// Set the correct resolver
resolver = _jmsResolver;
// Drive the parser
_sibParser = _matching.primeMatchParser(_sibParser,
selectorString,
SelectorDomain.JMS.toInt());
parser = _sibParser;
}
else if(domain.equals(SelectorDomain.SIMESSAGE))
{
// Set the correct resolver
resolver = _simessageResolver;
// Drive the parser
_sibParser = _matching.primeMatchParser(_sibParser,
selectorString,
SelectorDomain.SIMESSAGE.toInt());
parser = _sibParser;
}
else // In the XPath1.0 case we use the default resolver
{
// Set the correct resolver
resolver = _defaultResolver;
// Drive the parser
_xpathParser = _matching.primeMatchParser(_xpathParser,
selectorString,
SelectorDomain.XPATH1.toInt());
parser = _xpathParser;
}
// We're ready to parse the selector
if(disableXPathOptimizer && domain.equals(SelectorDomain.XPATH1))
{
// In this special case we'll disable the MatchSpace XPath
// optimizations and process XPath expressions as whole entities.
XPath10Parser xpParser = (XPath10Parser)parser;
selectorTree = xpParser.parseWholeSelector(selectorString);
}
else
{
// Parse in the usual manner
selectorTree = parser.getSelector(selectorString);
}
// Check that the selector parsed ok.
if (selectorTree.getType() == Selector.INVALID)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "parseSelector", "SISelectorSyntaxException");
throw new SISelectorSyntaxException(
nls.getFormattedMessage(
"INVALID_SELECTOR_ERROR_CWSIP0371",
new Object[] { selectorString },
null));
}
selectorTree = transformer.resolve(selectorTree, resolver, _positionAssigner);
// Check that the selector resolved ok.
if (selectorTree.getType() == Selector.INVALID)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "parseSelector", "SISelectorSyntaxException");
throw new SISelectorSyntaxException(
nls.getFormattedMessage(
"INVALID_SELECTOR_ERROR_CWSIP0371",
new Object[] { selectorString },
null));
}
}
}
catch (RuntimeException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching.parseSelector",
"1:1741:1.117.1.11",
this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "parseSelector", "SISelectorSyntaxException");
throw new SISelectorSyntaxException(
nls.getFormattedMessage(
"INVALID_SELECTOR_ERROR_CWSIP0371",
new Object[] { null },
null));
}
catch (MatchingException e)
{
// No FFDC code needed
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "parseSelector", "SISelectorSyntaxException");
throw new SISelectorSyntaxException(
nls.getFormattedMessage(
"INVALID_SELECTOR_ERROR_CWSIP0376",
new Object[] { e },
null));
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "parseSelector", selectorTree);
return selectorTree;
} } | public class class_name {
public Selector parseSelector(String selectorString,
SelectorDomain domain)
throws SISelectorSyntaxException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "parseSelector", new Object[] { selectorString, domain });
Selector selectorTree = null;
Transformer transformer = Matching.getTransformer();
Resolver resolver = null;
try
{
// Synchronization block to protect the parser object from being reset
// whilst in use.
synchronized (this) // depends on control dependency: [try], data = [none]
{
MatchParser parser = null;
if(domain.equals(SelectorDomain.JMS))
{
// Set the correct resolver
resolver = _jmsResolver; // depends on control dependency: [if], data = [none]
// Drive the parser
_sibParser = _matching.primeMatchParser(_sibParser,
selectorString,
SelectorDomain.JMS.toInt()); // depends on control dependency: [if], data = [none]
parser = _sibParser; // depends on control dependency: [if], data = [none]
}
else if(domain.equals(SelectorDomain.SIMESSAGE))
{
// Set the correct resolver
resolver = _simessageResolver; // depends on control dependency: [if], data = [none]
// Drive the parser
_sibParser = _matching.primeMatchParser(_sibParser,
selectorString,
SelectorDomain.SIMESSAGE.toInt()); // depends on control dependency: [if], data = [none]
parser = _sibParser; // depends on control dependency: [if], data = [none]
}
else // In the XPath1.0 case we use the default resolver
{
// Set the correct resolver
resolver = _defaultResolver; // depends on control dependency: [if], data = [none]
// Drive the parser
_xpathParser = _matching.primeMatchParser(_xpathParser,
selectorString,
SelectorDomain.XPATH1.toInt()); // depends on control dependency: [if], data = [none]
parser = _xpathParser; // depends on control dependency: [if], data = [none]
}
// We're ready to parse the selector
if(disableXPathOptimizer && domain.equals(SelectorDomain.XPATH1))
{
// In this special case we'll disable the MatchSpace XPath
// optimizations and process XPath expressions as whole entities.
XPath10Parser xpParser = (XPath10Parser)parser;
selectorTree = xpParser.parseWholeSelector(selectorString); // depends on control dependency: [if], data = [none]
}
else
{
// Parse in the usual manner
selectorTree = parser.getSelector(selectorString); // depends on control dependency: [if], data = [none]
}
// Check that the selector parsed ok.
if (selectorTree.getType() == Selector.INVALID)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "parseSelector", "SISelectorSyntaxException");
throw new SISelectorSyntaxException(
nls.getFormattedMessage(
"INVALID_SELECTOR_ERROR_CWSIP0371",
new Object[] { selectorString },
null));
}
selectorTree = transformer.resolve(selectorTree, resolver, _positionAssigner);
// Check that the selector resolved ok.
if (selectorTree.getType() == Selector.INVALID)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "parseSelector", "SISelectorSyntaxException");
throw new SISelectorSyntaxException(
nls.getFormattedMessage(
"INVALID_SELECTOR_ERROR_CWSIP0371",
new Object[] { selectorString },
null));
}
}
}
catch (RuntimeException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching.parseSelector",
"1:1741:1.117.1.11",
this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "parseSelector", "SISelectorSyntaxException");
throw new SISelectorSyntaxException(
nls.getFormattedMessage(
"INVALID_SELECTOR_ERROR_CWSIP0371",
new Object[] { null },
null));
} // depends on control dependency: [catch], data = [none]
catch (MatchingException e)
{
// No FFDC code needed
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "parseSelector", "SISelectorSyntaxException");
throw new SISelectorSyntaxException(
nls.getFormattedMessage(
"INVALID_SELECTOR_ERROR_CWSIP0376",
new Object[] { e },
null));
} // depends on control dependency: [catch], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "parseSelector", selectorTree);
return selectorTree;
} } |
public class class_name {
public static Basic2DMatrix diagonal(int size, double diagonal) {
double[][] array = new double[size][size];
for (int i = 0; i < size; i++) {
array[i][i] = diagonal;
}
return new Basic2DMatrix(array);
} } | public class class_name {
public static Basic2DMatrix diagonal(int size, double diagonal) {
double[][] array = new double[size][size];
for (int i = 0; i < size; i++) {
array[i][i] = diagonal; // depends on control dependency: [for], data = [i]
}
return new Basic2DMatrix(array);
} } |
public class class_name {
public double calculateGHEffectiveAtomPolarizability(IAtomContainer atomContainer, IAtom atom,
int influenceSphereCutOff, boolean addExplicitH) {
double polarizabilitiy = 0;
IAtomContainer acH;
if (addExplicitH) {
acH = atomContainer.getBuilder().newInstance(IAtomContainer.class, atomContainer);
addExplicitHydrogens(acH);
} else {
acH = atomContainer;
}
List<IAtom> startAtom = new ArrayList<>(1);
startAtom.add(0, atom);
double bond;
polarizabilitiy += getKJPolarizabilityFactor(acH, atom);
for (int i = 0; i < acH.getAtomCount(); i++) {
if (!acH.getAtom(i).equals(atom)) {
bond = PathTools.breadthFirstTargetSearch(acH, startAtom, acH.getAtom(i), 0, influenceSphereCutOff);
if (bond == 1) {
polarizabilitiy += getKJPolarizabilityFactor(acH, acH.getAtom(i));
} else {
polarizabilitiy += (Math.pow(0.5, bond - 1) * getKJPolarizabilityFactor(acH, acH.getAtom(i)));
}//if bond==0
}//if !=atom
}//for
return polarizabilitiy;
} } | public class class_name {
public double calculateGHEffectiveAtomPolarizability(IAtomContainer atomContainer, IAtom atom,
int influenceSphereCutOff, boolean addExplicitH) {
double polarizabilitiy = 0;
IAtomContainer acH;
if (addExplicitH) {
acH = atomContainer.getBuilder().newInstance(IAtomContainer.class, atomContainer); // depends on control dependency: [if], data = [none]
addExplicitHydrogens(acH); // depends on control dependency: [if], data = [none]
} else {
acH = atomContainer; // depends on control dependency: [if], data = [none]
}
List<IAtom> startAtom = new ArrayList<>(1);
startAtom.add(0, atom);
double bond;
polarizabilitiy += getKJPolarizabilityFactor(acH, atom);
for (int i = 0; i < acH.getAtomCount(); i++) {
if (!acH.getAtom(i).equals(atom)) {
bond = PathTools.breadthFirstTargetSearch(acH, startAtom, acH.getAtom(i), 0, influenceSphereCutOff); // depends on control dependency: [if], data = [none]
if (bond == 1) {
polarizabilitiy += getKJPolarizabilityFactor(acH, acH.getAtom(i)); // depends on control dependency: [if], data = [none]
} else {
polarizabilitiy += (Math.pow(0.5, bond - 1) * getKJPolarizabilityFactor(acH, acH.getAtom(i))); // depends on control dependency: [if], data = [1)]
}//if bond==0
}//if !=atom
}//for
return polarizabilitiy;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.