code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public boolean preValidateTopic(final SpecTopic specTopic, final Map<String, SpecTopic> specTopics,
final Set<String> processedFixedUrls, final BookType bookType, boolean allowRelationships, final ContentSpec contentSpec) {
// Check if the app should be shutdown
if (isShuttingDown.get()) {
shutdown.set(true);
return false;
}
boolean valid = true;
// Checks that the id isn't null and is a valid topic ID
if (specTopic.getId() == null || !specTopic.getId().matches(CSConstants.ALL_TOPIC_ID_REGEX)) {
log.error(String.format(ProcessorConstants.ERROR_INVALID_TOPIC_ID_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
if ((bookType == BookType.BOOK || bookType == BookType.BOOK_DRAFT) && specTopic.getParent() instanceof Level) {
final Level parent = (Level) specTopic.getParent();
// Check that the topic is inside a chapter/section/process/appendix/part/preface
final LevelType parentLevelType = parent.getLevelType();
if (parent == null || parentLevelType == LevelType.BASE) {
log.error(format(ProcessorConstants.ERROR_TOPIC_OUTSIDE_CHAPTER_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that there are no levels in the parent part (ie the topic is in the intro)
if (parent != null && parentLevelType == LevelType.PART) {
final List<Node> parentChildren = parent.getChildNodes();
final int index = parentChildren.indexOf(specTopic);
for (int i = 0; i < index; i++) {
final Node node = parentChildren.get(i);
if (node instanceof Level && ((Level) node).getLevelType() != LevelType.INITIAL_CONTENT) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NOT_IN_PART_INTRO_MSG, specTopic.getLineNumber(),
specTopic.getText()));
valid = false;
break;
}
}
}
}
// Check that the title exists
if (isNullOrEmpty(specTopic.getTitle())) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TITLE_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that we aren't using translations for anything but existing topics
if (!specTopic.isTopicAnExistingTopic()) {
// Check that we aren't processing translations
if (processingOptions.isTranslation()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_NEW_TRANSLATION_TOPIC, specTopic.getLineNumber(),
specTopic.getText()));
valid = false;
}
}
// Check that the initial content topic doesn't have a fixed url and if it does then print a warning,
// otherwise check that the fixed url is valid
if (specTopic.getTopicType() == TopicType.INITIAL_CONTENT && !isNullOrEmpty(specTopic.getFixedUrl())) {
log.warn(format(ProcessorConstants.WARN_FIXED_URL_WILL_BE_IGNORED_MSG, specTopic.getLineNumber(), specTopic.getText()));
specTopic.setFixedUrl(null);
} else if (!isNullOrEmpty(specTopic.getFixedUrl())) {
if (!validateFixedUrl(specTopic, processedFixedUrls)) {
valid = false;
} else {
processedFixedUrls.add(specTopic.getFixedUrl());
}
}
// Check that we are allowed to create new topics
if (!specTopic.isTopicAnExistingTopic() && !processingOptions.isAllowNewTopics()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_NEW_TOPIC_BUILD, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// New Topics
if (specTopic.isTopicANewTopic()) {
if (isNullOrEmpty(specTopic.getType())) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TYPE_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Existing Topics
} else if (specTopic.isTopicAnExistingTopic()) {
// Check that tags aren't trying to be removed
if (!specTopic.getRemoveTags(false).isEmpty()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_EXISTING_TOPIC_CANNOT_REMOVE_TAGS, specTopic.getLineNumber(),
specTopic.getText()));
valid = false;
}
// Check that tags aren't trying to be added to a revision
if (processingOptions.isPrintChangeWarnings() && specTopic.getRevision() != null && !specTopic.getTags(false).isEmpty()) {
log.warn(
String.format(ProcessorConstants.WARN_TAGS_IGNORE_MSG, specTopic.getLineNumber(), "revision", specTopic.getText()));
}
// Check that urls aren't trying to be added
if (!specTopic.getSourceUrls(false).isEmpty()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_EXISTING_TOPIC_CANNOT_ADD_SOURCE_URLS, specTopic.getLineNumber(),
specTopic.getText()));
valid = false;
}
// Check that the assigned writer and description haven't been set
if (specTopic.getAssignedWriter(false) != null || specTopic.getDescription(false) != null) {
log.error(
String.format(ProcessorConstants.ERROR_TOPIC_EXISTING_BAD_OPTIONS, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that we aren't processing translations
if (!specTopic.getTags(true).isEmpty() && processingOptions.isTranslation()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TAGS_TRANSLATION_TOPIC, specTopic.getLineNumber(),
specTopic.getText()));
valid = false;
}
}
// Duplicated Topics
else if (specTopic.isTopicADuplicateTopic()) {
String temp = "N" + specTopic.getId().substring(1);
// Check that the topic exists in the content specification
if (!specTopics.containsKey(temp)) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
} else {
// Check that the topic titles match the original
if (!specTopic.getTitle().equals(specTopics.get(temp).getTitle())) {
String topicTitleMsg = "Topic " + specTopic.getId() + ": " + specTopics.get(temp).getTitle();
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TITLES_NONMATCH_MSG, specTopic.getLineNumber(),
specTopic.getText(), topicTitleMsg));
valid = false;
}
}
// Cloned Topics
} else if (specTopic.isTopicAClonedTopic()) {
// Check if a description or type exists. If one does then generate an error.
if ((specTopic.getType() != null && !specTopic.getType().equals("")) || (specTopic.getDescription(
false) != null && !specTopic.getDescription(false).equals(""))) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_CLONED_BAD_OPTIONS, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Duplicated Cloned Topics
} else if (specTopic.isTopicAClonedDuplicateTopic()) {
// Find the duplicate topic in the content spec
final String topicId = specTopic.getId().substring(1);
int count = 0;
SpecTopic clonedTopic = null;
for (final Entry<String, SpecTopic> entry : specTopics.entrySet()) {
final String uniqueTopicId = entry.getKey();
if (uniqueTopicId.endsWith(topicId) && !uniqueTopicId.endsWith(specTopic.getId())) {
clonedTopic = entry.getValue();
count++;
}
}
// Check that the topic exists
if (count == 0) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check that the referenced topic is unique
else if (count > 1) {
log.error(
String.format(ProcessorConstants.ERROR_TOPIC_DUPLICATE_CLONES_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
} else {
// Check that the title matches
if (!specTopic.getTitle().equals(clonedTopic.getTitle())) {
String topicTitleMsg = "Topic " + specTopic.getId() + ": " + clonedTopic.getTitle();
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TITLES_NONMATCH_MSG, specTopic.getLineNumber(),
specTopic.getText(), topicTitleMsg));
valid = false;
}
}
}
// Check to make sure no relationships exist if they aren't allowed
if (!allowRelationships && specTopic.getRelationships().size() > 0) {
log.error(format(ProcessorConstants.ERROR_TOPIC_HAS_RELATIONSHIPS_MSG, specTopic.getLineNumber(), specTopic.getText()));
valid = false;
}
// Check for conflicting conditions
checkForConflictingCondition(specTopic, contentSpec);
return valid;
} } | public class class_name {
public boolean preValidateTopic(final SpecTopic specTopic, final Map<String, SpecTopic> specTopics,
final Set<String> processedFixedUrls, final BookType bookType, boolean allowRelationships, final ContentSpec contentSpec) {
// Check if the app should be shutdown
if (isShuttingDown.get()) {
shutdown.set(true); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
boolean valid = true;
// Checks that the id isn't null and is a valid topic ID
if (specTopic.getId() == null || !specTopic.getId().matches(CSConstants.ALL_TOPIC_ID_REGEX)) {
log.error(String.format(ProcessorConstants.ERROR_INVALID_TOPIC_ID_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
if ((bookType == BookType.BOOK || bookType == BookType.BOOK_DRAFT) && specTopic.getParent() instanceof Level) {
final Level parent = (Level) specTopic.getParent();
// Check that the topic is inside a chapter/section/process/appendix/part/preface
final LevelType parentLevelType = parent.getLevelType();
if (parent == null || parentLevelType == LevelType.BASE) {
log.error(format(ProcessorConstants.ERROR_TOPIC_OUTSIDE_CHAPTER_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Check that there are no levels in the parent part (ie the topic is in the intro)
if (parent != null && parentLevelType == LevelType.PART) {
final List<Node> parentChildren = parent.getChildNodes();
final int index = parentChildren.indexOf(specTopic);
for (int i = 0; i < index; i++) {
final Node node = parentChildren.get(i);
if (node instanceof Level && ((Level) node).getLevelType() != LevelType.INITIAL_CONTENT) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NOT_IN_PART_INTRO_MSG, specTopic.getLineNumber(),
specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
break;
}
}
}
}
// Check that the title exists
if (isNullOrEmpty(specTopic.getTitle())) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TITLE_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Check that we aren't using translations for anything but existing topics
if (!specTopic.isTopicAnExistingTopic()) {
// Check that we aren't processing translations
if (processingOptions.isTranslation()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_NEW_TRANSLATION_TOPIC, specTopic.getLineNumber(),
specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
}
// Check that the initial content topic doesn't have a fixed url and if it does then print a warning,
// otherwise check that the fixed url is valid
if (specTopic.getTopicType() == TopicType.INITIAL_CONTENT && !isNullOrEmpty(specTopic.getFixedUrl())) {
log.warn(format(ProcessorConstants.WARN_FIXED_URL_WILL_BE_IGNORED_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
specTopic.setFixedUrl(null); // depends on control dependency: [if], data = [none]
} else if (!isNullOrEmpty(specTopic.getFixedUrl())) {
if (!validateFixedUrl(specTopic, processedFixedUrls)) {
valid = false; // depends on control dependency: [if], data = [none]
} else {
processedFixedUrls.add(specTopic.getFixedUrl()); // depends on control dependency: [if], data = [none]
}
}
// Check that we are allowed to create new topics
if (!specTopic.isTopicAnExistingTopic() && !processingOptions.isAllowNewTopics()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_NEW_TOPIC_BUILD, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// New Topics
if (specTopic.isTopicANewTopic()) {
if (isNullOrEmpty(specTopic.getType())) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TYPE_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Existing Topics
} else if (specTopic.isTopicAnExistingTopic()) {
// Check that tags aren't trying to be removed
if (!specTopic.getRemoveTags(false).isEmpty()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_EXISTING_TOPIC_CANNOT_REMOVE_TAGS, specTopic.getLineNumber(),
specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Check that tags aren't trying to be added to a revision
if (processingOptions.isPrintChangeWarnings() && specTopic.getRevision() != null && !specTopic.getTags(false).isEmpty()) {
log.warn(
String.format(ProcessorConstants.WARN_TAGS_IGNORE_MSG, specTopic.getLineNumber(), "revision", specTopic.getText())); // depends on control dependency: [if], data = [none]
}
// Check that urls aren't trying to be added
if (!specTopic.getSourceUrls(false).isEmpty()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_EXISTING_TOPIC_CANNOT_ADD_SOURCE_URLS, specTopic.getLineNumber(),
specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Check that the assigned writer and description haven't been set
if (specTopic.getAssignedWriter(false) != null || specTopic.getDescription(false) != null) {
log.error(
String.format(ProcessorConstants.ERROR_TOPIC_EXISTING_BAD_OPTIONS, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Check that we aren't processing translations
if (!specTopic.getTags(true).isEmpty() && processingOptions.isTranslation()) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NO_TAGS_TRANSLATION_TOPIC, specTopic.getLineNumber(),
specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
}
// Duplicated Topics
else if (specTopic.isTopicADuplicateTopic()) {
String temp = "N" + specTopic.getId().substring(1);
// Check that the topic exists in the content specification
if (!specTopics.containsKey(temp)) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
} else {
// Check that the topic titles match the original
if (!specTopic.getTitle().equals(specTopics.get(temp).getTitle())) {
String topicTitleMsg = "Topic " + specTopic.getId() + ": " + specTopics.get(temp).getTitle();
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TITLES_NONMATCH_MSG, specTopic.getLineNumber(),
specTopic.getText(), topicTitleMsg)); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
}
// Cloned Topics
} else if (specTopic.isTopicAClonedTopic()) {
// Check if a description or type exists. If one does then generate an error.
if ((specTopic.getType() != null && !specTopic.getType().equals("")) || (specTopic.getDescription(
false) != null && !specTopic.getDescription(false).equals(""))) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_CLONED_BAD_OPTIONS, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Duplicated Cloned Topics
} else if (specTopic.isTopicAClonedDuplicateTopic()) {
// Find the duplicate topic in the content spec
final String topicId = specTopic.getId().substring(1);
int count = 0;
SpecTopic clonedTopic = null;
for (final Entry<String, SpecTopic> entry : specTopics.entrySet()) {
final String uniqueTopicId = entry.getKey();
if (uniqueTopicId.endsWith(topicId) && !uniqueTopicId.endsWith(specTopic.getId())) {
clonedTopic = entry.getValue(); // depends on control dependency: [if], data = [none]
count++; // depends on control dependency: [if], data = [none]
}
}
// Check that the topic exists
if (count == 0) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Check that the referenced topic is unique
else if (count > 1) {
log.error(
String.format(ProcessorConstants.ERROR_TOPIC_DUPLICATE_CLONES_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
} else {
// Check that the title matches
if (!specTopic.getTitle().equals(clonedTopic.getTitle())) {
String topicTitleMsg = "Topic " + specTopic.getId() + ": " + clonedTopic.getTitle();
log.error(String.format(ProcessorConstants.ERROR_TOPIC_TITLES_NONMATCH_MSG, specTopic.getLineNumber(),
specTopic.getText(), topicTitleMsg)); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
}
}
// Check to make sure no relationships exist if they aren't allowed
if (!allowRelationships && specTopic.getRelationships().size() > 0) {
log.error(format(ProcessorConstants.ERROR_TOPIC_HAS_RELATIONSHIPS_MSG, specTopic.getLineNumber(), specTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
}
// Check for conflicting conditions
checkForConflictingCondition(specTopic, contentSpec);
return valid;
} } |
public class class_name {
public void marshall(GetAuthorizerRequest getAuthorizerRequest, ProtocolMarshaller protocolMarshaller) {
if (getAuthorizerRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getAuthorizerRequest.getRestApiId(), RESTAPIID_BINDING);
protocolMarshaller.marshall(getAuthorizerRequest.getAuthorizerId(), AUTHORIZERID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetAuthorizerRequest getAuthorizerRequest, ProtocolMarshaller protocolMarshaller) {
if (getAuthorizerRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getAuthorizerRequest.getRestApiId(), RESTAPIID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getAuthorizerRequest.getAuthorizerId(), AUTHORIZERID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setServiceType(java.util.Collection<ServiceTypeDetail> serviceType) {
if (serviceType == null) {
this.serviceType = null;
return;
}
this.serviceType = new com.amazonaws.internal.SdkInternalList<ServiceTypeDetail>(serviceType);
} } | public class class_name {
public void setServiceType(java.util.Collection<ServiceTypeDetail> serviceType) {
if (serviceType == null) {
this.serviceType = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.serviceType = new com.amazonaws.internal.SdkInternalList<ServiceTypeDetail>(serviceType);
} } |
public class class_name {
public void setResourceAwsEc2InstanceType(java.util.Collection<StringFilter> resourceAwsEc2InstanceType) {
if (resourceAwsEc2InstanceType == null) {
this.resourceAwsEc2InstanceType = null;
return;
}
this.resourceAwsEc2InstanceType = new java.util.ArrayList<StringFilter>(resourceAwsEc2InstanceType);
} } | public class class_name {
public void setResourceAwsEc2InstanceType(java.util.Collection<StringFilter> resourceAwsEc2InstanceType) {
if (resourceAwsEc2InstanceType == null) {
this.resourceAwsEc2InstanceType = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.resourceAwsEc2InstanceType = new java.util.ArrayList<StringFilter>(resourceAwsEc2InstanceType);
} } |
public class class_name {
public static <T> MultivaluedMap<String, String> getBodyAsMultiValuedMap(Request<T> request) {
MultivaluedMap<String, String> map = new BodyMultivaluedMap();
Class<?> referenceClazz = request.getClass();
List<Field> fields = ClassUtil.getAnnotatedFields(referenceClazz, Body.class);
for (Field field : fields) {
Body body = field.getAnnotation(Body.class);
String parameter = body.value();
// in case the value() is null or empty
if (parameter == null || (parameter != null && parameter.isEmpty())) {
parameter = field.getName();
}
String value = ClassUtil.getValueOf(field, request, referenceClazz, String.class);
map.putSingle(parameter, value);
}
return map;
} } | public class class_name {
public static <T> MultivaluedMap<String, String> getBodyAsMultiValuedMap(Request<T> request) {
MultivaluedMap<String, String> map = new BodyMultivaluedMap();
Class<?> referenceClazz = request.getClass();
List<Field> fields = ClassUtil.getAnnotatedFields(referenceClazz, Body.class);
for (Field field : fields) {
Body body = field.getAnnotation(Body.class);
String parameter = body.value();
// in case the value() is null or empty
if (parameter == null || (parameter != null && parameter.isEmpty())) {
parameter = field.getName(); // depends on control dependency: [if], data = [none]
}
String value = ClassUtil.getValueOf(field, request, referenceClazz, String.class);
map.putSingle(parameter, value); // depends on control dependency: [for], data = [none]
}
return map;
} } |
public class class_name {
public static byte getValueLengthFromQualifier(final byte[] qualifier,
final int offset) {
validateQualifier(qualifier, offset);
short length;
if ((qualifier[offset] & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG) {
length = (short) (qualifier[offset + 3] & Internal.LENGTH_MASK);
} else {
length = (short) (qualifier[offset + 1] & Internal.LENGTH_MASK);
}
return (byte) (length + 1);
} } | public class class_name {
public static byte getValueLengthFromQualifier(final byte[] qualifier,
final int offset) {
validateQualifier(qualifier, offset);
short length;
if ((qualifier[offset] & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG) {
length = (short) (qualifier[offset + 3] & Internal.LENGTH_MASK); // depends on control dependency: [if], data = [none]
} else {
length = (short) (qualifier[offset + 1] & Internal.LENGTH_MASK); // depends on control dependency: [if], data = [none]
}
return (byte) (length + 1);
} } |
public class class_name {
private void initParityConfigs() {
Set<String> acceptedCodecIds = new HashSet<String>();
for (String s : conf.get("dfs.f4.accepted.codecs", "rs,xor").split(",")) {
acceptedCodecIds.add(s);
}
for (Codec c : Codec.getCodecs()) {
if (acceptedCodecIds.contains(c.id)) {
FSNamesystem.LOG.info("F4: Parity info."
+ " Id: " + c.id
+ " Parity Length: " + c.parityLength
+ " Parity Stripe Length: " + c.stripeLength
+ " Parity directory: " + c.parityDirectory
+ " Parity temp directory: " + c.tmpParityDirectory);
acceptedCodecs.add(c);
if (c.stripeLength > this.stripeLen) {
// Use the max stripe length
this.stripeLen = c.stripeLength;
}
}
}
FSNamesystem.LOG.info("F4: Initialized stripe len to: " + this.stripeLen);
} } | public class class_name {
private void initParityConfigs() {
Set<String> acceptedCodecIds = new HashSet<String>();
for (String s : conf.get("dfs.f4.accepted.codecs", "rs,xor").split(",")) {
acceptedCodecIds.add(s); // depends on control dependency: [for], data = [s]
}
for (Codec c : Codec.getCodecs()) {
if (acceptedCodecIds.contains(c.id)) {
FSNamesystem.LOG.info("F4: Parity info."
+ " Id: " + c.id
+ " Parity Length: " + c.parityLength
+ " Parity Stripe Length: " + c.stripeLength
+ " Parity directory: " + c.parityDirectory // depends on control dependency: [if], data = [none]
+ " Parity temp directory: " + c.tmpParityDirectory);
acceptedCodecs.add(c); // depends on control dependency: [if], data = [none]
if (c.stripeLength > this.stripeLen) {
// Use the max stripe length
this.stripeLen = c.stripeLength; // depends on control dependency: [if], data = [none]
}
}
}
FSNamesystem.LOG.info("F4: Initialized stripe len to: " + this.stripeLen);
} } |
public class class_name {
@Override
public boolean substituteVM(VM curId, VM nextId) {
if (VM.TYPE.equals(elemId)) {
if (rev.containsKey(nextId)) {
//the new id already exists. It is a failure scenario.
return false;
}
String fqn = rev.remove(curId);
if (fqn != null) {
//new resolution, with the substitution of the old one.
rev.put((E) nextId, fqn);
resolve.put(fqn, (E) nextId);
}
}
return true;
} } | public class class_name {
@Override
public boolean substituteVM(VM curId, VM nextId) {
if (VM.TYPE.equals(elemId)) {
if (rev.containsKey(nextId)) {
//the new id already exists. It is a failure scenario.
return false; // depends on control dependency: [if], data = [none]
}
String fqn = rev.remove(curId);
if (fqn != null) {
//new resolution, with the substitution of the old one.
rev.put((E) nextId, fqn); // depends on control dependency: [if], data = [none]
resolve.put(fqn, (E) nextId); // depends on control dependency: [if], data = [(fqn]
}
}
return true;
} } |
public class class_name {
public SinglePortRouterConfiguration build() {
if (this.enabled) {
try {
validate();
} catch (Exception e) {
throw logger.configurationValidationError(e);
}
SslConfigurationBuilder sslConfigurationBuilder = new SslConfigurationBuilder(null);
if (sslContext != null) {
sslConfigurationBuilder.sslContext(sslContext);
}
else if (keystorePath != null) {
sslConfigurationBuilder.keyStoreFileName(keystorePath).keyStorePassword(keystorePassword).enable();
}
AttributeSet attributes = ProtocolServerConfiguration.attributeDefinitionSet();
attributes.attribute(ProtocolServerConfiguration.NAME).set(name);
attributes.attribute(ProtocolServerConfiguration.HOST).set(ip.getHostName());
attributes.attribute(ProtocolServerConfiguration.PORT).set(port);
attributes.attribute(ProtocolServerConfiguration.IDLE_TIMEOUT).set(100);
attributes.attribute(ProtocolServerConfiguration.RECV_BUF_SIZE).set(receiveBufferSize);
attributes.attribute(ProtocolServerConfiguration.SEND_BUF_SIZE).set(sendBufferSize);
return new SinglePortRouterConfiguration(attributes.protect(), sslConfigurationBuilder.create());
}
return null;
} } | public class class_name {
public SinglePortRouterConfiguration build() {
if (this.enabled) {
try {
validate(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw logger.configurationValidationError(e);
} // depends on control dependency: [catch], data = [none]
SslConfigurationBuilder sslConfigurationBuilder = new SslConfigurationBuilder(null);
if (sslContext != null) {
sslConfigurationBuilder.sslContext(sslContext); // depends on control dependency: [if], data = [(sslContext]
}
else if (keystorePath != null) {
sslConfigurationBuilder.keyStoreFileName(keystorePath).keyStorePassword(keystorePassword).enable(); // depends on control dependency: [if], data = [(keystorePath]
}
AttributeSet attributes = ProtocolServerConfiguration.attributeDefinitionSet();
attributes.attribute(ProtocolServerConfiguration.NAME).set(name); // depends on control dependency: [if], data = [none]
attributes.attribute(ProtocolServerConfiguration.HOST).set(ip.getHostName()); // depends on control dependency: [if], data = [none]
attributes.attribute(ProtocolServerConfiguration.PORT).set(port); // depends on control dependency: [if], data = [none]
attributes.attribute(ProtocolServerConfiguration.IDLE_TIMEOUT).set(100); // depends on control dependency: [if], data = [none]
attributes.attribute(ProtocolServerConfiguration.RECV_BUF_SIZE).set(receiveBufferSize); // depends on control dependency: [if], data = [none]
attributes.attribute(ProtocolServerConfiguration.SEND_BUF_SIZE).set(sendBufferSize); // depends on control dependency: [if], data = [none]
return new SinglePortRouterConfiguration(attributes.protect(), sslConfigurationBuilder.create()); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static String sanitize(final String input) {
if(input == null) {
return null;
}
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
if (c == '*') {
// escape asterisk
sb.append("\\2a");
} else if (c == '(') {
// escape left parenthesis
sb.append("\\28");
} else if (c == ')') {
// escape right parenthesis
sb.append("\\29");
} else if (c == '\\') {
// escape backslash
sb.append("\\5c");
} else if (c == '\u0000') {
// escape NULL char
sb.append("\\00");
} else if (c <= 0x7f) {
// regular 1-byte UTF-8 char
sb.append(String.valueOf(c));
} else if (c >= 0x080) {
// higher-order 2, 3 and 4-byte UTF-8 chars
final byte[] utf8bytes = String.valueOf(c).getBytes(StandardCharsets.UTF_8);
for (final byte b : utf8bytes) {
sb.append(String.format("\\%02x", b));
}
}
}
return sb.toString();
} } | public class class_name {
public static String sanitize(final String input) {
if(input == null) {
return null; // depends on control dependency: [if], data = [none]
}
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
if (c == '*') {
// escape asterisk
sb.append("\\2a"); // depends on control dependency: [if], data = [none]
} else if (c == '(') {
// escape left parenthesis
sb.append("\\28"); // depends on control dependency: [if], data = [none]
} else if (c == ')') {
// escape right parenthesis
sb.append("\\29"); // depends on control dependency: [if], data = [none]
} else if (c == '\\') {
// escape backslash
sb.append("\\5c"); // depends on control dependency: [if], data = [none]
} else if (c == '\u0000') {
// escape NULL char
sb.append("\\00"); // depends on control dependency: [if], data = [none]
} else if (c <= 0x7f) {
// regular 1-byte UTF-8 char
sb.append(String.valueOf(c)); // depends on control dependency: [if], data = [(c]
} else if (c >= 0x080) {
// higher-order 2, 3 and 4-byte UTF-8 chars
final byte[] utf8bytes = String.valueOf(c).getBytes(StandardCharsets.UTF_8);
for (final byte b : utf8bytes) {
sb.append(String.format("\\%02x", b)); // depends on control dependency: [for], data = [b]
}
}
}
return sb.toString();
} } |
public class class_name {
public static String formatAddress(InetAddress inet){
if(inet == null){
throw new IllegalArgumentException();
}
if(inet instanceof Inet4Address){
return inet.getHostAddress();
} else if (inet instanceof Inet6Address){
byte[] byteRepresentation = inet.getAddress();
int[] hexRepresentation = new int[IPV6_LEN];
for(int i=0;i < hexRepresentation.length;i++){
hexRepresentation[i] = ( byteRepresentation[2*i] & 0xFF) << 8 | ( byteRepresentation[2*i+1] & 0xFF );
}
compactLongestZeroSequence(hexRepresentation);
return formatAddress6(hexRepresentation);
} else {
return inet.getHostAddress();
}
} } | public class class_name {
public static String formatAddress(InetAddress inet){
if(inet == null){
throw new IllegalArgumentException();
}
if(inet instanceof Inet4Address){
return inet.getHostAddress(); // depends on control dependency: [if], data = [none]
} else if (inet instanceof Inet6Address){
byte[] byteRepresentation = inet.getAddress();
int[] hexRepresentation = new int[IPV6_LEN];
for(int i=0;i < hexRepresentation.length;i++){
hexRepresentation[i] = ( byteRepresentation[2*i] & 0xFF) << 8 | ( byteRepresentation[2*i+1] & 0xFF ); // depends on control dependency: [for], data = [i]
}
compactLongestZeroSequence(hexRepresentation); // depends on control dependency: [if], data = [none]
return formatAddress6(hexRepresentation); // depends on control dependency: [if], data = [none]
} else {
return inet.getHostAddress(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void download(GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream)
throws IOException {
Preconditions.checkArgument(downloadState == DownloadState.NOT_STARTED);
requestUrl.put("alt", "media");
if (directDownloadEnabled) {
updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS);
HttpResponse response =
executeCurrentRequest(lastBytePos, requestUrl, requestHeaders, outputStream);
// All required bytes have been downloaded from the server.
mediaContentLength =
firstNonNull(response.getHeaders().getContentLength(), mediaContentLength);
bytesDownloaded = mediaContentLength;
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE);
return;
}
// Download the media content in chunks.
while (true) {
long currentRequestLastBytePos = bytesDownloaded + chunkSize - 1;
if (lastBytePos != -1) {
// If last byte position has been specified, use it iff it is smaller than the chunk size.
currentRequestLastBytePos = Math.min(lastBytePos, currentRequestLastBytePos);
}
HttpResponse response = executeCurrentRequest(
currentRequestLastBytePos, requestUrl, requestHeaders, outputStream);
String contentRange = response.getHeaders().getContentRange();
long nextByteIndex = getNextByteIndex(contentRange);
setMediaContentLength(contentRange);
// If the last byte position is specified, complete the download when it is less than
// nextByteIndex.
if (lastBytePos != -1 && lastBytePos <= nextByteIndex) {
// All required bytes from the range have been downloaded from the server.
bytesDownloaded = lastBytePos;
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE);
return;
}
if (mediaContentLength <= nextByteIndex) {
// All required bytes have been downloaded from the server.
bytesDownloaded = mediaContentLength;
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE);
return;
}
bytesDownloaded = nextByteIndex;
updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS);
}
} } | public class class_name {
public void download(GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream)
throws IOException {
Preconditions.checkArgument(downloadState == DownloadState.NOT_STARTED);
requestUrl.put("alt", "media");
if (directDownloadEnabled) {
updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS);
HttpResponse response =
executeCurrentRequest(lastBytePos, requestUrl, requestHeaders, outputStream);
// All required bytes have been downloaded from the server.
mediaContentLength =
firstNonNull(response.getHeaders().getContentLength(), mediaContentLength);
bytesDownloaded = mediaContentLength;
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE);
return;
}
// Download the media content in chunks.
while (true) {
long currentRequestLastBytePos = bytesDownloaded + chunkSize - 1;
if (lastBytePos != -1) {
// If last byte position has been specified, use it iff it is smaller than the chunk size.
currentRequestLastBytePos = Math.min(lastBytePos, currentRequestLastBytePos); // depends on control dependency: [if], data = [(lastBytePos]
}
HttpResponse response = executeCurrentRequest(
currentRequestLastBytePos, requestUrl, requestHeaders, outputStream);
String contentRange = response.getHeaders().getContentRange();
long nextByteIndex = getNextByteIndex(contentRange);
setMediaContentLength(contentRange);
// If the last byte position is specified, complete the download when it is less than
// nextByteIndex.
if (lastBytePos != -1 && lastBytePos <= nextByteIndex) {
// All required bytes from the range have been downloaded from the server.
bytesDownloaded = lastBytePos; // depends on control dependency: [if], data = [none]
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (mediaContentLength <= nextByteIndex) {
// All required bytes have been downloaded from the server.
bytesDownloaded = mediaContentLength; // depends on control dependency: [if], data = [none]
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
bytesDownloaded = nextByteIndex;
updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS);
}
} } |
public class class_name {
private static void addResultForMonth(final GovernmentBodyAnnualOutcomeSummary governmentBodyAnnualOutcomeSummary, final int month,
final String value) {
if (value != null && value.length() >0 ) {
governmentBodyAnnualOutcomeSummary.addData(month,Double.valueOf(value.replaceAll(",", ".")));
}
} } | public class class_name {
private static void addResultForMonth(final GovernmentBodyAnnualOutcomeSummary governmentBodyAnnualOutcomeSummary, final int month,
final String value) {
if (value != null && value.length() >0 ) {
governmentBodyAnnualOutcomeSummary.addData(month,Double.valueOf(value.replaceAll(",", "."))); // depends on control dependency: [if], data = [(value]
}
} } |
public class class_name {
protected void addUseInfo(List<? extends Element> mems,
Content heading, String tableSummary, Content contentTree) {
if (mems == null || mems.isEmpty()) {
return;
}
List<? extends Element> members = mems;
boolean printedUseTableHeader = false;
if (members.size() > 0) {
Content caption = writer.getTableCaption(heading);
Content table = (configuration.isOutputHtml5())
? HtmlTree.TABLE(HtmlStyle.useSummary, caption)
: HtmlTree.TABLE(HtmlStyle.useSummary, tableSummary, caption);
Content tbody = new HtmlTree(HtmlTag.TBODY);
boolean altColor = true;
for (Element element : members) {
TypeElement te = utils.getEnclosingTypeElement(element);
if (!printedUseTableHeader) {
table.addContent(writer.getSummaryTableHeader(
this.getSummaryTableHeader(element), "col"));
printedUseTableHeader = true;
}
HtmlTree tr = new HtmlTree(HtmlTag.TR);
tr.addStyle(altColor ? HtmlStyle.altColor : HtmlStyle.rowColor);
altColor = !altColor;
HtmlTree tdFirst = new HtmlTree(HtmlTag.TD);
tdFirst.addStyle(HtmlStyle.colFirst);
writer.addSummaryType(this, element, tdFirst);
tr.addContent(tdFirst);
HtmlTree thType = new HtmlTree(HtmlTag.TH);
thType.addStyle(HtmlStyle.colSecond);
thType.addAttr(HtmlAttr.SCOPE, "row");
if (te != null
&& !utils.isConstructor(element)
&& !utils.isClass(element)
&& !utils.isInterface(element)
&& !utils.isAnnotationType(element)) {
HtmlTree name = new HtmlTree(HtmlTag.SPAN);
name.addStyle(HtmlStyle.typeNameLabel);
name.addContent(name(te) + ".");
thType.addContent(name);
}
addSummaryLink(utils.isClass(element) || utils.isInterface(element)
? LinkInfoImpl.Kind.CLASS_USE
: LinkInfoImpl.Kind.MEMBER,
te, element, thType);
tr.addContent(thType);
HtmlTree tdDesc = new HtmlTree(HtmlTag.TD);
tdDesc.addStyle(HtmlStyle.colLast);
writer.addSummaryLinkComment(this, element, tdDesc);
tr.addContent(tdDesc);
tbody.addContent(tr);
}
table.addContent(tbody);
contentTree.addContent(table);
}
} } | public class class_name {
protected void addUseInfo(List<? extends Element> mems,
Content heading, String tableSummary, Content contentTree) {
if (mems == null || mems.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
List<? extends Element> members = mems;
boolean printedUseTableHeader = false;
if (members.size() > 0) {
Content caption = writer.getTableCaption(heading);
Content table = (configuration.isOutputHtml5())
? HtmlTree.TABLE(HtmlStyle.useSummary, caption)
: HtmlTree.TABLE(HtmlStyle.useSummary, tableSummary, caption);
Content tbody = new HtmlTree(HtmlTag.TBODY);
boolean altColor = true;
for (Element element : members) {
TypeElement te = utils.getEnclosingTypeElement(element);
if (!printedUseTableHeader) {
table.addContent(writer.getSummaryTableHeader(
this.getSummaryTableHeader(element), "col")); // depends on control dependency: [if], data = [none]
printedUseTableHeader = true; // depends on control dependency: [if], data = [none]
}
HtmlTree tr = new HtmlTree(HtmlTag.TR);
tr.addStyle(altColor ? HtmlStyle.altColor : HtmlStyle.rowColor); // depends on control dependency: [for], data = [none]
altColor = !altColor; // depends on control dependency: [for], data = [none]
HtmlTree tdFirst = new HtmlTree(HtmlTag.TD);
tdFirst.addStyle(HtmlStyle.colFirst); // depends on control dependency: [for], data = [none]
writer.addSummaryType(this, element, tdFirst); // depends on control dependency: [for], data = [element]
tr.addContent(tdFirst); // depends on control dependency: [for], data = [none]
HtmlTree thType = new HtmlTree(HtmlTag.TH);
thType.addStyle(HtmlStyle.colSecond); // depends on control dependency: [for], data = [none]
thType.addAttr(HtmlAttr.SCOPE, "row"); // depends on control dependency: [for], data = [none]
if (te != null
&& !utils.isConstructor(element)
&& !utils.isClass(element)
&& !utils.isInterface(element)
&& !utils.isAnnotationType(element)) {
HtmlTree name = new HtmlTree(HtmlTag.SPAN);
name.addStyle(HtmlStyle.typeNameLabel); // depends on control dependency: [if], data = [none]
name.addContent(name(te) + "."); // depends on control dependency: [if], data = [(te]
thType.addContent(name); // depends on control dependency: [if], data = [none]
}
addSummaryLink(utils.isClass(element) || utils.isInterface(element)
? LinkInfoImpl.Kind.CLASS_USE
: LinkInfoImpl.Kind.MEMBER,
te, element, thType); // depends on control dependency: [for], data = [none]
tr.addContent(thType); // depends on control dependency: [for], data = [none]
HtmlTree tdDesc = new HtmlTree(HtmlTag.TD);
tdDesc.addStyle(HtmlStyle.colLast); // depends on control dependency: [for], data = [none]
writer.addSummaryLinkComment(this, element, tdDesc); // depends on control dependency: [for], data = [element]
tr.addContent(tdDesc); // depends on control dependency: [for], data = [none]
tbody.addContent(tr); // depends on control dependency: [for], data = [none]
}
table.addContent(tbody); // depends on control dependency: [if], data = [none]
contentTree.addContent(table); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void printHelp(PrintWriter pw, int width, String cmdLineSyntax,
String header, Options options, int leftPad,
int descPad, String footer, boolean autoUsage)
{
if (cmdLineSyntax == null || cmdLineSyntax.length() == 0)
{
throw new IllegalArgumentException("cmdLineSyntax not provided");
}
if (autoUsage)
{
printUsage(pw, width, cmdLineSyntax, options);
}
else
{
printUsage(pw, width, cmdLineSyntax);
}
if (header != null && header.trim().length() > 0)
{
printWrapped(pw, width, header);
}
printOptions(pw, width, options, leftPad, descPad);
if (footer != null && footer.trim().length() > 0)
{
printWrapped(pw, width, footer);
}
} } | public class class_name {
public void printHelp(PrintWriter pw, int width, String cmdLineSyntax,
String header, Options options, int leftPad,
int descPad, String footer, boolean autoUsage)
{
if (cmdLineSyntax == null || cmdLineSyntax.length() == 0)
{
throw new IllegalArgumentException("cmdLineSyntax not provided");
}
if (autoUsage)
{
printUsage(pw, width, cmdLineSyntax, options); // depends on control dependency: [if], data = [none]
}
else
{
printUsage(pw, width, cmdLineSyntax); // depends on control dependency: [if], data = [none]
}
if (header != null && header.trim().length() > 0)
{
printWrapped(pw, width, header); // depends on control dependency: [if], data = [none]
}
printOptions(pw, width, options, leftPad, descPad);
if (footer != null && footer.trim().length() > 0)
{
printWrapped(pw, width, footer); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void readFrom(InputStream is) throws IOException {
while(true) {
if(count==buf.length) {
// reallocate
byte[] data = new byte[buf.length*2];
System.arraycopy(buf,0,data,0,buf.length);
buf = data;
}
int sz = is.read(buf,count,buf.length-count);
if(sz<0) return;
count += sz;
}
} } | public class class_name {
public void readFrom(InputStream is) throws IOException {
while(true) {
if(count==buf.length) {
// reallocate
byte[] data = new byte[buf.length*2];
System.arraycopy(buf,0,data,0,buf.length); // depends on control dependency: [if], data = [buf.length)]
buf = data; // depends on control dependency: [if], data = [none]
}
int sz = is.read(buf,count,buf.length-count);
if(sz<0) return;
count += sz;
}
} } |
public class class_name {
private boolean checkLocations(long length, CompoundLocation<Location> locations) {
for(Location location : locations.getLocations()){
if(location instanceof RemoteLocation)
continue;
if(location.getIntBeginPosition() == null ||
location.getIntBeginPosition() < 0){
return false;
}
if(location.getIntEndPosition() == null ||
location.getIntEndPosition() > length){
return false;
}
}
return true;
} } | public class class_name {
private boolean checkLocations(long length, CompoundLocation<Location> locations) {
for(Location location : locations.getLocations()){
if(location instanceof RemoteLocation)
continue;
if(location.getIntBeginPosition() == null ||
location.getIntBeginPosition() < 0){
return false; // depends on control dependency: [if], data = [none]
}
if(location.getIntEndPosition() == null ||
location.getIntEndPosition() > length){
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public int compareTo(Timestamp ts) {
long thisTime = this.getTime();
long anotherTime = ts.getTime();
int i = (thisTime<anotherTime ? -1 :(thisTime==anotherTime?0 :1));
if (i == 0) {
if (nanos > ts.nanos) {
return 1;
} else if (nanos < ts.nanos) {
return -1;
}
}
return i;
} } | public class class_name {
public int compareTo(Timestamp ts) {
long thisTime = this.getTime();
long anotherTime = ts.getTime();
int i = (thisTime<anotherTime ? -1 :(thisTime==anotherTime?0 :1));
if (i == 0) {
if (nanos > ts.nanos) {
return 1; // depends on control dependency: [if], data = [none]
} else if (nanos < ts.nanos) {
return -1; // depends on control dependency: [if], data = [none]
}
}
return i;
} } |
public class class_name {
public static void addTransitiveMatches(HollowReadStateEngine stateEngine, Map<String, BitSet> matches) {
List<HollowSchema> schemaList = HollowSchemaSorter.dependencyOrderedSchemaList(stateEngine);
Collections.reverse(schemaList);
for(HollowSchema schema : schemaList) {
BitSet currentMatches = matches.get(schema.getName());
if(currentMatches != null) {
addTransitiveMatches(stateEngine, schema.getName(), matches);
}
}
} } | public class class_name {
public static void addTransitiveMatches(HollowReadStateEngine stateEngine, Map<String, BitSet> matches) {
List<HollowSchema> schemaList = HollowSchemaSorter.dependencyOrderedSchemaList(stateEngine);
Collections.reverse(schemaList);
for(HollowSchema schema : schemaList) {
BitSet currentMatches = matches.get(schema.getName());
if(currentMatches != null) {
addTransitiveMatches(stateEngine, schema.getName(), matches); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected final WroManagerFactory getManagerFactory() {
if (managerFactory == null) {
try {
managerFactory = wroManagerFactory != null ? createCustomManagerFactory() : newWroManagerFactory();
onAfterCreate(managerFactory);
} catch (final MojoExecutionException e) {
throw WroRuntimeException.wrap(e);
}
}
return managerFactory;
} } | public class class_name {
protected final WroManagerFactory getManagerFactory() {
if (managerFactory == null) {
try {
managerFactory = wroManagerFactory != null ? createCustomManagerFactory() : newWroManagerFactory(); // depends on control dependency: [try], data = [none]
onAfterCreate(managerFactory); // depends on control dependency: [try], data = [none]
} catch (final MojoExecutionException e) {
throw WroRuntimeException.wrap(e);
} // depends on control dependency: [catch], data = [none]
}
return managerFactory;
} } |
public class class_name {
public Actions keyUp(CharSequence key) {
if (isBuildingActions()) {
action.addAction(new KeyUpAction(jsonKeyboard, jsonMouse, asKeys(key)));
}
return addKeyAction(key, codePoint -> tick(defaultKeyboard.createKeyUp(codePoint)));
} } | public class class_name {
public Actions keyUp(CharSequence key) {
if (isBuildingActions()) {
action.addAction(new KeyUpAction(jsonKeyboard, jsonMouse, asKeys(key))); // depends on control dependency: [if], data = [none]
}
return addKeyAction(key, codePoint -> tick(defaultKeyboard.createKeyUp(codePoint)));
} } |
public class class_name {
public void marshall(TagListEntry tagListEntry, ProtocolMarshaller protocolMarshaller) {
if (tagListEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(tagListEntry.getKey(), KEY_BINDING);
protocolMarshaller.marshall(tagListEntry.getValue(), VALUE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(TagListEntry tagListEntry, ProtocolMarshaller protocolMarshaller) {
if (tagListEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(tagListEntry.getKey(), KEY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(tagListEntry.getValue(), VALUE_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 WebDriver innerFrame(String... frames) {
delegate.defaultContent();
for (String frame : frames) {
try {
String selector = String.format("frame#%1$s,frame[name=%1$s],iframe#%1$s,iframe[name=%1$s]", frame);
Wait().until(frameToBeAvailableAndSwitchToIt_fixed(By.cssSelector(selector)));
}
catch (NoSuchElementException | TimeoutException e) {
throw new NoSuchFrameException("No frame found with id/name = " + frame, e);
}
}
return webDriver;
} } | public class class_name {
public WebDriver innerFrame(String... frames) {
delegate.defaultContent();
for (String frame : frames) {
try {
String selector = String.format("frame#%1$s,frame[name=%1$s],iframe#%1$s,iframe[name=%1$s]", frame);
Wait().until(frameToBeAvailableAndSwitchToIt_fixed(By.cssSelector(selector))); // depends on control dependency: [try], data = [none]
}
catch (NoSuchElementException | TimeoutException e) {
throw new NoSuchFrameException("No frame found with id/name = " + frame, e);
} // depends on control dependency: [catch], data = [none]
}
return webDriver;
} } |
public class class_name {
public static ZrtpCacheEntry fromString(String key, String value) {
String data = null;
String number = null;
int sep = value.indexOf(',');
if (sep > 0) {
data = value.substring(0, sep);
number = value.substring(sep + 1);
} else {
data = value;
number = "";
}
byte[] buffer = new byte[data.length() / 2];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (byte) Short.parseShort(
data.substring(i * 2, i * 2 + 2), 16);
}
AndroidCacheEntry entry = new AndroidCacheEntry(key, buffer, number);
return entry;
} } | public class class_name {
public static ZrtpCacheEntry fromString(String key, String value) {
String data = null;
String number = null;
int sep = value.indexOf(',');
if (sep > 0) {
data = value.substring(0, sep);
// depends on control dependency: [if], data = [none]
number = value.substring(sep + 1);
// depends on control dependency: [if], data = [(sep]
} else {
data = value;
// depends on control dependency: [if], data = [none]
number = "";
// depends on control dependency: [if], data = [none]
}
byte[] buffer = new byte[data.length() / 2];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (byte) Short.parseShort(
data.substring(i * 2, i * 2 + 2), 16);
// depends on control dependency: [for], data = [i]
}
AndroidCacheEntry entry = new AndroidCacheEntry(key, buffer, number);
return entry;
} } |
public class class_name {
public void clearTmpData() {
for (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {
((LblTree) e.nextElement()).setTmpData(null);
}
} } | public class class_name {
public void clearTmpData() {
for (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {
((LblTree) e.nextElement()).setTmpData(null); // depends on control dependency: [for], data = [e]
}
} } |
public class class_name {
private void appendMutableGetters(JMessage message, JField field) throws GeneratorException {
if (field.field().getDescriptor() instanceof PPrimitive ||
field.type() == PType.ENUM) {
// The other fields will have ordinary non-mutable getters.
appendGetter(field);
return;
}
BlockCommentBuilder comment = new BlockCommentBuilder(writer);
comment.commentRaw("Get the builder for the contained <code>" + field.name() + "</code> message field.");
if (field.hasComment()) {
comment.paragraph()
.comment(field.comment());
}
comment.newline()
.return_("The field message builder");
if (JAnnotation.isDeprecated(field)) {
String reason = field.field().getAnnotationValue(ThriftAnnotation.DEPRECATED);
if (reason != null && reason.trim().length() > 0) {
comment.deprecated_(reason);
}
}
comment.finish();
if (JAnnotation.isDeprecated(field)) {
writer.appendln(JAnnotation.DEPRECATED);
}
writer.appendln(JAnnotation.NON_NULL);
switch (field.type()) {
case MESSAGE: {
writer.formatln("public %s._Builder %s() {", field.instanceType(), field.mutable())
.begin();
if (message.isUnion()) {
writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum())
.formatln(" %s();", field.resetter())
.appendln('}')
.formatln("%s = _Field.%s;", UNION_FIELD, field.fieldEnum());
writer.appendln("modified = true;");
} else {
writer.formatln("optionals.set(%d);", field.index());
writer.formatln("modified.set(%d);", field.index());
}
writer.newline()
.formatln("if (%s != null) {", field.member())
.formatln(" %s_builder = %s.mutate();", field.member(), field.member())
.formatln(" %s = null;", field.member())
.formatln("} else if (%s_builder == null) {", field.member())
.formatln(" %s_builder = %s.builder();", field.member(), field.instanceType())
.appendln('}')
.formatln("return %s_builder;", field.member());
writer.end()
.appendln('}')
.newline();
// Also add "normal" getter for the message field, which will
// return the message or the builder dependent on which is set.
// It will not change the state of the builder.
comment = new BlockCommentBuilder(writer);
if (field.hasComment()) {
comment.comment(field.comment())
.newline();
}
comment.return_("The field value");
if (JAnnotation.isDeprecated(field)) {
String reason = field.field().getAnnotationValue(ThriftAnnotation.DEPRECATED);
if (reason != null && reason.trim().length() > 0) {
comment.deprecated_(reason);
}
}
comment.finish();
if (JAnnotation.isDeprecated(field)) {
writer.appendln(JAnnotation.DEPRECATED);
}
writer.formatln("public %s %s() {", field.instanceType(), field.getter())
.begin();
if (message.isUnion()) {
writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum())
.formatln(" return null;")
.appendln('}');
}
writer.newline()
.formatln("if (%s_builder != null) {", field.member())
.formatln(" return %s_builder.build();", field.member())
.appendln('}')
.formatln("return %s;", field.member());
writer.end()
.appendln('}')
.newline();
break;
}
case SET:
case LIST:
case MAP:
comment = new BlockCommentBuilder(writer);
if (field.hasComment()) {
comment.comment(field.comment())
.newline();
}
comment.return_("The mutable <code>" + field.name() + "</code> container");
if (JAnnotation.isDeprecated(field)) {
String reason = field.field().getAnnotationValue(ThriftAnnotation.DEPRECATED);
if (reason != null && reason.trim().length() > 0) {
comment.deprecated_(reason);
}
}
comment.finish();
if (JAnnotation.isDeprecated(field)) {
writer.appendln(JAnnotation.DEPRECATED);
}
writer.formatln("public %s %s() {", field.fieldType(), field.mutable())
.begin();
if (message.isUnion()) {
writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum())
.formatln(" %s();", field.resetter())
.appendln('}')
.formatln("%s = _Field.%s;", UNION_FIELD, field.fieldEnum());
writer.appendln("modified = true;");
} else {
writer.formatln("optionals.set(%d);", field.index());
writer.formatln("modified.set(%d);", field.index());
}
writer.newline()
.formatln("if (%s == null) {", field.member())
.formatln(" %s = new %s<>();", field.member(), field.builderMutableType())
.formatln("} else if (!(%s instanceof %s)) {", field.member(), field.builderMutableType())
.formatln(" %s = new %s<>(%s);", field.member(), field.builderMutableType(), field.member())
.appendln("}");
writer.formatln("return %s;", field.member());
writer.end()
.appendln('}')
.newline();
break;
default:
throw new GeneratorException("Unexpected field type: " + field.type());
}
} } | public class class_name {
private void appendMutableGetters(JMessage message, JField field) throws GeneratorException {
if (field.field().getDescriptor() instanceof PPrimitive ||
field.type() == PType.ENUM) {
// The other fields will have ordinary non-mutable getters.
appendGetter(field);
return;
}
BlockCommentBuilder comment = new BlockCommentBuilder(writer);
comment.commentRaw("Get the builder for the contained <code>" + field.name() + "</code> message field.");
if (field.hasComment()) {
comment.paragraph()
.comment(field.comment());
}
comment.newline()
.return_("The field message builder");
if (JAnnotation.isDeprecated(field)) {
String reason = field.field().getAnnotationValue(ThriftAnnotation.DEPRECATED);
if (reason != null && reason.trim().length() > 0) {
comment.deprecated_(reason); // depends on control dependency: [if], data = [(reason]
}
}
comment.finish();
if (JAnnotation.isDeprecated(field)) {
writer.appendln(JAnnotation.DEPRECATED);
}
writer.appendln(JAnnotation.NON_NULL);
switch (field.type()) {
case MESSAGE: {
writer.formatln("public %s._Builder %s() {", field.instanceType(), field.mutable())
.begin();
if (message.isUnion()) {
writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum())
.formatln(" %s();", field.resetter()) // depends on control dependency: [if], data = [none]
.appendln('}')
.formatln("%s = _Field.%s;", UNION_FIELD, field.fieldEnum()); // depends on control dependency: [if], data = [none]
writer.appendln("modified = true;"); // depends on control dependency: [if], data = [none]
} else {
writer.formatln("optionals.set(%d);", field.index()); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
writer.formatln("modified.set(%d);", field.index()); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
writer.newline()
.formatln("if (%s != null) {", field.member())
.formatln(" %s_builder = %s.mutate();", field.member(), field.member())
.formatln(" %s = null;", field.member())
.formatln("} else if (%s_builder == null) {", field.member())
.formatln(" %s_builder = %s.builder();", field.member(), field.instanceType())
.appendln('}')
.formatln("return %s_builder;", field.member());
writer.end()
.appendln('}')
.newline();
// Also add "normal" getter for the message field, which will
// return the message or the builder dependent on which is set.
// It will not change the state of the builder.
comment = new BlockCommentBuilder(writer);
if (field.hasComment()) {
comment.comment(field.comment())
.newline();
}
comment.return_("The field value");
if (JAnnotation.isDeprecated(field)) {
String reason = field.field().getAnnotationValue(ThriftAnnotation.DEPRECATED);
if (reason != null && reason.trim().length() > 0) {
comment.deprecated_(reason); // depends on control dependency: [if], data = [(reason]
}
}
comment.finish();
if (JAnnotation.isDeprecated(field)) {
writer.appendln(JAnnotation.DEPRECATED);
}
writer.formatln("public %s %s() {", field.instanceType(), field.getter())
.begin();
if (message.isUnion()) {
writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum())
.formatln(" return null;")
.appendln('}'); // depends on control dependency: [if], data = [none]
}
writer.newline()
.formatln("if (%s_builder != null) {", field.member())
.formatln(" return %s_builder.build();", field.member())
.appendln('}')
.formatln("return %s;", field.member());
writer.end()
.appendln('}')
.newline();
break;
}
case SET:
case LIST:
case MAP:
comment = new BlockCommentBuilder(writer);
if (field.hasComment()) {
comment.comment(field.comment())
.newline();
}
comment.return_("The mutable <code>" + field.name() + "</code> container");
if (JAnnotation.isDeprecated(field)) {
String reason = field.field().getAnnotationValue(ThriftAnnotation.DEPRECATED);
if (reason != null && reason.trim().length() > 0) {
comment.deprecated_(reason); // depends on control dependency: [if], data = [(reason]
}
}
comment.finish();
if (JAnnotation.isDeprecated(field)) {
writer.appendln(JAnnotation.DEPRECATED);
}
writer.formatln("public %s %s() {", field.fieldType(), field.mutable())
.begin();
if (message.isUnion()) {
writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum())
.formatln(" %s();", field.resetter()) // depends on control dependency: [if], data = [none]
.appendln('}')
.formatln("%s = _Field.%s;", UNION_FIELD, field.fieldEnum()); // depends on control dependency: [if], data = [none]
writer.appendln("modified = true;"); // depends on control dependency: [if], data = [none]
} else {
writer.formatln("optionals.set(%d);", field.index()); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
writer.formatln("modified.set(%d);", field.index()); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
writer.newline()
.formatln("if (%s == null) {", field.member())
.formatln(" %s = new %s<>();", field.member(), field.builderMutableType())
.formatln("} else if (!(%s instanceof %s)) {", field.member(), field.builderMutableType())
.formatln(" %s = new %s<>(%s);", field.member(), field.builderMutableType(), field.member())
.appendln("}");
writer.formatln("return %s;", field.member());
writer.end()
.appendln('}')
.newline();
break;
default:
throw new GeneratorException("Unexpected field type: " + field.type());
}
} } |
public class class_name {
protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException,
CommandLineParsingException {
Properties props = new Properties();
props.load(propertiesInputStream);
if (props.containsKey("strict")) {
strict = Boolean.valueOf(props.getProperty("strict"));
}
for (Map.Entry entry : props.entrySet()) {
try {
if ("promptOnNonLocalDatabase".equals(entry.getKey())) {
continue;
}
if (((String) entry.getKey()).startsWith("parameter.")) {
changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue
());
} else {
Field field = getClass().getDeclaredField((String) entry.getKey());
Object currentValue = field.get(this);
if (currentValue == null) {
String value = entry.getValue().toString().trim();
if (field.getType().equals(Boolean.class)) {
field.set(this, Boolean.valueOf(value));
} else {
field.set(this, value);
}
}
}
} catch (NoSuchFieldException ignored) {
if (strict) {
throw new CommandLineParsingException(
String.format(coreBundle.getString("parameter.unknown"), entry.getKey())
);
} else {
Scope.getCurrentScope().getLog(getClass()).warning(
LogType.LOG, String.format(coreBundle.getString("parameter.ignored"), entry.getKey())
);
}
} catch (IllegalAccessException e) {
throw new UnexpectedLiquibaseException(
String.format(coreBundle.getString("parameter.unknown"), entry.getKey())
);
}
}
} } | public class class_name {
protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException,
CommandLineParsingException {
Properties props = new Properties();
props.load(propertiesInputStream);
if (props.containsKey("strict")) {
strict = Boolean.valueOf(props.getProperty("strict"));
}
for (Map.Entry entry : props.entrySet()) {
try {
if ("promptOnNonLocalDatabase".equals(entry.getKey())) {
continue;
}
if (((String) entry.getKey()).startsWith("parameter.")) {
changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue
());
} else {
Field field = getClass().getDeclaredField((String) entry.getKey());
Object currentValue = field.get(this);
if (currentValue == null) {
String value = entry.getValue().toString().trim();
if (field.getType().equals(Boolean.class)) {
field.set(this, Boolean.valueOf(value)); // depends on control dependency: [if], data = [none]
} else {
field.set(this, value); // depends on control dependency: [if], data = [none]
}
}
}
} catch (NoSuchFieldException ignored) {
if (strict) {
throw new CommandLineParsingException(
String.format(coreBundle.getString("parameter.unknown"), entry.getKey())
);
} else {
Scope.getCurrentScope().getLog(getClass()).warning(
LogType.LOG, String.format(coreBundle.getString("parameter.ignored"), entry.getKey())
);
}
} catch (IllegalAccessException e) {
throw new UnexpectedLiquibaseException(
String.format(coreBundle.getString("parameter.unknown"), entry.getKey())
);
}
}
} } |
public class class_name {
private void executeSql(Reader inputReader, Map<String, String> replacers, boolean abortOnError) {
String statement = "";
LineNumberReader reader = null;
String line = null;
// parse the setup script
try {
reader = new LineNumberReader(inputReader);
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
String currentToken = st.nextToken();
// comment! Skip rest of the line
if (currentToken.startsWith("#")) {
break;
}
// not to be executed
if (currentToken.startsWith("prompt")) {
break;
}
// add token to query
statement += " " + currentToken;
// query complete (terminated by ';')
if (currentToken.endsWith(";")) {
// cut of ';' at the end
statement = statement.substring(0, (statement.length() - 1));
// normal statement, execute it
try {
if (replacers != null) {
statement = replaceTokens(statement, replacers);
executeStatement(statement);
} else {
executeStatement(statement);
}
} catch (SQLException e) {
if (!abortOnError) {
if (m_errorLogging) {
m_errors.add("Error executing SQL statement: " + statement);
m_errors.add(CmsException.getStackTraceAsString(e));
}
} else {
throw e;
}
}
// reset
statement = "";
}
}
statement += " \n";
}
} catch (SQLException e) {
if (m_errorLogging) {
m_errors.add("Error executing SQL statement: " + statement);
m_errors.add(CmsException.getStackTraceAsString(e));
}
} catch (Exception e) {
if (m_errorLogging) {
m_errors.add("Error parsing database setup SQL script in line: " + line);
m_errors.add(CmsException.getStackTraceAsString(e));
}
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
// noop
}
}
} } | public class class_name {
private void executeSql(Reader inputReader, Map<String, String> replacers, boolean abortOnError) {
String statement = "";
LineNumberReader reader = null;
String line = null;
// parse the setup script
try {
reader = new LineNumberReader(inputReader); // depends on control dependency: [try], data = [none]
while (true) {
line = reader.readLine(); // depends on control dependency: [while], data = [none]
if (line == null) {
break;
}
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
String currentToken = st.nextToken();
// comment! Skip rest of the line
if (currentToken.startsWith("#")) {
break;
}
// not to be executed
if (currentToken.startsWith("prompt")) {
break;
}
// add token to query
statement += " " + currentToken; // depends on control dependency: [while], data = [none]
// query complete (terminated by ';')
if (currentToken.endsWith(";")) {
// cut of ';' at the end
statement = statement.substring(0, (statement.length() - 1)); // depends on control dependency: [if], data = [none]
// normal statement, execute it
try {
if (replacers != null) {
statement = replaceTokens(statement, replacers); // depends on control dependency: [if], data = [none]
executeStatement(statement); // depends on control dependency: [if], data = [none]
} else {
executeStatement(statement); // depends on control dependency: [if], data = [none]
}
} catch (SQLException e) {
if (!abortOnError) {
if (m_errorLogging) {
m_errors.add("Error executing SQL statement: " + statement); // depends on control dependency: [if], data = [none]
m_errors.add(CmsException.getStackTraceAsString(e)); // depends on control dependency: [if], data = [none]
}
} else {
throw e;
}
} // depends on control dependency: [catch], data = [none]
// reset
statement = ""; // depends on control dependency: [if], data = [none]
}
}
statement += " \n"; // depends on control dependency: [while], data = [none]
}
} catch (SQLException e) {
if (m_errorLogging) {
m_errors.add("Error executing SQL statement: " + statement); // depends on control dependency: [if], data = [none]
m_errors.add(CmsException.getStackTraceAsString(e)); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
if (m_errorLogging) {
m_errors.add("Error parsing database setup SQL script in line: " + line); // depends on control dependency: [if], data = [none]
m_errors.add(CmsException.getStackTraceAsString(e)); // depends on control dependency: [if], data = [none]
}
} finally { // depends on control dependency: [catch], data = [none]
try {
if (reader != null) {
reader.close(); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
// noop
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public ListTasksResult withTasks(TaskListEntry... tasks) {
if (this.tasks == null) {
setTasks(new java.util.ArrayList<TaskListEntry>(tasks.length));
}
for (TaskListEntry ele : tasks) {
this.tasks.add(ele);
}
return this;
} } | public class class_name {
public ListTasksResult withTasks(TaskListEntry... tasks) {
if (this.tasks == null) {
setTasks(new java.util.ArrayList<TaskListEntry>(tasks.length)); // depends on control dependency: [if], data = [none]
}
for (TaskListEntry ele : tasks) {
this.tasks.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static float[] getDash( String dashStr ) {
if (dashStr == null) {
return null;
}
String[] dashSplit = dashStr.split(","); //$NON-NLS-1$
int size = dashSplit.length;
float[] dash = new float[size];
try {
for( int i = 0; i < dash.length; i++ ) {
dash[i] = Float.parseFloat(dashSplit[i].trim());
}
return dash;
} catch (NumberFormatException e) {
return null;
}
} } | public class class_name {
public static float[] getDash( String dashStr ) {
if (dashStr == null) {
return null; // depends on control dependency: [if], data = [none]
}
String[] dashSplit = dashStr.split(","); //$NON-NLS-1$
int size = dashSplit.length;
float[] dash = new float[size];
try {
for( int i = 0; i < dash.length; i++ ) {
dash[i] = Float.parseFloat(dashSplit[i].trim()); // depends on control dependency: [for], data = [i]
}
return dash; // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
MonocleWindow getWindow(boolean recalculateCache) {
if (window == null || recalculateCache) {
window = (MonocleWindow)
MonocleWindowManager.getInstance().getWindowForLocation(x, y);
}
return window;
} } | public class class_name {
MonocleWindow getWindow(boolean recalculateCache) {
if (window == null || recalculateCache) {
window = (MonocleWindow)
MonocleWindowManager.getInstance().getWindowForLocation(x, y); // depends on control dependency: [if], data = [none]
}
return window;
} } |
public class class_name {
public void marshall(GlobalTable globalTable, ProtocolMarshaller protocolMarshaller) {
if (globalTable == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(globalTable.getGlobalTableName(), GLOBALTABLENAME_BINDING);
protocolMarshaller.marshall(globalTable.getReplicationGroup(), REPLICATIONGROUP_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GlobalTable globalTable, ProtocolMarshaller protocolMarshaller) {
if (globalTable == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(globalTable.getGlobalTableName(), GLOBALTABLENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(globalTable.getReplicationGroup(), REPLICATIONGROUP_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 Map<String,String> parse(final char[] chars, int offset, int length, char separator) {
if (chars == null) {
return new HashMap<String,String>();
}
HashMap<String,String> params = new HashMap<String,String>();
this.chars = chars;
this.pos = offset;
this.len = length;
String paramName = null;
String paramValue = null;
while (hasChar()) {
paramName = parseToken(new char[] { '=', separator });
paramValue = null;
if (hasChar() && (chars[pos] == '=')) {
pos++; // skip '='
paramValue = parseQuotedToken(new char[] { separator });
}
if (hasChar() && (chars[pos] == separator)) {
pos++; // skip separator
}
if ((paramName != null) && (paramName.length() > 0)) {
if (this.lowerCaseNames) {
paramName = paramName.toLowerCase();
}
params.put(paramName, paramValue);
}
}
return params;
} } | public class class_name {
public Map<String,String> parse(final char[] chars, int offset, int length, char separator) {
if (chars == null) {
return new HashMap<String,String>(); // depends on control dependency: [if], data = [none]
}
HashMap<String,String> params = new HashMap<String,String>();
this.chars = chars;
this.pos = offset;
this.len = length;
String paramName = null;
String paramValue = null;
while (hasChar()) {
paramName = parseToken(new char[] { '=', separator }); // depends on control dependency: [while], data = [none]
paramValue = null; // depends on control dependency: [while], data = [none]
if (hasChar() && (chars[pos] == '=')) {
pos++; // skip '=' // depends on control dependency: [if], data = [none]
paramValue = parseQuotedToken(new char[] { separator }); // depends on control dependency: [if], data = [none]
}
if (hasChar() && (chars[pos] == separator)) {
pos++; // skip separator // depends on control dependency: [if], data = [none]
}
if ((paramName != null) && (paramName.length() > 0)) {
if (this.lowerCaseNames) {
paramName = paramName.toLowerCase(); // depends on control dependency: [if], data = [none]
}
params.put(paramName, paramValue); // depends on control dependency: [if], data = [none]
}
}
return params;
} } |
public class class_name {
private static boolean charIsEscaped(String str, int index) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "charIsEscaped", new Object[]{str, index});
// precondition, null str or out of range index returns false.
if (str == null || index < 0 || index >= str.length()) return false;
// A character is escaped if it is preceded by an odd number of '\'s.
int nEscape = 0;
int i = index-1;
while(i>=0 && str.charAt(i) == '\\') {
nEscape++;
i--;
}
boolean result = nEscape % 2 == 1 ;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "charIsEscaped", result);
return result;
} } | public class class_name {
private static boolean charIsEscaped(String str, int index) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "charIsEscaped", new Object[]{str, index});
// precondition, null str or out of range index returns false.
if (str == null || index < 0 || index >= str.length()) return false;
// A character is escaped if it is preceded by an odd number of '\'s.
int nEscape = 0;
int i = index-1;
while(i>=0 && str.charAt(i) == '\\') {
nEscape++; // depends on control dependency: [while], data = [none]
i--; // depends on control dependency: [while], data = [none]
}
boolean result = nEscape % 2 == 1 ;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "charIsEscaped", result);
return result;
} } |
public class class_name {
@Deprecated
@Override
@SuppressWarnings("unchecked")
public void serializeObject(GenericObject rec, String fieldName, String typeName, Object obj) {
if( obj == null ){
rec.add(fieldName, null);
} else if (isPrimitive(obj.getClass())){
serializePrimitive(rec, fieldName, obj);
return;
} else {
GenericObject subObject = new GenericObject(typeName, obj);
getSerializer(typeName).serialize(obj, subObject);
rec.add(fieldName, subObject);
}
} } | public class class_name {
@Deprecated
@Override
@SuppressWarnings("unchecked")
public void serializeObject(GenericObject rec, String fieldName, String typeName, Object obj) {
if( obj == null ){
rec.add(fieldName, null); // depends on control dependency: [if], data = [none]
} else if (isPrimitive(obj.getClass())){
serializePrimitive(rec, fieldName, obj); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
} else {
GenericObject subObject = new GenericObject(typeName, obj);
getSerializer(typeName).serialize(obj, subObject); // depends on control dependency: [if], data = [none]
rec.add(fieldName, subObject); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static void mergeKafka10ImportConfigurations(Map<String, ImportConfiguration> processorConfig) {
if (processorConfig.isEmpty()) {
return;
}
Map<String, ImportConfiguration> kafka10ProcessorConfigs = new HashMap<>();
Iterator<Map.Entry<String, ImportConfiguration>> iter = processorConfig.entrySet().iterator();
while (iter.hasNext()) {
String configName = iter.next().getKey();
ImportConfiguration importConfig = processorConfig.get(configName);
Properties properties = importConfig.getmoduleProperties();
String importBundleJar = properties.getProperty(ImportDataProcessor.IMPORT_MODULE);
Preconditions.checkNotNull(importBundleJar,
"Import source is undefined or custom import plugin class missing.");
//handle special cases for kafka 10 and maybe late versions
String[] bundleJar = importBundleJar.split("kafkastream");
if (bundleJar.length > 1) {
String version = bundleJar[1].substring(0, bundleJar[1].indexOf(".jar"));
if (!version.isEmpty()) {
int versionNumber = Integer.parseInt(version);
if (versionNumber == 10) {
kafka10ProcessorConfigs.put(configName, importConfig);
iter.remove();
}
}
}
}
if (kafka10ProcessorConfigs.isEmpty()) {
return;
}
Map<String, ImportConfiguration> mergedConfigs = new HashMap<>();
iter = kafka10ProcessorConfigs.entrySet().iterator();
while (iter.hasNext()) {
ImportConfiguration importConfig = iter.next().getValue();
Properties props = importConfig.getmoduleProperties();
//organize the kafka10 importer by the broker list and group id
//All importers must be configured by either broker list or zookeeper in the same group
//otherwise, these importers can not be correctly merged.
String brokers = props.getProperty("brokers");
String groupid = props.getProperty("groupid", "voltdb");
if (brokers == null) {
brokers = props.getProperty("zookeeper");
}
String brokersGroup = brokers + "_" + groupid;
ImportConfiguration config = mergedConfigs.get(brokersGroup);
if (config == null) {
mergedConfigs.put(brokersGroup, importConfig);
} else {
config.mergeProperties(props);
}
}
processorConfig.putAll(mergedConfigs);
} } | public class class_name {
private static void mergeKafka10ImportConfigurations(Map<String, ImportConfiguration> processorConfig) {
if (processorConfig.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
Map<String, ImportConfiguration> kafka10ProcessorConfigs = new HashMap<>();
Iterator<Map.Entry<String, ImportConfiguration>> iter = processorConfig.entrySet().iterator();
while (iter.hasNext()) {
String configName = iter.next().getKey();
ImportConfiguration importConfig = processorConfig.get(configName);
Properties properties = importConfig.getmoduleProperties();
String importBundleJar = properties.getProperty(ImportDataProcessor.IMPORT_MODULE);
Preconditions.checkNotNull(importBundleJar,
"Import source is undefined or custom import plugin class missing."); // depends on control dependency: [while], data = [none]
//handle special cases for kafka 10 and maybe late versions
String[] bundleJar = importBundleJar.split("kafkastream");
if (bundleJar.length > 1) {
String version = bundleJar[1].substring(0, bundleJar[1].indexOf(".jar"));
if (!version.isEmpty()) {
int versionNumber = Integer.parseInt(version);
if (versionNumber == 10) {
kafka10ProcessorConfigs.put(configName, importConfig); // depends on control dependency: [if], data = [none]
iter.remove(); // depends on control dependency: [if], data = [none]
}
}
}
}
if (kafka10ProcessorConfigs.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
Map<String, ImportConfiguration> mergedConfigs = new HashMap<>();
iter = kafka10ProcessorConfigs.entrySet().iterator();
while (iter.hasNext()) {
ImportConfiguration importConfig = iter.next().getValue();
Properties props = importConfig.getmoduleProperties();
//organize the kafka10 importer by the broker list and group id
//All importers must be configured by either broker list or zookeeper in the same group
//otherwise, these importers can not be correctly merged.
String brokers = props.getProperty("brokers");
String groupid = props.getProperty("groupid", "voltdb");
if (brokers == null) {
brokers = props.getProperty("zookeeper"); // depends on control dependency: [if], data = [none]
}
String brokersGroup = brokers + "_" + groupid;
ImportConfiguration config = mergedConfigs.get(brokersGroup);
if (config == null) {
mergedConfigs.put(brokersGroup, importConfig); // depends on control dependency: [if], data = [none]
} else {
config.mergeProperties(props); // depends on control dependency: [if], data = [none]
}
}
processorConfig.putAll(mergedConfigs);
} } |
public class class_name {
public void marshall(EndpointDescription endpointDescription, ProtocolMarshaller protocolMarshaller) {
if (endpointDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(endpointDescription.getEndpointId(), ENDPOINTID_BINDING);
protocolMarshaller.marshall(endpointDescription.getWeight(), WEIGHT_BINDING);
protocolMarshaller.marshall(endpointDescription.getHealthState(), HEALTHSTATE_BINDING);
protocolMarshaller.marshall(endpointDescription.getHealthReason(), HEALTHREASON_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(EndpointDescription endpointDescription, ProtocolMarshaller protocolMarshaller) {
if (endpointDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(endpointDescription.getEndpointId(), ENDPOINTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(endpointDescription.getWeight(), WEIGHT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(endpointDescription.getHealthState(), HEALTHSTATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(endpointDescription.getHealthReason(), HEALTHREASON_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void axpy(long n, double alpha, INDArray x, INDArray y) {
if (Nd4j.getExecutioner().getProfilingMode() == OpExecutioner.ProfilingMode.ALL)
OpProfiler.getInstance().processBlasCall(false, x, y);
if (x.isSparse() && !y.isSparse()) {
Nd4j.getSparseBlasWrapper().level1().axpy(n, alpha, x, y);
} else if (x.data().dataType() == DataBuffer.Type.DOUBLE) {
DefaultOpExecutioner.validateDataType(DataBuffer.Type.DOUBLE, x, y);
daxpy(n, alpha, x, BlasBufferUtil.getBlasStride(x), y, BlasBufferUtil.getBlasStride(y));
} else if (x.data().dataType() == DataBuffer.Type.FLOAT) {
DefaultOpExecutioner.validateDataType(DataBuffer.Type.FLOAT, x, y);
saxpy(n, (float) alpha, x, BlasBufferUtil.getBlasStride(x), y, BlasBufferUtil.getBlasStride(y));
} else {
DefaultOpExecutioner.validateDataType(DataBuffer.Type.HALF, x, y);
haxpy(n, (float) alpha, x, BlasBufferUtil.getBlasStride(x), y, BlasBufferUtil.getBlasStride(y));
}
} } | public class class_name {
@Override
public void axpy(long n, double alpha, INDArray x, INDArray y) {
if (Nd4j.getExecutioner().getProfilingMode() == OpExecutioner.ProfilingMode.ALL)
OpProfiler.getInstance().processBlasCall(false, x, y);
if (x.isSparse() && !y.isSparse()) {
Nd4j.getSparseBlasWrapper().level1().axpy(n, alpha, x, y); // depends on control dependency: [if], data = [none]
} else if (x.data().dataType() == DataBuffer.Type.DOUBLE) {
DefaultOpExecutioner.validateDataType(DataBuffer.Type.DOUBLE, x, y); // depends on control dependency: [if], data = [none]
daxpy(n, alpha, x, BlasBufferUtil.getBlasStride(x), y, BlasBufferUtil.getBlasStride(y)); // depends on control dependency: [if], data = [none]
} else if (x.data().dataType() == DataBuffer.Type.FLOAT) {
DefaultOpExecutioner.validateDataType(DataBuffer.Type.FLOAT, x, y); // depends on control dependency: [if], data = [none]
saxpy(n, (float) alpha, x, BlasBufferUtil.getBlasStride(x), y, BlasBufferUtil.getBlasStride(y)); // depends on control dependency: [if], data = [none]
} else {
DefaultOpExecutioner.validateDataType(DataBuffer.Type.HALF, x, y); // depends on control dependency: [if], data = [none]
haxpy(n, (float) alpha, x, BlasBufferUtil.getBlasStride(x), y, BlasBufferUtil.getBlasStride(y)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Collection<Container> getContainersToStop(final ImageConfiguration image,
final String defaultContainerNamePattern,
final Date buildTimestamp,
final Collection<Container> containers) {
String containerNamePattern = extractContainerNamePattern(image, defaultContainerNamePattern);
// Only special treatment for indexed container names
if (!containerNamePattern.contains(INDEX_PLACEHOLDER)) {
return containers;
}
final String partiallyApplied =
replacePlaceholders(
containerNamePattern,
image.getName(),
image.getAlias(),
buildTimestamp);
return keepOnlyLastIndexedContainer(containers, partiallyApplied);
} } | public class class_name {
public static Collection<Container> getContainersToStop(final ImageConfiguration image,
final String defaultContainerNamePattern,
final Date buildTimestamp,
final Collection<Container> containers) {
String containerNamePattern = extractContainerNamePattern(image, defaultContainerNamePattern);
// Only special treatment for indexed container names
if (!containerNamePattern.contains(INDEX_PLACEHOLDER)) {
return containers; // depends on control dependency: [if], data = [none]
}
final String partiallyApplied =
replacePlaceholders(
containerNamePattern,
image.getName(),
image.getAlias(),
buildTimestamp);
return keepOnlyLastIndexedContainer(containers, partiallyApplied);
} } |
public class class_name {
public Long hincrBy(Object key, Object field, long value) {
Jedis jedis = getJedis();
try {
return jedis.hincrBy(keyToBytes(key), fieldToBytes(field), value);
}
finally {close(jedis);}
} } | public class class_name {
public Long hincrBy(Object key, Object field, long value) {
Jedis jedis = getJedis();
try {
return jedis.hincrBy(keyToBytes(key), fieldToBytes(field), value);
// depends on control dependency: [try], data = [none]
}
finally {close(jedis);}
} } |
public class class_name {
public boolean setDbParamaters(
Map<String, String[]> request,
String provider,
String contextPath,
HttpSession session) {
String conStr = getReqValue(request, "dbCreateConStr");
// store the DB provider
m_provider = provider;
boolean isFormSubmitted = ((getReqValue(request, "submit") != null) && (conStr != null));
if (conStr == null) {
conStr = "";
}
String database = "";
if (provider.equals(MYSQL_PROVIDER)
|| provider.equals(MSSQL_PROVIDER)
|| provider.equals(DB2_PROVIDER)
|| provider.equals(AS400_PROVIDER)) {
database = getReqValue(request, "db");
} else if (provider.equals(POSTGRESQL_PROVIDER)) {
database = getReqValue(request, "dbName");
}
if (provider.equals(MYSQL_PROVIDER)
|| provider.equals(MSSQL_PROVIDER)
|| provider.equals(POSTGRESQL_PROVIDER)
|| provider.equals(AS400_PROVIDER)
|| provider.equals(DB2_PROVIDER)) {
isFormSubmitted = (isFormSubmitted && (database != null));
}
if (!(MAXDB_PROVIDER.equals(provider)
|| MSSQL_PROVIDER.equals(provider)
|| MYSQL_PROVIDER.equals(provider)
|| ORACLE_PROVIDER.equals(provider)
|| DB2_PROVIDER.equals(provider)
|| AS400_PROVIDER.equals(provider)
|| HSQLDB_PROVIDER.equals(provider)
|| POSTGRESQL_PROVIDER.equals(provider))) {
throw new RuntimeException("Database provider '" + provider + "' not supported!");
}
if (isInitialized()) {
String createDb = getReqValue(request, "createDb");
if ((createDb == null) || provider.equals(DB2_PROVIDER) || provider.equals(AS400_PROVIDER)) {
createDb = "";
}
String createTables = getReqValue(request, "createTables");
if (createTables == null) {
createTables = "";
}
if (isFormSubmitted) {
if (provider.equals(POSTGRESQL_PROVIDER)) {
setDb(database);
String templateDb = getReqValue(request, "templateDb");
setDbProperty(getDatabase() + ".templateDb", templateDb);
setDbProperty(getDatabase() + ".newDb", database);
if (!conStr.endsWith("/")) {
conStr += "/";
}
setDbProperty(getDatabase() + ".constr", conStr + getDbProperty(getDatabase() + ".templateDb"));
setDbProperty(getDatabase() + ".constr.newDb", conStr + getDbProperty(getDatabase() + ".newDb"));
conStr += database;
} else if (provider.equals(MYSQL_PROVIDER)
|| provider.equals(DB2_PROVIDER)
|| provider.equals(MSSQL_PROVIDER)
|| provider.equals(POSTGRESQL_PROVIDER)) {
if (!conStr.endsWith("/")) {
conStr += "/";
}
conStr += database;
} else if (provider.equals(AS400_PROVIDER)) {
if (conStr.endsWith("/")) {
conStr = conStr.substring(0, conStr.length() - 1);
}
if (!conStr.endsWith(";")) {
conStr += ";";
}
conStr += "libraries='" + database + "'";
}
setDbWorkConStr(conStr);
if (provider.equals(POSTGRESQL_PROVIDER)) {
setDb(database);
}
String dbCreateUser = getReqValue(request, "dbCreateUser");
String dbCreatePwd = getReqValue(request, "dbCreatePwd");
String dbWorkUser = getReqValue(request, "dbWorkUser");
String dbWorkPwd = getReqValue(request, "dbWorkPwd");
if ((dbCreateUser != null) && !provider.equals(DB2_PROVIDER) && !provider.equals(AS400_PROVIDER)) {
setDbCreateUser(dbCreateUser);
}
setDbCreatePwd(dbCreatePwd);
if (dbWorkUser.equals("")) {
dbWorkUser = contextPath;
}
if (dbWorkUser.equals("")) {
dbWorkUser = "opencms";
}
if (dbWorkUser.startsWith("/")) {
dbWorkUser = dbWorkUser.substring(1, dbWorkUser.length());
}
setDbWorkUser(dbWorkUser);
setDbWorkPwd(dbWorkPwd);
if (provider.equals(ORACLE_PROVIDER)) {
String dbDefaultTablespace = getReqValue(request, "dbDefaultTablespace");
String dbTemporaryTablespace = getReqValue(request, "dbTemporaryTablespace");
String dbIndexTablespace = getReqValue(request, "dbIndexTablespace");
setDbProperty(getDatabase() + ".defaultTablespace", dbDefaultTablespace);
setDbProperty(getDatabase() + ".temporaryTablespace", dbTemporaryTablespace);
setDbProperty(getDatabase() + ".indexTablespace", dbIndexTablespace);
}
Map<String, String> replacer = new HashMap<String, String>();
if (!provider.equals(MYSQL_PROVIDER) || provider.equals(MSSQL_PROVIDER)) {
replacer.put("${user}", dbWorkUser);
replacer.put("${password}", dbWorkPwd);
}
if (provider.equals(MYSQL_PROVIDER)
|| provider.equals(MSSQL_PROVIDER)
|| provider.equals(POSTGRESQL_PROVIDER)) {
replacer.put("${database}", database);
}
if (provider.equals(ORACLE_PROVIDER)) {
replacer.put("${defaultTablespace}", getDbProperty(getDatabase() + ".defaultTablespace"));
replacer.put("${indexTablespace}", getDbProperty(getDatabase() + ".indexTablespace"));
replacer.put("${temporaryTablespace}", getDbProperty(getDatabase() + ".temporaryTablespace"));
}
setReplacer(replacer);
if (session != null) {
if (provider.equals(GENERIC_PROVIDER)
|| provider.equals(ORACLE_PROVIDER)
|| provider.equals(DB2_PROVIDER)
|| provider.equals(AS400_PROVIDER)
|| provider.equals(MAXDB_PROVIDER)) {
session.setAttribute("createTables", createTables);
}
session.setAttribute("createDb", createDb);
}
} else {
String dbName = "opencms";
// initialize the database name with the app name
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(contextPath)) {
dbName = contextPath.substring(1);
}
if (provider.equals(ORACLE_PROVIDER)
|| provider.equals(POSTGRESQL_PROVIDER)
|| provider.equals(MAXDB_PROVIDER)) {
setDbWorkUser(dbName);
} else if (dbName != null) {
setDb(dbName);
}
}
}
return isFormSubmitted;
} } | public class class_name {
public boolean setDbParamaters(
Map<String, String[]> request,
String provider,
String contextPath,
HttpSession session) {
String conStr = getReqValue(request, "dbCreateConStr");
// store the DB provider
m_provider = provider;
boolean isFormSubmitted = ((getReqValue(request, "submit") != null) && (conStr != null));
if (conStr == null) {
conStr = ""; // depends on control dependency: [if], data = [none]
}
String database = "";
if (provider.equals(MYSQL_PROVIDER)
|| provider.equals(MSSQL_PROVIDER)
|| provider.equals(DB2_PROVIDER)
|| provider.equals(AS400_PROVIDER)) {
database = getReqValue(request, "db"); // depends on control dependency: [if], data = [none]
} else if (provider.equals(POSTGRESQL_PROVIDER)) {
database = getReqValue(request, "dbName"); // depends on control dependency: [if], data = [none]
}
if (provider.equals(MYSQL_PROVIDER)
|| provider.equals(MSSQL_PROVIDER)
|| provider.equals(POSTGRESQL_PROVIDER)
|| provider.equals(AS400_PROVIDER)
|| provider.equals(DB2_PROVIDER)) {
isFormSubmitted = (isFormSubmitted && (database != null)); // depends on control dependency: [if], data = [none]
}
if (!(MAXDB_PROVIDER.equals(provider)
|| MSSQL_PROVIDER.equals(provider)
|| MYSQL_PROVIDER.equals(provider)
|| ORACLE_PROVIDER.equals(provider)
|| DB2_PROVIDER.equals(provider)
|| AS400_PROVIDER.equals(provider)
|| HSQLDB_PROVIDER.equals(provider)
|| POSTGRESQL_PROVIDER.equals(provider))) {
throw new RuntimeException("Database provider '" + provider + "' not supported!");
}
if (isInitialized()) {
String createDb = getReqValue(request, "createDb");
if ((createDb == null) || provider.equals(DB2_PROVIDER) || provider.equals(AS400_PROVIDER)) {
createDb = ""; // depends on control dependency: [if], data = [none]
}
String createTables = getReqValue(request, "createTables");
if (createTables == null) {
createTables = ""; // depends on control dependency: [if], data = [none]
}
if (isFormSubmitted) {
if (provider.equals(POSTGRESQL_PROVIDER)) {
setDb(database); // depends on control dependency: [if], data = [none]
String templateDb = getReqValue(request, "templateDb");
setDbProperty(getDatabase() + ".templateDb", templateDb); // depends on control dependency: [if], data = [none]
setDbProperty(getDatabase() + ".newDb", database); // depends on control dependency: [if], data = [none]
if (!conStr.endsWith("/")) {
conStr += "/"; // depends on control dependency: [if], data = [none]
}
setDbProperty(getDatabase() + ".constr", conStr + getDbProperty(getDatabase() + ".templateDb")); // depends on control dependency: [if], data = [none]
setDbProperty(getDatabase() + ".constr.newDb", conStr + getDbProperty(getDatabase() + ".newDb")); // depends on control dependency: [if], data = [none]
conStr += database; // depends on control dependency: [if], data = [none]
} else if (provider.equals(MYSQL_PROVIDER)
|| provider.equals(DB2_PROVIDER)
|| provider.equals(MSSQL_PROVIDER)
|| provider.equals(POSTGRESQL_PROVIDER)) {
if (!conStr.endsWith("/")) {
conStr += "/"; // depends on control dependency: [if], data = [none]
}
conStr += database; // depends on control dependency: [if], data = [none]
} else if (provider.equals(AS400_PROVIDER)) {
if (conStr.endsWith("/")) {
conStr = conStr.substring(0, conStr.length() - 1); // depends on control dependency: [if], data = [none]
}
if (!conStr.endsWith(";")) {
conStr += ";"; // depends on control dependency: [if], data = [none]
}
conStr += "libraries='" + database + "'"; // depends on control dependency: [if], data = [none]
}
setDbWorkConStr(conStr); // depends on control dependency: [if], data = [none]
if (provider.equals(POSTGRESQL_PROVIDER)) {
setDb(database); // depends on control dependency: [if], data = [none]
}
String dbCreateUser = getReqValue(request, "dbCreateUser");
String dbCreatePwd = getReqValue(request, "dbCreatePwd");
String dbWorkUser = getReqValue(request, "dbWorkUser");
String dbWorkPwd = getReqValue(request, "dbWorkPwd");
if ((dbCreateUser != null) && !provider.equals(DB2_PROVIDER) && !provider.equals(AS400_PROVIDER)) {
setDbCreateUser(dbCreateUser); // depends on control dependency: [if], data = [none]
}
setDbCreatePwd(dbCreatePwd); // depends on control dependency: [if], data = [none]
if (dbWorkUser.equals("")) {
dbWorkUser = contextPath; // depends on control dependency: [if], data = [none]
}
if (dbWorkUser.equals("")) {
dbWorkUser = "opencms"; // depends on control dependency: [if], data = [none]
}
if (dbWorkUser.startsWith("/")) {
dbWorkUser = dbWorkUser.substring(1, dbWorkUser.length()); // depends on control dependency: [if], data = [none]
}
setDbWorkUser(dbWorkUser); // depends on control dependency: [if], data = [none]
setDbWorkPwd(dbWorkPwd); // depends on control dependency: [if], data = [none]
if (provider.equals(ORACLE_PROVIDER)) {
String dbDefaultTablespace = getReqValue(request, "dbDefaultTablespace");
String dbTemporaryTablespace = getReqValue(request, "dbTemporaryTablespace");
String dbIndexTablespace = getReqValue(request, "dbIndexTablespace");
setDbProperty(getDatabase() + ".defaultTablespace", dbDefaultTablespace); // depends on control dependency: [if], data = [none]
setDbProperty(getDatabase() + ".temporaryTablespace", dbTemporaryTablespace); // depends on control dependency: [if], data = [none]
setDbProperty(getDatabase() + ".indexTablespace", dbIndexTablespace); // depends on control dependency: [if], data = [none]
}
Map<String, String> replacer = new HashMap<String, String>();
if (!provider.equals(MYSQL_PROVIDER) || provider.equals(MSSQL_PROVIDER)) {
replacer.put("${user}", dbWorkUser); // depends on control dependency: [if], data = [none]
replacer.put("${password}", dbWorkPwd); // depends on control dependency: [if], data = [none]
}
if (provider.equals(MYSQL_PROVIDER)
|| provider.equals(MSSQL_PROVIDER)
|| provider.equals(POSTGRESQL_PROVIDER)) {
replacer.put("${database}", database); // depends on control dependency: [if], data = [none]
}
if (provider.equals(ORACLE_PROVIDER)) {
replacer.put("${defaultTablespace}", getDbProperty(getDatabase() + ".defaultTablespace")); // depends on control dependency: [if], data = [none]
replacer.put("${indexTablespace}", getDbProperty(getDatabase() + ".indexTablespace")); // depends on control dependency: [if], data = [none]
replacer.put("${temporaryTablespace}", getDbProperty(getDatabase() + ".temporaryTablespace")); // depends on control dependency: [if], data = [none]
}
setReplacer(replacer); // depends on control dependency: [if], data = [none]
if (session != null) {
if (provider.equals(GENERIC_PROVIDER)
|| provider.equals(ORACLE_PROVIDER)
|| provider.equals(DB2_PROVIDER)
|| provider.equals(AS400_PROVIDER)
|| provider.equals(MAXDB_PROVIDER)) {
session.setAttribute("createTables", createTables); // depends on control dependency: [if], data = [none]
}
session.setAttribute("createDb", createDb); // depends on control dependency: [if], data = [none]
}
} else {
String dbName = "opencms";
// initialize the database name with the app name
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(contextPath)) {
dbName = contextPath.substring(1); // depends on control dependency: [if], data = [none]
}
if (provider.equals(ORACLE_PROVIDER)
|| provider.equals(POSTGRESQL_PROVIDER)
|| provider.equals(MAXDB_PROVIDER)) {
setDbWorkUser(dbName); // depends on control dependency: [if], data = [none]
} else if (dbName != null) {
setDb(dbName); // depends on control dependency: [if], data = [(dbName]
}
}
}
return isFormSubmitted;
} } |
public class class_name {
public java.util.List<SystemControl> getSystemControls() {
if (systemControls == null) {
systemControls = new com.amazonaws.internal.SdkInternalList<SystemControl>();
}
return systemControls;
} } | public class class_name {
public java.util.List<SystemControl> getSystemControls() {
if (systemControls == null) {
systemControls = new com.amazonaws.internal.SdkInternalList<SystemControl>(); // depends on control dependency: [if], data = [none]
}
return systemControls;
} } |
public class class_name {
private void failover(long globalModVersionOfFailover) {
if (!executionGraph.getRestartStrategy().canRestart()) {
executionGraph.failGlobal(new FlinkException("RestartStrategy validate fail"));
}
else {
JobStatus curStatus = this.state;
if (curStatus.equals(JobStatus.RUNNING)) {
cancel(globalModVersionOfFailover);
}
else if (curStatus.equals(JobStatus.CANCELED)) {
reset(globalModVersionOfFailover);
}
else {
LOG.info("FailoverRegion {} is {} when notified to failover.", id, state);
}
}
} } | public class class_name {
private void failover(long globalModVersionOfFailover) {
if (!executionGraph.getRestartStrategy().canRestart()) {
executionGraph.failGlobal(new FlinkException("RestartStrategy validate fail")); // depends on control dependency: [if], data = [none]
}
else {
JobStatus curStatus = this.state;
if (curStatus.equals(JobStatus.RUNNING)) {
cancel(globalModVersionOfFailover); // depends on control dependency: [if], data = [none]
}
else if (curStatus.equals(JobStatus.CANCELED)) {
reset(globalModVersionOfFailover); // depends on control dependency: [if], data = [none]
}
else {
LOG.info("FailoverRegion {} is {} when notified to failover.", id, state); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private Boolean getBooleanParameter(String key){
Integer i = (Integer)parameters.get(key);
if (i == null){
return null;
}
return i.equals(1);
} } | public class class_name {
private Boolean getBooleanParameter(String key){
Integer i = (Integer)parameters.get(key);
if (i == null){
return null; // depends on control dependency: [if], data = [none]
}
return i.equals(1);
} } |
public class class_name {
public void init(
AOStream parent,
String selectionCriteriasAsString,
ConsumableKey[] consumerKeys,
long idleTimeout,
MPAlarmManager am,
SelectionCriteria[] selectionCriterias)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"init",
new Object[] {
parent,
selectionCriteriasAsString,
consumerKeys,
Long.valueOf(idleTimeout),
am,
selectionCriterias });
this.lock();
try
{
this.parent = parent;
this.selectionCriteriasAsString = selectionCriteriasAsString;
this.cks = consumerKeys;
this.ck = consumerKeys[0];
this.selectionCriterias = selectionCriterias;
this.isready = false;
this.dispatcher = cks[0].getConsumerManager(); // all cks[i] have the same ConsumerDispatcher
this.temporarilyStopped = !dispatcher.getDestination().isReceiveAllowed();
this.closed = false;
this.listOfRequests = new LinkedList();
this.tableOfRequests = new HashMap<Long, AORequestedTick>();
this.idleTimeout = idleTimeout;
this.am = am;
if (ck instanceof GatheringConsumerKey)
this.gatherMessages = true;
if (idleTimeout > 0)
this.idleHandler = am.create(idleTimeout, this);
}
finally
{
this.unlock();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "init");
} } | public class class_name {
public void init(
AOStream parent,
String selectionCriteriasAsString,
ConsumableKey[] consumerKeys,
long idleTimeout,
MPAlarmManager am,
SelectionCriteria[] selectionCriterias)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"init",
new Object[] {
parent,
selectionCriteriasAsString,
consumerKeys,
Long.valueOf(idleTimeout),
am,
selectionCriterias });
this.lock();
try
{
this.parent = parent; // depends on control dependency: [try], data = [none]
this.selectionCriteriasAsString = selectionCriteriasAsString; // depends on control dependency: [try], data = [none]
this.cks = consumerKeys; // depends on control dependency: [try], data = [none]
this.ck = consumerKeys[0]; // depends on control dependency: [try], data = [none]
this.selectionCriterias = selectionCriterias; // depends on control dependency: [try], data = [none]
this.isready = false; // depends on control dependency: [try], data = [none]
this.dispatcher = cks[0].getConsumerManager(); // all cks[i] have the same ConsumerDispatcher // depends on control dependency: [try], data = [none]
this.temporarilyStopped = !dispatcher.getDestination().isReceiveAllowed(); // depends on control dependency: [try], data = [none]
this.closed = false; // depends on control dependency: [try], data = [none]
this.listOfRequests = new LinkedList(); // depends on control dependency: [try], data = [none]
this.tableOfRequests = new HashMap<Long, AORequestedTick>(); // depends on control dependency: [try], data = [none]
this.idleTimeout = idleTimeout; // depends on control dependency: [try], data = [none]
this.am = am; // depends on control dependency: [try], data = [none]
if (ck instanceof GatheringConsumerKey)
this.gatherMessages = true;
if (idleTimeout > 0)
this.idleHandler = am.create(idleTimeout, this);
}
finally
{
this.unlock();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "init");
} } |
public class class_name {
public T queryString(String name, String value) {
List<String> l = queryString.get(name);
if (l == null) {
l = new ArrayList<String>();
}
l.add(value);
queryString.put(name, l);
return derived.cast(this);
} } | public class class_name {
public T queryString(String name, String value) {
List<String> l = queryString.get(name);
if (l == null) {
l = new ArrayList<String>(); // depends on control dependency: [if], data = [none]
}
l.add(value);
queryString.put(name, l);
return derived.cast(this);
} } |
public class class_name {
public static PeriodFormatter wordBased(Locale locale) {
PeriodFormatter pf = FORMATTERS.get(locale);
if (pf == null) {
DynamicWordBased dynamic = new DynamicWordBased(buildWordBased(locale));
pf = new PeriodFormatter(dynamic, dynamic, locale, null);
PeriodFormatter existing = FORMATTERS.putIfAbsent(locale, pf);
if (existing != null) {
pf = existing;
}
}
return pf;
} } | public class class_name {
public static PeriodFormatter wordBased(Locale locale) {
PeriodFormatter pf = FORMATTERS.get(locale);
if (pf == null) {
DynamicWordBased dynamic = new DynamicWordBased(buildWordBased(locale));
pf = new PeriodFormatter(dynamic, dynamic, locale, null); // depends on control dependency: [if], data = [null)]
PeriodFormatter existing = FORMATTERS.putIfAbsent(locale, pf);
if (existing != null) {
pf = existing; // depends on control dependency: [if], data = [none]
}
}
return pf;
} } |
public class class_name {
@Override
public synchronized List<String> lookup(QName serviceName, SLPropertiesMatcher matcher)
throws ServiceLocatorException, InterruptedException {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Looking up endpoints of service " + serviceName + "...");
}
List<String> liveEndpoints;
RootNode rootNode = getBackend().connect();
ServiceNode serviceNode = rootNode.getServiceNode(serviceName);
if (serviceNode.exists()) {
liveEndpoints = new ArrayList<String>();
List<EndpointNode> endpointNodes = serviceNode.getEndPoints();
for (EndpointNode endpointNode : endpointNodes) {
if (endpointNode.isLive()) {
byte[] content = endpointNode.getContent();
SLEndpoint endpoint = transformer.toSLEndpoint(serviceName, content, true);
SLProperties props = endpoint.getProperties();
if (LOG.isLoggable(Level.FINE)) {
StringBuilder sb = new StringBuilder();
for (String prop : props.getPropertyNames()) {
sb.append(prop + " : ");
for (String value : props.getValues(prop)) {
sb.append(value + " ");
}
sb.append("\n");
}
LOG.fine("Lookup of service " + serviceName + " props = " + sb.toString());
LOG.fine("matcher = " + matcher.toString());
}
if (matcher.isMatching(props)) {
liveEndpoints.add(endpointNode.getEndpointName());
if (LOG.isLoggable(Level.FINE))
LOG.fine("matched = " + endpointNode.getEndpointName());
} else if (LOG.isLoggable(Level.FINE))
LOG.fine("not matched = " + endpointNode.getEndpointName());
}
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Lookup of service " + serviceName + " failed, service is not known.");
}
liveEndpoints = Collections.emptyList();
}
return liveEndpoints;
} } | public class class_name {
@Override
public synchronized List<String> lookup(QName serviceName, SLPropertiesMatcher matcher)
throws ServiceLocatorException, InterruptedException {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Looking up endpoints of service " + serviceName + "...");
}
List<String> liveEndpoints;
RootNode rootNode = getBackend().connect();
ServiceNode serviceNode = rootNode.getServiceNode(serviceName);
if (serviceNode.exists()) {
liveEndpoints = new ArrayList<String>();
List<EndpointNode> endpointNodes = serviceNode.getEndPoints();
for (EndpointNode endpointNode : endpointNodes) {
if (endpointNode.isLive()) {
byte[] content = endpointNode.getContent();
SLEndpoint endpoint = transformer.toSLEndpoint(serviceName, content, true);
SLProperties props = endpoint.getProperties();
if (LOG.isLoggable(Level.FINE)) {
StringBuilder sb = new StringBuilder();
for (String prop : props.getPropertyNames()) {
sb.append(prop + " : "); // depends on control dependency: [for], data = [prop]
for (String value : props.getValues(prop)) {
sb.append(value + " "); // depends on control dependency: [for], data = [value]
}
sb.append("\n"); // depends on control dependency: [for], data = [none]
}
LOG.fine("Lookup of service " + serviceName + " props = " + sb.toString()); // depends on control dependency: [if], data = [none]
LOG.fine("matcher = " + matcher.toString()); // depends on control dependency: [if], data = [none]
}
if (matcher.isMatching(props)) {
liveEndpoints.add(endpointNode.getEndpointName()); // depends on control dependency: [if], data = [none]
if (LOG.isLoggable(Level.FINE))
LOG.fine("matched = " + endpointNode.getEndpointName());
} else if (LOG.isLoggable(Level.FINE))
LOG.fine("not matched = " + endpointNode.getEndpointName());
}
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Lookup of service " + serviceName + " failed, service is not known.");
}
liveEndpoints = Collections.emptyList();
}
return liveEndpoints;
} } |
public class class_name {
protected void init(CmsObject cms, CmsResource imageRes, String scaleParams) {
setCmsObject(cms);
// set VFS URI without scaling parameters
setResource(cms, imageRes);
setVfsUri(cms.getRequestContext().getSitePath(imageRes));
// the originalScaler reads the image dimensions from the VFS properties
CmsImageScaler originalScaler = new CmsImageScaler(cms, getResource());
// set original scaler
setOriginalScaler(originalScaler);
// set base scaler
CmsImageScaler baseScaler = originalScaler;
if (scaleParams != null) {
// scale parameters have been set
baseScaler = new CmsImageScaler(scaleParams);
baseScaler.setFocalPoint(originalScaler.getFocalPoint());
}
setBaseScaler(baseScaler);
// set the current scaler to the base scaler
setScaler(baseScaler);
} } | public class class_name {
protected void init(CmsObject cms, CmsResource imageRes, String scaleParams) {
setCmsObject(cms);
// set VFS URI without scaling parameters
setResource(cms, imageRes);
setVfsUri(cms.getRequestContext().getSitePath(imageRes));
// the originalScaler reads the image dimensions from the VFS properties
CmsImageScaler originalScaler = new CmsImageScaler(cms, getResource());
// set original scaler
setOriginalScaler(originalScaler);
// set base scaler
CmsImageScaler baseScaler = originalScaler;
if (scaleParams != null) {
// scale parameters have been set
baseScaler = new CmsImageScaler(scaleParams); // depends on control dependency: [if], data = [(scaleParams]
baseScaler.setFocalPoint(originalScaler.getFocalPoint()); // depends on control dependency: [if], data = [none]
}
setBaseScaler(baseScaler);
// set the current scaler to the base scaler
setScaler(baseScaler);
} } |
public class class_name {
@RequestMapping ( "/{id}/monitor" )
public ModelAndView monitor ( @PathVariable ( "id" ) final String id)
{
final JobHandle job = this.manager.getJob ( id );
if ( job != null )
{
logger.debug ( "Job: {} - {}", job.getId (), job.getState () );
}
else
{
logger.debug ( "No job: {}", id );
}
final Map<String, Object> model = new HashMap<> ( 1 );
model.put ( "job", job );
return new ModelAndView ( "monitor", model );
} } | public class class_name {
@RequestMapping ( "/{id}/monitor" )
public ModelAndView monitor ( @PathVariable ( "id" ) final String id)
{
final JobHandle job = this.manager.getJob ( id );
if ( job != null )
{
logger.debug ( "Job: {} - {}", job.getId (), job.getState () ); // depends on control dependency: [if], data = [none]
}
else
{
logger.debug ( "No job: {}", id ); // depends on control dependency: [if], data = [none]
}
final Map<String, Object> model = new HashMap<> ( 1 );
model.put ( "job", job );
return new ModelAndView ( "monitor", model );
} } |
public class class_name {
public Decision<JobXMLDescriptor> getOrCreateDecision()
{
List<Node> nodeList = model.get("decision");
if (nodeList != null && nodeList.size() > 0)
{
return new DecisionImpl<JobXMLDescriptor>(this, "decision", model, nodeList.get(0));
}
return createDecision();
} } | public class class_name {
public Decision<JobXMLDescriptor> getOrCreateDecision()
{
List<Node> nodeList = model.get("decision");
if (nodeList != null && nodeList.size() > 0)
{
return new DecisionImpl<JobXMLDescriptor>(this, "decision", model, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createDecision();
} } |
public class class_name {
private void buildDawg(Keyset keyset, DawgBuilder dawgBuilder)
{
dawgBuilder.init();
for (int i = 0; i < keyset.numKeys(); ++i)
{
dawgBuilder.insert(keyset.getKey(i), keyset.getValue(i));
}
dawgBuilder.finish();
} } | public class class_name {
private void buildDawg(Keyset keyset, DawgBuilder dawgBuilder)
{
dawgBuilder.init();
for (int i = 0; i < keyset.numKeys(); ++i)
{
dawgBuilder.insert(keyset.getKey(i), keyset.getValue(i)); // depends on control dependency: [for], data = [i]
}
dawgBuilder.finish();
} } |
public class class_name {
public static float[] doubleArrayToFloatArray(double[] a) {
float[] result = new float[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = (float) a[i];
}
return result;
} } | public class class_name {
public static float[] doubleArrayToFloatArray(double[] a) {
float[] result = new float[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = (float) a[i];
// depends on control dependency: [for], data = [i]
}
return result;
} } |
public class class_name {
private static List<String> splitAddress(String addresses){
if(StrUtil.isBlank(addresses)) {
return null;
}
List<String> result;
if(StrUtil.contains(addresses, ',')) {
result = StrUtil.splitTrim(addresses, ',');
}else if(StrUtil.contains(addresses, ';')) {
result = StrUtil.splitTrim(addresses, ';');
}else {
result = CollUtil.newArrayList(addresses);
}
return result;
} } | public class class_name {
private static List<String> splitAddress(String addresses){
if(StrUtil.isBlank(addresses)) {
return null;
// depends on control dependency: [if], data = [none]
}
List<String> result;
if(StrUtil.contains(addresses, ',')) {
result = StrUtil.splitTrim(addresses, ',');
// depends on control dependency: [if], data = [none]
}else if(StrUtil.contains(addresses, ';')) {
result = StrUtil.splitTrim(addresses, ';');
// depends on control dependency: [if], data = [none]
}else {
result = CollUtil.newArrayList(addresses);
// depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
protected void completeSarlAgents(boolean allowAgentType, boolean isExtensionFilter, ContentAssistContext context,
ICompletionProposalAcceptor acceptor) {
if (isSarlProposalEnabled()) {
completeSubJavaTypes(Agent.class, allowAgentType, context,
TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE,
getQualifiedNameValueConverter(),
isExtensionFilter ? createExtensionFilter(context, IJavaSearchConstants.CLASS)
: createVisibilityFilter(context, IJavaSearchConstants.CLASS), acceptor);
}
} } | public class class_name {
protected void completeSarlAgents(boolean allowAgentType, boolean isExtensionFilter, ContentAssistContext context,
ICompletionProposalAcceptor acceptor) {
if (isSarlProposalEnabled()) {
completeSubJavaTypes(Agent.class, allowAgentType, context,
TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE,
getQualifiedNameValueConverter(),
isExtensionFilter ? createExtensionFilter(context, IJavaSearchConstants.CLASS)
: createVisibilityFilter(context, IJavaSearchConstants.CLASS), acceptor); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean isCommitted()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{ // 306998.15
Tr.debug(tc, "isCommitted: " + committed);
}
return committed;
} } | public class class_name {
public boolean isCommitted()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{ // 306998.15
Tr.debug(tc, "isCommitted: " + committed); // depends on control dependency: [if], data = [none]
}
return committed;
} } |
public class class_name {
@Override
public void notifyChanged(IChemObjectChangeEvent evt) {
if (getNotification() && getListenerCount() > 0) {
List<IChemObjectListener> listeners = lazyChemObjectListeners();
for (Object listener : listeners) {
((IChemObjectListener) listener).stateChanged(evt);
}
}
} } | public class class_name {
@Override
public void notifyChanged(IChemObjectChangeEvent evt) {
if (getNotification() && getListenerCount() > 0) {
List<IChemObjectListener> listeners = lazyChemObjectListeners();
for (Object listener : listeners) {
((IChemObjectListener) listener).stateChanged(evt); // depends on control dependency: [for], data = [listener]
}
}
} } |
public class class_name {
public void releaseAll() {
synchronized(this) {
Object[] refSet = allocatedMemoryReferences.values().toArray();
if(refSet.length != 0) {
logger.finer("Releasing allocated memory regions");
}
for(Object ref : refSet) {
release((MemoryReference) ref);
}
}
} } | public class class_name {
public void releaseAll() {
synchronized(this) {
Object[] refSet = allocatedMemoryReferences.values().toArray();
if(refSet.length != 0) {
logger.finer("Releasing allocated memory regions"); // depends on control dependency: [if], data = [none]
}
for(Object ref : refSet) {
release((MemoryReference) ref); // depends on control dependency: [for], data = [ref]
}
}
} } |
public class class_name {
@Override
public void provideServiceability() {
Exception e = new Exception();
try {
FFDCFilter.processException(e, "com.ibm.ws.recoverylog.custom.jdbc.impl.SQLMultiScopeRecoveryLog.provideServiceability", "3624", this);
HashMap<Long, RecoverableUnit> rus = _recoverableUnits;
if (rus != null)
FFDCFilter.processException(e, "com.ibm.ws.recoverylog.custom.jdbc.impl.SQLMultiScopeRecoveryLog.provideServiceability", "3628", rus);
} catch (Exception ex) {
// Do nothing
}
} } | public class class_name {
@Override
public void provideServiceability() {
Exception e = new Exception();
try {
FFDCFilter.processException(e, "com.ibm.ws.recoverylog.custom.jdbc.impl.SQLMultiScopeRecoveryLog.provideServiceability", "3624", this); // depends on control dependency: [try], data = [none]
HashMap<Long, RecoverableUnit> rus = _recoverableUnits;
if (rus != null)
FFDCFilter.processException(e, "com.ibm.ws.recoverylog.custom.jdbc.impl.SQLMultiScopeRecoveryLog.provideServiceability", "3628", rus);
} catch (Exception ex) {
// Do nothing
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public URL getResource(String path) throws MalformedURLException {
if (!path.startsWith("/"))
throw new MalformedURLException("Path '" + path +
"' does not start with '/'");
URL url = new URL(myResourceBaseURL, path.substring(1));
InputStream is = null;
try {
is = url.openStream();
} catch (Throwable t) {
url = null;
} finally {
if (is != null) {
try {
is.close();
} catch (Throwable t2) {
// Ignore
}
}
}
return url;
} } | public class class_name {
public URL getResource(String path) throws MalformedURLException {
if (!path.startsWith("/"))
throw new MalformedURLException("Path '" + path +
"' does not start with '/'");
URL url = new URL(myResourceBaseURL, path.substring(1));
InputStream is = null;
try {
is = url.openStream();
} catch (Throwable t) {
url = null;
} finally {
if (is != null) {
try {
is.close(); // depends on control dependency: [try], data = [none]
} catch (Throwable t2) {
// Ignore
} // depends on control dependency: [catch], data = [none]
}
}
return url;
} } |
public class class_name {
public static int count(String str,String target){
int count=0;
int index=0;
while(true){
index=str.indexOf(target,index+1);
if(index>0){
count++;
}else{
break;
}
}
return count;
} } | public class class_name {
public static int count(String str,String target){
int count=0;
int index=0;
while(true){
index=str.indexOf(target,index+1); // depends on control dependency: [while], data = [none]
if(index>0){
count++; // depends on control dependency: [if], data = [none]
}else{
break;
}
}
return count;
} } |
public class class_name {
private void updateFontButton(@Nonnull final MindMapPanelConfig config) {
final String strStyle;
final Font thefont = config.getFont();
if (thefont.isBold()) {
strStyle = thefont.isItalic() ? "bolditalic" : "bold";
} else {
strStyle = thefont.isItalic() ? "italic" : "plain";
}
this.buttonFont.setText(thefont.getName() + ", " + strStyle + ", " + thefont.getSize());
} } | public class class_name {
private void updateFontButton(@Nonnull final MindMapPanelConfig config) {
final String strStyle;
final Font thefont = config.getFont();
if (thefont.isBold()) {
strStyle = thefont.isItalic() ? "bolditalic" : "bold"; // depends on control dependency: [if], data = [none]
} else {
strStyle = thefont.isItalic() ? "italic" : "plain"; // depends on control dependency: [if], data = [none]
}
this.buttonFont.setText(thefont.getName() + ", " + strStyle + ", " + thefont.getSize());
} } |
public class class_name {
public static <S extends ScopeType<S>> boolean isScopeTypeAncestor(S scopeType, S possibleAncestor) {
Queue<S> ancestors = new LinkedList<>();
ancestors.add(scopeType);
while (true) {
if (ancestors.isEmpty()) {
return false;
}
if (ancestors.peek().equals(possibleAncestor)) {
return true;
}
Collection<S> parentScopes = ancestors.poll().parentScopes();
if (parentScopes != null) {
ancestors.addAll(parentScopes);
}
}
} } | public class class_name {
public static <S extends ScopeType<S>> boolean isScopeTypeAncestor(S scopeType, S possibleAncestor) {
Queue<S> ancestors = new LinkedList<>();
ancestors.add(scopeType);
while (true) {
if (ancestors.isEmpty()) {
return false; // depends on control dependency: [if], data = [none]
}
if (ancestors.peek().equals(possibleAncestor)) {
return true; // depends on control dependency: [if], data = [none]
}
Collection<S> parentScopes = ancestors.poll().parentScopes();
if (parentScopes != null) {
ancestors.addAll(parentScopes); // depends on control dependency: [if], data = [(parentScopes]
}
}
} } |
public class class_name {
public static List<File> listAllFiles( File directory, String fileExtension ) {
String ext = fileExtension;
if( ext != null ) {
ext = ext.toLowerCase();
if( ! ext.startsWith( "." ))
ext = "." + ext;
}
List<File> result = new ArrayList<> ();
for( File f : listAllFiles( directory )) {
if( ext == null || f.getName().toLowerCase().endsWith( ext ))
result.add( f );
}
return result;
} } | public class class_name {
public static List<File> listAllFiles( File directory, String fileExtension ) {
String ext = fileExtension;
if( ext != null ) {
ext = ext.toLowerCase(); // depends on control dependency: [if], data = [none]
if( ! ext.startsWith( "." ))
ext = "." + ext;
}
List<File> result = new ArrayList<> ();
for( File f : listAllFiles( directory )) {
if( ext == null || f.getName().toLowerCase().endsWith( ext ))
result.add( f );
}
return result;
} } |
public class class_name {
public void processDocument(BufferedReader document) throws IOException {
// Local maps to record occurrence counts.
Map<Pair<String>,Double> localLemmaCounts =
new HashMap<Pair<String>,Double>();
Map<RelationTuple, SparseDoubleVector> localTuples =
new HashMap<RelationTuple, SparseDoubleVector>();
// Iterate over all of the parseable dependency parsed sentences in the
// document.
for (DependencyTreeNode[] nodes = null;
(nodes = parser.readNextTree(document)) != null; ) {
// Skip empty documents.
if (nodes.length == 0)
continue;
// Examine the paths for each word in the sentence.
for (int i = 0; i < nodes.length; ++i) {
// Reject words that are not nouns, verbs, or adjectives.
if (!(nodes[i].pos().startsWith("N") ||
nodes[i].pos().startsWith("J") ||
nodes[i].pos().startsWith("V")))
continue;
String focusWord = nodes[i].word();
// Skip words that are rejected by the semantic filter.
if (!acceptWord(focusWord))
continue;
int focusIndex = termBasis.getDimension(focusWord);
// Create the path iterator for all acceptable paths rooted at
// the focus word in the sentence.
Iterator<DependencyPath> pathIter =
new FilteredDependencyIterator(nodes[i], acceptor, 1);
while (pathIter.hasNext()) {
DependencyPath path = pathIter.next();
DependencyTreeNode last = path.last();
// Reject words that are not nouns, verbs, or adjectives.
if (!(last.pos().startsWith("N") ||
last.pos().startsWith("J") ||
last.pos().startsWith("V")))
continue;
// Get the feature index for the co-occurring word.
String otherTerm = last.word();
// Skip any filtered features.
if (otherTerm.equals(EMPTY_STRING))
continue;
int featureIndex = termBasis.getDimension(otherTerm);
Pair<String> p = new Pair<String>(focusWord, otherTerm);
Double curCount = localLemmaCounts.get(p);
localLemmaCounts.put(p, (curCount == null)
? 1 : 1 + curCount);
// Create a RelationTuple as a local key that records this
// relation tuple occurrence. If there is not a local
// relation vector, create it. Then add an occurrence count
// of 1.
DependencyRelation relation = path.iterator().next();
// Skip relations that do not have the focusWord as the
// head word in the relation. The inverse relation will
// eventually be encountered and we'll account for it then.
if (!relation.headNode().word().equals(focusWord))
continue;
RelationTuple relationKey = new RelationTuple(
focusIndex, relation.relation().intern());
SparseDoubleVector relationVector = localTuples.get(
relationKey);
if (relationVector == null) {
relationVector = new CompactSparseVector();
localTuples.put(relationKey, relationVector);
}
relationVector.add(featureIndex, 1);
}
}
}
document.close();
// Once the document has been processed, update the co-occurrence matrix
// accordingly.
for (Map.Entry<Pair<String>,Double> e : localLemmaCounts.entrySet()){
// Push the local co-occurrence counts to the larger mapping.
Pair<String> p = e.getKey();
// Get the prefernce vectors for the current focus word. If they do
// not exist, create it in a thread safe manner.
SelectionalPreference preference = preferenceVectors.get(p.x);
if (preference == null) {
synchronized (this) {
preference = preferenceVectors.get(p.x);
if (preference == null) {
preference = new SelectionalPreference(combinor);
preferenceVectors.put(p.x, preference);
}
}
}
// Add the local count.
synchronized (preference) {
preference.lemmaVector.add(
termBasis.getDimension(p.y), e.getValue());
}
}
// Push the relation tuple counts to the larger counts.
for (Map.Entry<RelationTuple, SparseDoubleVector> r :
localTuples.entrySet()) {
// Get the global counts for this relation tuple. If it does not
// exist, create a new one in a thread safe manner.
SparseDoubleVector relationCounts = relationVectors.get(r.getKey());
if (relationCounts == null) {
synchronized (this) {
relationCounts = relationVectors.get(r.getKey());
if (relationCounts == null) {
relationCounts = new CompactSparseVector();
relationVectors.put(r.getKey(), relationCounts);
}
}
}
// Update the counts.
synchronized (relationCounts) {
VectorMath.add(relationCounts, r.getValue());
}
}
} } | public class class_name {
public void processDocument(BufferedReader document) throws IOException {
// Local maps to record occurrence counts.
Map<Pair<String>,Double> localLemmaCounts =
new HashMap<Pair<String>,Double>();
Map<RelationTuple, SparseDoubleVector> localTuples =
new HashMap<RelationTuple, SparseDoubleVector>();
// Iterate over all of the parseable dependency parsed sentences in the
// document.
for (DependencyTreeNode[] nodes = null;
(nodes = parser.readNextTree(document)) != null; ) {
// Skip empty documents.
if (nodes.length == 0)
continue;
// Examine the paths for each word in the sentence.
for (int i = 0; i < nodes.length; ++i) {
// Reject words that are not nouns, verbs, or adjectives.
if (!(nodes[i].pos().startsWith("N") ||
nodes[i].pos().startsWith("J") ||
nodes[i].pos().startsWith("V")))
continue;
String focusWord = nodes[i].word();
// Skip words that are rejected by the semantic filter.
if (!acceptWord(focusWord))
continue;
int focusIndex = termBasis.getDimension(focusWord);
// Create the path iterator for all acceptable paths rooted at
// the focus word in the sentence.
Iterator<DependencyPath> pathIter =
new FilteredDependencyIterator(nodes[i], acceptor, 1);
while (pathIter.hasNext()) {
DependencyPath path = pathIter.next();
DependencyTreeNode last = path.last();
// Reject words that are not nouns, verbs, or adjectives.
if (!(last.pos().startsWith("N") ||
last.pos().startsWith("J") ||
last.pos().startsWith("V")))
continue;
// Get the feature index for the co-occurring word.
String otherTerm = last.word();
// Skip any filtered features.
if (otherTerm.equals(EMPTY_STRING))
continue;
int featureIndex = termBasis.getDimension(otherTerm);
Pair<String> p = new Pair<String>(focusWord, otherTerm);
Double curCount = localLemmaCounts.get(p);
localLemmaCounts.put(p, (curCount == null)
? 1 : 1 + curCount); // depends on control dependency: [while], data = [none]
// Create a RelationTuple as a local key that records this
// relation tuple occurrence. If there is not a local
// relation vector, create it. Then add an occurrence count
// of 1.
DependencyRelation relation = path.iterator().next();
// Skip relations that do not have the focusWord as the
// head word in the relation. The inverse relation will
// eventually be encountered and we'll account for it then.
if (!relation.headNode().word().equals(focusWord))
continue;
RelationTuple relationKey = new RelationTuple(
focusIndex, relation.relation().intern());
SparseDoubleVector relationVector = localTuples.get(
relationKey);
if (relationVector == null) {
relationVector = new CompactSparseVector(); // depends on control dependency: [if], data = [none]
localTuples.put(relationKey, relationVector); // depends on control dependency: [if], data = [none]
}
relationVector.add(featureIndex, 1); // depends on control dependency: [while], data = [none]
}
}
}
document.close();
// Once the document has been processed, update the co-occurrence matrix
// accordingly.
for (Map.Entry<Pair<String>,Double> e : localLemmaCounts.entrySet()){
// Push the local co-occurrence counts to the larger mapping.
Pair<String> p = e.getKey();
// Get the prefernce vectors for the current focus word. If they do
// not exist, create it in a thread safe manner.
SelectionalPreference preference = preferenceVectors.get(p.x);
if (preference == null) {
synchronized (this) {
preference = preferenceVectors.get(p.x);
if (preference == null) {
preference = new SelectionalPreference(combinor); // depends on control dependency: [if], data = [none]
preferenceVectors.put(p.x, preference); // depends on control dependency: [if], data = [none]
}
}
}
// Add the local count.
synchronized (preference) {
preference.lemmaVector.add(
termBasis.getDimension(p.y), e.getValue());
}
}
// Push the relation tuple counts to the larger counts.
for (Map.Entry<RelationTuple, SparseDoubleVector> r :
localTuples.entrySet()) {
// Get the global counts for this relation tuple. If it does not
// exist, create a new one in a thread safe manner.
SparseDoubleVector relationCounts = relationVectors.get(r.getKey());
if (relationCounts == null) {
synchronized (this) {
relationCounts = relationVectors.get(r.getKey());
if (relationCounts == null) {
relationCounts = new CompactSparseVector();
relationVectors.put(r.getKey(), relationCounts);
}
}
}
// Update the counts.
synchronized (relationCounts) {
VectorMath.add(relationCounts, r.getValue());
}
}
} } |
public class class_name {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span addLink(Data data) {
Span span = data.linkSpan;
for (int i = 0; i < data.size; i++) {
span.addLink(data.links[i]);
}
return span;
} } | public class class_name {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span addLink(Data data) {
Span span = data.linkSpan;
for (int i = 0; i < data.size; i++) {
span.addLink(data.links[i]); // depends on control dependency: [for], data = [i]
}
return span;
} } |
public class class_name {
public void setBccAddresses(java.util.Collection<String> bccAddresses) {
if (bccAddresses == null) {
this.bccAddresses = null;
return;
}
this.bccAddresses = new java.util.ArrayList<String>(bccAddresses);
} } | public class class_name {
public void setBccAddresses(java.util.Collection<String> bccAddresses) {
if (bccAddresses == null) {
this.bccAddresses = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.bccAddresses = new java.util.ArrayList<String>(bccAddresses);
} } |
public class class_name {
private int scanForOne(byte[] data , int index , int end ) {
while (index < end && data[index] != 1) {
index++;
}
return index;
} } | public class class_name {
private int scanForOne(byte[] data , int index , int end ) {
while (index < end && data[index] != 1) {
index++; // depends on control dependency: [while], data = [none]
}
return index;
} } |
public class class_name {
private void removeUnreferencedFunctionArgs(Scope fparamScope) {
// Notice that removing unreferenced function args breaks
// Function.prototype.length. In advanced mode, we don't really care
// about this: we consider "length" the equivalent of reflecting on
// the function's lexical source.
//
// Rather than create a new option for this, we assume that if the user
// is removing globals, then it's OK to remove unused function args.
//
// See http://blickly.github.io/closure-compiler-issues/#253
if (!removeGlobals) {
return;
}
Node function = fparamScope.getRootNode();
checkState(function.isFunction());
if (NodeUtil.isGetOrSetKey(function.getParent())) {
// The parameters object literal setters can not be removed.
return;
}
Node argList = NodeUtil.getFunctionParameters(function);
// Strip as many unreferenced args off the end of the function declaration as possible.
maybeRemoveUnusedTrailingParameters(argList, fparamScope);
// Mark any remaining unused parameters are unused to OptimizeParameters can try to remove
// them.
markUnusedParameters(argList, fparamScope);
} } | public class class_name {
private void removeUnreferencedFunctionArgs(Scope fparamScope) {
// Notice that removing unreferenced function args breaks
// Function.prototype.length. In advanced mode, we don't really care
// about this: we consider "length" the equivalent of reflecting on
// the function's lexical source.
//
// Rather than create a new option for this, we assume that if the user
// is removing globals, then it's OK to remove unused function args.
//
// See http://blickly.github.io/closure-compiler-issues/#253
if (!removeGlobals) {
return; // depends on control dependency: [if], data = [none]
}
Node function = fparamScope.getRootNode();
checkState(function.isFunction());
if (NodeUtil.isGetOrSetKey(function.getParent())) {
// The parameters object literal setters can not be removed.
return; // depends on control dependency: [if], data = [none]
}
Node argList = NodeUtil.getFunctionParameters(function);
// Strip as many unreferenced args off the end of the function declaration as possible.
maybeRemoveUnusedTrailingParameters(argList, fparamScope);
// Mark any remaining unused parameters are unused to OptimizeParameters can try to remove
// them.
markUnusedParameters(argList, fparamScope);
} } |
public class class_name {
public void setPartsSha1(List<String> sha1s) {
JsonArray jsonArray = new JsonArray();
for (String s : sha1s) {
jsonArray.add(s);
}
set(FIELD_PARTS_SHA1, jsonArray);
} } | public class class_name {
public void setPartsSha1(List<String> sha1s) {
JsonArray jsonArray = new JsonArray();
for (String s : sha1s) {
jsonArray.add(s); // depends on control dependency: [for], data = [s]
}
set(FIELD_PARTS_SHA1, jsonArray);
} } |
public class class_name {
private Set<TraceeBackendProvider> getTraceeProviderFromClassloader(
final Map<ClassLoader, Set<TraceeBackendProvider>> cacheCopy,
final ClassLoader classLoader) {
// use cache to get TraceeBackendProvider or empty results from old lookups
Set<TraceeBackendProvider> classLoaderProviders = cacheCopy.get(classLoader);
if (isLookupNeeded(classLoaderProviders)) {
classLoaderProviders = loadProviders(classLoader);
updatedCache(classLoader, classLoaderProviders);
}
return classLoaderProviders;
} } | public class class_name {
private Set<TraceeBackendProvider> getTraceeProviderFromClassloader(
final Map<ClassLoader, Set<TraceeBackendProvider>> cacheCopy,
final ClassLoader classLoader) {
// use cache to get TraceeBackendProvider or empty results from old lookups
Set<TraceeBackendProvider> classLoaderProviders = cacheCopy.get(classLoader);
if (isLookupNeeded(classLoaderProviders)) {
classLoaderProviders = loadProviders(classLoader); // depends on control dependency: [if], data = [none]
updatedCache(classLoader, classLoaderProviders); // depends on control dependency: [if], data = [none]
}
return classLoaderProviders;
} } |
public class class_name {
public static String urlDecode(String s) {
try {
return URLDecoder.decode(s, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("get a jdk that actually supports utf-8", e);
}
} } | public class class_name {
public static String urlDecode(String s) {
try {
return URLDecoder.decode(s, StandardCharsets.UTF_8.name()); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("get a jdk that actually supports utf-8", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(DeleteTableRequest deleteTableRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteTableRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteTableRequest.getCatalogId(), CATALOGID_BINDING);
protocolMarshaller.marshall(deleteTableRequest.getDatabaseName(), DATABASENAME_BINDING);
protocolMarshaller.marshall(deleteTableRequest.getName(), NAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeleteTableRequest deleteTableRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteTableRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteTableRequest.getCatalogId(), CATALOGID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deleteTableRequest.getDatabaseName(), DATABASENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deleteTableRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static ResultSet triangleContouring(Connection connection, String tableName, Value... varArgs) throws SQLException {
if (connection.getMetaData().getURL().equals(HACK_URL)) {
return new ExplodeResultSet(connection,tableName, Collections.singletonList(0.0)).getResultSet();
}
ExplodeResultSet rowSource = null;
if(varArgs.length > 3) {
// First ones may be column names
if(varArgs[0] instanceof ValueString &&
varArgs[1] instanceof ValueString &&
varArgs[2] instanceof ValueString) {
// Use table columns for iso levels
List<Double> isoLvls = new ArrayList<Double>(varArgs.length - 3);
for(int idArg = 3; idArg < varArgs.length; idArg++) {
isoLvls.add(varArgs[idArg].getDouble());
}
rowSource = new ExplodeResultSet(connection,tableName,varArgs[0].getString(), varArgs[1].getString(),
varArgs[2].getString(), isoLvls);
}
}
if(rowSource == null) {
// Use Z
List<Double> isoLvls = new ArrayList<Double>(varArgs.length);
for (Value value : varArgs) {
if (value instanceof ValueArray) {
for (Value arrVal : ((ValueArray) value).getList()) {
isoLvls.add(arrVal.getDouble());
}
} else {
isoLvls.add(value.getDouble());
}
}
rowSource = new ExplodeResultSet(connection,tableName, isoLvls);
}
return rowSource.getResultSet();
} } | public class class_name {
public static ResultSet triangleContouring(Connection connection, String tableName, Value... varArgs) throws SQLException {
if (connection.getMetaData().getURL().equals(HACK_URL)) {
return new ExplodeResultSet(connection,tableName, Collections.singletonList(0.0)).getResultSet(); // depends on control dependency: [if], data = [none]
}
ExplodeResultSet rowSource = null;
if(varArgs.length > 3) {
// First ones may be column names
if(varArgs[0] instanceof ValueString &&
varArgs[1] instanceof ValueString &&
varArgs[2] instanceof ValueString) {
// Use table columns for iso levels
List<Double> isoLvls = new ArrayList<Double>(varArgs.length - 3);
for(int idArg = 3; idArg < varArgs.length; idArg++) {
isoLvls.add(varArgs[idArg].getDouble()); // depends on control dependency: [for], data = [idArg]
}
rowSource = new ExplodeResultSet(connection,tableName,varArgs[0].getString(), varArgs[1].getString(),
varArgs[2].getString(), isoLvls); // depends on control dependency: [if], data = [none]
}
}
if(rowSource == null) {
// Use Z
List<Double> isoLvls = new ArrayList<Double>(varArgs.length);
for (Value value : varArgs) {
if (value instanceof ValueArray) {
for (Value arrVal : ((ValueArray) value).getList()) {
isoLvls.add(arrVal.getDouble()); // depends on control dependency: [for], data = [arrVal]
}
} else {
isoLvls.add(value.getDouble()); // depends on control dependency: [if], data = [none]
}
}
rowSource = new ExplodeResultSet(connection,tableName, isoLvls); // depends on control dependency: [if], data = [none]
}
return rowSource.getResultSet();
} } |
public class class_name {
private void handleDataFrameComplete(DataFrame dataFrame) {
Exceptions.checkArgument(dataFrame.isSealed(), "dataFrame", "Cannot publish a non-sealed DataFrame.");
// Write DataFrame to DataFrameLog.
CommitArgs commitArgs = new CommitArgs(this.lastSerializedSequenceNumber, this.lastStartedSequenceNumber, dataFrame.getLength());
try {
this.args.beforeCommit.accept(commitArgs);
this.targetLog.append(dataFrame.getData(), this.args.writeTimeout)
.thenAcceptAsync(logAddress -> {
commitArgs.setLogAddress(logAddress);
this.args.commitSuccess.accept(commitArgs);
}, this.args.executor)
.exceptionally(ex -> handleProcessingException(ex, commitArgs));
} catch (Throwable ex) {
handleProcessingException(ex, commitArgs);
// Even though we invoked the dataFrameCommitFailureCallback() - which was for the DurableLog to handle,
// we still need to fail the current call, which most likely leads to failing the LogItem that triggered this.
throw ex;
}
} } | public class class_name {
private void handleDataFrameComplete(DataFrame dataFrame) {
Exceptions.checkArgument(dataFrame.isSealed(), "dataFrame", "Cannot publish a non-sealed DataFrame.");
// Write DataFrame to DataFrameLog.
CommitArgs commitArgs = new CommitArgs(this.lastSerializedSequenceNumber, this.lastStartedSequenceNumber, dataFrame.getLength());
try {
this.args.beforeCommit.accept(commitArgs); // depends on control dependency: [try], data = [none]
this.targetLog.append(dataFrame.getData(), this.args.writeTimeout)
.thenAcceptAsync(logAddress -> {
commitArgs.setLogAddress(logAddress); // depends on control dependency: [try], data = [none]
this.args.commitSuccess.accept(commitArgs); // depends on control dependency: [try], data = [none]
}, this.args.executor)
.exceptionally(ex -> handleProcessingException(ex, commitArgs));
} catch (Throwable ex) {
handleProcessingException(ex, commitArgs);
// Even though we invoked the dataFrameCommitFailureCallback() - which was for the DurableLog to handle,
// we still need to fail the current call, which most likely leads to failing the LogItem that triggered this.
throw ex;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void escapeValueTo(final String field, final StringBuilder target) {
if (field == null) {
target.append(DETAILS_QUOTE_CHAR);
target.append(DETAILS_QUOTE_CHAR);
return;
}
target.append(DETAILS_QUOTE_CHAR);
if (field.indexOf(DETAILS_ESCAPE_CHAR) == -1 && field.indexOf(DETAILS_QUOTE_CHAR) == -1) {
target.append(field);
} else {
final int len = field.length();
for (int i = 0; i < len; i++) {
final char charAt = field.charAt(i);
if (charAt == DETAILS_ESCAPE_CHAR || charAt == DETAILS_QUOTE_CHAR) {
target.append(DETAILS_ESCAPE_CHAR);
}
target.append(charAt);
}
}
target.append(DETAILS_QUOTE_CHAR);
} } | public class class_name {
private void escapeValueTo(final String field, final StringBuilder target) {
if (field == null) {
target.append(DETAILS_QUOTE_CHAR); // depends on control dependency: [if], data = [none]
target.append(DETAILS_QUOTE_CHAR); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
target.append(DETAILS_QUOTE_CHAR);
if (field.indexOf(DETAILS_ESCAPE_CHAR) == -1 && field.indexOf(DETAILS_QUOTE_CHAR) == -1) {
target.append(field); // depends on control dependency: [if], data = [none]
} else {
final int len = field.length();
for (int i = 0; i < len; i++) {
final char charAt = field.charAt(i);
if (charAt == DETAILS_ESCAPE_CHAR || charAt == DETAILS_QUOTE_CHAR) {
target.append(DETAILS_ESCAPE_CHAR); // depends on control dependency: [if], data = [none]
}
target.append(charAt); // depends on control dependency: [for], data = [none]
}
}
target.append(DETAILS_QUOTE_CHAR);
} } |
public class class_name {
@Override
public EClass getIfcSurfaceOfRevolution() {
if (ifcSurfaceOfRevolutionEClass == null) {
ifcSurfaceOfRevolutionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(676);
}
return ifcSurfaceOfRevolutionEClass;
} } | public class class_name {
@Override
public EClass getIfcSurfaceOfRevolution() {
if (ifcSurfaceOfRevolutionEClass == null) {
ifcSurfaceOfRevolutionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(676);
// depends on control dependency: [if], data = [none]
}
return ifcSurfaceOfRevolutionEClass;
} } |
public class class_name {
public static String generateAlias(String basename, int counter, String fallback) {
// build trimmed and lower case version of the base name
String lowerCaseBaseName = basename.trim().toLowerCase(Locale.ENGLISH);
// use only simple characters for the alias
StringBuilder builder = new StringBuilder();
for( char c : lowerCaseBaseName.toCharArray() ) {
if( c >= 'a' && c <= 'z' ) {
builder.append( c );
}
}
// add some default keyword, if builder is still empty
if( builder.length() == 0 ) {
if(fallback != null && fallback.length() > 0) {
builder.append( fallback );
} else {
builder.append( "default" );
}
}
// finally append the counter to get uniqueness
builder.append( counter );
// return the result
return builder.toString();
} } | public class class_name {
public static String generateAlias(String basename, int counter, String fallback) {
// build trimmed and lower case version of the base name
String lowerCaseBaseName = basename.trim().toLowerCase(Locale.ENGLISH);
// use only simple characters for the alias
StringBuilder builder = new StringBuilder();
for( char c : lowerCaseBaseName.toCharArray() ) {
if( c >= 'a' && c <= 'z' ) {
builder.append( c ); // depends on control dependency: [if], data = [( c]
}
}
// add some default keyword, if builder is still empty
if( builder.length() == 0 ) {
if(fallback != null && fallback.length() > 0) {
builder.append( fallback ); // depends on control dependency: [if], data = [none]
} else {
builder.append( "default" ); // depends on control dependency: [if], data = [none]
}
}
// finally append the counter to get uniqueness
builder.append( counter );
// return the result
return builder.toString();
} } |
public class class_name {
@Override
protected Deque<XMLEvent> getAdditionalEvents(XMLEvent event) {
if (event.isStartElement()) {
final StartElement startElement = event.asStartElement();
// All following logic requires an ID attribute, ignore any element without one
final Attribute idAttribute =
startElement.getAttributeByName(IUserLayoutManager.ID_ATTR_NAME);
if (idAttribute == null) {
return null;
}
// Create and return a transient (dynamically created) folder that includes a transient
// channel
// if we are processing the tart element of the root node
// iff the subscribeId is present and describes a transient channel and not a regular
// layout channel.
final String subscribeId = this.userLayoutManager.getFocusedId();
if (this.rootFolderId.equals(idAttribute.getValue())
&& subscribeId != null
&& !subscribeId.equals("")
&& this.userLayoutManager.isTransientChannel(subscribeId)) {
IPortletDefinition chanDef = null;
try {
chanDef = this.userLayoutManager.getChannelDefinition(subscribeId);
} catch (Exception e) {
logger.error(
"Could not obtain IChannelDefinition for subscribe id: {}",
subscribeId,
e);
}
if (chanDef != null) {
final QName name = startElement.getName();
final String namespaceURI = name.getNamespaceURI();
final String prefix = name.getPrefix();
final Deque<XMLEvent> transientEventBuffer = new LinkedList<XMLEvent>();
final Collection<Attribute> transientFolderAttributes =
new LinkedList<Attribute>();
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute(
"ID", TransientUserLayoutManagerWrapper.TRANSIENT_FOLDER_ID));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute(
"name", chanDef != null ? chanDef.getTitle() : "Temporary"));
transientFolderAttributes.add(EVENT_FACTORY.createAttribute("type", "regular"));
transientFolderAttributes.add(EVENT_FACTORY.createAttribute("hidden", "false"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("unremovable", "true"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("immutable", "true"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("unremovable", "true"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:addChildAllowed", "false"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:deleteAllowed", "false"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:editAllowed", "false"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:moveAllowed", "false"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:precedence", "100.0"));
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("transient", "true"));
final StartElement transientFolder =
EVENT_FACTORY.createStartElement(
prefix,
namespaceURI,
IUserLayoutManager.FOLDER,
transientFolderAttributes.iterator(),
null);
transientEventBuffer.add(transientFolder);
// TODO Move IChannelDefinition/IPortletDefinition -> StAX events code somewhere
// reusable
final Collection<Attribute> channelAttrs = new LinkedList<Attribute>();
channelAttrs.add(EVENT_FACTORY.createAttribute("ID", subscribeId));
channelAttrs.add(
EVENT_FACTORY.createAttribute(
"typeID", Integer.toString(chanDef.getType().getId())));
channelAttrs.add(EVENT_FACTORY.createAttribute("hidden", "false"));
channelAttrs.add(EVENT_FACTORY.createAttribute("unremovable", "true"));
channelAttrs.add(EVENT_FACTORY.createAttribute("dlm:deleteAllowed", "false"));
channelAttrs.add(EVENT_FACTORY.createAttribute("dlm:moveAllowed", "false"));
channelAttrs.add(EVENT_FACTORY.createAttribute("name", chanDef.getName()));
channelAttrs.add(
EVENT_FACTORY.createAttribute("description", chanDef.getDescription()));
channelAttrs.add(EVENT_FACTORY.createAttribute("title", chanDef.getTitle()));
channelAttrs.add(
EVENT_FACTORY.createAttribute(
"chanID", chanDef.getPortletDefinitionId().getStringId()));
channelAttrs.add(EVENT_FACTORY.createAttribute("fname", chanDef.getFName()));
channelAttrs.add(
EVENT_FACTORY.createAttribute(
"timeout", Integer.toString(chanDef.getTimeout())));
channelAttrs.add(EVENT_FACTORY.createAttribute("transient", "true"));
final StartElement startChannel =
EVENT_FACTORY.createStartElement(
prefix,
namespaceURI,
IUserLayoutManager.CHANNEL,
channelAttrs.iterator(),
null);
transientEventBuffer.offer(startChannel);
// add channel parameter elements
for (final IPortletDefinitionParameter parm : chanDef.getParameters()) {
final Collection<Attribute> parameterAttrs = new LinkedList<Attribute>();
parameterAttrs.add(EVENT_FACTORY.createAttribute("name", parm.getName()));
parameterAttrs.add(EVENT_FACTORY.createAttribute("value", parm.getValue()));
final StartElement startParameter =
EVENT_FACTORY.createStartElement(
prefix,
namespaceURI,
IUserLayoutManager.PARAMETER,
parameterAttrs.iterator(),
null);
transientEventBuffer.offer(startParameter);
final EndElement endParameter =
EVENT_FACTORY.createEndElement(
prefix, namespaceURI, IUserLayoutManager.PARAMETER, null);
transientEventBuffer.offer(endParameter);
}
final EndElement endChannel =
EVENT_FACTORY.createEndElement(
prefix, namespaceURI, IUserLayoutManager.CHANNEL, null);
transientEventBuffer.offer(endChannel);
final EndElement endFolder =
EVENT_FACTORY.createEndElement(
prefix, namespaceURI, IUserLayoutManager.FOLDER, null);
transientEventBuffer.offer(endFolder);
return transientEventBuffer;
} else { // I don't think subscribeId could be null, but log warning if so.
logger.warn(
"Unable to resolve portlet definition for subscribe ID {}",
subscribeId);
}
}
}
return null;
} } | public class class_name {
@Override
protected Deque<XMLEvent> getAdditionalEvents(XMLEvent event) {
if (event.isStartElement()) {
final StartElement startElement = event.asStartElement();
// All following logic requires an ID attribute, ignore any element without one
final Attribute idAttribute =
startElement.getAttributeByName(IUserLayoutManager.ID_ATTR_NAME);
if (idAttribute == null) {
return null; // depends on control dependency: [if], data = [none]
}
// Create and return a transient (dynamically created) folder that includes a transient
// channel
// if we are processing the tart element of the root node
// iff the subscribeId is present and describes a transient channel and not a regular
// layout channel.
final String subscribeId = this.userLayoutManager.getFocusedId();
if (this.rootFolderId.equals(idAttribute.getValue())
&& subscribeId != null
&& !subscribeId.equals("")
&& this.userLayoutManager.isTransientChannel(subscribeId)) {
IPortletDefinition chanDef = null;
try {
chanDef = this.userLayoutManager.getChannelDefinition(subscribeId); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error(
"Could not obtain IChannelDefinition for subscribe id: {}",
subscribeId,
e);
} // depends on control dependency: [catch], data = [none]
if (chanDef != null) {
final QName name = startElement.getName();
final String namespaceURI = name.getNamespaceURI();
final String prefix = name.getPrefix();
final Deque<XMLEvent> transientEventBuffer = new LinkedList<XMLEvent>();
final Collection<Attribute> transientFolderAttributes =
new LinkedList<Attribute>();
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute(
"ID", TransientUserLayoutManagerWrapper.TRANSIENT_FOLDER_ID)); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute(
"name", chanDef != null ? chanDef.getTitle() : "Temporary")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(EVENT_FACTORY.createAttribute("type", "regular")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(EVENT_FACTORY.createAttribute("hidden", "false")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("unremovable", "true")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("immutable", "true")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("unremovable", "true")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:addChildAllowed", "false")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:deleteAllowed", "false")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:editAllowed", "false")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:moveAllowed", "false")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("dlm:precedence", "100.0")); // depends on control dependency: [if], data = [none]
transientFolderAttributes.add(
EVENT_FACTORY.createAttribute("transient", "true")); // depends on control dependency: [if], data = [none]
final StartElement transientFolder =
EVENT_FACTORY.createStartElement(
prefix,
namespaceURI,
IUserLayoutManager.FOLDER,
transientFolderAttributes.iterator(),
null);
transientEventBuffer.add(transientFolder); // depends on control dependency: [if], data = [none]
// TODO Move IChannelDefinition/IPortletDefinition -> StAX events code somewhere
// reusable
final Collection<Attribute> channelAttrs = new LinkedList<Attribute>();
channelAttrs.add(EVENT_FACTORY.createAttribute("ID", subscribeId)); // depends on control dependency: [if], data = [none]
channelAttrs.add(
EVENT_FACTORY.createAttribute(
"typeID", Integer.toString(chanDef.getType().getId()))); // depends on control dependency: [if], data = [none]
channelAttrs.add(EVENT_FACTORY.createAttribute("hidden", "false")); // depends on control dependency: [if], data = [none]
channelAttrs.add(EVENT_FACTORY.createAttribute("unremovable", "true")); // depends on control dependency: [if], data = [none]
channelAttrs.add(EVENT_FACTORY.createAttribute("dlm:deleteAllowed", "false")); // depends on control dependency: [if], data = [none]
channelAttrs.add(EVENT_FACTORY.createAttribute("dlm:moveAllowed", "false")); // depends on control dependency: [if], data = [none]
channelAttrs.add(EVENT_FACTORY.createAttribute("name", chanDef.getName())); // depends on control dependency: [if], data = [none]
channelAttrs.add(
EVENT_FACTORY.createAttribute("description", chanDef.getDescription())); // depends on control dependency: [if], data = [none]
channelAttrs.add(EVENT_FACTORY.createAttribute("title", chanDef.getTitle())); // depends on control dependency: [if], data = [none]
channelAttrs.add(
EVENT_FACTORY.createAttribute(
"chanID", chanDef.getPortletDefinitionId().getStringId())); // depends on control dependency: [if], data = [none]
channelAttrs.add(EVENT_FACTORY.createAttribute("fname", chanDef.getFName())); // depends on control dependency: [if], data = [none]
channelAttrs.add(
EVENT_FACTORY.createAttribute(
"timeout", Integer.toString(chanDef.getTimeout()))); // depends on control dependency: [if], data = [none]
channelAttrs.add(EVENT_FACTORY.createAttribute("transient", "true")); // depends on control dependency: [if], data = [none]
final StartElement startChannel =
EVENT_FACTORY.createStartElement(
prefix,
namespaceURI,
IUserLayoutManager.CHANNEL,
channelAttrs.iterator(),
null);
transientEventBuffer.offer(startChannel); // depends on control dependency: [if], data = [none]
// add channel parameter elements
for (final IPortletDefinitionParameter parm : chanDef.getParameters()) {
final Collection<Attribute> parameterAttrs = new LinkedList<Attribute>();
parameterAttrs.add(EVENT_FACTORY.createAttribute("name", parm.getName())); // depends on control dependency: [for], data = [parm]
parameterAttrs.add(EVENT_FACTORY.createAttribute("value", parm.getValue())); // depends on control dependency: [for], data = [parm]
final StartElement startParameter =
EVENT_FACTORY.createStartElement(
prefix,
namespaceURI,
IUserLayoutManager.PARAMETER,
parameterAttrs.iterator(),
null);
transientEventBuffer.offer(startParameter); // depends on control dependency: [for], data = [none]
final EndElement endParameter =
EVENT_FACTORY.createEndElement(
prefix, namespaceURI, IUserLayoutManager.PARAMETER, null);
transientEventBuffer.offer(endParameter); // depends on control dependency: [for], data = [none]
}
final EndElement endChannel =
EVENT_FACTORY.createEndElement(
prefix, namespaceURI, IUserLayoutManager.CHANNEL, null);
transientEventBuffer.offer(endChannel); // depends on control dependency: [if], data = [none]
final EndElement endFolder =
EVENT_FACTORY.createEndElement(
prefix, namespaceURI, IUserLayoutManager.FOLDER, null);
transientEventBuffer.offer(endFolder); // depends on control dependency: [if], data = [none]
return transientEventBuffer; // depends on control dependency: [if], data = [none]
} else { // I don't think subscribeId could be null, but log warning if so.
logger.warn(
"Unable to resolve portlet definition for subscribe ID {}",
subscribeId); // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public static void prefixKeyWithSalt(final byte[] row_key) {
if (Const.SALT_WIDTH() > 0) {
if (row_key.length < (Const.SALT_WIDTH() + TSDB.metrics_width()) ||
(Bytes.memcmp(row_key, new byte[Const.SALT_WIDTH() + TSDB.metrics_width()],
Const.SALT_WIDTH(), TSDB.metrics_width()) == 0)) {
// ^ Don't salt the global annotation row, leave it at zero
return;
}
final int tags_start = Const.SALT_WIDTH() + TSDB.metrics_width() +
Const.TIMESTAMP_BYTES;
// we want the metric and tags, not the timestamp
final byte[] salt_base =
new byte[row_key.length - Const.SALT_WIDTH() - Const.TIMESTAMP_BYTES];
System.arraycopy(row_key, Const.SALT_WIDTH(), salt_base, 0, TSDB.metrics_width());
System.arraycopy(row_key, tags_start,salt_base, TSDB.metrics_width(),
row_key.length - tags_start);
int modulo = Arrays.hashCode(salt_base) % Const.SALT_BUCKETS();
if (modulo < 0) {
// make sure we return a positive salt.
modulo = modulo * -1;
}
final byte[] salt = getSaltBytes(modulo);
System.arraycopy(salt, 0, row_key, 0, Const.SALT_WIDTH());
} // else salting is disabled so it's a no-op
} } | public class class_name {
public static void prefixKeyWithSalt(final byte[] row_key) {
if (Const.SALT_WIDTH() > 0) {
if (row_key.length < (Const.SALT_WIDTH() + TSDB.metrics_width()) ||
(Bytes.memcmp(row_key, new byte[Const.SALT_WIDTH() + TSDB.metrics_width()],
Const.SALT_WIDTH(), TSDB.metrics_width()) == 0)) {
// ^ Don't salt the global annotation row, leave it at zero
return; // depends on control dependency: [if], data = [none]
}
final int tags_start = Const.SALT_WIDTH() + TSDB.metrics_width() +
Const.TIMESTAMP_BYTES;
// we want the metric and tags, not the timestamp
final byte[] salt_base =
new byte[row_key.length - Const.SALT_WIDTH() - Const.TIMESTAMP_BYTES];
System.arraycopy(row_key, Const.SALT_WIDTH(), salt_base, 0, TSDB.metrics_width()); // depends on control dependency: [if], data = [none]
System.arraycopy(row_key, tags_start,salt_base, TSDB.metrics_width(),
row_key.length - tags_start); // depends on control dependency: [if], data = [none]
int modulo = Arrays.hashCode(salt_base) % Const.SALT_BUCKETS();
if (modulo < 0) {
// make sure we return a positive salt.
modulo = modulo * -1; // depends on control dependency: [if], data = [none]
}
final byte[] salt = getSaltBytes(modulo);
System.arraycopy(salt, 0, row_key, 0, Const.SALT_WIDTH()); // depends on control dependency: [if], data = [none]
} // else salting is disabled so it's a no-op
} } |
public class class_name {
public static void trimStackTraceTo(Throwable t, Class<?> cls) {
StackTraceElement[] ste = t.getStackTrace();
String name = cls.getName();
for (int i = 0; i < ste.length; i++) {
if (ste[i].getClassName().equals(name)) {
t.setStackTrace(Arrays.copyOf(ste, i));
return;
}
}
} } | public class class_name {
public static void trimStackTraceTo(Throwable t, Class<?> cls) {
StackTraceElement[] ste = t.getStackTrace();
String name = cls.getName();
for (int i = 0; i < ste.length; i++) {
if (ste[i].getClassName().equals(name)) {
t.setStackTrace(Arrays.copyOf(ste, i)); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public int[] next()
{
if (numLeft == total)
{
numLeft = numLeft - 1;
return a;
}
int temp;
// Find largest index j with a[j] < a[j+1]
int j = a.length - 2;
while (a[j] > a[j + 1])
{
j--;
}
// Find index k such that a[k] is smallest integer
// greater than a[j] to the right of a[j]
int k = a.length - 1;
while (a[j] > a[k])
{
k--;
}
// Interchange a[j] and a[k]
temp = a[k];
a[k] = a[j];
a[j] = temp;
// Put tail end of permutation after jth position in increasing order
int r = a.length - 1;
int s = j + 1;
while (r > s)
{
temp = a[s];
a[s] = a[r];
a[r] = temp;
r--;
s++;
}
numLeft = numLeft - 1;
return a;
} } | public class class_name {
public int[] next()
{
if (numLeft == total)
{
numLeft = numLeft - 1; // depends on control dependency: [if], data = [none]
return a; // depends on control dependency: [if], data = [none]
}
int temp;
// Find largest index j with a[j] < a[j+1]
int j = a.length - 2;
while (a[j] > a[j + 1])
{
j--; // depends on control dependency: [while], data = [none]
}
// Find index k such that a[k] is smallest integer
// greater than a[j] to the right of a[j]
int k = a.length - 1;
while (a[j] > a[k])
{
k--; // depends on control dependency: [while], data = [none]
}
// Interchange a[j] and a[k]
temp = a[k];
a[k] = a[j];
a[j] = temp;
// Put tail end of permutation after jth position in increasing order
int r = a.length - 1;
int s = j + 1;
while (r > s)
{
temp = a[s]; // depends on control dependency: [while], data = [none]
a[s] = a[r]; // depends on control dependency: [while], data = [none]
a[r] = temp; // depends on control dependency: [while], data = [none]
r--; // depends on control dependency: [while], data = [none]
s++; // depends on control dependency: [while], data = [none]
}
numLeft = numLeft - 1;
return a;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T> T lookup(final String id) {
for (final IdentifiableController controller : identifiables) {
if(controller.getId().equals(id)) {
return (T) controller;
}
}
throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'");
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T> T lookup(final String id) {
for (final IdentifiableController controller : identifiables) {
if(controller.getId().equals(id)) {
return (T) controller; // depends on control dependency: [if], data = [none]
}
}
throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'");
} } |
public class class_name {
private boolean readZeroes(int bytes) {
int endPosition = dataPosition + bytes;
if (endPosition > dataSize) {
return false;
}
for (int i = dataPosition; i < endPosition; i++) {
if (data[i] == null || !data[i].isEncodedAsAllZeroBytes) {
return false;
}
}
// Note in this case we short-circuit other verification -- even if we are reading weirdly
// clobbered zeroes, they're still zeroes. Future reads might fail, though.
dataPosition = endPosition;
return true;
} } | public class class_name {
private boolean readZeroes(int bytes) {
int endPosition = dataPosition + bytes;
if (endPosition > dataSize) {
return false; // depends on control dependency: [if], data = [none]
}
for (int i = dataPosition; i < endPosition; i++) {
if (data[i] == null || !data[i].isEncodedAsAllZeroBytes) {
return false; // depends on control dependency: [if], data = [none]
}
}
// Note in this case we short-circuit other verification -- even if we are reading weirdly
// clobbered zeroes, they're still zeroes. Future reads might fail, though.
dataPosition = endPosition;
return true;
} } |
public class class_name {
@SuppressWarnings({"rawtypes", "unchecked"})
protected Object transform(Object result, QueryResultMapper resultMapper) {
Object actualResult = null;
if (result instanceof Collection) {
if (ProcessInstanceCustomDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of ProcessInstanceCustomDesc to ProcessInstanceCustomList");
actualResult = convertToProcessInstanceCustomVarsList((Collection<ProcessInstanceCustomDesc>) result);
} else if (ProcessInstanceWithVarsDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of ProcessInstanceWithVarsDesc to ProcessInstanceList");
actualResult = convertToProcessInstanceWithVarsList((Collection<ProcessInstanceWithVarsDesc>) result);
} else if (ProcessInstanceDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of ProcessInstanceDesc to ProcessInstanceList");
actualResult = convertToProcessInstanceList((Collection<ProcessInstanceDesc>) result);
} else if (UserTaskInstanceWithVarsDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of UserTaskInstanceWithVarsDesc to TaskInstanceList");
actualResult = convertToTaskInstanceWithVarsList((Collection<UserTaskInstanceWithVarsDesc>) result);
} else if (UserTaskInstanceWithPotOwnerDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of UserTaskInstanceWithPotOwnerDesc to TaskInstanceList");
actualResult = convertToTaskInstanceListPO((Collection<UserTaskInstanceWithPotOwnerDesc>) result);
} else if (UserTaskInstanceDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of UserTaskInstanceDesc to TaskInstanceList");
actualResult = convertToTaskInstanceList((Collection<UserTaskInstanceDesc>) result);
} else if (TaskSummary.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of TaskSummary to TaskSummaryList");
actualResult = convertToTaskSummaryList((Collection<TaskSummary>) result);
} else if (ExecutionError.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of ExecutionError to ErrorInstanceList");
actualResult = convertToErrorInstanceList((List<ExecutionError>) result);
} else if (List.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of List to ArrayList");
actualResult = new ArrayList((Collection) result);
}else {
logger.debug("Convert not supported for custom type {}", resultMapper.getType());
actualResult = result;
}
logger.debug("Actual result after converting is {}", actualResult);
} else {
logger.debug("Result is not a collection - {}, skipping any conversion", result);
actualResult = result;
}
return actualResult;
} } | public class class_name {
@SuppressWarnings({"rawtypes", "unchecked"})
protected Object transform(Object result, QueryResultMapper resultMapper) {
Object actualResult = null;
if (result instanceof Collection) {
if (ProcessInstanceCustomDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of ProcessInstanceCustomDesc to ProcessInstanceCustomList"); // depends on control dependency: [if], data = [none]
actualResult = convertToProcessInstanceCustomVarsList((Collection<ProcessInstanceCustomDesc>) result); // depends on control dependency: [if], data = [none]
} else if (ProcessInstanceWithVarsDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of ProcessInstanceWithVarsDesc to ProcessInstanceList"); // depends on control dependency: [if], data = [none]
actualResult = convertToProcessInstanceWithVarsList((Collection<ProcessInstanceWithVarsDesc>) result); // depends on control dependency: [if], data = [none]
} else if (ProcessInstanceDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of ProcessInstanceDesc to ProcessInstanceList"); // depends on control dependency: [if], data = [none]
actualResult = convertToProcessInstanceList((Collection<ProcessInstanceDesc>) result); // depends on control dependency: [if], data = [none]
} else if (UserTaskInstanceWithVarsDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of UserTaskInstanceWithVarsDesc to TaskInstanceList"); // depends on control dependency: [if], data = [none]
actualResult = convertToTaskInstanceWithVarsList((Collection<UserTaskInstanceWithVarsDesc>) result); // depends on control dependency: [if], data = [none]
} else if (UserTaskInstanceWithPotOwnerDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of UserTaskInstanceWithPotOwnerDesc to TaskInstanceList"); // depends on control dependency: [if], data = [none]
actualResult = convertToTaskInstanceListPO((Collection<UserTaskInstanceWithPotOwnerDesc>) result); // depends on control dependency: [if], data = [none]
} else if (UserTaskInstanceDesc.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of UserTaskInstanceDesc to TaskInstanceList"); // depends on control dependency: [if], data = [none]
actualResult = convertToTaskInstanceList((Collection<UserTaskInstanceDesc>) result); // depends on control dependency: [if], data = [none]
} else if (TaskSummary.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of TaskSummary to TaskSummaryList"); // depends on control dependency: [if], data = [none]
actualResult = convertToTaskSummaryList((Collection<TaskSummary>) result); // depends on control dependency: [if], data = [none]
} else if (ExecutionError.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of ExecutionError to ErrorInstanceList"); // depends on control dependency: [if], data = [none]
actualResult = convertToErrorInstanceList((List<ExecutionError>) result); // depends on control dependency: [if], data = [none]
} else if (List.class.isAssignableFrom(resultMapper.getType())) {
logger.debug("Converting collection of List to ArrayList"); // depends on control dependency: [if], data = [none]
actualResult = new ArrayList((Collection) result); // depends on control dependency: [if], data = [none]
}else {
logger.debug("Convert not supported for custom type {}", resultMapper.getType()); // depends on control dependency: [if], data = [none]
actualResult = result; // depends on control dependency: [if], data = [none]
}
logger.debug("Actual result after converting is {}", actualResult); // depends on control dependency: [if], data = [none]
} else {
logger.debug("Result is not a collection - {}, skipping any conversion", result); // depends on control dependency: [if], data = [none]
actualResult = result; // depends on control dependency: [if], data = [none]
}
return actualResult;
} } |
public class class_name {
private boolean _update(final Identification id) throws IOException, ServletException {
final File newLucee = downloadCore(id);
if (newLucee == null) return false;
if (singelton != null) singelton.reset();
final Version v = null;
try {
bundleCollection = BundleLoader.loadBundles(this, getFelixCacheDirectory(), getBundleDirectory(), newLucee, bundleCollection);
final CFMLEngine e = getEngine(bundleCollection);
if (e == null) throw new IOException("can't load engine");
version = e.getInfo().getVersion();
// engine = e;
setEngine(e);
// e.reset();
callListeners(e);
ConfigServer cs = getConfigServer(e);
if (cs != null) {
Log log = cs.getLog("deploy");
log.info("loader", "Lucee Version [" + v + "] installed");
}
}
catch (final Exception e) {
System.gc();
try {
newLucee.delete();
}
catch (final Exception ee) {}
log(e);
e.printStackTrace();
return false;
}
log(Logger.LOG_DEBUG, "Version (" + v + ")installed");
return true;
} } | public class class_name {
private boolean _update(final Identification id) throws IOException, ServletException {
final File newLucee = downloadCore(id);
if (newLucee == null) return false;
if (singelton != null) singelton.reset();
final Version v = null;
try {
bundleCollection = BundleLoader.loadBundles(this, getFelixCacheDirectory(), getBundleDirectory(), newLucee, bundleCollection);
final CFMLEngine e = getEngine(bundleCollection);
if (e == null) throw new IOException("can't load engine");
version = e.getInfo().getVersion();
// engine = e;
setEngine(e);
// e.reset();
callListeners(e);
ConfigServer cs = getConfigServer(e);
if (cs != null) {
Log log = cs.getLog("deploy");
log.info("loader", "Lucee Version [" + v + "] installed"); // depends on control dependency: [if], data = [none]
}
}
catch (final Exception e) {
System.gc();
try {
newLucee.delete(); // depends on control dependency: [try], data = [none]
}
catch (final Exception ee) {} // depends on control dependency: [catch], data = [none]
log(e);
e.printStackTrace();
return false;
}
log(Logger.LOG_DEBUG, "Version (" + v + ")installed");
return true;
} } |
public class class_name {
@Override ImmutableSet<String> getExtraCommandLineArgs() {
String agentJar = options.get(ALLOCATION_AGENT_JAR_OPTION);
if (Strings.isNullOrEmpty(agentJar)) {
try {
Optional<File> instrumentJar = findAllocationInstrumentJarOnClasspath();
// TODO(gak): bundle up the allocation jar and unpack it if it's not on the classpath
if (instrumentJar.isPresent()) {
agentJar = instrumentJar.get().getAbsolutePath();
}
} catch (IOException e) {
logger.log(SEVERE,
"An exception occurred trying to locate the allocation agent jar on the classpath", e);
}
}
if (Strings.isNullOrEmpty(agentJar) || !new File(agentJar).exists()) {
throw new IllegalStateException("Can't find required allocationinstrumenter agent jar");
}
// Add microbenchmark args to minimize differences in the output
return new ImmutableSet.Builder<String>()
.addAll(super.getExtraCommandLineArgs())
// we just run in interpreted mode to ensure that intrinsics don't break the instrumentation
.add("-Xint")
.add("-javaagent:" + agentJar)
// Some environments rename files and use symlinks to improve resource caching,
// if the agent jar path is actually a symlink it will prevent the agent from finding itself
// and adding itself to the bootclasspath, so we do it manually here.
.add("-Xbootclasspath/a:" + agentJar)
.build();
} } | public class class_name {
@Override ImmutableSet<String> getExtraCommandLineArgs() {
String agentJar = options.get(ALLOCATION_AGENT_JAR_OPTION);
if (Strings.isNullOrEmpty(agentJar)) {
try {
Optional<File> instrumentJar = findAllocationInstrumentJarOnClasspath();
// TODO(gak): bundle up the allocation jar and unpack it if it's not on the classpath
if (instrumentJar.isPresent()) {
agentJar = instrumentJar.get().getAbsolutePath(); // depends on control dependency: [if], data = [none]
}
} catch (IOException e) {
logger.log(SEVERE,
"An exception occurred trying to locate the allocation agent jar on the classpath", e);
} // depends on control dependency: [catch], data = [none]
}
if (Strings.isNullOrEmpty(agentJar) || !new File(agentJar).exists()) {
throw new IllegalStateException("Can't find required allocationinstrumenter agent jar");
}
// Add microbenchmark args to minimize differences in the output
return new ImmutableSet.Builder<String>()
.addAll(super.getExtraCommandLineArgs())
// we just run in interpreted mode to ensure that intrinsics don't break the instrumentation
.add("-Xint")
.add("-javaagent:" + agentJar)
// Some environments rename files and use symlinks to improve resource caching,
// if the agent jar path is actually a symlink it will prevent the agent from finding itself
// and adding itself to the bootclasspath, so we do it manually here.
.add("-Xbootclasspath/a:" + agentJar)
.build();
} } |
public class class_name {
@Override
public byte[] hGet(byte[] key, byte[] field) {
try {
if (isPipelined()) {
pipeline(new JedisResult(pipeline.hget(key, field)));
return null;
}
return client.hget(key, field);
} catch (Exception ex) {
throw convertException(ex);
}
} } | public class class_name {
@Override
public byte[] hGet(byte[] key, byte[] field) {
try {
if (isPipelined()) {
pipeline(new JedisResult(pipeline.hget(key, field))); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
return client.hget(key, field); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
throw convertException(ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void add(final Field _field)
{
this.fields.put(_field.getId(), _field);
this.fieldName2Field.put(_field.getName(), _field);
if (_field.getReference() != null && _field.getReference().length() > 0) {
final String ref = _field.getReference();
int index;
int end = 0;
while ((index = ref.indexOf("$<", end)) > 0) {
index += 2;
end = ref.indexOf(">", index);
addFieldExpr(ref.substring(index, end));
}
}
_field.setCollectionUUID(getUUID());
} } | public class class_name {
public void add(final Field _field)
{
this.fields.put(_field.getId(), _field);
this.fieldName2Field.put(_field.getName(), _field);
if (_field.getReference() != null && _field.getReference().length() > 0) {
final String ref = _field.getReference();
int index;
int end = 0;
while ((index = ref.indexOf("$<", end)) > 0) {
index += 2; // depends on control dependency: [while], data = [none]
end = ref.indexOf(">", index); // depends on control dependency: [while], data = [none]
addFieldExpr(ref.substring(index, end)); // depends on control dependency: [while], data = [none]
}
}
_field.setCollectionUUID(getUUID());
} } |
public class class_name {
@Override
protected void visitHtmlOpenTagNode(HtmlOpenTagNode node) {
if (node.getKeyNode() != null) {
// Push key BEFORE emitting `elementOpen`. Later, for `elementOpen` calls of keyed elements,
// we do not specify any key.
Expression key = translateExpr(node.getKeyNode().getExpr());
getJsCodeBuilder().append(INCREMENTAL_DOM_PUSH_MANUAL_KEY.call(key));
}
Expression tagCodeChunk = getTagNameCodeChunk(node.getTagName());
emitOpenAndVisitAttributes(node, tagCodeChunk);
// Whether or not it is valid for this tag to be self closing has already been validated by the
// HtmlContextVisitor. So we just need to output the close instructions if the node is self
// closing or definitely void.
if (node.isSelfClosing() || node.getTagName().isDefinitelyVoid()) {
emitClose(tagCodeChunk);
}
} } | public class class_name {
@Override
protected void visitHtmlOpenTagNode(HtmlOpenTagNode node) {
if (node.getKeyNode() != null) {
// Push key BEFORE emitting `elementOpen`. Later, for `elementOpen` calls of keyed elements,
// we do not specify any key.
Expression key = translateExpr(node.getKeyNode().getExpr());
getJsCodeBuilder().append(INCREMENTAL_DOM_PUSH_MANUAL_KEY.call(key)); // depends on control dependency: [if], data = [none]
}
Expression tagCodeChunk = getTagNameCodeChunk(node.getTagName());
emitOpenAndVisitAttributes(node, tagCodeChunk);
// Whether or not it is valid for this tag to be self closing has already been validated by the
// HtmlContextVisitor. So we just need to output the close instructions if the node is self
// closing or definitely void.
if (node.isSelfClosing() || node.getTagName().isDefinitelyVoid()) {
emitClose(tagCodeChunk); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public <A extends Appendable> A document(A output) throws IOException {
StringBuilder line = new StringBuilder();
for (Field field: Beans.getKnownInstanceFields(_prototype)) {
description d = field.getAnnotation(description.class);
if (d == null) continue;
placeholder p = field.getAnnotation(placeholder.class);
String n = Strings.splitCamelCase(field.getName(), "-").toLowerCase();
char key = getShortOptionKey(field);
if ((field.getType() == Boolean.class || field.getType() == Boolean.TYPE) && _booleans.containsKey(key)) {
line.append(" -").append(key).append(", --").append(n);
} else {
line.append(" --").append(n).append('=').append(p != null ? p.value() : "value");
}
if (line.length() < 16) {
for (int i = line.length(); i < 16; ++i) line.append(' ');
line.append(d.value());
} else {
line.append("\n\t\t").append(d.value());
}
output.append(line.toString()).append('\n');
line.setLength(0);
}
return output;
} } | public class class_name {
public <A extends Appendable> A document(A output) throws IOException {
StringBuilder line = new StringBuilder();
for (Field field: Beans.getKnownInstanceFields(_prototype)) {
description d = field.getAnnotation(description.class);
if (d == null) continue;
placeholder p = field.getAnnotation(placeholder.class);
String n = Strings.splitCamelCase(field.getName(), "-").toLowerCase();
char key = getShortOptionKey(field);
if ((field.getType() == Boolean.class || field.getType() == Boolean.TYPE) && _booleans.containsKey(key)) {
line.append(" -").append(key).append(", --").append(n); // depends on control dependency: [if], data = [none]
} else {
line.append(" --").append(n).append('=').append(p != null ? p.value() : "value"); // depends on control dependency: [if], data = [none]
}
if (line.length() < 16) {
for (int i = line.length(); i < 16; ++i) line.append(' ');
line.append(d.value()); // depends on control dependency: [if], data = [none]
} else {
line.append("\n\t\t").append(d.value()); // depends on control dependency: [if], data = [none]
}
output.append(line.toString()).append('\n');
line.setLength(0);
}
return output;
} } |
public class class_name {
@ResourceMapping(value = "retrieveSearchJSONResults")
public ModelAndView showJSONSearchResults(PortletRequest request) {
PortletPreferences prefs = request.getPreferences();
int maxTextLength =
Integer.parseInt(prefs.getValue(AUTOCOMPLETE_MAX_TEXT_LENGTH_PREF_NAME, "180"));
final Map<String, Object> model = new HashMap<>();
List<AutocompleteResultsModel> results = new ArrayList<>();
final PortletSession session = request.getPortletSession();
String queryId = (String) session.getAttribute(SEARCH_LAST_QUERY_ID);
if (queryId != null) {
final PortalSearchResults portalSearchResults =
this.getPortalSearchResults(request, queryId);
if (portalSearchResults != null) {
final ConcurrentMap<String, List<Tuple<SearchResult, String>>> resultsMap =
portalSearchResults.getResults();
results = collateResultsForAutoCompleteResponse(resultsMap, maxTextLength);
}
}
model.put("results", results);
model.put("count", results.size());
return new ModelAndView("json", model);
} } | public class class_name {
@ResourceMapping(value = "retrieveSearchJSONResults")
public ModelAndView showJSONSearchResults(PortletRequest request) {
PortletPreferences prefs = request.getPreferences();
int maxTextLength =
Integer.parseInt(prefs.getValue(AUTOCOMPLETE_MAX_TEXT_LENGTH_PREF_NAME, "180"));
final Map<String, Object> model = new HashMap<>();
List<AutocompleteResultsModel> results = new ArrayList<>();
final PortletSession session = request.getPortletSession();
String queryId = (String) session.getAttribute(SEARCH_LAST_QUERY_ID);
if (queryId != null) {
final PortalSearchResults portalSearchResults =
this.getPortalSearchResults(request, queryId);
if (portalSearchResults != null) {
final ConcurrentMap<String, List<Tuple<SearchResult, String>>> resultsMap =
portalSearchResults.getResults();
results = collateResultsForAutoCompleteResponse(resultsMap, maxTextLength); // depends on control dependency: [if], data = [none]
}
}
model.put("results", results);
model.put("count", results.size());
return new ModelAndView("json", model);
} } |
public class class_name {
private void traverseAndRemoveUnusedReferences(Node root) {
// Create scope from parent of root node, which also has externs as a child, so we'll
// have extern definitions in scope.
Scope scope = scopeCreator.createScope(root.getParent(), null);
if (!scope.hasSlot(NodeUtil.JSC_PROPERTY_NAME_FN)) {
// TODO(b/70730762): Passes that add references to this should ensure it is declared.
// NOTE: null input makes this an extern var.
scope.declare(
NodeUtil.JSC_PROPERTY_NAME_FN, /* no declaration node */ null, /* no input */ null);
}
worklist.add(new Continuation(root, scope));
while (!worklist.isEmpty()) {
Continuation continuation = worklist.remove();
continuation.apply();
}
removeUnreferencedVarsAndPolyfills();
removeIndependentlyRemovableProperties();
for (Scope fparamScope : allFunctionParamScopes) {
removeUnreferencedFunctionArgs(fparamScope);
}
} } | public class class_name {
private void traverseAndRemoveUnusedReferences(Node root) {
// Create scope from parent of root node, which also has externs as a child, so we'll
// have extern definitions in scope.
Scope scope = scopeCreator.createScope(root.getParent(), null);
if (!scope.hasSlot(NodeUtil.JSC_PROPERTY_NAME_FN)) {
// TODO(b/70730762): Passes that add references to this should ensure it is declared.
// NOTE: null input makes this an extern var.
scope.declare(
NodeUtil.JSC_PROPERTY_NAME_FN, /* no declaration node */ null, /* no input */ null); // depends on control dependency: [if], data = [none]
}
worklist.add(new Continuation(root, scope));
while (!worklist.isEmpty()) {
Continuation continuation = worklist.remove();
continuation.apply(); // depends on control dependency: [while], data = [none]
}
removeUnreferencedVarsAndPolyfills();
removeIndependentlyRemovableProperties();
for (Scope fparamScope : allFunctionParamScopes) {
removeUnreferencedFunctionArgs(fparamScope); // depends on control dependency: [for], data = [fparamScope]
}
} } |
public class class_name {
@Nullable
private Node trySimplifyUnusedResult(Node expression) {
ArrayDeque<Node> sideEffectRoots = new ArrayDeque<>();
boolean atFixedPoint = trySimplifyUnusedResultInternal(expression, sideEffectRoots);
if (atFixedPoint) {
// `expression` is in a form that cannot be further optimized.
return expression;
} else if (sideEffectRoots.isEmpty()) {
deleteNode(expression);
return null;
} else if (sideEffectRoots.peekFirst() == expression) {
// Expression was a conditional that was transformed. There can't be any other side-effects,
// but we also can't detach the transformed root.
checkState(sideEffectRoots.size() == 1, sideEffectRoots);
reportChangeToEnclosingScope(expression);
return expression;
} else {
Node sideEffects = asDetachedExpression(sideEffectRoots.pollFirst());
// Assemble a tree of comma expressions for all the side-effects. The tree must execute the
// side-effects in FIFO order with respect to the queue. It must also be left leaning to match
// the parser's preferred strucutre.
while (!sideEffectRoots.isEmpty()) {
Node next = asDetachedExpression(sideEffectRoots.pollFirst());
sideEffects = IR.comma(sideEffects, next).srcref(next);
}
expression.getParent().addChildBefore(sideEffects, expression);
deleteNode(expression);
return sideEffects;
}
} } | public class class_name {
@Nullable
private Node trySimplifyUnusedResult(Node expression) {
ArrayDeque<Node> sideEffectRoots = new ArrayDeque<>();
boolean atFixedPoint = trySimplifyUnusedResultInternal(expression, sideEffectRoots);
if (atFixedPoint) {
// `expression` is in a form that cannot be further optimized.
return expression; // depends on control dependency: [if], data = [none]
} else if (sideEffectRoots.isEmpty()) {
deleteNode(expression); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
} else if (sideEffectRoots.peekFirst() == expression) {
// Expression was a conditional that was transformed. There can't be any other side-effects,
// but we also can't detach the transformed root.
checkState(sideEffectRoots.size() == 1, sideEffectRoots); // depends on control dependency: [if], data = [none]
reportChangeToEnclosingScope(expression); // depends on control dependency: [if], data = [expression)]
return expression; // depends on control dependency: [if], data = [none]
} else {
Node sideEffects = asDetachedExpression(sideEffectRoots.pollFirst());
// Assemble a tree of comma expressions for all the side-effects. The tree must execute the
// side-effects in FIFO order with respect to the queue. It must also be left leaning to match
// the parser's preferred strucutre.
while (!sideEffectRoots.isEmpty()) {
Node next = asDetachedExpression(sideEffectRoots.pollFirst());
sideEffects = IR.comma(sideEffects, next).srcref(next); // depends on control dependency: [while], data = [none]
}
expression.getParent().addChildBefore(sideEffects, expression); // depends on control dependency: [if], data = [expression)]
deleteNode(expression); // depends on control dependency: [if], data = [expression)]
return sideEffects; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void setQuota(String path, long nsQuota, long dsQuota) throws IOException {
writeLock();
try {
if (isInSafeMode()) {
throw new SafeModeException("Cannot setQuota " + path, safeMode);
}
INode[] inodes = this.dir.getExistingPathINodes(path);
if (isPermissionEnabled
&& isPermissionCheckingEnabled(inodes)) {
checkSuperuserPrivilege();
}
dir.setQuota(path, nsQuota, dsQuota);
} finally {
writeUnlock();
}
getEditLog().logSync(false);
} } | public class class_name {
void setQuota(String path, long nsQuota, long dsQuota) throws IOException {
writeLock();
try {
if (isInSafeMode()) {
throw new SafeModeException("Cannot setQuota " + path, safeMode);
}
INode[] inodes = this.dir.getExistingPathINodes(path);
if (isPermissionEnabled
&& isPermissionCheckingEnabled(inodes)) {
checkSuperuserPrivilege(); // depends on control dependency: [if], data = [none]
}
dir.setQuota(path, nsQuota, dsQuota);
} finally {
writeUnlock();
}
getEditLog().logSync(false);
} } |
public class class_name {
public void cancel() {
if (!isCancelled) {
isCancelled = true;
IntSet segmentsCopy = getUnfinishedSegments();
synchronized (segments) {
unfinishedSegments.clear();
}
if (trace) {
log.tracef("Cancelling inbound state transfer from %s with unfinished segments %s", source, segmentsCopy);
}
sendCancelCommand(segmentsCopy);
notifyCompletion(false);
}
} } | public class class_name {
public void cancel() {
if (!isCancelled) {
isCancelled = true; // depends on control dependency: [if], data = [none]
IntSet segmentsCopy = getUnfinishedSegments();
synchronized (segments) { // depends on control dependency: [if], data = [none]
unfinishedSegments.clear();
}
if (trace) {
log.tracef("Cancelling inbound state transfer from %s with unfinished segments %s", source, segmentsCopy); // depends on control dependency: [if], data = [none]
}
sendCancelCommand(segmentsCopy); // depends on control dependency: [if], data = [none]
notifyCompletion(false); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public JTree getTreeSite() {
if (treeSite == null) {
treeSite = new JTree(new DefaultTreeModel(new DefaultMutableTreeNode()));
treeSite.setShowsRootHandles(true);
treeSite.setName("treeSite");
treeSite.setToggleClickCount(1);
// Force macOS L&F to query the row height from SiteMapTreeCellRenderer to hide the filtered nodes.
// Other L&Fs hide the filtered nodes by default.
LookAndFeel laf = UIManager.getLookAndFeel();
if (laf != null && Constant.isMacOsX()
&& UIManager.getSystemLookAndFeelClassName().equals(laf.getClass().getName())) {
treeSite.setRowHeight(0);
}
treeSite.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
@Override
public void valueChanged(javax.swing.event.TreeSelectionEvent e) {
SiteNode node = (SiteNode) treeSite.getLastSelectedPathComponent();
if (node == null) {
return;
}
if (!node.isRoot()) {
HttpMessage msg = null;
try {
msg = node.getHistoryReference().getHttpMessage();
} catch (Exception e1) {
// ZAP: Log exceptions
log.warn(e1.getMessage(), e1);
return;
}
getView().displayMessage(msg);
// ZAP: Call SiteMapListenners
for (SiteMapListener listener : listeners) {
listener.nodeSelected(node);
}
} else {
// ZAP: clear the views when the root is selected
getView().displayMessage(null);
}
}
});
treeSite.setComponentPopupMenu(new SitesCustomPopupMenu());
// ZAP: Add custom tree cell renderer.
DefaultTreeCellRenderer renderer = new SiteMapTreeCellRenderer(listeners);
treeSite.setCellRenderer(renderer);
String deleteSiteNode = "zap.delete.sitenode";
treeSite.getInputMap().put(getView().getDefaultDeleteKeyStroke(), deleteSiteNode);
treeSite.getActionMap().put(deleteSiteNode, new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
ExtensionHistory extHistory = Control.getSingleton().getExtensionLoader().getExtension(
ExtensionHistory.class);
if (extHistory == null || treeSite.getSelectionCount() == 0) {
return;
}
int result = View.getSingleton().showConfirmDialog(Constant.messages.getString("sites.purge.warning"));
if (result != JOptionPane.YES_OPTION) {
return;
}
SiteMap siteMap = Model.getSingleton().getSession().getSiteTree();
for (TreePath path : treeSite.getSelectionPaths()) {
extHistory.purge(siteMap, (SiteNode) path.getLastPathComponent());
}
}
});
}
return treeSite;
} } | public class class_name {
public JTree getTreeSite() {
if (treeSite == null) {
treeSite = new JTree(new DefaultTreeModel(new DefaultMutableTreeNode()));
// depends on control dependency: [if], data = [none]
treeSite.setShowsRootHandles(true);
// depends on control dependency: [if], data = [none]
treeSite.setName("treeSite");
// depends on control dependency: [if], data = [none]
treeSite.setToggleClickCount(1);
// depends on control dependency: [if], data = [none]
// Force macOS L&F to query the row height from SiteMapTreeCellRenderer to hide the filtered nodes.
// Other L&Fs hide the filtered nodes by default.
LookAndFeel laf = UIManager.getLookAndFeel();
if (laf != null && Constant.isMacOsX()
&& UIManager.getSystemLookAndFeelClassName().equals(laf.getClass().getName())) {
treeSite.setRowHeight(0);
// depends on control dependency: [if], data = [none]
}
treeSite.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
@Override
public void valueChanged(javax.swing.event.TreeSelectionEvent e) {
SiteNode node = (SiteNode) treeSite.getLastSelectedPathComponent();
if (node == null) {
return;
// depends on control dependency: [if], data = [none]
}
if (!node.isRoot()) {
HttpMessage msg = null;
try {
msg = node.getHistoryReference().getHttpMessage();
// depends on control dependency: [try], data = [none]
} catch (Exception e1) {
// ZAP: Log exceptions
log.warn(e1.getMessage(), e1);
return;
}
// depends on control dependency: [catch], data = [none]
getView().displayMessage(msg);
// depends on control dependency: [if], data = [none]
// ZAP: Call SiteMapListenners
for (SiteMapListener listener : listeners) {
listener.nodeSelected(node);
// depends on control dependency: [for], data = [listener]
}
} else {
// ZAP: clear the views when the root is selected
getView().displayMessage(null);
// depends on control dependency: [if], data = [none]
}
}
});
// depends on control dependency: [if], data = [none]
treeSite.setComponentPopupMenu(new SitesCustomPopupMenu());
// depends on control dependency: [if], data = [none]
// ZAP: Add custom tree cell renderer.
DefaultTreeCellRenderer renderer = new SiteMapTreeCellRenderer(listeners);
treeSite.setCellRenderer(renderer);
// depends on control dependency: [if], data = [none]
String deleteSiteNode = "zap.delete.sitenode";
treeSite.getInputMap().put(getView().getDefaultDeleteKeyStroke(), deleteSiteNode);
// depends on control dependency: [if], data = [none]
treeSite.getActionMap().put(deleteSiteNode, new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
ExtensionHistory extHistory = Control.getSingleton().getExtensionLoader().getExtension(
ExtensionHistory.class);
if (extHistory == null || treeSite.getSelectionCount() == 0) {
return;
// depends on control dependency: [if], data = [none]
}
int result = View.getSingleton().showConfirmDialog(Constant.messages.getString("sites.purge.warning"));
if (result != JOptionPane.YES_OPTION) {
return;
}
SiteMap siteMap = Model.getSingleton().getSession().getSiteTree();
for (TreePath path : treeSite.getSelectionPaths()) {
extHistory.purge(siteMap, (SiteNode) path.getLastPathComponent());
}
}
});
}
return treeSite;
} } // depends on control dependency: [if], data = [none] |
public class class_name {
public static HashFunction concatenating(Iterable<HashFunction> hashFunctions) {
checkNotNull(hashFunctions);
// We can't use Iterables.toArray() here because there's no hash->collect dependency
List<HashFunction> list = new ArrayList<HashFunction>();
for (HashFunction hashFunction : hashFunctions) {
list.add(hashFunction);
}
checkArgument(list.size() > 0, "number of hash functions (%s) must be > 0", list.size());
return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
} } | public class class_name {
public static HashFunction concatenating(Iterable<HashFunction> hashFunctions) {
checkNotNull(hashFunctions);
// We can't use Iterables.toArray() here because there's no hash->collect dependency
List<HashFunction> list = new ArrayList<HashFunction>();
for (HashFunction hashFunction : hashFunctions) {
list.add(hashFunction); // depends on control dependency: [for], data = [hashFunction]
}
checkArgument(list.size() > 0, "number of hash functions (%s) must be > 0", list.size());
return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
} } |
public class class_name {
@Override
public boolean hasVideo() {
KeyFrameMeta meta = analyzeKeyFrames();
if (meta == null) {
return false;
}
return (!meta.audioOnly && meta.positions.length > 0);
} } | public class class_name {
@Override
public boolean hasVideo() {
KeyFrameMeta meta = analyzeKeyFrames();
if (meta == null) {
return false; // depends on control dependency: [if], data = [none]
}
return (!meta.audioOnly && meta.positions.length > 0);
} } |
public class class_name {
@Override
public void tagLocation(INDArray array, Location location) {
if (location == Location.HOST)
AtomicAllocator.getInstance().getAllocationPoint(array).tickHostWrite();
else if (location == Location.DEVICE)
AtomicAllocator.getInstance().getAllocationPoint(array).tickDeviceWrite();
else if (location == Location.EVERYWHERE) {
AtomicAllocator.getInstance().getAllocationPoint(array).tickDeviceWrite();
AtomicAllocator.getInstance().getAllocationPoint(array).tickHostRead();
}
} } | public class class_name {
@Override
public void tagLocation(INDArray array, Location location) {
if (location == Location.HOST)
AtomicAllocator.getInstance().getAllocationPoint(array).tickHostWrite();
else if (location == Location.DEVICE)
AtomicAllocator.getInstance().getAllocationPoint(array).tickDeviceWrite();
else if (location == Location.EVERYWHERE) {
AtomicAllocator.getInstance().getAllocationPoint(array).tickDeviceWrite(); // depends on control dependency: [if], data = [none]
AtomicAllocator.getInstance().getAllocationPoint(array).tickHostRead(); // depends on control dependency: [if], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.