code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public IPersonAttributesGroupDefinition createPagsDefinition(
IPerson person, IEntityGroup parent, String groupName, String description) {
// What's the target of the upcoming permissions check?
String target =
parent != null
? parent.getEntityIdentifier().getKey()
: IPermission
.ALL_GROUPS_TARGET; // Must have blanket permission to create one
// w/o a parent
// Verify permission
if (!hasPermission(person, IPermission.CREATE_GROUP_ACTIVITY, target)) {
throw new RuntimeAuthorizationException(
person, IPermission.CREATE_GROUP_ACTIVITY, target);
}
// VALIDATION STEP: The group name & description are allowable
if (StringUtils.isBlank(groupName)) {
throw new IllegalArgumentException("Specified groupName is blank: " + groupName);
}
if (!GROUP_NAME_VALIDATOR_PATTERN.matcher(groupName).matches()) {
throw new IllegalArgumentException(
"Specified groupName is too long, too short, or contains invalid characters: "
+ groupName);
}
if (!StringUtils.isBlank(description)) { // Blank description is allowable
if (!GROUP_DESC_VALIDATOR_PATTERN.matcher(description).matches()) {
throw new IllegalArgumentException(
"Specified description is too long or contains invalid characters: "
+ description);
}
}
// VALIDATION STEP: We don't have a group by that name already
EntityIdentifier[] people =
GroupService.searchForGroups(
groupName, IGroupConstants.SearchMethod.DISCRETE_CI, IPerson.class);
EntityIdentifier[] portlets =
GroupService.searchForGroups(
groupName,
IGroupConstants.SearchMethod.DISCRETE_CI,
IPortletDefinition.class);
if (people.length != 0 || portlets.length != 0) {
throw new IllegalArgumentException("Specified groupName already in use: " + groupName);
}
IPersonAttributesGroupDefinition rslt =
pagsGroupDefDao.createPersonAttributesGroupDefinition(groupName, description);
if (parent != null) {
// Should refactor this switch to instead choose a service and invoke a method on it
switch (parent.getServiceName().toString()) {
case SERVICE_NAME_LOCAL:
IEntityGroup member =
GroupService.findGroup(
rslt.getCompositeEntityIdentifierForGroup().getKey());
if (member == null) {
String msg =
"The specified group was created, but is not present in the store: "
+ rslt.getName();
throw new RuntimeException(msg);
}
parent.addChild(member);
parent.updateMembers();
break;
case SERVICE_NAME_PAGS:
IPersonAttributesGroupDefinition parentDef =
getPagsGroupDefByName(parent.getName());
Set<IPersonAttributesGroupDefinition> members =
new HashSet<>(parentDef.getMembers());
members.add(rslt);
parentDef.setMembers(members);
pagsGroupDefDao.updatePersonAttributesGroupDefinition(parentDef);
break;
default:
String msg =
"The specified group service does not support adding members: "
+ parent.getServiceName();
throw new UnsupportedOperationException(msg);
}
}
return rslt;
} } | public class class_name {
public IPersonAttributesGroupDefinition createPagsDefinition(
IPerson person, IEntityGroup parent, String groupName, String description) {
// What's the target of the upcoming permissions check?
String target =
parent != null
? parent.getEntityIdentifier().getKey()
: IPermission
.ALL_GROUPS_TARGET; // Must have blanket permission to create one
// w/o a parent
// Verify permission
if (!hasPermission(person, IPermission.CREATE_GROUP_ACTIVITY, target)) {
throw new RuntimeAuthorizationException(
person, IPermission.CREATE_GROUP_ACTIVITY, target);
}
// VALIDATION STEP: The group name & description are allowable
if (StringUtils.isBlank(groupName)) {
throw new IllegalArgumentException("Specified groupName is blank: " + groupName);
}
if (!GROUP_NAME_VALIDATOR_PATTERN.matcher(groupName).matches()) {
throw new IllegalArgumentException(
"Specified groupName is too long, too short, or contains invalid characters: "
+ groupName);
}
if (!StringUtils.isBlank(description)) { // Blank description is allowable
if (!GROUP_DESC_VALIDATOR_PATTERN.matcher(description).matches()) {
throw new IllegalArgumentException(
"Specified description is too long or contains invalid characters: "
+ description);
}
}
// VALIDATION STEP: We don't have a group by that name already
EntityIdentifier[] people =
GroupService.searchForGroups(
groupName, IGroupConstants.SearchMethod.DISCRETE_CI, IPerson.class);
EntityIdentifier[] portlets =
GroupService.searchForGroups(
groupName,
IGroupConstants.SearchMethod.DISCRETE_CI,
IPortletDefinition.class);
if (people.length != 0 || portlets.length != 0) {
throw new IllegalArgumentException("Specified groupName already in use: " + groupName);
}
IPersonAttributesGroupDefinition rslt =
pagsGroupDefDao.createPersonAttributesGroupDefinition(groupName, description);
if (parent != null) {
// Should refactor this switch to instead choose a service and invoke a method on it
switch (parent.getServiceName().toString()) {
case SERVICE_NAME_LOCAL:
IEntityGroup member =
GroupService.findGroup(
rslt.getCompositeEntityIdentifierForGroup().getKey());
if (member == null) {
String msg =
"The specified group was created, but is not present in the store: "
+ rslt.getName(); // depends on control dependency: [if], data = [none]
throw new RuntimeException(msg);
}
parent.addChild(member);
parent.updateMembers();
break;
case SERVICE_NAME_PAGS:
IPersonAttributesGroupDefinition parentDef =
getPagsGroupDefByName(parent.getName());
Set<IPersonAttributesGroupDefinition> members =
new HashSet<>(parentDef.getMembers());
members.add(rslt);
parentDef.setMembers(members);
pagsGroupDefDao.updatePersonAttributesGroupDefinition(parentDef);
break;
default:
String msg =
"The specified group service does not support adding members: "
+ parent.getServiceName();
throw new UnsupportedOperationException(msg);
}
}
return rslt;
} } |
public class class_name {
@Override
public List<ModelServiceInstance> getServiceInstanceList() {
List<ModelServiceInstance> instances = null;
String keyName = null;
if (query.getCriteria().size() > 0) {
keyName = query.getCriteria().get(0).getMetadataKey();
}
if (keyName != null && !keyName.isEmpty()) {
List<ModelServiceInstance> modelInstances = getLookupService()
.queryUPModelInstances(query);
instances = ServiceInstanceQueryHelper
.filter(query, modelInstances);
}
if (instances != null) {
return instances;
} else {
return Collections.emptyList();
}
} } | public class class_name {
@Override
public List<ModelServiceInstance> getServiceInstanceList() {
List<ModelServiceInstance> instances = null;
String keyName = null;
if (query.getCriteria().size() > 0) {
keyName = query.getCriteria().get(0).getMetadataKey(); // depends on control dependency: [if], data = [0)]
}
if (keyName != null && !keyName.isEmpty()) {
List<ModelServiceInstance> modelInstances = getLookupService()
.queryUPModelInstances(query);
instances = ServiceInstanceQueryHelper
.filter(query, modelInstances); // depends on control dependency: [if], data = [none]
}
if (instances != null) {
return instances; // depends on control dependency: [if], data = [none]
} else {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static boolean areVariablesDistinct(ImmutableList<? extends VariableOrGroundTerm> arguments) {
Set<Variable> encounteredVariables = new HashSet<>();
for (VariableOrGroundTerm argument : arguments) {
if (argument instanceof Variable) {
if (!encounteredVariables.add((Variable)argument)) {
return false;
}
}
}
return true;
} } | public class class_name {
public static boolean areVariablesDistinct(ImmutableList<? extends VariableOrGroundTerm> arguments) {
Set<Variable> encounteredVariables = new HashSet<>();
for (VariableOrGroundTerm argument : arguments) {
if (argument instanceof Variable) {
if (!encounteredVariables.add((Variable)argument)) {
return false; // depends on control dependency: [if], data = [none]
}
}
}
return true;
} } |
public class class_name {
public java.util.List<CustomVerificationEmailTemplate> getCustomVerificationEmailTemplates() {
if (customVerificationEmailTemplates == null) {
customVerificationEmailTemplates = new com.amazonaws.internal.SdkInternalList<CustomVerificationEmailTemplate>();
}
return customVerificationEmailTemplates;
} } | public class class_name {
public java.util.List<CustomVerificationEmailTemplate> getCustomVerificationEmailTemplates() {
if (customVerificationEmailTemplates == null) {
customVerificationEmailTemplates = new com.amazonaws.internal.SdkInternalList<CustomVerificationEmailTemplate>(); // depends on control dependency: [if], data = [none]
}
return customVerificationEmailTemplates;
} } |
public class class_name {
public void setAvailablePortSpeeds(java.util.Collection<String> availablePortSpeeds) {
if (availablePortSpeeds == null) {
this.availablePortSpeeds = null;
return;
}
this.availablePortSpeeds = new com.amazonaws.internal.SdkInternalList<String>(availablePortSpeeds);
} } | public class class_name {
public void setAvailablePortSpeeds(java.util.Collection<String> availablePortSpeeds) {
if (availablePortSpeeds == null) {
this.availablePortSpeeds = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.availablePortSpeeds = new com.amazonaws.internal.SdkInternalList<String>(availablePortSpeeds);
} } |
public class class_name {
private static Type[] extractTypeArgumentsFrom(final Map<TypeVariable<?>, Type> mappings, final TypeVariable<?>[] variables) {
final Type[] result = new Type[variables.length];
int index = 0;
for (final TypeVariable<?> var : variables) {
Validate.isTrue(mappings.containsKey(var), "missing argument mapping for %s", toString(var));
result[index++] = mappings.get(var);
}
return result;
} } | public class class_name {
private static Type[] extractTypeArgumentsFrom(final Map<TypeVariable<?>, Type> mappings, final TypeVariable<?>[] variables) {
final Type[] result = new Type[variables.length];
int index = 0;
for (final TypeVariable<?> var : variables) {
Validate.isTrue(mappings.containsKey(var), "missing argument mapping for %s", toString(var)); // depends on control dependency: [for], data = [var]
result[index++] = mappings.get(var); // depends on control dependency: [for], data = [var]
}
return result;
} } |
public class class_name {
public void addDependency(final Dependency dependency) {
if(dependency != null && !dependencies.contains(dependency)){
this.dependencies.add(dependency);
}
} } | public class class_name {
public void addDependency(final Dependency dependency) {
if(dependency != null && !dependencies.contains(dependency)){
this.dependencies.add(dependency); // depends on control dependency: [if], data = [(dependency]
}
} } |
public class class_name {
public void marshall(ParameterValue parameterValue, ProtocolMarshaller protocolMarshaller) {
if (parameterValue == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(parameterValue.getName(), NAME_BINDING);
protocolMarshaller.marshall(parameterValue.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(ParameterValue parameterValue, ProtocolMarshaller protocolMarshaller) {
if (parameterValue == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(parameterValue.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(parameterValue.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 static void decodePathSegment(List<PathSegment> segments, String segment, boolean decode) {
int colon = segment.indexOf(';');
if (colon != -1) {
segments.add(new PathSegmentImpl(
(colon == 0) ? "" : segment.substring(0, colon),
decode,
decodeMatrix(segment, decode)));
} else {
segments.add(new PathSegmentImpl(
segment,
decode));
}
} } | public class class_name {
public static void decodePathSegment(List<PathSegment> segments, String segment, boolean decode) {
int colon = segment.indexOf(';');
if (colon != -1) {
segments.add(new PathSegmentImpl(
(colon == 0) ? "" : segment.substring(0, colon),
decode,
decodeMatrix(segment, decode))); // depends on control dependency: [if], data = [none]
} else {
segments.add(new PathSegmentImpl(
segment,
decode)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public Response setDescription( String applicationName, String desc ) {
this.logger.fine( "Request: change the description of " + applicationName + "." );
Response response = Response.ok().build();
String lang = lang( this.manager );
try {
ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName );
if( ma == null ) {
response = handleError(
Status.NOT_FOUND,
new RestError( REST_INEXISTING, application( applicationName )),
lang ).build();
} else {
this.manager.applicationMngr().updateApplication( ma, desc );
}
} catch( IOException e ) {
response = RestServicesUtils.handleError(
Status.FORBIDDEN,
new RestError( ErrorCode.REST_UNDETAILED_ERROR, e ),
lang ).build();
}
return response;
} } | public class class_name {
@Override
public Response setDescription( String applicationName, String desc ) {
this.logger.fine( "Request: change the description of " + applicationName + "." );
Response response = Response.ok().build();
String lang = lang( this.manager );
try {
ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName );
if( ma == null ) {
response = handleError(
Status.NOT_FOUND,
new RestError( REST_INEXISTING, application( applicationName )),
lang ).build(); // depends on control dependency: [if], data = [none]
} else {
this.manager.applicationMngr().updateApplication( ma, desc ); // depends on control dependency: [if], data = [( ma]
}
} catch( IOException e ) {
response = RestServicesUtils.handleError(
Status.FORBIDDEN,
new RestError( ErrorCode.REST_UNDETAILED_ERROR, e ),
lang ).build();
} // depends on control dependency: [catch], data = [none]
return response;
} } |
public class class_name {
private Stmt.IfElse parseIfStatement(EnclosingScope scope) {
int start = index;
// An if statement begins with the keyword "if", followed by an
// expression representing the condition.
match(If);
// NOTE: expression terminated by ':'
Expr c = parseLogicalExpression(scope, true);
// The a colon to signal the start of a block.
match(Colon);
matchEndLine();
int end = index;
// First, parse the true branch, which is required
Stmt.Block tblk = parseBlock(scope, scope.isInLoop());
// Second, attempt to parse the false branch, which is optional.
Stmt.Block fblk = null;
if (tryAndMatchAtIndent(true, scope.getIndent(), Else) != null) {
int if_start = index;
if (tryAndMatch(true, If) != null) {
// This is an if-chain, so backtrack and parse a complete If
index = if_start;
fblk = new Stmt.Block(parseIfStatement(scope));
} else {
match(Colon);
matchEndLine();
fblk = parseBlock(scope, scope.isInLoop());
}
}
Stmt.IfElse stmt;
if(fblk == null) {
stmt = new Stmt.IfElse(c, tblk);
} else {
stmt = new Stmt.IfElse(c, tblk, fblk);
}
// Done!
return annotateSourceLocation(stmt, start, end-1);
} } | public class class_name {
private Stmt.IfElse parseIfStatement(EnclosingScope scope) {
int start = index;
// An if statement begins with the keyword "if", followed by an
// expression representing the condition.
match(If);
// NOTE: expression terminated by ':'
Expr c = parseLogicalExpression(scope, true);
// The a colon to signal the start of a block.
match(Colon);
matchEndLine();
int end = index;
// First, parse the true branch, which is required
Stmt.Block tblk = parseBlock(scope, scope.isInLoop());
// Second, attempt to parse the false branch, which is optional.
Stmt.Block fblk = null;
if (tryAndMatchAtIndent(true, scope.getIndent(), Else) != null) {
int if_start = index;
if (tryAndMatch(true, If) != null) {
// This is an if-chain, so backtrack and parse a complete If
index = if_start; // depends on control dependency: [if], data = [none]
fblk = new Stmt.Block(parseIfStatement(scope)); // depends on control dependency: [if], data = [none]
} else {
match(Colon); // depends on control dependency: [if], data = [none]
matchEndLine(); // depends on control dependency: [if], data = [none]
fblk = parseBlock(scope, scope.isInLoop()); // depends on control dependency: [if], data = [none]
}
}
Stmt.IfElse stmt;
if(fblk == null) {
stmt = new Stmt.IfElse(c, tblk); // depends on control dependency: [if], data = [none]
} else {
stmt = new Stmt.IfElse(c, tblk, fblk); // depends on control dependency: [if], data = [none]
}
// Done!
return annotateSourceLocation(stmt, start, end-1);
} } |
public class class_name {
protected void checkForConflictingCondition(final IOptionsNode node, final ContentSpec contentSpec) {
if (!isNullOrEmpty(node.getConditionStatement())) {
final String publicanCfg;
if (!contentSpec.getDefaultPublicanCfg().equals(CommonConstants.CS_PUBLICAN_CFG_TITLE)) {
final String name = contentSpec.getDefaultPublicanCfg();
final Matcher matcher = CSConstants.CUSTOM_PUBLICAN_CFG_PATTERN.matcher(name);
final String fixedName = matcher.find() ? matcher.group(1) : name;
publicanCfg = contentSpec.getAdditionalPublicanCfg(fixedName);
} else {
publicanCfg = contentSpec.getPublicanCfg();
}
// Make sure a publican.cfg is defined before doing any checks
if (!isNullOrEmpty(publicanCfg)) {
if (publicanCfg.contains("condition:")) {
log.warn(String.format(ProcessorConstants.WARN_CONDITION_IGNORED_MSG, node.getLineNumber(), node.getText()));
}
}
}
} } | public class class_name {
protected void checkForConflictingCondition(final IOptionsNode node, final ContentSpec contentSpec) {
if (!isNullOrEmpty(node.getConditionStatement())) {
final String publicanCfg;
if (!contentSpec.getDefaultPublicanCfg().equals(CommonConstants.CS_PUBLICAN_CFG_TITLE)) {
final String name = contentSpec.getDefaultPublicanCfg();
final Matcher matcher = CSConstants.CUSTOM_PUBLICAN_CFG_PATTERN.matcher(name);
final String fixedName = matcher.find() ? matcher.group(1) : name;
publicanCfg = contentSpec.getAdditionalPublicanCfg(fixedName); // depends on control dependency: [if], data = [none]
} else {
publicanCfg = contentSpec.getPublicanCfg(); // depends on control dependency: [if], data = [none]
}
// Make sure a publican.cfg is defined before doing any checks
if (!isNullOrEmpty(publicanCfg)) {
if (publicanCfg.contains("condition:")) {
log.warn(String.format(ProcessorConstants.WARN_CONDITION_IGNORED_MSG, node.getLineNumber(), node.getText())); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public static String flagNames(long flags) {
StringBuilder sbuf = new StringBuilder();
int i = 0;
long f = flags & StandardFlags;
while (f != 0) {
if ((f & 1) != 0) {
sbuf.append(" ");
sbuf.append(flagName[i]);
}
f = f >> 1;
i++;
}
return sbuf.toString();
} } | public class class_name {
public static String flagNames(long flags) {
StringBuilder sbuf = new StringBuilder();
int i = 0;
long f = flags & StandardFlags;
while (f != 0) {
if ((f & 1) != 0) {
sbuf.append(" "); // depends on control dependency: [if], data = [none]
sbuf.append(flagName[i]); // depends on control dependency: [if], data = [none]
}
f = f >> 1; // depends on control dependency: [while], data = [none]
i++; // depends on control dependency: [while], data = [none]
}
return sbuf.toString();
} } |
public class class_name {
public AddressTemplate replaceWildcards(String wildcard, String... wildcards) {
List<String> allWildcards = new ArrayList<>();
allWildcards.add(wildcard);
if (wildcards != null) {
allWildcards.addAll(Arrays.asList(wildcards));
}
LinkedList<Token> replacedTokens = new LinkedList<>();
Iterator<String> wi = allWildcards.iterator();
for (Token token : tokens) {
if (wi.hasNext() && token.hasKey() && "*".equals(token.getValue())) {
replacedTokens.add(new Token(token.getKey(), wi.next()));
} else {
replacedTokens.add(new Token(token.key, token.value));
}
}
return AddressTemplate.of(join(this.optional, replacedTokens));
} } | public class class_name {
public AddressTemplate replaceWildcards(String wildcard, String... wildcards) {
List<String> allWildcards = new ArrayList<>();
allWildcards.add(wildcard);
if (wildcards != null) {
allWildcards.addAll(Arrays.asList(wildcards)); // depends on control dependency: [if], data = [(wildcards]
}
LinkedList<Token> replacedTokens = new LinkedList<>();
Iterator<String> wi = allWildcards.iterator();
for (Token token : tokens) {
if (wi.hasNext() && token.hasKey() && "*".equals(token.getValue())) {
replacedTokens.add(new Token(token.getKey(), wi.next())); // depends on control dependency: [if], data = [none]
} else {
replacedTokens.add(new Token(token.key, token.value)); // depends on control dependency: [if], data = [none]
}
}
return AddressTemplate.of(join(this.optional, replacedTokens));
} } |
public class class_name {
@SuppressWarnings("PMD.EmptyCatchBlock")
public static ResourceInfo resourceInfo(URL resource) {
try {
Path path = Paths.get(resource.toURI());
return new ResourceInfo(Files.isDirectory(path),
Files.getLastModifiedTime(path).toInstant()
.with(ChronoField.NANO_OF_SECOND, 0));
} catch (FileSystemNotFoundException | IOException
| URISyntaxException e) {
// Fall through
}
if ("jar".equals(resource.getProtocol())) {
try {
JarURLConnection conn
= (JarURLConnection) resource.openConnection();
JarEntry entry = conn.getJarEntry();
return new ResourceInfo(entry.isDirectory(),
entry.getLastModifiedTime().toInstant()
.with(ChronoField.NANO_OF_SECOND, 0));
} catch (IOException e) {
// Fall through
}
}
try {
URLConnection conn = resource.openConnection();
long lastModified = conn.getLastModified();
if (lastModified != 0) {
return new ResourceInfo(null, Instant.ofEpochMilli(
lastModified).with(ChronoField.NANO_OF_SECOND, 0));
}
} catch (IOException e) {
// Fall through
}
return new ResourceInfo(null, null);
} } | public class class_name {
@SuppressWarnings("PMD.EmptyCatchBlock")
public static ResourceInfo resourceInfo(URL resource) {
try {
Path path = Paths.get(resource.toURI());
return new ResourceInfo(Files.isDirectory(path),
Files.getLastModifiedTime(path).toInstant()
.with(ChronoField.NANO_OF_SECOND, 0)); // depends on control dependency: [try], data = [none]
} catch (FileSystemNotFoundException | IOException
| URISyntaxException e) {
// Fall through
} // depends on control dependency: [catch], data = [none]
if ("jar".equals(resource.getProtocol())) {
try {
JarURLConnection conn
= (JarURLConnection) resource.openConnection();
JarEntry entry = conn.getJarEntry();
return new ResourceInfo(entry.isDirectory(),
entry.getLastModifiedTime().toInstant()
.with(ChronoField.NANO_OF_SECOND, 0)); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// Fall through
} // depends on control dependency: [catch], data = [none]
}
try {
URLConnection conn = resource.openConnection();
long lastModified = conn.getLastModified();
if (lastModified != 0) {
return new ResourceInfo(null, Instant.ofEpochMilli(
lastModified).with(ChronoField.NANO_OF_SECOND, 0)); // depends on control dependency: [if], data = [none]
}
} catch (IOException e) {
// Fall through
} // depends on control dependency: [catch], data = [none]
return new ResourceInfo(null, null);
} } |
public class class_name {
@Override
protected void encode() {
char[] controlChars = toControlChars(content);
int l = controlChars.length;
if (!content.matches("[\u0000-\u007F]+")) {
throw new OkapiException("Invalid characters in input data");
}
int[] values = new int[controlChars.length + 2];
for (int i = 0; i < l; i++) {
values[i] = positionOf(controlChars[i], CODE_93_LOOKUP);
}
int c = calculateCheckDigitC(values, l);
values[l] = c;
l++;
int k = calculateCheckDigitK(values, l);
values[l] = k;
l++;
readable = content;
if (showCheckDigits) {
readable = readable + CODE_93_LOOKUP[c] + CODE_93_LOOKUP[k];
}
if (startStopDelimiter != null) {
readable = startStopDelimiter + readable + startStopDelimiter;
}
encodeInfo += "Check Digit C: " + c + "\n";
encodeInfo += "Check Digit K: " + k + "\n";
pattern = new String[] { toPattern(values) };
row_count = 1;
row_height = new int[] { -1 };
} } | public class class_name {
@Override
protected void encode() {
char[] controlChars = toControlChars(content);
int l = controlChars.length;
if (!content.matches("[\u0000-\u007F]+")) {
throw new OkapiException("Invalid characters in input data");
}
int[] values = new int[controlChars.length + 2];
for (int i = 0; i < l; i++) {
values[i] = positionOf(controlChars[i], CODE_93_LOOKUP);
// depends on control dependency: [for], data = [i]
}
int c = calculateCheckDigitC(values, l);
values[l] = c;
l++;
int k = calculateCheckDigitK(values, l);
values[l] = k;
l++;
readable = content;
if (showCheckDigits) {
readable = readable + CODE_93_LOOKUP[c] + CODE_93_LOOKUP[k];
// depends on control dependency: [if], data = [none]
}
if (startStopDelimiter != null) {
readable = startStopDelimiter + readable + startStopDelimiter;
// depends on control dependency: [if], data = [none]
}
encodeInfo += "Check Digit C: " + c + "\n";
encodeInfo += "Check Digit K: " + k + "\n";
pattern = new String[] { toPattern(values) };
row_count = 1;
row_height = new int[] { -1 };
} } |
public class class_name {
private static String xSystemToUnicode(String s) {
String result = "";
int length = s.length();
for (int i = 0; i < length; i++){
char c1 = s.charAt(i);
char c2 = (i + 1 < length) ? s.charAt(i + 1) : ' ';
if (c2 == 'x') {
switch (c1) {
case 'c': result += 'ĉ'; ++i; break;
case 'g': result += 'ĝ'; ++i; break;
case 'h': result += 'ĥ'; ++i; break;
case 'j': result += 'ĵ'; ++i; break;
case 's': result += 'ŝ'; ++i; break;
case 'u': result += 'ŭ'; ++i; break;
default: result += c1; break;
}
} else {
result += c1;
}
}
return result;
} } | public class class_name {
private static String xSystemToUnicode(String s) {
String result = "";
int length = s.length();
for (int i = 0; i < length; i++){
char c1 = s.charAt(i);
char c2 = (i + 1 < length) ? s.charAt(i + 1) : ' ';
if (c2 == 'x') {
switch (c1) {
case 'c': result += 'ĉ'; ++i; break;
case 'g': result += 'ĝ'; ++i; break;
case 'h': result += 'ĥ'; ++i; break;
case 'j': result += 'ĵ'; ++i; break;
case 's': result += 'ŝ'; ++i; break;
case 'u': result += 'ŭ'; ++i; break;
default: result += c1; break;
}
} else {
result += c1; // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public <T> T addSymbolizer( Symbolizer newSymbolizer, Class<T> symbolizerClass ) {
SymbolizerWrapper wrapper = null;
if (newSymbolizer != null) {
if (newSymbolizer instanceof PointSymbolizer) {
wrapper = new PointSymbolizerWrapper(newSymbolizer, this);
} else if (newSymbolizer instanceof LineSymbolizer) {
wrapper = new LineSymbolizerWrapper(newSymbolizer, this);
} else if (newSymbolizer instanceof PolygonSymbolizer) {
wrapper = new PolygonSymbolizerWrapper(newSymbolizer, this);
} else if (newSymbolizer instanceof TextSymbolizer) {
wrapper = new TextSymbolizerWrapper(newSymbolizer, this, getType());
} else if (newSymbolizer instanceof RasterSymbolizer) {
wrapper = new RasterSymbolizerWrapper(newSymbolizer, this);
} else {
return null;
}
} else {
if (symbolizerClass.isAssignableFrom(PointSymbolizerWrapper.class)) {
newSymbolizer = sf.createPointSymbolizer();
wrapper = new PointSymbolizerWrapper(newSymbolizer, this);
} else if (symbolizerClass.isAssignableFrom(LineSymbolizerWrapper.class)) {
newSymbolizer = sf.createLineSymbolizer();
wrapper = new LineSymbolizerWrapper(newSymbolizer, this);
} else if (symbolizerClass.isAssignableFrom(PolygonSymbolizerWrapper.class)) {
newSymbolizer = sf.createPolygonSymbolizer();
wrapper = new PolygonSymbolizerWrapper(newSymbolizer, this);
} else if (symbolizerClass.isAssignableFrom(TextSymbolizerWrapper.class)) {
newSymbolizer = sf.createTextSymbolizer();
wrapper = new TextSymbolizerWrapper(newSymbolizer, this, getType());
} else if (symbolizerClass.isAssignableFrom(RasterSymbolizer.class)) {
wrapper = new RasterSymbolizerWrapper(newSymbolizer, this);
} else {
return null;
}
}
rule.symbolizers().add(newSymbolizer);
symbolizersWrapperList.add(wrapper);
return symbolizerClass.cast(wrapper);
} } | public class class_name {
public <T> T addSymbolizer( Symbolizer newSymbolizer, Class<T> symbolizerClass ) {
SymbolizerWrapper wrapper = null;
if (newSymbolizer != null) {
if (newSymbolizer instanceof PointSymbolizer) {
wrapper = new PointSymbolizerWrapper(newSymbolizer, this); // depends on control dependency: [if], data = [none]
} else if (newSymbolizer instanceof LineSymbolizer) {
wrapper = new LineSymbolizerWrapper(newSymbolizer, this); // depends on control dependency: [if], data = [none]
} else if (newSymbolizer instanceof PolygonSymbolizer) {
wrapper = new PolygonSymbolizerWrapper(newSymbolizer, this); // depends on control dependency: [if], data = [none]
} else if (newSymbolizer instanceof TextSymbolizer) {
wrapper = new TextSymbolizerWrapper(newSymbolizer, this, getType()); // depends on control dependency: [if], data = [none]
} else if (newSymbolizer instanceof RasterSymbolizer) {
wrapper = new RasterSymbolizerWrapper(newSymbolizer, this); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} else {
if (symbolizerClass.isAssignableFrom(PointSymbolizerWrapper.class)) {
newSymbolizer = sf.createPointSymbolizer(); // depends on control dependency: [if], data = [none]
wrapper = new PointSymbolizerWrapper(newSymbolizer, this); // depends on control dependency: [if], data = [none]
} else if (symbolizerClass.isAssignableFrom(LineSymbolizerWrapper.class)) {
newSymbolizer = sf.createLineSymbolizer(); // depends on control dependency: [if], data = [none]
wrapper = new LineSymbolizerWrapper(newSymbolizer, this); // depends on control dependency: [if], data = [none]
} else if (symbolizerClass.isAssignableFrom(PolygonSymbolizerWrapper.class)) {
newSymbolizer = sf.createPolygonSymbolizer(); // depends on control dependency: [if], data = [none]
wrapper = new PolygonSymbolizerWrapper(newSymbolizer, this); // depends on control dependency: [if], data = [none]
} else if (symbolizerClass.isAssignableFrom(TextSymbolizerWrapper.class)) {
newSymbolizer = sf.createTextSymbolizer(); // depends on control dependency: [if], data = [none]
wrapper = new TextSymbolizerWrapper(newSymbolizer, this, getType()); // depends on control dependency: [if], data = [none]
} else if (symbolizerClass.isAssignableFrom(RasterSymbolizer.class)) {
wrapper = new RasterSymbolizerWrapper(newSymbolizer, this); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
}
rule.symbolizers().add(newSymbolizer);
symbolizersWrapperList.add(wrapper);
return symbolizerClass.cast(wrapper);
} } |
public class class_name {
@Override
public byte[] getBlob(int columnIndex) {
byte[] value;
try {
value = resultSet
.getBytes(resultIndexToResultSetIndex(columnIndex));
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to get blob bytes for column index: " + columnIndex,
e);
}
return value;
} } | public class class_name {
@Override
public byte[] getBlob(int columnIndex) {
byte[] value;
try {
value = resultSet
.getBytes(resultIndexToResultSetIndex(columnIndex)); // depends on control dependency: [try], data = [none]
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to get blob bytes for column index: " + columnIndex,
e);
} // depends on control dependency: [catch], data = [none]
return value;
} } |
public class class_name {
private void checkNonEmpty(Decl.Variable d, LifetimeRelation lifetimes) {
if (relaxedSubtypeOperator.isVoid(d.getType(), lifetimes)) {
syntaxError(d.getType(), EMPTY_TYPE);
}
} } | public class class_name {
private void checkNonEmpty(Decl.Variable d, LifetimeRelation lifetimes) {
if (relaxedSubtypeOperator.isVoid(d.getType(), lifetimes)) {
syntaxError(d.getType(), EMPTY_TYPE); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setAdditionalMasterSecurityGroups(java.util.Collection<String> additionalMasterSecurityGroups) {
if (additionalMasterSecurityGroups == null) {
this.additionalMasterSecurityGroups = null;
return;
}
this.additionalMasterSecurityGroups = new com.amazonaws.internal.SdkInternalList<String>(additionalMasterSecurityGroups);
} } | public class class_name {
public void setAdditionalMasterSecurityGroups(java.util.Collection<String> additionalMasterSecurityGroups) {
if (additionalMasterSecurityGroups == null) {
this.additionalMasterSecurityGroups = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.additionalMasterSecurityGroups = new com.amazonaws.internal.SdkInternalList<String>(additionalMasterSecurityGroups);
} } |
public class class_name {
int asciiOnlyCaseMap(IntHolder flagP, byte[]bytes, IntHolder pp, int end, byte[]to, int toP, int toEnd) {
int toStart = toP;
int flags = flagP.value;
while (pp.value < end && toP < toEnd) {
// specialize for singlebyte ?
int length = length(bytes, pp.value, end);
if (length < 0) return length;
int code = mbcToCode(bytes, pp.value, end);
pp.value += length;
if (code >= 'a' && code <= 'z' && ((flags & Config.CASE_UPCASE) != 0)) {
flags |= Config.CASE_MODIFIED;
code += 'A' - 'a';
} else if (code >= 'A' && code <= 'Z' && ((flags & (Config.CASE_DOWNCASE | Config.CASE_FOLD)) != 0)) {
flags |= Config.CASE_MODIFIED;
code += 'a' - 'A';
}
toP += codeToMbc(code, to, toP);
if ((flags & Config.CASE_TITLECASE) != 0) {
flags ^= (Config.CASE_UPCASE | Config.CASE_DOWNCASE | Config.CASE_TITLECASE);
}
}
flagP.value = flags;
return toP - toStart;
} } | public class class_name {
int asciiOnlyCaseMap(IntHolder flagP, byte[]bytes, IntHolder pp, int end, byte[]to, int toP, int toEnd) {
int toStart = toP;
int flags = flagP.value;
while (pp.value < end && toP < toEnd) {
// specialize for singlebyte ?
int length = length(bytes, pp.value, end);
if (length < 0) return length;
int code = mbcToCode(bytes, pp.value, end);
pp.value += length; // depends on control dependency: [while], data = [none]
if (code >= 'a' && code <= 'z' && ((flags & Config.CASE_UPCASE) != 0)) {
flags |= Config.CASE_MODIFIED; // depends on control dependency: [if], data = [none]
code += 'A' - 'a'; // depends on control dependency: [if], data = [none]
} else if (code >= 'A' && code <= 'Z' && ((flags & (Config.CASE_DOWNCASE | Config.CASE_FOLD)) != 0)) {
flags |= Config.CASE_MODIFIED; // depends on control dependency: [if], data = [none]
code += 'a' - 'A'; // depends on control dependency: [if], data = [none]
}
toP += codeToMbc(code, to, toP); // depends on control dependency: [while], data = [none]
if ((flags & Config.CASE_TITLECASE) != 0) {
flags ^= (Config.CASE_UPCASE | Config.CASE_DOWNCASE | Config.CASE_TITLECASE); // depends on control dependency: [if], data = [none]
}
}
flagP.value = flags;
return toP - toStart;
} } |
public class class_name {
public Observable<ServiceResponse<List<AdvisorInner>>> listByServerWithServiceResponseAsync(String resourceGroupName, String serverName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serverName == null) {
throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listByServer(resourceGroupName, serverName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<AdvisorInner>>>>() {
@Override
public Observable<ServiceResponse<List<AdvisorInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<AdvisorInner>> clientResponse = listByServerDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<List<AdvisorInner>>> listByServerWithServiceResponseAsync(String resourceGroupName, String serverName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serverName == null) {
throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listByServer(resourceGroupName, serverName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<AdvisorInner>>>>() {
@Override
public Observable<ServiceResponse<List<AdvisorInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<AdvisorInner>> clientResponse = listByServerDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public static boolean haveEqualArrays(Object[] arra, Object[] arrb,
int count) {
if (count > arra.length || count > arrb.length) {
return false;
}
for (int j = 0; j < count; j++) {
if (arra[j] != arrb[j]) {
if (arra[j] == null || !arra[j].equals(arrb[j])) {
return false;
}
}
}
return true;
} } | public class class_name {
public static boolean haveEqualArrays(Object[] arra, Object[] arrb,
int count) {
if (count > arra.length || count > arrb.length) {
return false; // depends on control dependency: [if], data = [none]
}
for (int j = 0; j < count; j++) {
if (arra[j] != arrb[j]) {
if (arra[j] == null || !arra[j].equals(arrb[j])) {
return false; // depends on control dependency: [if], data = [none]
}
}
}
return true;
} } |
public class class_name {
private int parse(final IntBuffer buff, final int start) {
int pos = start;
/**
* Revision (1 byte): An unsigned 8-bit value that specifies the revision of the SECURITY_DESCRIPTOR
* structure. This field MUST be set to one.
*/
final byte[] header = NumberFacility.getBytes(buff.get(pos));
revision = header[0];
/**
* Control (2 bytes): An unsigned 16-bit field that specifies control access bit flags. The Self Relative
* (SR) bit MUST be set when the security descriptor is in self-relative format.
*/
controlFlags = new byte[] { header[3], header[2] };
final boolean[] controlFlag = NumberFacility.getBits(controlFlags);
pos++;
/**
* OffsetOwner (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID
* specifies the owner of the object to which the security descriptor is associated. This must be a valid
* offset if the OD flag is not set. If this field is set to zero, the OwnerSid field MUST not be present.
*/
if (!controlFlag[15]) {
offsetOwner = NumberFacility.getReverseUInt(buff.get(pos));
} else {
offsetOwner = 0;
}
pos++;
/**
* OffsetGroup (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID
* specifies the group of the object to which the security descriptor is associated. This must be a valid
* offset if the GD flag is not set. If this field is set to zero, the GroupSid field MUST not be present.
*/
if (!controlFlag[14]) {
offsetGroup = NumberFacility.getReverseUInt(buff.get(pos));
} else {
offsetGroup = 0;
}
pos++;
/**
* OffsetSacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains
* system ACEs. Typically, the system ACL contains auditing ACEs (such as SYSTEM_AUDIT_ACE,
* SYSTEM_AUDIT_CALLBACK_ACE, or SYSTEM_AUDIT_CALLBACK_OBJECT_ACE), and at most one Label ACE (as specified
* in section 2.4.4.13). This must be a valid offset if the SP flag is set; if the SP flag is not set, this
* field MUST be set to zero. If this field is set to zero, the Sacl field MUST not be present.
*/
if (controlFlag[11]) {
offsetSACL = NumberFacility.getReverseUInt(buff.get(pos));
} else {
offsetSACL = 0;
}
pos++;
/**
* OffsetDacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains ACEs
* that control access. Typically, the DACL contains ACEs that grant or deny access to principals or groups.
* This must be a valid offset if the DP flag is set; if the DP flag is not set, this field MUST be set to
* zero. If this field is set to zero, the Dacl field MUST not be present.
*/
if (controlFlag[13]) {
offsetDACL = NumberFacility.getReverseUInt(buff.get(pos));
} else {
offsetDACL = 0;
}
/**
* OwnerSid (variable): The SID of the owner of the object. The length of the SID MUST be a multiple of 4.
* This field MUST be present if the OffsetOwner field is not zero.
*/
if (offsetOwner > 0) {
pos = (int) (offsetOwner / 4);
// read for OwnerSid
owner = new SID();
pos = owner.parse(buff, pos);
}
/**
* GroupSid (variable): The SID of the group of the object. The length of the SID MUST be a multiple of 4.
* This field MUST be present if the GroupOwner field is not zero.
*/
if (offsetGroup > 0) {
// read for GroupSid
pos = (int) (offsetGroup / 4);
group = new SID();
pos = group.parse(buff, pos);
}
/**
* Sacl (variable): The SACL of the object. The length of the SID MUST be a multiple of 4. This field MUST
* be present if the SP flag is set.
*/
if (offsetSACL > 0) {
// read for Sacl
pos = (int) (offsetSACL / 4);
sacl = new ACL();
pos = sacl.parse(buff, pos);
}
/**
* Dacl (variable): The DACL of the object. The length of the SID MUST be a multiple of 4. This field MUST
* be present if the DP flag is set.
*/
if (offsetDACL > 0) {
pos = (int) (offsetDACL / 4);
dacl = new ACL();
pos = dacl.parse(buff, pos);
}
return pos;
} } | public class class_name {
private int parse(final IntBuffer buff, final int start) {
int pos = start;
/**
* Revision (1 byte): An unsigned 8-bit value that specifies the revision of the SECURITY_DESCRIPTOR
* structure. This field MUST be set to one.
*/
final byte[] header = NumberFacility.getBytes(buff.get(pos));
revision = header[0];
/**
* Control (2 bytes): An unsigned 16-bit field that specifies control access bit flags. The Self Relative
* (SR) bit MUST be set when the security descriptor is in self-relative format.
*/
controlFlags = new byte[] { header[3], header[2] };
final boolean[] controlFlag = NumberFacility.getBits(controlFlags);
pos++;
/**
* OffsetOwner (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID
* specifies the owner of the object to which the security descriptor is associated. This must be a valid
* offset if the OD flag is not set. If this field is set to zero, the OwnerSid field MUST not be present.
*/
if (!controlFlag[15]) {
offsetOwner = NumberFacility.getReverseUInt(buff.get(pos)); // depends on control dependency: [if], data = [none]
} else {
offsetOwner = 0; // depends on control dependency: [if], data = [none]
}
pos++;
/**
* OffsetGroup (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID
* specifies the group of the object to which the security descriptor is associated. This must be a valid
* offset if the GD flag is not set. If this field is set to zero, the GroupSid field MUST not be present.
*/
if (!controlFlag[14]) {
offsetGroup = NumberFacility.getReverseUInt(buff.get(pos)); // depends on control dependency: [if], data = [none]
} else {
offsetGroup = 0; // depends on control dependency: [if], data = [none]
}
pos++;
/**
* OffsetSacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains
* system ACEs. Typically, the system ACL contains auditing ACEs (such as SYSTEM_AUDIT_ACE,
* SYSTEM_AUDIT_CALLBACK_ACE, or SYSTEM_AUDIT_CALLBACK_OBJECT_ACE), and at most one Label ACE (as specified
* in section 2.4.4.13). This must be a valid offset if the SP flag is set; if the SP flag is not set, this
* field MUST be set to zero. If this field is set to zero, the Sacl field MUST not be present.
*/
if (controlFlag[11]) {
offsetSACL = NumberFacility.getReverseUInt(buff.get(pos)); // depends on control dependency: [if], data = [none]
} else {
offsetSACL = 0; // depends on control dependency: [if], data = [none]
}
pos++;
/**
* OffsetDacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains ACEs
* that control access. Typically, the DACL contains ACEs that grant or deny access to principals or groups.
* This must be a valid offset if the DP flag is set; if the DP flag is not set, this field MUST be set to
* zero. If this field is set to zero, the Dacl field MUST not be present.
*/
if (controlFlag[13]) {
offsetDACL = NumberFacility.getReverseUInt(buff.get(pos)); // depends on control dependency: [if], data = [none]
} else {
offsetDACL = 0; // depends on control dependency: [if], data = [none]
}
/**
* OwnerSid (variable): The SID of the owner of the object. The length of the SID MUST be a multiple of 4.
* This field MUST be present if the OffsetOwner field is not zero.
*/
if (offsetOwner > 0) {
pos = (int) (offsetOwner / 4); // depends on control dependency: [if], data = [(offsetOwner]
// read for OwnerSid
owner = new SID(); // depends on control dependency: [if], data = [none]
pos = owner.parse(buff, pos); // depends on control dependency: [if], data = [none]
}
/**
* GroupSid (variable): The SID of the group of the object. The length of the SID MUST be a multiple of 4.
* This field MUST be present if the GroupOwner field is not zero.
*/
if (offsetGroup > 0) {
// read for GroupSid
pos = (int) (offsetGroup / 4); // depends on control dependency: [if], data = [(offsetGroup]
group = new SID(); // depends on control dependency: [if], data = [none]
pos = group.parse(buff, pos); // depends on control dependency: [if], data = [none]
}
/**
* Sacl (variable): The SACL of the object. The length of the SID MUST be a multiple of 4. This field MUST
* be present if the SP flag is set.
*/
if (offsetSACL > 0) {
// read for Sacl
pos = (int) (offsetSACL / 4); // depends on control dependency: [if], data = [(offsetSACL]
sacl = new ACL(); // depends on control dependency: [if], data = [none]
pos = sacl.parse(buff, pos); // depends on control dependency: [if], data = [none]
}
/**
* Dacl (variable): The DACL of the object. The length of the SID MUST be a multiple of 4. This field MUST
* be present if the DP flag is set.
*/
if (offsetDACL > 0) {
pos = (int) (offsetDACL / 4); // depends on control dependency: [if], data = [(offsetDACL]
dacl = new ACL(); // depends on control dependency: [if], data = [none]
pos = dacl.parse(buff, pos); // depends on control dependency: [if], data = [none]
}
return pos;
} } |
public class class_name {
public BoundingBox getBoundingBox(Projection projection) {
BoundingBox boundingBox = getBoundingBox();
if (projection != null) {
ProjectionTransform transform = getProjection().getTransformation(
projection);
if (!transform.isSameProjection()) {
boundingBox = boundingBox.transform(transform);
}
}
return boundingBox;
} } | public class class_name {
public BoundingBox getBoundingBox(Projection projection) {
BoundingBox boundingBox = getBoundingBox();
if (projection != null) {
ProjectionTransform transform = getProjection().getTransformation(
projection);
if (!transform.isSameProjection()) {
boundingBox = boundingBox.transform(transform); // depends on control dependency: [if], data = [none]
}
}
return boundingBox;
} } |
public class class_name {
public static String getEnv(){
if(ENV == null){
if(!blank(System.getenv("ACTIVE_ENV"))) {
ENV = System.getenv("ACTIVE_ENV");
}
if(!blank(System.getProperty("ACTIVE_ENV"))) {
ENV = System.getProperty("ACTIVE_ENV");
}
if(!blank(System.getProperty("active_env"))) {
ENV = System.getProperty("active_env");
}
if(blank(ENV)){
ENV = "development";
LOGGER.warn("Environment variable ACTIVE_ENV not provided, defaulting to '" + ENV + "'");
}
}
return ENV;
} } | public class class_name {
public static String getEnv(){
if(ENV == null){
if(!blank(System.getenv("ACTIVE_ENV"))) {
ENV = System.getenv("ACTIVE_ENV"); // depends on control dependency: [if], data = [none]
}
if(!blank(System.getProperty("ACTIVE_ENV"))) {
ENV = System.getProperty("ACTIVE_ENV"); // depends on control dependency: [if], data = [none]
}
if(!blank(System.getProperty("active_env"))) {
ENV = System.getProperty("active_env"); // depends on control dependency: [if], data = [none]
}
if(blank(ENV)){
ENV = "development"; // depends on control dependency: [if], data = [none]
LOGGER.warn("Environment variable ACTIVE_ENV not provided, defaulting to '" + ENV + "'"); // depends on control dependency: [if], data = [none]
}
}
return ENV;
} } |
public class class_name {
public static Basic1DMatrix diagonal(int size, double diagonal) {
double[] array = new double[size * size];
for (int i = 0; i < size; i++) {
array[i * size + i] = diagonal;
}
return new Basic1DMatrix(size, size, array);
} } | public class class_name {
public static Basic1DMatrix diagonal(int size, double diagonal) {
double[] array = new double[size * size];
for (int i = 0; i < size; i++) {
array[i * size + i] = diagonal; // depends on control dependency: [for], data = [i]
}
return new Basic1DMatrix(size, size, array);
} } |
public class class_name {
public static SqlExpression exp(String name, String op, Object value) {
if(value!=null && value instanceof Nesting){
return NestExps.create(name, op, (Nesting) value);
}
return Exps.create(name, op, value);
} } | public class class_name {
public static SqlExpression exp(String name, String op, Object value) {
if(value!=null && value instanceof Nesting){
return NestExps.create(name, op, (Nesting) value);
// depends on control dependency: [if], data = [none]
}
return Exps.create(name, op, value);
} } |
public class class_name {
public static List<Point2D_F64> createLayout( int numRows , int numCols , double centerDistance ) {
List<Point2D_F64> ret = new ArrayList<>();
double spaceX = centerDistance/2.0;
double spaceY = centerDistance*Math.sin(UtilAngle.radian(60));
double width = (numCols-1)*spaceX;
double height = (numRows-1)*spaceY;
for (int row = 0; row < numRows; row++) {
double y = row*spaceY - height/2;
for (int col = row%2; col < numCols; col += 2) {
double x = col*spaceX - width/2;
ret.add( new Point2D_F64(x,y));
}
}
return ret;
} } | public class class_name {
public static List<Point2D_F64> createLayout( int numRows , int numCols , double centerDistance ) {
List<Point2D_F64> ret = new ArrayList<>();
double spaceX = centerDistance/2.0;
double spaceY = centerDistance*Math.sin(UtilAngle.radian(60));
double width = (numCols-1)*spaceX;
double height = (numRows-1)*spaceY;
for (int row = 0; row < numRows; row++) {
double y = row*spaceY - height/2;
for (int col = row%2; col < numCols; col += 2) {
double x = col*spaceX - width/2;
ret.add( new Point2D_F64(x,y)); // depends on control dependency: [for], data = [none]
}
}
return ret;
} } |
public class class_name {
public void start() {
if (SubscriptionHelper.setOnce(upstream, EmptySubscription.INSTANCE)) {
queue = new SpscArrayQueue<T>(bufferSize);
}
} } | public class class_name {
public void start() {
if (SubscriptionHelper.setOnce(upstream, EmptySubscription.INSTANCE)) {
queue = new SpscArrayQueue<T>(bufferSize); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private CmsResource findReferencingPage(CmsResource source) throws CmsException {
List<CmsRelation> relationsToFile = m_cms.readRelations(
CmsRelationFilter.relationsToStructureId(source.getStructureId()));
for (CmsRelation relation : relationsToFile) {
try {
CmsResource referencingPage = relation.getSource(m_cms, CmsResourceFilter.DEFAULT);
if (CmsResourceTypeXmlContainerPage.isContainerPage(referencingPage)) {
return referencingPage;
}
} catch (CmsException e) {
LOG.info(e.getLocalizedMessage(), e);
}
}
return null;
} } | public class class_name {
private CmsResource findReferencingPage(CmsResource source) throws CmsException {
List<CmsRelation> relationsToFile = m_cms.readRelations(
CmsRelationFilter.relationsToStructureId(source.getStructureId()));
for (CmsRelation relation : relationsToFile) {
try {
CmsResource referencingPage = relation.getSource(m_cms, CmsResourceFilter.DEFAULT);
if (CmsResourceTypeXmlContainerPage.isContainerPage(referencingPage)) {
return referencingPage;
// depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
LOG.info(e.getLocalizedMessage(), e);
}
// depends on control dependency: [catch], data = [none]
}
return null;
} } |
public class class_name {
public SockAddr getNetmask() {
SockAddr sockAddr = null;
if (this.netmask != null) {
sockAddr = new SockAddr(this.netmask.getSaFamily().getValue(), this.netmask.getData());
}
return sockAddr;
} } | public class class_name {
public SockAddr getNetmask() {
SockAddr sockAddr = null;
if (this.netmask != null) {
sockAddr = new SockAddr(this.netmask.getSaFamily().getValue(), this.netmask.getData()); // depends on control dependency: [if], data = [(this.netmask]
}
return sockAddr;
} } |
public class class_name {
protected static boolean defaultIgnoreNullValue(Object obj) {
if(obj instanceof CharSequence || obj instanceof JSONTokener || obj instanceof Map) {
return false;
}
return true;
} } | public class class_name {
protected static boolean defaultIgnoreNullValue(Object obj) {
if(obj instanceof CharSequence || obj instanceof JSONTokener || obj instanceof Map) {
return false;
// depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
@GwtIncompatible("Unnecessary")
int processResults(Result result, List<JSModule> modules, B options) throws IOException {
if (config.printPassGraph) {
if (compiler.getRoot() == null) {
return 1;
} else {
Appendable jsOutput = createDefaultOutput();
jsOutput.append(
DotFormatter.toDot(compiler.getPassConfig().getPassGraph()));
jsOutput.append('\n');
closeAppendable(jsOutput);
return 0;
}
}
if (config.printAst) {
if (compiler.getRoot() == null) {
return 1;
} else {
Appendable jsOutput = createDefaultOutput();
ControlFlowGraph<Node> cfg = compiler.computeCFG();
DotFormatter.appendDot(
compiler.getRoot().getLastChild(), cfg, jsOutput);
jsOutput.append('\n');
closeAppendable(jsOutput);
return 0;
}
}
if (config.printTree) {
if (compiler.getRoot() == null) {
compiler.report(JSError.make(NO_TREE_GENERATED_ERROR));
return 1;
} else {
Appendable jsOutput = createDefaultOutput();
compiler.getRoot().appendStringTree(jsOutput);
jsOutput.append("\n");
closeAppendable(jsOutput);
return 0;
}
}
if (config.skipNormalOutputs) {
// Output the manifest and bundle files if requested.
outputManifest();
outputBundle();
outputModuleGraphJson();
return 0;
} else if (options.outputJs != OutputJs.NONE && result.success) {
outputModuleGraphJson();
if (modules == null) {
outputSingleBinary(options);
// Output the source map if requested.
// If output files are being written to stdout as a JSON string,
// outputSingleBinary will have added the sourcemap to the output file
if (!isOutputInJson()) {
outputSourceMap(options, config.jsOutputFile);
}
} else {
DiagnosticType error = outputModuleBinaryAndSourceMaps(compiler.getModules(), options);
if (error != null) {
compiler.report(JSError.make(error));
return 1;
}
}
// Output the externs if required.
if (options.externExportsPath != null) {
try (Writer eeOut = openExternExportsStream(options, config.jsOutputFile)) {
eeOut.append(result.externExport);
}
}
// Output the variable and property name maps if requested.
outputNameMaps();
// Output the ReplaceStrings map if requested
outputStringMap();
// Output the manifest and bundle files if requested.
outputManifest();
outputBundle();
if (isOutputInJson()) {
outputJsonStream();
}
}
// return 0 if no errors, the error count otherwise
return Math.min(result.errors.size(), 0x7f);
} } | public class class_name {
@GwtIncompatible("Unnecessary")
int processResults(Result result, List<JSModule> modules, B options) throws IOException {
if (config.printPassGraph) {
if (compiler.getRoot() == null) {
return 1; // depends on control dependency: [if], data = [none]
} else {
Appendable jsOutput = createDefaultOutput();
jsOutput.append(
DotFormatter.toDot(compiler.getPassConfig().getPassGraph())); // depends on control dependency: [if], data = [none]
jsOutput.append('\n'); // depends on control dependency: [if], data = [none]
closeAppendable(jsOutput); // depends on control dependency: [if], data = [none]
return 0; // depends on control dependency: [if], data = [none]
}
}
if (config.printAst) {
if (compiler.getRoot() == null) {
return 1; // depends on control dependency: [if], data = [none]
} else {
Appendable jsOutput = createDefaultOutput();
ControlFlowGraph<Node> cfg = compiler.computeCFG();
DotFormatter.appendDot(
compiler.getRoot().getLastChild(), cfg, jsOutput); // depends on control dependency: [if], data = [none]
jsOutput.append('\n'); // depends on control dependency: [if], data = [none]
closeAppendable(jsOutput); // depends on control dependency: [if], data = [none]
return 0; // depends on control dependency: [if], data = [none]
}
}
if (config.printTree) {
if (compiler.getRoot() == null) {
compiler.report(JSError.make(NO_TREE_GENERATED_ERROR)); // depends on control dependency: [if], data = [none]
return 1; // depends on control dependency: [if], data = [none]
} else {
Appendable jsOutput = createDefaultOutput();
compiler.getRoot().appendStringTree(jsOutput); // depends on control dependency: [if], data = [none]
jsOutput.append("\n"); // depends on control dependency: [if], data = [none]
closeAppendable(jsOutput); // depends on control dependency: [if], data = [none]
return 0; // depends on control dependency: [if], data = [none]
}
}
if (config.skipNormalOutputs) {
// Output the manifest and bundle files if requested.
outputManifest();
outputBundle();
outputModuleGraphJson();
return 0;
} else if (options.outputJs != OutputJs.NONE && result.success) {
outputModuleGraphJson();
if (modules == null) {
outputSingleBinary(options); // depends on control dependency: [if], data = [none]
// Output the source map if requested.
// If output files are being written to stdout as a JSON string,
// outputSingleBinary will have added the sourcemap to the output file
if (!isOutputInJson()) {
outputSourceMap(options, config.jsOutputFile); // depends on control dependency: [if], data = [none]
}
} else {
DiagnosticType error = outputModuleBinaryAndSourceMaps(compiler.getModules(), options);
if (error != null) {
compiler.report(JSError.make(error)); // depends on control dependency: [if], data = [(error]
return 1; // depends on control dependency: [if], data = [none]
}
}
// Output the externs if required.
if (options.externExportsPath != null) {
try (Writer eeOut = openExternExportsStream(options, config.jsOutputFile)) {
eeOut.append(result.externExport);
}
}
// Output the variable and property name maps if requested.
outputNameMaps();
// Output the ReplaceStrings map if requested
outputStringMap();
// Output the manifest and bundle files if requested.
outputManifest();
outputBundle();
if (isOutputInJson()) {
outputJsonStream();
}
}
// return 0 if no errors, the error count otherwise
return Math.min(result.errors.size(), 0x7f);
} } |
public class class_name {
@Override
public String indexValue(String name, Object value) {
if (value == null) {
return null;
} else if (value instanceof ByteBuffer) {
ByteBuffer bb = (ByteBuffer) value;
return ByteBufferUtils.toHex(bb);
} else if (value instanceof byte[]) {
byte[] bytes = (byte[]) value;
return ByteBufferUtils.toHex(bytes);
} else if (value instanceof String) {
String string = (String) value;
string = string.replaceFirst("0x", "");
byte[] bytes = Hex.hexToBytes(string);
return Hex.bytesToHex(bytes);
} else {
throw new IllegalArgumentException(String.format("Value '%s' cannot be cast to byte array", value));
}
} } | public class class_name {
@Override
public String indexValue(String name, Object value) {
if (value == null) {
return null; // depends on control dependency: [if], data = [none]
} else if (value instanceof ByteBuffer) {
ByteBuffer bb = (ByteBuffer) value;
return ByteBufferUtils.toHex(bb); // depends on control dependency: [if], data = [none]
} else if (value instanceof byte[]) {
byte[] bytes = (byte[]) value;
return ByteBufferUtils.toHex(bytes); // depends on control dependency: [if], data = [none]
} else if (value instanceof String) {
String string = (String) value;
string = string.replaceFirst("0x", ""); // depends on control dependency: [if], data = [none]
byte[] bytes = Hex.hexToBytes(string);
return Hex.bytesToHex(bytes); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException(String.format("Value '%s' cannot be cast to byte array", value));
}
} } |
public class class_name {
public static void show(DialogControl<?> control) {
DialogResponse<?> response = control.getLastResponse();
if (response != null) {
control.callback(response);
return;
}
Window root = null;
try {
Map<String, Object> args = Collections.singletonMap("control", control);
root = (Window) PageUtil
.createPage(DialogConstants.RESOURCE_PREFIX + "promptDialog.fsp", ExecutionContext.getPage(), args)
.get(0);
root.modal(null);
} catch (Exception e) {
log.error("Error Displaying Dialog", e);
if (root != null) {
root.destroy();
}
throw MiscUtil.toUnchecked(e);
}
} } | public class class_name {
public static void show(DialogControl<?> control) {
DialogResponse<?> response = control.getLastResponse();
if (response != null) {
control.callback(response); // depends on control dependency: [if], data = [(response]
return; // depends on control dependency: [if], data = [none]
}
Window root = null;
try {
Map<String, Object> args = Collections.singletonMap("control", control);
root = (Window) PageUtil
.createPage(DialogConstants.RESOURCE_PREFIX + "promptDialog.fsp", ExecutionContext.getPage(), args)
.get(0); // depends on control dependency: [try], data = [none]
root.modal(null); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.error("Error Displaying Dialog", e);
if (root != null) {
root.destroy(); // depends on control dependency: [if], data = [none]
}
throw MiscUtil.toUnchecked(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public EClass getIfcHeatingValueMeasure() {
if (ifcHeatingValueMeasureEClass == null) {
ifcHeatingValueMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(683);
}
return ifcHeatingValueMeasureEClass;
} } | public class class_name {
public EClass getIfcHeatingValueMeasure() {
if (ifcHeatingValueMeasureEClass == null) {
ifcHeatingValueMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(683);
// depends on control dependency: [if], data = [none]
}
return ifcHeatingValueMeasureEClass;
} } |
public class class_name {
public AbcNode getChild(String label) {
if (label == null || label.equals(""))
return null;
String[] generation = label.split("/");
String child = generation[0];
String grandchild = "";
if (generation.length > 1) {
for (int i = 1; i < generation.length; i++) {
grandchild += (grandchild.equals("") ? "" : "/");
grandchild += generation[i];
}
}
Iterator it = childs.iterator();
while (it.hasNext()) {
AbcNode abcn = (AbcNode) it.next();
if (child.equals(abcn.getLabel())) {
if (grandchild.equals(""))
return abcn;
else
return abcn.getChild(grandchild);
}
}
return null;
} } | public class class_name {
public AbcNode getChild(String label) {
if (label == null || label.equals(""))
return null;
String[] generation = label.split("/");
String child = generation[0];
String grandchild = "";
if (generation.length > 1) {
for (int i = 1; i < generation.length; i++) {
grandchild += (grandchild.equals("") ? "" : "/"); // depends on control dependency: [for], data = [none]
grandchild += generation[i]; // depends on control dependency: [for], data = [i]
}
}
Iterator it = childs.iterator();
while (it.hasNext()) {
AbcNode abcn = (AbcNode) it.next();
if (child.equals(abcn.getLabel())) {
if (grandchild.equals(""))
return abcn;
else
return abcn.getChild(grandchild);
}
}
return null;
} } |
public class class_name {
@Override
protected void buildJsonItemSpecificPart(JSONObject jsonObj, CmsResource res, String sitePath) {
// file target
String pointer;
try {
pointer = new String(getCms().readFile(res).getContents());
if (CmsStringUtil.isEmptyOrWhitespaceOnly(pointer)) {
pointer = getJsp().link(getCms().getSitePath(res));
}
jsonObj.append("pointer", pointer);
} catch (CmsException e) {
// reading the resource or property value failed
LOG.error(e.getLocalizedMessage(), e);
} catch (JSONException e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
}
} } | public class class_name {
@Override
protected void buildJsonItemSpecificPart(JSONObject jsonObj, CmsResource res, String sitePath) {
// file target
String pointer;
try {
pointer = new String(getCms().readFile(res).getContents()); // depends on control dependency: [try], data = [none]
if (CmsStringUtil.isEmptyOrWhitespaceOnly(pointer)) {
pointer = getJsp().link(getCms().getSitePath(res)); // depends on control dependency: [if], data = [none]
}
jsonObj.append("pointer", pointer); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// reading the resource or property value failed
LOG.error(e.getLocalizedMessage(), e);
} catch (JSONException e) { // depends on control dependency: [catch], data = [none]
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Requires({
"oldLocals != null",
"extraIndex >= -1"
})
@Ensures("result >= 0")
protected int getPostDescOffset(List<Integer> oldLocals, int extraIndex) {
int off = 0;
if (extraIndex != -1) {
++off;
}
off += oldLocals.size();
return off;
} } | public class class_name {
@Requires({
"oldLocals != null",
"extraIndex >= -1"
})
@Ensures("result >= 0")
protected int getPostDescOffset(List<Integer> oldLocals, int extraIndex) {
int off = 0;
if (extraIndex != -1) {
++off; // depends on control dependency: [if], data = [none]
}
off += oldLocals.size();
return off;
} } |
public class class_name {
public ColumnType[] detectColumnTypes(Iterator<String[]> rows, ReadOptions options) {
boolean useSampling = options.sample();
// to hold the results
List<ColumnType> columnTypes = new ArrayList<>();
// to hold the data read from the file
List<List<String>> columnData = new ArrayList<>();
int rowCount = 0; // make sure we don't go over maxRows
int nextRow = 0;
while (rows.hasNext()) {
String[] nextLine = rows.next();
// initialize the arrays to hold the strings. we don't know how many we need until we read the first row
if (rowCount == 0) {
for (int i = 0; i < nextLine.length; i++) {
columnData.add(new ArrayList<>());
}
}
int columnNumber = 0;
if (rowCount == nextRow) {
for (String field : nextLine) {
columnData.get(columnNumber).add(field);
columnNumber++;
}
if (useSampling) {
nextRow = nextRow(nextRow);
} else {
nextRow = nextRowWithoutSampling(nextRow);
}
}
rowCount++;
}
// now detect
for (List<String> valuesList : columnData) {
ColumnType detectedType = detectType(valuesList, options);
if (detectedType.equals(StringColumnType.STRING) && rowCount > STRING_COLUMN_ROW_COUNT_CUTOFF) {
HashSet<String> unique = new HashSet<>(valuesList);
double uniquePct = unique.size() / (valuesList.size() * 1.0);
if (uniquePct > STRING_COLUMN_CUTOFF) {
detectedType = TEXT;
}
}
columnTypes.add(detectedType);
}
return columnTypes.toArray(new ColumnType[0]);
} } | public class class_name {
public ColumnType[] detectColumnTypes(Iterator<String[]> rows, ReadOptions options) {
boolean useSampling = options.sample();
// to hold the results
List<ColumnType> columnTypes = new ArrayList<>();
// to hold the data read from the file
List<List<String>> columnData = new ArrayList<>();
int rowCount = 0; // make sure we don't go over maxRows
int nextRow = 0;
while (rows.hasNext()) {
String[] nextLine = rows.next();
// initialize the arrays to hold the strings. we don't know how many we need until we read the first row
if (rowCount == 0) {
for (int i = 0; i < nextLine.length; i++) {
columnData.add(new ArrayList<>()); // depends on control dependency: [for], data = [none]
}
}
int columnNumber = 0;
if (rowCount == nextRow) {
for (String field : nextLine) {
columnData.get(columnNumber).add(field); // depends on control dependency: [for], data = [field]
columnNumber++; // depends on control dependency: [for], data = [none]
}
if (useSampling) {
nextRow = nextRow(nextRow); // depends on control dependency: [if], data = [none]
} else {
nextRow = nextRowWithoutSampling(nextRow); // depends on control dependency: [if], data = [none]
}
}
rowCount++; // depends on control dependency: [while], data = [none]
}
// now detect
for (List<String> valuesList : columnData) {
ColumnType detectedType = detectType(valuesList, options);
if (detectedType.equals(StringColumnType.STRING) && rowCount > STRING_COLUMN_ROW_COUNT_CUTOFF) {
HashSet<String> unique = new HashSet<>(valuesList);
double uniquePct = unique.size() / (valuesList.size() * 1.0);
if (uniquePct > STRING_COLUMN_CUTOFF) {
detectedType = TEXT; // depends on control dependency: [if], data = [none]
}
}
columnTypes.add(detectedType); // depends on control dependency: [for], data = [none]
}
return columnTypes.toArray(new ColumnType[0]);
} } |
public class class_name {
public static double varianceDoublematrixColumn( double[][] matrix, int column, double mean )
{
double variance;
variance = 0;
for( int i = 0; i < matrix.length; i++ ) {
variance += (matrix[i][column] - mean) * (matrix[i][column] - mean);
}
return variance / matrix.length;
} } | public class class_name {
public static double varianceDoublematrixColumn( double[][] matrix, int column, double mean )
{
double variance;
variance = 0;
for( int i = 0; i < matrix.length; i++ ) {
variance += (matrix[i][column] - mean) * (matrix[i][column] - mean); // depends on control dependency: [for], data = [i]
}
return variance / matrix.length;
} } |
public class class_name {
private String addPathProperty(final List<String> command, final String typeName, final String propertyName, final Map<String, String> properties, final DirectoryGrouping directoryGrouping,
final File typeDir, File serverDir) {
final String result;
final String value = properties.get(propertyName);
if (value == null) {
switch (directoryGrouping) {
case BY_TYPE:
result = getAbsolutePath(typeDir, "servers", serverName);
break;
case BY_SERVER:
default:
result = getAbsolutePath(serverDir, typeName);
break;
}
properties.put(propertyName, result);
} else {
final File dir = new File(value);
switch (directoryGrouping) {
case BY_TYPE:
result = getAbsolutePath(dir, "servers", serverName);
break;
case BY_SERVER:
default:
result = getAbsolutePath(dir, serverName);
break;
}
}
command.add(String.format("-D%s=%s", propertyName, result));
return result;
} } | public class class_name {
private String addPathProperty(final List<String> command, final String typeName, final String propertyName, final Map<String, String> properties, final DirectoryGrouping directoryGrouping,
final File typeDir, File serverDir) {
final String result;
final String value = properties.get(propertyName);
if (value == null) {
switch (directoryGrouping) {
case BY_TYPE:
result = getAbsolutePath(typeDir, "servers", serverName);
break;
case BY_SERVER:
default:
result = getAbsolutePath(serverDir, typeName);
break;
}
properties.put(propertyName, result); // depends on control dependency: [if], data = [none]
} else {
final File dir = new File(value);
switch (directoryGrouping) {
case BY_TYPE:
result = getAbsolutePath(dir, "servers", serverName);
break;
case BY_SERVER:
default:
result = getAbsolutePath(dir, serverName);
break;
}
}
command.add(String.format("-D%s=%s", propertyName, result));
return result;
} } |
public class class_name {
public static int arrayHashCode(Object array) {
if (array == null) {
return 0;
}
IType arrayType = TypeSystem.getFromObject(array);
int iLen = arrayType.getArrayLength(array);
int hashCode = 0;
for (int i = 0; i < iLen; i++) {
Object value = arrayType.getArrayComponent(array, i);
if (value != null) {
IType valueType = TypeSystem.getFromObject(value);
if (valueType.isArray()) {
hashCode = 31 * hashCode + hashCode(value);
} else {
hashCode = 31 * hashCode + value.hashCode();
}
}
}
return hashCode * 31 + iLen;
} } | public class class_name {
public static int arrayHashCode(Object array) {
if (array == null) {
return 0; // depends on control dependency: [if], data = [none]
}
IType arrayType = TypeSystem.getFromObject(array);
int iLen = arrayType.getArrayLength(array);
int hashCode = 0;
for (int i = 0; i < iLen; i++) {
Object value = arrayType.getArrayComponent(array, i);
if (value != null) {
IType valueType = TypeSystem.getFromObject(value);
if (valueType.isArray()) {
hashCode = 31 * hashCode + hashCode(value); // depends on control dependency: [if], data = [none]
} else {
hashCode = 31 * hashCode + value.hashCode(); // depends on control dependency: [if], data = [none]
}
}
}
return hashCode * 31 + iLen;
} } |
public class class_name {
public String generateFilename(IScope scope, String name, String extension, GenerationType type) {
String result = getStreamDirectory(scope) + name;
if (extension != null && !extension.equals("")) {
result += extension;
}
return result;
} } | public class class_name {
public String generateFilename(IScope scope, String name, String extension, GenerationType type) {
String result = getStreamDirectory(scope) + name;
if (extension != null && !extension.equals("")) {
result += extension;
// depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
private static int asInteger(final long[] data, final int n) {
int t;
int cnt = 0;
long seed = 0;
if (n < 2) {
throw new SketchesArgumentException("Given value of n must be > 1.");
}
if (n > (1 << 30)) {
while (++cnt < 10000) {
final long[] h = MurmurHash3.hash(data, seed);
t = (int) (h[0] & INT_MASK);
if (t < n) {
return t;
}
t = (int) ((h[0] >>> 33));
if (t < n) {
return t;
}
t = (int) (h[1] & INT_MASK);
if (t < n) {
return t;
}
t = (int) ((h[1] >>> 33));
if (t < n) {
return t;
}
seed += PRIME;
} // end while
throw new SketchesStateException(
"Internal Error: Failed to find integer < n within 10000 iterations.");
}
final long mask = ceilingPowerOf2(n) - 1;
while (++cnt < 10000) {
final long[] h = MurmurHash3.hash(data, seed);
t = (int) (h[0] & mask);
if (t < n) {
return t;
}
t = (int) ((h[0] >>> 33) & mask);
if (t < n) {
return t;
}
t = (int) (h[1] & mask);
if (t < n) {
return t;
}
t = (int) ((h[1] >>> 33) & mask);
if (t < n) {
return t;
}
seed += PRIME;
} // end while
throw new SketchesStateException(
"Internal Error: Failed to find integer < n within 10000 iterations.");
} } | public class class_name {
private static int asInteger(final long[] data, final int n) {
int t;
int cnt = 0;
long seed = 0;
if (n < 2) {
throw new SketchesArgumentException("Given value of n must be > 1.");
}
if (n > (1 << 30)) {
while (++cnt < 10000) {
final long[] h = MurmurHash3.hash(data, seed);
t = (int) (h[0] & INT_MASK); // depends on control dependency: [while], data = [none]
if (t < n) {
return t; // depends on control dependency: [if], data = [none]
}
t = (int) ((h[0] >>> 33)); // depends on control dependency: [while], data = [none]
if (t < n) {
return t; // depends on control dependency: [if], data = [none]
}
t = (int) (h[1] & INT_MASK); // depends on control dependency: [while], data = [none]
if (t < n) {
return t; // depends on control dependency: [if], data = [none]
}
t = (int) ((h[1] >>> 33)); // depends on control dependency: [while], data = [none]
if (t < n) {
return t; // depends on control dependency: [if], data = [none]
}
seed += PRIME; // depends on control dependency: [while], data = [none]
} // end while
throw new SketchesStateException(
"Internal Error: Failed to find integer < n within 10000 iterations.");
}
final long mask = ceilingPowerOf2(n) - 1;
while (++cnt < 10000) {
final long[] h = MurmurHash3.hash(data, seed);
t = (int) (h[0] & mask); // depends on control dependency: [while], data = [none]
if (t < n) {
return t; // depends on control dependency: [if], data = [none]
}
t = (int) ((h[0] >>> 33) & mask); // depends on control dependency: [while], data = [none]
if (t < n) {
return t; // depends on control dependency: [if], data = [none]
}
t = (int) (h[1] & mask); // depends on control dependency: [while], data = [none]
if (t < n) {
return t; // depends on control dependency: [if], data = [none]
}
t = (int) ((h[1] >>> 33) & mask); // depends on control dependency: [while], data = [none]
if (t < n) {
return t; // depends on control dependency: [if], data = [none]
}
seed += PRIME; // depends on control dependency: [while], data = [none]
} // end while
throw new SketchesStateException(
"Internal Error: Failed to find integer < n within 10000 iterations.");
} } |
public class class_name {
protected double [] getBestSecondBestEntropy(DoubleVector entropy){
double[] entropyValues = new double[2];
double best = Double.MAX_VALUE;
double secondBest = Double.MAX_VALUE;
for (int i = 0; i < entropy.numValues(); i++) {
if (entropy.getValue(i) < best) {
secondBest = best;
best = entropy.getValue(i);
} else{
if (entropy.getValue(i) < secondBest) {
secondBest = entropy.getValue(i);
}
}
}
entropyValues[0] = best;
entropyValues[1] = secondBest;
return entropyValues;
} } | public class class_name {
protected double [] getBestSecondBestEntropy(DoubleVector entropy){
double[] entropyValues = new double[2];
double best = Double.MAX_VALUE;
double secondBest = Double.MAX_VALUE;
for (int i = 0; i < entropy.numValues(); i++) {
if (entropy.getValue(i) < best) {
secondBest = best; // depends on control dependency: [if], data = [none]
best = entropy.getValue(i); // depends on control dependency: [if], data = [none]
} else{
if (entropy.getValue(i) < secondBest) {
secondBest = entropy.getValue(i); // depends on control dependency: [if], data = [none]
}
}
}
entropyValues[0] = best;
entropyValues[1] = secondBest;
return entropyValues;
} } |
public class class_name {
@Override
public boolean retainAll(IntSet c) {
if (c == null || c.isEmpty())
return false;
IntIterator itr = iterator();
boolean res = false;
while (itr.hasNext()) {
int e = itr.next();
if (!c.contains(e)) {
res = true;
itr.remove();
}
}
return res;
} } | public class class_name {
@Override
public boolean retainAll(IntSet c) {
if (c == null || c.isEmpty())
return false;
IntIterator itr = iterator();
boolean res = false;
while (itr.hasNext()) {
int e = itr.next();
if (!c.contains(e)) {
res = true;
// depends on control dependency: [if], data = [none]
itr.remove();
// depends on control dependency: [if], data = [none]
}
}
return res;
} } |
public class class_name {
public final Mono<T> log(Logger logger,
Level level,
boolean showOperatorLine,
SignalType... options) {
SignalLogger<T> log = new SignalLogger<>(this, "IGNORED", level,
showOperatorLine,
s -> logger,
options);
if (this instanceof Fuseable) {
return onAssembly(new MonoLogFuseable<>(this, log));
}
return onAssembly(new MonoLog<>(this, log));
} } | public class class_name {
public final Mono<T> log(Logger logger,
Level level,
boolean showOperatorLine,
SignalType... options) {
SignalLogger<T> log = new SignalLogger<>(this, "IGNORED", level,
showOperatorLine,
s -> logger,
options);
if (this instanceof Fuseable) {
return onAssembly(new MonoLogFuseable<>(this, log)); // depends on control dependency: [if], data = [none]
}
return onAssembly(new MonoLog<>(this, log));
} } |
public class class_name {
@Override
public void visitClassContext(ClassContext classContext) {
try {
stack = new OpcodeStack();
localMethodCalls = new HashMap<>();
fieldMethodCalls = new HashMap<>();
staticMethodCalls = new HashMap<>();
branchTargets = new BitSet();
super.visitClassContext(classContext);
} finally {
stack = null;
localMethodCalls = null;
fieldMethodCalls = null;
staticMethodCalls = null;
branchTargets = null;
}
} } | public class class_name {
@Override
public void visitClassContext(ClassContext classContext) {
try {
stack = new OpcodeStack(); // depends on control dependency: [try], data = [none]
localMethodCalls = new HashMap<>(); // depends on control dependency: [try], data = [none]
fieldMethodCalls = new HashMap<>(); // depends on control dependency: [try], data = [none]
staticMethodCalls = new HashMap<>(); // depends on control dependency: [try], data = [none]
branchTargets = new BitSet(); // depends on control dependency: [try], data = [none]
super.visitClassContext(classContext); // depends on control dependency: [try], data = [none]
} finally {
stack = null;
localMethodCalls = null;
fieldMethodCalls = null;
staticMethodCalls = null;
branchTargets = null;
}
} } |
public class class_name {
public Marshaller createMarshaller(String encoding) {
try {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
}
return marshaller;
} catch (JAXBException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public Marshaller createMarshaller(String encoding) {
try {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // depends on control dependency: [try], data = [none]
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); // depends on control dependency: [if], data = [none]
}
return marshaller; // depends on control dependency: [try], data = [none]
} catch (JAXBException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static base_responses add(nitro_service client, vpnintranetapplication resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
vpnintranetapplication addresources[] = new vpnintranetapplication[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new vpnintranetapplication();
addresources[i].intranetapplication = resources[i].intranetapplication;
addresources[i].protocol = resources[i].protocol;
addresources[i].destip = resources[i].destip;
addresources[i].netmask = resources[i].netmask;
addresources[i].iprange = resources[i].iprange;
addresources[i].hostname = resources[i].hostname;
addresources[i].clientapplication = resources[i].clientapplication;
addresources[i].spoofiip = resources[i].spoofiip;
addresources[i].destport = resources[i].destport;
addresources[i].interception = resources[i].interception;
addresources[i].srcip = resources[i].srcip;
addresources[i].srcport = resources[i].srcport;
}
result = add_bulk_request(client, addresources);
}
return result;
} } | public class class_name {
public static base_responses add(nitro_service client, vpnintranetapplication resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
vpnintranetapplication addresources[] = new vpnintranetapplication[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new vpnintranetapplication(); // depends on control dependency: [for], data = [i]
addresources[i].intranetapplication = resources[i].intranetapplication; // depends on control dependency: [for], data = [i]
addresources[i].protocol = resources[i].protocol; // depends on control dependency: [for], data = [i]
addresources[i].destip = resources[i].destip; // depends on control dependency: [for], data = [i]
addresources[i].netmask = resources[i].netmask; // depends on control dependency: [for], data = [i]
addresources[i].iprange = resources[i].iprange; // depends on control dependency: [for], data = [i]
addresources[i].hostname = resources[i].hostname; // depends on control dependency: [for], data = [i]
addresources[i].clientapplication = resources[i].clientapplication; // depends on control dependency: [for], data = [i]
addresources[i].spoofiip = resources[i].spoofiip; // depends on control dependency: [for], data = [i]
addresources[i].destport = resources[i].destport; // depends on control dependency: [for], data = [i]
addresources[i].interception = resources[i].interception; // depends on control dependency: [for], data = [i]
addresources[i].srcip = resources[i].srcip; // depends on control dependency: [for], data = [i]
addresources[i].srcport = resources[i].srcport; // depends on control dependency: [for], data = [i]
}
result = add_bulk_request(client, addresources);
}
return result;
} } |
public class class_name {
@Override
protected void consume() {
E obj = null;
try {
obj = queue.take();
} catch (InterruptedException e) {
//thread.isInterrupted();
return;
}
process(obj);
} } | public class class_name {
@Override
protected void consume() {
E obj = null;
try {
obj = queue.take();
// depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
//thread.isInterrupted();
return;
}
// depends on control dependency: [catch], data = [none]
process(obj);
} } |
public class class_name {
public void setMaxIndexWaitTime(String maxIndexWaitTime) {
try {
setMaxIndexWaitTime(Long.parseLong(maxIndexWaitTime));
} catch (Exception e) {
LOG.error(
Messages.get().getBundle().key(
Messages.LOG_PARSE_MAX_INDEX_WAITTIME_FAILED_2,
maxIndexWaitTime,
new Long(DEFAULT_MAX_INDEX_WAITTIME)),
e);
setMaxIndexWaitTime(DEFAULT_MAX_INDEX_WAITTIME);
}
} } | public class class_name {
public void setMaxIndexWaitTime(String maxIndexWaitTime) {
try {
setMaxIndexWaitTime(Long.parseLong(maxIndexWaitTime)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOG.error(
Messages.get().getBundle().key(
Messages.LOG_PARSE_MAX_INDEX_WAITTIME_FAILED_2,
maxIndexWaitTime,
new Long(DEFAULT_MAX_INDEX_WAITTIME)),
e);
setMaxIndexWaitTime(DEFAULT_MAX_INDEX_WAITTIME);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private TaskType getTaskType(String value)
{
TaskType result = TaskType.FIXED_UNITS;
if (value != null && value.equals("fixed-duration"))
{
result = TaskType.FIXED_DURATION;
}
return (result);
} } | public class class_name {
private TaskType getTaskType(String value)
{
TaskType result = TaskType.FIXED_UNITS;
if (value != null && value.equals("fixed-duration"))
{
result = TaskType.FIXED_DURATION; // depends on control dependency: [if], data = [none]
}
return (result);
} } |
public class class_name {
public static Nature getNature(String natureStr) {
Nature nature = NATUREMAP.get(natureStr);
if (nature == null) {
nature = new Nature(natureStr, FYI, FYI, YI);
NATUREMAP.put(natureStr, nature);
return nature;
}
return nature;
} } | public class class_name {
public static Nature getNature(String natureStr) {
Nature nature = NATUREMAP.get(natureStr);
if (nature == null) {
nature = new Nature(natureStr, FYI, FYI, YI); // depends on control dependency: [if], data = [(nature]
NATUREMAP.put(natureStr, nature); // depends on control dependency: [if], data = [(nature]
return nature; // depends on control dependency: [if], data = [none]
}
return nature;
} } |
public class class_name {
private String getDefaultBrowserAgent(Context context) {
String userAgent = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
try {
userAgent = WebSettings.getDefaultUserAgent(context);
} catch (Exception ignore) {
// A known Android issue. Webview packages are not accessible while any updates for chrome is in progress.
// https://bugs.chromium.org/p/chromium/issues/detail?id=506369
}
}
return userAgent;
} } | public class class_name {
private String getDefaultBrowserAgent(Context context) {
String userAgent = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
try {
userAgent = WebSettings.getDefaultUserAgent(context); // depends on control dependency: [try], data = [none]
} catch (Exception ignore) {
// A known Android issue. Webview packages are not accessible while any updates for chrome is in progress.
// https://bugs.chromium.org/p/chromium/issues/detail?id=506369
} // depends on control dependency: [catch], data = [none]
}
return userAgent;
} } |
public class class_name {
public static void removeNodesByTagName(Element doc, String tagname) {
NodeList nodes = doc.getElementsByTagName(tagname);
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
doc.removeChild(n);
}
} } | public class class_name {
public static void removeNodesByTagName(Element doc, String tagname) {
NodeList nodes = doc.getElementsByTagName(tagname);
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
doc.removeChild(n); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public static String getSchemePrefix(String spec) {
int colon = spec.indexOf(':');
if (colon < 1) {
return null;
}
for (int i = 0; i < colon; i++) {
char c = spec.charAt(i);
if (!isValidSchemeChar(i, c)) {
return null;
}
}
return spec.substring(0, colon).toLowerCase(Locale.US);
} } | public class class_name {
public static String getSchemePrefix(String spec) {
int colon = spec.indexOf(':');
if (colon < 1) {
return null; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < colon; i++) {
char c = spec.charAt(i);
if (!isValidSchemeChar(i, c)) {
return null; // depends on control dependency: [if], data = [none]
}
}
return spec.substring(0, colon).toLowerCase(Locale.US);
} } |
public class class_name {
public MethodDelegationBinder.Record compile(MethodDescription candidate) {
if (IgnoreForBinding.Verifier.check(candidate)) {
return MethodDelegationBinder.Record.Illegal.INSTANCE;
}
List<DelegationProcessor.Handler> handlers = new ArrayList<DelegationProcessor.Handler>(candidate.getParameters().size());
for (ParameterDescription parameterDescription : candidate.getParameters()) {
handlers.add(delegationProcessor.prepare(parameterDescription));
}
return new Record(candidate, handlers, RuntimeType.Verifier.check(candidate));
} } | public class class_name {
public MethodDelegationBinder.Record compile(MethodDescription candidate) {
if (IgnoreForBinding.Verifier.check(candidate)) {
return MethodDelegationBinder.Record.Illegal.INSTANCE; // depends on control dependency: [if], data = [none]
}
List<DelegationProcessor.Handler> handlers = new ArrayList<DelegationProcessor.Handler>(candidate.getParameters().size());
for (ParameterDescription parameterDescription : candidate.getParameters()) {
handlers.add(delegationProcessor.prepare(parameterDescription)); // depends on control dependency: [for], data = [parameterDescription]
}
return new Record(candidate, handlers, RuntimeType.Verifier.check(candidate));
} } |
public class class_name {
private IAtom[] getBridgeAtoms(IAtomContainer sharedAtoms) {
IAtom[] bridgeAtoms = new IAtom[2];
IAtom atom;
int counter = 0;
for (int f = 0; f < sharedAtoms.getAtomCount(); f++) {
atom = sharedAtoms.getAtom(f);
if (sharedAtoms.getConnectedAtomsList(atom).size() == 1) {
bridgeAtoms[counter] = atom;
counter++;
}
}
return bridgeAtoms;
} } | public class class_name {
private IAtom[] getBridgeAtoms(IAtomContainer sharedAtoms) {
IAtom[] bridgeAtoms = new IAtom[2];
IAtom atom;
int counter = 0;
for (int f = 0; f < sharedAtoms.getAtomCount(); f++) {
atom = sharedAtoms.getAtom(f); // depends on control dependency: [for], data = [f]
if (sharedAtoms.getConnectedAtomsList(atom).size() == 1) {
bridgeAtoms[counter] = atom; // depends on control dependency: [if], data = [none]
counter++; // depends on control dependency: [if], data = [none]
}
}
return bridgeAtoms;
} } |
public class class_name {
private void doListGet(final Message<JsonObject> message) {
final String name = message.body().getString("name");
if (name == null) {
message.reply(new JsonObject().putString("status", "error").putString("message", "No name specified."));
return;
}
final Integer index = message.body().getInteger("index");
if (index == null) {
message.reply(new JsonObject().putString("status", "error").putString("message", "No index specified."));
return;
}
context.execute(new Action<Object>() {
@Override
public Object perform() {
return data.getList(formatKey(name)).get(index);
}
}, new Handler<AsyncResult<Object>>() {
@Override
public void handle(AsyncResult<Object> result) {
if (result.failed()) {
message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
} else {
message.reply(new JsonObject().putString("status", "ok").putValue("result", result.result()));
}
}
});
} } | public class class_name {
private void doListGet(final Message<JsonObject> message) {
final String name = message.body().getString("name");
if (name == null) {
message.reply(new JsonObject().putString("status", "error").putString("message", "No name specified.")); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final Integer index = message.body().getInteger("index");
if (index == null) {
message.reply(new JsonObject().putString("status", "error").putString("message", "No index specified.")); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
context.execute(new Action<Object>() {
@Override
public Object perform() {
return data.getList(formatKey(name)).get(index);
}
}, new Handler<AsyncResult<Object>>() {
@Override
public void handle(AsyncResult<Object> result) {
if (result.failed()) {
message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage())); // depends on control dependency: [if], data = [none]
} else {
message.reply(new JsonObject().putString("status", "ok").putValue("result", result.result())); // depends on control dependency: [if], data = [none]
}
}
});
} } |
public class class_name {
private String findErrorPage(Throwable exception) {
if (exception instanceof EJBException && exception.getCause() != null) {
exception = exception.getCause();
}
String errorPage = WebXml.INSTANCE.findErrorPageLocation(exception);
return errorPage;
} } | public class class_name {
private String findErrorPage(Throwable exception) {
if (exception instanceof EJBException && exception.getCause() != null) {
exception = exception.getCause(); // depends on control dependency: [if], data = [none]
}
String errorPage = WebXml.INSTANCE.findErrorPageLocation(exception);
return errorPage;
} } |
public class class_name {
public static Iterator<ImageReader> getImageReadersBySuffix(String fileSuffix) {
if (fileSuffix == null) {
throw new IllegalArgumentException("fileSuffix == null!");
}
// Ensure category is present
Iterator iter;
try {
iter = theRegistry.getServiceProviders(ImageReaderSpi.class, new ContainsFilter(readerFileSuffixesMethod, fileSuffix), true);
} catch (IllegalArgumentException e) {
return new HashSet().iterator();
}
return new ImageReaderIterator(iter);
} } | public class class_name {
public static Iterator<ImageReader> getImageReadersBySuffix(String fileSuffix) {
if (fileSuffix == null) {
throw new IllegalArgumentException("fileSuffix == null!");
}
// Ensure category is present
Iterator iter;
try {
iter = theRegistry.getServiceProviders(ImageReaderSpi.class, new ContainsFilter(readerFileSuffixesMethod, fileSuffix), true);
// depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
return new HashSet().iterator();
}
// depends on control dependency: [catch], data = [none]
return new ImageReaderIterator(iter);
} } |
public class class_name {
public static GrayU16 average( InterleavedU16 input , GrayU16 output ) {
if (output == null) {
output = new GrayU16(input.width, input.height);
} else {
output.reshape(input.width,input.height);
}
if( BoofConcurrency.USE_CONCURRENT ) {
ConvertInterleavedToSingle_MT.average(input,output);
} else {
ConvertInterleavedToSingle.average(input,output);
}
return output;
} } | public class class_name {
public static GrayU16 average( InterleavedU16 input , GrayU16 output ) {
if (output == null) {
output = new GrayU16(input.width, input.height); // depends on control dependency: [if], data = [none]
} else {
output.reshape(input.width,input.height); // depends on control dependency: [if], data = [none]
}
if( BoofConcurrency.USE_CONCURRENT ) {
ConvertInterleavedToSingle_MT.average(input,output); // depends on control dependency: [if], data = [none]
} else {
ConvertInterleavedToSingle.average(input,output); // depends on control dependency: [if], data = [none]
}
return output;
} } |
public class class_name {
@Override
public long
totalSize()
{
long size = 1;
for(int i = 0; i < this.rank; i++) {
size *= slice(i).getCount();
}
return size;
} } | public class class_name {
@Override
public long
totalSize()
{
long size = 1;
for(int i = 0; i < this.rank; i++) {
size *= slice(i).getCount(); // depends on control dependency: [for], data = [i]
}
return size;
} } |
public class class_name {
private void updateMember(GossipMember remoteMember, boolean direct) {
GossipMember localMember = members.get(remoteMember.id());
if (localMember == null) {
remoteMember.setActive(true);
remoteMember.setReachable(true);
members.put(remoteMember.id(), remoteMember);
post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_ADDED, remoteMember));
} else if (!Objects.equals(localMember.version(), remoteMember.version())) {
members.remove(localMember.id());
localMember.setReachable(false);
post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember));
localMember.setActive(false);
post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_REMOVED, localMember));
members.put(remoteMember.id(), remoteMember);
remoteMember.setActive(true);
remoteMember.setReachable(true);
post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_ADDED, remoteMember));
} else if (!Objects.equals(localMember.properties(), remoteMember.properties())) {
if (!localMember.isReachable()) {
localMember.setReachable(true);
post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember));
}
localMember.properties().putAll(remoteMember.properties());
post(new GroupMembershipEvent(GroupMembershipEvent.Type.METADATA_CHANGED, localMember));
} else if (!localMember.isReachable() && direct) {
localMember.setReachable(true);
localMember.setTerm(localMember.getTerm() + 1);
post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember));
} else if (!localMember.isReachable() && remoteMember.getTerm() > localMember.getTerm()) {
localMember.setReachable(true);
localMember.setTerm(remoteMember.getTerm());
post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember));
}
} } | public class class_name {
private void updateMember(GossipMember remoteMember, boolean direct) {
GossipMember localMember = members.get(remoteMember.id());
if (localMember == null) {
remoteMember.setActive(true); // depends on control dependency: [if], data = [none]
remoteMember.setReachable(true); // depends on control dependency: [if], data = [none]
members.put(remoteMember.id(), remoteMember); // depends on control dependency: [if], data = [none]
post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_ADDED, remoteMember)); // depends on control dependency: [if], data = [none]
} else if (!Objects.equals(localMember.version(), remoteMember.version())) {
members.remove(localMember.id()); // depends on control dependency: [if], data = [none]
localMember.setReachable(false); // depends on control dependency: [if], data = [none]
post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); // depends on control dependency: [if], data = [none]
localMember.setActive(false); // depends on control dependency: [if], data = [none]
post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_REMOVED, localMember)); // depends on control dependency: [if], data = [none]
members.put(remoteMember.id(), remoteMember); // depends on control dependency: [if], data = [none]
remoteMember.setActive(true); // depends on control dependency: [if], data = [none]
remoteMember.setReachable(true); // depends on control dependency: [if], data = [none]
post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_ADDED, remoteMember)); // depends on control dependency: [if], data = [none]
} else if (!Objects.equals(localMember.properties(), remoteMember.properties())) {
if (!localMember.isReachable()) {
localMember.setReachable(true); // depends on control dependency: [if], data = [none]
post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); // depends on control dependency: [if], data = [none]
}
localMember.properties().putAll(remoteMember.properties()); // depends on control dependency: [if], data = [none]
post(new GroupMembershipEvent(GroupMembershipEvent.Type.METADATA_CHANGED, localMember)); // depends on control dependency: [if], data = [none]
} else if (!localMember.isReachable() && direct) {
localMember.setReachable(true); // depends on control dependency: [if], data = [none]
localMember.setTerm(localMember.getTerm() + 1); // depends on control dependency: [if], data = [none]
post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); // depends on control dependency: [if], data = [none]
} else if (!localMember.isReachable() && remoteMember.getTerm() > localMember.getTerm()) {
localMember.setReachable(true); // depends on control dependency: [if], data = [none]
localMember.setTerm(remoteMember.getTerm()); // depends on control dependency: [if], data = [none]
post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static List<String> getDateRangeSpan(long startDate, long endDate) {
if (startDate > endDate) {
// switch so that the end is always before the start
long temp = endDate;
endDate = startDate;
startDate = temp;
}
List<String> result = new ArrayList<String>(100);
// initialize calendars from the time value
Calendar calStart = Calendar.getInstance(OpenCms.getLocaleManager().getTimeZone());
Calendar calEnd = Calendar.getInstance(calStart.getTimeZone());
calStart.setTimeInMillis(startDate);
calEnd.setTimeInMillis(endDate);
// get the required info to build the date range from the calendars
int startDay = calStart.get(Calendar.DAY_OF_MONTH);
int endDay = calEnd.get(Calendar.DAY_OF_MONTH);
int maxDayInStartMonth = calStart.getActualMaximum(Calendar.DAY_OF_MONTH);
int startMonth = calStart.get(Calendar.MONTH) + 1;
int endMonth = calEnd.get(Calendar.MONTH) + 1;
int startYear = calStart.get(Calendar.YEAR);
int endYear = calEnd.get(Calendar.YEAR);
// first add all full years in the date range
result.addAll(getYearSpan(startYear + 1, endYear - 1));
if (startYear != endYear) {
// different year, different month
result.addAll(getMonthSpan(startMonth + 1, 12, startYear));
result.addAll(getMonthSpan(1, endMonth - 1, endYear));
result.addAll(getDaySpan(startDay, maxDayInStartMonth, startMonth, startYear));
result.addAll(getDaySpan(1, endDay, endMonth, endYear));
} else {
if (startMonth != endMonth) {
// same year, different month
result.addAll(getMonthSpan(startMonth + 1, endMonth - 1, startYear));
result.addAll(getDaySpan(startDay, maxDayInStartMonth, startMonth, startYear));
result.addAll(getDaySpan(1, endDay, endMonth, endYear));
} else {
// same year, same month
result.addAll(getDaySpan(startDay, endDay, endMonth, endYear));
}
}
// sort the result, makes the range better readable in the debugger
Collections.sort(result);
return result;
} } | public class class_name {
public static List<String> getDateRangeSpan(long startDate, long endDate) {
if (startDate > endDate) {
// switch so that the end is always before the start
long temp = endDate;
endDate = startDate; // depends on control dependency: [if], data = [none]
startDate = temp; // depends on control dependency: [if], data = [none]
}
List<String> result = new ArrayList<String>(100);
// initialize calendars from the time value
Calendar calStart = Calendar.getInstance(OpenCms.getLocaleManager().getTimeZone());
Calendar calEnd = Calendar.getInstance(calStart.getTimeZone());
calStart.setTimeInMillis(startDate);
calEnd.setTimeInMillis(endDate);
// get the required info to build the date range from the calendars
int startDay = calStart.get(Calendar.DAY_OF_MONTH);
int endDay = calEnd.get(Calendar.DAY_OF_MONTH);
int maxDayInStartMonth = calStart.getActualMaximum(Calendar.DAY_OF_MONTH);
int startMonth = calStart.get(Calendar.MONTH) + 1;
int endMonth = calEnd.get(Calendar.MONTH) + 1;
int startYear = calStart.get(Calendar.YEAR);
int endYear = calEnd.get(Calendar.YEAR);
// first add all full years in the date range
result.addAll(getYearSpan(startYear + 1, endYear - 1));
if (startYear != endYear) {
// different year, different month
result.addAll(getMonthSpan(startMonth + 1, 12, startYear)); // depends on control dependency: [if], data = [none]
result.addAll(getMonthSpan(1, endMonth - 1, endYear)); // depends on control dependency: [if], data = [endYear)]
result.addAll(getDaySpan(startDay, maxDayInStartMonth, startMonth, startYear)); // depends on control dependency: [if], data = [none]
result.addAll(getDaySpan(1, endDay, endMonth, endYear)); // depends on control dependency: [if], data = [endYear)]
} else {
if (startMonth != endMonth) {
// same year, different month
result.addAll(getMonthSpan(startMonth + 1, endMonth - 1, startYear)); // depends on control dependency: [if], data = [(startMonth]
result.addAll(getDaySpan(startDay, maxDayInStartMonth, startMonth, startYear)); // depends on control dependency: [if], data = [none]
result.addAll(getDaySpan(1, endDay, endMonth, endYear)); // depends on control dependency: [if], data = [none]
} else {
// same year, same month
result.addAll(getDaySpan(startDay, endDay, endMonth, endYear)); // depends on control dependency: [if], data = [none]
}
}
// sort the result, makes the range better readable in the debugger
Collections.sort(result);
return result;
} } |
public class class_name {
public List<T> getChildChoices()
{
final List<T> childChoices = getModelsMap().get(getSelectedRootOption());
if (CollectionExtensions.isEmpty(childChoices))
{
return Collections.emptyList();
}
return childChoices;
} } | public class class_name {
public List<T> getChildChoices()
{
final List<T> childChoices = getModelsMap().get(getSelectedRootOption());
if (CollectionExtensions.isEmpty(childChoices))
{
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
return childChoices;
} } |
public class class_name {
private static String truncateOffsetPattern(String offsetHM) {
int idx_mm = offsetHM.indexOf("mm");
if (idx_mm < 0) {
throw new RuntimeException("Bad time zone hour pattern data");
}
int idx_HH = offsetHM.substring(0, idx_mm).lastIndexOf("HH");
if (idx_HH >= 0) {
return offsetHM.substring(0, idx_HH + 2);
}
int idx_H = offsetHM.substring(0, idx_mm).lastIndexOf("H");
if (idx_H >= 0) {
return offsetHM.substring(0, idx_H + 1);
}
throw new RuntimeException("Bad time zone hour pattern data");
} } | public class class_name {
private static String truncateOffsetPattern(String offsetHM) {
int idx_mm = offsetHM.indexOf("mm");
if (idx_mm < 0) {
throw new RuntimeException("Bad time zone hour pattern data");
}
int idx_HH = offsetHM.substring(0, idx_mm).lastIndexOf("HH");
if (idx_HH >= 0) {
return offsetHM.substring(0, idx_HH + 2); // depends on control dependency: [if], data = [none]
}
int idx_H = offsetHM.substring(0, idx_mm).lastIndexOf("H");
if (idx_H >= 0) {
return offsetHM.substring(0, idx_H + 1); // depends on control dependency: [if], data = [none]
}
throw new RuntimeException("Bad time zone hour pattern data");
} } |
public class class_name {
private String getType(String propertyName, String explicitTargetEntity, ElementKind expectedElementKind) {
for ( Element elem : element.getEnclosedElements() ) {
if ( !expectedElementKind.equals( elem.getKind() ) ) {
continue;
}
TypeMirror mirror;
String name = elem.getSimpleName().toString();
if ( ElementKind.METHOD.equals( elem.getKind() ) ) {
name = StringUtil.getPropertyName( name );
mirror = ( (ExecutableElement) elem ).getReturnType();
}
else {
mirror = elem.asType();
}
if ( name == null || !name.equals( propertyName ) ) {
continue;
}
if ( explicitTargetEntity != null ) {
// TODO should there be a check of the target entity class and if it is loadable?
return explicitTargetEntity;
}
switch ( mirror.getKind() ) {
case INT: {
return "java.lang.Integer";
}
case LONG: {
return "java.lang.Long";
}
case BOOLEAN: {
return "java.lang.Boolean";
}
case BYTE: {
return "java.lang.Byte";
}
case SHORT: {
return "java.lang.Short";
}
case CHAR: {
return "java.lang.Char";
}
case FLOAT: {
return "java.lang.Float";
}
case DOUBLE: {
return "java.lang.Double";
}
case DECLARED: {
return mirror.toString();
}
case TYPEVAR: {
return mirror.toString();
}
default: {
}
}
}
context.logMessage(
Diagnostic.Kind.WARNING,
"Unable to determine type for property " + propertyName + " of class " + getQualifiedName()
+ " using access type " + accessTypeInfo.getDefaultAccessType()
);
return null;
} } | public class class_name {
private String getType(String propertyName, String explicitTargetEntity, ElementKind expectedElementKind) {
for ( Element elem : element.getEnclosedElements() ) {
if ( !expectedElementKind.equals( elem.getKind() ) ) {
continue;
}
TypeMirror mirror;
String name = elem.getSimpleName().toString();
if ( ElementKind.METHOD.equals( elem.getKind() ) ) {
name = StringUtil.getPropertyName( name ); // depends on control dependency: [if], data = [none]
mirror = ( (ExecutableElement) elem ).getReturnType(); // depends on control dependency: [if], data = [none]
}
else {
mirror = elem.asType(); // depends on control dependency: [if], data = [none]
}
if ( name == null || !name.equals( propertyName ) ) {
continue;
}
if ( explicitTargetEntity != null ) {
// TODO should there be a check of the target entity class and if it is loadable?
return explicitTargetEntity; // depends on control dependency: [if], data = [none]
}
switch ( mirror.getKind() ) {
case INT: {
return "java.lang.Integer"; // depends on control dependency: [for], data = [none]
}
case LONG: {
return "java.lang.Long";
}
case BOOLEAN: {
return "java.lang.Boolean";
}
case BYTE: {
return "java.lang.Byte";
}
case SHORT: {
return "java.lang.Short";
}
case CHAR: {
return "java.lang.Char";
}
case FLOAT: {
return "java.lang.Float";
}
case DOUBLE: {
return "java.lang.Double";
}
case DECLARED: {
return mirror.toString();
}
case TYPEVAR: {
return mirror.toString();
}
default: {
}
}
}
context.logMessage(
Diagnostic.Kind.WARNING,
"Unable to determine type for property " + propertyName + " of class " + getQualifiedName()
+ " using access type " + accessTypeInfo.getDefaultAccessType()
);
return null;
} } |
public class class_name {
String ensureFoldername(String resourcename) {
if (CmsStringUtil.isEmpty(resourcename)) {
return "";
}
if (!CmsResource.isFolder(resourcename)) {
resourcename = resourcename.concat("/");
}
if (resourcename.charAt(0) == '/') {
resourcename = resourcename.substring(1);
}
return resourcename;
} } | public class class_name {
String ensureFoldername(String resourcename) {
if (CmsStringUtil.isEmpty(resourcename)) {
return ""; // depends on control dependency: [if], data = [none]
}
if (!CmsResource.isFolder(resourcename)) {
resourcename = resourcename.concat("/"); // depends on control dependency: [if], data = [none]
}
if (resourcename.charAt(0) == '/') {
resourcename = resourcename.substring(1); // depends on control dependency: [if], data = [none]
}
return resourcename;
} } |
public class class_name {
public String getSelectedEditorUri() {
// get the handler class from the OpenCms runtime property
I_CmsEditorHandler editorClass = OpenCms.getWorkplaceManager().getEditorHandler();
// the resourcenameparameter could be encoded, so decode it
String resource = getParamResource();
resource = CmsEncoder.unescape(resource, CmsEncoder.ENCODING_UTF_8);
if (editorClass == null) {
// error getting the dialog class, return to file list
return CmsWorkplace.FILE_EXPLORER_FILELIST;
}
// get the dialog URI from the class defined in the configuration
String editorUri = null;
try {
editorUri = editorClass.getEditorUri(resource, getJsp());
if (editorUri == null) {
// no valid editor was found, show the error dialog
throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_NO_EDITOR_FOUND_0));
}
} catch (CmsException e) {
showErrorDialog(getJsp(), e);
}
return editorUri;
} } | public class class_name {
public String getSelectedEditorUri() {
// get the handler class from the OpenCms runtime property
I_CmsEditorHandler editorClass = OpenCms.getWorkplaceManager().getEditorHandler();
// the resourcenameparameter could be encoded, so decode it
String resource = getParamResource();
resource = CmsEncoder.unescape(resource, CmsEncoder.ENCODING_UTF_8);
if (editorClass == null) {
// error getting the dialog class, return to file list
return CmsWorkplace.FILE_EXPLORER_FILELIST; // depends on control dependency: [if], data = [none]
}
// get the dialog URI from the class defined in the configuration
String editorUri = null;
try {
editorUri = editorClass.getEditorUri(resource, getJsp()); // depends on control dependency: [try], data = [none]
if (editorUri == null) {
// no valid editor was found, show the error dialog
throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_NO_EDITOR_FOUND_0));
}
} catch (CmsException e) {
showErrorDialog(getJsp(), e);
} // depends on control dependency: [catch], data = [none]
return editorUri;
} } |
public class class_name {
public Map<String, Object> getPersistentAttributes() {
Request request = requestEnvelope.getRequest();
if (persistenceAdapter == null) {
throw new IllegalStateException("Attempting to read persistence attributes without configured persistence adapter");
}
if (!persistenceAttributesSet) {
Optional<Map<String, Object>> retrievedAttributes = persistenceAdapter.getAttributes(requestEnvelope);
if (retrievedAttributes.isPresent()) {
logger.debug("[{}] Found existing persistence attributes", request.getRequestId());
persistentAttributes = retrievedAttributes.get();
} else {
logger.debug("[{}] No existing persistence attributes", request.getRequestId());
persistentAttributes = new HashMap<>();
}
persistenceAttributesSet = true;
}
return persistentAttributes;
} } | public class class_name {
public Map<String, Object> getPersistentAttributes() {
Request request = requestEnvelope.getRequest();
if (persistenceAdapter == null) {
throw new IllegalStateException("Attempting to read persistence attributes without configured persistence adapter");
}
if (!persistenceAttributesSet) {
Optional<Map<String, Object>> retrievedAttributes = persistenceAdapter.getAttributes(requestEnvelope);
if (retrievedAttributes.isPresent()) {
logger.debug("[{}] Found existing persistence attributes", request.getRequestId()); // depends on control dependency: [if], data = [none]
persistentAttributes = retrievedAttributes.get(); // depends on control dependency: [if], data = [none]
} else {
logger.debug("[{}] No existing persistence attributes", request.getRequestId()); // depends on control dependency: [if], data = [none]
persistentAttributes = new HashMap<>(); // depends on control dependency: [if], data = [none]
}
persistenceAttributesSet = true; // depends on control dependency: [if], data = [none]
}
return persistentAttributes;
} } |
public class class_name {
private void createShape() {
if (shape == null) {
float firstItemMargin = noxConfig.getNoxItemMargin();
float firstItemSize = noxConfig.getNoxItemSize();
int viewHeight = getMeasuredHeight();
int viewWidth = getMeasuredWidth();
int numberOfElements = noxItemCatalog.size();
ShapeConfig shapeConfig =
new ShapeConfig(numberOfElements, viewWidth, viewHeight, firstItemSize, firstItemMargin);
shape = ShapeFactory.getShapeByKey(defaultShapeKey, shapeConfig);
} else {
shape.setNumberOfElements(noxItemCatalog.size());
}
shape.calculate();
} } | public class class_name {
private void createShape() {
if (shape == null) {
float firstItemMargin = noxConfig.getNoxItemMargin();
float firstItemSize = noxConfig.getNoxItemSize();
int viewHeight = getMeasuredHeight();
int viewWidth = getMeasuredWidth();
int numberOfElements = noxItemCatalog.size();
ShapeConfig shapeConfig =
new ShapeConfig(numberOfElements, viewWidth, viewHeight, firstItemSize, firstItemMargin);
shape = ShapeFactory.getShapeByKey(defaultShapeKey, shapeConfig); // depends on control dependency: [if], data = [none]
} else {
shape.setNumberOfElements(noxItemCatalog.size()); // depends on control dependency: [if], data = [none]
}
shape.calculate();
} } |
public class class_name {
public Runnable wrap(final Runnable r) {
return new Runnable() {
@Override
public void run() {
Context previous = attach();
try {
r.run();
} finally {
detach(previous);
}
}
};
} } | public class class_name {
public Runnable wrap(final Runnable r) {
return new Runnable() {
@Override
public void run() {
Context previous = attach();
try {
r.run(); // depends on control dependency: [try], data = [none]
} finally {
detach(previous);
}
}
};
} } |
public class class_name {
@Override
public <T> T getProperty(final Object bean, final String name) {
BeanProperty beanProperty = new BeanProperty(this, bean, name);
if (!isSilent) {
resolveNestedProperties(beanProperty);
return (T) getIndexProperty(beanProperty);
}
else {
try {
resolveNestedProperties(beanProperty);
return (T) getIndexProperty(beanProperty);
}
catch (Exception ignore) {
return null;
}
}
} } | public class class_name {
@Override
public <T> T getProperty(final Object bean, final String name) {
BeanProperty beanProperty = new BeanProperty(this, bean, name);
if (!isSilent) {
resolveNestedProperties(beanProperty); // depends on control dependency: [if], data = [none]
return (T) getIndexProperty(beanProperty); // depends on control dependency: [if], data = [none]
}
else {
try {
resolveNestedProperties(beanProperty); // depends on control dependency: [try], data = [none]
return (T) getIndexProperty(beanProperty); // depends on control dependency: [try], data = [none]
}
catch (Exception ignore) {
return null;
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void printHtmlField(PrintWriter out, String strTag, String strParams, String strData)
{
String strField = ((BasePanel)this.getRecordOwner()).getProperty("name");
if ((strField != null) && (strField.length() > 0) && (m_recDetail.getField(strField) != null))
{
String string = m_recDetail.getField(strField).toString();
out.print(string);
}
} } | public class class_name {
public void printHtmlField(PrintWriter out, String strTag, String strParams, String strData)
{
String strField = ((BasePanel)this.getRecordOwner()).getProperty("name");
if ((strField != null) && (strField.length() > 0) && (m_recDetail.getField(strField) != null))
{
String string = m_recDetail.getField(strField).toString();
out.print(string); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String getIdentifier(String propertyId, int orderNum) throws VCASException
{
try
{
Connection con = dataSource.getConnection();
ResultSet rs = null;
PreparedStatement ps = null;
try
{
ps = con.prepareStatement(sqlSelectRecord);
ps.setString(1, propertyId);
ps.setInt(2, orderNum);
rs = ps.executeQuery();
if (rs.next())
{
return rs.getString("CAS_ID");
}
else
{
throw new RecordNotFoundException("No record found with propertyId=" + propertyId + " orderNum="
+ orderNum);
}
}
finally
{
if (rs != null)
{
try
{
rs.close();
}
catch (SQLException e)
{
LOG.error("Can't close the ResultSet: " + e.getMessage());
}
}
if (ps != null)
{
try
{
ps.close();
}
catch (SQLException e)
{
LOG.error("Can't close the Statement: " + e.getMessage());
}
}
con.close();
}
}
catch (SQLException e)
{
throw new VCASException("VCAS GET ID database error: " + e, e);
}
} } | public class class_name {
public String getIdentifier(String propertyId, int orderNum) throws VCASException
{
try
{
Connection con = dataSource.getConnection();
ResultSet rs = null;
PreparedStatement ps = null;
try
{
ps = con.prepareStatement(sqlSelectRecord);
ps.setString(1, propertyId);
ps.setInt(2, orderNum);
rs = ps.executeQuery();
if (rs.next())
{
return rs.getString("CAS_ID");
// depends on control dependency: [if], data = [none]
}
else
{
throw new RecordNotFoundException("No record found with propertyId=" + propertyId + " orderNum="
+ orderNum);
}
}
finally
{
if (rs != null)
{
try
{
rs.close();
// depends on control dependency: [try], data = [none]
}
catch (SQLException e)
{
LOG.error("Can't close the ResultSet: " + e.getMessage());
}
}
if (ps != null)
{
try
{
ps.close();
}
catch (SQLException e)
{
LOG.error("Can't close the Statement: " + e.getMessage());
}
// depends on control dependency: [catch], data = [none]
}
con.close();
}
}
catch (SQLException e)
{
throw new VCASException("VCAS GET ID database error: " + e, e);
}
} } |
public class class_name {
public List<Dependency> getDependencies(List<String> scopes) {
log.debug( "Valid scopes: {}", scopes );
List<Dependency> dependencies = new ArrayList<Dependency>();
for (Dependency dependency : getMavenModel().getDependencies()) {
// Substitute Properties
// XXX: There has to be a way maven handles this automatically
log.debug( "Project properties: {} ", this.mavenModel.getProperties() );
String artifactId = substituteProperty(dependency.getArtifactId());
String groupId = substituteProperty(dependency.getGroupId());
String version = substituteProperty(dependency.getVersion());
String type = substituteProperty(dependency.getType());
String classifier = substituteProperty(dependency.getClassifier());
String systemPath = substituteProperty(dependency.getSystemPath());
dependency.setSystemPath(systemPath);
dependency.setArtifactId(artifactId);
dependency.setGroupId(groupId);
dependency.setVersion(version);
dependency.setType(type);
dependency.setClassifier( classifier );
dependencies.add(dependency);
}
if ( scopes == null ) {
scopes = Arrays.asList( "compile", "runtime" );
}
for ( Iterator<Dependency> iterator = dependencies.iterator(); iterator.hasNext(); ) {
Dependency dependency = iterator.next();
String scope = dependency.getScope();
// Default scope for dependencies is compile
if ( scope == null ) {
scope = "compile";
}
if ( !scopes.contains( scope ) ) {
log.debug( "Removing {} with scope {}", dependency, dependency.getScope() );
iterator.remove();
}
}
return dependencies;
} } | public class class_name {
public List<Dependency> getDependencies(List<String> scopes) {
log.debug( "Valid scopes: {}", scopes );
List<Dependency> dependencies = new ArrayList<Dependency>();
for (Dependency dependency : getMavenModel().getDependencies()) {
// Substitute Properties
// XXX: There has to be a way maven handles this automatically
log.debug( "Project properties: {} ", this.mavenModel.getProperties() ); // depends on control dependency: [for], data = [none]
String artifactId = substituteProperty(dependency.getArtifactId());
String groupId = substituteProperty(dependency.getGroupId());
String version = substituteProperty(dependency.getVersion());
String type = substituteProperty(dependency.getType());
String classifier = substituteProperty(dependency.getClassifier());
String systemPath = substituteProperty(dependency.getSystemPath());
dependency.setSystemPath(systemPath); // depends on control dependency: [for], data = [dependency]
dependency.setArtifactId(artifactId); // depends on control dependency: [for], data = [dependency]
dependency.setGroupId(groupId); // depends on control dependency: [for], data = [dependency]
dependency.setVersion(version); // depends on control dependency: [for], data = [dependency]
dependency.setType(type); // depends on control dependency: [for], data = [dependency]
dependency.setClassifier( classifier ); // depends on control dependency: [for], data = [dependency]
dependencies.add(dependency); // depends on control dependency: [for], data = [dependency]
}
if ( scopes == null ) {
scopes = Arrays.asList( "compile", "runtime" ); // depends on control dependency: [if], data = [none]
}
for ( Iterator<Dependency> iterator = dependencies.iterator(); iterator.hasNext(); ) {
Dependency dependency = iterator.next();
String scope = dependency.getScope();
// Default scope for dependencies is compile
if ( scope == null ) {
scope = "compile"; // depends on control dependency: [if], data = [none]
}
if ( !scopes.contains( scope ) ) {
log.debug( "Removing {} with scope {}", dependency, dependency.getScope() ); // depends on control dependency: [if], data = [none]
iterator.remove(); // depends on control dependency: [if], data = [none]
}
}
return dependencies;
} } |
public class class_name {
public boolean enforce(Object... rvals) {
if (!enabled) {
return true;
}
Map<String, AviatorFunction> functions = new HashMap<>();
for (Map.Entry<String, AviatorFunction> entry : fm.fm.entrySet()) {
String key = entry.getKey();
AviatorFunction function = entry.getValue();
functions.put(key, function);
}
if (model.model.containsKey("g")) {
for (Map.Entry<String, Assertion> entry : model.model.get("g").entrySet()) {
String key = entry.getKey();
Assertion ast = entry.getValue();
RoleManager rm = ast.rm;
functions.put(key, BuiltInFunctions.generateGFunction(key, rm));
}
}
AviatorEvaluatorInstance eval = AviatorEvaluator.newInstance();
for (AviatorFunction f : functions.values()) {
eval.addFunction(f);
}
String expString = model.model.get("m").get("m").value;
Expression expression = eval.compile(expString);
Effect policyEffects[];
float matcherResults[];
int policyLen;
if ((policyLen = model.model.get("p").get("p").policy.size()) != 0) {
policyEffects = new Effect[policyLen];
matcherResults = new float[policyLen];
for (int i = 0; i < model.model.get("p").get("p").policy.size(); i ++) {
List<String> pvals = model.model.get("p").get("p").policy.get(i);
// Util.logPrint("Policy Rule: " + pvals);
Map<String, Object> parameters = new HashMap<>();
for (int j = 0; j < model.model.get("r").get("r").tokens.length; j ++) {
String token = model.model.get("r").get("r").tokens[j];
parameters.put(token, rvals[j]);
}
for (int j = 0; j < model.model.get("p").get("p").tokens.length; j ++) {
String token = model.model.get("p").get("p").tokens[j];
parameters.put(token, pvals.get(j));
}
Object result = expression.execute(parameters);
// Util.logPrint("Result: " + result);
if (result instanceof Boolean) {
if (!((boolean) result)) {
policyEffects[i] = Effect.Indeterminate;
continue;
}
} else if (result instanceof Float) {
if ((float) result == 0) {
policyEffects[i] = Effect.Indeterminate;
continue;
} else {
matcherResults[i] = (float) result;
}
} else {
throw new Error("matcher result should be bool, int or float");
}
if (parameters.containsKey("p_eft")) {
String eft = (String) parameters.get("p_eft");
if (eft.equals("allow")) {
policyEffects[i] = Effect.Allow;
} else if (eft.equals("deny")) {
policyEffects[i] = Effect.Deny;
} else {
policyEffects[i] = Effect.Indeterminate;
}
} else {
policyEffects[i] = Effect.Allow;
}
if (model.model.get("e").get("e").value.equals("priority(p_eft) || deny")) {
break;
}
}
} else {
policyEffects = new Effect[1];
matcherResults = new float[1];
Map<String, Object> parameters = new HashMap<>();
for (int j = 0; j < model.model.get("r").get("r").tokens.length; j ++) {
String token = model.model.get("r").get("r").tokens[j];
parameters.put(token, rvals[j]);
}
for (int j = 0; j < model.model.get("p").get("p").tokens.length; j ++) {
String token = model.model.get("p").get("p").tokens[j];
parameters.put(token, "");
}
Object result = expression.execute(parameters);
// Util.logPrint("Result: " + result);
if ((boolean) result) {
policyEffects[0] = Effect.Allow;
} else {
policyEffects[0] = Effect.Indeterminate;
}
}
boolean result = eft.mergeEffects(model.model.get("e").get("e").value, policyEffects, matcherResults);
StringBuilder reqStr = new StringBuilder("Request: ");
for (int i = 0; i < rvals.length; i ++) {
String rval = rvals[i].toString();
if (i != rvals.length - 1) {
reqStr.append(String.format("%s, ", rval));
} else {
reqStr.append(String.format("%s", rval));
}
}
reqStr.append(String.format(" ---> %s", result));
Util.logPrint(reqStr.toString());
return result;
} } | public class class_name {
public boolean enforce(Object... rvals) {
if (!enabled) {
return true; // depends on control dependency: [if], data = [none]
}
Map<String, AviatorFunction> functions = new HashMap<>();
for (Map.Entry<String, AviatorFunction> entry : fm.fm.entrySet()) {
String key = entry.getKey();
AviatorFunction function = entry.getValue();
functions.put(key, function); // depends on control dependency: [for], data = [none]
}
if (model.model.containsKey("g")) {
for (Map.Entry<String, Assertion> entry : model.model.get("g").entrySet()) {
String key = entry.getKey();
Assertion ast = entry.getValue();
RoleManager rm = ast.rm;
functions.put(key, BuiltInFunctions.generateGFunction(key, rm)); // depends on control dependency: [for], data = [none]
}
}
AviatorEvaluatorInstance eval = AviatorEvaluator.newInstance();
for (AviatorFunction f : functions.values()) {
eval.addFunction(f); // depends on control dependency: [for], data = [f]
}
String expString = model.model.get("m").get("m").value;
Expression expression = eval.compile(expString);
Effect policyEffects[];
float matcherResults[];
int policyLen;
if ((policyLen = model.model.get("p").get("p").policy.size()) != 0) {
policyEffects = new Effect[policyLen]; // depends on control dependency: [if], data = [none]
matcherResults = new float[policyLen]; // depends on control dependency: [if], data = [none]
for (int i = 0; i < model.model.get("p").get("p").policy.size(); i ++) {
List<String> pvals = model.model.get("p").get("p").policy.get(i);
// Util.logPrint("Policy Rule: " + pvals);
Map<String, Object> parameters = new HashMap<>();
for (int j = 0; j < model.model.get("r").get("r").tokens.length; j ++) {
String token = model.model.get("r").get("r").tokens[j];
parameters.put(token, rvals[j]); // depends on control dependency: [for], data = [j]
}
for (int j = 0; j < model.model.get("p").get("p").tokens.length; j ++) {
String token = model.model.get("p").get("p").tokens[j];
parameters.put(token, pvals.get(j)); // depends on control dependency: [for], data = [j]
}
Object result = expression.execute(parameters);
// Util.logPrint("Result: " + result);
if (result instanceof Boolean) {
if (!((boolean) result)) {
policyEffects[i] = Effect.Indeterminate; // depends on control dependency: [if], data = [none]
continue;
}
} else if (result instanceof Float) {
if ((float) result == 0) {
policyEffects[i] = Effect.Indeterminate; // depends on control dependency: [if], data = [none]
continue;
} else {
matcherResults[i] = (float) result; // depends on control dependency: [if], data = [none]
}
} else {
throw new Error("matcher result should be bool, int or float");
}
if (parameters.containsKey("p_eft")) {
String eft = (String) parameters.get("p_eft");
if (eft.equals("allow")) {
policyEffects[i] = Effect.Allow; // depends on control dependency: [if], data = [none]
} else if (eft.equals("deny")) {
policyEffects[i] = Effect.Deny; // depends on control dependency: [if], data = [none]
} else {
policyEffects[i] = Effect.Indeterminate; // depends on control dependency: [if], data = [none]
}
} else {
policyEffects[i] = Effect.Allow; // depends on control dependency: [if], data = [none]
}
if (model.model.get("e").get("e").value.equals("priority(p_eft) || deny")) {
break;
}
}
} else {
policyEffects = new Effect[1]; // depends on control dependency: [if], data = [none]
matcherResults = new float[1]; // depends on control dependency: [if], data = [none]
Map<String, Object> parameters = new HashMap<>();
for (int j = 0; j < model.model.get("r").get("r").tokens.length; j ++) {
String token = model.model.get("r").get("r").tokens[j];
parameters.put(token, rvals[j]); // depends on control dependency: [for], data = [j]
}
for (int j = 0; j < model.model.get("p").get("p").tokens.length; j ++) {
String token = model.model.get("p").get("p").tokens[j];
parameters.put(token, ""); // depends on control dependency: [for], data = [none]
}
Object result = expression.execute(parameters);
// Util.logPrint("Result: " + result);
if ((boolean) result) {
policyEffects[0] = Effect.Allow; // depends on control dependency: [if], data = [none]
} else {
policyEffects[0] = Effect.Indeterminate; // depends on control dependency: [if], data = [none]
}
}
boolean result = eft.mergeEffects(model.model.get("e").get("e").value, policyEffects, matcherResults);
StringBuilder reqStr = new StringBuilder("Request: ");
for (int i = 0; i < rvals.length; i ++) {
String rval = rvals[i].toString();
if (i != rvals.length - 1) {
reqStr.append(String.format("%s, ", rval)); // depends on control dependency: [if], data = [none]
} else {
reqStr.append(String.format("%s", rval)); // depends on control dependency: [if], data = [none]
}
}
reqStr.append(String.format(" ---> %s", result));
Util.logPrint(reqStr.toString());
return result;
} } |
public class class_name {
public static String escapeRegExp(final String value) {
final StringBuilder buff = new StringBuilder();
if (value == null || value.length() == 0) {
return "";
}
int index = 0;
// $( )+.[^{\
while (index < value.length()) {
final char current = value.charAt(index);
switch (current) {
case '.':
buff.append("\\.");
break;
// case '/':
// case '|':
case '\\':
buff.append("[\\\\|/]");
break;
case '(':
buff.append("\\(");
break;
case ')':
buff.append("\\)");
break;
case '[':
buff.append("\\[");
break;
case ']':
buff.append("\\]");
break;
case '{':
buff.append("\\{");
break;
case '}':
buff.append("\\}");
break;
case '^':
buff.append("\\^");
break;
case '+':
buff.append("\\+");
break;
case '$':
buff.append("\\$");
break;
default:
buff.append(current);
}
index++;
}
return buff.toString();
} } | public class class_name {
public static String escapeRegExp(final String value) {
final StringBuilder buff = new StringBuilder();
if (value == null || value.length() == 0) {
return ""; // depends on control dependency: [if], data = [none]
}
int index = 0;
// $( )+.[^{\
while (index < value.length()) {
final char current = value.charAt(index);
switch (current) {
case '.':
buff.append("\\.");
break;
// case '/':
// case '|':
case '\\':
buff.append("[\\\\|/]");
break;
case '(':
buff.append("\\(");
break;
case ')':
buff.append("\\)");
break;
case '[':
buff.append("\\[");
break;
case ']':
buff.append("\\]");
break;
case '{':
buff.append("\\{");
break;
case '}':
buff.append("\\}");
break;
case '^':
buff.append("\\^");
break;
case '+':
buff.append("\\+");
break;
case '$':
buff.append("\\$");
break;
default:
buff.append(current);
}
index++; // depends on control dependency: [while], data = [none]
}
return buff.toString();
} } |
public class class_name {
static void runPartialLearner(boolean withCache) {
// setup SULs and counters
StateLocalInputSUL<Integer, Character> target = SUL;
ResetCounterStateLocalInputSUL<Integer, Character> resetCounter =
new ResetCounterStateLocalInputSUL<>("Resets", target);
SymbolCounterStateLocalInputSUL<Integer, Character> symbolCounter =
new SymbolCounterStateLocalInputSUL<>("Symbols", resetCounter);
// construct a (state local input) simulator membership query oracle
StateLocalInputMealyOracle<Integer, OutputAndLocalInputs<Integer, Character>> mqOracle =
new StateLocalInputSULOracle<>(symbolCounter);
// construct storage for EquivalenceOracle chain, because we want to use the potential cache as well
List<EquivalenceOracle<StateLocalInputMealyMachine<?, Integer, ?, Character>, Integer, Word<OutputAndLocalInputs<Integer, Character>>>>
eqOracles = new ArrayList<>(2);
if (withCache) {
StateLocalInputMealyCacheOracle<Integer, Character> mqCache =
MealyCaches.createStateLocalInputTreeCache(mqOracle.definedInputs(Word.epsilon()), mqOracle);
eqOracles.add(mqCache.createStateLocalInputCacheConsistencyTest());
mqOracle = mqCache;
}
// construct L* instance
PartialLStarMealy<Integer, Character> lstar =
new PartialLStarMealyBuilder<Integer, Character>().withOracle(mqOracle)
.withCexHandler(ObservationTableCEXHandlers.RIVEST_SCHAPIRE)
.create();
// here, we simply fallback to an equivalence check for the original automaton model
eqOracles.add(new StateLocalInputMealySimulatorEQOracle<>(TARGET));
// construct single EQ oracle
EquivalenceOracle<StateLocalInputMealyMachine<?, Integer, ?, Character>, Integer, Word<OutputAndLocalInputs<Integer, Character>>>
eqOracle = new EQOracleChain<>(eqOracles);
// construct the experiment
// note, we can't use the regular MealyExperiment (or MooreExperiment) because the output type of our hypothesis
// is different from our membership query type
Experiment<StateLocalInputMealyMachine<?, Integer, ?, Character>> experiment =
new Experiment<>(lstar, eqOracle, INPUTS);
// run experiment
experiment.run();
// report results
System.out.println("Partial Hypothesis" + (withCache ? ", with cache" : ""));
System.out.println("-------------------------------------------------------");
System.out.println(resetCounter.getStatisticalData().getSummary());
System.out.println(symbolCounter.getStatisticalData().getSummary());
System.out.println("-------------------------------------------------------");
} } | public class class_name {
static void runPartialLearner(boolean withCache) {
// setup SULs and counters
StateLocalInputSUL<Integer, Character> target = SUL;
ResetCounterStateLocalInputSUL<Integer, Character> resetCounter =
new ResetCounterStateLocalInputSUL<>("Resets", target);
SymbolCounterStateLocalInputSUL<Integer, Character> symbolCounter =
new SymbolCounterStateLocalInputSUL<>("Symbols", resetCounter);
// construct a (state local input) simulator membership query oracle
StateLocalInputMealyOracle<Integer, OutputAndLocalInputs<Integer, Character>> mqOracle =
new StateLocalInputSULOracle<>(symbolCounter);
// construct storage for EquivalenceOracle chain, because we want to use the potential cache as well
List<EquivalenceOracle<StateLocalInputMealyMachine<?, Integer, ?, Character>, Integer, Word<OutputAndLocalInputs<Integer, Character>>>>
eqOracles = new ArrayList<>(2);
if (withCache) {
StateLocalInputMealyCacheOracle<Integer, Character> mqCache =
MealyCaches.createStateLocalInputTreeCache(mqOracle.definedInputs(Word.epsilon()), mqOracle);
eqOracles.add(mqCache.createStateLocalInputCacheConsistencyTest()); // depends on control dependency: [if], data = [none]
mqOracle = mqCache; // depends on control dependency: [if], data = [none]
}
// construct L* instance
PartialLStarMealy<Integer, Character> lstar =
new PartialLStarMealyBuilder<Integer, Character>().withOracle(mqOracle)
.withCexHandler(ObservationTableCEXHandlers.RIVEST_SCHAPIRE)
.create();
// here, we simply fallback to an equivalence check for the original automaton model
eqOracles.add(new StateLocalInputMealySimulatorEQOracle<>(TARGET));
// construct single EQ oracle
EquivalenceOracle<StateLocalInputMealyMachine<?, Integer, ?, Character>, Integer, Word<OutputAndLocalInputs<Integer, Character>>>
eqOracle = new EQOracleChain<>(eqOracles);
// construct the experiment
// note, we can't use the regular MealyExperiment (or MooreExperiment) because the output type of our hypothesis
// is different from our membership query type
Experiment<StateLocalInputMealyMachine<?, Integer, ?, Character>> experiment =
new Experiment<>(lstar, eqOracle, INPUTS);
// run experiment
experiment.run();
// report results
System.out.println("Partial Hypothesis" + (withCache ? ", with cache" : ""));
System.out.println("-------------------------------------------------------");
System.out.println(resetCounter.getStatisticalData().getSummary());
System.out.println(symbolCounter.getStatisticalData().getSummary());
System.out.println("-------------------------------------------------------");
} } |
public class class_name {
private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) {
ParsePosition pos = (position != null ? position : new ParsePosition(0));
DateTimeParseContext context = parseUnresolved0(text, pos);
if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) {
String abbr;
if (text.length() > 64) {
abbr = text.subSequence(0, 64).toString() + "...";
} else {
abbr = text.toString();
}
if (pos.getErrorIndex() >= 0) {
throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " +
pos.getErrorIndex(), text, pos.getErrorIndex());
} else {
throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " +
pos.getIndex(), text, pos.getIndex());
}
}
return context.toResolved(resolverStyle, resolverFields);
} } | public class class_name {
private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) {
ParsePosition pos = (position != null ? position : new ParsePosition(0));
DateTimeParseContext context = parseUnresolved0(text, pos);
if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) {
String abbr;
if (text.length() > 64) {
abbr = text.subSequence(0, 64).toString() + "..."; // depends on control dependency: [if], data = [64)]
} else {
abbr = text.toString(); // depends on control dependency: [if], data = [none]
}
if (pos.getErrorIndex() >= 0) {
throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " +
pos.getErrorIndex(), text, pos.getErrorIndex());
} else {
throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " +
pos.getIndex(), text, pos.getIndex());
}
}
return context.toResolved(resolverStyle, resolverFields);
} } |
public class class_name {
@Override
protected void append(LoggingEvent loggingEvent)
{
java.util.logging.Logger logger = java.util.logging.Logger.getLogger(loggingEvent.getLoggerName());
if (logger == null) {
LogLog.warn(format("Cannot obtain JUL %s. Verify that this appender is used while an appropriate LogManager is active.", loggingEvent.getLoggerName()));
return;
}
Level level = loggingEvent.getLevel();
java.util.logging.Level julLevel = convertLog4jLevel(level);
LogRecord record = new LogRecord(julLevel, loggingEvent.getRenderedMessage());
record.setMillis(loggingEvent.getTimeStamp());
LocationInfo location = loggingEvent.getLocationInformation();
if (location != null) {
record.setSourceClassName(location.getClassName());
record.setSourceMethodName(location.getMethodName());
}
logger.log(record);
} } | public class class_name {
@Override
protected void append(LoggingEvent loggingEvent)
{
java.util.logging.Logger logger = java.util.logging.Logger.getLogger(loggingEvent.getLoggerName());
if (logger == null) {
LogLog.warn(format("Cannot obtain JUL %s. Verify that this appender is used while an appropriate LogManager is active.", loggingEvent.getLoggerName())); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
Level level = loggingEvent.getLevel();
java.util.logging.Level julLevel = convertLog4jLevel(level);
LogRecord record = new LogRecord(julLevel, loggingEvent.getRenderedMessage());
record.setMillis(loggingEvent.getTimeStamp());
LocationInfo location = loggingEvent.getLocationInformation();
if (location != null) {
record.setSourceClassName(location.getClassName()); // depends on control dependency: [if], data = [(location]
record.setSourceMethodName(location.getMethodName()); // depends on control dependency: [if], data = [(location]
}
logger.log(record);
} } |
public class class_name {
@Override
public void perform(GraphRewrite event, EvaluationContext context)
{
checkVariableName(event, context);
WindupVertexFrame payload = resolveVariable(event, getVariableName());
if (payload instanceof FileReferenceModel)
{
FileModel file = ((FileReferenceModel) payload).getFile();
perform(event, context, (XmlFileModel) file);
}
else
{
super.perform(event, context);
}
} } | public class class_name {
@Override
public void perform(GraphRewrite event, EvaluationContext context)
{
checkVariableName(event, context);
WindupVertexFrame payload = resolveVariable(event, getVariableName());
if (payload instanceof FileReferenceModel)
{
FileModel file = ((FileReferenceModel) payload).getFile();
perform(event, context, (XmlFileModel) file); // depends on control dependency: [if], data = [none]
}
else
{
super.perform(event, context); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void writeHeader(final VcfHeader header, final PrintWriter writer) {
checkNotNull(header);
checkNotNull(writer);
for (String meta : header.getMeta()) {
writer.println(meta);
}
} } | public class class_name {
public static void writeHeader(final VcfHeader header, final PrintWriter writer) {
checkNotNull(header);
checkNotNull(writer);
for (String meta : header.getMeta()) {
writer.println(meta); // depends on control dependency: [for], data = [meta]
}
} } |
public class class_name {
private double[][] _step(double[][] state, char ch1, char ch2) {
double cost;
_shift(state);
state[2][0] = state[1][0] + deletionDistance;
for (int i = 0; i < morseBase.length(); i++) {
cost = (morseBase.charAt(i) == ch1) ? 0 : replaceDistance;
state[2][i + 1] = Math.min(state[2][i] + insertionDistance,
state[1][i] + cost);
state[2][i + 1] = Math.min(state[2][i + 1],
state[1][i + 1] + deletionDistance);
if (i > 0 && ch2 != 0x00 && (morseBase.charAt(i - 1) == ch1)
&& (morseBase.charAt(i) == ch2)) {
state[2][i + 1] = Math.min(state[2][i + 1],
state[0][i - 1] + transpositionDistance);
}
}
return state;
} } | public class class_name {
private double[][] _step(double[][] state, char ch1, char ch2) {
double cost;
_shift(state);
state[2][0] = state[1][0] + deletionDistance;
for (int i = 0; i < morseBase.length(); i++) {
cost = (morseBase.charAt(i) == ch1) ? 0 : replaceDistance; // depends on control dependency: [for], data = [i]
state[2][i + 1] = Math.min(state[2][i] + insertionDistance,
state[1][i] + cost); // depends on control dependency: [for], data = [i]
state[2][i + 1] = Math.min(state[2][i + 1],
state[1][i + 1] + deletionDistance); // depends on control dependency: [for], data = [i]
if (i > 0 && ch2 != 0x00 && (morseBase.charAt(i - 1) == ch1)
&& (morseBase.charAt(i) == ch2)) {
state[2][i + 1] = Math.min(state[2][i + 1],
state[0][i - 1] + transpositionDistance); // depends on control dependency: [if], data = [none]
}
}
return state;
} } |
public class class_name {
@Override
public List<TimelineObjectHolder<VersionType, ObjectType>> lookup(Interval interval)
{
try {
lock.readLock().lock();
return lookup(interval, false);
}
finally {
lock.readLock().unlock();
}
} } | public class class_name {
@Override
public List<TimelineObjectHolder<VersionType, ObjectType>> lookup(Interval interval)
{
try {
lock.readLock().lock(); // depends on control dependency: [try], data = [none]
return lookup(interval, false); // depends on control dependency: [try], data = [none]
}
finally {
lock.readLock().unlock();
}
} } |
public class class_name {
protected ORole createRole(final ODocument roleDoc) {
ORole role = null;
// If databaseName is set, then only allow roles with the same databaseName.
if (databaseName != null && !databaseName.isEmpty()) {
if (roleDoc != null && roleDoc.containsField(OSystemRole.DB_FILTER) && roleDoc.fieldType(OSystemRole.DB_FILTER) == OType.EMBEDDEDLIST) {
List<String> dbNames = roleDoc.field(OSystemRole.DB_FILTER, OType.EMBEDDEDLIST);
for (String dbName : dbNames) {
if (dbName != null && !dbName.isEmpty() && (dbName.equalsIgnoreCase(databaseName) || dbName.equals("*"))) {
role = new OSystemRole(roleDoc);
break;
}
}
}
}
// If databaseName is not set, only return roles without a OSystemRole.DB_FILTER property or if set to "*".
else {
if (roleDoc != null) {
if (!roleDoc.containsField(OSystemRole.DB_FILTER)) {
role = new OSystemRole(roleDoc);
} else { // It does use the dbFilter property.
if(roleDoc.fieldType(OSystemRole.DB_FILTER) == OType.EMBEDDEDLIST) {
List<String> dbNames = roleDoc.field(OSystemRole.DB_FILTER, OType.EMBEDDEDLIST);
for (String dbName : dbNames) {
if (dbName != null && !dbName.isEmpty() && dbName.equals("*")) {
role = new OSystemRole(roleDoc);
break;
}
}
}
}
}
}
return role;
} } | public class class_name {
protected ORole createRole(final ODocument roleDoc) {
ORole role = null;
// If databaseName is set, then only allow roles with the same databaseName.
if (databaseName != null && !databaseName.isEmpty()) {
if (roleDoc != null && roleDoc.containsField(OSystemRole.DB_FILTER) && roleDoc.fieldType(OSystemRole.DB_FILTER) == OType.EMBEDDEDLIST) {
List<String> dbNames = roleDoc.field(OSystemRole.DB_FILTER, OType.EMBEDDEDLIST);
for (String dbName : dbNames) {
if (dbName != null && !dbName.isEmpty() && (dbName.equalsIgnoreCase(databaseName) || dbName.equals("*"))) {
role = new OSystemRole(roleDoc); // depends on control dependency: [if], data = [none]
break;
}
}
}
}
// If databaseName is not set, only return roles without a OSystemRole.DB_FILTER property or if set to "*".
else {
if (roleDoc != null) {
if (!roleDoc.containsField(OSystemRole.DB_FILTER)) {
role = new OSystemRole(roleDoc); // depends on control dependency: [if], data = [none]
} else { // It does use the dbFilter property.
if(roleDoc.fieldType(OSystemRole.DB_FILTER) == OType.EMBEDDEDLIST) {
List<String> dbNames = roleDoc.field(OSystemRole.DB_FILTER, OType.EMBEDDEDLIST);
for (String dbName : dbNames) {
if (dbName != null && !dbName.isEmpty() && dbName.equals("*")) {
role = new OSystemRole(roleDoc); // depends on control dependency: [if], data = [none]
break;
}
}
}
}
}
}
return role;
} } |
public class class_name {
public static GeometryCollection extrudePolygonAsGeometry(Polygon polygon, double height){
GeometryFactory factory = polygon.getFactory();
Geometry[] geometries = new Geometry[3];
//Extract floor
//We process the exterior ring
final LineString shell = getClockWise(polygon.getExteriorRing());
ArrayList<Polygon> walls = new ArrayList<Polygon>();
for (int i = 1; i < shell.getNumPoints(); i++) {
walls.add(extrudeEdge(shell.getCoordinateN(i - 1), shell.getCoordinateN(i), height, factory));
}
final int nbOfHoles = polygon.getNumInteriorRing();
final LinearRing[] holes = new LinearRing[nbOfHoles];
for (int i = 0; i < nbOfHoles; i++) {
final LineString hole = getCounterClockWise(polygon.getInteriorRingN(i));
for (int j = 1; j < hole.getNumPoints(); j++) {
walls.add(extrudeEdge(hole.getCoordinateN(j - 1),
hole.getCoordinateN(j), height, factory));
}
holes[i] = factory.createLinearRing(hole.getCoordinateSequence());
}
geometries[0]= factory.createPolygon(factory.createLinearRing(shell.getCoordinateSequence()), holes);
geometries[1]= factory.createMultiPolygon(walls.toArray(new Polygon[0]));
geometries[2]= extractRoof(polygon, height);
return polygon.getFactory().createGeometryCollection(geometries);
} } | public class class_name {
public static GeometryCollection extrudePolygonAsGeometry(Polygon polygon, double height){
GeometryFactory factory = polygon.getFactory();
Geometry[] geometries = new Geometry[3];
//Extract floor
//We process the exterior ring
final LineString shell = getClockWise(polygon.getExteriorRing());
ArrayList<Polygon> walls = new ArrayList<Polygon>();
for (int i = 1; i < shell.getNumPoints(); i++) {
walls.add(extrudeEdge(shell.getCoordinateN(i - 1), shell.getCoordinateN(i), height, factory)); // depends on control dependency: [for], data = [i]
}
final int nbOfHoles = polygon.getNumInteriorRing();
final LinearRing[] holes = new LinearRing[nbOfHoles];
for (int i = 0; i < nbOfHoles; i++) {
final LineString hole = getCounterClockWise(polygon.getInteriorRingN(i));
for (int j = 1; j < hole.getNumPoints(); j++) {
walls.add(extrudeEdge(hole.getCoordinateN(j - 1),
hole.getCoordinateN(j), height, factory)); // depends on control dependency: [for], data = [j]
}
holes[i] = factory.createLinearRing(hole.getCoordinateSequence()); // depends on control dependency: [for], data = [i]
}
geometries[0]= factory.createPolygon(factory.createLinearRing(shell.getCoordinateSequence()), holes);
geometries[1]= factory.createMultiPolygon(walls.toArray(new Polygon[0]));
geometries[2]= extractRoof(polygon, height);
return polygon.getFactory().createGeometryCollection(geometries);
} } |
public class class_name {
public synchronized void start() {
if (mStopped) {
Preconditions.checkState(mLoggingWorkerThread == null);
mStopped = false;
mLoggingWorkerThread = new Thread(new AuditLoggingWorker());
mLoggingWorkerThread.setName(AUDIT_LOG_THREAD_NAME);
mLoggingWorkerThread.start();
LOG.info("AsyncUserAccessAuditLogWriter thread started.");
}
} } | public class class_name {
public synchronized void start() {
if (mStopped) {
Preconditions.checkState(mLoggingWorkerThread == null); // depends on control dependency: [if], data = [none]
mStopped = false; // depends on control dependency: [if], data = [none]
mLoggingWorkerThread = new Thread(new AuditLoggingWorker()); // depends on control dependency: [if], data = [none]
mLoggingWorkerThread.setName(AUDIT_LOG_THREAD_NAME); // depends on control dependency: [if], data = [none]
mLoggingWorkerThread.start(); // depends on control dependency: [if], data = [none]
LOG.info("AsyncUserAccessAuditLogWriter thread started."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <K, V> boolean any(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> predicate) {
BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
for (Map.Entry<K, V> entry : self.entrySet()) {
if (bcw.callForMap(entry)) {
return true;
}
}
return false;
} } | public class class_name {
public static <K, V> boolean any(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> predicate) {
BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
for (Map.Entry<K, V> entry : self.entrySet()) {
if (bcw.callForMap(entry)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
private void loadAllParts()
throws IOException
{
// Get first boundary
String line = _in.readLine();
if (!line.equals(_boundary))
{
log.warn(line);
throw new IOException("Missing initial multi part boundary");
}
// Read each part
while (!_lastPart)
{
// Read Part headers
Part part = new Part();
String content_disposition=null;
while ((line=_in.readLine())!=null)
{
// If blank line, end of part headers
if (line.length()==0)
break;
if(log.isDebugEnabled())log.debug("LINE="+line);
// place part header key and value in map
int c = line.indexOf(':',0);
if (c>0)
{
String key = line.substring(0,c).trim().toLowerCase();
String value = line.substring(c+1,line.length()).trim();
String ev = (String) part._headers.get(key);
part._headers.put(key,(ev!=null)?(ev+';'+value):value);
if(log.isDebugEnabled())log.debug(key+": "+value);
if (key.equals("content-disposition"))
content_disposition=value;
}
}
// Extract content-disposition
boolean form_data=false;
if (content_disposition==null)
{
throw new IOException("Missing content-disposition");
}
StringTokenizer tok =
new StringTokenizer(content_disposition,";");
while (tok.hasMoreTokens())
{
String t = tok.nextToken().trim();
String tl = t.toLowerCase();
if (t.startsWith("form-data"))
form_data=true;
else if (tl.startsWith("name="))
part._name=value(t);
else if (tl.startsWith("filename="))
part._filename=value(t);
}
// Check disposition
if (!form_data)
{
log.warn("Non form-data part in multipart/form-data");
continue;
}
if (part._name==null || part._name.length()==0)
{
log.warn("Part with no name in multipart/form-data");
continue;
}
if(log.isDebugEnabled())log.debug("name="+part._name);
if(log.isDebugEnabled())log.debug("filename="+part._filename);
_partMap.add(part._name,part);
part._data=readBytes();
}
} } | public class class_name {
private void loadAllParts()
throws IOException
{
// Get first boundary
String line = _in.readLine();
if (!line.equals(_boundary))
{
log.warn(line);
throw new IOException("Missing initial multi part boundary");
}
// Read each part
while (!_lastPart)
{
// Read Part headers
Part part = new Part();
String content_disposition=null;
while ((line=_in.readLine())!=null)
{
// If blank line, end of part headers
if (line.length()==0)
break;
if(log.isDebugEnabled())log.debug("LINE="+line);
// place part header key and value in map
int c = line.indexOf(':',0);
if (c>0)
{
String key = line.substring(0,c).trim().toLowerCase();
String value = line.substring(c+1,line.length()).trim();
String ev = (String) part._headers.get(key);
part._headers.put(key,(ev!=null)?(ev+';'+value):value); // depends on control dependency: [if], data = [none]
if(log.isDebugEnabled())log.debug(key+": "+value);
if (key.equals("content-disposition"))
content_disposition=value;
}
}
// Extract content-disposition
boolean form_data=false;
if (content_disposition==null)
{
throw new IOException("Missing content-disposition");
}
StringTokenizer tok =
new StringTokenizer(content_disposition,";");
while (tok.hasMoreTokens())
{
String t = tok.nextToken().trim();
String tl = t.toLowerCase();
if (t.startsWith("form-data"))
form_data=true;
else if (tl.startsWith("name="))
part._name=value(t);
else if (tl.startsWith("filename="))
part._filename=value(t);
}
// Check disposition
if (!form_data)
{
log.warn("Non form-data part in multipart/form-data"); // depends on control dependency: [if], data = [none]
continue;
}
if (part._name==null || part._name.length()==0)
{
log.warn("Part with no name in multipart/form-data"); // depends on control dependency: [if], data = [none]
continue;
}
if(log.isDebugEnabled())log.debug("name="+part._name);
if(log.isDebugEnabled())log.debug("filename="+part._filename);
_partMap.add(part._name,part);
part._data=readBytes();
}
} } |
public class class_name {
synchronized public void performHostDiscovery(MetricRegistry metricRegistry) {
// Host discovery is not idempotent; only take action if it hasn't been performed.
if (_hostDiscoveryPerformed) {
return;
}
Iterable<String> hosts = null;
// Statically configured list of seeds.
if (_seeds != null) {
hosts = Splitter.on(',').trimResults().split(_seeds);
}
// Perform ZooKeeper discovery to find the seeds.
if (_zooKeeperServiceName != null) {
checkState(hosts == null, "Too many host discovery mechanisms configured.");
checkState(_curator != null,
"ZooKeeper host discovery is configured but withZooKeeperHostDiscovery() was not called.");
try (HostDiscovery hostDiscovery = new ZooKeeperHostDiscovery(_curator, _zooKeeperServiceName, metricRegistry)) {
List<String> hostList = Lists.newArrayList();
for (ServiceEndPoint endPoint : hostDiscovery.getHosts()) {
// The host:port is in the end point ID
hostList.add(endPoint.getId());
// The partitioner class name is in the json-encoded end point payload
if (_partitioner == null && endPoint.getPayload() != null) {
JsonNode payload = JsonHelper.fromJson(endPoint.getPayload(), JsonNode.class);
String partitioner = payload.path("partitioner").textValue();
if (partitioner != null) {
_partitioner = CassandraPartitioner.fromClass(partitioner);
}
}
}
hosts = hostList;
} catch (IOException ex) {
// suppress any IOExceptions that might result from closing our ZooKeeperHostDiscovery
}
}
checkState(hosts != null, "No Cassandra host discovery mechanisms are configured.");
//noinspection ConstantConditions
checkState(!Iterables.isEmpty(hosts), "Unable to discover any Cassandra seed instances.");
checkState(_partitioner != null, "Cassandra partitioner not configured or discoverable.");
_seeds = Joiner.on(',').join(hosts);
_hostDiscoveryPerformed = true;
} } | public class class_name {
synchronized public void performHostDiscovery(MetricRegistry metricRegistry) {
// Host discovery is not idempotent; only take action if it hasn't been performed.
if (_hostDiscoveryPerformed) {
return; // depends on control dependency: [if], data = [none]
}
Iterable<String> hosts = null;
// Statically configured list of seeds.
if (_seeds != null) {
hosts = Splitter.on(',').trimResults().split(_seeds); // depends on control dependency: [if], data = [(_seeds]
}
// Perform ZooKeeper discovery to find the seeds.
if (_zooKeeperServiceName != null) {
checkState(hosts == null, "Too many host discovery mechanisms configured."); // depends on control dependency: [if], data = [none]
checkState(_curator != null,
"ZooKeeper host discovery is configured but withZooKeeperHostDiscovery() was not called."); // depends on control dependency: [if], data = [none]
try (HostDiscovery hostDiscovery = new ZooKeeperHostDiscovery(_curator, _zooKeeperServiceName, metricRegistry)) {
List<String> hostList = Lists.newArrayList();
for (ServiceEndPoint endPoint : hostDiscovery.getHosts()) {
// The host:port is in the end point ID
hostList.add(endPoint.getId()); // depends on control dependency: [for], data = [endPoint]
// The partitioner class name is in the json-encoded end point payload
if (_partitioner == null && endPoint.getPayload() != null) {
JsonNode payload = JsonHelper.fromJson(endPoint.getPayload(), JsonNode.class);
String partitioner = payload.path("partitioner").textValue();
if (partitioner != null) {
_partitioner = CassandraPartitioner.fromClass(partitioner); // depends on control dependency: [if], data = [(partitioner]
}
}
}
hosts = hostList; // depends on control dependency: [if], data = [none]
} catch (IOException ex) {
// suppress any IOExceptions that might result from closing our ZooKeeperHostDiscovery
}
}
checkState(hosts != null, "No Cassandra host discovery mechanisms are configured.");
//noinspection ConstantConditions
checkState(!Iterables.isEmpty(hosts), "Unable to discover any Cassandra seed instances.");
checkState(_partitioner != null, "Cassandra partitioner not configured or discoverable.");
_seeds = Joiner.on(',').join(hosts);
_hostDiscoveryPerformed = true;
} } |
public class class_name {
public static byte[] ensureCapacity(byte array[], int capacity){
if(capacity<=0 || capacity-array.length<=0)
return array;
int newCapacity = array.length*2;
if(newCapacity-capacity< 0)
newCapacity = capacity;
if(newCapacity<0){
if(capacity<0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
return Arrays.copyOf(array, newCapacity);
} } | public class class_name {
public static byte[] ensureCapacity(byte array[], int capacity){
if(capacity<=0 || capacity-array.length<=0)
return array;
int newCapacity = array.length*2;
if(newCapacity-capacity< 0)
newCapacity = capacity;
if(newCapacity<0){
if(capacity<0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE; // depends on control dependency: [if], data = [none]
}
return Arrays.copyOf(array, newCapacity);
} } |
public class class_name {
public static void main(String[] args) {
try {
Arguments arguments = new Arguments(args);
File root = new File(arguments.next("content"));
if (!root.isDirectory()) {
root = new File(".");
}
String rootPath = root.getCanonicalPath();
String sip = arguments.next("build/files.zip");
new FileArchiver().run(rootPath, sip);
} catch (IOException e) {
e.printStackTrace(System.out);
System.exit(1);
}
} } | public class class_name {
public static void main(String[] args) {
try {
Arguments arguments = new Arguments(args);
File root = new File(arguments.next("content"));
if (!root.isDirectory()) {
root = new File("."); // depends on control dependency: [if], data = [none]
}
String rootPath = root.getCanonicalPath();
String sip = arguments.next("build/files.zip");
new FileArchiver().run(rootPath, sip);
} catch (IOException e) {
e.printStackTrace(System.out);
System.exit(1);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public String getPrefixName() {
if (cachedPrefixName == null) {
StringBuilder buffer = new StringBuilder();
buffer.append("_").append(width).append("x").append(height);
cachedPrefixName = new String(buffer);
}
return cachedPrefixName;
} } | public class class_name {
@Override
public String getPrefixName() {
if (cachedPrefixName == null) {
StringBuilder buffer = new StringBuilder();
buffer.append("_").append(width).append("x").append(height); // depends on control dependency: [if], data = [none]
cachedPrefixName = new String(buffer); // depends on control dependency: [if], data = [none]
}
return cachedPrefixName;
} } |
public class class_name {
public byte[] getByteArray(Integer offset)
{
byte[] result = null;
if (offset != null)
{
result = m_map.get(offset);
}
return (result);
} } | public class class_name {
public byte[] getByteArray(Integer offset)
{
byte[] result = null;
if (offset != null)
{
result = m_map.get(offset); // depends on control dependency: [if], data = [(offset]
}
return (result);
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.