code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public Set<String> getUniqueWords(Object document) {
Set<String> features = new FastSet<String>();
if (document instanceof AnalyzedText){
features.addAll(((AnalyzedText)document).getUniqueWords());
if (includeLengthCategory){
features.add(((AnalyzedText)document).getLengthCategory().toString());
}
}else{
addWords(document, features);
}
return features;
} } | public class class_name {
public Set<String> getUniqueWords(Object document) {
Set<String> features = new FastSet<String>();
if (document instanceof AnalyzedText){
features.addAll(((AnalyzedText)document).getUniqueWords());
// depends on control dependency: [if], data = [none]
if (includeLengthCategory){
features.add(((AnalyzedText)document).getLengthCategory().toString());
// depends on control dependency: [if], data = [none]
}
}else{
addWords(document, features);
// depends on control dependency: [if], data = [none]
}
return features;
} } |
public class class_name {
public void start(Intent intent) {
intent = setupIntent(intent);
if (application != null) {
// Extra flag is required when starting from application:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
application.startActivity(intent);
return; // No transitions, so just return
}
if (activity != null) {
if (requestCode == NO_RESULT_CODE) {
activity.startActivity(intent);
} else {
activity.startActivityForResult(intent, requestCode);
}
} else if (fragment != null) {
if (requestCode == NO_RESULT_CODE) {
fragment.startActivity(intent);
} else {
fragment.startActivityForResult(intent, requestCode);
}
} else if (fragmentSupport != null) {
if (requestCode == NO_RESULT_CODE) {
fragmentSupport.startActivity(intent);
} else {
fragmentSupport.startActivityForResult(intent, requestCode);
}
}
setTransition(false);
} } | public class class_name {
public void start(Intent intent) {
intent = setupIntent(intent);
if (application != null) {
// Extra flag is required when starting from application:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // depends on control dependency: [if], data = [none]
application.startActivity(intent); // depends on control dependency: [if], data = [none]
return; // No transitions, so just return // depends on control dependency: [if], data = [none]
}
if (activity != null) {
if (requestCode == NO_RESULT_CODE) {
activity.startActivity(intent); // depends on control dependency: [if], data = [none]
} else {
activity.startActivityForResult(intent, requestCode); // depends on control dependency: [if], data = [none]
}
} else if (fragment != null) {
if (requestCode == NO_RESULT_CODE) {
fragment.startActivity(intent); // depends on control dependency: [if], data = [none]
} else {
fragment.startActivityForResult(intent, requestCode); // depends on control dependency: [if], data = [none]
}
} else if (fragmentSupport != null) {
if (requestCode == NO_RESULT_CODE) {
fragmentSupport.startActivity(intent); // depends on control dependency: [if], data = [none]
} else {
fragmentSupport.startActivityForResult(intent, requestCode); // depends on control dependency: [if], data = [none]
}
}
setTransition(false);
} } |
public class class_name {
private void checkAndAddLengths(final int... requiredLengths) {
for( final int length : requiredLengths ) {
if( length < 0 ) {
throw new IllegalArgumentException(String.format("required length cannot be negative but was %d",
length));
}
this.requiredLengths.add(length);
}
} } | public class class_name {
private void checkAndAddLengths(final int... requiredLengths) {
for( final int length : requiredLengths ) {
if( length < 0 ) {
throw new IllegalArgumentException(String.format("required length cannot be negative but was %d",
length));
}
this.requiredLengths.add(length); // depends on control dependency: [for], data = [length]
}
} } |
public class class_name {
private void setArgumentValue(final Object value) {
try {
getUnderlyingField().set(getContainingObject(), value);
} catch (final IllegalAccessException e) {
throw new CommandLineException.ShouldNeverReachHereException(
String.format(
"Couldn't set field value for %s in %s with value %s.",
getUnderlyingField().getName(),
getContainingObject().toString(),
value.toString()),
e);
}
} } | public class class_name {
private void setArgumentValue(final Object value) {
try {
getUnderlyingField().set(getContainingObject(), value); // depends on control dependency: [try], data = [none]
} catch (final IllegalAccessException e) {
throw new CommandLineException.ShouldNeverReachHereException(
String.format(
"Couldn't set field value for %s in %s with value %s.",
getUnderlyingField().getName(),
getContainingObject().toString(),
value.toString()),
e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static double[] toN(int n) {
double[] result = new double[n];
for (int i = 0; i < n; i++) {
result[i] = i;
}
return result;
} } | public class class_name {
public static double[] toN(int n) {
double[] result = new double[n];
for (int i = 0; i < n; i++) {
result[i] = i; // depends on control dependency: [for], data = [i]
}
return result;
} } |
public class class_name {
@Override
public Object getAttribute(String key) {
if (userAttributes == null) {
return null;
}
final List<Object> values = userAttributes.get(key);
if (values != null && values.size() > 0) {
return values.get(0);
}
return null;
} } | public class class_name {
@Override
public Object getAttribute(String key) {
if (userAttributes == null) {
return null; // depends on control dependency: [if], data = [none]
}
final List<Object> values = userAttributes.get(key);
if (values != null && values.size() > 0) {
return values.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static String uriEncode(String value, boolean encodeSlash) {
try {
StringBuilder builder = new StringBuilder();
for (byte b : value.getBytes(AipClientConst.DEFAULT_ENCODING)) {
if (URI_UNRESERVED_CHARACTERS.get(b & 0xFF)) {
builder.append((char) b);
} else {
builder.append(PERCENT_ENCODED_STRINGS[b & 0xFF]);
}
}
String encodeString = builder.toString();
if (!encodeSlash) {
return encodeString.replace("%2F", "/");
}
return encodeString;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static String uriEncode(String value, boolean encodeSlash) {
try {
StringBuilder builder = new StringBuilder();
for (byte b : value.getBytes(AipClientConst.DEFAULT_ENCODING)) {
if (URI_UNRESERVED_CHARACTERS.get(b & 0xFF)) {
builder.append((char) b); // depends on control dependency: [if], data = [none]
} else {
builder.append(PERCENT_ENCODED_STRINGS[b & 0xFF]); // depends on control dependency: [if], data = [none]
}
}
String encodeString = builder.toString();
if (!encodeSlash) {
return encodeString.replace("%2F", "/"); // depends on control dependency: [if], data = [none]
}
return encodeString; // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public Optional<TemplateContentData> load(String responseTemplateName, Input input) throws TemplateLoaderException {
TemplateEnumerator templateEnumerator = templateEnumeratorSupplier.apply(responseTemplateName, input);
while (templateEnumerator.hasNext()) {
String templateName = (String) templateEnumerator.next();
String templatePath = buildCompletePath(templateName);
try {
URI templateUri = getResourceURI(templatePath);
if (templateUri != null) {
String templateIdentifier = templateUri.toString();
TemplateContentData templateContentData = templateCache.get(templateIdentifier);
if (templateContentData == null) {
try (InputStream inputStream = getTemplateAsStream(templatePath)) {
byte[] templateByteArray = new byte[inputStream.available()];
inputStream.read(templateByteArray);
templateContentData = TemplateContentData.builder()
.withIdentifier(templateIdentifier)
.withTemplateContent(templateByteArray)
.withTemplateBaseDir(directoryPath)
.build();
} catch (IOException e) {
String message = String.format("Fail to read template file: %s with error: %s", templatePath, e.getMessage());
LOGGER.error(message);
throw new TemplateLoaderException(message);
}
templateCache.put(templateIdentifier, templateContentData);
}
return Optional.of(templateContentData);
}
} catch (URISyntaxException e) {
String message = String.format("Cannot get valid URI for template file path: %s with error: %s", templatePath, e.getMessage());
LOGGER.error(message);
throw new TemplateLoaderException(message);
}
}
String message = String.format("Cannot find template file: %s given directory path: %s and file extension: %s, returning empty.",
responseTemplateName, directoryPath, fileExtension);
LOGGER.warn(message);
return Optional.empty();
} } | public class class_name {
@Override
public Optional<TemplateContentData> load(String responseTemplateName, Input input) throws TemplateLoaderException {
TemplateEnumerator templateEnumerator = templateEnumeratorSupplier.apply(responseTemplateName, input);
while (templateEnumerator.hasNext()) {
String templateName = (String) templateEnumerator.next();
String templatePath = buildCompletePath(templateName);
try {
URI templateUri = getResourceURI(templatePath);
if (templateUri != null) {
String templateIdentifier = templateUri.toString();
TemplateContentData templateContentData = templateCache.get(templateIdentifier);
if (templateContentData == null) {
try (InputStream inputStream = getTemplateAsStream(templatePath)) {
byte[] templateByteArray = new byte[inputStream.available()];
inputStream.read(templateByteArray); // depends on control dependency: [if], data = [none]
templateContentData = TemplateContentData.builder()
.withIdentifier(templateIdentifier)
.withTemplateContent(templateByteArray)
.withTemplateBaseDir(directoryPath)
.build(); // depends on control dependency: [if], data = [none]
} catch (IOException e) { // depends on control dependency: [if], data = [none]
String message = String.format("Fail to read template file: %s with error: %s", templatePath, e.getMessage());
LOGGER.error(message);
throw new TemplateLoaderException(message);
}
templateCache.put(templateIdentifier, templateContentData); // depends on control dependency: [if], data = [none]
}
return Optional.of(templateContentData);
}
} catch (URISyntaxException e) {
String message = String.format("Cannot get valid URI for template file path: %s with error: %s", templatePath, e.getMessage());
LOGGER.error(message);
throw new TemplateLoaderException(message);
}
}
String message = String.format("Cannot find template file: %s given directory path: %s and file extension: %s, returning empty.",
responseTemplateName, directoryPath, fileExtension);
LOGGER.warn(message);
return Optional.empty();
} } |
public class class_name {
public static void assertVisiblyEquals(String message, Object expected, Object actual) {
String expectedInQuotes = inQuotesIfNotNull(expected);
String actualInQuotes = inQuotesIfNotNull(actual);
if (areBothNull(expected, actual)) {
pass(message);
} else if (isObjectEquals(String.valueOf(expected), String.valueOf(actual))) {
pass(message);
} else {
fail(message, actualInQuotes + " after toString() does not equal expected " + expectedInQuotes);
}
} } | public class class_name {
public static void assertVisiblyEquals(String message, Object expected, Object actual) {
String expectedInQuotes = inQuotesIfNotNull(expected);
String actualInQuotes = inQuotesIfNotNull(actual);
if (areBothNull(expected, actual)) {
pass(message); // depends on control dependency: [if], data = [none]
} else if (isObjectEquals(String.valueOf(expected), String.valueOf(actual))) {
pass(message); // depends on control dependency: [if], data = [none]
} else {
fail(message, actualInQuotes + " after toString() does not equal expected " + expectedInQuotes); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static QualifiedName of(Class<?> cls) {
if (cls.getEnclosingClass() != null) {
return QualifiedName.of(cls.getEnclosingClass()).nestedType(cls.getSimpleName());
} else if (cls.getPackage() != null) {
return QualifiedName.of(cls.getPackage().getName(), cls.getSimpleName());
} else {
return QualifiedName.of("", cls.getSimpleName());
}
} } | public class class_name {
public static QualifiedName of(Class<?> cls) {
if (cls.getEnclosingClass() != null) {
return QualifiedName.of(cls.getEnclosingClass()).nestedType(cls.getSimpleName()); // depends on control dependency: [if], data = [(cls.getEnclosingClass()]
} else if (cls.getPackage() != null) {
return QualifiedName.of(cls.getPackage().getName(), cls.getSimpleName()); // depends on control dependency: [if], data = [(cls.getPackage()]
} else {
return QualifiedName.of("", cls.getSimpleName()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public R applyOrElse(P1 p1, P2 p2, F2<? super P1, ? super P2, ? extends R> fallback) {
try {
return apply(p1, p2);
} catch (RuntimeException e) {
return fallback.apply(p1, p2);
}
} } | public class class_name {
public R applyOrElse(P1 p1, P2 p2, F2<? super P1, ? super P2, ? extends R> fallback) {
try {
return apply(p1, p2); // depends on control dependency: [try], data = [none]
} catch (RuntimeException e) {
return fallback.apply(p1, p2);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public WebElement getWebElement() {
List<WebElement> elements = getWebElements();
if (elements.size() > match) {
return elements.get(match);
}
String reason = this.prettyOutputStart() + " was not located on the page";
if( !elements.isEmpty() ) {
reason += ", but " + elements.size() + " elements matching the locator were. Try using a lower match";
}
throw new NoSuchElementException(reason);
} } | public class class_name {
public WebElement getWebElement() {
List<WebElement> elements = getWebElements();
if (elements.size() > match) {
return elements.get(match); // depends on control dependency: [if], data = [match)]
}
String reason = this.prettyOutputStart() + " was not located on the page";
if( !elements.isEmpty() ) {
reason += ", but " + elements.size() + " elements matching the locator were. Try using a lower match"; // depends on control dependency: [if], data = [none]
}
throw new NoSuchElementException(reason);
} } |
public class class_name {
public WorkUnitStream transform(Function<WorkUnit, WorkUnit> function) {
if (this.materializedWorkUnits == null) {
return new BasicWorkUnitStream(this, Iterators.transform(this.workUnits, function), null);
} else {
return new BasicWorkUnitStream(this, null, Lists.newArrayList(Lists.transform(this.materializedWorkUnits, function)));
}
} } | public class class_name {
public WorkUnitStream transform(Function<WorkUnit, WorkUnit> function) {
if (this.materializedWorkUnits == null) {
return new BasicWorkUnitStream(this, Iterators.transform(this.workUnits, function), null); // depends on control dependency: [if], data = [null)]
} else {
return new BasicWorkUnitStream(this, null, Lists.newArrayList(Lists.transform(this.materializedWorkUnits, function))); // depends on control dependency: [if], data = [(this.materializedWorkUnits]
}
} } |
public class class_name {
protected Map<ArtifactIdentifier, Collection<BinaryArtifact>> filterBinaryArtifacts(Map<ArtifactIdentifier, Collection<BinaryArtifact>> artifactsMap, String url, String branch) {
Map<ArtifactIdentifier, Collection<BinaryArtifact>> rt = new HashMap<>();
String urlNoNull = url != null? url : "";
String branchNoNull = branch != null? branch : "";
for (Map.Entry<ArtifactIdentifier, Collection<BinaryArtifact>> e : artifactsMap.entrySet()) {
ArtifactIdentifier id = e.getKey();
List<BinaryArtifact> artifacts = new ArrayList<>();
boolean added = false;
for (BinaryArtifact ba : e.getValue()) {
String baUrl = ba.getScmUrl();
String baBranch = ba.getScmBranch();
if (HygieiaUtils.smartUrlEquals(urlNoNull, baUrl) && ObjectUtils.equals(branchNoNull, baBranch)) {
artifacts.add(ba);
added = true;
break;
}
}
if (logger.isDebugEnabled() && !added) {
StringBuilder sb = new StringBuilder();
sb.append("Ignoring artifact identifier " + id.getGroup() + ":" + id.getName() + ":" + id.getVersion()
+ " since it does not correspond to any artifacts that use the component's repository\n");
sb.append("Component repo: (url: " + url + " branch: " + branch + ")\n");
sb.append("Artifacts:\n");
boolean hasPrinted = false;
for (BinaryArtifact ba : e.getValue()) {
sb.append(" " + ba.getArtifactGroupId() + ":" + ba.getArtifactName() + ":" + ba.getArtifactVersion()
+ " " + "(url: " + ba.getScmUrl() + " branch: " + ba.getScmBranch() + ")\n");
hasPrinted = true;
}
if (!hasPrinted) {
sb.append("(None)\n");
}
logger.debug(sb.toString());
}
if (!artifacts.isEmpty()) {
rt.put(e.getKey(), artifacts);
}
}
return rt;
} } | public class class_name {
protected Map<ArtifactIdentifier, Collection<BinaryArtifact>> filterBinaryArtifacts(Map<ArtifactIdentifier, Collection<BinaryArtifact>> artifactsMap, String url, String branch) {
Map<ArtifactIdentifier, Collection<BinaryArtifact>> rt = new HashMap<>();
String urlNoNull = url != null? url : "";
String branchNoNull = branch != null? branch : "";
for (Map.Entry<ArtifactIdentifier, Collection<BinaryArtifact>> e : artifactsMap.entrySet()) {
ArtifactIdentifier id = e.getKey();
List<BinaryArtifact> artifacts = new ArrayList<>();
boolean added = false;
for (BinaryArtifact ba : e.getValue()) {
String baUrl = ba.getScmUrl();
String baBranch = ba.getScmBranch();
if (HygieiaUtils.smartUrlEquals(urlNoNull, baUrl) && ObjectUtils.equals(branchNoNull, baBranch)) {
artifacts.add(ba);
// depends on control dependency: [if], data = [none]
added = true;
// depends on control dependency: [if], data = [none]
break;
}
}
if (logger.isDebugEnabled() && !added) {
StringBuilder sb = new StringBuilder();
sb.append("Ignoring artifact identifier " + id.getGroup() + ":" + id.getName() + ":" + id.getVersion()
+ " since it does not correspond to any artifacts that use the component's repository\n");
// depends on control dependency: [if], data = [none]
sb.append("Component repo: (url: " + url + " branch: " + branch + ")\n");
sb.append("Artifacts:\n");
// depends on control dependency: [if], data = [none]
boolean hasPrinted = false;
for (BinaryArtifact ba : e.getValue()) {
sb.append(" " + ba.getArtifactGroupId() + ":" + ba.getArtifactName() + ":" + ba.getArtifactVersion()
+ " " + "(url: " + ba.getScmUrl() + " branch: " + ba.getScmBranch() + ")\n");
// depends on control dependency: [for], data = [ba]
hasPrinted = true;
// depends on control dependency: [for], data = [none]
}
if (!hasPrinted) {
sb.append("(None)\n");
// depends on control dependency: [if], data = [none]
}
logger.debug(sb.toString());
// depends on control dependency: [if], data = [none]
}
if (!artifacts.isEmpty()) {
rt.put(e.getKey(), artifacts);
// depends on control dependency: [if], data = [none]
}
}
return rt;
} } |
public class class_name {
public void probeRequest(PrintStream ps, ReqState rs)
{
Enumeration e;
int i;
HttpServletRequest request = rs.getRequest();
ps.println("####################### PROBE ##################################");
ps.println("The HttpServletRequest object is actually a: " + request.getClass().getName());
ps.println("");
ps.println("HttpServletRequest Interface:");
ps.println(" getAuthType: " + request.getAuthType());
ps.println(" getMethod: " + request.getMethod());
ps.println(" getPathInfo: " + request.getPathInfo());
ps.println(" getPathTranslated: " + request.getPathTranslated());
ps.println(" getRequestURL: " + request.getRequestURL());
ps.println(" getQueryString: " + request.getQueryString());
ps.println(" getRemoteUser: " + request.getRemoteUser());
ps.println(" getRequestedSessionId: " + request.getRequestedSessionId());
ps.println(" getRequestURI: " + request.getRequestURI());
ps.println(" getServletPath: " + request.getServletPath());
ps.println(" isRequestedSessionIdFromCookie: " + request.isRequestedSessionIdFromCookie());
ps.println(" isRequestedSessionIdValid: " + request.isRequestedSessionIdValid());
ps.println(" isRequestedSessionIdFromURL: " + request.isRequestedSessionIdFromURL());
ps.println("");
i = 0;
e = request.getHeaderNames();
ps.println(" Header Names:");
while(e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Header[" + i + "]: " + s);
ps.println(": " + request.getHeader(s));
}
ps.println("");
ps.println("ServletRequest Interface:");
ps.println(" getCharacterEncoding: " + request.getCharacterEncoding());
ps.println(" getContentType: " + request.getContentType());
ps.println(" getContentLength: " + request.getContentLength());
ps.println(" getProtocol: " + request.getProtocol());
ps.println(" getScheme: " + request.getScheme());
ps.println(" getServerName: " + request.getServerName());
ps.println(" getServerPort: " + request.getServerPort());
ps.println(" getRemoteAddr: " + request.getRemoteAddr());
ps.println(" getRemoteHost: " + request.getRemoteHost());
//ps.println(" getRealPath: "+request.getRealPath());
ps.println(".............................");
ps.println("");
i = 0;
e = request.getAttributeNames();
ps.println(" Attribute Names:");
while(e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Attribute[" + i + "]: " + s);
ps.println(" Type: " + request.getAttribute(s));
}
ps.println(".............................");
ps.println("");
i = 0;
e = request.getParameterNames();
ps.println(" Parameter Names:");
while(e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Parameter[" + i + "]: " + s);
ps.println(" Value: " + request.getParameter(s));
}
ps.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
ps.println(" . . . . . . . . . Servlet Infomation API . . . . . . . . . . . . . .");
ps.println("");
ps.println("Servlet Context:");
ps.println("");
i = 0;
e = servletContext.getAttributeNames();
ps.println(" Attribute Names:");
while(e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Attribute[" + i + "]: " + s);
ps.println(" Type: " + servletContext.getAttribute(s));
}
ps.println(" ServletContext.getRealPath(\".\"): " + servletContext.getRealPath("."));
ps.println(" ServletContext.getMajorVersion(): " + servletContext.getMajorVersion());
// ps.println("ServletContext.getMimeType(): " + sc.getMimeType());
ps.println(" ServletContext.getMinorVersion(): " + servletContext.getMinorVersion());
// ps.println("ServletContext.getRealPath(): " + sc.getRealPath());
ps.println(".............................");
ps.println("Servlet Config:");
ps.println("");
ServletConfig scnfg = getServletConfig();
i = 0;
e = scnfg.getInitParameterNames();
ps.println(" InitParameters:");
while(e.hasMoreElements()) {
String p = (String) e.nextElement();
ps.print(" InitParameter[" + i + "]: " + p);
ps.println(" Value: " + scnfg.getInitParameter(p));
i++;
}
ps.println("");
ps.println("######################## END PROBE ###############################");
ps.println("");
} } | public class class_name {
public void probeRequest(PrintStream ps, ReqState rs)
{
Enumeration e;
int i;
HttpServletRequest request = rs.getRequest();
ps.println("####################### PROBE ##################################");
ps.println("The HttpServletRequest object is actually a: " + request.getClass().getName());
ps.println("");
ps.println("HttpServletRequest Interface:");
ps.println(" getAuthType: " + request.getAuthType());
ps.println(" getMethod: " + request.getMethod());
ps.println(" getPathInfo: " + request.getPathInfo());
ps.println(" getPathTranslated: " + request.getPathTranslated());
ps.println(" getRequestURL: " + request.getRequestURL());
ps.println(" getQueryString: " + request.getQueryString());
ps.println(" getRemoteUser: " + request.getRemoteUser());
ps.println(" getRequestedSessionId: " + request.getRequestedSessionId());
ps.println(" getRequestURI: " + request.getRequestURI());
ps.println(" getServletPath: " + request.getServletPath());
ps.println(" isRequestedSessionIdFromCookie: " + request.isRequestedSessionIdFromCookie());
ps.println(" isRequestedSessionIdValid: " + request.isRequestedSessionIdValid());
ps.println(" isRequestedSessionIdFromURL: " + request.isRequestedSessionIdFromURL());
ps.println("");
i = 0;
e = request.getHeaderNames();
ps.println(" Header Names:");
while(e.hasMoreElements()) {
i++; // depends on control dependency: [while], data = [none]
String s = (String) e.nextElement();
ps.print(" Header[" + i + "]: " + s); // depends on control dependency: [while], data = [none]
ps.println(": " + request.getHeader(s)); // depends on control dependency: [while], data = [none]
}
ps.println("");
ps.println("ServletRequest Interface:");
ps.println(" getCharacterEncoding: " + request.getCharacterEncoding());
ps.println(" getContentType: " + request.getContentType());
ps.println(" getContentLength: " + request.getContentLength());
ps.println(" getProtocol: " + request.getProtocol());
ps.println(" getScheme: " + request.getScheme());
ps.println(" getServerName: " + request.getServerName());
ps.println(" getServerPort: " + request.getServerPort());
ps.println(" getRemoteAddr: " + request.getRemoteAddr());
ps.println(" getRemoteHost: " + request.getRemoteHost());
//ps.println(" getRealPath: "+request.getRealPath());
ps.println(".............................");
ps.println("");
i = 0;
e = request.getAttributeNames();
ps.println(" Attribute Names:");
while(e.hasMoreElements()) {
i++; // depends on control dependency: [while], data = [none]
String s = (String) e.nextElement();
ps.print(" Attribute[" + i + "]: " + s); // depends on control dependency: [while], data = [none]
ps.println(" Type: " + request.getAttribute(s)); // depends on control dependency: [while], data = [none]
}
ps.println(".............................");
ps.println("");
i = 0;
e = request.getParameterNames();
ps.println(" Parameter Names:");
while(e.hasMoreElements()) {
i++; // depends on control dependency: [while], data = [none]
String s = (String) e.nextElement();
ps.print(" Parameter[" + i + "]: " + s); // depends on control dependency: [while], data = [none]
ps.println(" Value: " + request.getParameter(s)); // depends on control dependency: [while], data = [none]
}
ps.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
ps.println(" . . . . . . . . . Servlet Infomation API . . . . . . . . . . . . . .");
ps.println("");
ps.println("Servlet Context:");
ps.println("");
i = 0;
e = servletContext.getAttributeNames();
ps.println(" Attribute Names:");
while(e.hasMoreElements()) {
i++;
String s = (String) e.nextElement();
ps.print(" Attribute[" + i + "]: " + s);
ps.println(" Type: " + servletContext.getAttribute(s));
}
ps.println(" ServletContext.getRealPath(\".\"): " + servletContext.getRealPath("."));
ps.println(" ServletContext.getMajorVersion(): " + servletContext.getMajorVersion());
// ps.println("ServletContext.getMimeType(): " + sc.getMimeType());
ps.println(" ServletContext.getMinorVersion(): " + servletContext.getMinorVersion());
// ps.println("ServletContext.getRealPath(): " + sc.getRealPath());
ps.println(".............................");
ps.println("Servlet Config:");
ps.println("");
ServletConfig scnfg = getServletConfig();
i = 0;
e = scnfg.getInitParameterNames();
ps.println(" InitParameters:");
while(e.hasMoreElements()) {
String p = (String) e.nextElement();
ps.print(" InitParameter[" + i + "]: " + p);
ps.println(" Value: " + scnfg.getInitParameter(p));
i++;
}
ps.println("");
ps.println("######################## END PROBE ###############################");
ps.println("");
} } |
public class class_name {
public static boolean copyFile(File srcFile, File destFile) {
boolean result = false;
try {
InputStream in = new FileInputStream(srcFile);
try {
result = copyToFile(in, destFile);
} finally {
in.close();
}
} catch (IOException e) {
result = false;
}
return result;
} } | public class class_name {
public static boolean copyFile(File srcFile, File destFile) {
boolean result = false;
try {
InputStream in = new FileInputStream(srcFile);
try {
result = copyToFile(in, destFile); // depends on control dependency: [try], data = [none]
} finally {
in.close();
}
} catch (IOException e) {
result = false;
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
static public String getVariableName(NetcdfDataset ds, String key, Formatter errlog) {
Variable v = null;
String vs = getLiteral(ds, key, errlog);
if (vs != null) {
v = ds.findVariable(vs);
if ((v == null) && (errlog != null))
errlog.format(" Cant find Variable %s from %s%n", vs, key);
}
return v == null ? null : v.getShortName();
} } | public class class_name {
static public String getVariableName(NetcdfDataset ds, String key, Formatter errlog) {
Variable v = null;
String vs = getLiteral(ds, key, errlog);
if (vs != null) {
v = ds.findVariable(vs);
// depends on control dependency: [if], data = [(vs]
if ((v == null) && (errlog != null))
errlog.format(" Cant find Variable %s from %s%n", vs, key);
}
return v == null ? null : v.getShortName();
} } |
public class class_name {
public ProcessDefinitionCacheEntry resolveProcessDefinition(ProcessDefinition processDefinition) {
String processDefinitionId = processDefinition.getId();
String deploymentId = processDefinition.getDeploymentId();
ProcessDefinitionCacheEntry cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);
if (cachedProcessDefinition == null) {
CommandContext commandContext = Context.getCommandContext();
DeploymentEntity deployment = deploymentEntityManager.findById(deploymentId);
deployment.setNew(false);
deploy(deployment, null);
cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);
if (cachedProcessDefinition == null) {
throw new ActivitiException("deployment '" + deploymentId + "' didn't put process definition '" + processDefinitionId + "' in the cache");
}
}
return cachedProcessDefinition;
} } | public class class_name {
public ProcessDefinitionCacheEntry resolveProcessDefinition(ProcessDefinition processDefinition) {
String processDefinitionId = processDefinition.getId();
String deploymentId = processDefinition.getDeploymentId();
ProcessDefinitionCacheEntry cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);
if (cachedProcessDefinition == null) {
CommandContext commandContext = Context.getCommandContext();
DeploymentEntity deployment = deploymentEntityManager.findById(deploymentId);
deployment.setNew(false); // depends on control dependency: [if], data = [none]
deploy(deployment, null); // depends on control dependency: [if], data = [null)]
cachedProcessDefinition = processDefinitionCache.get(processDefinitionId); // depends on control dependency: [if], data = [none]
if (cachedProcessDefinition == null) {
throw new ActivitiException("deployment '" + deploymentId + "' didn't put process definition '" + processDefinitionId + "' in the cache");
}
}
return cachedProcessDefinition;
} } |
public class class_name {
@SuppressWarnings("unchecked")
protected Collection<IClient> getClients() {
if (!hasClients()) {
// avoid creating new Collection object if no clients exist.
return Collections.EMPTY_SET;
}
return Collections.unmodifiableCollection(clients.values());
} } | public class class_name {
@SuppressWarnings("unchecked")
protected Collection<IClient> getClients() {
if (!hasClients()) {
// avoid creating new Collection object if no clients exist.
return Collections.EMPTY_SET;
// depends on control dependency: [if], data = [none]
}
return Collections.unmodifiableCollection(clients.values());
} } |
public class class_name {
public static Map<String, String> read(final String path) {
Map<String, String> map = new HashMap<String, String>();
if (path != null) {
try {
Properties p = loadProperties(path);
for (Object key : p.keySet()) {
String value = p.getProperty(String.valueOf(key));
// remove single/double quotes
if ((value.startsWith("\"") && value.endsWith("\"")) ||
(value.startsWith("\'") && value.endsWith("\'"))) {
value = value.substring(1, value.length() - 1);
}
value = value.trim();
if (!value.equals("")) {
map.put(String.valueOf(key), value);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return map;
} } | public class class_name {
public static Map<String, String> read(final String path) {
Map<String, String> map = new HashMap<String, String>();
if (path != null) {
try {
Properties p = loadProperties(path);
for (Object key : p.keySet()) {
String value = p.getProperty(String.valueOf(key));
// remove single/double quotes
if ((value.startsWith("\"") && value.endsWith("\"")) ||
(value.startsWith("\'") && value.endsWith("\'"))) {
value = value.substring(1, value.length() - 1); // depends on control dependency: [if], data = [none]
}
value = value.trim(); // depends on control dependency: [for], data = [none]
if (!value.equals("")) {
map.put(String.valueOf(key), value); // depends on control dependency: [if], data = [none]
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
return map;
} } |
public class class_name {
public CreateJobRequest withOutputs(CreateJobOutput... outputs) {
if (this.outputs == null) {
setOutputs(new com.amazonaws.internal.SdkInternalList<CreateJobOutput>(outputs.length));
}
for (CreateJobOutput ele : outputs) {
this.outputs.add(ele);
}
return this;
} } | public class class_name {
public CreateJobRequest withOutputs(CreateJobOutput... outputs) {
if (this.outputs == null) {
setOutputs(new com.amazonaws.internal.SdkInternalList<CreateJobOutput>(outputs.length)); // depends on control dependency: [if], data = [none]
}
for (CreateJobOutput ele : outputs) {
this.outputs.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
void selectJobsToInitialize() {
for (String queue : jobQueues.keySet()) {
ArrayList<JobInProgress> jobsToInitialize = getJobsToInitialize(queue);
printJobs(jobsToInitialize);
JobInitializationThread t = threadsToQueueMap.get(queue);
for (JobInProgress job : jobsToInitialize) {
t.addJobsToQueue(queue, job);
}
}
} } | public class class_name {
void selectJobsToInitialize() {
for (String queue : jobQueues.keySet()) {
ArrayList<JobInProgress> jobsToInitialize = getJobsToInitialize(queue);
printJobs(jobsToInitialize); // depends on control dependency: [for], data = [none]
JobInitializationThread t = threadsToQueueMap.get(queue);
for (JobInProgress job : jobsToInitialize) {
t.addJobsToQueue(queue, job); // depends on control dependency: [for], data = [job]
}
}
} } |
public class class_name {
public static JSONObject getJsonParameterMap(Map<String, String[]> params) {
JSONObject result = new JSONObject();
for (Map.Entry<String, String[]> entry : params.entrySet()) {
String paramKey = entry.getKey();
JSONArray paramValue = new JSONArray();
for (int i = 0, l = entry.getValue().length; i < l; i++) {
paramValue.put(entry.getValue()[i]);
}
try {
result.putOpt(paramKey, paramValue);
} catch (JSONException e) {
// should never happen
LOG.warn(e.getLocalizedMessage(), e);
}
}
return result;
} } | public class class_name {
public static JSONObject getJsonParameterMap(Map<String, String[]> params) {
JSONObject result = new JSONObject();
for (Map.Entry<String, String[]> entry : params.entrySet()) {
String paramKey = entry.getKey();
JSONArray paramValue = new JSONArray();
for (int i = 0, l = entry.getValue().length; i < l; i++) {
paramValue.put(entry.getValue()[i]); // depends on control dependency: [for], data = [i]
}
try {
result.putOpt(paramKey, paramValue); // depends on control dependency: [try], data = [none]
} catch (JSONException e) {
// should never happen
LOG.warn(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
return result;
} } |
public class class_name {
Set<String> getValues(RequestType pType, ObjectName pName) {
if (RequestType.READ == pType) {
return readAttributes.get(pName);
} else if (RequestType.WRITE == pType) {
return writeAttributes.get(pName);
} else if (RequestType.EXEC == pType) {
return operations.get(pName);
} else {
throw new IllegalArgumentException("Invalid type " + pType);
}
} } | public class class_name {
Set<String> getValues(RequestType pType, ObjectName pName) {
if (RequestType.READ == pType) {
return readAttributes.get(pName); // depends on control dependency: [if], data = [none]
} else if (RequestType.WRITE == pType) {
return writeAttributes.get(pName); // depends on control dependency: [if], data = [none]
} else if (RequestType.EXEC == pType) {
return operations.get(pName); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Invalid type " + pType);
}
} } |
public class class_name {
private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {
// updates the coordinator metadata with recent stores and cluster xml
updateCoordinatorMetadataWithLatestState();
logger.info("Creating a Fat client for store: " + storeName);
SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),
storeClientProps);
if(this.fatClientMap == null) {
this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();
}
DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,
fatClientFactory,
1,
this.coordinatorMetadata.getStoreDefs(),
this.coordinatorMetadata.getClusterXmlStr());
this.fatClientMap.put(storeName, fatClient);
} } | public class class_name {
private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {
// updates the coordinator metadata with recent stores and cluster xml
updateCoordinatorMetadataWithLatestState();
logger.info("Creating a Fat client for store: " + storeName);
SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),
storeClientProps);
if(this.fatClientMap == null) {
this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>(); // depends on control dependency: [if], data = [none]
}
DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,
fatClientFactory,
1,
this.coordinatorMetadata.getStoreDefs(),
this.coordinatorMetadata.getClusterXmlStr());
this.fatClientMap.put(storeName, fatClient);
} } |
public class class_name {
public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) {
Resources res = context.getResources();
Duration duration = readableDuration.toDuration();
final int hours = (int) duration.getStandardHours();
if (hours != 0) {
return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours);
}
final int minutes = (int) duration.getStandardMinutes();
if (minutes != 0) {
return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes);
}
final int seconds = (int) duration.getStandardSeconds();
return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds);
} } | public class class_name {
public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) {
Resources res = context.getResources();
Duration duration = readableDuration.toDuration();
final int hours = (int) duration.getStandardHours();
if (hours != 0) {
return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours); // depends on control dependency: [if], data = [none]
}
final int minutes = (int) duration.getStandardMinutes();
if (minutes != 0) {
return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes); // depends on control dependency: [if], data = [none]
}
final int seconds = (int) duration.getStandardSeconds();
return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds);
} } |
public class class_name {
static int sizeImpl(Multiset<?> multiset) {
long size = 0;
for (Entry<?> entry : multiset.entrySet()) {
size += entry.getCount();
}
return Ints.saturatedCast(size);
} } | public class class_name {
static int sizeImpl(Multiset<?> multiset) {
long size = 0;
for (Entry<?> entry : multiset.entrySet()) {
size += entry.getCount(); // depends on control dependency: [for], data = [entry]
}
return Ints.saturatedCast(size);
} } |
public class class_name {
private int selectCoords(Collection<Point2d[]> ps, Point2d[] coords, IRing macrocycle, IRingSet ringset) {
assert ps.size() != 0;
final int[] winding = new int[coords.length];
MacroScore best = null;
for (Point2d[] p : ps) {
final int wind = winding(p, winding);
MacroScore score = bestScore(macrocycle, ringset, wind, winding);
if (score.compareTo(best) < 0) {
best = score;
System.arraycopy(p, 0, coords, 0, p.length);
}
}
// never null
return best != null ? best.offset : 0;
} } | public class class_name {
private int selectCoords(Collection<Point2d[]> ps, Point2d[] coords, IRing macrocycle, IRingSet ringset) {
assert ps.size() != 0;
final int[] winding = new int[coords.length];
MacroScore best = null;
for (Point2d[] p : ps) {
final int wind = winding(p, winding);
MacroScore score = bestScore(macrocycle, ringset, wind, winding);
if (score.compareTo(best) < 0) {
best = score; // depends on control dependency: [if], data = [none]
System.arraycopy(p, 0, coords, 0, p.length); // depends on control dependency: [if], data = [none]
}
}
// never null
return best != null ? best.offset : 0;
} } |
public class class_name {
private static Class<Object> guessMBeanInterface(Object instance) {
Class<Object> mbeanInterface = null;
Class<Object>[] interfaces = (Class<Object>[])instance.getClass().getInterfaces();
for (Class<Object> anInterface : interfaces) {
if (anInterface.getName().endsWith("MBean")) {
mbeanInterface = anInterface;
break;
}
}
if (mbeanInterface == null) {
throw new IllegalArgumentException("Can not find the MBean interface of class " + instance.getClass().getName());
}
return mbeanInterface;
} } | public class class_name {
private static Class<Object> guessMBeanInterface(Object instance) {
Class<Object> mbeanInterface = null;
Class<Object>[] interfaces = (Class<Object>[])instance.getClass().getInterfaces();
for (Class<Object> anInterface : interfaces) {
if (anInterface.getName().endsWith("MBean")) {
mbeanInterface = anInterface; // depends on control dependency: [if], data = [none]
break;
}
}
if (mbeanInterface == null) {
throw new IllegalArgumentException("Can not find the MBean interface of class " + instance.getClass().getName());
}
return mbeanInterface;
} } |
public class class_name {
public void setEdges(java.util.Collection<Edge> edges) {
if (edges == null) {
this.edges = null;
return;
}
this.edges = new java.util.ArrayList<Edge>(edges);
} } | public class class_name {
public void setEdges(java.util.Collection<Edge> edges) {
if (edges == null) {
this.edges = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.edges = new java.util.ArrayList<Edge>(edges);
} } |
public class class_name {
public static float toFloat(final String str, final float defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Float.parseFloat(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
} } | public class class_name {
public static float toFloat(final String str, final float defaultValue) {
if (str == null) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
try {
return Float.parseFloat(str); // depends on control dependency: [try], data = [none]
} catch (final NumberFormatException nfe) {
return defaultValue;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void initialize() {
if (Ignition.state() == IgniteState.STOPPED) {
this.ignite = Ignition.start(igniteConfiguration);
LOGGER.debug("Starting ignite cache engine");
} else if (Ignition.state() == IgniteState.STARTED) {
this.ignite = Ignition.ignite();
LOGGER.debug("Ignite cache engine has started");
}
} } | public class class_name {
public void initialize() {
if (Ignition.state() == IgniteState.STOPPED) {
this.ignite = Ignition.start(igniteConfiguration); // depends on control dependency: [if], data = [none]
LOGGER.debug("Starting ignite cache engine"); // depends on control dependency: [if], data = [none]
} else if (Ignition.state() == IgniteState.STARTED) {
this.ignite = Ignition.ignite(); // depends on control dependency: [if], data = [none]
LOGGER.debug("Ignite cache engine has started"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static void findMethodSignatures(String code, Set<String> signatures) {
if (code == null) {
return;
}
Matcher matcher = OBJC_METHOD_DECL_PATTERN.matcher(code);
while (matcher.find()) {
StringBuilder signature = new StringBuilder();
signature.append(matcher.group(1));
if (matcher.group(2) != null) {
signature.append(':');
String additionalParams = matcher.group(3);
if (additionalParams != null) {
Matcher paramsMatcher = ADDITIONAL_PARAM_PATTERN.matcher(additionalParams);
while (paramsMatcher.find()) {
signature.append(paramsMatcher.group(1)).append(':');
}
}
}
signatures.add(signature.toString());
}
} } | public class class_name {
private static void findMethodSignatures(String code, Set<String> signatures) {
if (code == null) {
return; // depends on control dependency: [if], data = [none]
}
Matcher matcher = OBJC_METHOD_DECL_PATTERN.matcher(code);
while (matcher.find()) {
StringBuilder signature = new StringBuilder();
signature.append(matcher.group(1)); // depends on control dependency: [while], data = [none]
if (matcher.group(2) != null) {
signature.append(':'); // depends on control dependency: [if], data = [none]
String additionalParams = matcher.group(3);
if (additionalParams != null) {
Matcher paramsMatcher = ADDITIONAL_PARAM_PATTERN.matcher(additionalParams);
while (paramsMatcher.find()) {
signature.append(paramsMatcher.group(1)).append(':'); // depends on control dependency: [while], data = [none]
}
}
}
signatures.add(signature.toString()); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
private void uploadJsonRevision(final RevisionInternal rev) {
// Get the revision's properties:
if (!db.inlineFollowingAttachmentsIn(rev)) {
setError(new CouchbaseLiteException(Status.BAD_ATTACHMENT));
return;
}
final String path = String.format(Locale.ENGLISH, "%s?new_edits=false", encodeDocumentId(rev.getDocID()));
CustomFuture future = sendAsyncRequest("PUT",
path,
rev.getProperties(),
new RemoteRequestCompletion() {
public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
if (e != null) {
setError(e);
} else {
Log.v(TAG, "%s: Sent %s (JSON), response=%s", this, rev, result);
removePending(rev);
}
}
});
future.setQueue(pendingFutures);
pendingFutures.add(future);
} } | public class class_name {
private void uploadJsonRevision(final RevisionInternal rev) {
// Get the revision's properties:
if (!db.inlineFollowingAttachmentsIn(rev)) {
setError(new CouchbaseLiteException(Status.BAD_ATTACHMENT)); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final String path = String.format(Locale.ENGLISH, "%s?new_edits=false", encodeDocumentId(rev.getDocID()));
CustomFuture future = sendAsyncRequest("PUT",
path,
rev.getProperties(),
new RemoteRequestCompletion() {
public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
if (e != null) {
setError(e); // depends on control dependency: [if], data = [(e]
} else {
Log.v(TAG, "%s: Sent %s (JSON), response=%s", this, rev, result); // depends on control dependency: [if], data = [none]
removePending(rev); // depends on control dependency: [if], data = [none]
}
}
});
future.setQueue(pendingFutures);
pendingFutures.add(future);
} } |
public class class_name {
@Override
public String getResourcePath(String basePath, String relativePath) {
String result = null;
if (binaryGeneratorRegistry.isGeneratedBinaryResource(relativePath)) {
result = relativePath;
} else if (contextPath != null && relativePath.startsWith(contextPath)) {
result = relativePath.substring(contextPath.length() - 1);
} else {
result = PathNormalizer.concatWebPath(basePath, relativePath);
}
return result;
} } | public class class_name {
@Override
public String getResourcePath(String basePath, String relativePath) {
String result = null;
if (binaryGeneratorRegistry.isGeneratedBinaryResource(relativePath)) {
result = relativePath; // depends on control dependency: [if], data = [none]
} else if (contextPath != null && relativePath.startsWith(contextPath)) {
result = relativePath.substring(contextPath.length() - 1); // depends on control dependency: [if], data = [(contextPath]
} else {
result = PathNormalizer.concatWebPath(basePath, relativePath); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public PointerDensityHierarchyRepresentationResult run(Database db, Relation<O> relation) {
final DistanceQuery<O> distQ = db.getDistanceQuery(relation, getDistanceFunction());
final KNNQuery<O> knnQ = db.getKNNQuery(distQ, minPts);
// We need array addressing later.
final ArrayDBIDs ids = DBIDUtil.ensureArray(relation.getDBIDs());
// Compute the core distances
// minPts + 1: ignore query point.
final WritableDoubleDataStore coredists = computeCoreDists(ids, knnQ, minPts);
WritableDBIDDataStore pi = DataStoreUtil.makeDBIDStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_STATIC);
WritableDoubleDataStore lambda = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_STATIC, Double.POSITIVE_INFINITY);
// Temporary storage for m.
WritableDoubleDataStore m = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP);
FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("Running HDBSCAN*-SLINK", ids.size(), LOG) : null;
// has to be an array for monotonicity reasons!
ModifiableDBIDs processedIDs = DBIDUtil.newArray(ids.size());
for(DBIDIter id = ids.iter(); id.valid(); id.advance()) {
// Steps 1,3,4 are exactly as in SLINK
step1(id, pi, lambda);
// Step 2 is modified to use a different distance
step2(id, processedIDs, distQ, coredists, m);
step3(id, pi, lambda, processedIDs, m);
step4(id, pi, lambda, processedIDs);
processedIDs.add(id);
LOG.incrementProcessed(progress);
}
LOG.ensureCompleted(progress);
return new PointerDensityHierarchyRepresentationResult(ids, pi, lambda, distQ.getDistanceFunction().isSquared(), coredists);
} } | public class class_name {
public PointerDensityHierarchyRepresentationResult run(Database db, Relation<O> relation) {
final DistanceQuery<O> distQ = db.getDistanceQuery(relation, getDistanceFunction());
final KNNQuery<O> knnQ = db.getKNNQuery(distQ, minPts);
// We need array addressing later.
final ArrayDBIDs ids = DBIDUtil.ensureArray(relation.getDBIDs());
// Compute the core distances
// minPts + 1: ignore query point.
final WritableDoubleDataStore coredists = computeCoreDists(ids, knnQ, minPts);
WritableDBIDDataStore pi = DataStoreUtil.makeDBIDStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_STATIC);
WritableDoubleDataStore lambda = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_STATIC, Double.POSITIVE_INFINITY);
// Temporary storage for m.
WritableDoubleDataStore m = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP);
FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("Running HDBSCAN*-SLINK", ids.size(), LOG) : null;
// has to be an array for monotonicity reasons!
ModifiableDBIDs processedIDs = DBIDUtil.newArray(ids.size());
for(DBIDIter id = ids.iter(); id.valid(); id.advance()) {
// Steps 1,3,4 are exactly as in SLINK
step1(id, pi, lambda); // depends on control dependency: [for], data = [id]
// Step 2 is modified to use a different distance
step2(id, processedIDs, distQ, coredists, m); // depends on control dependency: [for], data = [id]
step3(id, pi, lambda, processedIDs, m); // depends on control dependency: [for], data = [id]
step4(id, pi, lambda, processedIDs); // depends on control dependency: [for], data = [id]
processedIDs.add(id); // depends on control dependency: [for], data = [id]
LOG.incrementProcessed(progress); // depends on control dependency: [for], data = [none]
}
LOG.ensureCompleted(progress);
return new PointerDensityHierarchyRepresentationResult(ids, pi, lambda, distQ.getDistanceFunction().isSquared(), coredists);
} } |
public class class_name {
public static ResourceCalculatorPlugin getResourceCalculatorPlugin(
Class<? extends ResourceCalculatorPlugin> clazz, Configuration conf) {
if (clazz != null) {
return ReflectionUtils.newInstance(clazz, conf);
}
// No class given, try a os specific class
try {
String osName = System.getProperty("os.name");
if (osName.startsWith("Linux")) {
return new LinuxResourceCalculatorPlugin();
}
} catch (SecurityException se) {
// Failed to get Operating System name.
return new NullResourceCalculatorPlugin();
}
// Not supported on this system.
return new NullResourceCalculatorPlugin();
} } | public class class_name {
public static ResourceCalculatorPlugin getResourceCalculatorPlugin(
Class<? extends ResourceCalculatorPlugin> clazz, Configuration conf) {
if (clazz != null) {
return ReflectionUtils.newInstance(clazz, conf); // depends on control dependency: [if], data = [(clazz]
}
// No class given, try a os specific class
try {
String osName = System.getProperty("os.name");
if (osName.startsWith("Linux")) {
return new LinuxResourceCalculatorPlugin(); // depends on control dependency: [if], data = [none]
}
} catch (SecurityException se) {
// Failed to get Operating System name.
return new NullResourceCalculatorPlugin();
} // depends on control dependency: [catch], data = [none]
// Not supported on this system.
return new NullResourceCalculatorPlugin();
} } |
public class class_name {
public Date cookieExpiration(String expectedCookieName) {
Cookie cookie = cookie(expectedCookieName);
if (cookie != null) {
return cookie.getExpiry();
}
return null;
} } | public class class_name {
public Date cookieExpiration(String expectedCookieName) {
Cookie cookie = cookie(expectedCookieName);
if (cookie != null) {
return cookie.getExpiry(); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
static String parseRoleIdentifier(final String trackingId)
{
if (StringUtil.isNullOrWhiteSpace(trackingId) || !trackingId.contains(TRACKING_ID_TOKEN_SEPARATOR))
{
return null;
}
return trackingId.substring(trackingId.indexOf(TRACKING_ID_TOKEN_SEPARATOR));
} } | public class class_name {
static String parseRoleIdentifier(final String trackingId)
{
if (StringUtil.isNullOrWhiteSpace(trackingId) || !trackingId.contains(TRACKING_ID_TOKEN_SEPARATOR))
{
return null; // depends on control dependency: [if], data = [none]
}
return trackingId.substring(trackingId.indexOf(TRACKING_ID_TOKEN_SEPARATOR));
} } |
public class class_name {
private boolean isProfilingHeader(final String confidentialData, final ILoggingEvent event) {
if (!LOGGING_FILTER_NAME.equals(event.getLoggerName())) {
return false;
}
for (final ProfilingFeatureType profileType : ProfilingFeatureType.values()) {
// See ProfilingDataItem#getKey
if (confidentialData.startsWith("\"" + profileType.name() + ":")) {
return true;
}
}
return false;
} } | public class class_name {
private boolean isProfilingHeader(final String confidentialData, final ILoggingEvent event) {
if (!LOGGING_FILTER_NAME.equals(event.getLoggerName())) {
return false; // depends on control dependency: [if], data = [none]
}
for (final ProfilingFeatureType profileType : ProfilingFeatureType.values()) {
// See ProfilingDataItem#getKey
if (confidentialData.startsWith("\"" + profileType.name() + ":")) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new PriorityBlockingQueue<E>(Collections2.cast(elements));
}
PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<E>();
Iterables.addAll(queue, elements);
return queue;
} } | public class class_name {
public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new PriorityBlockingQueue<E>(Collections2.cast(elements)); // depends on control dependency: [if], data = [none]
}
PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<E>();
Iterables.addAll(queue, elements);
return queue;
} } |
public class class_name {
private JComponent createControls()
{
JPanel controls = new JPanel(new FlowLayout(FlowLayout.RIGHT));
final JCheckBox meanCheckBox = new JCheckBox("Show Mean and Standard Deviation", false);
meanCheckBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent itemEvent)
{
chart.setNotify(false);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
if (itemEvent.getStateChange() == ItemEvent.SELECTED)
{
plot.setDataset(1, meanDataSet);
plot.setRenderer(1, meanRenderer);
}
else
{
plot.setDataset(1, null);
plot.setRenderer(1, null);
}
chart.setNotify(true);
}
});
controls.add(meanCheckBox);
return controls;
} } | public class class_name {
private JComponent createControls()
{
JPanel controls = new JPanel(new FlowLayout(FlowLayout.RIGHT));
final JCheckBox meanCheckBox = new JCheckBox("Show Mean and Standard Deviation", false);
meanCheckBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent itemEvent)
{
chart.setNotify(false);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
if (itemEvent.getStateChange() == ItemEvent.SELECTED)
{
plot.setDataset(1, meanDataSet); // depends on control dependency: [if], data = [none]
plot.setRenderer(1, meanRenderer); // depends on control dependency: [if], data = [none]
}
else
{
plot.setDataset(1, null); // depends on control dependency: [if], data = [none]
plot.setRenderer(1, null); // depends on control dependency: [if], data = [none]
}
chart.setNotify(true);
}
});
controls.add(meanCheckBox);
return controls;
} } |
public class class_name {
public void marshall(DisableGatewayRequest disableGatewayRequest, ProtocolMarshaller protocolMarshaller) {
if (disableGatewayRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(disableGatewayRequest.getGatewayARN(), GATEWAYARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DisableGatewayRequest disableGatewayRequest, ProtocolMarshaller protocolMarshaller) {
if (disableGatewayRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(disableGatewayRequest.getGatewayARN(), GATEWAYARN_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 KafkaClient setProducerProperties(Properties props) {
if (props == null) {
producerProperties = null;
} else {
producerProperties = new Properties();
producerProperties.putAll(props);
}
return this;
} } | public class class_name {
public KafkaClient setProducerProperties(Properties props) {
if (props == null) {
producerProperties = null; // depends on control dependency: [if], data = [none]
} else {
producerProperties = new Properties(); // depends on control dependency: [if], data = [none]
producerProperties.putAll(props); // depends on control dependency: [if], data = [(props]
}
return this;
} } |
public class class_name {
public void setAlgorithm(KeyAgreementType dh)
{
log("DH algorithm set: " + getDHName(dhMode) + " -> " + getDHName(dh));
try {
if(dhMode != null && dh.keyType == dhMode.keyType) return;
dhMode = dh;
switch (dhMode.keyType) {
case KeyAgreementType.DH_MODE_DH3K:
byte[] dhGen = new byte[384];
Arrays.zero(dhGen);
dhGen[383] = 0x02;
dhSystem = new DHCryptoSystem(DH_PRIME, dhGen);
dhKeyPair = dhSystem.createDHKeyPair();
clearEcdh();
break;
case KeyAgreementType.DH_MODE_EC25:
ecSystem = new ECCryptoSystem(ECCryptoSystem.EC256R1);
ecKeyPair = ecSystem.createECKeyPair();
clearDh();
break;
case KeyAgreementType.DH_MODE_EC38:
default:
ecSystem = new ECCryptoSystem(ECCryptoSystem.EC384R1);
ecKeyPair = ecSystem.createECKeyPair();
clearDh();
break;
}
} catch (InvalidCryptoSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedCryptoSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CryptoTokenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CryptoUnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } | public class class_name {
public void setAlgorithm(KeyAgreementType dh)
{
log("DH algorithm set: " + getDHName(dhMode) + " -> " + getDHName(dh));
try {
if(dhMode != null && dh.keyType == dhMode.keyType) return;
dhMode = dh;
// depends on control dependency: [try], data = [none]
switch (dhMode.keyType) {
case KeyAgreementType.DH_MODE_DH3K:
byte[] dhGen = new byte[384];
Arrays.zero(dhGen);
dhGen[383] = 0x02;
dhSystem = new DHCryptoSystem(DH_PRIME, dhGen);
dhKeyPair = dhSystem.createDHKeyPair();
clearEcdh();
break;
case KeyAgreementType.DH_MODE_EC25:
ecSystem = new ECCryptoSystem(ECCryptoSystem.EC256R1);
ecKeyPair = ecSystem.createECKeyPair();
clearDh();
break;
case KeyAgreementType.DH_MODE_EC38:
default:
ecSystem = new ECCryptoSystem(ECCryptoSystem.EC384R1);
ecKeyPair = ecSystem.createECKeyPair();
clearDh();
break;
}
} catch (InvalidCryptoSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedCryptoSystemException e) {
// depends on control dependency: [catch], data = [none]
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CryptoTokenException e) {
// depends on control dependency: [catch], data = [none]
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CryptoUnsupportedOperationException e) {
// depends on control dependency: [catch], data = [none]
// TODO Auto-generated catch block
e.printStackTrace();
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Nullable
private static Node primaryAccessControlScopeRootFor(Node node) {
if (isExtendsTarget(node)) {
return node.getParent();
} else if (isFunctionOrClass(node)) {
return node;
} else {
return null;
}
} } | public class class_name {
@Nullable
private static Node primaryAccessControlScopeRootFor(Node node) {
if (isExtendsTarget(node)) {
return node.getParent(); // depends on control dependency: [if], data = [none]
} else if (isFunctionOrClass(node)) {
return node; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static char[] extractCodePoint(String codePoint) {
try {
return Character.toChars(Integer.valueOf(codePoint, 16));
} catch (IllegalArgumentException e) {
// This may be caused by NumberFormatException of Integer.valueOf() or
// IllegalArgumentException of Character.toChars().
throw new IllegalArgumentException("Invalid code point: \\u" + codePoint, e);
}
} } | public class class_name {
private static char[] extractCodePoint(String codePoint) {
try {
return Character.toChars(Integer.valueOf(codePoint, 16)); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
// This may be caused by NumberFormatException of Integer.valueOf() or
// IllegalArgumentException of Character.toChars().
throw new IllegalArgumentException("Invalid code point: \\u" + codePoint, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void doSave() {
if (txt_PubCert.getDocument().getLength() < MIN_CERT_LENGTH) {
logger.error("Illegal state! There seems to be no certificate available.");
bt_save.setEnabled(false);
}
final JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(false);
fc.setSelectedFile(new File(OWASP_ZAP_ROOT_CA_FILENAME));
if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
final File f = fc.getSelectedFile();
if (logger.isInfoEnabled()) {
logger.info("Saving Root CA certificate to " + f);
}
try {
writePubCertificateToFile(f);
} catch (final Exception e) {
logger.error("Error while writing certificate data to file " + f, e);
}
}
} } | public class class_name {
private void doSave() {
if (txt_PubCert.getDocument().getLength() < MIN_CERT_LENGTH) {
logger.error("Illegal state! There seems to be no certificate available.");
// depends on control dependency: [if], data = [none]
bt_save.setEnabled(false);
// depends on control dependency: [if], data = [none]
}
final JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(false);
fc.setSelectedFile(new File(OWASP_ZAP_ROOT_CA_FILENAME));
if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
final File f = fc.getSelectedFile();
if (logger.isInfoEnabled()) {
logger.info("Saving Root CA certificate to " + f);
}
try {
writePubCertificateToFile(f);
} catch (final Exception e) {
logger.error("Error while writing certificate data to file " + f, e);
}
}
} } |
public class class_name {
public void marshall(RegisterDomainRequest registerDomainRequest, ProtocolMarshaller protocolMarshaller) {
if (registerDomainRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(registerDomainRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(registerDomainRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(registerDomainRequest.getWorkflowExecutionRetentionPeriodInDays(), WORKFLOWEXECUTIONRETENTIONPERIODINDAYS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(RegisterDomainRequest registerDomainRequest, ProtocolMarshaller protocolMarshaller) {
if (registerDomainRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(registerDomainRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(registerDomainRequest.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(registerDomainRequest.getWorkflowExecutionRetentionPeriodInDays(), WORKFLOWEXECUTIONRETENTIONPERIODINDAYS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static String generateDestinationToHiveColumnMapping(
Optional<Map<String, String>> hiveColumns,
Table destinationTableMeta) {
StringBuilder columns = new StringBuilder();
boolean isFirst = true;
List<FieldSchema> fieldList = destinationTableMeta.getSd().getCols();
for (FieldSchema field : fieldList) {
if (isFirst) {
isFirst = false;
} else {
columns.append(", \n");
}
String name = field.getName();
String type = escapeHiveType(field.getType());
String comment = field.getComment();
if (hiveColumns.isPresent()) {
hiveColumns.get().put(name, type);
}
columns.append(String.format(" `%s` %s COMMENT '%s'", name, type, escapeStringForHive(comment)));
}
return columns.toString();
} } | public class class_name {
private static String generateDestinationToHiveColumnMapping(
Optional<Map<String, String>> hiveColumns,
Table destinationTableMeta) {
StringBuilder columns = new StringBuilder();
boolean isFirst = true;
List<FieldSchema> fieldList = destinationTableMeta.getSd().getCols();
for (FieldSchema field : fieldList) {
if (isFirst) {
isFirst = false; // depends on control dependency: [if], data = [none]
} else {
columns.append(", \n"); // depends on control dependency: [if], data = [none]
}
String name = field.getName();
String type = escapeHiveType(field.getType());
String comment = field.getComment();
if (hiveColumns.isPresent()) {
hiveColumns.get().put(name, type); // depends on control dependency: [if], data = [none]
}
columns.append(String.format(" `%s` %s COMMENT '%s'", name, type, escapeStringForHive(comment))); // depends on control dependency: [for], data = [none]
}
return columns.toString();
} } |
public class class_name {
@Override
public void close() {
LOG.log(Level.FINER, "Closing the evaluators - begin");
final List<EvaluatorManager> evaluatorsCopy;
synchronized (this) {
evaluatorsCopy = new ArrayList<>(this.evaluators.values());
}
for (final EvaluatorManager evaluatorManager : evaluatorsCopy) {
if (!evaluatorManager.isClosedOrClosing()) {
LOG.log(Level.WARNING, "Unclean shutdown of evaluator {0}", evaluatorManager.getId());
evaluatorManager.close();
}
}
LOG.log(Level.FINER, "Closing the evaluators - end");
} } | public class class_name {
@Override
public void close() {
LOG.log(Level.FINER, "Closing the evaluators - begin");
final List<EvaluatorManager> evaluatorsCopy;
synchronized (this) {
evaluatorsCopy = new ArrayList<>(this.evaluators.values());
}
for (final EvaluatorManager evaluatorManager : evaluatorsCopy) {
if (!evaluatorManager.isClosedOrClosing()) {
LOG.log(Level.WARNING, "Unclean shutdown of evaluator {0}", evaluatorManager.getId()); // depends on control dependency: [if], data = [none]
evaluatorManager.close(); // depends on control dependency: [if], data = [none]
}
}
LOG.log(Level.FINER, "Closing the evaluators - end");
} } |
public class class_name {
private void setAvailabilityState(final AvailabilityState.State controllerAvailability) throws InterruptedException {
synchronized (controllerAvailabilityMonitor) {
// filter unchanged events
if (this.availabilityState.equals(controllerAvailability)) {
return;
}
// update state and notify
this.availabilityState = controllerAvailability;
logger.debug(this + " is now " + controllerAvailability.name());
try {
// notify remotes about controller shutdown
if (availabilityState.equals(DEACTIVATING)) {
try {
logger.debug("Notify data change of " + this);
validateInitialization();
if (!informer.isActive()) {
logger.debug("Skip update notification because connection not established.");
return;
}
try {
informer.publish(new Event(informer.getScope(), Void.class, null));
} catch (CouldNotPerformException ex) {
throw new CouldNotPerformException("Could not notify change of " + this + "!", ex);
}
} catch (final NotInitializedException ex) {
logger.debug("Skip update notification because instance is not initialized.");
} catch (CouldNotPerformException ex) {
ExceptionPrinter.printHistory(new CouldNotPerformException("Could not update communication service state in internal data object!", ex), logger);
}
}
} finally {
// wakeup listener.
this.controllerAvailabilityMonitor.notifyAll();
}
}
} } | public class class_name {
private void setAvailabilityState(final AvailabilityState.State controllerAvailability) throws InterruptedException {
synchronized (controllerAvailabilityMonitor) {
// filter unchanged events
if (this.availabilityState.equals(controllerAvailability)) {
return; // depends on control dependency: [if], data = [none]
}
// update state and notify
this.availabilityState = controllerAvailability;
logger.debug(this + " is now " + controllerAvailability.name());
try {
// notify remotes about controller shutdown
if (availabilityState.equals(DEACTIVATING)) {
try {
logger.debug("Notify data change of " + this); // depends on control dependency: [try], data = [none]
validateInitialization(); // depends on control dependency: [try], data = [none]
if (!informer.isActive()) {
logger.debug("Skip update notification because connection not established."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
try {
informer.publish(new Event(informer.getScope(), Void.class, null)); // depends on control dependency: [try], data = [none]
} catch (CouldNotPerformException ex) {
throw new CouldNotPerformException("Could not notify change of " + this + "!", ex);
} // depends on control dependency: [catch], data = [none]
} catch (final NotInitializedException ex) {
logger.debug("Skip update notification because instance is not initialized.");
} catch (CouldNotPerformException ex) { // depends on control dependency: [catch], data = [none]
ExceptionPrinter.printHistory(new CouldNotPerformException("Could not update communication service state in internal data object!", ex), logger);
} // depends on control dependency: [catch], data = [none]
}
} finally {
// wakeup listener.
this.controllerAvailabilityMonitor.notifyAll();
}
}
} } |
public class class_name {
private String getConfigPathFromRoot(File galaxyRoot, String configFileName) throws IOException {
if (isPre20141006Release(galaxyRoot)) {
return configFileName;
} else {
File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME);
File toolConf = new File(configDirectory, configFileName);
// if config file does not exist, copy it from the .sample version
if (!toolConf.exists()) {
File toolConfSample = new File(configDirectory, configFileName + ".sample");
Files.copy(toolConfSample, toolConf);
}
return CONFIG_DIR_NAME + "/" + configFileName;
}
} } | public class class_name {
private String getConfigPathFromRoot(File galaxyRoot, String configFileName) throws IOException {
if (isPre20141006Release(galaxyRoot)) {
return configFileName;
} else {
File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME);
File toolConf = new File(configDirectory, configFileName);
// if config file does not exist, copy it from the .sample version
if (!toolConf.exists()) {
File toolConfSample = new File(configDirectory, configFileName + ".sample");
Files.copy(toolConfSample, toolConf); // depends on control dependency: [if], data = [none]
}
return CONFIG_DIR_NAME + "/" + configFileName;
}
} } |
public class class_name {
public void marshall(EmergencyContact emergencyContact, ProtocolMarshaller protocolMarshaller) {
if (emergencyContact == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(emergencyContact.getEmailAddress(), EMAILADDRESS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(EmergencyContact emergencyContact, ProtocolMarshaller protocolMarshaller) {
if (emergencyContact == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(emergencyContact.getEmailAddress(), EMAILADDRESS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public boolean requeueSilent(IQueueMessage<ID, DATA> msg) {
try {
return putToQueue(msg.clone(), true);
} catch (RocksDBException e) {
throw new QueueException(e);
}
} } | public class class_name {
@Override
public boolean requeueSilent(IQueueMessage<ID, DATA> msg) {
try {
return putToQueue(msg.clone(), true); // depends on control dependency: [try], data = [none]
} catch (RocksDBException e) {
throw new QueueException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected String hashByteArray(byte[] data) {
if (mCRC32 != null) {
return hashCRC32(data);
} else if (mHashAlgorithm != null) {
return messageDigest(data);
} else {
// Default.
return hashCRC32(data);
}
} } | public class class_name {
protected String hashByteArray(byte[] data) {
if (mCRC32 != null) {
return hashCRC32(data); // depends on control dependency: [if], data = [none]
} else if (mHashAlgorithm != null) {
return messageDigest(data); // depends on control dependency: [if], data = [none]
} else {
// Default.
return hashCRC32(data); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Deprecated
public static String getAlgorithmProperty(String algName,
String propName) {
ProviderProperty entry = getProviderProperty("Alg." + propName
+ "." + algName);
if (entry != null) {
return entry.className;
} else {
return null;
}
} } | public class class_name {
@Deprecated
public static String getAlgorithmProperty(String algName,
String propName) {
ProviderProperty entry = getProviderProperty("Alg." + propName
+ "." + algName);
if (entry != null) {
return entry.className; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public FacesConfigNavigationRuleType<WebFacesConfigDescriptor> getOrCreateNavigationRule()
{
List<Node> nodeList = model.get("navigation-rule");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigNavigationRuleTypeImpl<WebFacesConfigDescriptor>(this, "navigation-rule", model, nodeList.get(0));
}
return createNavigationRule();
} } | public class class_name {
public FacesConfigNavigationRuleType<WebFacesConfigDescriptor> getOrCreateNavigationRule()
{
List<Node> nodeList = model.get("navigation-rule");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigNavigationRuleTypeImpl<WebFacesConfigDescriptor>(this, "navigation-rule", model, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createNavigationRule();
} } |
public class class_name {
public static CardConfiguration fromJson(JSONObject json) {
if (json == null) {
json = new JSONObject();
}
CardConfiguration cardConfiguration = new CardConfiguration();
JSONArray jsonArray = json.optJSONArray(SUPPORTED_CARD_TYPES_KEY);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
cardConfiguration.mSupportedCardTypes.add(jsonArray.optString(i, ""));
}
}
cardConfiguration.mCollectFraudData = json.optBoolean(COLLECT_DEVICE_DATA_KEY, false);
return cardConfiguration;
} } | public class class_name {
public static CardConfiguration fromJson(JSONObject json) {
if (json == null) {
json = new JSONObject(); // depends on control dependency: [if], data = [none]
}
CardConfiguration cardConfiguration = new CardConfiguration();
JSONArray jsonArray = json.optJSONArray(SUPPORTED_CARD_TYPES_KEY);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
cardConfiguration.mSupportedCardTypes.add(jsonArray.optString(i, "")); // depends on control dependency: [for], data = [i]
}
}
cardConfiguration.mCollectFraudData = json.optBoolean(COLLECT_DEVICE_DATA_KEY, false);
return cardConfiguration;
} } |
public class class_name {
public static byte min(byte... array) {
checkArgument(array.length > 0);
byte min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
} } | public class class_name {
public static byte min(byte... array) {
checkArgument(array.length > 0);
byte min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i]; // depends on control dependency: [if], data = [none]
}
}
return min;
} } |
public class class_name {
public static List<String> getFilesInFolder(String folder, String ext) {
// tryto find using normal file system lookup
List<String> files = new Vector<>();
File dir = new File(folder);
if (dir.exists() && dir.isDirectory()) {
String[] list = dir.list();
for (String file : list) {
if (file.endsWith(ext)) {
files.add(file);
}
}
}
return files;
} } | public class class_name {
public static List<String> getFilesInFolder(String folder, String ext) {
// tryto find using normal file system lookup
List<String> files = new Vector<>();
File dir = new File(folder);
if (dir.exists() && dir.isDirectory()) {
String[] list = dir.list();
for (String file : list) {
if (file.endsWith(ext)) {
files.add(file);
// depends on control dependency: [if], data = [none]
}
}
}
return files;
} } |
public class class_name {
public SelectBuilder orderBy(String name, boolean ascending) {
if (ascending) {
orderBys.add(name + " asc");
} else {
orderBys.add(name + " desc");
}
return this;
} } | public class class_name {
public SelectBuilder orderBy(String name, boolean ascending) {
if (ascending) {
orderBys.add(name + " asc"); // depends on control dependency: [if], data = [none]
} else {
orderBys.add(name + " desc"); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public void visit(NodeData node) throws RepositoryException
{
try
{
entering(node, currentLevel);
if ((maxLevel == -1) || (currentLevel < maxLevel))
{
currentLevel++;
List<PropertyData> properies = new ArrayList<PropertyData>(dataManager.getChildPropertiesData(node));
// Sorting properties
Collections.sort(properies, new PropertyDataOrderComparator());
for (PropertyData data : properies)
{
InternalQName propName = data.getQPath().getName();
// 7.3.3 Respecting Property Semantics
// When an element or attribute representing such a property is
// encountered, an implementation may either skip it or respect it.
if (Constants.JCR_LOCKISDEEP.equals(propName) || Constants.JCR_LOCKOWNER.equals(propName))
{
continue;
}
data.accept(this);
}
if (!isNoRecurse() && (currentLevel > 0))
{
List<NodeData> nodes = new ArrayList<NodeData>(dataManager.getChildNodesData(node));
// Sorting nodes
Collections.sort(nodes, new NodeDataOrderComparator());
for (NodeData data : nodes)
{
data.accept(this);
}
}
currentLevel--;
}
leaving(node, currentLevel);
}
catch (RepositoryException re)
{
currentLevel = 0;
throw re;
}
} } | public class class_name {
public void visit(NodeData node) throws RepositoryException
{
try
{
entering(node, currentLevel);
if ((maxLevel == -1) || (currentLevel < maxLevel))
{
currentLevel++;
List<PropertyData> properies = new ArrayList<PropertyData>(dataManager.getChildPropertiesData(node));
// Sorting properties
Collections.sort(properies, new PropertyDataOrderComparator());
for (PropertyData data : properies)
{
InternalQName propName = data.getQPath().getName();
// 7.3.3 Respecting Property Semantics
// When an element or attribute representing such a property is
// encountered, an implementation may either skip it or respect it.
if (Constants.JCR_LOCKISDEEP.equals(propName) || Constants.JCR_LOCKOWNER.equals(propName))
{
continue;
}
data.accept(this);
}
if (!isNoRecurse() && (currentLevel > 0))
{
List<NodeData> nodes = new ArrayList<NodeData>(dataManager.getChildNodesData(node));
// Sorting nodes
Collections.sort(nodes, new NodeDataOrderComparator());
for (NodeData data : nodes)
{
data.accept(this); // depends on control dependency: [for], data = [data]
}
}
currentLevel--;
}
leaving(node, currentLevel);
}
catch (RepositoryException re)
{
currentLevel = 0;
throw re;
}
} } |
public class class_name {
public synchronized void synchronizeSchema() {
OObjectDatabaseTx database = ((OObjectDatabaseTx) ODatabaseRecordThreadLocal.instance().get().getDatabaseOwner());
Collection<Class<?>> registeredEntities = database.getEntityManager().getRegisteredEntities();
boolean automaticSchemaGeneration = database.isAutomaticSchemaGeneration();
boolean reloadSchema = false;
for (Class<?> iClass : registeredEntities) {
if (Proxy.class.isAssignableFrom(iClass) || iClass.isEnum() || OReflectionHelper.isJavaType(iClass) || iClass
.isAnonymousClass())
return;
if (!database.getMetadata().getSchema().existsClass(iClass.getSimpleName())) {
database.getMetadata().getSchema().createClass(iClass.getSimpleName());
reloadSchema = true;
}
for (Class<?> currentClass = iClass; currentClass != Object.class; ) {
if (automaticSchemaGeneration && !currentClass.equals(Object.class) && !currentClass.equals(ODocument.class)) {
((OSchemaProxyObject) database.getMetadata().getSchema()).generateSchema(currentClass, database.getUnderlying());
}
String iClassName = currentClass.getSimpleName();
currentClass = currentClass.getSuperclass();
if (currentClass == null || currentClass.equals(ODocument.class))
// POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER
// ODOCUMENT FIELDS
currentClass = Object.class;
if (database != null && !database.isClosed() && !currentClass.equals(Object.class)) {
OClass oSuperClass;
OClass currentOClass = database.getMetadata().getSchema().getClass(iClassName);
if (!database.getMetadata().getSchema().existsClass(currentClass.getSimpleName())) {
oSuperClass = database.getMetadata().getSchema().createClass(currentClass.getSimpleName());
reloadSchema = true;
} else {
oSuperClass = database.getMetadata().getSchema().getClass(currentClass.getSimpleName());
reloadSchema = true;
}
if (!currentOClass.getSuperClasses().contains(oSuperClass)) {
currentOClass.setSuperClasses(Arrays.asList(oSuperClass));
reloadSchema = true;
}
}
}
}
if (database != null && !database.isClosed() && reloadSchema) {
database.getMetadata().getSchema().reload();
}
} } | public class class_name {
public synchronized void synchronizeSchema() {
OObjectDatabaseTx database = ((OObjectDatabaseTx) ODatabaseRecordThreadLocal.instance().get().getDatabaseOwner());
Collection<Class<?>> registeredEntities = database.getEntityManager().getRegisteredEntities();
boolean automaticSchemaGeneration = database.isAutomaticSchemaGeneration();
boolean reloadSchema = false;
for (Class<?> iClass : registeredEntities) {
if (Proxy.class.isAssignableFrom(iClass) || iClass.isEnum() || OReflectionHelper.isJavaType(iClass) || iClass
.isAnonymousClass())
return;
if (!database.getMetadata().getSchema().existsClass(iClass.getSimpleName())) {
database.getMetadata().getSchema().createClass(iClass.getSimpleName()); // depends on control dependency: [if], data = [none]
reloadSchema = true; // depends on control dependency: [if], data = [none]
}
for (Class<?> currentClass = iClass; currentClass != Object.class; ) {
if (automaticSchemaGeneration && !currentClass.equals(Object.class) && !currentClass.equals(ODocument.class)) {
((OSchemaProxyObject) database.getMetadata().getSchema()).generateSchema(currentClass, database.getUnderlying()); // depends on control dependency: [if], data = [none]
}
String iClassName = currentClass.getSimpleName();
currentClass = currentClass.getSuperclass(); // depends on control dependency: [for], data = [currentClass]
if (currentClass == null || currentClass.equals(ODocument.class))
// POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER
// ODOCUMENT FIELDS
currentClass = Object.class;
if (database != null && !database.isClosed() && !currentClass.equals(Object.class)) {
OClass oSuperClass;
OClass currentOClass = database.getMetadata().getSchema().getClass(iClassName);
if (!database.getMetadata().getSchema().existsClass(currentClass.getSimpleName())) {
oSuperClass = database.getMetadata().getSchema().createClass(currentClass.getSimpleName()); // depends on control dependency: [if], data = [none]
reloadSchema = true; // depends on control dependency: [if], data = [none]
} else {
oSuperClass = database.getMetadata().getSchema().getClass(currentClass.getSimpleName()); // depends on control dependency: [if], data = [none]
reloadSchema = true; // depends on control dependency: [if], data = [none]
}
if (!currentOClass.getSuperClasses().contains(oSuperClass)) {
currentOClass.setSuperClasses(Arrays.asList(oSuperClass)); // depends on control dependency: [if], data = [none]
reloadSchema = true; // depends on control dependency: [if], data = [none]
}
}
}
}
if (database != null && !database.isClosed() && reloadSchema) {
database.getMetadata().getSchema().reload(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
private void decreaseKey(ReflectedHandle<K, V> n, K newKey) {
if (n.inner == null && free != n) {
throw new IllegalArgumentException("Invalid handle!");
}
int c;
if (comparator == null) {
c = ((Comparable<? super K>) newKey).compareTo(n.key);
} else {
c = comparator.compare(newKey, n.key);
}
if (c > 0) {
throw new IllegalArgumentException("Keys can only be decreased!");
}
n.key = newKey;
if (c == 0 || free == n) {
return;
}
// actual decrease
AddressableHeap.Handle<K, HandleMap<K, V>> nInner = n.inner;
if (n.minNotMax) {
// we are in the min heap, easy case
n.inner.decreaseKey(newKey);
} else {
// we are in the max heap, remove
nInner.delete();
ReflectedHandle<K, V> nOuter = nInner.getValue().outer;
nOuter.inner = null;
nOuter.minNotMax = false;
// remove min
AddressableHeap.Handle<K, HandleMap<K, V>> minInner = nInner.getValue().otherInner;
ReflectedHandle<K, V> minOuter = minInner.getValue().outer;
minInner.delete();
minOuter.inner = null;
minOuter.minNotMax = false;
// update key
nOuter.key = newKey;
// reinsert both
insertPair(nOuter, minOuter);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
private void decreaseKey(ReflectedHandle<K, V> n, K newKey) {
if (n.inner == null && free != n) {
throw new IllegalArgumentException("Invalid handle!");
}
int c;
if (comparator == null) {
c = ((Comparable<? super K>) newKey).compareTo(n.key); // depends on control dependency: [if], data = [none]
} else {
c = comparator.compare(newKey, n.key); // depends on control dependency: [if], data = [none]
}
if (c > 0) {
throw new IllegalArgumentException("Keys can only be decreased!");
}
n.key = newKey;
if (c == 0 || free == n) {
return; // depends on control dependency: [if], data = [none]
}
// actual decrease
AddressableHeap.Handle<K, HandleMap<K, V>> nInner = n.inner;
if (n.minNotMax) {
// we are in the min heap, easy case
n.inner.decreaseKey(newKey); // depends on control dependency: [if], data = [none]
} else {
// we are in the max heap, remove
nInner.delete(); // depends on control dependency: [if], data = [none]
ReflectedHandle<K, V> nOuter = nInner.getValue().outer;
nOuter.inner = null; // depends on control dependency: [if], data = [none]
nOuter.minNotMax = false; // depends on control dependency: [if], data = [none]
// remove min
AddressableHeap.Handle<K, HandleMap<K, V>> minInner = nInner.getValue().otherInner;
ReflectedHandle<K, V> minOuter = minInner.getValue().outer;
minInner.delete(); // depends on control dependency: [if], data = [none]
minOuter.inner = null; // depends on control dependency: [if], data = [none]
minOuter.minNotMax = false; // depends on control dependency: [if], data = [none]
// update key
nOuter.key = newKey; // depends on control dependency: [if], data = [none]
// reinsert both
insertPair(nOuter, minOuter); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
double computeSideError(List<Point2D_I32> contour , int indexA , int indexB ) {
assignLine(contour, indexA, indexB, line);
// don't sample the end points because the error will be zero by definition
int numSamples;
double sumOfDistances = 0;
int length;
if( indexB >= indexA ) {
length = indexB-indexA-1;
numSamples = Math.min(length,maxNumberOfSideSamples);
for (int i = 0; i < numSamples; i++) {
int index = indexA+1+length*i/numSamples;
Point2D_I32 p = contour.get(index);
sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y);
}
sumOfDistances /= numSamples;
} else {
length = contour.size()-indexA-1 + indexB;
numSamples = Math.min(length,maxNumberOfSideSamples);
for (int i = 0; i < numSamples; i++) {
int where = length*i/numSamples;
int index = (indexA+1+where)%contour.size();
Point2D_I32 p = contour.get(index);
sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y);
}
sumOfDistances /= numSamples;
}
// handle divide by zero error
if( numSamples > 0 )
return sumOfDistances;
else
return 0;
} } | public class class_name {
double computeSideError(List<Point2D_I32> contour , int indexA , int indexB ) {
assignLine(contour, indexA, indexB, line);
// don't sample the end points because the error will be zero by definition
int numSamples;
double sumOfDistances = 0;
int length;
if( indexB >= indexA ) {
length = indexB-indexA-1; // depends on control dependency: [if], data = [none]
numSamples = Math.min(length,maxNumberOfSideSamples); // depends on control dependency: [if], data = [none]
for (int i = 0; i < numSamples; i++) {
int index = indexA+1+length*i/numSamples;
Point2D_I32 p = contour.get(index);
sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y); // depends on control dependency: [for], data = [none]
}
sumOfDistances /= numSamples; // depends on control dependency: [if], data = [none]
} else {
length = contour.size()-indexA-1 + indexB; // depends on control dependency: [if], data = [none]
numSamples = Math.min(length,maxNumberOfSideSamples); // depends on control dependency: [if], data = [none]
for (int i = 0; i < numSamples; i++) {
int where = length*i/numSamples;
int index = (indexA+1+where)%contour.size();
Point2D_I32 p = contour.get(index);
sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y); // depends on control dependency: [for], data = [none]
}
sumOfDistances /= numSamples; // depends on control dependency: [if], data = [none]
}
// handle divide by zero error
if( numSamples > 0 )
return sumOfDistances;
else
return 0;
} } |
public class class_name {
public TaskUpdateOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null;
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate);
}
return this;
} } | public class class_name {
public TaskUpdateOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null; // depends on control dependency: [if], data = [none]
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate]
}
return this;
} } |
public class class_name {
private static String formatPrincipal(final String username) {
if (StringUtils.isNotBlank(LDAP_AUTH_USERNAME_FMT)) {
return String.format(LDAP_AUTH_USERNAME_FMT, username);
}
return username;
} } | public class class_name {
private static String formatPrincipal(final String username) {
if (StringUtils.isNotBlank(LDAP_AUTH_USERNAME_FMT)) {
return String.format(LDAP_AUTH_USERNAME_FMT, username); // depends on control dependency: [if], data = [none]
}
return username;
} } |
public class class_name {
@Nullable
public static ImmutableWorkerInfo selectWorker(
final Task task,
final Map<String, ImmutableWorkerInfo> allWorkers,
final WorkerTaskRunnerConfig workerTaskRunnerConfig,
@Nullable final AffinityConfig affinityConfig,
final Function<ImmutableMap<String, ImmutableWorkerInfo>, ImmutableWorkerInfo> workerSelector
)
{
// Workers that could potentially run this task, ignoring affinityConfig.
final Map<String, ImmutableWorkerInfo> runnableWorkers = allWorkers
.values()
.stream()
.filter(worker -> worker.canRunTask(task)
&& worker.isValidVersion(workerTaskRunnerConfig.getMinWorkerVersion()))
.collect(Collectors.toMap(w -> w.getWorker().getHost(), Function.identity()));
if (affinityConfig == null) {
// All runnable workers are valid.
return workerSelector.apply(ImmutableMap.copyOf(runnableWorkers));
} else {
// Workers assigned to the affinity pool for our task.
final Set<String> dataSourceWorkers = affinityConfig.getAffinity().get(task.getDataSource());
if (dataSourceWorkers == null) {
// No affinity config for this dataSource; use non-affinity workers.
return workerSelector.apply(getNonAffinityWorkers(affinityConfig, runnableWorkers));
} else {
// Get runnable, affinity workers.
final ImmutableMap<String, ImmutableWorkerInfo> dataSourceWorkerMap =
ImmutableMap.copyOf(Maps.filterKeys(runnableWorkers, dataSourceWorkers::contains));
final ImmutableWorkerInfo selected = workerSelector.apply(dataSourceWorkerMap);
if (selected != null) {
return selected;
} else if (affinityConfig.isStrong()) {
return null;
} else {
// Weak affinity allows us to use nonAffinityWorkers for this dataSource, if no affinity workers
// are available.
return workerSelector.apply(getNonAffinityWorkers(affinityConfig, runnableWorkers));
}
}
}
} } | public class class_name {
@Nullable
public static ImmutableWorkerInfo selectWorker(
final Task task,
final Map<String, ImmutableWorkerInfo> allWorkers,
final WorkerTaskRunnerConfig workerTaskRunnerConfig,
@Nullable final AffinityConfig affinityConfig,
final Function<ImmutableMap<String, ImmutableWorkerInfo>, ImmutableWorkerInfo> workerSelector
)
{
// Workers that could potentially run this task, ignoring affinityConfig.
final Map<String, ImmutableWorkerInfo> runnableWorkers = allWorkers
.values()
.stream()
.filter(worker -> worker.canRunTask(task)
&& worker.isValidVersion(workerTaskRunnerConfig.getMinWorkerVersion()))
.collect(Collectors.toMap(w -> w.getWorker().getHost(), Function.identity()));
if (affinityConfig == null) {
// All runnable workers are valid.
return workerSelector.apply(ImmutableMap.copyOf(runnableWorkers)); // depends on control dependency: [if], data = [none]
} else {
// Workers assigned to the affinity pool for our task.
final Set<String> dataSourceWorkers = affinityConfig.getAffinity().get(task.getDataSource());
if (dataSourceWorkers == null) {
// No affinity config for this dataSource; use non-affinity workers.
return workerSelector.apply(getNonAffinityWorkers(affinityConfig, runnableWorkers)); // depends on control dependency: [if], data = [none]
} else {
// Get runnable, affinity workers.
final ImmutableMap<String, ImmutableWorkerInfo> dataSourceWorkerMap =
ImmutableMap.copyOf(Maps.filterKeys(runnableWorkers, dataSourceWorkers::contains));
final ImmutableWorkerInfo selected = workerSelector.apply(dataSourceWorkerMap);
if (selected != null) {
return selected; // depends on control dependency: [if], data = [none]
} else if (affinityConfig.isStrong()) {
return null; // depends on control dependency: [if], data = [none]
} else {
// Weak affinity allows us to use nonAffinityWorkers for this dataSource, if no affinity workers
// are available.
return workerSelector.apply(getNonAffinityWorkers(affinityConfig, runnableWorkers)); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public boolean matchesTag(final UdpChannel udpChannel)
{
if (!hasTag || !udpChannel.hasTag() || tag != udpChannel.tag())
{
return false;
}
if (udpChannel.remoteData().getAddress().isAnyLocalAddress() &&
udpChannel.remoteData().getPort() == 0 &&
udpChannel.localData().getAddress().isAnyLocalAddress() &&
udpChannel.localData().getPort() == 0)
{
return true;
}
throw new IllegalArgumentException("matching tag has set endpoint or control address");
} } | public class class_name {
public boolean matchesTag(final UdpChannel udpChannel)
{
if (!hasTag || !udpChannel.hasTag() || tag != udpChannel.tag())
{
return false; // depends on control dependency: [if], data = [none]
}
if (udpChannel.remoteData().getAddress().isAnyLocalAddress() &&
udpChannel.remoteData().getPort() == 0 &&
udpChannel.localData().getAddress().isAnyLocalAddress() &&
udpChannel.localData().getPort() == 0)
{
return true; // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException("matching tag has set endpoint or control address");
} } |
public class class_name {
public void addTaskHook(ITaskHook newHook) {
Collection<org.apache.heron.api.hooks.ITaskHook> hooks = delegate.getHooks();
if (hooks == null) {
ITaskHookDelegate delegateHook = new ITaskHookDelegate();
delegateHook.addHook(newHook);
delegate.addTaskHook(delegateHook);
} else {
for (org.apache.heron.api.hooks.ITaskHook hook : hooks) {
if (hook instanceof ITaskHookDelegate) {
ITaskHookDelegate delegateHook = (ITaskHookDelegate) hook;
delegateHook.addHook(newHook);
return;
}
}
throw new RuntimeException("StormCompat taskHooks not setup properly");
}
} } | public class class_name {
public void addTaskHook(ITaskHook newHook) {
Collection<org.apache.heron.api.hooks.ITaskHook> hooks = delegate.getHooks();
if (hooks == null) {
ITaskHookDelegate delegateHook = new ITaskHookDelegate();
delegateHook.addHook(newHook); // depends on control dependency: [if], data = [none]
delegate.addTaskHook(delegateHook); // depends on control dependency: [if], data = [none]
} else {
for (org.apache.heron.api.hooks.ITaskHook hook : hooks) {
if (hook instanceof ITaskHookDelegate) {
ITaskHookDelegate delegateHook = (ITaskHookDelegate) hook;
delegateHook.addHook(newHook); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
throw new RuntimeException("StormCompat taskHooks not setup properly");
}
} } |
public class class_name {
public static int getFirstScreenHeight()
{
final GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment
.getLocalGraphicsEnvironment();
final GraphicsDevice[] graphicsDevices = graphicsEnvironment.getScreenDevices();
int height = getScreenHeight();
for (final GraphicsDevice graphicsDevice : graphicsDevices)
{
final GraphicsConfiguration[] graphicsConfigurations = graphicsDevice
.getConfigurations();
final GraphicsConfiguration graphicsConfiguration = ArrayExtensions
.getFirst(graphicsConfigurations);
if (graphicsConfiguration != null)
{
final Rectangle bounds = graphicsConfiguration.getBounds();
final double h = bounds.getHeight();
height = (int)h;
break;
}
}
return height;
} } | public class class_name {
public static int getFirstScreenHeight()
{
final GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment
.getLocalGraphicsEnvironment();
final GraphicsDevice[] graphicsDevices = graphicsEnvironment.getScreenDevices();
int height = getScreenHeight();
for (final GraphicsDevice graphicsDevice : graphicsDevices)
{
final GraphicsConfiguration[] graphicsConfigurations = graphicsDevice
.getConfigurations();
final GraphicsConfiguration graphicsConfiguration = ArrayExtensions
.getFirst(graphicsConfigurations);
if (graphicsConfiguration != null)
{
final Rectangle bounds = graphicsConfiguration.getBounds();
final double h = bounds.getHeight();
height = (int)h; // depends on control dependency: [if], data = [none]
break;
}
}
return height;
} } |
public class class_name {
@Override
public void close() {
if (!this.closed.getAndSet(true)) {
this.conditionalUpdateProcessor.close();
this.cacheManager.unregister(this.cache);
this.cache.close();
this.recoveryTracker.close();
}
} } | public class class_name {
@Override
public void close() {
if (!this.closed.getAndSet(true)) {
this.conditionalUpdateProcessor.close(); // depends on control dependency: [if], data = [none]
this.cacheManager.unregister(this.cache); // depends on control dependency: [if], data = [none]
this.cache.close(); // depends on control dependency: [if], data = [none]
this.recoveryTracker.close(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public RequestBuilder newRequestBuilder(Class<RequestBuilder> clazz) {
RequestBuilder b = null;
try {
b = clazz.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return b.resolver(FunctionResolver.DEFAULT);
} } | public class class_name {
@Override
public RequestBuilder newRequestBuilder(Class<RequestBuilder> clazz) {
RequestBuilder b = null;
try {
b = clazz.newInstance(); // depends on control dependency: [try], data = [none]
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none]
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
return b.resolver(FunctionResolver.DEFAULT);
} } |
public class class_name {
public CcgParseResult parse(AnnotatedSentence sentence, ChartCost inputFilter) {
AnnotatedSentence annotatedSentence = null;
if (supertagger != null) {
for (int i = 0; i < multitagThresholds.length; i++) {
// Try parsing at each multitag threshold. If parsing succeeds,
// immediately return the parse. Otherwise, continue to further
// thresholds.
List<WordAndPos> supertaggerInput = sentence.getWordsAndPosTags();
ListSupertaggedSentence supertaggedSentence = supertagger
.multitag(supertaggerInput, multitagThresholds[i]);
annotatedSentence = sentence.addAnnotation(supertaggerAnnotationName,
supertaggedSentence.getAnnotation());
CcgParse parse = inference.getBestParse(parser, annotatedSentence, inputFilter,
new NullLogFunction());
if (parse != null) {
return new CcgParseResult(parse, annotatedSentence, multitagThresholds[i]);
}
}
// Parsing was unsuccessful at all thresholds
return null;
} else {
CcgParse parse = inference.getBestParse(parser, sentence, inputFilter, new NullLogFunction());
if (parse != null) {
return new CcgParseResult(parse, sentence, 0.0);
} else {
return null;
}
}
} } | public class class_name {
public CcgParseResult parse(AnnotatedSentence sentence, ChartCost inputFilter) {
AnnotatedSentence annotatedSentence = null;
if (supertagger != null) {
for (int i = 0; i < multitagThresholds.length; i++) {
// Try parsing at each multitag threshold. If parsing succeeds,
// immediately return the parse. Otherwise, continue to further
// thresholds.
List<WordAndPos> supertaggerInput = sentence.getWordsAndPosTags();
ListSupertaggedSentence supertaggedSentence = supertagger
.multitag(supertaggerInput, multitagThresholds[i]);
annotatedSentence = sentence.addAnnotation(supertaggerAnnotationName,
supertaggedSentence.getAnnotation()); // depends on control dependency: [for], data = [none]
CcgParse parse = inference.getBestParse(parser, annotatedSentence, inputFilter,
new NullLogFunction());
if (parse != null) {
return new CcgParseResult(parse, annotatedSentence, multitagThresholds[i]); // depends on control dependency: [if], data = [(parse]
}
}
// Parsing was unsuccessful at all thresholds
return null; // depends on control dependency: [if], data = [none]
} else {
CcgParse parse = inference.getBestParse(parser, sentence, inputFilter, new NullLogFunction());
if (parse != null) {
return new CcgParseResult(parse, sentence, 0.0); // depends on control dependency: [if], data = [(parse]
} else {
return null; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static Calendar modify(Calendar calendar, int dateField, ModifyType modifyType) {
// 上下午特殊处理
if (Calendar.AM_PM == dateField) {
boolean isAM = DateUtil.isAM(calendar);
switch (modifyType) {
case TRUNCATE:
calendar.set(Calendar.HOUR_OF_DAY, isAM ? 0 : 12);
break;
case CEILING:
calendar.set(Calendar.HOUR_OF_DAY, isAM ? 11 : 23);
break;
case ROUND:
int min = isAM ? 0 : 12;
int max = isAM ? 11 : 23;
int href = (max - min) / 2 + 1;
int value = calendar.get(Calendar.HOUR_OF_DAY);
calendar.set(Calendar.HOUR_OF_DAY, (value < href) ? min : max);
break;
}
}
// 当用户指定了无关字段时,降级字段
if (ArrayUtil.contains(ignoreFields, dateField)) {
return modify(calendar, dateField + 1, modifyType);
}
for (int i = Calendar.MILLISECOND; i > dateField; i--) {
if (ArrayUtil.contains(ignoreFields, i) || Calendar.WEEK_OF_MONTH == i) {
// 忽略无关字段(WEEK_OF_MONTH)始终不做修改
continue;
}
if (Calendar.WEEK_OF_MONTH == dateField) {
// 在星期模式下,月的处理忽略之
if (Calendar.DAY_OF_MONTH == i) {
continue;
} else if (Calendar.DAY_OF_WEEK_IN_MONTH == i) {
// 星期模式下,星期几统一用DAY_OF_WEEK处理
i = Calendar.DAY_OF_WEEK;
}
} else if (Calendar.DAY_OF_WEEK_IN_MONTH == i) {
// 非星期模式下,星期处理忽略之
// 由于DAY_OF_WEEK忽略,自动降级到DAY_OF_WEEK_IN_MONTH
continue;
}
modifyField(calendar, i, modifyType);
}
return calendar;
} } | public class class_name {
public static Calendar modify(Calendar calendar, int dateField, ModifyType modifyType) {
// 上下午特殊处理
if (Calendar.AM_PM == dateField) {
boolean isAM = DateUtil.isAM(calendar);
switch (modifyType) {
case TRUNCATE:
calendar.set(Calendar.HOUR_OF_DAY, isAM ? 0 : 12);
break;
case CEILING:
calendar.set(Calendar.HOUR_OF_DAY, isAM ? 11 : 23);
break;
case ROUND:
int min = isAM ? 0 : 12;
int max = isAM ? 11 : 23;
int href = (max - min) / 2 + 1;
int value = calendar.get(Calendar.HOUR_OF_DAY);
calendar.set(Calendar.HOUR_OF_DAY, (value < href) ? min : max);
break;
}
}
// 当用户指定了无关字段时,降级字段
if (ArrayUtil.contains(ignoreFields, dateField)) {
return modify(calendar, dateField + 1, modifyType);
// depends on control dependency: [if], data = [none]
}
for (int i = Calendar.MILLISECOND; i > dateField; i--) {
if (ArrayUtil.contains(ignoreFields, i) || Calendar.WEEK_OF_MONTH == i) {
// 忽略无关字段(WEEK_OF_MONTH)始终不做修改
continue;
}
if (Calendar.WEEK_OF_MONTH == dateField) {
// 在星期模式下,月的处理忽略之
if (Calendar.DAY_OF_MONTH == i) {
continue;
} else if (Calendar.DAY_OF_WEEK_IN_MONTH == i) {
// 星期模式下,星期几统一用DAY_OF_WEEK处理
i = Calendar.DAY_OF_WEEK;
// depends on control dependency: [if], data = [none]
}
} else if (Calendar.DAY_OF_WEEK_IN_MONTH == i) {
// 非星期模式下,星期处理忽略之
// 由于DAY_OF_WEEK忽略,自动降级到DAY_OF_WEEK_IN_MONTH
continue;
}
modifyField(calendar, i, modifyType);
// depends on control dependency: [for], data = [i]
}
return calendar;
} } |
public class class_name {
public void initialize() {
try {
writeLock.lock();
if (!isInitialized()) {
super.initialize();
setInitialized(true);
this.initCalled = true;
}
} finally {
// downgrade to readlock before releasing just in case
readLock.lock();
writeLock.unlock();
readLock.unlock();
}
} } | public class class_name {
public void initialize() {
try {
writeLock.lock(); // depends on control dependency: [try], data = [none]
if (!isInitialized()) {
super.initialize(); // depends on control dependency: [if], data = [none]
setInitialized(true); // depends on control dependency: [if], data = [none]
this.initCalled = true; // depends on control dependency: [if], data = [none]
}
} finally {
// downgrade to readlock before releasing just in case
readLock.lock();
writeLock.unlock();
readLock.unlock();
}
} } |
public class class_name {
@Override
public void command(String... args)
{
addArgument(File.class, "xml-config-file-path");
super.command(args);
configFile = getArgument("xml-config-file-path");
readConfig();
if (watch)
{
Thread thread = new Thread(this, configFile+" watcher");
thread.start();
}
} } | public class class_name {
@Override
public void command(String... args)
{
addArgument(File.class, "xml-config-file-path");
super.command(args);
configFile = getArgument("xml-config-file-path");
readConfig();
if (watch)
{
Thread thread = new Thread(this, configFile+" watcher");
thread.start();
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private boolean createEmptyHeader( String filePath, int rows ) {
try {
RandomAccessFile theCreatedFile = new RandomAccessFile(filePath, "rw");
rowaddresses = new long[rows + 1];
// the size of a long
theCreatedFile.write(4);
// write the addresses of the row begins. Since we don't know how
// much
// they will be compressed, they will be filled after the
// compression
for( int i = 0; i < rows + 1; i++ ) {
theCreatedFile.writeInt(0);
}
pointerInFilePosition = theCreatedFile.getFilePointer();
rowaddresses[0] = pointerInFilePosition;
theCreatedFile.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
} } | public class class_name {
private boolean createEmptyHeader( String filePath, int rows ) {
try {
RandomAccessFile theCreatedFile = new RandomAccessFile(filePath, "rw");
rowaddresses = new long[rows + 1]; // depends on control dependency: [try], data = [none]
// the size of a long
theCreatedFile.write(4); // depends on control dependency: [try], data = [none]
// write the addresses of the row begins. Since we don't know how
// much
// they will be compressed, they will be filled after the
// compression
for( int i = 0; i < rows + 1; i++ ) {
theCreatedFile.writeInt(0); // depends on control dependency: [for], data = [none]
}
pointerInFilePosition = theCreatedFile.getFilePointer(); // depends on control dependency: [try], data = [none]
rowaddresses[0] = pointerInFilePosition; // depends on control dependency: [try], data = [none]
theCreatedFile.close(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
return false;
} // depends on control dependency: [catch], data = [none]
return true;
} } |
public class class_name {
protected void trace( int x , int y , int indexInten ) {
int dx,dy;
int indexOut = output.getIndex(x,y);
open.grow().set(x,y);
output.data[indexOut] = 1;
intensity.data[ indexInten ] = MARK_TRAVERSED;
while( open.size() > 0 ) {
active.set(open.removeTail());
indexInten = intensity.getIndex(active.x,active.y);
int indexDir = direction.getIndex(active.x,active.y);
boolean first = true;
while( true ) {
//----- First check along the direction of the edge. Only need to check 2 points this way
switch( direction.data[ indexDir ] ) {
case 0: dx = 0;dy= 1; break;
case 1: dx = 1;dy= -1; break;
case 2: dx = 1;dy= 0; break;
case -1: dx = 1;dy= 1; break;
default: throw new RuntimeException("Unknown direction: "+direction.data[ indexDir ]);
}
int indexForward = indexInten + dy*intensity.stride + dx;
int indexBackward = indexInten - dy*intensity.stride - dx;
int prevIndexDir = indexDir;
boolean match = false;
// pixel coordinate of forward and backward point
x = active.x; y = active.y;
int fx = active.x+dx, fy = active.y+dy;
int bx = active.x-dx, by = active.y-dy;
if( intensity.isInBounds(fx,fy) && intensity.data[ indexForward ] >= lower ) {
intensity.data[ indexForward ] = MARK_TRAVERSED;
output.unsafe_set(fx, fy, 1);
active.set(fx, fy);
match = true;
indexInten = indexForward;
indexDir = prevIndexDir + dy*intensity.stride + dx;
}
if( intensity.isInBounds(bx,by) && intensity.data[ indexBackward ] >= lower ) {
intensity.data[ indexBackward ] = MARK_TRAVERSED;
output.unsafe_set(bx,by,1);
if( match ) {
open.grow().set(bx,by);
} else {
active.set(bx,by);
match = true;
indexInten = indexBackward;
indexDir = prevIndexDir - dy*intensity.stride - dx;
}
}
if( first || !match ) {
boolean priorMatch = match;
// Check local neighbors if its one of the end points, which would be the first point or
// any point for which no matches were found
match = checkAllNeighbors(x,y,match);
if( !match )
break;
else {
// if it was the first it's no longer the first
first = false;
// the point at the end was just added and is to be searched in the next iteration
if( !priorMatch ) {
indexInten = intensity.getIndex(active.x, active.y);
indexDir = direction.getIndex(active.x,active.y);
}
}
}
}
}
} } | public class class_name {
protected void trace( int x , int y , int indexInten ) {
int dx,dy;
int indexOut = output.getIndex(x,y);
open.grow().set(x,y);
output.data[indexOut] = 1;
intensity.data[ indexInten ] = MARK_TRAVERSED;
while( open.size() > 0 ) {
active.set(open.removeTail()); // depends on control dependency: [while], data = [none]
indexInten = intensity.getIndex(active.x,active.y); // depends on control dependency: [while], data = [none]
int indexDir = direction.getIndex(active.x,active.y);
boolean first = true;
while( true ) {
//----- First check along the direction of the edge. Only need to check 2 points this way
switch( direction.data[ indexDir ] ) {
case 0: dx = 0;dy= 1; break;
case 1: dx = 1;dy= -1; break;
case 2: dx = 1;dy= 0; break;
case -1: dx = 1;dy= 1; break;
default: throw new RuntimeException("Unknown direction: "+direction.data[ indexDir ]);
}
int indexForward = indexInten + dy*intensity.stride + dx;
int indexBackward = indexInten - dy*intensity.stride - dx;
int prevIndexDir = indexDir;
boolean match = false;
// pixel coordinate of forward and backward point
x = active.x; y = active.y; // depends on control dependency: [while], data = [none] // depends on control dependency: [while], data = [none]
int fx = active.x+dx, fy = active.y+dy;
int bx = active.x-dx, by = active.y-dy;
if( intensity.isInBounds(fx,fy) && intensity.data[ indexForward ] >= lower ) {
intensity.data[ indexForward ] = MARK_TRAVERSED; // depends on control dependency: [if], data = [none]
output.unsafe_set(fx, fy, 1); // depends on control dependency: [if], data = [none]
active.set(fx, fy); // depends on control dependency: [if], data = [none]
match = true; // depends on control dependency: [if], data = [none]
indexInten = indexForward; // depends on control dependency: [if], data = [none]
indexDir = prevIndexDir + dy*intensity.stride + dx; // depends on control dependency: [if], data = [none]
}
if( intensity.isInBounds(bx,by) && intensity.data[ indexBackward ] >= lower ) {
intensity.data[ indexBackward ] = MARK_TRAVERSED; // depends on control dependency: [if], data = [none]
output.unsafe_set(bx,by,1); // depends on control dependency: [if], data = [none]
if( match ) {
open.grow().set(bx,by); // depends on control dependency: [if], data = [none]
} else {
active.set(bx,by); // depends on control dependency: [if], data = [none]
match = true; // depends on control dependency: [if], data = [none]
indexInten = indexBackward; // depends on control dependency: [if], data = [none]
indexDir = prevIndexDir - dy*intensity.stride - dx; // depends on control dependency: [if], data = [none]
}
}
if( first || !match ) {
boolean priorMatch = match;
// Check local neighbors if its one of the end points, which would be the first point or
// any point for which no matches were found
match = checkAllNeighbors(x,y,match); // depends on control dependency: [if], data = [none]
if( !match )
break;
else {
// if it was the first it's no longer the first
first = false; // depends on control dependency: [if], data = [none]
// the point at the end was just added and is to be searched in the next iteration
if( !priorMatch ) {
indexInten = intensity.getIndex(active.x, active.y); // depends on control dependency: [if], data = [none]
indexDir = direction.getIndex(active.x,active.y); // depends on control dependency: [if], data = [none]
}
}
}
}
}
} } |
public class class_name {
public static synchronized ClassLoader start() {
if (isHotdeploy()) {
final ClassLoader originalLoader = getThreadContextClassLoader();
if (isAnotherThreadHotdeploy()) { // e.g. job started
inheritAnotherThreadClassLoader(); // to use same loader
} else { // normally here
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
// remove this if-statement to avoid context class-loader being null by jflute (2017/12/17)
// if stop() without start(), context class-loader becomes null
// if hot-deploy process makes new thread, the thread inherits
// hot-deploy class-loader as context class-loader
// so this if-statement causes stop() without start()
// (though hot-deploy class-loader may wrap hot-deploy class-loader, but no problem?)
// _/_/_/_/_/_/_/_/_/_/
//if (!isThreadContextHotdeploy()) {
HotdeployUtil.start();
}
++hotdeployCount;
return originalLoader;
} else {
return null;
}
} } | public class class_name {
public static synchronized ClassLoader start() {
if (isHotdeploy()) {
final ClassLoader originalLoader = getThreadContextClassLoader();
if (isAnotherThreadHotdeploy()) { // e.g. job started
inheritAnotherThreadClassLoader(); // to use same loader // depends on control dependency: [if], data = [none]
} else { // normally here
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
// remove this if-statement to avoid context class-loader being null by jflute (2017/12/17)
// if stop() without start(), context class-loader becomes null
// if hot-deploy process makes new thread, the thread inherits
// hot-deploy class-loader as context class-loader
// so this if-statement causes stop() without start()
// (though hot-deploy class-loader may wrap hot-deploy class-loader, but no problem?)
// _/_/_/_/_/_/_/_/_/_/
//if (!isThreadContextHotdeploy()) {
HotdeployUtil.start(); // depends on control dependency: [if], data = [none]
}
++hotdeployCount; // depends on control dependency: [if], data = [none]
return originalLoader; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void postJsonMessage(StringEntity input) {
String pageToken = FbBotMillContext.getInstance().getPageToken();
// If the page token is invalid, returns.
if (!validatePageToken(pageToken)) {
return;
}
String url = FbBotMillNetworkConstants.FACEBOOK_BASE_URL
+ FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken;
postInternal(url, input);
} } | public class class_name {
public static void postJsonMessage(StringEntity input) {
String pageToken = FbBotMillContext.getInstance().getPageToken();
// If the page token is invalid, returns.
if (!validatePageToken(pageToken)) {
return; // depends on control dependency: [if], data = [none]
}
String url = FbBotMillNetworkConstants.FACEBOOK_BASE_URL
+ FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken;
postInternal(url, input);
} } |
public class class_name {
public static List<DiskRange> mergeAdjacentDiskRanges(Collection<DiskRange> diskRanges, DataSize maxMergeDistance, DataSize maxReadSize)
{
// sort ranges by start offset
List<DiskRange> ranges = new ArrayList<>(diskRanges);
Collections.sort(ranges, new Comparator<DiskRange>()
{
@Override
public int compare(DiskRange o1, DiskRange o2)
{
return Long.compare(o1.getOffset(), o2.getOffset());
}
});
// merge overlapping ranges
long maxReadSizeBytes = maxReadSize.toBytes();
long maxMergeDistanceBytes = maxMergeDistance.toBytes();
ImmutableList.Builder<DiskRange> result = ImmutableList.builder();
DiskRange last = ranges.get(0);
for (int i = 1; i < ranges.size(); i++) {
DiskRange current = ranges.get(i);
DiskRange merged = last.span(current);
if (merged.getLength() <= maxReadSizeBytes && last.getEnd() + maxMergeDistanceBytes >= current.getOffset()) {
last = merged;
}
else {
result.add(last);
last = current;
}
}
result.add(last);
return result.build();
} } | public class class_name {
public static List<DiskRange> mergeAdjacentDiskRanges(Collection<DiskRange> diskRanges, DataSize maxMergeDistance, DataSize maxReadSize)
{
// sort ranges by start offset
List<DiskRange> ranges = new ArrayList<>(diskRanges);
Collections.sort(ranges, new Comparator<DiskRange>()
{
@Override
public int compare(DiskRange o1, DiskRange o2)
{
return Long.compare(o1.getOffset(), o2.getOffset());
}
});
// merge overlapping ranges
long maxReadSizeBytes = maxReadSize.toBytes();
long maxMergeDistanceBytes = maxMergeDistance.toBytes();
ImmutableList.Builder<DiskRange> result = ImmutableList.builder();
DiskRange last = ranges.get(0);
for (int i = 1; i < ranges.size(); i++) {
DiskRange current = ranges.get(i);
DiskRange merged = last.span(current);
if (merged.getLength() <= maxReadSizeBytes && last.getEnd() + maxMergeDistanceBytes >= current.getOffset()) {
last = merged; // depends on control dependency: [if], data = [none]
}
else {
result.add(last); // depends on control dependency: [if], data = [none]
last = current; // depends on control dependency: [if], data = [none]
}
}
result.add(last);
return result.build();
} } |
public class class_name {
public Hessian2Output createHessian2Output()
{
Hessian2Output out = _freeHessian2Output.allocate();
if (out == null) {
out = new Hessian2Output();
out.setSerializerFactory(getSerializerFactory());
}
return out;
} } | public class class_name {
public Hessian2Output createHessian2Output()
{
Hessian2Output out = _freeHessian2Output.allocate();
if (out == null) {
out = new Hessian2Output(); // depends on control dependency: [if], data = [none]
out.setSerializerFactory(getSerializerFactory()); // depends on control dependency: [if], data = [none]
}
return out;
} } |
public class class_name {
public void marshall(StopDeliveryStreamEncryptionRequest stopDeliveryStreamEncryptionRequest, ProtocolMarshaller protocolMarshaller) {
if (stopDeliveryStreamEncryptionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(stopDeliveryStreamEncryptionRequest.getDeliveryStreamName(), DELIVERYSTREAMNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(StopDeliveryStreamEncryptionRequest stopDeliveryStreamEncryptionRequest, ProtocolMarshaller protocolMarshaller) {
if (stopDeliveryStreamEncryptionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(stopDeliveryStreamEncryptionRequest.getDeliveryStreamName(), DELIVERYSTREAMNAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void postProcessDistances(double distances[]) {
for(int i = 0; i < distances.length; i++) {
distances[i] = Math.sqrt(distances[i]);
}
} } | public class class_name {
public void postProcessDistances(double distances[]) {
for(int i = 0; i < distances.length; i++) {
distances[i] = Math.sqrt(distances[i]); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
@Override
public List<String> getNodeNames(CommandContext ctx, OperationRequestAddress prefix) {
ModelControllerClient client = ctx.getModelControllerClient();
if(client == null) {
return Collections.emptyList();
}
if(prefix.isEmpty()) {
throw new IllegalArgumentException("The prefix must end on a type but it's empty.");
}
if(!prefix.endsOnType()) {
throw new IllegalArgumentException("The prefix doesn't end on a type.");
}
final ModelNode request;
DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(prefix);
try {
builder.setOperationName(Util.READ_CHILDREN_NAMES);
builder.addProperty(Util.CHILD_TYPE, prefix.getNodeType());
builder.addProperty(Util.INCLUDE_SINGLETONS, "true");
request = builder.buildRequest();
} catch (OperationFormatException e1) {
throw new IllegalStateException("Failed to build operation", e1);
}
List<String> result;
try {
ModelNode outcome = client.execute(request);
if (!Util.isSuccess(outcome)) {
// TODO logging... exception?
result = Collections.emptyList();
} else {
result = Util.getList(outcome);
}
} catch (Exception e) {
result = Collections.emptyList();
}
return result;
} } | public class class_name {
@Override
public List<String> getNodeNames(CommandContext ctx, OperationRequestAddress prefix) {
ModelControllerClient client = ctx.getModelControllerClient();
if(client == null) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
if(prefix.isEmpty()) {
throw new IllegalArgumentException("The prefix must end on a type but it's empty.");
}
if(!prefix.endsOnType()) {
throw new IllegalArgumentException("The prefix doesn't end on a type.");
}
final ModelNode request;
DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(prefix);
try {
builder.setOperationName(Util.READ_CHILDREN_NAMES); // depends on control dependency: [try], data = [none]
builder.addProperty(Util.CHILD_TYPE, prefix.getNodeType()); // depends on control dependency: [try], data = [none]
builder.addProperty(Util.INCLUDE_SINGLETONS, "true"); // depends on control dependency: [try], data = [none]
request = builder.buildRequest(); // depends on control dependency: [try], data = [none]
} catch (OperationFormatException e1) {
throw new IllegalStateException("Failed to build operation", e1);
} // depends on control dependency: [catch], data = [none]
List<String> result;
try {
ModelNode outcome = client.execute(request);
if (!Util.isSuccess(outcome)) {
// TODO logging... exception?
result = Collections.emptyList(); // depends on control dependency: [if], data = [none]
} else {
result = Util.getList(outcome); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
result = Collections.emptyList();
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
private boolean isRecursiveDeleteSafe(@Nullable AlluxioURI alluxioUri) {
if (alluxioUri == null || !alluxioUri.toString().startsWith(mRootPath.toString())) {
// Path is not part of sub-tree being deleted
return false;
}
if (mUfsSyncChecker == null) {
// Delete is unchecked
return true;
}
return mUfsSyncChecker.isDirectoryInSync(alluxioUri);
} } | public class class_name {
private boolean isRecursiveDeleteSafe(@Nullable AlluxioURI alluxioUri) {
if (alluxioUri == null || !alluxioUri.toString().startsWith(mRootPath.toString())) {
// Path is not part of sub-tree being deleted
return false; // depends on control dependency: [if], data = [none]
}
if (mUfsSyncChecker == null) {
// Delete is unchecked
return true; // depends on control dependency: [if], data = [none]
}
return mUfsSyncChecker.isDirectoryInSync(alluxioUri);
} } |
public class class_name {
private static String getFullNameForItemGroup(@Nullable BlueOrganization org, @Nonnull ItemGroup itemGroup) {
if (itemGroup instanceof Item) {
return getFullNameForItem(org, (Item)itemGroup);
} else {
return itemGroup.getFullName();
}
} } | public class class_name {
private static String getFullNameForItemGroup(@Nullable BlueOrganization org, @Nonnull ItemGroup itemGroup) {
if (itemGroup instanceof Item) {
return getFullNameForItem(org, (Item)itemGroup); // depends on control dependency: [if], data = [none]
} else {
return itemGroup.getFullName(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public FieldDoc wrap(FieldDoc source) {
if (source == null || source instanceof Proxy<?> || !(source instanceof FieldDocImpl)) {
return source;
}
return new FieldDocWrapper((FieldDocImpl) source);
} } | public class class_name {
public FieldDoc wrap(FieldDoc source) {
if (source == null || source instanceof Proxy<?> || !(source instanceof FieldDocImpl)) {
return source; // depends on control dependency: [if], data = [none]
}
return new FieldDocWrapper((FieldDocImpl) source);
} } |
public class class_name {
public static DataType getDtypeFromContext() {
try {
lock.readLock().lock();
if (dtype == null) {
lock.readLock().unlock();
lock.writeLock().lock();
if (dtype == null)
dtype = getDtypeFromContext(Nd4jContext.getInstance().getConf().getProperty("dtype"));
lock.writeLock().unlock();
lock.readLock().lock();
}
return dtype;
} finally {
lock.readLock().unlock();
}
} } | public class class_name {
public static DataType getDtypeFromContext() {
try {
lock.readLock().lock(); // depends on control dependency: [try], data = [none]
if (dtype == null) {
lock.readLock().unlock(); // depends on control dependency: [if], data = [none]
lock.writeLock().lock(); // depends on control dependency: [if], data = [none]
if (dtype == null)
dtype = getDtypeFromContext(Nd4jContext.getInstance().getConf().getProperty("dtype"));
lock.writeLock().unlock(); // depends on control dependency: [if], data = [none]
lock.readLock().lock(); // depends on control dependency: [if], data = [none]
}
return dtype; // depends on control dependency: [try], data = [none]
} finally {
lock.readLock().unlock();
}
} } |
public class class_name {
private static RLPList decodeRLPList(ByteBuffer bb) {
byte firstByte = bb.get();
int firstByteUnsigned = firstByte & 0xFF;
long payloadSize=-1;
if ((firstByteUnsigned>=0xc0) && (firstByteUnsigned<=0xf7)) {
// length of the list in bytes
int offsetSmallList = 0xc0 & 0xff;
payloadSize=(long)(firstByteUnsigned) - offsetSmallList;
} else if ((firstByteUnsigned>=0xf8) && (firstByteUnsigned<=0xff)) {
// read size of indicator (size of the size)
int noOfBytesSize = firstByteUnsigned-0xf7;
byte[] indicator = new byte[noOfBytesSize+1];
indicator[0]=firstByte;
bb.get(indicator, 1, noOfBytesSize);
// read the size of the data
payloadSize = convertIndicatorToRLPSize(indicator);
} else {
LOG.error("Invalid RLP encoded list detected");
}
ArrayList<RLPObject> payloadList=new ArrayList<>();
if (payloadSize>0) {
byte[] payload=new byte[(int) payloadSize];
bb.get(payload);
ByteBuffer payloadBB=ByteBuffer.wrap(payload);
while(payloadBB.remaining()>0) {
switch (EthereumUtil.detectRLPObjectType(payloadBB)) {
case EthereumUtil.RLP_OBJECTTYPE_ELEMENT:
payloadList.add(EthereumUtil.decodeRLPElement(payloadBB));
break;
case EthereumUtil.RLP_OBJECTTYPE_LIST:
payloadList.add(EthereumUtil.decodeRLPList(payloadBB));
break;
default: LOG.error("Unknown object type");
}
}
}
return new RLPList(payloadList);
} } | public class class_name {
private static RLPList decodeRLPList(ByteBuffer bb) {
byte firstByte = bb.get();
int firstByteUnsigned = firstByte & 0xFF;
long payloadSize=-1;
if ((firstByteUnsigned>=0xc0) && (firstByteUnsigned<=0xf7)) {
// length of the list in bytes
int offsetSmallList = 0xc0 & 0xff;
payloadSize=(long)(firstByteUnsigned) - offsetSmallList; // depends on control dependency: [if], data = [none]
} else if ((firstByteUnsigned>=0xf8) && (firstByteUnsigned<=0xff)) {
// read size of indicator (size of the size)
int noOfBytesSize = firstByteUnsigned-0xf7;
byte[] indicator = new byte[noOfBytesSize+1];
indicator[0]=firstByte; // depends on control dependency: [if], data = [none]
bb.get(indicator, 1, noOfBytesSize); // depends on control dependency: [if], data = [none]
// read the size of the data
payloadSize = convertIndicatorToRLPSize(indicator); // depends on control dependency: [if], data = [none]
} else {
LOG.error("Invalid RLP encoded list detected"); // depends on control dependency: [if], data = [none]
}
ArrayList<RLPObject> payloadList=new ArrayList<>();
if (payloadSize>0) {
byte[] payload=new byte[(int) payloadSize];
bb.get(payload); // depends on control dependency: [if], data = [none]
ByteBuffer payloadBB=ByteBuffer.wrap(payload);
while(payloadBB.remaining()>0) {
switch (EthereumUtil.detectRLPObjectType(payloadBB)) {
case EthereumUtil.RLP_OBJECTTYPE_ELEMENT:
payloadList.add(EthereumUtil.decodeRLPElement(payloadBB));
break;
case EthereumUtil.RLP_OBJECTTYPE_LIST:
payloadList.add(EthereumUtil.decodeRLPList(payloadBB));
break;
default: LOG.error("Unknown object type");
}
}
}
return new RLPList(payloadList);
} } |
public class class_name {
public T[] getQuantiles(final double[] fRanks) {
if (isEmpty()) { return null; }
ItemsAuxiliary<T> aux = null;
@SuppressWarnings("unchecked")
final T[] quantiles = (T[]) Array.newInstance(minValue_.getClass(), fRanks.length);
for (int i = 0; i < fRanks.length; i++) {
final double fRank = fRanks[i];
if (fRank == 0.0) { quantiles[i] = minValue_; }
else if (fRank == 1.0) { quantiles[i] = maxValue_; }
else {
if (aux == null) {
aux = this.constructAuxiliary();
}
quantiles[i] = aux.getQuantile(fRank);
}
}
return quantiles;
} } | public class class_name {
public T[] getQuantiles(final double[] fRanks) {
if (isEmpty()) { return null; } // depends on control dependency: [if], data = [none]
ItemsAuxiliary<T> aux = null;
@SuppressWarnings("unchecked")
final T[] quantiles = (T[]) Array.newInstance(minValue_.getClass(), fRanks.length);
for (int i = 0; i < fRanks.length; i++) {
final double fRank = fRanks[i];
if (fRank == 0.0) { quantiles[i] = minValue_; } // depends on control dependency: [if], data = [none]
else if (fRank == 1.0) { quantiles[i] = maxValue_; } // depends on control dependency: [if], data = [none]
else {
if (aux == null) {
aux = this.constructAuxiliary(); // depends on control dependency: [if], data = [none]
}
quantiles[i] = aux.getQuantile(fRank); // depends on control dependency: [if], data = [(fRank]
}
}
return quantiles;
} } |
public class class_name {
private void vaildateHostPort(String host, String port)
{
if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())
{
logger.error("Host or port should not be null / port should be numeric");
throw new IllegalArgumentException("Host or port should not be null / port should be numeric");
}
} } | public class class_name {
private void vaildateHostPort(String host, String port)
{
if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())
{
logger.error("Host or port should not be null / port should be numeric"); // depends on control dependency: [if], data = [none]
throw new IllegalArgumentException("Host or port should not be null / port should be numeric");
}
} } |
public class class_name {
private void update(int seqNo, long guessedIndex) {
long delta = guessedIndex - (((long) this.roc) << 16 | this.seqNum);
/* update the replay bit mask */
if (delta > 0) {
replayWindow = replayWindow << delta;
replayWindow |= 1;
} else {
replayWindow |= (1 << delta);
}
if (seqNo > seqNum) {
seqNum = seqNo & 0xffff;
}
if (this.guessedROC > this.roc) {
roc = guessedROC;
seqNum = seqNo & 0xffff;
}
} } | public class class_name {
private void update(int seqNo, long guessedIndex) {
long delta = guessedIndex - (((long) this.roc) << 16 | this.seqNum);
/* update the replay bit mask */
if (delta > 0) {
replayWindow = replayWindow << delta; // depends on control dependency: [if], data = [none]
replayWindow |= 1; // depends on control dependency: [if], data = [none]
} else {
replayWindow |= (1 << delta); // depends on control dependency: [if], data = [none]
}
if (seqNo > seqNum) {
seqNum = seqNo & 0xffff; // depends on control dependency: [if], data = [none]
}
if (this.guessedROC > this.roc) {
roc = guessedROC; // depends on control dependency: [if], data = [none]
seqNum = seqNo & 0xffff; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static VoltTable unionTables(Collection<VoltTable> operands) {
VoltTable result = null;
// Locate the first non-null table to get the schema
for (VoltTable vt : operands) {
if (vt != null) {
result = new VoltTable(vt.getTableSchema());
result.setStatusCode(vt.getStatusCode());
break;
}
}
if (result != null) {
result.addTables(operands);
result.resetRowPosition();
}
return result;
} } | public class class_name {
public static VoltTable unionTables(Collection<VoltTable> operands) {
VoltTable result = null;
// Locate the first non-null table to get the schema
for (VoltTable vt : operands) {
if (vt != null) {
result = new VoltTable(vt.getTableSchema()); // depends on control dependency: [if], data = [(vt]
result.setStatusCode(vt.getStatusCode()); // depends on control dependency: [if], data = [(vt]
break;
}
}
if (result != null) {
result.addTables(operands); // depends on control dependency: [if], data = [none]
result.resetRowPosition(); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public static void putIfAbsent(Map<String, String> map, String name, String value) {
if (!map.containsKey(name)) {
map.put(name, value);
}
} } | public class class_name {
public static void putIfAbsent(Map<String, String> map, String name, String value) {
if (!map.containsKey(name)) {
map.put(name, value); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static boolean isHeaderAllowingMultipleValues(final Buffer headerName) {
final int size = headerName.getReadableBytes();
if (size == 7) {
return !isSubjectHeader(headerName);
} else if (size == 5) {
return !isAllowHeader(headerName);
} else if (size == 4) {
return !isDateHeader(headerName);
} else if (size == 1) {
return !isAllowEventsHeaderShort(headerName);
} else if (size == 12) {
return !isAllowEventsHeader(headerName);
}
return true;
} } | public class class_name {
private static boolean isHeaderAllowingMultipleValues(final Buffer headerName) {
final int size = headerName.getReadableBytes();
if (size == 7) {
return !isSubjectHeader(headerName); // depends on control dependency: [if], data = [none]
} else if (size == 5) {
return !isAllowHeader(headerName); // depends on control dependency: [if], data = [none]
} else if (size == 4) {
return !isDateHeader(headerName); // depends on control dependency: [if], data = [none]
} else if (size == 1) {
return !isAllowEventsHeaderShort(headerName); // depends on control dependency: [if], data = [none]
} else if (size == 12) {
return !isAllowEventsHeader(headerName); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public static ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
if (cl == null) {
// When this method is called for initializing a ICU4J class
// during bootstrap, cl might be still null (other than Android?).
// In this case, we want to use the bootstrap class loader.
cl = getBootstrapClassLoader();
}
}
return cl;
} } | public class class_name {
public static ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = ClassLoader.getSystemClassLoader(); // depends on control dependency: [if], data = [none]
if (cl == null) {
// When this method is called for initializing a ICU4J class
// during bootstrap, cl might be still null (other than Android?).
// In this case, we want to use the bootstrap class loader.
cl = getBootstrapClassLoader(); // depends on control dependency: [if], data = [none]
}
}
return cl;
} } |
public class class_name {
private static void
transferNonExistingSymbols(List<String> symbolsList,
Map<String, Integer> symbolsMap)
{
int sid = 1;
for (String text : symbolsList)
{
assert text == null || text.length() > 0;
if (text != null)
{
putToMapIfNotThere(symbolsMap, text, sid);
}
sid++;
}
} } | public class class_name {
private static void
transferNonExistingSymbols(List<String> symbolsList,
Map<String, Integer> symbolsMap)
{
int sid = 1;
for (String text : symbolsList)
{
assert text == null || text.length() > 0; // depends on control dependency: [for], data = [text]
if (text != null)
{
putToMapIfNotThere(symbolsMap, text, sid); // depends on control dependency: [if], data = [none]
}
sid++; // depends on control dependency: [for], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.