code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public void shrink(int delta) {
if (delta <= 0) {
return;
}
int newLimit = buffer.limit() - delta;
if (newLimit <= 0) {
newLimit = 0;
}
this.buffer.limit(newLimit);
} } | public class class_name {
public void shrink(int delta) {
if (delta <= 0) {
return; // depends on control dependency: [if], data = [none]
}
int newLimit = buffer.limit() - delta;
if (newLimit <= 0) {
newLimit = 0; // depends on control dependency: [if], data = [none]
}
this.buffer.limit(newLimit);
} } |
public class class_name {
public void drawImage (final PDInlineImage inlineImage,
final float x,
final float y,
final float width,
final float height) throws IOException
{
if (inTextMode)
{
throw new IllegalStateException ("Error: drawImage is not allowed within a text block.");
}
saveGraphicsState ();
transform (new Matrix (width, 0, 0, height, x, y));
// create the image dictionary
final StringBuilder sb = new StringBuilder ();
sb.append ("BI");
sb.append ("\n /W ");
sb.append (inlineImage.getWidth ());
sb.append ("\n /H ");
sb.append (inlineImage.getHeight ());
sb.append ("\n /CS ");
sb.append ("/");
sb.append (inlineImage.getColorSpace ().getName ());
if (inlineImage.getDecode () != null && inlineImage.getDecode ().size () > 0)
{
sb.append ("\n /D ");
sb.append ("[");
for (final COSBase base : inlineImage.getDecode ())
{
sb.append (((COSNumber) base).intValue ());
sb.append (" ");
}
sb.append ("]");
}
if (inlineImage.isStencil ())
{
sb.append ("\n /IM true");
}
sb.append ("\n /BPC ");
sb.append (inlineImage.getBitsPerComponent ());
// image dictionary
write (sb.toString ());
writeLine ();
// binary data
writeOperator ((byte) 'I', (byte) 'D');
writeBytes (inlineImage.getData ());
writeLine ();
writeOperator ((byte) 'E', (byte) 'I');
restoreGraphicsState ();
} } | public class class_name {
public void drawImage (final PDInlineImage inlineImage,
final float x,
final float y,
final float width,
final float height) throws IOException
{
if (inTextMode)
{
throw new IllegalStateException ("Error: drawImage is not allowed within a text block.");
}
saveGraphicsState ();
transform (new Matrix (width, 0, 0, height, x, y));
// create the image dictionary
final StringBuilder sb = new StringBuilder ();
sb.append ("BI");
sb.append ("\n /W ");
sb.append (inlineImage.getWidth ());
sb.append ("\n /H ");
sb.append (inlineImage.getHeight ());
sb.append ("\n /CS ");
sb.append ("/");
sb.append (inlineImage.getColorSpace ().getName ());
if (inlineImage.getDecode () != null && inlineImage.getDecode ().size () > 0)
{
sb.append ("\n /D ");
sb.append ("[");
for (final COSBase base : inlineImage.getDecode ())
{
sb.append (((COSNumber) base).intValue ()); // depends on control dependency: [for], data = [base]
sb.append (" "); // depends on control dependency: [for], data = [none]
}
sb.append ("]");
}
if (inlineImage.isStencil ())
{
sb.append ("\n /IM true");
}
sb.append ("\n /BPC ");
sb.append (inlineImage.getBitsPerComponent ());
// image dictionary
write (sb.toString ());
writeLine ();
// binary data
writeOperator ((byte) 'I', (byte) 'D');
writeBytes (inlineImage.getData ());
writeLine ();
writeOperator ((byte) 'E', (byte) 'I');
restoreGraphicsState ();
} } |
public class class_name {
private void processDependencies(JsonObject json, File baseDir, File rootFile,
String parentPackage, Engine engine) throws AnalysisException {
if (json.containsKey("dependencies")) {
final JsonObject deps = json.getJsonObject("dependencies");
for (Map.Entry<String, JsonValue> entry : deps.entrySet()) {
final JsonObject jo = (JsonObject) entry.getValue();
final String name = entry.getKey();
final String version = jo.getString("version");
final File base = Paths.get(baseDir.getPath(), "node_modules", name).toFile();
final File f = new File(base, PACKAGE_JSON);
if (jo.containsKey("dependencies")) {
final String subPackageName = String.format("%s/%s:%s", parentPackage, name, version);
processDependencies(jo, base, rootFile, subPackageName, engine);
}
final Dependency child;
if (f.exists()) {
//TOOD - we should use the integrity value instead of calculating the SHA1/MD5
child = new Dependency(f);
child.setEcosystem(DEPENDENCY_ECOSYSTEM);
try (JsonReader jr = Json.createReader(FileUtils.openInputStream(f))) {
final JsonObject childJson = jr.readObject();
gatherEvidence(childJson, child);
} catch (JsonException e) {
LOGGER.warn("Failed to parse package.json file from dependency.", e);
} catch (IOException e) {
throw new AnalysisException("Problem occurred while reading dependency file.", e);
}
} else {
LOGGER.warn("Unable to find node module: {}", f.toString());
child = new Dependency(rootFile, true);
child.setEcosystem(DEPENDENCY_ECOSYSTEM);
//TOOD - we should use the integrity value instead of calculating the SHA1/MD5
child.setSha1sum(Checksum.getSHA1Checksum(String.format("%s:%s", name, version)));
child.setSha256sum(Checksum.getSHA256Checksum(String.format("%s:%s", name, version)));
child.setMd5sum(Checksum.getMD5Checksum(String.format("%s:%s", name, version)));
child.addEvidence(EvidenceType.VENDOR, rootFile.getName(), "name", name, Confidence.HIGHEST);
child.addEvidence(EvidenceType.PRODUCT, rootFile.getName(), "name", name, Confidence.HIGHEST);
child.addEvidence(EvidenceType.VERSION, rootFile.getName(), "version", version, Confidence.HIGHEST);
child.setName(name);
child.setVersion(version);
final String packagePath = String.format("%s:%s", name, version);
child.setDisplayFileName(packagePath);
child.setPackagePath(packagePath);
}
child.addProjectReference(parentPackage);
child.setEcosystem(DEPENDENCY_ECOSYSTEM);
final Dependency existing = findDependency(engine, name, version);
if (existing != null) {
if (existing.isVirtual()) {
DependencyMergingAnalyzer.mergeDependencies(child, existing, null);
engine.removeDependency(existing);
engine.addDependency(child);
} else {
DependencyBundlingAnalyzer.mergeDependencies(existing, child, null);
}
} else {
engine.addDependency(child);
}
}
}
} } | public class class_name {
private void processDependencies(JsonObject json, File baseDir, File rootFile,
String parentPackage, Engine engine) throws AnalysisException {
if (json.containsKey("dependencies")) {
final JsonObject deps = json.getJsonObject("dependencies");
for (Map.Entry<String, JsonValue> entry : deps.entrySet()) {
final JsonObject jo = (JsonObject) entry.getValue();
final String name = entry.getKey();
final String version = jo.getString("version");
final File base = Paths.get(baseDir.getPath(), "node_modules", name).toFile();
final File f = new File(base, PACKAGE_JSON);
if (jo.containsKey("dependencies")) {
final String subPackageName = String.format("%s/%s:%s", parentPackage, name, version);
processDependencies(jo, base, rootFile, subPackageName, engine); // depends on control dependency: [if], data = [none]
}
final Dependency child;
if (f.exists()) {
//TOOD - we should use the integrity value instead of calculating the SHA1/MD5
child = new Dependency(f); // depends on control dependency: [if], data = [none]
child.setEcosystem(DEPENDENCY_ECOSYSTEM); // depends on control dependency: [if], data = [none]
try (JsonReader jr = Json.createReader(FileUtils.openInputStream(f))) {
final JsonObject childJson = jr.readObject();
gatherEvidence(childJson, child); // depends on control dependency: [if], data = [none]
} catch (JsonException e) { // depends on control dependency: [for], data = [none]
LOGGER.warn("Failed to parse package.json file from dependency.", e);
} catch (IOException e) { // depends on control dependency: [for], data = [none]
throw new AnalysisException("Problem occurred while reading dependency file.", e);
}
} else {
LOGGER.warn("Unable to find node module: {}", f.toString());
child = new Dependency(rootFile, true);
child.setEcosystem(DEPENDENCY_ECOSYSTEM);
//TOOD - we should use the integrity value instead of calculating the SHA1/MD5
child.setSha1sum(Checksum.getSHA1Checksum(String.format("%s:%s", name, version)));
child.setSha256sum(Checksum.getSHA256Checksum(String.format("%s:%s", name, version)));
child.setMd5sum(Checksum.getMD5Checksum(String.format("%s:%s", name, version)));
child.addEvidence(EvidenceType.VENDOR, rootFile.getName(), "name", name, Confidence.HIGHEST);
child.addEvidence(EvidenceType.PRODUCT, rootFile.getName(), "name", name, Confidence.HIGHEST);
child.addEvidence(EvidenceType.VERSION, rootFile.getName(), "version", version, Confidence.HIGHEST);
child.setName(name);
child.setVersion(version);
final String packagePath = String.format("%s:%s", name, version);
child.setDisplayFileName(packagePath);
child.setPackagePath(packagePath);
}
child.addProjectReference(parentPackage);
child.setEcosystem(DEPENDENCY_ECOSYSTEM);
final Dependency existing = findDependency(engine, name, version);
if (existing != null) {
if (existing.isVirtual()) {
DependencyMergingAnalyzer.mergeDependencies(child, existing, null); // depends on control dependency: [if], data = [none]
engine.removeDependency(existing); // depends on control dependency: [if], data = [none]
engine.addDependency(child); // depends on control dependency: [if], data = [none]
} else {
DependencyBundlingAnalyzer.mergeDependencies(existing, child, null); // depends on control dependency: [if], data = [none]
}
} else {
engine.addDependency(child); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
protected final void assertDoesNotHaveDuplicates() {
isNotNull();
Collection<?> duplicates = duplicatesFrom(actualAsList());
if (duplicates.isEmpty()) {
return;
}
failIfCustomMessageIsSet();
throw failure(format("<%s> contains duplicate(s):<%s>", actual, duplicates));
} } | public class class_name {
protected final void assertDoesNotHaveDuplicates() {
isNotNull();
Collection<?> duplicates = duplicatesFrom(actualAsList());
if (duplicates.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
failIfCustomMessageIsSet();
throw failure(format("<%s> contains duplicate(s):<%s>", actual, duplicates));
} } |
public class class_name {
@Override
public void startMonitor() {
// 监听application.yml变化
executor.scheduleWithFixedDelay(() -> {
try {
loadRemoteConfig();
} catch (Throwable e) {
logger.error("scan remote application.yml failed", e);
}
}, 10, 3, TimeUnit.SECONDS);
// 监听adapter变化
executor.scheduleWithFixedDelay(() -> {
try {
loadRemoteAdapterConfigs();
} catch (Throwable e) {
logger.error("scan remote adapter configs failed", e);
}
}, 10, 3, TimeUnit.SECONDS);
} } | public class class_name {
@Override
public void startMonitor() {
// 监听application.yml变化
executor.scheduleWithFixedDelay(() -> {
try {
loadRemoteConfig();
// depends on control dependency: [try], data = [none]
} catch (Throwable e) {
logger.error("scan remote application.yml failed", e);
}
// depends on control dependency: [catch], data = [none]
}, 10, 3, TimeUnit.SECONDS);
// 监听adapter变化
executor.scheduleWithFixedDelay(() -> {
try {
loadRemoteAdapterConfigs();
// depends on control dependency: [try], data = [none]
} catch (Throwable e) {
logger.error("scan remote adapter configs failed", e);
}
// depends on control dependency: [catch], data = [none]
}, 10, 3, TimeUnit.SECONDS);
} } |
public class class_name {
public static boolean isTime(String s)
{
// Build a time formatter using the format specified by timeFormat
DateFormat dateFormatter = new SimpleDateFormat(timeFormat);
try
{
dateFormatter.parse(s);
return true;
}
catch (ParseException e)
{
// Exception noted so can be ignored.
e = null;
return false;
}
} } | public class class_name {
public static boolean isTime(String s)
{
// Build a time formatter using the format specified by timeFormat
DateFormat dateFormatter = new SimpleDateFormat(timeFormat);
try
{
dateFormatter.parse(s); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
}
catch (ParseException e)
{
// Exception noted so can be ignored.
e = null;
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void doNotifyListenersOfRemovedValues(Set<R> oldItems) {
List<SetValueChangeListener<R>> listenersCopy = new ArrayList<SetValueChangeListener<R>>(listeners);
Set<R> unmodifiable = Collections.unmodifiableSet(oldItems);
for (SetValueChangeListener<R> listener : listenersCopy) {
listener.valuesRemoved(this, unmodifiable);
}
} } | public class class_name {
protected void doNotifyListenersOfRemovedValues(Set<R> oldItems) {
List<SetValueChangeListener<R>> listenersCopy = new ArrayList<SetValueChangeListener<R>>(listeners);
Set<R> unmodifiable = Collections.unmodifiableSet(oldItems);
for (SetValueChangeListener<R> listener : listenersCopy) {
listener.valuesRemoved(this, unmodifiable); // depends on control dependency: [for], data = [listener]
}
} } |
public class class_name {
private void generateBuilderClass() {
if (data.isSkipBuilderGeneration()) {
return;
}
List<PropertyGen> nonDerived = nonDerivedProperties();
generateSeparator();
String finalType = data.isTypeFinal() ? "final " : "";
addLine(1, "/**");
addLine(1, " * The bean-builder for {@code " + data.getTypeRaw() + "}.");
if (data.isTypeGeneric()) {
for (int j = 0; j < data.getTypeGenericCount(); j++) {
addLine(1, " * @param " + data.getTypeGenericName(j, true) + " the type");
}
}
addLine(1, " */");
String superBuilder;
if (data.isSubClass()) {
superBuilder = data.getSuperTypeRaw() + ".Builder" + data.getSuperTypeGeneric(true);
} else if (data.isEffectiveBuilderScopeVisible()) {
data.ensureImport(DirectFieldsBeanBuilder.class);
superBuilder = "DirectFieldsBeanBuilder<" + data.getTypeNoExtends() + ">";
} else {
data.ensureImport(DirectPrivateBeanBuilder.class);
superBuilder = "DirectPrivateBeanBuilder<" + data.getTypeNoExtends() + ">";
}
if (data.isConstructable()) {
addLine(1, data.getEffectiveBuilderScope() + "static " + finalType +
"class Builder" + data.getTypeGeneric(true) + " extends " + superBuilder + " {");
} else {
addLine(1, data.getEffectiveBuilderScope() + "abstract static " + finalType +
"class Builder" + data.getTypeGeneric(true) + " extends " + superBuilder + " {");
}
if (nonDerived.size() > 0) {
addBlankLine();
generateBuilderProperties();
}
addBlankLine();
generateBuilderConstructorNoArgs();
generateBuilderConstructorCopy();
generateIndentedSeparator();
generateBuilderGet();
generateBuilderSet();
generateBuilderOtherSets();
if (data.isConstructable()) {
generateBuilderBuild();
}
generateIndentedSeparator();
generateBuilderPropertySetMethods();
generateIndentedSeparator();
generateBuilderToString();
addLine(1, "}");
addBlankLine();
} } | public class class_name {
private void generateBuilderClass() {
if (data.isSkipBuilderGeneration()) {
return; // depends on control dependency: [if], data = [none]
}
List<PropertyGen> nonDerived = nonDerivedProperties();
generateSeparator();
String finalType = data.isTypeFinal() ? "final " : "";
addLine(1, "/**");
addLine(1, " * The bean-builder for {@code " + data.getTypeRaw() + "}.");
if (data.isTypeGeneric()) {
for (int j = 0; j < data.getTypeGenericCount(); j++) {
addLine(1, " * @param " + data.getTypeGenericName(j, true) + " the type");
}
}
addLine(1, " */");
String superBuilder;
if (data.isSubClass()) {
superBuilder = data.getSuperTypeRaw() + ".Builder" + data.getSuperTypeGeneric(true); // depends on control dependency: [if], data = [none]
} else if (data.isEffectiveBuilderScopeVisible()) {
data.ensureImport(DirectFieldsBeanBuilder.class); // depends on control dependency: [if], data = [none]
superBuilder = "DirectFieldsBeanBuilder<" + data.getTypeNoExtends() + ">"; // depends on control dependency: [if], data = [none]
} else {
data.ensureImport(DirectPrivateBeanBuilder.class); // depends on control dependency: [if], data = [none]
superBuilder = "DirectPrivateBeanBuilder<" + data.getTypeNoExtends() + ">"; // depends on control dependency: [if], data = [none]
}
if (data.isConstructable()) {
addLine(1, data.getEffectiveBuilderScope() + "static " + finalType +
"class Builder" + data.getTypeGeneric(true) + " extends " + superBuilder + " {"); // depends on control dependency: [if], data = [none]
} else {
addLine(1, data.getEffectiveBuilderScope() + "abstract static " + finalType +
"class Builder" + data.getTypeGeneric(true) + " extends " + superBuilder + " {"); // depends on control dependency: [if], data = [none]
}
if (nonDerived.size() > 0) {
addBlankLine(); // depends on control dependency: [if], data = [none]
generateBuilderProperties(); // depends on control dependency: [if], data = [none]
}
addBlankLine();
generateBuilderConstructorNoArgs();
generateBuilderConstructorCopy();
generateIndentedSeparator();
generateBuilderGet();
generateBuilderSet();
generateBuilderOtherSets();
if (data.isConstructable()) {
generateBuilderBuild(); // depends on control dependency: [if], data = [none]
}
generateIndentedSeparator();
generateBuilderPropertySetMethods();
generateIndentedSeparator();
generateBuilderToString();
addLine(1, "}");
addBlankLine();
} } |
public class class_name {
public boolean nextLine() throws IOException {
while(reader.readLine(buf.delete(0, buf.length()))) {
++lineNumber;
if(lengthWithoutLinefeed(buf) > 0) {
return true;
}
}
return false;
} } | public class class_name {
public boolean nextLine() throws IOException {
while(reader.readLine(buf.delete(0, buf.length()))) {
++lineNumber;
if(lengthWithoutLinefeed(buf) > 0) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public void marshall(HandshakeFilter handshakeFilter, ProtocolMarshaller protocolMarshaller) {
if (handshakeFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(handshakeFilter.getActionType(), ACTIONTYPE_BINDING);
protocolMarshaller.marshall(handshakeFilter.getParentHandshakeId(), PARENTHANDSHAKEID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(HandshakeFilter handshakeFilter, ProtocolMarshaller protocolMarshaller) {
if (handshakeFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(handshakeFilter.getActionType(), ACTIONTYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(handshakeFilter.getParentHandshakeId(), PARENTHANDSHAKEID_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 {
void notifyAcceptOutbind(Outbind outbind) throws IllegalStateException {
this.lock.lock();
try {
if (this.request == null) {
this.request = new OutbindRequest(outbind);
this.requestCondition.signal();
}
else {
throw new IllegalStateException("Already waiting for acceptance outbind");
}
}
finally {
this.lock.unlock();
}
} } | public class class_name {
void notifyAcceptOutbind(Outbind outbind) throws IllegalStateException {
this.lock.lock();
try {
if (this.request == null) {
this.request = new OutbindRequest(outbind); // depends on control dependency: [if], data = [none]
this.requestCondition.signal(); // depends on control dependency: [if], data = [none]
}
else {
throw new IllegalStateException("Already waiting for acceptance outbind");
}
}
finally {
this.lock.unlock();
}
} } |
public class class_name {
public static <T> String concatenate(Collection<T> values, String sepStr) {
assert values != null;
assert sepStr != null;
// Watch for the empty case first.
if (values.size() == 0) {
return "";
}
// This handles any size >= 1.
StringBuilder buffer = new StringBuilder();
boolean bFirst = true;
for (T value : values) {
if (bFirst) {
bFirst = false;
} else {
buffer.append(sepStr);
}
buffer.append(value.toString());
}
return buffer.toString();
} } | public class class_name {
public static <T> String concatenate(Collection<T> values, String sepStr) {
assert values != null;
assert sepStr != null;
// Watch for the empty case first.
if (values.size() == 0) {
return "";
// depends on control dependency: [if], data = [none]
}
// This handles any size >= 1.
StringBuilder buffer = new StringBuilder();
boolean bFirst = true;
for (T value : values) {
if (bFirst) {
bFirst = false;
// depends on control dependency: [if], data = [none]
} else {
buffer.append(sepStr);
// depends on control dependency: [if], data = [none]
}
buffer.append(value.toString());
// depends on control dependency: [for], data = [value]
}
return buffer.toString();
} } |
public class class_name {
private void resizeStorage() {
int currentElementsPerNode = maxElementsPerNode;
int newElementsPerNode = (int) (currentElementsPerNode * RESIZE_MULTIPLE);
if (newElementsPerNode <= currentElementsPerNode) {
throw new IllegalStateException("cannot resize fixed length array from "
+ currentElementsPerNode + " to " + newElementsPerNode);
}
FixedLengthElementArray newStorage = new FixedLengthElementArray(memoryRecycler,
numNodes * bitsPerElement * newElementsPerNode);
LongStream.range(0, numNodes).forEach(nodeIndex -> {
long currentBucketStart = nodeIndex * currentElementsPerNode * bitsPerElement;
long newBucketStart = nodeIndex * newElementsPerNode * bitsPerElement;
for (int offset = 0; offset < currentElementsPerNode; offset++) {
long element = storage.getElementValue(currentBucketStart + offset * bitsPerElement,
bitsPerElement, elementMask);
if (element == NO_ELEMENT) {
break; // we have exhausted the elements at this index
}
newStorage.setElementValue(
newBucketStart + offset * bitsPerElement, bitsPerElement, element);
}
});
storage.destroy(memoryRecycler);
storage = newStorage;
maxElementsPerNode = newElementsPerNode;
} } | public class class_name {
private void resizeStorage() {
int currentElementsPerNode = maxElementsPerNode;
int newElementsPerNode = (int) (currentElementsPerNode * RESIZE_MULTIPLE);
if (newElementsPerNode <= currentElementsPerNode) {
throw new IllegalStateException("cannot resize fixed length array from "
+ currentElementsPerNode + " to " + newElementsPerNode);
}
FixedLengthElementArray newStorage = new FixedLengthElementArray(memoryRecycler,
numNodes * bitsPerElement * newElementsPerNode);
LongStream.range(0, numNodes).forEach(nodeIndex -> {
long currentBucketStart = nodeIndex * currentElementsPerNode * bitsPerElement;
long newBucketStart = nodeIndex * newElementsPerNode * bitsPerElement;
for (int offset = 0; offset < currentElementsPerNode; offset++) {
long element = storage.getElementValue(currentBucketStart + offset * bitsPerElement,
bitsPerElement, elementMask);
if (element == NO_ELEMENT) {
break; // we have exhausted the elements at this index
}
newStorage.setElementValue(
newBucketStart + offset * bitsPerElement, bitsPerElement, element); // depends on control dependency: [for], data = [none]
}
});
storage.destroy(memoryRecycler);
storage = newStorage;
maxElementsPerNode = newElementsPerNode;
} } |
public class class_name {
int createUserIndexForChains() {
if (m_chainIndices == null) {
m_chainIndices = new ArrayList<AttributeStreamOfInt32>(3);
}
AttributeStreamOfInt32 new_stream = new AttributeStreamOfInt32(
m_chainData.capacity(), -1);
for (int i = 0, n = m_chainIndices.size(); i < n; i++) {
if (m_chainIndices.get(i) == null) {
m_chainIndices.set(i, new_stream);
return i;
}
}
m_chainIndices.add(new_stream);
return m_chainIndices.size() - 1;
} } | public class class_name {
int createUserIndexForChains() {
if (m_chainIndices == null) {
m_chainIndices = new ArrayList<AttributeStreamOfInt32>(3); // depends on control dependency: [if], data = [none]
}
AttributeStreamOfInt32 new_stream = new AttributeStreamOfInt32(
m_chainData.capacity(), -1);
for (int i = 0, n = m_chainIndices.size(); i < n; i++) {
if (m_chainIndices.get(i) == null) {
m_chainIndices.set(i, new_stream); // depends on control dependency: [if], data = [none]
return i; // depends on control dependency: [if], data = [none]
}
}
m_chainIndices.add(new_stream);
return m_chainIndices.size() - 1;
} } |
public class class_name {
public boolean checkAndReturn() {
// Check if any thread has been interrupted
if (interrupted.get()) {
// If so, interrupt this thread
interrupt();
return true;
}
// Check if this thread has been interrupted
if (Thread.currentThread().isInterrupted()) {
// If so, interrupt other threads
interrupted.set(true);
return true;
}
return false;
} } | public class class_name {
public boolean checkAndReturn() {
// Check if any thread has been interrupted
if (interrupted.get()) {
// If so, interrupt this thread
interrupt(); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
// Check if this thread has been interrupted
if (Thread.currentThread().isInterrupted()) {
// If so, interrupt other threads
interrupted.set(true); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static UUID getPrevious(UUID uuid) {
checkArgument(uuid.version() == 1, "Not a time UUID");
UUID min = minimumUuid();
long lsb = uuid.getLeastSignificantBits();
if (lsb > min.getLeastSignificantBits()) {
return new UUID(uuid.getMostSignificantBits(), lsb - 1);
}
long timestamp = uuid.timestamp();
if (timestamp > min.timestamp()) {
return new UUID(getMostSignificantBits(timestamp - 1), maximumUuid().getLeastSignificantBits());
}
return null; // No previous exists since uuid == minimumUuid()
} } | public class class_name {
public static UUID getPrevious(UUID uuid) {
checkArgument(uuid.version() == 1, "Not a time UUID");
UUID min = minimumUuid();
long lsb = uuid.getLeastSignificantBits();
if (lsb > min.getLeastSignificantBits()) {
return new UUID(uuid.getMostSignificantBits(), lsb - 1); // depends on control dependency: [if], data = [none]
}
long timestamp = uuid.timestamp();
if (timestamp > min.timestamp()) {
return new UUID(getMostSignificantBits(timestamp - 1), maximumUuid().getLeastSignificantBits()); // depends on control dependency: [if], data = [(timestamp]
}
return null; // No previous exists since uuid == minimumUuid()
} } |
public class class_name {
@NonNull
static Set<String> scopeCollectionToStringSet(@NonNull Collection<Scope> scopeCollection) {
Set<String> stringCollection = new HashSet<>();
for (Scope scope : scopeCollection) {
stringCollection.add(scope.name());
}
return stringCollection;
} } | public class class_name {
@NonNull
static Set<String> scopeCollectionToStringSet(@NonNull Collection<Scope> scopeCollection) {
Set<String> stringCollection = new HashSet<>();
for (Scope scope : scopeCollection) {
stringCollection.add(scope.name()); // depends on control dependency: [for], data = [scope]
}
return stringCollection;
} } |
public class class_name {
public static String[] convertListTokenToArrayStrings(
final List<Token> tokenizedSentence) {
final List<String> tokensList = new ArrayList<>();
for (final Token token : tokenizedSentence) {
tokensList.add(token.getTokenValue());
}
return tokensList.toArray(new String[tokensList.size()]);
} } | public class class_name {
public static String[] convertListTokenToArrayStrings(
final List<Token> tokenizedSentence) {
final List<String> tokensList = new ArrayList<>();
for (final Token token : tokenizedSentence) {
tokensList.add(token.getTokenValue()); // depends on control dependency: [for], data = [token]
}
return tokensList.toArray(new String[tokensList.size()]);
} } |
public class class_name {
public ModelHandler borrowtHandlerObject(String formName) {
ModelHandler modelHandler = null;
try {
modelHandler = handlerObjectFactory.borrowHandlerObject(formName);
modelHandler.setModelMapping(modelFactory.getModelMapping(formName));
} catch (Exception ex) {
Debug.logError("[JdonFramework]can't get the modelHandler for the formName " + formName, module);
returnHandlerObject(modelHandler);
}
return modelHandler;
} } | public class class_name {
public ModelHandler borrowtHandlerObject(String formName) {
ModelHandler modelHandler = null;
try {
modelHandler = handlerObjectFactory.borrowHandlerObject(formName);
// depends on control dependency: [try], data = [none]
modelHandler.setModelMapping(modelFactory.getModelMapping(formName));
// depends on control dependency: [try], data = [none]
} catch (Exception ex) {
Debug.logError("[JdonFramework]can't get the modelHandler for the formName " + formName, module);
returnHandlerObject(modelHandler);
}
// depends on control dependency: [catch], data = [none]
return modelHandler;
} } |
public class class_name {
private Collection<Sentence> readDoc() throws IOException {
final Collection<Sentence> sentences = new ArrayList<>();
StringBuilder sentence = new StringBuilder();
Collection<ConllToken> tokens = new ArrayList<>();
int tokenStartIndex = 0;
for (String line; (line = r.readLine()) != null; ) {
// empty line means end-of-sentence
if (line.isEmpty()) {
// if we have an empty line and something in the actual sentence then add it
if (sentence.length() > 0) {
sentences.add(new Sentence(sentence.toString(), tokens));
sentence = new StringBuilder();
tokens = new ArrayList<>();
tokenStartIndex = 0;
}
}
else {
// this assumes there is ever only a single space between token and classifiers
final String[] parts = SPACES.split(line);
switch (parts[0]) {
case "-DOCSTART-":
// we use DOCSTART as the end of the current doc, also throw away the following empty line
r.readLine();
// no need to think about a current sentence, the previous empty line will have saved it
return sentences;
default:
if (sentence.length() > 0) sentence.append(" ");
sentence.append(parts[0]);
tokens.add(new ConllToken(tokenStartIndex, parts[0], parts[1] + " " + parts[2], parts[3]));
tokenStartIndex += parts[0].length() + 1; // add 1 for the space between tokens
}
}
}
// if we run out of data in the file
if (sentence.length() > 0) sentences.add(new Sentence(sentence.toString(), tokens));
return sentences;
} } | public class class_name {
private Collection<Sentence> readDoc() throws IOException {
final Collection<Sentence> sentences = new ArrayList<>();
StringBuilder sentence = new StringBuilder();
Collection<ConllToken> tokens = new ArrayList<>();
int tokenStartIndex = 0;
for (String line; (line = r.readLine()) != null; ) {
// empty line means end-of-sentence
if (line.isEmpty()) {
// if we have an empty line and something in the actual sentence then add it
if (sentence.length() > 0) {
sentences.add(new Sentence(sentence.toString(), tokens)); // depends on control dependency: [if], data = [none]
sentence = new StringBuilder(); // depends on control dependency: [if], data = [none]
tokens = new ArrayList<>(); // depends on control dependency: [if], data = [none]
tokenStartIndex = 0; // depends on control dependency: [if], data = [none]
}
}
else {
// this assumes there is ever only a single space between token and classifiers
final String[] parts = SPACES.split(line);
switch (parts[0]) { // depends on control dependency: [if], data = [none]
case "-DOCSTART-":
// we use DOCSTART as the end of the current doc, also throw away the following empty line
r.readLine();
// no need to think about a current sentence, the previous empty line will have saved it
return sentences;
default:
if (sentence.length() > 0) sentence.append(" ");
sentence.append(parts[0]);
tokens.add(new ConllToken(tokenStartIndex, parts[0], parts[1] + " " + parts[2], parts[3]));
tokenStartIndex += parts[0].length() + 1; // add 1 for the space between tokens
}
}
}
// if we run out of data in the file
if (sentence.length() > 0) sentences.add(new Sentence(sentence.toString(), tokens));
return sentences;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static <K, V> Cache<K, V> getGlobalCache() {
if (caches.containsKey(GLOBAL_CACHE)) {
return Cast.as(caches.get(GLOBAL_CACHE));
}
return register(getCacheSpec(GLOBAL_CACHE));
} } | public class class_name {
@SuppressWarnings("unchecked")
public static <K, V> Cache<K, V> getGlobalCache() {
if (caches.containsKey(GLOBAL_CACHE)) {
return Cast.as(caches.get(GLOBAL_CACHE)); // depends on control dependency: [if], data = [none]
}
return register(getCacheSpec(GLOBAL_CACHE));
} } |
public class class_name {
private void addActionFromRouteElem(ControllerRouteModel<Raml> elem, Resource resource) {
Action action = new Action();
action.setType(ActionType.valueOf(elem.getHttpMethod().name()));
action.setDescription(elem.getDescription());
//handle body
addBodyToAction(elem, action);
//Handle responses
addResponsesToAction(elem, action);
//handle all route params
for (RouteParamModel<Raml> param : elem.getParams()) {
AbstractParam ap = null; //the param to add
//Fill the param info depending on its type
switch (param.getParamType()) {
case FORM:
MimeType formMime = action.getBody().get("application/x-www-form-urlencoded");
if (formMime == null) {
//create default form mimeType
formMime = new MimeType("application/x-www-form-urlencoded");
}
if (formMime.getFormParameters() == null) { //why raml, why you ain't init that
formMime.setFormParameters(new LinkedHashMap<String, List<FormParameter>>(2));
}
ap = new FormParameter();
formMime.getFormParameters().put(param.getName(), singletonList((FormParameter) ap));
break;
case PARAM:
case PATH_PARAM:
if (!ancestorOrIHasParam(resource, param.getName())) {
ap = new UriParameter();
resource.getUriParameters().put(param.getName(), (UriParameter) ap);
}
//we do nothing if the param has already been define in the resouce or its ancestor.
break;
case QUERY:
ap = new QueryParameter();
action.getQueryParameters().put(param.getName(), (QueryParameter) ap);
break;
case BODY:
default:
break; //body is handled at the method level.
}
if (ap == null) {
//no param has been created, we skip.
continue;
}
//Set param type
ParamType type = typeConverter(param.getValueType());
if (type != null) {
ap.setType(type);
}
//set required, usually thanks to the notnull constraints annotation.
if(param.isMandatory()){
ap.setRequired(true);
} else {
ap.setRequired(false);
}
//set minimum if specified
if(param.getMin()!=null){
ap.setMinimum(BigDecimal.valueOf(param.getMin()));
//TODO warn if type is not number/integer
}
//set maximum if specified
if(param.getMax()!=null){
ap.setMinimum(BigDecimal.valueOf(param.getMax()));
//TODO warn if type is not number/integer
}
//set default value
if (param.getDefaultValue() != null) {
ap.setRequired(false);
ap.setDefaultValue(param.getDefaultValue());
}
}
resource.getActions().put(action.getType(), action);
} } | public class class_name {
private void addActionFromRouteElem(ControllerRouteModel<Raml> elem, Resource resource) {
Action action = new Action();
action.setType(ActionType.valueOf(elem.getHttpMethod().name()));
action.setDescription(elem.getDescription());
//handle body
addBodyToAction(elem, action);
//Handle responses
addResponsesToAction(elem, action);
//handle all route params
for (RouteParamModel<Raml> param : elem.getParams()) {
AbstractParam ap = null; //the param to add
//Fill the param info depending on its type
switch (param.getParamType()) {
case FORM:
MimeType formMime = action.getBody().get("application/x-www-form-urlencoded");
if (formMime == null) {
//create default form mimeType
formMime = new MimeType("application/x-www-form-urlencoded"); // depends on control dependency: [if], data = [none]
}
if (formMime.getFormParameters() == null) { //why raml, why you ain't init that
formMime.setFormParameters(new LinkedHashMap<String, List<FormParameter>>(2)); // depends on control dependency: [if], data = [none]
}
ap = new FormParameter(); // depends on control dependency: [for], data = [none]
formMime.getFormParameters().put(param.getName(), singletonList((FormParameter) ap)); // depends on control dependency: [for], data = [param]
break;
case PARAM:
case PATH_PARAM:
if (!ancestorOrIHasParam(resource, param.getName())) {
ap = new UriParameter(); // depends on control dependency: [if], data = [none]
resource.getUriParameters().put(param.getName(), (UriParameter) ap); // depends on control dependency: [if], data = [none]
}
//we do nothing if the param has already been define in the resouce or its ancestor.
break;
case QUERY:
ap = new QueryParameter();
action.getQueryParameters().put(param.getName(), (QueryParameter) ap); // depends on control dependency: [for], data = [param]
break;
case BODY:
default:
break; //body is handled at the method level.
}
if (ap == null) {
//no param has been created, we skip.
continue;
}
//Set param type
ParamType type = typeConverter(param.getValueType());
if (type != null) {
ap.setType(type); // depends on control dependency: [if], data = [(type]
}
//set required, usually thanks to the notnull constraints annotation.
if(param.isMandatory()){
ap.setRequired(true); // depends on control dependency: [if], data = [none]
} else {
ap.setRequired(false); // depends on control dependency: [if], data = [none]
}
//set minimum if specified
if(param.getMin()!=null){
ap.setMinimum(BigDecimal.valueOf(param.getMin())); // depends on control dependency: [if], data = [(param.getMin()]
//TODO warn if type is not number/integer
}
//set maximum if specified
if(param.getMax()!=null){
ap.setMinimum(BigDecimal.valueOf(param.getMax())); // depends on control dependency: [if], data = [(param.getMax()]
//TODO warn if type is not number/integer
}
//set default value
if (param.getDefaultValue() != null) {
ap.setRequired(false); // depends on control dependency: [if], data = [none]
ap.setDefaultValue(param.getDefaultValue()); // depends on control dependency: [if], data = [(param.getDefaultValue()]
}
}
resource.getActions().put(action.getType(), action);
} } |
public class class_name {
@Override
public List<LocalDate> getIMMDates(final LocalDate start, final LocalDate end, final IMMPeriod period) {
final List<LocalDate> dates = new ArrayList<>();
LocalDate date = start;
while (true) {
date = getNextIMMDate(true, date, period);
if (!date.isAfter(end)) {
dates.add(date);
} else {
break;
}
}
return dates;
} } | public class class_name {
@Override
public List<LocalDate> getIMMDates(final LocalDate start, final LocalDate end, final IMMPeriod period) {
final List<LocalDate> dates = new ArrayList<>();
LocalDate date = start;
while (true) {
date = getNextIMMDate(true, date, period);
// depends on control dependency: [while], data = [none]
if (!date.isAfter(end)) {
dates.add(date);
// depends on control dependency: [if], data = [none]
} else {
break;
}
}
return dates;
} } |
public class class_name {
protected void viewLocationDidChange (int dx, int dy)
{
// inform our view trackers
for (int ii = 0, ll = _trackers.size(); ii < ll; ii++) {
_trackers.get(ii).viewLocationDidChange(dx, dy);
}
// pass the word on to our sprite/anim managers via the meta manager
_metamgr.viewLocationDidChange(dx, dy);
} } | public class class_name {
protected void viewLocationDidChange (int dx, int dy)
{
// inform our view trackers
for (int ii = 0, ll = _trackers.size(); ii < ll; ii++) {
_trackers.get(ii).viewLocationDidChange(dx, dy); // depends on control dependency: [for], data = [ii]
}
// pass the word on to our sprite/anim managers via the meta manager
_metamgr.viewLocationDidChange(dx, dy);
} } |
public class class_name {
public synchronized static void addShutdownHook(Runnable task) {
if (task != null) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
task.run();
}
catch (RuntimeException rex) {
Say.warn("Exception while processing shutdown-hook", rex);
}
}));
}
} } | public class class_name {
public synchronized static void addShutdownHook(Runnable task) {
if (task != null) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
task.run(); // depends on control dependency: [if], data = [none]
}
catch (RuntimeException rex) {
Say.warn("Exception while processing shutdown-hook", rex);
}
}));
}
} } |
public class class_name {
@Override
public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) {
if(!ctx.isDomainMode()) {
return -1;
}
if(buffer.isEmpty()) {
candidates.add("{rollout");
return 0;
}
try {
parsedOp.parseOperation(null, buffer, ctx);
} catch (CommandFormatException e) {
return -1;
}
if(parsedOp.isRequestComplete()) {
return -1;
}
if(parsedOp.endsOnHeaderListStart() || parsedOp.endsOnHeaderSeparator()) {
candidates.add("rollout");
return parsedOp.getLastSeparatorIndex() + 1;
}
if(parsedOp.getLastHeader() == null) {
if(ctx.getParsedCommandLine().getOriginalLine().endsWith(" ") /* '{rollout ' */) {
final String originalLine = ctx.getParsedCommandLine().getOriginalLine();
int bufferIndex = originalLine.lastIndexOf(buffer);
if(bufferIndex == -1) { // that's illegal state
return -1;
}
candidates.add("name=");
candidates.addAll(Util.getServerGroups(ctx.getModelControllerClient()));
return originalLine.length() - bufferIndex;
} else if (ctx.getParsedCommandLine().getOriginalLine().endsWith("rollout")) {
// In order to have the completion to be allowed to continue
candidates.add(" ");
}
return buffer.length();
}
final ParsedOperationRequestHeader lastHeader = parsedOp.getLastHeader();
if(!(lastHeader instanceof ParsedRolloutPlanHeader)) {
throw new IllegalStateException("Expected " + ParsedRolloutPlanHeader.class + " but got " + lastHeader.getName() + " of " + lastHeader);
}
final ParsedRolloutPlanHeader rollout = (ParsedRolloutPlanHeader) lastHeader;
if(rollout.endsOnPlanIdValueSeparator()) {
candidates.addAll(Util.getNodeNames(ctx.getModelControllerClient(), address, Util.ROLLOUT_PLAN));
return rollout.getLastSeparatorIndex() + 1;
}
final String planRef = rollout.getPlanRef();
if(planRef != null) {
final List<String> nodeNames = Util.getNodeNames(ctx.getModelControllerClient(), address, Util.ROLLOUT_PLAN);
for(String name : nodeNames) {
if(name.startsWith(planRef)) {
candidates.add(name);
}
}
return rollout.getLastChunkIndex();
}
if(rollout.hasProperties()) {
final String lastName = rollout.getLastPropertyName();
if (Util.ROLLBACK_ACROSS_GROUPS.equals(lastName)) {
if (rollout.getLastPropertyValue() != null) {
return -1;
}
candidates.add("}");
candidates.add(";");
return rollout.getLastChunkIndex() + lastName.length();
}
if (Util.ROLLBACK_ACROSS_GROUPS.startsWith(lastName)) {
candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
}
return rollout.getLastChunkIndex();
}
final List<String> serverGroups = Util.getServerGroups(ctx.getModelControllerClient());
boolean containsAllGroups = true;
for (String group : serverGroups) {
if (!rollout.containsGroup(group)) {
containsAllGroups = false;
break;
}
}
if(rollout.endsOnGroupSeparator()) {
if (containsAllGroups) {
return -1;
}
for(String group : serverGroups) {
if(!rollout.containsGroup(group)) {
candidates.add(group);
}
}
return buffer.length();
}
final SingleRolloutPlanGroup lastGroup = rollout.getLastGroup();
if(lastGroup == null) {
return -1;
}
if (lastGroup.endsOnPropertyListEnd()) {
if (!containsAllGroups) {
candidates.add("^");
candidates.add(",");
} else if (Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
} else {
candidates.add(" ");
}
return buffer.length();
}
if(lastGroup.endsOnPropertyListStart()) {
candidates.add(Util.MAX_FAILED_SERVERS);
candidates.add(Util.MAX_FAILURE_PERCENTAGE);
candidates.add(Util.ROLLING_TO_SERVERS);
candidates.add(Util.NOT_OPERATOR);
return buffer.length();
}
// Only return the set of boolean properties
if (lastGroup.endsOnNotOperator()) {
candidates.add(Util.ROLLING_TO_SERVERS);
return buffer.length();
}
if (lastGroup.hasProperties()) {
// To propose the right end character
boolean containsAll = lastGroup.hasProperty(Util.MAX_FAILED_SERVERS)
&& lastGroup.hasProperty(Util.MAX_FAILURE_PERCENTAGE)
&& lastGroup.hasProperty(Util.ROLLING_TO_SERVERS);
final String propValue = lastGroup.getLastPropertyValue();
if(propValue != null) {
if(Util.TRUE.startsWith(propValue)) {
candidates.add(Util.TRUE);
} else if(Util.FALSE.startsWith(propValue)) {
candidates.add(Util.FALSE);
} else {
candidates.add(containsAll ? ")" : ",");
return buffer.length();
}
} else if(lastGroup.endsOnPropertyValueSeparator()) {
if(Util.ROLLING_TO_SERVERS.equals(lastGroup.getLastPropertyName())) {
candidates.add(Util.FALSE);
candidates.add(containsAll ? ")" : ",");
}
return buffer.length();
} else if(lastGroup.endsOnPropertySeparator()) {
if(!lastGroup.hasProperty(Util.MAX_FAILED_SERVERS)) {
candidates.add(Util.MAX_FAILED_SERVERS);
}
if(!lastGroup.hasProperty(Util.MAX_FAILURE_PERCENTAGE)) {
candidates.add(Util.MAX_FAILURE_PERCENTAGE);
}
if(!lastGroup.hasProperty(Util.ROLLING_TO_SERVERS)) {
candidates.add(Util.ROLLING_TO_SERVERS);
candidates.add(Util.NOT_OPERATOR);
}
return lastGroup.getLastSeparatorIndex() + 1;
} else {
final String propName = lastGroup.getLastPropertyName();
if(Util.MAX_FAILED_SERVERS.startsWith(propName)) {
candidates.add(Util.MAX_FAILED_SERVERS + '=');
}
if(Util.MAX_FAILURE_PERCENTAGE.startsWith(propName)) {
candidates.add(Util.MAX_FAILURE_PERCENTAGE + '=');
} else if (Util.ROLLING_TO_SERVERS.equals(propName)) {
if (lastGroup.isLastPropertyNegated() && !containsAll) {
candidates.add(Util.ROLLING_TO_SERVERS + ",");
} else {
candidates.add("=" + Util.FALSE);
if (!containsAll) {
candidates.add(",");
} else {
candidates.add(")");
}
}
} else if (Util.ROLLING_TO_SERVERS.startsWith(propName)) {
candidates.add(Util.ROLLING_TO_SERVERS);
}
}
if (candidates.isEmpty() && containsAll) {
candidates.add(")");
}
return lastGroup.getLastChunkIndex();
}
if (Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
return buffer.length();
}
int result = lastGroup.getLastChunkIndex();
final String groupName = lastGroup.getGroupName();
boolean isLastGroup = false;
for (String group : serverGroups) {
if (group.equals(groupName)) {
isLastGroup = true;
}
if (!isLastGroup && group.startsWith(groupName)) {
candidates.add(group);
}
}
if(Util.NAME.startsWith(groupName)) {
candidates.add("name=");
} else {
if (candidates.isEmpty()) {
if (isLastGroup) {
candidates.add("(");
if (containsAllGroups) {
candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
} else {
candidates.add(",");
candidates.add("^");
}
}
}
}
return result;
} } | public class class_name {
@Override
public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) {
if(!ctx.isDomainMode()) {
return -1; // depends on control dependency: [if], data = [none]
}
if(buffer.isEmpty()) {
candidates.add("{rollout"); // depends on control dependency: [if], data = [none]
return 0; // depends on control dependency: [if], data = [none]
}
try {
parsedOp.parseOperation(null, buffer, ctx); // depends on control dependency: [try], data = [none]
} catch (CommandFormatException e) {
return -1;
} // depends on control dependency: [catch], data = [none]
if(parsedOp.isRequestComplete()) {
return -1; // depends on control dependency: [if], data = [none]
}
if(parsedOp.endsOnHeaderListStart() || parsedOp.endsOnHeaderSeparator()) {
candidates.add("rollout"); // depends on control dependency: [if], data = [none]
return parsedOp.getLastSeparatorIndex() + 1; // depends on control dependency: [if], data = [none]
}
if(parsedOp.getLastHeader() == null) {
if(ctx.getParsedCommandLine().getOriginalLine().endsWith(" ") /* '{rollout ' */) {
final String originalLine = ctx.getParsedCommandLine().getOriginalLine();
int bufferIndex = originalLine.lastIndexOf(buffer);
if(bufferIndex == -1) { // that's illegal state
return -1; // depends on control dependency: [if], data = [none]
}
candidates.add("name="); // depends on control dependency: [if], data = [none]
candidates.addAll(Util.getServerGroups(ctx.getModelControllerClient())); // depends on control dependency: [if], data = [none]
return originalLine.length() - bufferIndex; // depends on control dependency: [if], data = [none]
} else if (ctx.getParsedCommandLine().getOriginalLine().endsWith("rollout")) {
// In order to have the completion to be allowed to continue
candidates.add(" "); // depends on control dependency: [if], data = [none]
}
return buffer.length(); // depends on control dependency: [if], data = [none]
}
final ParsedOperationRequestHeader lastHeader = parsedOp.getLastHeader();
if(!(lastHeader instanceof ParsedRolloutPlanHeader)) {
throw new IllegalStateException("Expected " + ParsedRolloutPlanHeader.class + " but got " + lastHeader.getName() + " of " + lastHeader);
}
final ParsedRolloutPlanHeader rollout = (ParsedRolloutPlanHeader) lastHeader;
if(rollout.endsOnPlanIdValueSeparator()) {
candidates.addAll(Util.getNodeNames(ctx.getModelControllerClient(), address, Util.ROLLOUT_PLAN)); // depends on control dependency: [if], data = [none]
return rollout.getLastSeparatorIndex() + 1; // depends on control dependency: [if], data = [none]
}
final String planRef = rollout.getPlanRef();
if(planRef != null) {
final List<String> nodeNames = Util.getNodeNames(ctx.getModelControllerClient(), address, Util.ROLLOUT_PLAN);
for(String name : nodeNames) {
if(name.startsWith(planRef)) {
candidates.add(name); // depends on control dependency: [if], data = [none]
}
}
return rollout.getLastChunkIndex(); // depends on control dependency: [if], data = [none]
}
if(rollout.hasProperties()) {
final String lastName = rollout.getLastPropertyName();
if (Util.ROLLBACK_ACROSS_GROUPS.equals(lastName)) {
if (rollout.getLastPropertyValue() != null) {
return -1; // depends on control dependency: [if], data = [none]
}
candidates.add("}"); // depends on control dependency: [if], data = [none]
candidates.add(";"); // depends on control dependency: [if], data = [none]
return rollout.getLastChunkIndex() + lastName.length(); // depends on control dependency: [if], data = [none]
}
if (Util.ROLLBACK_ACROSS_GROUPS.startsWith(lastName)) {
candidates.add(Util.ROLLBACK_ACROSS_GROUPS); // depends on control dependency: [if], data = [none]
}
return rollout.getLastChunkIndex(); // depends on control dependency: [if], data = [none]
}
final List<String> serverGroups = Util.getServerGroups(ctx.getModelControllerClient());
boolean containsAllGroups = true;
for (String group : serverGroups) {
if (!rollout.containsGroup(group)) {
containsAllGroups = false; // depends on control dependency: [if], data = [none]
break;
}
}
if(rollout.endsOnGroupSeparator()) {
if (containsAllGroups) {
return -1; // depends on control dependency: [if], data = [none]
}
for(String group : serverGroups) {
if(!rollout.containsGroup(group)) {
candidates.add(group); // depends on control dependency: [if], data = [none]
}
}
return buffer.length(); // depends on control dependency: [if], data = [none]
}
final SingleRolloutPlanGroup lastGroup = rollout.getLastGroup();
if(lastGroup == null) {
return -1; // depends on control dependency: [if], data = [none]
}
if (lastGroup.endsOnPropertyListEnd()) {
if (!containsAllGroups) {
candidates.add("^"); // depends on control dependency: [if], data = [none]
candidates.add(","); // depends on control dependency: [if], data = [none]
} else if (Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
candidates.add(Util.ROLLBACK_ACROSS_GROUPS); // depends on control dependency: [if], data = [none]
} else {
candidates.add(" "); // depends on control dependency: [if], data = [none]
}
return buffer.length(); // depends on control dependency: [if], data = [none]
}
if(lastGroup.endsOnPropertyListStart()) {
candidates.add(Util.MAX_FAILED_SERVERS); // depends on control dependency: [if], data = [none]
candidates.add(Util.MAX_FAILURE_PERCENTAGE); // depends on control dependency: [if], data = [none]
candidates.add(Util.ROLLING_TO_SERVERS); // depends on control dependency: [if], data = [none]
candidates.add(Util.NOT_OPERATOR); // depends on control dependency: [if], data = [none]
return buffer.length(); // depends on control dependency: [if], data = [none]
}
// Only return the set of boolean properties
if (lastGroup.endsOnNotOperator()) {
candidates.add(Util.ROLLING_TO_SERVERS); // depends on control dependency: [if], data = [none]
return buffer.length(); // depends on control dependency: [if], data = [none]
}
if (lastGroup.hasProperties()) {
// To propose the right end character
boolean containsAll = lastGroup.hasProperty(Util.MAX_FAILED_SERVERS)
&& lastGroup.hasProperty(Util.MAX_FAILURE_PERCENTAGE)
&& lastGroup.hasProperty(Util.ROLLING_TO_SERVERS);
final String propValue = lastGroup.getLastPropertyValue();
if(propValue != null) {
if(Util.TRUE.startsWith(propValue)) {
candidates.add(Util.TRUE); // depends on control dependency: [if], data = [none]
} else if(Util.FALSE.startsWith(propValue)) {
candidates.add(Util.FALSE); // depends on control dependency: [if], data = [none]
} else {
candidates.add(containsAll ? ")" : ","); // depends on control dependency: [if], data = [none]
return buffer.length(); // depends on control dependency: [if], data = [none]
}
} else if(lastGroup.endsOnPropertyValueSeparator()) {
if(Util.ROLLING_TO_SERVERS.equals(lastGroup.getLastPropertyName())) {
candidates.add(Util.FALSE); // depends on control dependency: [if], data = [none]
candidates.add(containsAll ? ")" : ","); // depends on control dependency: [if], data = [none]
}
return buffer.length(); // depends on control dependency: [if], data = [none]
} else if(lastGroup.endsOnPropertySeparator()) {
if(!lastGroup.hasProperty(Util.MAX_FAILED_SERVERS)) {
candidates.add(Util.MAX_FAILED_SERVERS); // depends on control dependency: [if], data = [none]
}
if(!lastGroup.hasProperty(Util.MAX_FAILURE_PERCENTAGE)) {
candidates.add(Util.MAX_FAILURE_PERCENTAGE); // depends on control dependency: [if], data = [none]
}
if(!lastGroup.hasProperty(Util.ROLLING_TO_SERVERS)) {
candidates.add(Util.ROLLING_TO_SERVERS); // depends on control dependency: [if], data = [none]
candidates.add(Util.NOT_OPERATOR); // depends on control dependency: [if], data = [none]
}
return lastGroup.getLastSeparatorIndex() + 1; // depends on control dependency: [if], data = [none]
} else {
final String propName = lastGroup.getLastPropertyName();
if(Util.MAX_FAILED_SERVERS.startsWith(propName)) {
candidates.add(Util.MAX_FAILED_SERVERS + '='); // depends on control dependency: [if], data = [none]
}
if(Util.MAX_FAILURE_PERCENTAGE.startsWith(propName)) {
candidates.add(Util.MAX_FAILURE_PERCENTAGE + '='); // depends on control dependency: [if], data = [none]
} else if (Util.ROLLING_TO_SERVERS.equals(propName)) {
if (lastGroup.isLastPropertyNegated() && !containsAll) {
candidates.add(Util.ROLLING_TO_SERVERS + ","); // depends on control dependency: [if], data = [none]
} else {
candidates.add("=" + Util.FALSE); // depends on control dependency: [if], data = [none]
if (!containsAll) {
candidates.add(","); // depends on control dependency: [if], data = [none]
} else {
candidates.add(")"); // depends on control dependency: [if], data = [none]
}
}
} else if (Util.ROLLING_TO_SERVERS.startsWith(propName)) {
candidates.add(Util.ROLLING_TO_SERVERS); // depends on control dependency: [if], data = [none]
}
}
if (candidates.isEmpty() && containsAll) {
candidates.add(")"); // depends on control dependency: [if], data = [none]
}
return lastGroup.getLastChunkIndex(); // depends on control dependency: [if], data = [none]
}
if (Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
candidates.add(Util.ROLLBACK_ACROSS_GROUPS); // depends on control dependency: [if], data = [none]
return buffer.length(); // depends on control dependency: [if], data = [none]
}
int result = lastGroup.getLastChunkIndex();
final String groupName = lastGroup.getGroupName();
boolean isLastGroup = false;
for (String group : serverGroups) {
if (group.equals(groupName)) {
isLastGroup = true; // depends on control dependency: [if], data = [none]
}
if (!isLastGroup && group.startsWith(groupName)) {
candidates.add(group); // depends on control dependency: [if], data = [none]
}
}
if(Util.NAME.startsWith(groupName)) {
candidates.add("name="); // depends on control dependency: [if], data = [none]
} else {
if (candidates.isEmpty()) {
if (isLastGroup) {
candidates.add("("); // depends on control dependency: [if], data = [none]
if (containsAllGroups) {
candidates.add(Util.ROLLBACK_ACROSS_GROUPS); // depends on control dependency: [if], data = [none]
} else {
candidates.add(","); // depends on control dependency: [if], data = [none]
candidates.add("^"); // depends on control dependency: [if], data = [none]
}
}
}
}
return result;
} } |
public class class_name {
private int findKey(K key) {
int i = 0;
for (K otherKey : this.keys) {
if (this.comparator.compare(key, otherKey) == 0) {
return i;
}
i++;
}
return -1;
} } | public class class_name {
private int findKey(K key) {
int i = 0;
for (K otherKey : this.keys) {
if (this.comparator.compare(key, otherKey) == 0) {
return i; // depends on control dependency: [if], data = [none]
}
i++; // depends on control dependency: [for], data = [none]
}
return -1;
} } |
public class class_name {
public void run() {
while (continueBackup) {
if (changedListVersion < changedList.getVersion()) {
cleanupBackupDir(SAVED_BACKUPS);
String filename = String.valueOf(System.currentTimeMillis());
File persistFile = new File(backupDir, filename);
backingUp = true;
changedListVersion = changedList.persist(persistFile);
backingUp = false;
}
sleepAndCheck(backupFrequency);
}
} } | public class class_name {
public void run() {
while (continueBackup) {
if (changedListVersion < changedList.getVersion()) {
cleanupBackupDir(SAVED_BACKUPS); // depends on control dependency: [if], data = [none]
String filename = String.valueOf(System.currentTimeMillis());
File persistFile = new File(backupDir, filename);
backingUp = true; // depends on control dependency: [if], data = [none]
changedListVersion = changedList.persist(persistFile); // depends on control dependency: [if], data = [none]
backingUp = false; // depends on control dependency: [if], data = [none]
}
sleepAndCheck(backupFrequency); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public static <T extends Comparable<? super T>> T max(T[] numberArray) {
if (isEmpty(numberArray)) {
throw new IllegalArgumentException("Number array must not empty !");
}
T max = numberArray[0];
for (int i = 0; i < numberArray.length; i++) {
if (ObjectUtil.compare(max, numberArray[i]) < 0) {
max = numberArray[i];
}
}
return max;
} } | public class class_name {
public static <T extends Comparable<? super T>> T max(T[] numberArray) {
if (isEmpty(numberArray)) {
throw new IllegalArgumentException("Number array must not empty !");
}
T max = numberArray[0];
for (int i = 0; i < numberArray.length; i++) {
if (ObjectUtil.compare(max, numberArray[i]) < 0) {
max = numberArray[i];
// depends on control dependency: [if], data = [none]
}
}
return max;
} } |
public class class_name {
public static ListBoxModel getParsersAsListModel() {
ListBoxModel items = new ListBoxModel();
for (ParserDescription parser : getAvailableParsers()) {
items.add(parser.getName(), parser.getGroup());
}
return items;
} } | public class class_name {
public static ListBoxModel getParsersAsListModel() {
ListBoxModel items = new ListBoxModel();
for (ParserDescription parser : getAvailableParsers()) {
items.add(parser.getName(), parser.getGroup()); // depends on control dependency: [for], data = [parser]
}
return items;
} } |
public class class_name {
public void unsetActiveSession() {
if (log.isInfoEnabled()) {
log.info("Setting no active session for site '" + site + "'.");
}
if (this.activeSession != null) {
this.activeSession.setActive(false);
// If the active session was one with no tokens, delete it, at it will probably not
// match anything from this point forward
if (this.activeSession.getTokenValuesCount() == 0) {
this.removeHttpSession(this.activeSession);
} else {
// Notify the model that the session is updated
model.fireHttpSessionUpdated(this.activeSession);
}
this.activeSession = null;
}
} } | public class class_name {
public void unsetActiveSession() {
if (log.isInfoEnabled()) {
log.info("Setting no active session for site '" + site + "'."); // depends on control dependency: [if], data = [none]
}
if (this.activeSession != null) {
this.activeSession.setActive(false); // depends on control dependency: [if], data = [none]
// If the active session was one with no tokens, delete it, at it will probably not
// match anything from this point forward
if (this.activeSession.getTokenValuesCount() == 0) {
this.removeHttpSession(this.activeSession); // depends on control dependency: [if], data = [none]
} else {
// Notify the model that the session is updated
model.fireHttpSessionUpdated(this.activeSession); // depends on control dependency: [if], data = [none]
}
this.activeSession = null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public Content getNavLinkPrevious() {
Content li;
if (prev == null) {
li = HtmlTree.LI(contents.prevPackageLabel);
} else {
DocPath path = DocPath.relativePath(packageElement, prev);
li = HtmlTree.LI(getHyperLink(path.resolve(DocPaths.PACKAGE_SUMMARY),
contents.prevPackageLabel, "", ""));
}
return li;
} } | public class class_name {
@Override
public Content getNavLinkPrevious() {
Content li;
if (prev == null) {
li = HtmlTree.LI(contents.prevPackageLabel); // depends on control dependency: [if], data = [none]
} else {
DocPath path = DocPath.relativePath(packageElement, prev);
li = HtmlTree.LI(getHyperLink(path.resolve(DocPaths.PACKAGE_SUMMARY),
contents.prevPackageLabel, "", "")); // depends on control dependency: [if], data = [none]
}
return li;
} } |
public class class_name {
public void marshall(BatchScheduleActionCreateResult batchScheduleActionCreateResult, ProtocolMarshaller protocolMarshaller) {
if (batchScheduleActionCreateResult == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchScheduleActionCreateResult.getScheduleActions(), SCHEDULEACTIONS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BatchScheduleActionCreateResult batchScheduleActionCreateResult, ProtocolMarshaller protocolMarshaller) {
if (batchScheduleActionCreateResult == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchScheduleActionCreateResult.getScheduleActions(), SCHEDULEACTIONS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static RingbufferStoreWrapper create(ObjectNamespace namespace,
RingbufferStoreConfig storeConfig,
InMemoryFormat inMemoryFormat, SerializationService serializationService,
ClassLoader classLoader) {
checkNotNull(namespace, "namespace should not be null");
checkNotNull(serializationService, "serializationService should not be null");
final RingbufferStoreWrapper storeWrapper = new RingbufferStoreWrapper(namespace);
storeWrapper.serializationService = serializationService;
if (storeConfig == null || !storeConfig.isEnabled()) {
return storeWrapper;
}
// create ring buffer store.
final RingbufferStore ringbufferStore = createRingbufferStore(namespace, storeConfig, classLoader);
if (ringbufferStore != null) {
storeWrapper.enabled = storeConfig.isEnabled();
storeWrapper.inMemoryFormat = inMemoryFormat;
storeWrapper.store = ringbufferStore;
}
return storeWrapper;
} } | public class class_name {
public static RingbufferStoreWrapper create(ObjectNamespace namespace,
RingbufferStoreConfig storeConfig,
InMemoryFormat inMemoryFormat, SerializationService serializationService,
ClassLoader classLoader) {
checkNotNull(namespace, "namespace should not be null");
checkNotNull(serializationService, "serializationService should not be null");
final RingbufferStoreWrapper storeWrapper = new RingbufferStoreWrapper(namespace);
storeWrapper.serializationService = serializationService;
if (storeConfig == null || !storeConfig.isEnabled()) {
return storeWrapper; // depends on control dependency: [if], data = [none]
}
// create ring buffer store.
final RingbufferStore ringbufferStore = createRingbufferStore(namespace, storeConfig, classLoader);
if (ringbufferStore != null) {
storeWrapper.enabled = storeConfig.isEnabled(); // depends on control dependency: [if], data = [none]
storeWrapper.inMemoryFormat = inMemoryFormat; // depends on control dependency: [if], data = [none]
storeWrapper.store = ringbufferStore; // depends on control dependency: [if], data = [none]
}
return storeWrapper;
} } |
public class class_name {
public void addClassCompileTask(final String className,
final BaseDescr descr,
final String text,
final MemoryResourceReader src,
final ErrorHandler handler) {
final String fileName = className.replace('.',
'/') + ".java";
if (src != null) {
src.add(fileName,
text.getBytes(IoUtils.UTF8_CHARSET));
} else {
this.src.add(fileName,
text.getBytes(IoUtils.UTF8_CHARSET));
}
this.errorHandlers.put(fileName,
handler);
addClassName(fileName);
} } | public class class_name {
public void addClassCompileTask(final String className,
final BaseDescr descr,
final String text,
final MemoryResourceReader src,
final ErrorHandler handler) {
final String fileName = className.replace('.',
'/') + ".java";
if (src != null) {
src.add(fileName,
text.getBytes(IoUtils.UTF8_CHARSET)); // depends on control dependency: [if], data = [none]
} else {
this.src.add(fileName,
text.getBytes(IoUtils.UTF8_CHARSET)); // depends on control dependency: [if], data = [none]
}
this.errorHandlers.put(fileName,
handler);
addClassName(fileName);
} } |
public class class_name {
private void createPreStreamingTags(int timestamp, boolean clear) {
log.debug("Creating pre-streaming tags");
if (clear) {
firstTags.clear();
}
ITag tag = null;
IoBuffer body = null;
if (hasVideo) {
//video tag #1
body = IoBuffer.allocate(41);
body.setAutoExpand(true);
body.put(PREFIX_VIDEO_CONFIG_FRAME); //prefix
if (videoDecoderBytes != null) {
//because of other processing we do this check
if (log.isDebugEnabled()) {
log.debug("Video decoder bytes: {}", HexDump.byteArrayToHexString(videoDecoderBytes));
}
body.put(videoDecoderBytes);
}
tag = new Tag(IoConstants.TYPE_VIDEO, timestamp, body.position(), null, 0);
body.flip();
tag.setBody(body);
//add tag
firstTags.add(tag);
}
// TODO: Handle other mp4 container audio codecs like mp3
// mp3 header magic number ((int & 0xffe00000) == 0xffe00000)
if (hasAudio) {
//audio tag #1
if (audioDecoderBytes != null) {
//because of other processing we do this check
if (log.isDebugEnabled()) {
log.debug("Audio decoder bytes: {}", HexDump.byteArrayToHexString(audioDecoderBytes));
}
body = IoBuffer.allocate(audioDecoderBytes.length + 3);
body.setAutoExpand(true);
body.put(PREFIX_AUDIO_CONFIG_FRAME); //prefix
body.put(audioDecoderBytes);
body.put((byte) 0x06); //suffix
tag = new Tag(IoConstants.TYPE_AUDIO, timestamp, body.position(), null, 0);
body.flip();
tag.setBody(body);
//add tag
firstTags.add(tag);
} else {
log.info("Audio decoder bytes were not available");
}
}
} } | public class class_name {
private void createPreStreamingTags(int timestamp, boolean clear) {
log.debug("Creating pre-streaming tags");
if (clear) {
firstTags.clear(); // depends on control dependency: [if], data = [none]
}
ITag tag = null;
IoBuffer body = null;
if (hasVideo) {
//video tag #1
body = IoBuffer.allocate(41); // depends on control dependency: [if], data = [none]
body.setAutoExpand(true); // depends on control dependency: [if], data = [none]
body.put(PREFIX_VIDEO_CONFIG_FRAME); //prefix // depends on control dependency: [if], data = [none]
if (videoDecoderBytes != null) {
//because of other processing we do this check
if (log.isDebugEnabled()) {
log.debug("Video decoder bytes: {}", HexDump.byteArrayToHexString(videoDecoderBytes)); // depends on control dependency: [if], data = [none]
}
body.put(videoDecoderBytes); // depends on control dependency: [if], data = [(videoDecoderBytes]
}
tag = new Tag(IoConstants.TYPE_VIDEO, timestamp, body.position(), null, 0); // depends on control dependency: [if], data = [none]
body.flip(); // depends on control dependency: [if], data = [none]
tag.setBody(body); // depends on control dependency: [if], data = [none]
//add tag
firstTags.add(tag); // depends on control dependency: [if], data = [none]
}
// TODO: Handle other mp4 container audio codecs like mp3
// mp3 header magic number ((int & 0xffe00000) == 0xffe00000)
if (hasAudio) {
//audio tag #1
if (audioDecoderBytes != null) {
//because of other processing we do this check
if (log.isDebugEnabled()) {
log.debug("Audio decoder bytes: {}", HexDump.byteArrayToHexString(audioDecoderBytes)); // depends on control dependency: [if], data = [none]
}
body = IoBuffer.allocate(audioDecoderBytes.length + 3); // depends on control dependency: [if], data = [(audioDecoderBytes]
body.setAutoExpand(true); // depends on control dependency: [if], data = [none]
body.put(PREFIX_AUDIO_CONFIG_FRAME); //prefix // depends on control dependency: [if], data = [none]
body.put(audioDecoderBytes); // depends on control dependency: [if], data = [(audioDecoderBytes]
body.put((byte) 0x06); //suffix // depends on control dependency: [if], data = [none]
tag = new Tag(IoConstants.TYPE_AUDIO, timestamp, body.position(), null, 0); // depends on control dependency: [if], data = [none]
body.flip(); // depends on control dependency: [if], data = [none]
tag.setBody(body); // depends on control dependency: [if], data = [none]
//add tag
firstTags.add(tag); // depends on control dependency: [if], data = [none]
} else {
log.info("Audio decoder bytes were not available"); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void allowASCII(boolean allow) {
this.allowASCII = allow;
ISO9660NamingConventions.FORCE_ISO9660_CHARSET = !allow;
if (allow) {
System.out.println("Warning: Allowing the full ASCII character set breaks ISO 9660 conformance.");
}
} } | public class class_name {
public void allowASCII(boolean allow) {
this.allowASCII = allow;
ISO9660NamingConventions.FORCE_ISO9660_CHARSET = !allow;
if (allow) {
System.out.println("Warning: Allowing the full ASCII character set breaks ISO 9660 conformance."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public CreateWorkspacesResult withFailedRequests(FailedCreateWorkspaceRequest... failedRequests) {
if (this.failedRequests == null) {
setFailedRequests(new com.amazonaws.internal.SdkInternalList<FailedCreateWorkspaceRequest>(failedRequests.length));
}
for (FailedCreateWorkspaceRequest ele : failedRequests) {
this.failedRequests.add(ele);
}
return this;
} } | public class class_name {
public CreateWorkspacesResult withFailedRequests(FailedCreateWorkspaceRequest... failedRequests) {
if (this.failedRequests == null) {
setFailedRequests(new com.amazonaws.internal.SdkInternalList<FailedCreateWorkspaceRequest>(failedRequests.length)); // depends on control dependency: [if], data = [none]
}
for (FailedCreateWorkspaceRequest ele : failedRequests) {
this.failedRequests.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private void showDialog(final AjaxRequestTarget _target,
final String _key,
final boolean _isSniplett,
final boolean _goOnButton)
{
final ModalWindowContainer modal = ((AbstractContentPage) getPage()).getModal();
modal.setInitialWidth(350);
modal.setInitialHeight(200);
modal.setPageCreator(new ModalWindow.PageCreator() {
private static final long serialVersionUID = 1L;
@Override
public Page createPage()
{
return new DialogPage(((AbstractContentPage) getPage()).getPageReference(),
_key, _isSniplett, _goOnButton);
}
});
if (_goOnButton) {
modal.setWindowClosedCallback(new WindowClosedCallback()
{
private static final long serialVersionUID = 1L;
@Override
public void onClose(final AjaxRequestTarget _target)
{
if (AjaxSubmitCloseButton.this.validated) {
_target.appendJavaScript(getExecuteScript());
}
}
});
}
modal.show(_target);
} } | public class class_name {
private void showDialog(final AjaxRequestTarget _target,
final String _key,
final boolean _isSniplett,
final boolean _goOnButton)
{
final ModalWindowContainer modal = ((AbstractContentPage) getPage()).getModal();
modal.setInitialWidth(350);
modal.setInitialHeight(200);
modal.setPageCreator(new ModalWindow.PageCreator() {
private static final long serialVersionUID = 1L;
@Override
public Page createPage()
{
return new DialogPage(((AbstractContentPage) getPage()).getPageReference(),
_key, _isSniplett, _goOnButton);
}
});
if (_goOnButton) {
modal.setWindowClosedCallback(new WindowClosedCallback()
{
private static final long serialVersionUID = 1L;
@Override
public void onClose(final AjaxRequestTarget _target)
{
if (AjaxSubmitCloseButton.this.validated) {
_target.appendJavaScript(getExecuteScript()); // depends on control dependency: [if], data = [none]
}
}
}); // depends on control dependency: [if], data = [none]
}
modal.show(_target);
} } |
public class class_name {
@Override
public void fluff(String format, Object... args) {
if (showFluff()) {
hard(format, args);
}
} } | public class class_name {
@Override
public void fluff(String format, Object... args) {
if (showFluff()) {
hard(format, args); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(RoomData roomData, ProtocolMarshaller protocolMarshaller) {
if (roomData == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(roomData.getRoomArn(), ROOMARN_BINDING);
protocolMarshaller.marshall(roomData.getRoomName(), ROOMNAME_BINDING);
protocolMarshaller.marshall(roomData.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(roomData.getProviderCalendarId(), PROVIDERCALENDARID_BINDING);
protocolMarshaller.marshall(roomData.getProfileArn(), PROFILEARN_BINDING);
protocolMarshaller.marshall(roomData.getProfileName(), PROFILENAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(RoomData roomData, ProtocolMarshaller protocolMarshaller) {
if (roomData == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(roomData.getRoomArn(), ROOMARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(roomData.getRoomName(), ROOMNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(roomData.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(roomData.getProviderCalendarId(), PROVIDERCALENDARID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(roomData.getProfileArn(), PROFILEARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(roomData.getProfileName(), PROFILENAME_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 void updateListenersIfNeeded(int player, TrackPositionUpdate update, Beat beat) {
// Iterate over a copy to avoid issues with concurrent modification
for (Map.Entry<TrackPositionListener, TrackPositionUpdate> entry :
new HashMap<TrackPositionListener, TrackPositionUpdate>(trackPositionListeners).entrySet()) {
if (player == listenerPlayerNumbers.get(entry.getKey())) { // This listener is interested in this player
if (update == null) { // We are reporting a loss of information
if (entry.getValue() != NO_INFORMATION) {
if (trackPositionListeners.replace(entry.getKey(), entry.getValue(), NO_INFORMATION)) {
try {
entry.getKey().movementChanged(null);
} catch (Throwable t) {
logger.warn("Problem delivering null movementChanged update", t);
}
}
}
} else { // We have some information, see if it is a significant change from what was last reported
final TrackPositionUpdate lastUpdate = entry.getValue();
if (lastUpdate == NO_INFORMATION ||
lastUpdate.playing != update.playing ||
Math.abs(lastUpdate.pitch - update.pitch) > 0.000001 ||
interpolationsDisagree(lastUpdate, update)) {
if (trackPositionListeners.replace(entry.getKey(), entry.getValue(), update)) {
try {
entry.getKey().movementChanged(update);
} catch (Throwable t) {
logger.warn("Problem delivering movementChanged update", t);
}
}
}
// And regardless of whether this was a significant change, if this was a new beat and the listener
// implements the interface that requests all beats, send that information.
if (update.definitive && entry.getKey() instanceof TrackPositionBeatListener) {
try {
((TrackPositionBeatListener) entry.getKey()).newBeat(beat, update);
} catch (Throwable t) {
logger.warn("Problem delivering newBeat update", t);
}
}
}
}
}
} } | public class class_name {
private void updateListenersIfNeeded(int player, TrackPositionUpdate update, Beat beat) {
// Iterate over a copy to avoid issues with concurrent modification
for (Map.Entry<TrackPositionListener, TrackPositionUpdate> entry :
new HashMap<TrackPositionListener, TrackPositionUpdate>(trackPositionListeners).entrySet()) {
if (player == listenerPlayerNumbers.get(entry.getKey())) { // This listener is interested in this player
if (update == null) { // We are reporting a loss of information
if (entry.getValue() != NO_INFORMATION) {
if (trackPositionListeners.replace(entry.getKey(), entry.getValue(), NO_INFORMATION)) {
try {
entry.getKey().movementChanged(null); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
logger.warn("Problem delivering null movementChanged update", t);
} // depends on control dependency: [catch], data = [none]
}
}
} else { // We have some information, see if it is a significant change from what was last reported
final TrackPositionUpdate lastUpdate = entry.getValue();
if (lastUpdate == NO_INFORMATION ||
lastUpdate.playing != update.playing ||
Math.abs(lastUpdate.pitch - update.pitch) > 0.000001 ||
interpolationsDisagree(lastUpdate, update)) {
if (trackPositionListeners.replace(entry.getKey(), entry.getValue(), update)) {
try {
entry.getKey().movementChanged(update); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
logger.warn("Problem delivering movementChanged update", t);
} // depends on control dependency: [catch], data = [none]
}
}
// And regardless of whether this was a significant change, if this was a new beat and the listener
// implements the interface that requests all beats, send that information.
if (update.definitive && entry.getKey() instanceof TrackPositionBeatListener) {
try {
((TrackPositionBeatListener) entry.getKey()).newBeat(beat, update); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
logger.warn("Problem delivering newBeat update", t);
} // depends on control dependency: [catch], data = [none]
}
}
}
}
} } |
public class class_name {
public static final void intToBytes( int i, byte[] data, int[] offset ) {
/**
* TODO: We use network-order within OceanStore, but temporarily
* supporting intel-order to work with some JNI code until JNI code is
* set to interoperate with network-order.
*/
if (data != null) {
for( int j = (offset[0] + SIZE_INT) - 1; j >= offset[0]; --j ) {
data[j] = (byte) i;
i >>= 8;
}
}
offset[0] += SIZE_INT;
} } | public class class_name {
public static final void intToBytes( int i, byte[] data, int[] offset ) {
/**
* TODO: We use network-order within OceanStore, but temporarily
* supporting intel-order to work with some JNI code until JNI code is
* set to interoperate with network-order.
*/
if (data != null) {
for( int j = (offset[0] + SIZE_INT) - 1; j >= offset[0]; --j ) {
data[j] = (byte) i; // depends on control dependency: [for], data = [j]
i >>= 8; // depends on control dependency: [for], data = [none]
}
}
offset[0] += SIZE_INT;
} } |
public class class_name {
public boolean contains(final T element) {
if (element == null) {
return false;
}
return lowerEndpoint.includes(element) && upperEndpoint.includes(element);
} } | public class class_name {
public boolean contains(final T element) {
if (element == null) {
return false; // depends on control dependency: [if], data = [none]
}
return lowerEndpoint.includes(element) && upperEndpoint.includes(element);
} } |
public class class_name {
@Override
public void onConnect(int rst, HuaweiApiClient client) {
HMSAgentLog.d("onConnect:" + rst);
if (client == null || !ApiClientMgr.INST.isConnect(client)) {
HMSAgentLog.e("client not connted");
onPMSPayEnd(rst, null);
return;
}
// 调用HMS-SDK pay 接口
PendingResult<PayResult> payResult = HuaweiPay.HuaweiPayApi.productPay(client, payReq);
payResult.setResultCallback(new ResultCallback<PayResult>() {
@Override
public void onResult(PayResult result) {
if (result == null) {
HMSAgentLog.e("result is null");
onPMSPayEnd(HMSAgent.AgentResultCode.RESULT_IS_NULL, null);
return;
}
Status status = result.getStatus();
if (status == null) {
HMSAgentLog.e("status is null");
onPMSPayEnd(HMSAgent.AgentResultCode.STATUS_IS_NULL, null);
return;
}
int rstCode = status.getStatusCode();
HMSAgentLog.d("status=" + status);
// 需要重试的错误码,并且可以重试
if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID
|| rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) {
retryTimes--;
connect();
} else if (rstCode == PayStatusCodes.PAY_STATE_SUCCESS) {
// 支付校验完成,取当前activity进行后续支付操作
Activity curActivity = ActivityMgr.INST.getLastActivity();
if (curActivity == null) {
HMSAgentLog.e("activity is null");
onPMSPayEnd(HMSAgent.AgentResultCode.NO_ACTIVITY_FOR_USE, null);
return;
}
if (statusForPay != null) {
HMSAgentLog.e("has already a pay to dispose");
onPMSPayEnd(HMSAgent.AgentResultCode.REQUEST_REPEATED, null);
return;
}
//启动支付流程
try {
statusForPay = status;
Intent intent = new Intent(curActivity, HMSPMSPayAgentActivity.class);
intent.putExtra(BaseAgentActivity.EXTRA_IS_FULLSCREEN, UIUtils.isActivityFullscreen(curActivity));
curActivity.startActivity(intent);
} catch (Exception e) {
HMSAgentLog.e("start HMSPayAgentActivity error:" + e.getMessage());
onPMSPayEnd(HMSAgent.AgentResultCode.START_ACTIVITY_ERROR, null);
}
}else {
onPMSPayEnd(rstCode, null);
}
}
});
} } | public class class_name {
@Override
public void onConnect(int rst, HuaweiApiClient client) {
HMSAgentLog.d("onConnect:" + rst);
if (client == null || !ApiClientMgr.INST.isConnect(client)) {
HMSAgentLog.e("client not connted");
// depends on control dependency: [if], data = [none]
onPMSPayEnd(rst, null);
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
// 调用HMS-SDK pay 接口
PendingResult<PayResult> payResult = HuaweiPay.HuaweiPayApi.productPay(client, payReq);
payResult.setResultCallback(new ResultCallback<PayResult>() {
@Override
public void onResult(PayResult result) {
if (result == null) {
HMSAgentLog.e("result is null");
// depends on control dependency: [if], data = [none]
onPMSPayEnd(HMSAgent.AgentResultCode.RESULT_IS_NULL, null);
// depends on control dependency: [if], data = [null)]
return;
// depends on control dependency: [if], data = [none]
}
Status status = result.getStatus();
if (status == null) {
HMSAgentLog.e("status is null");
// depends on control dependency: [if], data = [none]
onPMSPayEnd(HMSAgent.AgentResultCode.STATUS_IS_NULL, null);
// depends on control dependency: [if], data = [null)]
return;
// depends on control dependency: [if], data = [none]
}
int rstCode = status.getStatusCode();
HMSAgentLog.d("status=" + status);
// 需要重试的错误码,并且可以重试
if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID
|| rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) {
retryTimes--;
// depends on control dependency: [if], data = [none]
connect();
// depends on control dependency: [if], data = [none]
} else if (rstCode == PayStatusCodes.PAY_STATE_SUCCESS) {
// 支付校验完成,取当前activity进行后续支付操作
Activity curActivity = ActivityMgr.INST.getLastActivity();
if (curActivity == null) {
HMSAgentLog.e("activity is null");
// depends on control dependency: [if], data = [none]
onPMSPayEnd(HMSAgent.AgentResultCode.NO_ACTIVITY_FOR_USE, null);
// depends on control dependency: [if], data = [null)]
return;
// depends on control dependency: [if], data = [none]
}
if (statusForPay != null) {
HMSAgentLog.e("has already a pay to dispose");
// depends on control dependency: [if], data = [none]
onPMSPayEnd(HMSAgent.AgentResultCode.REQUEST_REPEATED, null);
// depends on control dependency: [if], data = [null)]
return;
// depends on control dependency: [if], data = [none]
}
//启动支付流程
try {
statusForPay = status;
// depends on control dependency: [try], data = [none]
Intent intent = new Intent(curActivity, HMSPMSPayAgentActivity.class);
intent.putExtra(BaseAgentActivity.EXTRA_IS_FULLSCREEN, UIUtils.isActivityFullscreen(curActivity));
// depends on control dependency: [try], data = [none]
curActivity.startActivity(intent);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
HMSAgentLog.e("start HMSPayAgentActivity error:" + e.getMessage());
onPMSPayEnd(HMSAgent.AgentResultCode.START_ACTIVITY_ERROR, null);
}
// depends on control dependency: [catch], data = [none]
}else {
onPMSPayEnd(rstCode, null);
// depends on control dependency: [if], data = [(rstCode]
}
}
});
} } |
public class class_name {
public void update(String jsonString, Object object) {
try {
mapper.readerForUpdating(object).readValue(jsonString);
} catch (JsonProcessingException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
} catch (IOException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
}
} } | public class class_name {
public void update(String jsonString, Object object) {
try {
mapper.readerForUpdating(object).readValue(jsonString); // depends on control dependency: [try], data = [none]
} catch (JsonProcessingException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
} catch (IOException e) { // depends on control dependency: [catch], data = [none]
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static void listAllThreads(final PrintWriter out) {
final ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
ThreadGroup rootThreadGroup = currentThreadGroup;
ThreadGroup parent = rootThreadGroup.getParent();
while (parent != null) {
rootThreadGroup = parent;
parent = parent.getParent();
}
// And list it, recursively
Util.printGroupInfo(out, rootThreadGroup, "");
} } | public class class_name {
private static void listAllThreads(final PrintWriter out) {
final ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
ThreadGroup rootThreadGroup = currentThreadGroup;
ThreadGroup parent = rootThreadGroup.getParent();
while (parent != null) {
rootThreadGroup = parent;
// depends on control dependency: [while], data = [none]
parent = parent.getParent();
// depends on control dependency: [while], data = [none]
}
// And list it, recursively
Util.printGroupInfo(out, rootThreadGroup, "");
} } |
public class class_name {
public static DruidPlugin druidPlugin(
Properties dbProp
) {
String dbUrl = dbProp.getProperty(GojaPropConst.DBURL),
username = dbProp.getProperty(GojaPropConst.DBUSERNAME),
password = dbProp.getProperty(GojaPropConst.DBPASSWORD);
if (!Strings.isNullOrEmpty(dbUrl)) {
String dbtype = JdbcUtils.getDbType(dbUrl, StringUtils.EMPTY);
String driverClassName;
try {
driverClassName = JdbcUtils.getDriverClassName(dbUrl);
} catch (SQLException e) {
throw new DatabaseException(e.getMessage(), e);
}
final DruidPlugin druidPlugin = new DruidPlugin(dbUrl, username, password, driverClassName);
// set validator
setValidatorQuery(dbtype, druidPlugin);
druidPlugin.addFilter(new StatFilter());
final String initialSize = dbProp.getProperty(GojaPropConst.DB_INITIAL_SIZE);
if (!Strings.isNullOrEmpty(initialSize)) {
druidPlugin.setInitialSize(MoreObjects.firstNonNull(Ints.tryParse(initialSize), 6));
}
final String initial_minidle = dbProp.getProperty(GojaPropConst.DB_INITIAL_MINIDLE);
if (!Strings.isNullOrEmpty(initial_minidle)) {
druidPlugin.setMinIdle(MoreObjects.firstNonNull(Ints.tryParse(initial_minidle), 5));
}
final String initial_maxwait = dbProp.getProperty(GojaPropConst.DB_INITIAL_MAXWAIT);
if (!Strings.isNullOrEmpty(initial_maxwait)) {
druidPlugin.setMaxWait(MoreObjects.firstNonNull(Ints.tryParse(initial_maxwait), 5));
}
final String initial_active = dbProp.getProperty(GojaPropConst.DB_INITIAL_ACTIVE);
if (!Strings.isNullOrEmpty(initial_active)) {
druidPlugin.setMaxActive(MoreObjects.firstNonNull(Ints.tryParse(initial_active), 5));
}
final String timeBetweenEvictionRunsMillis =
dbProp.getProperty(GojaPropConst.DB_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
if (!Strings.isNullOrEmpty(timeBetweenEvictionRunsMillis)) {
final Integer millis = MoreObjects.firstNonNull(Ints.tryParse(timeBetweenEvictionRunsMillis), 10000);
druidPlugin.setTimeBetweenEvictionRunsMillis(millis);
}
final String minEvictableIdleTimeMillis =
dbProp.getProperty(GojaPropConst.DB_MIN_EVICTABLE_IDLE_TIME_MILLIS);
if (!Strings.isNullOrEmpty(minEvictableIdleTimeMillis)) {
final Integer idleTimeMillis = MoreObjects.firstNonNull(Ints.tryParse(minEvictableIdleTimeMillis), 10000);
druidPlugin.setMinEvictableIdleTimeMillis(idleTimeMillis);
}
final WallFilter wall = new WallFilter();
wall.setDbType(dbtype);
druidPlugin.addFilter(wall);
if (GojaConfig.getPropertyToBoolean(GojaPropConst.DBLOGFILE, false)) {
// 增加 LogFilter 输出JDBC执行的日志
druidPlugin.addFilter(new Slf4jLogFilter());
}
return druidPlugin;
}
return null;
} } | public class class_name {
public static DruidPlugin druidPlugin(
Properties dbProp
) {
String dbUrl = dbProp.getProperty(GojaPropConst.DBURL),
username = dbProp.getProperty(GojaPropConst.DBUSERNAME),
password = dbProp.getProperty(GojaPropConst.DBPASSWORD);
if (!Strings.isNullOrEmpty(dbUrl)) {
String dbtype = JdbcUtils.getDbType(dbUrl, StringUtils.EMPTY);
String driverClassName;
try {
driverClassName = JdbcUtils.getDriverClassName(dbUrl); // depends on control dependency: [try], data = [none]
} catch (SQLException e) {
throw new DatabaseException(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
final DruidPlugin druidPlugin = new DruidPlugin(dbUrl, username, password, driverClassName);
// set validator
setValidatorQuery(dbtype, druidPlugin); // depends on control dependency: [if], data = [none]
druidPlugin.addFilter(new StatFilter()); // depends on control dependency: [if], data = [none]
final String initialSize = dbProp.getProperty(GojaPropConst.DB_INITIAL_SIZE);
if (!Strings.isNullOrEmpty(initialSize)) {
druidPlugin.setInitialSize(MoreObjects.firstNonNull(Ints.tryParse(initialSize), 6)); // depends on control dependency: [if], data = [none]
}
final String initial_minidle = dbProp.getProperty(GojaPropConst.DB_INITIAL_MINIDLE);
if (!Strings.isNullOrEmpty(initial_minidle)) {
druidPlugin.setMinIdle(MoreObjects.firstNonNull(Ints.tryParse(initial_minidle), 5)); // depends on control dependency: [if], data = [none]
}
final String initial_maxwait = dbProp.getProperty(GojaPropConst.DB_INITIAL_MAXWAIT);
if (!Strings.isNullOrEmpty(initial_maxwait)) {
druidPlugin.setMaxWait(MoreObjects.firstNonNull(Ints.tryParse(initial_maxwait), 5)); // depends on control dependency: [if], data = [none]
}
final String initial_active = dbProp.getProperty(GojaPropConst.DB_INITIAL_ACTIVE);
if (!Strings.isNullOrEmpty(initial_active)) {
druidPlugin.setMaxActive(MoreObjects.firstNonNull(Ints.tryParse(initial_active), 5)); // depends on control dependency: [if], data = [none]
}
final String timeBetweenEvictionRunsMillis =
dbProp.getProperty(GojaPropConst.DB_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
if (!Strings.isNullOrEmpty(timeBetweenEvictionRunsMillis)) {
final Integer millis = MoreObjects.firstNonNull(Ints.tryParse(timeBetweenEvictionRunsMillis), 10000);
druidPlugin.setTimeBetweenEvictionRunsMillis(millis); // depends on control dependency: [if], data = [none]
}
final String minEvictableIdleTimeMillis =
dbProp.getProperty(GojaPropConst.DB_MIN_EVICTABLE_IDLE_TIME_MILLIS);
if (!Strings.isNullOrEmpty(minEvictableIdleTimeMillis)) {
final Integer idleTimeMillis = MoreObjects.firstNonNull(Ints.tryParse(minEvictableIdleTimeMillis), 10000);
druidPlugin.setMinEvictableIdleTimeMillis(idleTimeMillis); // depends on control dependency: [if], data = [none]
}
final WallFilter wall = new WallFilter();
wall.setDbType(dbtype); // depends on control dependency: [if], data = [none]
druidPlugin.addFilter(wall); // depends on control dependency: [if], data = [none]
if (GojaConfig.getPropertyToBoolean(GojaPropConst.DBLOGFILE, false)) {
// 增加 LogFilter 输出JDBC执行的日志
druidPlugin.addFilter(new Slf4jLogFilter()); // depends on control dependency: [if], data = [none]
}
return druidPlugin; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static BufferedImage grayImage(Object srcIm) {
BufferedImage srcImage = read(srcIm);
BufferedImage grayImage = new BufferedImage(srcImage.getWidth(),
srcImage.getHeight(),
srcImage.getType());
for (int i = 0; i < srcImage.getWidth(); i++) {
for (int j = 0; j < srcImage.getHeight(); j++) {
grayImage.setRGB(i, j, Colors.getGray(srcImage, i, j));
}
}
return grayImage;
} } | public class class_name {
public static BufferedImage grayImage(Object srcIm) {
BufferedImage srcImage = read(srcIm);
BufferedImage grayImage = new BufferedImage(srcImage.getWidth(),
srcImage.getHeight(),
srcImage.getType());
for (int i = 0; i < srcImage.getWidth(); i++) {
for (int j = 0; j < srcImage.getHeight(); j++) {
grayImage.setRGB(i, j, Colors.getGray(srcImage, i, j)); // depends on control dependency: [for], data = [j]
}
}
return grayImage;
} } |
public class class_name {
@Override protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (changedView != this) {
return;
}
if (visibility == View.VISIBLE) {
resumePresenter();
} else {
pausePresenter();
}
} } | public class class_name {
@Override protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (changedView != this) {
return; // depends on control dependency: [if], data = [none]
}
if (visibility == View.VISIBLE) {
resumePresenter(); // depends on control dependency: [if], data = [none]
} else {
pausePresenter(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static MutableFst makeFilter(WriteableSymbolTable table, Semiring semiring, String eps1, String eps2) {
MutableFst filter = new MutableFst(semiring, table, table);
// State 0
MutableState s0 = filter.newStartState();
s0.setFinalWeight(semiring.one());
MutableState s1 = filter.newState();
s1.setFinalWeight(semiring.one());
MutableState s2 = filter.newState();
s2.setFinalWeight(semiring.one());
filter.addArc(s0, eps2, eps1, s0, semiring.one());
filter.addArc(s0, eps1, eps1, s1, semiring.one());
filter.addArc(s0, eps2, eps2, s2, semiring.one());
// self loops
filter.addArc(s1, eps1, eps1, s1, semiring.one());
filter.addArc(s2, eps2, eps2, s2, semiring.one());
for (ObjectIntCursor<String> cursor : table) {
int i = cursor.value;
String key = cursor.key;
if (key.equals(Fst.EPS) || key.equals(eps1) || key.equals(eps2)) {
continue;
}
filter.addArc(s0, i, i, s0, semiring.one());
filter.addArc(s1, i, i, s0, semiring.one());
filter.addArc(s2, i, i, s0, semiring.one());
}
return filter;
} } | public class class_name {
private static MutableFst makeFilter(WriteableSymbolTable table, Semiring semiring, String eps1, String eps2) {
MutableFst filter = new MutableFst(semiring, table, table);
// State 0
MutableState s0 = filter.newStartState();
s0.setFinalWeight(semiring.one());
MutableState s1 = filter.newState();
s1.setFinalWeight(semiring.one());
MutableState s2 = filter.newState();
s2.setFinalWeight(semiring.one());
filter.addArc(s0, eps2, eps1, s0, semiring.one());
filter.addArc(s0, eps1, eps1, s1, semiring.one());
filter.addArc(s0, eps2, eps2, s2, semiring.one());
// self loops
filter.addArc(s1, eps1, eps1, s1, semiring.one());
filter.addArc(s2, eps2, eps2, s2, semiring.one());
for (ObjectIntCursor<String> cursor : table) {
int i = cursor.value;
String key = cursor.key;
if (key.equals(Fst.EPS) || key.equals(eps1) || key.equals(eps2)) {
continue;
}
filter.addArc(s0, i, i, s0, semiring.one()); // depends on control dependency: [for], data = [none]
filter.addArc(s1, i, i, s0, semiring.one()); // depends on control dependency: [for], data = [none]
filter.addArc(s2, i, i, s0, semiring.one()); // depends on control dependency: [for], data = [none]
}
return filter;
} } |
public class class_name {
public ParcelFileDescriptor executeForBlobFileDescriptor(String sql, Object[] bindArgs,
CancellationSignal cancellationSignal) {
if (sql == null) {
throw new IllegalArgumentException("sql must not be null.");
}
final int cookie = mRecentOperations.beginOperation("executeForBlobFileDescriptor",
sql, bindArgs);
try {
final PreparedStatement statement = acquirePreparedStatement(sql);
try {
throwIfStatementForbidden(statement);
bindArguments(statement, bindArgs);
applyBlockGuardPolicy(statement);
attachCancellationSignal(cancellationSignal);
try {
int fd = nativeExecuteForBlobFileDescriptor(
mConnectionPtr, statement.mStatementPtr);
return fd >= 0 ? ParcelFileDescriptor.adoptFd(fd) : null;
} finally {
detachCancellationSignal(cancellationSignal);
}
} finally {
releasePreparedStatement(statement);
}
} catch (RuntimeException ex) {
mRecentOperations.failOperation(cookie, ex);
throw ex;
} finally {
mRecentOperations.endOperation(cookie);
}
} } | public class class_name {
public ParcelFileDescriptor executeForBlobFileDescriptor(String sql, Object[] bindArgs,
CancellationSignal cancellationSignal) {
if (sql == null) {
throw new IllegalArgumentException("sql must not be null.");
}
final int cookie = mRecentOperations.beginOperation("executeForBlobFileDescriptor",
sql, bindArgs);
try {
final PreparedStatement statement = acquirePreparedStatement(sql);
try {
throwIfStatementForbidden(statement); // depends on control dependency: [try], data = [none]
bindArguments(statement, bindArgs); // depends on control dependency: [try], data = [none]
applyBlockGuardPolicy(statement); // depends on control dependency: [try], data = [none]
attachCancellationSignal(cancellationSignal); // depends on control dependency: [try], data = [none]
try {
int fd = nativeExecuteForBlobFileDescriptor(
mConnectionPtr, statement.mStatementPtr);
return fd >= 0 ? ParcelFileDescriptor.adoptFd(fd) : null; // depends on control dependency: [try], data = [none]
} finally {
detachCancellationSignal(cancellationSignal);
}
} finally {
releasePreparedStatement(statement);
}
} catch (RuntimeException ex) {
mRecentOperations.failOperation(cookie, ex);
throw ex;
} finally { // depends on control dependency: [catch], data = [none]
mRecentOperations.endOperation(cookie);
}
} } |
public class class_name {
public boolean hasEntry(String dictName, String entryID) {
if (hasDictionary(dictName)) {
Dictionary dictionary = (Dictionary) dictionaries.get(dictName);
return dictionary.hasEntry(entryID.toLowerCase());
} else {
return false;
}
} } | public class class_name {
public boolean hasEntry(String dictName, String entryID) {
if (hasDictionary(dictName)) {
Dictionary dictionary = (Dictionary) dictionaries.get(dictName);
return dictionary.hasEntry(entryID.toLowerCase()); // depends on control dependency: [if], data = [none]
} else {
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void showAt(final int x, final int y) {
setPopupPositionAndShow(new PopupPanel.PositionCallback() {
@Override
public void setPosition(int offsetWidth, int offsetHeight) {
int left = x + Window.getScrollLeft();
int top = y + Window.getScrollTop();
int exceedingWidth = (offsetWidth + left) - (Window.getClientWidth() + Window.getScrollLeft());
if (exceedingWidth > 0) {
left -= exceedingWidth;
if (left < 0) {
left = 0;
}
}
int exceedingHeight = (offsetHeight + top) - (Window.getClientHeight() + Window.getScrollTop());
if (exceedingHeight > 0) {
top -= exceedingHeight;
if (top < 0) {
top = 0;
}
}
setPopupPosition(left, top);
}
});
} } | public class class_name {
public void showAt(final int x, final int y) {
setPopupPositionAndShow(new PopupPanel.PositionCallback() {
@Override
public void setPosition(int offsetWidth, int offsetHeight) {
int left = x + Window.getScrollLeft();
int top = y + Window.getScrollTop();
int exceedingWidth = (offsetWidth + left) - (Window.getClientWidth() + Window.getScrollLeft());
if (exceedingWidth > 0) {
left -= exceedingWidth; // depends on control dependency: [if], data = [none]
if (left < 0) {
left = 0; // depends on control dependency: [if], data = [none]
}
}
int exceedingHeight = (offsetHeight + top) - (Window.getClientHeight() + Window.getScrollTop());
if (exceedingHeight > 0) {
top -= exceedingHeight; // depends on control dependency: [if], data = [none]
if (top < 0) {
top = 0; // depends on control dependency: [if], data = [none]
}
}
setPopupPosition(left, top);
}
});
} } |
public class class_name {
boolean removeListenerByProbe(ProbeImpl probe, ProbeListener listener) {
boolean deactivatedProbe = false;
Set<ProbeListener> listeners = listenersByProbe.get(probe);
if (listeners != null) {
listeners.remove(listener);
if (listeners.isEmpty()) {
deactivateProbe(probe);
deactivatedProbe = true;
}
}
return deactivatedProbe;
} } | public class class_name {
boolean removeListenerByProbe(ProbeImpl probe, ProbeListener listener) {
boolean deactivatedProbe = false;
Set<ProbeListener> listeners = listenersByProbe.get(probe);
if (listeners != null) {
listeners.remove(listener); // depends on control dependency: [if], data = [none]
if (listeners.isEmpty()) {
deactivateProbe(probe); // depends on control dependency: [if], data = [none]
deactivatedProbe = true; // depends on control dependency: [if], data = [none]
}
}
return deactivatedProbe;
} } |
public class class_name {
private void addMessagingActiveMQExtension(OperationContext context, Map<PathAddress, ModelNode> migrationOperations, boolean describe) {
Resource root = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false);
if (root.getChildrenNames(EXTENSION).contains(MESSAGING_ACTIVEMQ_EXTENSION)) {
// extension is already added, do nothing
return;
}
PathAddress extensionAddress = pathAddress(EXTENSION, MESSAGING_ACTIVEMQ_EXTENSION);
OperationEntry addEntry = context.getRootResourceRegistration().getOperationEntry(extensionAddress, ADD);
ModelNode addOperation = createAddOperation(extensionAddress);
addOperation.get(MODULE).set(MESSAGING_ACTIVEMQ_MODULE);
if (describe) {
migrationOperations.put(extensionAddress, addOperation);
} else {
context.addStep(context.getResult().get(extensionAddress.toString()), addOperation, addEntry.getOperationHandler(), MODEL);
}
} } | public class class_name {
private void addMessagingActiveMQExtension(OperationContext context, Map<PathAddress, ModelNode> migrationOperations, boolean describe) {
Resource root = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false);
if (root.getChildrenNames(EXTENSION).contains(MESSAGING_ACTIVEMQ_EXTENSION)) {
// extension is already added, do nothing
return; // depends on control dependency: [if], data = [none]
}
PathAddress extensionAddress = pathAddress(EXTENSION, MESSAGING_ACTIVEMQ_EXTENSION);
OperationEntry addEntry = context.getRootResourceRegistration().getOperationEntry(extensionAddress, ADD);
ModelNode addOperation = createAddOperation(extensionAddress);
addOperation.get(MODULE).set(MESSAGING_ACTIVEMQ_MODULE);
if (describe) {
migrationOperations.put(extensionAddress, addOperation); // depends on control dependency: [if], data = [none]
} else {
context.addStep(context.getResult().get(extensionAddress.toString()), addOperation, addEntry.getOperationHandler(), MODEL); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void collect(PrintStream out, List<ItemSet> list, TotalSupportTree ttree, int[] itemset, int support) {
if (list != null) {
synchronized (list) {
list.add(new ItemSet(itemset, support));
}
}
if (out != null) {
synchronized (out) {
for (int i = 0; i < itemset.length; i++) {
out.format("%d ", itemset[i]);
}
out.format("(%d)%n", support);
}
}
if (ttree != null) {
synchronized (ttree) {
ttree.add(itemset, support);
}
}
} } | public class class_name {
private void collect(PrintStream out, List<ItemSet> list, TotalSupportTree ttree, int[] itemset, int support) {
if (list != null) {
synchronized (list) { // depends on control dependency: [if], data = [(list]
list.add(new ItemSet(itemset, support));
}
}
if (out != null) {
synchronized (out) { // depends on control dependency: [if], data = [(out]
for (int i = 0; i < itemset.length; i++) {
out.format("%d ", itemset[i]); // depends on control dependency: [for], data = [i]
}
out.format("(%d)%n", support);
}
}
if (ttree != null) {
synchronized (ttree) { // depends on control dependency: [if], data = [(ttree]
ttree.add(itemset, support);
}
}
} } |
public class class_name {
private static void getChroma0X(byte[] pels, int picW, int picH, byte[] blk, int blkOff, int blkStride, int fullX,
int fullY, int fracY, int blkW, int blkH) {
int w00 = fullY * picW + fullX;
int w01 = w00 + (fullY < picH - 1 ? picW : 0);
int eMy = 8 - fracY;
for (int j = 0; j < blkH; j++) {
for (int i = 0; i < blkW; i++) {
blk[blkOff + i] = (byte) ((eMy * pels[w00 + i] + fracY * pels[w01 + i] + 4) >> 3);
}
w00 += picW;
w01 += picW;
blkOff += blkStride;
}
} } | public class class_name {
private static void getChroma0X(byte[] pels, int picW, int picH, byte[] blk, int blkOff, int blkStride, int fullX,
int fullY, int fracY, int blkW, int blkH) {
int w00 = fullY * picW + fullX;
int w01 = w00 + (fullY < picH - 1 ? picW : 0);
int eMy = 8 - fracY;
for (int j = 0; j < blkH; j++) {
for (int i = 0; i < blkW; i++) {
blk[blkOff + i] = (byte) ((eMy * pels[w00 + i] + fracY * pels[w01 + i] + 4) >> 3); // depends on control dependency: [for], data = [i]
}
w00 += picW; // depends on control dependency: [for], data = [none]
w01 += picW; // depends on control dependency: [for], data = [none]
blkOff += blkStride; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
@Override
public void solve(DMatrixRMaj B , DMatrixRMaj X ) {
if( B.numRows != n ) {
throw new IllegalArgumentException("Unexpected matrix size");
}
X.reshape(n,B.numCols);
if(decomposer.isLower()) {
solveLower(A,B,X,vv);
} else {
throw new RuntimeException("Implement");
}
} } | public class class_name {
@Override
public void solve(DMatrixRMaj B , DMatrixRMaj X ) {
if( B.numRows != n ) {
throw new IllegalArgumentException("Unexpected matrix size");
}
X.reshape(n,B.numCols);
if(decomposer.isLower()) {
solveLower(A,B,X,vv); // depends on control dependency: [if], data = [none]
} else {
throw new RuntimeException("Implement");
}
} } |
public class class_name {
public static StringConsumers buildConsumer(Properties props, final String topic,//
final String groupId,//
final IMessageListener<String> listener,//
final int threads
) {
if (props == null || props.isEmpty()) {
props = new Properties();
}
props.put("groupid", groupId);
return new StringConsumers(props, topic, threads, listener);
} } | public class class_name {
public static StringConsumers buildConsumer(Properties props, final String topic,//
final String groupId,//
final IMessageListener<String> listener,//
final int threads
) {
if (props == null || props.isEmpty()) {
props = new Properties(); // depends on control dependency: [if], data = [none]
}
props.put("groupid", groupId);
return new StringConsumers(props, topic, threads, listener);
} } |
public class class_name {
public int read(byte[] buf, int off, int len) throws IOException {
if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length)
throw new IndexOutOfBoundsException();
if (len == 0)
return 0;
if (in == null)
throw new XZIOException("Stream closed");
if (exception != null)
throw exception;
if (endReached)
return -1;
int size = 0;
try {
while (len > 0) {
if (blockDecoder == null) {
try {
blockDecoder = new BlockInputStream(
in, check, verifyCheck, memoryLimit, -1, -1,
arrayCache);
} catch (IndexIndicatorException e) {
indexHash.validate(in);
validateStreamFooter();
endReached = true;
return size > 0 ? size : -1;
}
}
int ret = blockDecoder.read(buf, off, len);
if (ret > 0) {
size += ret;
off += ret;
len -= ret;
} else if (ret == -1) {
indexHash.add(blockDecoder.getUnpaddedSize(),
blockDecoder.getUncompressedSize());
blockDecoder = null;
}
}
} catch (IOException e) {
exception = e;
if (size == 0)
throw e;
}
return size;
} } | public class class_name {
public int read(byte[] buf, int off, int len) throws IOException {
if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length)
throw new IndexOutOfBoundsException();
if (len == 0)
return 0;
if (in == null)
throw new XZIOException("Stream closed");
if (exception != null)
throw exception;
if (endReached)
return -1;
int size = 0;
try {
while (len > 0) {
if (blockDecoder == null) {
try {
blockDecoder = new BlockInputStream(
in, check, verifyCheck, memoryLimit, -1, -1,
arrayCache); // depends on control dependency: [try], data = [none]
} catch (IndexIndicatorException e) {
indexHash.validate(in);
validateStreamFooter();
endReached = true;
return size > 0 ? size : -1;
} // depends on control dependency: [catch], data = [none]
}
int ret = blockDecoder.read(buf, off, len);
if (ret > 0) {
size += ret; // depends on control dependency: [if], data = [none]
off += ret; // depends on control dependency: [if], data = [none]
len -= ret; // depends on control dependency: [if], data = [none]
} else if (ret == -1) {
indexHash.add(blockDecoder.getUnpaddedSize(),
blockDecoder.getUncompressedSize()); // depends on control dependency: [if], data = [none]
blockDecoder = null; // depends on control dependency: [if], data = [none]
}
}
} catch (IOException e) {
exception = e;
if (size == 0)
throw e;
}
return size;
} } |
public class class_name {
@Override
public final EntityManager createEntityManager(Map map)
{
// For Application managed persistence context, type is always EXTENDED
if (isOpen())
{
return new EntityManagerImpl(this, map, transactionType, PersistenceContextType.EXTENDED);
}
throw new IllegalStateException("Entity manager factory has been closed.");
} } | public class class_name {
@Override
public final EntityManager createEntityManager(Map map)
{
// For Application managed persistence context, type is always EXTENDED
if (isOpen())
{
return new EntityManagerImpl(this, map, transactionType, PersistenceContextType.EXTENDED);
// depends on control dependency: [if], data = [none]
}
throw new IllegalStateException("Entity manager factory has been closed.");
} } |
public class class_name {
public static boolean isHexNumber(String value) {
final int index = (value.startsWith("-") ? 1 : 0);
if (value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index)) {
try {
Long.decode(value);
} catch (NumberFormatException e) {
return false;
}
return true;
}else {
return false;
}
} } | public class class_name {
public static boolean isHexNumber(String value) {
final int index = (value.startsWith("-") ? 1 : 0);
if (value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index)) {
try {
Long.decode(value);
// depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
return false;
}
// depends on control dependency: [catch], data = [none]
return true;
// depends on control dependency: [if], data = [none]
}else {
return false;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static OrderBy parse(String orderBy) {
OrderBy toReturn = new OrderBy();
String[] orderBys = orderBy.split(",");
for (String order : orderBys) {
order = order.trim();
String[] fields = order.split(":");
Order ord = Order.ASC;
NullOrder nullOrd = NullOrder.NULL_SMALLEST;
if (fields.length > 1) {
String[] qualifiers = fields[1].split("\\|");
for (String qualifier : qualifiers) {
qualifier = qualifier.trim();
boolean success = false;
try {
ord = Order.valueOf(qualifier.toUpperCase());
success = true;
} catch (IllegalArgumentException e) {
}
try {
nullOrd = NullOrder.valueOf(qualifier.toUpperCase());
success = true;
} catch (IllegalArgumentException e) {
}
if (!success) {
throw new PangoolRuntimeException("Unrecognised sort qualifier " + qualifier +
" on sorting string: " + orderBy + ". Valid qualifiers are " + validQualifiers());
}
}
}
toReturn.add(fields[0].trim(), ord, nullOrd);
}
return toReturn;
} } | public class class_name {
public static OrderBy parse(String orderBy) {
OrderBy toReturn = new OrderBy();
String[] orderBys = orderBy.split(",");
for (String order : orderBys) {
order = order.trim(); // depends on control dependency: [for], data = [order]
String[] fields = order.split(":");
Order ord = Order.ASC;
NullOrder nullOrd = NullOrder.NULL_SMALLEST;
if (fields.length > 1) {
String[] qualifiers = fields[1].split("\\|");
for (String qualifier : qualifiers) {
qualifier = qualifier.trim(); // depends on control dependency: [for], data = [qualifier]
boolean success = false;
try {
ord = Order.valueOf(qualifier.toUpperCase()); // depends on control dependency: [try], data = [none]
success = true; // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
} // depends on control dependency: [catch], data = [none]
try {
nullOrd = NullOrder.valueOf(qualifier.toUpperCase()); // depends on control dependency: [try], data = [none]
success = true; // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
} // depends on control dependency: [catch], data = [none]
if (!success) {
throw new PangoolRuntimeException("Unrecognised sort qualifier " + qualifier +
" on sorting string: " + orderBy + ". Valid qualifiers are " + validQualifiers());
}
}
}
toReturn.add(fields[0].trim(), ord, nullOrd); // depends on control dependency: [for], data = [none]
}
return toReturn;
} } |
public class class_name {
private static int checkIndexOf(final String str, final int strStartIndex, final String search) {
final int endIndex = str.length() - search.length();
if (endIndex >= strStartIndex) {
for (int i = strStartIndex; i <= endIndex; i++) {
if (checkRegionMatches(str, i, search)) {
return i;
}
}
}
return -1;
} } | public class class_name {
private static int checkIndexOf(final String str, final int strStartIndex, final String search) {
final int endIndex = str.length() - search.length();
if (endIndex >= strStartIndex) {
for (int i = strStartIndex; i <= endIndex; i++) {
if (checkRegionMatches(str, i, search)) {
return i; // depends on control dependency: [if], data = [none]
}
}
}
return -1;
} } |
public class class_name {
private void settingsSaveAsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_settingsSaveAsMenuItemActionPerformed
JFileChooser fc = new JFileChooser();
if (settingsFile != null) {
fc.setSelectedFile(settingsFile);
} else {
fc.setSelectedFile(DEFAULT_SETTINGS_FILE);
}
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
settingsFile = fc.getSelectedFile();
settingsSaveMenuItemActionPerformed(evt);
}
} } | public class class_name {
private void settingsSaveAsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_settingsSaveAsMenuItemActionPerformed
JFileChooser fc = new JFileChooser();
if (settingsFile != null) {
fc.setSelectedFile(settingsFile); // depends on control dependency: [if], data = [(settingsFile]
} else {
fc.setSelectedFile(DEFAULT_SETTINGS_FILE); // depends on control dependency: [if], data = [none]
}
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
settingsFile = fc.getSelectedFile(); // depends on control dependency: [if], data = [none]
settingsSaveMenuItemActionPerformed(evt); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setOnlyFirstAndLastTickLabelVisible(final boolean VISIBLE) {
if (null == onlyFirstAndLastTickLabelVisible) {
_onlyFirstAndLastTickLabelVisible = VISIBLE;
fireUpdateEvent(REDRAW_EVENT);
} else {
onlyFirstAndLastTickLabelVisible.set(VISIBLE);
}
} } | public class class_name {
public void setOnlyFirstAndLastTickLabelVisible(final boolean VISIBLE) {
if (null == onlyFirstAndLastTickLabelVisible) {
_onlyFirstAndLastTickLabelVisible = VISIBLE; // depends on control dependency: [if], data = [none]
fireUpdateEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none]
} else {
onlyFirstAndLastTickLabelVisible.set(VISIBLE); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <N, V> MutableValueGraph<N, V> inducedSubgraph(
ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
MutableValueGraph<N, V> subgraph = ValueGraphBuilder.from(graph).build();
for (N node : nodes) {
subgraph.addNode(node);
}
for (N node : subgraph.nodes()) {
for (N successorNode : graph.successors(node)) {
if (subgraph.nodes().contains(successorNode)) {
subgraph.putEdgeValue(node, successorNode, graph.edgeValue(node, successorNode));
}
}
}
return subgraph;
} } | public class class_name {
public static <N, V> MutableValueGraph<N, V> inducedSubgraph(
ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
MutableValueGraph<N, V> subgraph = ValueGraphBuilder.from(graph).build();
for (N node : nodes) {
subgraph.addNode(node); // depends on control dependency: [for], data = [node]
}
for (N node : subgraph.nodes()) {
for (N successorNode : graph.successors(node)) {
if (subgraph.nodes().contains(successorNode)) {
subgraph.putEdgeValue(node, successorNode, graph.edgeValue(node, successorNode)); // depends on control dependency: [if], data = [none]
}
}
}
return subgraph;
} } |
public class class_name {
protected Bucket getBucketForValue(long value) {
for (Bucket bucket : buckets) {
if (bucket.contains(value)) {
return bucket;
}
}
throw new IllegalStateException("Non continuous buckets.");
} } | public class class_name {
protected Bucket getBucketForValue(long value) {
for (Bucket bucket : buckets) {
if (bucket.contains(value)) {
return bucket;
// depends on control dependency: [if], data = [none]
}
}
throw new IllegalStateException("Non continuous buckets.");
} } |
public class class_name {
public String getByGroupWithLog(String key, String group) {
final String value = getByGroup(key, group);
if (value == null) {
log.debug("No key define for [{}] of group [{}] !", key, group);
}
return value;
} } | public class class_name {
public String getByGroupWithLog(String key, String group) {
final String value = getByGroup(key, group);
if (value == null) {
log.debug("No key define for [{}] of group [{}] !", key, group);
// depends on control dependency: [if], data = [none]
}
return value;
} } |
public class class_name {
public synchronized void waitOnIgnoringInterruptions()
{
if (tc.isEntryEnabled()) SibTr.entry(tc, "waitOnIgnoringInterruptions");
boolean interrupted;
do
{
interrupted = false;
try
{
waitOn();
}
catch (InterruptedException e)
{
// No FFDC code needed
interrupted = true;
}
}
while(interrupted);
if (tc.isEntryEnabled()) SibTr.exit(tc, "waitOnIgnoringInterruptions");
} } | public class class_name {
public synchronized void waitOnIgnoringInterruptions()
{
if (tc.isEntryEnabled()) SibTr.entry(tc, "waitOnIgnoringInterruptions");
boolean interrupted;
do
{
interrupted = false;
try
{
waitOn(); // depends on control dependency: [try], data = [none]
}
catch (InterruptedException e)
{
// No FFDC code needed
interrupted = true;
} // depends on control dependency: [catch], data = [none]
}
while(interrupted);
if (tc.isEntryEnabled()) SibTr.exit(tc, "waitOnIgnoringInterruptions");
} } |
public class class_name {
public CachedResultSet rename(String... names) {
for (int i = 0; i < names.length; ++i) {
this.columns[i] = names[i];
}
return this;
} } | public class class_name {
public CachedResultSet rename(String... names) {
for (int i = 0; i < names.length; ++i) {
this.columns[i] = names[i]; // depends on control dependency: [for], data = [i]
}
return this;
} } |
public class class_name {
@Deprecated
public static int sizeToInt(final Size size) {
if (size == null) {
return -1;
}
switch (size) {
case ZERO:
return 0;
case SMALL:
return MAX_SMALL;
case MEDIUM:
return MAX_MED;
case LARGE:
return MAX_LARGE;
default:
return COMMON_XL;
}
} } | public class class_name {
@Deprecated
public static int sizeToInt(final Size size) {
if (size == null) {
return -1; // depends on control dependency: [if], data = [none]
}
switch (size) {
case ZERO:
return 0;
case SMALL:
return MAX_SMALL;
case MEDIUM:
return MAX_MED;
case LARGE:
return MAX_LARGE;
default:
return COMMON_XL;
}
} } |
public class class_name {
private void appendRubyElements(RendersnakeHtmlCanvas html,
List<SubtitleItem.Inner> elements) throws IOException {
for (SubtitleItem.Inner element : elements) {
String kanji = element.getKanji();
if (kanji != null) {
html.ruby();
html.spanKanji(kanji);
html.rt(element.getText());
html._ruby();
} else {
html.write(element.getText());
}
}
} } | public class class_name {
private void appendRubyElements(RendersnakeHtmlCanvas html,
List<SubtitleItem.Inner> elements) throws IOException {
for (SubtitleItem.Inner element : elements) {
String kanji = element.getKanji();
if (kanji != null) {
html.ruby();
// depends on control dependency: [if], data = [none]
html.spanKanji(kanji);
// depends on control dependency: [if], data = [(kanji]
html.rt(element.getText());
// depends on control dependency: [if], data = [none]
html._ruby();
// depends on control dependency: [if], data = [none]
} else {
html.write(element.getText());
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public EClass getIfcRampFlight() {
if (ifcRampFlightEClass == null) {
ifcRampFlightEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(423);
}
return ifcRampFlightEClass;
} } | public class class_name {
public EClass getIfcRampFlight() {
if (ifcRampFlightEClass == null) {
ifcRampFlightEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(423);
// depends on control dependency: [if], data = [none]
}
return ifcRampFlightEClass;
} } |
public class class_name {
public static BufferedImage generate(String content, BarcodeFormat format, QrConfig config) {
final BitMatrix bitMatrix = encode(content, format, config);
final BufferedImage image = toImage(bitMatrix, config.foreColor, config.backColor);
final Image logoImg = config.img;
if (null != logoImg && BarcodeFormat.QR_CODE == format) {
// 只有二维码可以贴图
final int qrWidth = image.getWidth();
final int qrHeight = image.getHeight();
int width;
int height;
// 按照最短的边做比例缩放
if (qrWidth < qrHeight) {
width = qrWidth / config.ratio;
height = logoImg.getHeight(null) * width / logoImg.getWidth(null);
} else {
height = qrHeight / config.ratio;
width = logoImg.getWidth(null) * height / logoImg.getHeight(null);
}
Img.from(image).pressImage(//
Img.from(logoImg).round(0.3).getImg(), // 圆角
new Rectangle(width, height), //
1//
);
}
return image;
} } | public class class_name {
public static BufferedImage generate(String content, BarcodeFormat format, QrConfig config) {
final BitMatrix bitMatrix = encode(content, format, config);
final BufferedImage image = toImage(bitMatrix, config.foreColor, config.backColor);
final Image logoImg = config.img;
if (null != logoImg && BarcodeFormat.QR_CODE == format) {
// 只有二维码可以贴图
final int qrWidth = image.getWidth();
final int qrHeight = image.getHeight();
int width;
int height;
// 按照最短的边做比例缩放
if (qrWidth < qrHeight) {
width = qrWidth / config.ratio;
// depends on control dependency: [if], data = [none]
height = logoImg.getHeight(null) * width / logoImg.getWidth(null);
// depends on control dependency: [if], data = [none]
} else {
height = qrHeight / config.ratio;
// depends on control dependency: [if], data = [none]
width = logoImg.getWidth(null) * height / logoImg.getHeight(null);
// depends on control dependency: [if], data = [none]
}
Img.from(image).pressImage(//
Img.from(logoImg).round(0.3).getImg(), // 圆角
new Rectangle(width, height), //
1//
);
// depends on control dependency: [if], data = [none]
}
return image;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T> T get(String key, Class<T> type, T defaultValue)
{
Objects.requireNonNull(key);
Objects.requireNonNull(type);
String value = _map.get(key);
if (value == null) {
return defaultValue;
}
if (type.equals(String.class)) {
return (T) value;
}
T valueType = _converter.convert(type, value);
if (valueType != null) {
return valueType;
}
else {
log.warning(L.l("Unexpected type for key={0} type={1} value={2}",
key, type, value));
/*
throw new ConfigException(L.l("Unexpected type for key={0} type={1} value={2}",
key, type, value));
*/
return defaultValue;
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T> T get(String key, Class<T> type, T defaultValue)
{
Objects.requireNonNull(key);
Objects.requireNonNull(type);
String value = _map.get(key);
if (value == null) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
if (type.equals(String.class)) {
return (T) value; // depends on control dependency: [if], data = [none]
}
T valueType = _converter.convert(type, value);
if (valueType != null) {
return valueType; // depends on control dependency: [if], data = [none]
}
else {
log.warning(L.l("Unexpected type for key={0} type={1} value={2}",
key, type, value)); // depends on control dependency: [if], data = [none]
/*
throw new ConfigException(L.l("Unexpected type for key={0} type={1} value={2}",
key, type, value));
*/
return defaultValue; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public List<PropertyType<ValidationConfigurationDescriptor>> getAllProperty()
{
List<PropertyType<ValidationConfigurationDescriptor>> list = new ArrayList<PropertyType<ValidationConfigurationDescriptor>>();
List<Node> nodeList = model.get("property");
for(Node node: nodeList)
{
PropertyType<ValidationConfigurationDescriptor> type = new PropertyTypeImpl<ValidationConfigurationDescriptor>(this, "property", model, node);
list.add(type);
}
return list;
} } | public class class_name {
public List<PropertyType<ValidationConfigurationDescriptor>> getAllProperty()
{
List<PropertyType<ValidationConfigurationDescriptor>> list = new ArrayList<PropertyType<ValidationConfigurationDescriptor>>();
List<Node> nodeList = model.get("property");
for(Node node: nodeList)
{
PropertyType<ValidationConfigurationDescriptor> type = new PropertyTypeImpl<ValidationConfigurationDescriptor>(this, "property", model, node);
list.add(type); // depends on control dependency: [for], data = [none]
}
return list;
} } |
public class class_name {
protected final void bindPropertiesWithOverrides(final String propertyFile) {
checkNotNull(propertyFile, "classpath resource property file must not be null");
Properties properties = new Properties();
// load classpath resource properties
InputStream inputStream = getClass().getResourceAsStream(propertyFile);
if (inputStream != null) {
try {
properties.load(inputStream);
}
catch (IOException e) {
// ignore
}
}
// override with system properties
properties.putAll(System.getProperties());
// override with environment variables
for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
String reformattedKey = entry.getKey().replace('_', '.');
// only replace existing keys
if (properties.containsKey(reformattedKey)) {
properties.put(reformattedKey, entry.getValue());
}
}
// bind merged properties
bindProperties(properties);
} } | public class class_name {
protected final void bindPropertiesWithOverrides(final String propertyFile) {
checkNotNull(propertyFile, "classpath resource property file must not be null");
Properties properties = new Properties();
// load classpath resource properties
InputStream inputStream = getClass().getResourceAsStream(propertyFile);
if (inputStream != null) {
try {
properties.load(inputStream); // depends on control dependency: [try], data = [none]
}
catch (IOException e) {
// ignore
} // depends on control dependency: [catch], data = [none]
}
// override with system properties
properties.putAll(System.getProperties());
// override with environment variables
for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
String reformattedKey = entry.getKey().replace('_', '.');
// only replace existing keys
if (properties.containsKey(reformattedKey)) {
properties.put(reformattedKey, entry.getValue()); // depends on control dependency: [if], data = [none]
}
}
// bind merged properties
bindProperties(properties);
} } |
public class class_name {
private Object processElement(byte[] source, int offset, int currentColumnIndex) {
byte[] temp;
int length = columnsDataLength.get(currentColumnIndex);
if (columns.get(currentColumnIndex).getType() == Number.class) {
temp = Arrays.copyOfRange(source, offset + (int) (long) columnsDataOffset.get(currentColumnIndex),
offset + (int) (long) columnsDataOffset.get(currentColumnIndex) + length);
if (columnsDataLength.get(currentColumnIndex) <= 2) {
return bytesToShort(temp);
} else {
if (columns.get(currentColumnIndex).getFormat().getName().isEmpty()) {
return convertByteArrayToNumber(temp);
} else {
if (DATE_TIME_FORMAT_STRINGS.contains(columns.get(currentColumnIndex).getFormat().getName())) {
return bytesToDateTime(temp);
} else {
if (DATE_FORMAT_STRINGS.contains(columns.get(currentColumnIndex).getFormat().getName())) {
return bytesToDate(temp);
} else {
return convertByteArrayToNumber(temp);
}
}
}
}
} else {
byte[] bytes = trimBytesArray(source,
offset + columnsDataOffset.get(currentColumnIndex).intValue(), length);
if (byteOutput) {
return bytes;
} else {
try {
return (bytes == null ? null : bytesToString(bytes));
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
return null;
} } | public class class_name {
private Object processElement(byte[] source, int offset, int currentColumnIndex) {
byte[] temp;
int length = columnsDataLength.get(currentColumnIndex);
if (columns.get(currentColumnIndex).getType() == Number.class) {
temp = Arrays.copyOfRange(source, offset + (int) (long) columnsDataOffset.get(currentColumnIndex),
offset + (int) (long) columnsDataOffset.get(currentColumnIndex) + length); // depends on control dependency: [if], data = [none]
if (columnsDataLength.get(currentColumnIndex) <= 2) {
return bytesToShort(temp); // depends on control dependency: [if], data = [none]
} else {
if (columns.get(currentColumnIndex).getFormat().getName().isEmpty()) {
return convertByteArrayToNumber(temp); // depends on control dependency: [if], data = [none]
} else {
if (DATE_TIME_FORMAT_STRINGS.contains(columns.get(currentColumnIndex).getFormat().getName())) {
return bytesToDateTime(temp); // depends on control dependency: [if], data = [none]
} else {
if (DATE_FORMAT_STRINGS.contains(columns.get(currentColumnIndex).getFormat().getName())) {
return bytesToDate(temp); // depends on control dependency: [if], data = [none]
} else {
return convertByteArrayToNumber(temp); // depends on control dependency: [if], data = [none]
}
}
}
}
} else {
byte[] bytes = trimBytesArray(source,
offset + columnsDataOffset.get(currentColumnIndex).intValue(), length);
if (byteOutput) {
return bytes; // depends on control dependency: [if], data = [none]
} else {
try {
return (bytes == null ? null : bytesToString(bytes)); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
}
return null;
} } |
public class class_name {
public void marshall(ResolverRuleConfig resolverRuleConfig, ProtocolMarshaller protocolMarshaller) {
if (resolverRuleConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resolverRuleConfig.getName(), NAME_BINDING);
protocolMarshaller.marshall(resolverRuleConfig.getTargetIps(), TARGETIPS_BINDING);
protocolMarshaller.marshall(resolverRuleConfig.getResolverEndpointId(), RESOLVERENDPOINTID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ResolverRuleConfig resolverRuleConfig, ProtocolMarshaller protocolMarshaller) {
if (resolverRuleConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resolverRuleConfig.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(resolverRuleConfig.getTargetIps(), TARGETIPS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(resolverRuleConfig.getResolverEndpointId(), RESOLVERENDPOINTID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static HashMap<String, String> parseDirectives(byte[] buf)
throws SaslException {
HashMap<String, String> map = new HashMap<>();
boolean gettingKey = true;
boolean gettingQuotedValue = false;
boolean expectSeparator = false;
byte bch;
ByteArrayOutputStream key = new ByteArrayOutputStream(10);
ByteArrayOutputStream value = new ByteArrayOutputStream(10);
int i = skipLws(buf, 0);
while (i < buf.length) {
bch = buf[i];
if (gettingKey) {
if (bch == ',') {
if (key.size() != 0) {
throw new SaslException("Directive key contains a ',':"
+ key);
}
// Empty element, skip separator and lws
i = skipLws(buf, i + 1);
} else if (bch == '=') {
if (key.size() == 0) {
throw new SaslException("Empty directive key");
}
gettingKey = false; // Termination of key
i = skipLws(buf, i + 1); // Skip to next non whitespace
// Check whether value is quoted
if (i < buf.length) {
if (buf[i] == '"') {
gettingQuotedValue = true;
++i; // Skip quote
}
} else {
throw new SaslException("Valueless directive found: "
+ key.toString());
}
} else if (isLws(bch)) {
// LWS that occurs after key
i = skipLws(buf, i + 1);
// Expecting '='
if (i < buf.length) {
if (buf[i] != '=') {
throw new SaslException("'=' expected after key: "
+ key.toString());
}
} else {
throw new SaslException("'=' expected after key: "
+ key.toString());
}
} else {
key.write(bch); // Append to key
++i; // Advance
}
} else if (gettingQuotedValue) {
// Getting a quoted value
if (bch == '\\') {
// quoted-pair = "\" CHAR ==> CHAR
++i; // Skip escape
if (i < buf.length) {
value.write(buf[i]);
++i; // Advance
} else {
// Trailing escape in a quoted value
throw new SaslException(
"Unmatched quote found for directive: "
+ key.toString() + " with value: "
+ value.toString());
}
} else if (bch == '"') {
// closing quote
++i; // Skip closing quote
gettingQuotedValue = false;
expectSeparator = true;
} else {
value.write(bch);
++i; // Advance
}
} else if (isLws(bch) || bch == ',') {
// Value terminated
extractDirective(map, key.toString(), value.toString());
key.reset();
value.reset();
gettingKey = true;
gettingQuotedValue = expectSeparator = false;
i = skipLws(buf, i + 1); // Skip separator and LWS
} else if (expectSeparator) {
throw new SaslException(
"Expecting comma or linear whitespace after quoted string: \""
+ value.toString() + "\"");
} else {
value.write(bch); // Unquoted value
++i; // Advance
}
}
if (gettingQuotedValue) {
throw new SaslException("Unmatched quote found for directive: "
+ key.toString() + " with value: " + value.toString());
}
// Get last pair
if (key.size() > 0) {
extractDirective(map, key.toString(), value.toString());
}
return map;
} } | public class class_name {
public static HashMap<String, String> parseDirectives(byte[] buf)
throws SaslException {
HashMap<String, String> map = new HashMap<>();
boolean gettingKey = true;
boolean gettingQuotedValue = false;
boolean expectSeparator = false;
byte bch;
ByteArrayOutputStream key = new ByteArrayOutputStream(10);
ByteArrayOutputStream value = new ByteArrayOutputStream(10);
int i = skipLws(buf, 0);
while (i < buf.length) {
bch = buf[i];
if (gettingKey) {
if (bch == ',') {
if (key.size() != 0) {
throw new SaslException("Directive key contains a ',':"
+ key);
}
// Empty element, skip separator and lws
i = skipLws(buf, i + 1);
} else if (bch == '=') {
if (key.size() == 0) {
throw new SaslException("Empty directive key");
}
gettingKey = false; // Termination of key
i = skipLws(buf, i + 1); // Skip to next non whitespace
// Check whether value is quoted
if (i < buf.length) {
if (buf[i] == '"') {
gettingQuotedValue = true; // depends on control dependency: [if], data = [none]
++i; // Skip quote // depends on control dependency: [if], data = [none]
}
} else {
throw new SaslException("Valueless directive found: "
+ key.toString());
}
} else if (isLws(bch)) {
// LWS that occurs after key
i = skipLws(buf, i + 1);
// Expecting '='
if (i < buf.length) {
if (buf[i] != '=') {
throw new SaslException("'=' expected after key: "
+ key.toString());
}
} else {
throw new SaslException("'=' expected after key: "
+ key.toString());
}
} else {
key.write(bch); // Append to key
++i; // Advance
}
} else if (gettingQuotedValue) {
// Getting a quoted value
if (bch == '\\') {
// quoted-pair = "\" CHAR ==> CHAR
++i; // Skip escape
if (i < buf.length) {
value.write(buf[i]);
++i; // Advance
} else {
// Trailing escape in a quoted value
throw new SaslException(
"Unmatched quote found for directive: "
+ key.toString() + " with value: "
+ value.toString());
}
} else if (bch == '"') {
// closing quote
++i; // Skip closing quote
gettingQuotedValue = false;
expectSeparator = true;
} else {
value.write(bch);
++i; // Advance
}
} else if (isLws(bch) || bch == ',') {
// Value terminated
extractDirective(map, key.toString(), value.toString());
key.reset();
value.reset();
gettingKey = true;
gettingQuotedValue = expectSeparator = false;
i = skipLws(buf, i + 1); // Skip separator and LWS
} else if (expectSeparator) {
throw new SaslException(
"Expecting comma or linear whitespace after quoted string: \""
+ value.toString() + "\"");
} else {
value.write(bch); // Unquoted value
++i; // Advance
}
}
if (gettingQuotedValue) {
throw new SaslException("Unmatched quote found for directive: "
+ key.toString() + " with value: " + value.toString());
}
// Get last pair
if (key.size() > 0) {
extractDirective(map, key.toString(), value.toString());
}
return map;
} } |
public class class_name {
int getExistingPathINodes(byte[][] components, INode[] existing) {
assert compareTo(components[0]) == 0 :
"Incorrect name " + getLocalName() + " expected " + components[0];
INode curNode = this;
int count = 0;
int index = existing.length - components.length;
if (index > 0)
index = 0;
while ((count < components.length) && (curNode != null)) {
if (index >= 0)
existing[index] = curNode;
if (!curNode.isDirectory() || (count == components.length - 1))
break; // no more child, stop here
INodeDirectory parentDir = (INodeDirectory)curNode;
curNode = parentDir.getChildINode(components[count + 1]);
count += 1;
index += 1;
}
return count;
} } | public class class_name {
int getExistingPathINodes(byte[][] components, INode[] existing) {
assert compareTo(components[0]) == 0 :
"Incorrect name " + getLocalName() + " expected " + components[0];
INode curNode = this;
int count = 0;
int index = existing.length - components.length;
if (index > 0)
index = 0;
while ((count < components.length) && (curNode != null)) {
if (index >= 0)
existing[index] = curNode;
if (!curNode.isDirectory() || (count == components.length - 1))
break; // no more child, stop here
INodeDirectory parentDir = (INodeDirectory)curNode;
curNode = parentDir.getChildINode(components[count + 1]); // depends on control dependency: [while], data = [none]
count += 1; // depends on control dependency: [while], data = [none]
index += 1; // depends on control dependency: [while], data = [none]
}
return count;
} } |
public class class_name {
private void tryRegisterJava8() {
try {
tryRegister("java.time.Instant", "parse");
tryRegister("java.time.Duration", "parse");
tryRegister("java.time.LocalDate", "parse");
tryRegister("java.time.LocalTime", "parse");
tryRegister("java.time.LocalDateTime", "parse");
tryRegister("java.time.OffsetTime", "parse");
tryRegister("java.time.OffsetDateTime", "parse");
tryRegister("java.time.ZonedDateTime", "parse");
tryRegister("java.time.Year", "parse");
tryRegister("java.time.YearMonth", "parse");
tryRegister("java.time.MonthDay", "parse");
tryRegister("java.time.Period", "parse");
tryRegister("java.time.ZoneOffset", "of");
tryRegister("java.time.ZoneId", "of");
tryRegister("java.time.ZoneRegion", "of");
} catch (Throwable ex) {
if (LOG) {
System.err.println("tryRegisterJava8: " + ex);
}
}
} } | public class class_name {
private void tryRegisterJava8() {
try {
tryRegister("java.time.Instant", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.Duration", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.LocalDate", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.LocalTime", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.LocalDateTime", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.OffsetTime", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.OffsetDateTime", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.ZonedDateTime", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.Year", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.YearMonth", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.MonthDay", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.Period", "parse");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.ZoneOffset", "of");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.ZoneId", "of");
// depends on control dependency: [try], data = [none]
tryRegister("java.time.ZoneRegion", "of");
// depends on control dependency: [try], data = [none]
} catch (Throwable ex) {
if (LOG) {
System.err.println("tryRegisterJava8: " + ex);
// depends on control dependency: [if], data = [none]
}
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void reportError(Throwable t) {
checkNotNull(t);
synchronized (lock) {
// do not override the initial exception
if (error == null) {
error = t;
}
next = null;
lock.notifyAll();
}
} } | public class class_name {
public void reportError(Throwable t) {
checkNotNull(t);
synchronized (lock) {
// do not override the initial exception
if (error == null) {
error = t; // depends on control dependency: [if], data = [none]
}
next = null;
lock.notifyAll();
}
} } |
public class class_name {
public void initialize(@Nullable KeyParameter aesKey) {
DeterministicSeed seed = Main.bitcoin.wallet().getKeyChainSeed();
if (aesKey == null) {
if (seed.isEncrypted()) {
log.info("Wallet is encrypted, requesting password first.");
// Delay execution of this until after we've finished initialising this screen.
Platform.runLater(() -> askForPasswordAndRetry());
return;
}
} else {
this.aesKey = aesKey;
seed = seed.decrypt(checkNotNull(Main.bitcoin.wallet().getKeyCrypter()), "", aesKey);
// Now we can display the wallet seed as appropriate.
passwordButton.setText("Remove password");
}
// Set the date picker to show the birthday of this wallet.
Instant creationTime = Instant.ofEpochSecond(seed.getCreationTimeSeconds());
LocalDate origDate = creationTime.atZone(ZoneId.systemDefault()).toLocalDate();
datePicker.setValue(origDate);
// Set the mnemonic seed words.
final List<String> mnemonicCode = seed.getMnemonicCode();
checkNotNull(mnemonicCode); // Already checked for encryption.
String origWords = Utils.SPACE_JOINER.join(mnemonicCode);
wordsArea.setText(origWords);
// Validate words as they are being typed.
MnemonicCode codec = unchecked(MnemonicCode::new);
TextFieldValidator validator = new TextFieldValidator(wordsArea, text ->
!didThrow(() -> codec.check(Splitter.on(' ').splitToList(text)))
);
// Clear the date picker if the user starts editing the words, if it contained the current wallets date.
// This forces them to set the birthday field when restoring.
wordsArea.textProperty().addListener(o -> {
if (origDate.equals(datePicker.getValue()))
datePicker.setValue(null);
});
BooleanBinding datePickerIsInvalid = or(
datePicker.valueProperty().isNull(),
createBooleanBinding(() ->
datePicker.getValue().isAfter(LocalDate.now())
, /* depends on */ datePicker.valueProperty())
);
// Don't let the user click restore if the words area contains the current wallet words, or are an invalid set,
// or if the date field isn't set, or if it's in the future.
restoreButton.disableProperty().bind(
or(
or(
not(validator.valid),
equal(origWords, wordsArea.textProperty())
),
datePickerIsInvalid
)
);
// Highlight the date picker in red if it's empty or in the future, so the user knows why restore is disabled.
datePickerIsInvalid.addListener((dp, old, cur) -> {
if (cur) {
datePicker.getStyleClass().add("validation_error");
} else {
datePicker.getStyleClass().remove("validation_error");
}
});
} } | public class class_name {
public void initialize(@Nullable KeyParameter aesKey) {
DeterministicSeed seed = Main.bitcoin.wallet().getKeyChainSeed();
if (aesKey == null) {
if (seed.isEncrypted()) {
log.info("Wallet is encrypted, requesting password first."); // depends on control dependency: [if], data = [none]
// Delay execution of this until after we've finished initialising this screen.
Platform.runLater(() -> askForPasswordAndRetry()); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else {
this.aesKey = aesKey; // depends on control dependency: [if], data = [none]
seed = seed.decrypt(checkNotNull(Main.bitcoin.wallet().getKeyCrypter()), "", aesKey); // depends on control dependency: [if], data = [none]
// Now we can display the wallet seed as appropriate.
passwordButton.setText("Remove password"); // depends on control dependency: [if], data = [none]
}
// Set the date picker to show the birthday of this wallet.
Instant creationTime = Instant.ofEpochSecond(seed.getCreationTimeSeconds());
LocalDate origDate = creationTime.atZone(ZoneId.systemDefault()).toLocalDate();
datePicker.setValue(origDate);
// Set the mnemonic seed words.
final List<String> mnemonicCode = seed.getMnemonicCode();
checkNotNull(mnemonicCode); // Already checked for encryption.
String origWords = Utils.SPACE_JOINER.join(mnemonicCode);
wordsArea.setText(origWords);
// Validate words as they are being typed.
MnemonicCode codec = unchecked(MnemonicCode::new);
TextFieldValidator validator = new TextFieldValidator(wordsArea, text ->
!didThrow(() -> codec.check(Splitter.on(' ').splitToList(text)))
);
// Clear the date picker if the user starts editing the words, if it contained the current wallets date.
// This forces them to set the birthday field when restoring.
wordsArea.textProperty().addListener(o -> {
if (origDate.equals(datePicker.getValue()))
datePicker.setValue(null);
});
BooleanBinding datePickerIsInvalid = or(
datePicker.valueProperty().isNull(),
createBooleanBinding(() ->
datePicker.getValue().isAfter(LocalDate.now())
, /* depends on */ datePicker.valueProperty())
);
// Don't let the user click restore if the words area contains the current wallet words, or are an invalid set,
// or if the date field isn't set, or if it's in the future.
restoreButton.disableProperty().bind(
or(
or(
not(validator.valid),
equal(origWords, wordsArea.textProperty())
),
datePickerIsInvalid
)
);
// Highlight the date picker in red if it's empty or in the future, so the user knows why restore is disabled.
datePickerIsInvalid.addListener((dp, old, cur) -> {
if (cur) {
datePicker.getStyleClass().add("validation_error");
} else {
datePicker.getStyleClass().remove("validation_error");
}
});
} } |
public class class_name {
private AstNode parseCreateIndex( final DdlTokenStream tokens,
final AstNode parentNode ) throws ParsingException {
assert tokens != null;
assert parentNode != null;
assert (tokens.matches(STMT_CREATE_INDEX) || tokens.matches(STMT_CREATE_UNIQUE_INDEX) || tokens.matches(STMT_CREATE_BITMAP_INDEX));
markStartOfStatement(tokens);
tokens.consume(CREATE);
final boolean isUnique = tokens.canConsume(UNIQUE);
final boolean isBitmap = tokens.canConsume("BITMAP");
tokens.consume(INDEX);
final String indexName = parseName(tokens);
tokens.consume(ON);
AstNode indexNode = null;
if (tokens.canConsume("CLUSTER")) {
// table-cluster_index_clause
indexNode = nodeFactory().node(indexName, parentNode, TYPE_CREATE_CLUSTER_INDEX_STATEMENT);
indexNode.setProperty(OracleDdlLexicon.INDEX_TYPE, OracleDdlConstants.IndexTypes.CLUSTER);
final String clusterName = parseName(tokens);
indexNode.setProperty(OracleDdlLexicon.CLUSTER_NAME, clusterName);
} else {
final String tableName = parseName(tokens);
if (!tokens.matches('(')) {
// must be a table-index-clause as this has to be table-alias
final String tableAlias = tokens.consume();
indexNode = nodeFactory().node(indexName, parentNode, TYPE_CREATE_TABLE_INDEX_STATEMENT);
indexNode.setProperty(OracleDdlLexicon.INDEX_TYPE, OracleDdlConstants.IndexTypes.TABLE);
indexNode.setProperty(OracleDdlLexicon.TABLE_ALIAS, tableAlias);
}
// parse left-paren content right-paren
final String columnExpressionList = parseContentBetweenParens(tokens);
// must have FROM and WHERE clauses
if (tokens.canConsume("FROM")) {
indexNode = nodeFactory().node(indexName, parentNode, TYPE_CREATE_BITMAP_JOIN_INDEX_STATEMENT);
indexNode.setProperty(OracleDdlLexicon.INDEX_TYPE, OracleDdlConstants.IndexTypes.BITMAP_JOIN);
parseTableReferenceList(tokens, indexNode);
tokens.consume("WHERE");
final String whereClause = parseUntilTerminator(tokens); // this will have index attributes also:-(
indexNode.setProperty(OracleDdlLexicon.WHERE_CLAUSE, whereClause);
} else {
indexNode = nodeFactory().node(indexName, parentNode, TYPE_CREATE_TABLE_INDEX_STATEMENT);
indexNode.setProperty(OracleDdlLexicon.INDEX_TYPE, OracleDdlConstants.IndexTypes.TABLE);
}
indexNode.setProperty(OracleDdlLexicon.TABLE_NAME, tableName);
parseIndexColumnExpressionList('(' + columnExpressionList + ')', indexNode);
}
indexNode.setProperty(UNIQUE_INDEX, isUnique);
indexNode.setProperty(BITMAP_INDEX, isBitmap);
// index attributes are optional as is UNUSABLE
if (tokens.hasNext()) {
boolean unusable = false;
final List<String> indexAttributes = new ArrayList<String>();
while (tokens.hasNext() && !isTerminator(tokens)) {
String token = tokens.consume();
if ("UNUSABLE".equalsIgnoreCase(token)) {
unusable = true;
break; // must be last token found before terminator
}
// if number add it to previous
boolean processed = false;
if (token.matches("\\b\\d+\\b")) {
if (!indexAttributes.isEmpty()) {
final int index = (indexAttributes.size() - 1);
final String value = indexAttributes.get(index);
final String newValue = (value + SPACE + token);
indexAttributes.set(index, newValue);
processed = true;
}
}
if (!processed) {
indexAttributes.add(token);
}
}
if (!indexAttributes.isEmpty()) {
indexNode.setProperty(OracleDdlLexicon.INDEX_ATTRIBUTES, indexAttributes);
}
indexNode.setProperty(OracleDdlLexicon.UNUSABLE_INDEX, unusable);
}
markEndOfStatement(tokens, indexNode);
return indexNode;
} } | public class class_name {
private AstNode parseCreateIndex( final DdlTokenStream tokens,
final AstNode parentNode ) throws ParsingException {
assert tokens != null;
assert parentNode != null;
assert (tokens.matches(STMT_CREATE_INDEX) || tokens.matches(STMT_CREATE_UNIQUE_INDEX) || tokens.matches(STMT_CREATE_BITMAP_INDEX));
markStartOfStatement(tokens);
tokens.consume(CREATE);
final boolean isUnique = tokens.canConsume(UNIQUE);
final boolean isBitmap = tokens.canConsume("BITMAP");
tokens.consume(INDEX);
final String indexName = parseName(tokens);
tokens.consume(ON);
AstNode indexNode = null;
if (tokens.canConsume("CLUSTER")) {
// table-cluster_index_clause
indexNode = nodeFactory().node(indexName, parentNode, TYPE_CREATE_CLUSTER_INDEX_STATEMENT);
indexNode.setProperty(OracleDdlLexicon.INDEX_TYPE, OracleDdlConstants.IndexTypes.CLUSTER);
final String clusterName = parseName(tokens);
indexNode.setProperty(OracleDdlLexicon.CLUSTER_NAME, clusterName);
} else {
final String tableName = parseName(tokens);
if (!tokens.matches('(')) {
// must be a table-index-clause as this has to be table-alias
final String tableAlias = tokens.consume();
indexNode = nodeFactory().node(indexName, parentNode, TYPE_CREATE_TABLE_INDEX_STATEMENT); // depends on control dependency: [if], data = [none]
indexNode.setProperty(OracleDdlLexicon.INDEX_TYPE, OracleDdlConstants.IndexTypes.TABLE); // depends on control dependency: [if], data = [none]
indexNode.setProperty(OracleDdlLexicon.TABLE_ALIAS, tableAlias); // depends on control dependency: [if], data = [none]
}
// parse left-paren content right-paren
final String columnExpressionList = parseContentBetweenParens(tokens);
// must have FROM and WHERE clauses
if (tokens.canConsume("FROM")) {
indexNode = nodeFactory().node(indexName, parentNode, TYPE_CREATE_BITMAP_JOIN_INDEX_STATEMENT); // depends on control dependency: [if], data = [none]
indexNode.setProperty(OracleDdlLexicon.INDEX_TYPE, OracleDdlConstants.IndexTypes.BITMAP_JOIN); // depends on control dependency: [if], data = [none]
parseTableReferenceList(tokens, indexNode); // depends on control dependency: [if], data = [none]
tokens.consume("WHERE"); // depends on control dependency: [if], data = [none]
final String whereClause = parseUntilTerminator(tokens); // this will have index attributes also:-(
indexNode.setProperty(OracleDdlLexicon.WHERE_CLAUSE, whereClause); // depends on control dependency: [if], data = [none]
} else {
indexNode = nodeFactory().node(indexName, parentNode, TYPE_CREATE_TABLE_INDEX_STATEMENT); // depends on control dependency: [if], data = [none]
indexNode.setProperty(OracleDdlLexicon.INDEX_TYPE, OracleDdlConstants.IndexTypes.TABLE); // depends on control dependency: [if], data = [none]
}
indexNode.setProperty(OracleDdlLexicon.TABLE_NAME, tableName);
parseIndexColumnExpressionList('(' + columnExpressionList + ')', indexNode);
}
indexNode.setProperty(UNIQUE_INDEX, isUnique);
indexNode.setProperty(BITMAP_INDEX, isBitmap);
// index attributes are optional as is UNUSABLE
if (tokens.hasNext()) {
boolean unusable = false;
final List<String> indexAttributes = new ArrayList<String>();
while (tokens.hasNext() && !isTerminator(tokens)) {
String token = tokens.consume();
if ("UNUSABLE".equalsIgnoreCase(token)) {
unusable = true; // depends on control dependency: [if], data = [none]
break; // must be last token found before terminator
}
// if number add it to previous
boolean processed = false;
if (token.matches("\\b\\d+\\b")) {
if (!indexAttributes.isEmpty()) {
final int index = (indexAttributes.size() - 1);
final String value = indexAttributes.get(index);
final String newValue = (value + SPACE + token);
indexAttributes.set(index, newValue); // depends on control dependency: [if], data = [none]
processed = true; // depends on control dependency: [if], data = [none]
}
}
if (!processed) {
indexAttributes.add(token); // depends on control dependency: [if], data = [none]
}
}
if (!indexAttributes.isEmpty()) {
indexNode.setProperty(OracleDdlLexicon.INDEX_ATTRIBUTES, indexAttributes);
}
indexNode.setProperty(OracleDdlLexicon.UNUSABLE_INDEX, unusable);
}
markEndOfStatement(tokens, indexNode);
return indexNode;
} } |
public class class_name {
public java.util.Map<String, String> getSunday() {
if (sunday == null) {
sunday = new com.amazonaws.internal.SdkInternalMap<String, String>();
}
return sunday;
} } | public class class_name {
public java.util.Map<String, String> getSunday() {
if (sunday == null) {
sunday = new com.amazonaws.internal.SdkInternalMap<String, String>(); // depends on control dependency: [if], data = [none]
}
return sunday;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static <F,T> Expression getJoinedEntityField(From<?, F> grandparentJoin, Attribute<?, T> parentJoinAttr, SingularAttribute fieldAttr) {
// task -> * -> origJoin -> (fieldParentAttr field in) tojoinType -> fieldAttr
Class toAttrJoinType;
if( parentJoinAttr instanceof SingularAttribute ) {
toAttrJoinType = parentJoinAttr.getJavaType();
} else if( parentJoinAttr instanceof PluralAttribute ) {
toAttrJoinType = ((PluralAttribute) parentJoinAttr).getElementType().getJavaType();
} else {
String joinName = parentJoinAttr.getDeclaringType().getJavaType().getSimpleName() + "." + parentJoinAttr.getName();
throw new IllegalStateException("Unknown attribute type encountered when trying to join " + joinName );
}
Join<F, T> fieldParentJoin = null;
for( Join<F, ?> join : grandparentJoin.getJoins() ) {
if( join.getJavaType().equals(toAttrJoinType) ) {
if( join.getAttribute().equals(parentJoinAttr) ) {
fieldParentJoin = (Join<F, T>) join;
if( ! JoinType.INNER.equals(fieldParentJoin.getJoinType()) ) {
// This a criteria set by the user (as opposed to the user-limiting criteria) -- it MUST be followed
// This means that the join is not optional (LEFT) but mandatory (INNER)
fieldParentJoin = null;
}
break;
}
}
}
if( fieldParentJoin == null ) {
if( parentJoinAttr instanceof SingularAttribute) {
fieldParentJoin = grandparentJoin.join((SingularAttribute) parentJoinAttr);
} else if( parentJoinAttr instanceof CollectionAttribute) {
fieldParentJoin = grandparentJoin.join((CollectionAttribute) parentJoinAttr);
} else if( parentJoinAttr instanceof ListAttribute) {
fieldParentJoin = grandparentJoin.join((ListAttribute) parentJoinAttr);
} else if( parentJoinAttr instanceof SetAttribute) {
fieldParentJoin = grandparentJoin.join((SetAttribute) parentJoinAttr);
} else {
throw new IllegalStateException("Unknown attribute type encountered when trying to join" + parentJoinAttr.getName() );
}
}
return fieldParentJoin.get(fieldAttr);
} } | public class class_name {
@SuppressWarnings("unchecked")
public static <F,T> Expression getJoinedEntityField(From<?, F> grandparentJoin, Attribute<?, T> parentJoinAttr, SingularAttribute fieldAttr) {
// task -> * -> origJoin -> (fieldParentAttr field in) tojoinType -> fieldAttr
Class toAttrJoinType;
if( parentJoinAttr instanceof SingularAttribute ) {
toAttrJoinType = parentJoinAttr.getJavaType(); // depends on control dependency: [if], data = [none]
} else if( parentJoinAttr instanceof PluralAttribute ) {
toAttrJoinType = ((PluralAttribute) parentJoinAttr).getElementType().getJavaType(); // depends on control dependency: [if], data = [none]
} else {
String joinName = parentJoinAttr.getDeclaringType().getJavaType().getSimpleName() + "." + parentJoinAttr.getName();
throw new IllegalStateException("Unknown attribute type encountered when trying to join " + joinName );
}
Join<F, T> fieldParentJoin = null;
for( Join<F, ?> join : grandparentJoin.getJoins() ) {
if( join.getJavaType().equals(toAttrJoinType) ) {
if( join.getAttribute().equals(parentJoinAttr) ) {
fieldParentJoin = (Join<F, T>) join; // depends on control dependency: [if], data = [none]
if( ! JoinType.INNER.equals(fieldParentJoin.getJoinType()) ) {
// This a criteria set by the user (as opposed to the user-limiting criteria) -- it MUST be followed
// This means that the join is not optional (LEFT) but mandatory (INNER)
fieldParentJoin = null; // depends on control dependency: [if], data = [none]
}
break;
}
}
}
if( fieldParentJoin == null ) {
if( parentJoinAttr instanceof SingularAttribute) {
fieldParentJoin = grandparentJoin.join((SingularAttribute) parentJoinAttr); // depends on control dependency: [if], data = [none]
} else if( parentJoinAttr instanceof CollectionAttribute) {
fieldParentJoin = grandparentJoin.join((CollectionAttribute) parentJoinAttr); // depends on control dependency: [if], data = [none]
} else if( parentJoinAttr instanceof ListAttribute) {
fieldParentJoin = grandparentJoin.join((ListAttribute) parentJoinAttr); // depends on control dependency: [if], data = [none]
} else if( parentJoinAttr instanceof SetAttribute) {
fieldParentJoin = grandparentJoin.join((SetAttribute) parentJoinAttr); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalStateException("Unknown attribute type encountered when trying to join" + parentJoinAttr.getName() );
}
}
return fieldParentJoin.get(fieldAttr);
} } |
public class class_name {
public static String bin2hex(final byte[] b)
{
if (b == null)
{
return "";
}
StringBuffer sb = new StringBuffer(2 * b.length);
for (int i = 0; i < b.length; i++)
{
int v = (256 + b[i]) % 256;
sb.append(hex.charAt((v / 16) & 15));
sb.append(hex.charAt((v % 16) & 15));
}
return sb.toString();
} } | public class class_name {
public static String bin2hex(final byte[] b)
{
if (b == null)
{
return ""; // depends on control dependency: [if], data = [none]
}
StringBuffer sb = new StringBuffer(2 * b.length);
for (int i = 0; i < b.length; i++)
{
int v = (256 + b[i]) % 256;
sb.append(hex.charAt((v / 16) & 15)); // depends on control dependency: [for], data = [none]
sb.append(hex.charAt((v % 16) & 15)); // depends on control dependency: [for], data = [none]
}
return sb.toString();
} } |
public class class_name {
private Locale getLocale(CmsXmlContent content) {
List<Locale> locales = content.getLocales();
if (locales.contains(Locale.ENGLISH) || locales.isEmpty()) {
return Locale.ENGLISH;
}
return locales.get(0);
} } | public class class_name {
private Locale getLocale(CmsXmlContent content) {
List<Locale> locales = content.getLocales();
if (locales.contains(Locale.ENGLISH) || locales.isEmpty()) {
return Locale.ENGLISH; // depends on control dependency: [if], data = [none]
}
return locales.get(0);
} } |
public class class_name {
private List<Integer> getFragmentFilteredPageIds(List<String> templateFragments, boolean whitelist) throws WikiApiException{
try {
PreparedStatement statement = null;
ResultSet result = null;
List<Integer> matchedPages = new LinkedList<Integer>();
try {
StringBuffer sqlString = new StringBuffer();
StringBuffer subconditions = new StringBuffer();
sqlString
.append("SELECT p.pageId FROM "+ GeneratorConstants.TABLE_TPLID_TPLNAME+ " AS tpl, "
+ GeneratorConstants.TABLE_TPLID_PAGEID+ " AS p WHERE tpl.templateId = p.templateId "+(whitelist?"AND":"AND NOT")+" (");
for(@SuppressWarnings("unused") String fragment:templateFragments){
if(subconditions.length()!=0){
subconditions.append("OR ");
}
subconditions.append("tpl.templateName LIKE ?");
}
sqlString.append(subconditions);
sqlString.append(")");
statement = connection.prepareStatement(sqlString.toString());
int curIdx=1;
for(String fragment:templateFragments){
fragment=fragment.toLowerCase().trim();
fragment=fragment.replaceAll(" ","_");
statement.setString(curIdx++, fragment + "%");
}
result = execute(statement);
if (result == null) {
throw new WikiPageNotFoundException("Nothing was found");
}
while (result.next()) {
matchedPages.add(result.getInt(1));
}
}
finally {
if (statement != null) {
statement.close();
}
if (result != null) {
result.close();
}
}
return matchedPages;
}
catch (Exception e) {
throw new WikiApiException(e);
}
} } | public class class_name {
private List<Integer> getFragmentFilteredPageIds(List<String> templateFragments, boolean whitelist) throws WikiApiException{
try {
PreparedStatement statement = null;
ResultSet result = null;
List<Integer> matchedPages = new LinkedList<Integer>();
try {
StringBuffer sqlString = new StringBuffer();
StringBuffer subconditions = new StringBuffer();
sqlString
.append("SELECT p.pageId FROM "+ GeneratorConstants.TABLE_TPLID_TPLNAME+ " AS tpl, "
+ GeneratorConstants.TABLE_TPLID_PAGEID+ " AS p WHERE tpl.templateId = p.templateId "+(whitelist?"AND":"AND NOT")+" (");
for(@SuppressWarnings("unused") String fragment:templateFragments){
if(subconditions.length()!=0){
subconditions.append("OR "); // depends on control dependency: [if], data = [none]
}
subconditions.append("tpl.templateName LIKE ?"); // depends on control dependency: [for], data = [none]
}
sqlString.append(subconditions);
sqlString.append(")");
statement = connection.prepareStatement(sqlString.toString());
int curIdx=1;
for(String fragment:templateFragments){
fragment=fragment.toLowerCase().trim(); // depends on control dependency: [for], data = [fragment]
fragment=fragment.replaceAll(" ","_"); // depends on control dependency: [for], data = [fragment]
statement.setString(curIdx++, fragment + "%"); // depends on control dependency: [for], data = [fragment]
}
result = execute(statement);
if (result == null) {
throw new WikiPageNotFoundException("Nothing was found");
}
while (result.next()) {
matchedPages.add(result.getInt(1)); // depends on control dependency: [while], data = [none]
}
}
finally {
if (statement != null) {
statement.close(); // depends on control dependency: [if], data = [none]
}
if (result != null) {
result.close(); // depends on control dependency: [if], data = [none]
}
}
return matchedPages;
}
catch (Exception e) {
throw new WikiApiException(e);
}
} } |
public class class_name {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java twitter4j.examples.geo.GetGeoDetails [place id]");
System.exit(-1);
}
try {
Twitter twitter = new TwitterFactory().getInstance();
Place place = twitter.getGeoDetails(args[0]);
System.out.println("name: " + place.getName());
System.out.println("country: " + place.getCountry());
System.out.println("country code: " + place.getCountryCode());
System.out.println("full name: " + place.getFullName());
System.out.println("id: " + place.getId());
System.out.println("place type: " + place.getPlaceType());
System.out.println("street address: " + place.getStreetAddress());
Place[] containedWithinArray = place.getContainedWithIn();
if (containedWithinArray != null && containedWithinArray.length != 0) {
System.out.println(" contained within:");
for (Place containedWithinPlace : containedWithinArray) {
System.out.println(" id: " + containedWithinPlace.getId() + " name: " + containedWithinPlace.getFullName());
}
}
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to retrieve geo details: " + te.getMessage());
System.exit(-1);
}
} } | public class class_name {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java twitter4j.examples.geo.GetGeoDetails [place id]"); // depends on control dependency: [if], data = [none]
System.exit(-1); // depends on control dependency: [if], data = [1)]
}
try {
Twitter twitter = new TwitterFactory().getInstance();
Place place = twitter.getGeoDetails(args[0]);
System.out.println("name: " + place.getName());
System.out.println("country: " + place.getCountry());
System.out.println("country code: " + place.getCountryCode());
System.out.println("full name: " + place.getFullName());
System.out.println("id: " + place.getId());
System.out.println("place type: " + place.getPlaceType());
System.out.println("street address: " + place.getStreetAddress());
Place[] containedWithinArray = place.getContainedWithIn();
if (containedWithinArray != null && containedWithinArray.length != 0) {
System.out.println(" contained within:");
for (Place containedWithinPlace : containedWithinArray) {
System.out.println(" id: " + containedWithinPlace.getId() + " name: " + containedWithinPlace.getFullName());
}
}
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to retrieve geo details: " + te.getMessage());
System.exit(-1);
}
} } |
public class class_name {
private boolean isInWhiteList(String tpl)
{
if ((!whiteList.isEmpty() && whiteList.contains(tpl))
|| (whiteList.isEmpty())) {
return true;
}
return false;
} } | public class class_name {
private boolean isInWhiteList(String tpl)
{
if ((!whiteList.isEmpty() && whiteList.contains(tpl))
|| (whiteList.isEmpty())) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
public void visitParameterAnnotation(ParameterAnnotations arg0) {
ParameterAnnotationEntry[] parameterAnnotationEntries = arg0.getParameterAnnotationEntries();
int numParametersToMethod = getNumberMethodArguments();
int offset = 0;
if (numParametersToMethod > parameterAnnotationEntries.length) {
offset = 1;
}
for (int i = 0; i < parameterAnnotationEntries.length; i++) {
ParameterAnnotationEntry e = parameterAnnotationEntries[i];
for (AnnotationEntry ae : e.getAnnotationEntries()) {
boolean runtimeVisible = ae.isRuntimeVisible();
String name = ClassName.fromFieldSignature(ae.getAnnotationType());
if (name == null) {
continue;
}
name = ClassName.toDottedClassName(name);
Map<String, ElementValue> map = new HashMap<>();
for (ElementValuePair ev : ae.getElementValuePairs()) {
map.put(ev.getNameString(), ev.getValue());
}
visitParameterAnnotation(offset + i, name, map, runtimeVisible);
}
}
} } | public class class_name {
@Override
public void visitParameterAnnotation(ParameterAnnotations arg0) {
ParameterAnnotationEntry[] parameterAnnotationEntries = arg0.getParameterAnnotationEntries();
int numParametersToMethod = getNumberMethodArguments();
int offset = 0;
if (numParametersToMethod > parameterAnnotationEntries.length) {
offset = 1; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < parameterAnnotationEntries.length; i++) {
ParameterAnnotationEntry e = parameterAnnotationEntries[i];
for (AnnotationEntry ae : e.getAnnotationEntries()) {
boolean runtimeVisible = ae.isRuntimeVisible();
String name = ClassName.fromFieldSignature(ae.getAnnotationType());
if (name == null) {
continue;
}
name = ClassName.toDottedClassName(name); // depends on control dependency: [for], data = [none]
Map<String, ElementValue> map = new HashMap<>();
for (ElementValuePair ev : ae.getElementValuePairs()) {
map.put(ev.getNameString(), ev.getValue()); // depends on control dependency: [for], data = [ev]
}
visitParameterAnnotation(offset + i, name, map, runtimeVisible); // depends on control dependency: [for], data = [none]
}
}
} } |
public class class_name {
public Subclass withIAMEndpoint(String iamEndpoint) {
this.iamEndpoint = iamEndpoint;
if ((this.credentials.getCredentials() instanceof IBMOAuthCredentials) &&
((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager() instanceof DefaultTokenManager){
((DefaultTokenManager)((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager()).setIamEndpoint(iamEndpoint);
if (((DefaultTokenManager)((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager()).getProvider() instanceof DefaultTokenProvider){
((DefaultTokenProvider)((DefaultTokenManager)((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager()).getProvider()).setIamEndpoint(iamEndpoint);
((DefaultTokenProvider)((DefaultTokenManager)((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager()).getProvider()).retrieveToken();
}
}
return getSubclass();
} } | public class class_name {
public Subclass withIAMEndpoint(String iamEndpoint) {
this.iamEndpoint = iamEndpoint;
if ((this.credentials.getCredentials() instanceof IBMOAuthCredentials) &&
((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager() instanceof DefaultTokenManager){
((DefaultTokenManager)((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager()).setIamEndpoint(iamEndpoint); // depends on control dependency: [if], data = [none]
if (((DefaultTokenManager)((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager()).getProvider() instanceof DefaultTokenProvider){
((DefaultTokenProvider)((DefaultTokenManager)((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager()).getProvider()).setIamEndpoint(iamEndpoint); // depends on control dependency: [if], data = [none]
((DefaultTokenProvider)((DefaultTokenManager)((IBMOAuthCredentials)this.credentials.getCredentials()).getTokenManager()).getProvider()).retrieveToken(); // depends on control dependency: [if], data = [none]
}
}
return getSubclass();
} } |
public class class_name {
private boolean registerStream(IClientStream stream) {
if (streams.putIfAbsent(stream.getStreamId().doubleValue(), stream) == null) {
usedStreams.incrementAndGet();
return true;
}
log.error("Unable to register stream {}, stream with id {} was already added", stream, stream.getStreamId());
return false;
} } | public class class_name {
private boolean registerStream(IClientStream stream) {
if (streams.putIfAbsent(stream.getStreamId().doubleValue(), stream) == null) {
usedStreams.incrementAndGet();
// depends on control dependency: [if], data = [none]
return true;
// depends on control dependency: [if], data = [none]
}
log.error("Unable to register stream {}, stream with id {} was already added", stream, stream.getStreamId());
return false;
} } |
public class class_name {
@GET
@Path("jd")
@Produces(MediaType.APPLICATION_JSON)
@HttpCache
public List<JobDefDto> getJobDefs()
{
DbConn cnx = null;
try
{
cnx = Helpers.getDbSession();
return MetaService.getJobDef(cnx);
}
finally
{
Helpers.closeQuietly(cnx);
}
} } | public class class_name {
@GET
@Path("jd")
@Produces(MediaType.APPLICATION_JSON)
@HttpCache
public List<JobDefDto> getJobDefs()
{
DbConn cnx = null;
try
{
cnx = Helpers.getDbSession(); // depends on control dependency: [try], data = [none]
return MetaService.getJobDef(cnx); // depends on control dependency: [try], data = [none]
}
finally
{
Helpers.closeQuietly(cnx);
}
} } |
public class class_name {
public V put(K key, V value){
writeLock.lock();
try {
cache.put(key, value);
} finally {
writeLock.unlock();
}
return value;
} } | public class class_name {
public V put(K key, V value){
writeLock.lock();
try {
cache.put(key, value);
// depends on control dependency: [try], data = [none]
} finally {
writeLock.unlock();
}
return value;
} } |
public class class_name {
private Registry startRmiRegistryProcess(Configuration configuration, final int port) {
try {
final String javaHome = System.getProperty(JAVA_HOME);
String command = null;
if (javaHome == null) {
command = "rmiregistry";
} else {
if (javaHome.endsWith("bin")) {
command = javaHome + "/rmiregistry ";
} else {
command = javaHome + "/bin/rmiregistry ";
}
}
// try with new command with full path
return internalProcessStart(configuration, port, command);// NOPMD
} catch (Exception e1) {
// if failed exit...
LOGGER.error("The RMI Registry cannot be started.", e1);
throw new UnsupportedOperationException("could not start rmiregistry!!! Reason: " + e1.toString(), e1);// NOPMD
}
} } | public class class_name {
private Registry startRmiRegistryProcess(Configuration configuration, final int port) {
try {
final String javaHome = System.getProperty(JAVA_HOME);
String command = null;
if (javaHome == null) {
command = "rmiregistry"; // depends on control dependency: [if], data = [none]
} else {
if (javaHome.endsWith("bin")) {
command = javaHome + "/rmiregistry "; // depends on control dependency: [if], data = [none]
} else {
command = javaHome + "/bin/rmiregistry "; // depends on control dependency: [if], data = [none]
}
}
// try with new command with full path
return internalProcessStart(configuration, port, command);// NOPMD // depends on control dependency: [try], data = [none]
} catch (Exception e1) {
// if failed exit...
LOGGER.error("The RMI Registry cannot be started.", e1);
throw new UnsupportedOperationException("could not start rmiregistry!!! Reason: " + e1.toString(), e1);// NOPMD
} // depends on control dependency: [catch], data = [none]
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.