code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
@SuppressWarnings("unchecked")
protected <T extends Result>T createStAXResult(
Class<T> resultClass) throws SQLException {
StAXResult result = null;
OutputStream outputStream = this.setBinaryStreamImpl();
Constructor ctor;
XMLOutputFactory factory;
XMLStreamWriter xmlStreamWriter;
try {
factory = XMLOutputFactory.newInstance();
xmlStreamWriter = factory.createXMLStreamWriter(outputStream);
if (resultClass == null) {
result = new StAXResult(xmlStreamWriter);
} else {
ctor = resultClass.getConstructor(XMLStreamWriter.class);
result = (StAXResult) ctor.newInstance(xmlStreamWriter);
}
} catch (SecurityException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (IllegalArgumentException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (IllegalAccessException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (InvocationTargetException ex) {
throw Exceptions.resultInstantiation(ex.getTargetException());
} catch (FactoryConfigurationError ex) {
throw Exceptions.resultInstantiation(ex);
} catch (InstantiationException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (NoSuchMethodException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (XMLStreamException ex) {
throw Exceptions.resultInstantiation(ex);
}
return (T) result;
} } | public class class_name {
@SuppressWarnings("unchecked")
protected <T extends Result>T createStAXResult(
Class<T> resultClass) throws SQLException {
StAXResult result = null;
OutputStream outputStream = this.setBinaryStreamImpl();
Constructor ctor;
XMLOutputFactory factory;
XMLStreamWriter xmlStreamWriter;
try {
factory = XMLOutputFactory.newInstance();
xmlStreamWriter = factory.createXMLStreamWriter(outputStream);
if (resultClass == null) {
result = new StAXResult(xmlStreamWriter); // depends on control dependency: [if], data = [none]
} else {
ctor = resultClass.getConstructor(XMLStreamWriter.class); // depends on control dependency: [if], data = [none]
result = (StAXResult) ctor.newInstance(xmlStreamWriter); // depends on control dependency: [if], data = [none]
}
} catch (SecurityException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (IllegalArgumentException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (IllegalAccessException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (InvocationTargetException ex) {
throw Exceptions.resultInstantiation(ex.getTargetException());
} catch (FactoryConfigurationError ex) {
throw Exceptions.resultInstantiation(ex);
} catch (InstantiationException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (NoSuchMethodException ex) {
throw Exceptions.resultInstantiation(ex);
} catch (XMLStreamException ex) {
throw Exceptions.resultInstantiation(ex);
}
return (T) result;
} } |
public class class_name {
public void setPage(int offset, int length) {
if (this.delegate != null)
this.delegate.setPage(offset, length);
else {
boolean changed = this.pageOffset != offset || this.pageLength != length;
if (changed) {
this.pageOffset = offset;
this.pageLength = length;
this.pageChanged = true;
}
}
QueryRecorder.recordInvocation(this, "setPage", Void.TYPE,
QueryRecorder.literal(offset), QueryRecorder.literal(length));
} } | public class class_name {
public void setPage(int offset, int length) {
if (this.delegate != null)
this.delegate.setPage(offset, length);
else {
boolean changed = this.pageOffset != offset || this.pageLength != length;
if (changed) {
this.pageOffset = offset; // depends on control dependency: [if], data = [none]
this.pageLength = length; // depends on control dependency: [if], data = [none]
this.pageChanged = true; // depends on control dependency: [if], data = [none]
}
}
QueryRecorder.recordInvocation(this, "setPage", Void.TYPE,
QueryRecorder.literal(offset), QueryRecorder.literal(length));
} } |
public class class_name {
public static <T extends ImageGray<T>>
void rgbToHsv(Planar<T> rgb , Planar<T> hsv ) {
hsv.reshape(rgb.width,rgb.height,3);
if( hsv.getBandType() == GrayF32.class ) {
if(BoofConcurrency.USE_CONCURRENT ) {
ImplColorHsv_MT.rgbToHsv_F32((Planar<GrayF32>)rgb,(Planar<GrayF32>)hsv);
} else {
ImplColorHsv.rgbToHsv_F32((Planar<GrayF32>)rgb,(Planar<GrayF32>)hsv);
}
} else {
throw new IllegalArgumentException("Unsupported band type "+hsv.getBandType().getSimpleName());
}
} } | public class class_name {
public static <T extends ImageGray<T>>
void rgbToHsv(Planar<T> rgb , Planar<T> hsv ) {
hsv.reshape(rgb.width,rgb.height,3);
if( hsv.getBandType() == GrayF32.class ) {
if(BoofConcurrency.USE_CONCURRENT ) {
ImplColorHsv_MT.rgbToHsv_F32((Planar<GrayF32>)rgb,(Planar<GrayF32>)hsv); // depends on control dependency: [if], data = [none]
} else {
ImplColorHsv.rgbToHsv_F32((Planar<GrayF32>)rgb,(Planar<GrayF32>)hsv); // depends on control dependency: [if], data = [none]
}
} else {
throw new IllegalArgumentException("Unsupported band type "+hsv.getBandType().getSimpleName());
}
} } |
public class class_name {
public static INDArray gt(INDArray x, INDArray y, INDArray z, int... dimensions) {
if(dimensions == null || dimensions.length == 0) {
validateShapesNoDimCase(x,y,z);
return Nd4j.getExecutioner().exec(new OldGreaterThan(x,y,z));
}
return Nd4j.getExecutioner().exec(new BroadcastGreaterThan(x,y,z,dimensions));
} } | public class class_name {
public static INDArray gt(INDArray x, INDArray y, INDArray z, int... dimensions) {
if(dimensions == null || dimensions.length == 0) {
validateShapesNoDimCase(x,y,z); // depends on control dependency: [if], data = [none]
return Nd4j.getExecutioner().exec(new OldGreaterThan(x,y,z)); // depends on control dependency: [if], data = [none]
}
return Nd4j.getExecutioner().exec(new BroadcastGreaterThan(x,y,z,dimensions));
} } |
public class class_name {
public boolean isDisabledModelPageEntry(CmsUUID id) {
boolean result = false;
if (m_modelPageTreeItems.containsKey(id)) {
result = m_modelPageTreeItems.get(id).isDisabled();
} else if (m_parentModelPageTreeItems.containsKey(id)) {
result = m_parentModelPageTreeItems.get(id).isDisabled();
}
return result;
} } | public class class_name {
public boolean isDisabledModelPageEntry(CmsUUID id) {
boolean result = false;
if (m_modelPageTreeItems.containsKey(id)) {
result = m_modelPageTreeItems.get(id).isDisabled(); // depends on control dependency: [if], data = [none]
} else if (m_parentModelPageTreeItems.containsKey(id)) {
result = m_parentModelPageTreeItems.get(id).isDisabled(); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public JandexAssert hasNoFinalFieldsWithJsonbPropertyAnnotation() {
// Precondition
isNotNull();
final RuleJsonbFieldNotFinal rule = new RuleJsonbFieldNotFinal();
final StringBuilder sb = new StringBuilder();
boolean ok = true;
final Collection<ClassInfo> classes = actual.getKnownClasses();
for (final ClassInfo clasz : classes) {
final List<FieldInfo> fields = clasz.fields();
for (final FieldInfo field : fields) {
final AssertionResult result = rule.verify(field);
if (!result.isValid()) {
ok = false;
sb.append(result.getErrorMessage());
}
}
}
if (!ok) {
failWithMessage(
"At least one field has a 'final' modifier and is annotated with '@JsonbProperty' at the same time:\n" + sb.toString());
}
return this;
} } | public class class_name {
public JandexAssert hasNoFinalFieldsWithJsonbPropertyAnnotation() {
// Precondition
isNotNull();
final RuleJsonbFieldNotFinal rule = new RuleJsonbFieldNotFinal();
final StringBuilder sb = new StringBuilder();
boolean ok = true;
final Collection<ClassInfo> classes = actual.getKnownClasses();
for (final ClassInfo clasz : classes) {
final List<FieldInfo> fields = clasz.fields();
for (final FieldInfo field : fields) {
final AssertionResult result = rule.verify(field);
if (!result.isValid()) {
ok = false; // depends on control dependency: [if], data = [none]
sb.append(result.getErrorMessage()); // depends on control dependency: [if], data = [none]
}
}
}
if (!ok) {
failWithMessage(
"At least one field has a 'final' modifier and is annotated with '@JsonbProperty' at the same time:\n" + sb.toString()); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
protected Object buildOrRefreshObject(Map row, ClassDescriptor targetClassDescriptor, Object targetObject)
{
Object result = targetObject;
FieldDescriptor fmd;
FieldDescriptor[] fields = targetClassDescriptor.getFieldDescriptor(true);
if(targetObject == null)
{
// 1. create new object instance if needed
result = ClassHelper.buildNewObjectInstance(targetClassDescriptor);
}
// 2. fill all scalar attributes of the new object
for (int i = 0; i < fields.length; i++)
{
fmd = fields[i];
fmd.getPersistentField().set(result, row.get(fmd.getColumnName()));
}
if(targetObject == null)
{
// 3. for new build objects, invoke the initialization method for the class if one is provided
Method initializationMethod = targetClassDescriptor.getInitializationMethod();
if (initializationMethod != null)
{
try
{
initializationMethod.invoke(result, NO_ARGS);
}
catch (Exception ex)
{
throw new PersistenceBrokerException("Unable to invoke initialization method:" + initializationMethod.getName() + " for class:" + m_cld.getClassOfObject(), ex);
}
}
}
return result;
} } | public class class_name {
protected Object buildOrRefreshObject(Map row, ClassDescriptor targetClassDescriptor, Object targetObject)
{
Object result = targetObject;
FieldDescriptor fmd;
FieldDescriptor[] fields = targetClassDescriptor.getFieldDescriptor(true);
if(targetObject == null)
{
// 1. create new object instance if needed
result = ClassHelper.buildNewObjectInstance(targetClassDescriptor);
// depends on control dependency: [if], data = [none]
}
// 2. fill all scalar attributes of the new object
for (int i = 0; i < fields.length; i++)
{
fmd = fields[i];
// depends on control dependency: [for], data = [i]
fmd.getPersistentField().set(result, row.get(fmd.getColumnName()));
// depends on control dependency: [for], data = [none]
}
if(targetObject == null)
{
// 3. for new build objects, invoke the initialization method for the class if one is provided
Method initializationMethod = targetClassDescriptor.getInitializationMethod();
if (initializationMethod != null)
{
try
{
initializationMethod.invoke(result, NO_ARGS);
// depends on control dependency: [try], data = [none]
}
catch (Exception ex)
{
throw new PersistenceBrokerException("Unable to invoke initialization method:" + initializationMethod.getName() + " for class:" + m_cld.getClassOfObject(), ex);
}
// depends on control dependency: [catch], data = [none]
}
}
return result;
} } |
public class class_name {
private PorterDuffColorFilter createTintFilter(ColorStateList tint, PorterDuff.Mode tintMode) {
if (tint == null || tintMode == null) {
return null;
}
final int color = tint.getColorForState(getState(), Color.TRANSPARENT);
return new PorterDuffColorFilter(color, tintMode);
} } | public class class_name {
private PorterDuffColorFilter createTintFilter(ColorStateList tint, PorterDuff.Mode tintMode) {
if (tint == null || tintMode == null) {
return null; // depends on control dependency: [if], data = [none]
}
final int color = tint.getColorForState(getState(), Color.TRANSPARENT);
return new PorterDuffColorFilter(color, tintMode);
} } |
public class class_name {
public String getStringValue() {
if (value == null) {
return null;
}
if (value.contains("`")) {
return value.replaceAll("\\\\`", "`");
}
return value;
} } | public class class_name {
public String getStringValue() {
if (value == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (value.contains("`")) {
return value.replaceAll("\\\\`", "`"); // depends on control dependency: [if], data = [none]
}
return value;
} } |
public class class_name {
public void addInstance(String src,String id,String text)
{
Instance inst = new Instance(src,id,text);
ArrayList list = (ArrayList)sourceLists.get(src);
if (list==null) {
list = new ArrayList();
sourceLists.put(src,list);
sourceNames.add(src);
}
list.add(inst);
} } | public class class_name {
public void addInstance(String src,String id,String text)
{
Instance inst = new Instance(src,id,text);
ArrayList list = (ArrayList)sourceLists.get(src);
if (list==null) {
list = new ArrayList(); // depends on control dependency: [if], data = [none]
sourceLists.put(src,list); // depends on control dependency: [if], data = [none]
sourceNames.add(src); // depends on control dependency: [if], data = [none]
}
list.add(inst);
} } |
public class class_name {
public void setChildrenFollowInput(final boolean follow) {
if (follow != mChildrenFollowInput) {
mChildrenFollowInput = follow;
for (Widget child : getChildren()) {
child.registerPickable();
}
}
} } | public class class_name {
public void setChildrenFollowInput(final boolean follow) {
if (follow != mChildrenFollowInput) {
mChildrenFollowInput = follow; // depends on control dependency: [if], data = [none]
for (Widget child : getChildren()) {
child.registerPickable(); // depends on control dependency: [for], data = [child]
}
}
} } |
public class class_name {
private void processSecurityRoles(List<SecurityRole> securityRoles) {
for (SecurityRole securityRole : securityRoles) {
if (!allRoles.contains(securityRole.getRoleName())) {
allRoles.add(securityRole.getRoleName());
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "allRoles: " + allRoles);
}
} } | public class class_name {
private void processSecurityRoles(List<SecurityRole> securityRoles) {
for (SecurityRole securityRole : securityRoles) {
if (!allRoles.contains(securityRole.getRoleName())) {
allRoles.add(securityRole.getRoleName()); // depends on control dependency: [if], data = [none]
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "allRoles: " + allRoles); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final Parser<WithSource<T>> withSource() {
return new Parser<WithSource<T>>() {
@Override boolean apply(ParseContext ctxt) {
int begin = ctxt.getIndex();
if (!Parser.this.apply(ctxt)) {
return false;
}
String source = ctxt.source.subSequence(begin, ctxt.getIndex()).toString();
@SuppressWarnings("unchecked")
WithSource<T> withSource = new WithSource<T>((T) ctxt.result, source);
ctxt.result = withSource;
return true;
}
@Override public String toString() {
return Parser.this.toString();
}
};
} } | public class class_name {
public final Parser<WithSource<T>> withSource() {
return new Parser<WithSource<T>>() {
@Override boolean apply(ParseContext ctxt) {
int begin = ctxt.getIndex();
if (!Parser.this.apply(ctxt)) {
return false; // depends on control dependency: [if], data = [none]
}
String source = ctxt.source.subSequence(begin, ctxt.getIndex()).toString();
@SuppressWarnings("unchecked")
WithSource<T> withSource = new WithSource<T>((T) ctxt.result, source);
ctxt.result = withSource;
return true;
}
@Override public String toString() {
return Parser.this.toString();
}
};
} } |
public class class_name {
public V putIfAbsent(@NonNull K key, @NonNull V v) {
Entry<K, V> entry = get(key);
if (entry != null) {
return entry.mValue;
}
put(key, v);
return null;
} } | public class class_name {
public V putIfAbsent(@NonNull K key, @NonNull V v) {
Entry<K, V> entry = get(key);
if (entry != null) {
return entry.mValue; // depends on control dependency: [if], data = [none]
}
put(key, v);
return null;
} } |
public class class_name {
@Beta
public static <T> java.util.Optional<T> findLast(Stream<T> stream) {
class OptionalState {
boolean set = false;
T value = null;
void set(@Nullable T value) {
this.set = true;
this.value = value;
}
T get() {
checkState(set);
return value;
}
}
OptionalState state = new OptionalState();
Deque<Spliterator<T>> splits = new ArrayDeque<>();
splits.addLast(stream.spliterator());
while (!splits.isEmpty()) {
Spliterator<T> spliterator = splits.removeLast();
if (spliterator.getExactSizeIfKnown() == 0) {
continue; // drop this split
}
// Many spliterators will have trySplits that are SUBSIZED even if they are not themselves
// SUBSIZED.
if (spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
// we can drill down to exactly the smallest nonempty spliterator
while (true) {
Spliterator<T> prefix = spliterator.trySplit();
if (prefix == null || prefix.getExactSizeIfKnown() == 0) {
break;
} else if (spliterator.getExactSizeIfKnown() == 0) {
spliterator = prefix;
break;
}
}
// spliterator is known to be nonempty now
spliterator.forEachRemaining(state::set);
return java.util.Optional.of(state.get());
}
Spliterator<T> prefix = spliterator.trySplit();
if (prefix == null || prefix.getExactSizeIfKnown() == 0) {
// we can't split this any further
spliterator.forEachRemaining(state::set);
if (state.set) {
return java.util.Optional.of(state.get());
}
// fall back to the last split
continue;
}
splits.addLast(prefix);
splits.addLast(spliterator);
}
return java.util.Optional.empty();
} } | public class class_name {
@Beta
public static <T> java.util.Optional<T> findLast(Stream<T> stream) {
class OptionalState {
boolean set = false;
T value = null;
void set(@Nullable T value) {
this.set = true;
this.value = value;
}
T get() {
checkState(set);
return value;
}
}
OptionalState state = new OptionalState();
Deque<Spliterator<T>> splits = new ArrayDeque<>();
splits.addLast(stream.spliterator());
while (!splits.isEmpty()) {
Spliterator<T> spliterator = splits.removeLast();
if (spliterator.getExactSizeIfKnown() == 0) {
continue; // drop this split
}
// Many spliterators will have trySplits that are SUBSIZED even if they are not themselves
// SUBSIZED.
if (spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
// we can drill down to exactly the smallest nonempty spliterator
while (true) {
Spliterator<T> prefix = spliterator.trySplit();
if (prefix == null || prefix.getExactSizeIfKnown() == 0) {
break;
} else if (spliterator.getExactSizeIfKnown() == 0) {
spliterator = prefix; // depends on control dependency: [if], data = [none]
break;
}
}
// spliterator is known to be nonempty now
spliterator.forEachRemaining(state::set); // depends on control dependency: [if], data = [none]
return java.util.Optional.of(state.get()); // depends on control dependency: [if], data = [none]
}
Spliterator<T> prefix = spliterator.trySplit();
if (prefix == null || prefix.getExactSizeIfKnown() == 0) {
// we can't split this any further
spliterator.forEachRemaining(state::set); // depends on control dependency: [if], data = [none]
if (state.set) {
return java.util.Optional.of(state.get()); // depends on control dependency: [if], data = [none]
}
// fall back to the last split
continue;
}
splits.addLast(prefix); // depends on control dependency: [while], data = [none]
splits.addLast(spliterator); // depends on control dependency: [while], data = [none]
}
return java.util.Optional.empty();
} } |
public class class_name {
@Override
public Result<Void> updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) {
TimeTaken tt = trans.start(NS_UPDATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS);
try {
Result<?> rp = service.updateNsAttrib(trans,ns,key,value);
switch(rp.status) {
case OK:
setContentType(resp, keysDF.getOutType());
resp.getOutputStream().println();
return Result.ok();
default:
return Result.err(rp);
}
} catch (Exception e) {
trans.error().log(e,IN,NS_UPDATE_ATTRIB);
return Result.err(e);
} finally {
tt.done();
}
} } | public class class_name {
@Override
public Result<Void> updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) {
TimeTaken tt = trans.start(NS_UPDATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS);
try {
Result<?> rp = service.updateNsAttrib(trans,ns,key,value);
switch(rp.status) {
case OK:
setContentType(resp, keysDF.getOutType());
resp.getOutputStream().println();
return Result.ok();
default:
return Result.err(rp);
}
} catch (Exception e) {
trans.error().log(e,IN,NS_UPDATE_ATTRIB);
return Result.err(e);
} finally {
// depends on control dependency: [catch], data = [none]
tt.done();
}
} } |
public class class_name {
private static void loadDefaultConverters() {
TYPE_CONVERTERS.put(byte.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
return (value == null || value.equals(EMPTY_STRING) ? new Byte((byte)0) : new Byte(value.trim()));
}
});
TYPE_CONVERTERS.put(Byte.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, byte.class, null);
}
});
TYPE_CONVERTERS.put(boolean.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return Boolean.FALSE;
value = value.toLowerCase().trim();
if(value.equals("on") || value.equals("true"))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
});
TYPE_CONVERTERS.put(Boolean.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, boolean.class, null);
}
});
TYPE_CONVERTERS.put(char.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Character('\u0000');
else
return new Character(value.charAt(0));
}
});
TYPE_CONVERTERS.put(Character.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, char.class, null);
}
});
TYPE_CONVERTERS.put(double.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Double(0.0);
else
return new Double(value.trim());
}
});
TYPE_CONVERTERS.put(Double.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, double.class, null);
}
});
TYPE_CONVERTERS.put(float.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Float(0.0);
else
return new Float(value.trim());
}
});
TYPE_CONVERTERS.put(Float.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, float.class, null);
}
});
TYPE_CONVERTERS.put(int.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Integer(0);
else
return new Integer(value.trim());
}
});
TYPE_CONVERTERS.put(Integer.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, int.class, null);
}
});
TYPE_CONVERTERS.put(long.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Long(0);
else
return new Long(value.trim());
}
});
TYPE_CONVERTERS.put(Long.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, long.class, null);
}
});
TYPE_CONVERTERS.put(short.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Short((short)0);
else
return new Short(value.trim());
}
});
TYPE_CONVERTERS.put(Short.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, short.class, null);
}
});
TYPE_CONVERTERS.put(String.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null)
return null;
else
return value;
}
});
TYPE_CONVERTERS.put(java.math.BigDecimal.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return new BigDecimal(value.trim());
}
});
TYPE_CONVERTERS.put(java.math.BigInteger.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return new BigInteger(value.trim());
}
});
TYPE_CONVERTERS.put(byte[].class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return value.getBytes();
}
});
TYPE_CONVERTERS.put(Byte[].class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else {
byte[] bytes = value.getBytes();
Byte[] wBytes = new Byte[bytes.length];
for(int i = 0; i < bytes.length; i++)
wBytes[i] = new Byte(bytes[i]);
return wBytes;
}
}
});
TYPE_CONVERTERS.put(Date.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
try {
if(locale == null)
locale = Locale.getDefault();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
return df.parse(value);
} catch(java.text.ParseException pe) {
String msg = "Caugnt an error converting a String to a DateFormat.SHORT formatted Date";
LOGGER.warn(msg, pe);
TypeConversionException tce = new TypeConversionException(msg, pe);
tce.setLocalizedMessage(Bundle.getString("TypeUtils_javaUtilDateConvertError", new Object[]{pe.getMessage()}));
throw tce;
}
}
});
/* http://java.sun.com/j2se/1.4.1/docs/api/java/sql/Date.html */
TYPE_CONVERTERS.put(java.sql.Date.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING)) return null;
try {
return java.sql.Date.valueOf(value);
} catch(Exception e) {
String msg = "Caught an error converting a String to a java.sql.Date";
LOGGER.error(msg, e);
TypeConversionException tce = new TypeConversionException(msg, e);
tce.setLocalizedMessage(Bundle.getString("TypeUtils_javaSqlDateConvertError", new Object[]{e.getMessage()}));
throw tce;
}
}
});
/* http://java.sun.com/j2se/1.4.1/docs/api/java/sql/Timestamp.html */
TYPE_CONVERTERS.put(java.sql.Timestamp.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
try {
return java.sql.Timestamp.valueOf(value);
} catch(Exception e) {
String msg = "Caught an error converting a String to a java.sql.Timestamp";
LOGGER.error(msg, e);
TypeConversionException tce = new TypeConversionException(msg, e);
tce.setLocalizedMessage(Bundle.getString("TypeUtils_javaSqlTimestampConvertError", new Object[]{e.getMessage()}));
throw tce;
}
}
});
/* http://java.sun.com/j2se/1.4.1/docs/api/java/sql/Time.html */
TYPE_CONVERTERS.put(java.sql.Time.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
try {
return java.sql.Time.valueOf(value);
} catch(Exception e) {
String msg = "Caught an error converting a String to a java.sql.Time";
LOGGER.error(msg, e);
TypeConversionException tce = new TypeConversionException(msg, e);
tce.setLocalizedMessage(Bundle.getString("TypeUtils_javaSqlTimeConvertError", new Object[]{e.getMessage()}));
throw tce;
}
}
});
} } | public class class_name {
private static void loadDefaultConverters() {
TYPE_CONVERTERS.put(byte.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
return (value == null || value.equals(EMPTY_STRING) ? new Byte((byte)0) : new Byte(value.trim()));
}
});
TYPE_CONVERTERS.put(Byte.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, byte.class, null);
}
});
TYPE_CONVERTERS.put(boolean.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return Boolean.FALSE;
value = value.toLowerCase().trim();
if(value.equals("on") || value.equals("true"))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
});
TYPE_CONVERTERS.put(Boolean.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, boolean.class, null);
}
});
TYPE_CONVERTERS.put(char.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Character('\u0000');
else
return new Character(value.charAt(0));
}
});
TYPE_CONVERTERS.put(Character.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, char.class, null);
}
});
TYPE_CONVERTERS.put(double.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Double(0.0);
else
return new Double(value.trim());
}
});
TYPE_CONVERTERS.put(Double.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, double.class, null);
}
});
TYPE_CONVERTERS.put(float.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Float(0.0);
else
return new Float(value.trim());
}
});
TYPE_CONVERTERS.put(Float.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, float.class, null);
}
});
TYPE_CONVERTERS.put(int.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Integer(0);
else
return new Integer(value.trim());
}
});
TYPE_CONVERTERS.put(Integer.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, int.class, null);
}
});
TYPE_CONVERTERS.put(long.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Long(0);
else
return new Long(value.trim());
}
});
TYPE_CONVERTERS.put(Long.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, long.class, null);
}
});
TYPE_CONVERTERS.put(short.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return new Short((short)0);
else
return new Short(value.trim());
}
});
TYPE_CONVERTERS.put(Short.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return TypeUtils.convertToObject(value, short.class, null);
}
});
TYPE_CONVERTERS.put(String.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null)
return null;
else
return value;
}
});
TYPE_CONVERTERS.put(java.math.BigDecimal.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return new BigDecimal(value.trim());
}
});
TYPE_CONVERTERS.put(java.math.BigInteger.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return new BigInteger(value.trim());
}
});
TYPE_CONVERTERS.put(byte[].class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else
return value.getBytes();
}
});
TYPE_CONVERTERS.put(Byte[].class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
else {
byte[] bytes = value.getBytes();
Byte[] wBytes = new Byte[bytes.length];
for(int i = 0; i < bytes.length; i++)
wBytes[i] = new Byte(bytes[i]);
return wBytes; // depends on control dependency: [if], data = [none]
}
}
});
TYPE_CONVERTERS.put(Date.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
try {
if(locale == null)
locale = Locale.getDefault();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
return df.parse(value); // depends on control dependency: [try], data = [none]
} catch(java.text.ParseException pe) {
String msg = "Caugnt an error converting a String to a DateFormat.SHORT formatted Date";
LOGGER.warn(msg, pe);
TypeConversionException tce = new TypeConversionException(msg, pe);
tce.setLocalizedMessage(Bundle.getString("TypeUtils_javaUtilDateConvertError", new Object[]{pe.getMessage()}));
throw tce;
} // depends on control dependency: [catch], data = [none]
}
});
/* http://java.sun.com/j2se/1.4.1/docs/api/java/sql/Date.html */
TYPE_CONVERTERS.put(java.sql.Date.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING)) return null;
try {
return java.sql.Date.valueOf(value); // depends on control dependency: [try], data = [none]
} catch(Exception e) {
String msg = "Caught an error converting a String to a java.sql.Date";
LOGGER.error(msg, e);
TypeConversionException tce = new TypeConversionException(msg, e);
tce.setLocalizedMessage(Bundle.getString("TypeUtils_javaSqlDateConvertError", new Object[]{e.getMessage()}));
throw tce;
} // depends on control dependency: [catch], data = [none]
}
});
/* http://java.sun.com/j2se/1.4.1/docs/api/java/sql/Timestamp.html */
TYPE_CONVERTERS.put(java.sql.Timestamp.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
try {
return java.sql.Timestamp.valueOf(value); // depends on control dependency: [try], data = [none]
} catch(Exception e) {
String msg = "Caught an error converting a String to a java.sql.Timestamp";
LOGGER.error(msg, e);
TypeConversionException tce = new TypeConversionException(msg, e);
tce.setLocalizedMessage(Bundle.getString("TypeUtils_javaSqlTimestampConvertError", new Object[]{e.getMessage()}));
throw tce;
} // depends on control dependency: [catch], data = [none]
}
});
/* http://java.sun.com/j2se/1.4.1/docs/api/java/sql/Time.html */
TYPE_CONVERTERS.put(java.sql.Time.class, new BaseTypeConverter() {
public Object convertToObject(Class type, String value, Locale locale) {
if(value == null || value.equals(EMPTY_STRING))
return null;
try {
return java.sql.Time.valueOf(value); // depends on control dependency: [try], data = [none]
} catch(Exception e) {
String msg = "Caught an error converting a String to a java.sql.Time";
LOGGER.error(msg, e);
TypeConversionException tce = new TypeConversionException(msg, e);
tce.setLocalizedMessage(Bundle.getString("TypeUtils_javaSqlTimeConvertError", new Object[]{e.getMessage()}));
throw tce;
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
protected int[] toHyphenationPoints() {
int internalOffset = this.offset + 1;
int hyphenationCount = 0;
for (int i = 0; i < this.rankings.length; i++) {
if ((this.rankings[i] & 1) == 1) {
// odd ranking --> hyphenation...
hyphenationCount++;
}
}
int[] hyphenationPoints = new int[hyphenationCount];
hyphenationCount = 0;
for (int i = 0; i < this.rankings.length; i++) {
if ((this.rankings[i] & 1) == 1) {
// odd ranking --> hyphenation...
hyphenationPoints[hyphenationCount] = internalOffset + i;
hyphenationCount++;
}
}
return hyphenationPoints;
} } | public class class_name {
protected int[] toHyphenationPoints() {
int internalOffset = this.offset + 1;
int hyphenationCount = 0;
for (int i = 0; i < this.rankings.length; i++) {
if ((this.rankings[i] & 1) == 1) {
// odd ranking --> hyphenation...
hyphenationCount++;
// depends on control dependency: [if], data = [none]
}
}
int[] hyphenationPoints = new int[hyphenationCount];
hyphenationCount = 0;
for (int i = 0; i < this.rankings.length; i++) {
if ((this.rankings[i] & 1) == 1) {
// odd ranking --> hyphenation...
hyphenationPoints[hyphenationCount] = internalOffset + i;
// depends on control dependency: [if], data = [none]
hyphenationCount++;
// depends on control dependency: [if], data = [none]
}
}
return hyphenationPoints;
} } |
public class class_name {
public void parseAndExecuteCommand() {
CommandLineParser parser = new DefaultParser();
try {
CommandLine parsedOpts = parser.parse(this.options, this.args, true);
GlobalOptions globalOptions = createGlobalOptions(parsedOpts);
// Fetch the command and fail if there is ambiguity
String[] remainingArgs = parsedOpts.getArgs();
if (remainingArgs.length == 0) {
printHelpAndExit("Command not specified!");
}
String commandName = remainingArgs[0].toLowerCase();
remainingArgs = remainingArgs.length > 1 ?
Arrays.copyOfRange(remainingArgs, 1, remainingArgs.length) :
new String[]{};
Command command = commandList.get(commandName);
if (command == null) {
System.out.println("Command " + commandName + " not known.");
printHelpAndExit();
} else {
command.execute(globalOptions, remainingArgs);
}
} catch (ParseException e) {
printHelpAndExit("Ran into an error parsing args.");
}
} } | public class class_name {
public void parseAndExecuteCommand() {
CommandLineParser parser = new DefaultParser();
try {
CommandLine parsedOpts = parser.parse(this.options, this.args, true);
GlobalOptions globalOptions = createGlobalOptions(parsedOpts);
// Fetch the command and fail if there is ambiguity
String[] remainingArgs = parsedOpts.getArgs();
if (remainingArgs.length == 0) {
printHelpAndExit("Command not specified!"); // depends on control dependency: [if], data = [none]
}
String commandName = remainingArgs[0].toLowerCase();
remainingArgs = remainingArgs.length > 1 ?
Arrays.copyOfRange(remainingArgs, 1, remainingArgs.length) :
new String[]{}; // depends on control dependency: [try], data = [none]
Command command = commandList.get(commandName);
if (command == null) {
System.out.println("Command " + commandName + " not known."); // depends on control dependency: [if], data = [none]
printHelpAndExit(); // depends on control dependency: [if], data = [none]
} else {
command.execute(globalOptions, remainingArgs); // depends on control dependency: [if], data = [none]
}
} catch (ParseException e) {
printHelpAndExit("Ran into an error parsing args.");
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static boolean deleteMMapGraph(String path) {
String directory = ensureDirectory(path);
File f = new File(directory);
boolean ok = true;
if (f.exists()) {
ok = new File(directory + "nodes.mmap").delete();
ok = new File(directory + "edges.mmap").delete() && ok;
ok = new File(directory + "treeMap.mmap").delete() && ok;
ok = f.delete() && ok;
}
return ok;
} } | public class class_name {
public static boolean deleteMMapGraph(String path) {
String directory = ensureDirectory(path);
File f = new File(directory);
boolean ok = true;
if (f.exists()) {
ok = new File(directory + "nodes.mmap").delete();
ok = new File(directory + "edges.mmap").delete() && ok; // depends on control dependency: [if], data = [none]
ok = new File(directory + "treeMap.mmap").delete() && ok; // depends on control dependency: [if], data = [none]
ok = f.delete() && ok; // depends on control dependency: [if], data = [none]
}
return ok;
} } |
public class class_name {
public static boolean contextIsCompatible(InstancesHeader originalContext,
InstancesHeader newContext) {
if (newContext.numClasses() < originalContext.numClasses()) {
return false; // rule 1
}
if (newContext.numAttributes() < originalContext.numAttributes()) {
return false; // rule 2
}
int oPos = 0;
int nPos = 0;
while (oPos < originalContext.numAttributes()) {
if (oPos == originalContext.classIndex()) {
oPos++;
if (!(oPos < originalContext.numAttributes())) {
break;
}
}
if (nPos == newContext.classIndex()) {
nPos++;
}
if (originalContext.attribute(oPos).isNominal()) {
if (!newContext.attribute(nPos).isNominal()) {
return false; // rule 4
}
if (newContext.attribute(nPos).numValues() < originalContext.attribute(oPos).numValues()) {
return false; // rule 3
}
} else {
assert (originalContext.attribute(oPos).isNumeric());
if (!newContext.attribute(nPos).isNumeric()) {
return false; // rule 4
}
}
oPos++;
nPos++;
}
return true; // all checks clear
} } | public class class_name {
public static boolean contextIsCompatible(InstancesHeader originalContext,
InstancesHeader newContext) {
if (newContext.numClasses() < originalContext.numClasses()) {
return false; // rule 1 // depends on control dependency: [if], data = [none]
}
if (newContext.numAttributes() < originalContext.numAttributes()) {
return false; // rule 2 // depends on control dependency: [if], data = [none]
}
int oPos = 0;
int nPos = 0;
while (oPos < originalContext.numAttributes()) {
if (oPos == originalContext.classIndex()) {
oPos++; // depends on control dependency: [if], data = [none]
if (!(oPos < originalContext.numAttributes())) {
break;
}
}
if (nPos == newContext.classIndex()) {
nPos++; // depends on control dependency: [if], data = [none]
}
if (originalContext.attribute(oPos).isNominal()) {
if (!newContext.attribute(nPos).isNominal()) {
return false; // rule 4 // depends on control dependency: [if], data = [none]
}
if (newContext.attribute(nPos).numValues() < originalContext.attribute(oPos).numValues()) {
return false; // rule 3 // depends on control dependency: [if], data = [none]
}
} else {
assert (originalContext.attribute(oPos).isNumeric()); // depends on control dependency: [if], data = [none]
if (!newContext.attribute(nPos).isNumeric()) {
return false; // rule 4 // depends on control dependency: [if], data = [none]
}
}
oPos++; // depends on control dependency: [while], data = [none]
nPos++; // depends on control dependency: [while], data = [none]
}
return true; // all checks clear
} } |
public class class_name {
public void ifPresentOrElse(@NotNull IntConsumer consumer, @NotNull Runnable emptyAction) {
if (isPresent) {
consumer.accept(value);
} else {
emptyAction.run();
}
} } | public class class_name {
public void ifPresentOrElse(@NotNull IntConsumer consumer, @NotNull Runnable emptyAction) {
if (isPresent) {
consumer.accept(value); // depends on control dependency: [if], data = [none]
} else {
emptyAction.run(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setDimensions(String dimString) {
if (immutable) throw new IllegalStateException("Cant modify");
try {
setDimensions(Dimension.makeDimensionsList(getParentGroup(), dimString));
//this.dimensions = Dimension.makeDimensionsList(getParentGroup(), dimString);
resetShape();
} catch (IllegalStateException e) {
throw new IllegalArgumentException("Variable " + getFullName() + " setDimensions = '" + dimString +
"' FAILED: " + e.getMessage() + " file = " + getDatasetLocation());
}
} } | public class class_name {
public void setDimensions(String dimString) {
if (immutable) throw new IllegalStateException("Cant modify");
try {
setDimensions(Dimension.makeDimensionsList(getParentGroup(), dimString)); // depends on control dependency: [try], data = [none]
//this.dimensions = Dimension.makeDimensionsList(getParentGroup(), dimString);
resetShape(); // depends on control dependency: [try], data = [none]
} catch (IllegalStateException e) {
throw new IllegalArgumentException("Variable " + getFullName() + " setDimensions = '" + dimString +
"' FAILED: " + e.getMessage() + " file = " + getDatasetLocation());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void assignCoordinateSystemsExplicit(NetcdfDataset ncDataset) {
// look for explicit references to coord sys variables
for (VarProcess vp : varList) {
if (vp.coordSys != null && !vp.isCoordinateTransform) {
StringTokenizer stoker = new StringTokenizer(vp.coordSys);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap == null) {
parseInfo.format("***Cant find Coordinate System variable %s referenced from var= %s%n", vname, vp.v.getFullName());
userAdvice.format("***Cant find Coordinate System variable %s referenced from var= %s%n", vname, vp.v.getFullName());
continue;
}
if (ap.cs == null) {
parseInfo.format("***Not a Coordinate System variable %s referenced from var= %s%n", vname, vp.v.getFullName());
userAdvice.format("***Not a Coordinate System variable %s referenced from var= %s%n", vname, vp.v.getFullName());
continue;
}
VariableEnhanced ve = (VariableEnhanced) vp.v;
ve.addCoordinateSystem(ap.cs);
}
}
}
// look for explicit references from coord sys variables to data variables
for (VarProcess csVar : varList) {
if (!csVar.isCoordinateSystem || (csVar.coordSysFor == null))
continue;
// get list of dimensions from '_CoordinateSystemFor' attribute
List<Dimension> dimList = new ArrayList<>(6);
StringTokenizer stoker = new StringTokenizer(csVar.coordSysFor);
while (stoker.hasMoreTokens()) {
String dname = stoker.nextToken();
Dimension dim = ncDataset.getRootGroup().findDimension(dname);
if (dim == null) {
parseInfo.format("***Cant find Dimension %s referenced from CoordSys var= %s%n", dname, csVar.v.getFullName());
userAdvice.format("***Cant find Dimension %s referenced from CoordSys var= %s%n", dname, csVar.v.getFullName());
} else
dimList.add(dim);
}
// look for vars with those dimensions
for (VarProcess vp : varList) {
if (!vp.hasCoordinateSystem() && vp.isData() && (csVar.cs != null)) {
VariableEnhanced ve = (VariableEnhanced) vp.v;
if (CoordinateSystem.isSubset(dimList, vp.v.getDimensionsAll()) && CoordinateSystem.isSubset(vp.v.getDimensionsAll(), dimList))
ve.addCoordinateSystem(csVar.cs);
}
}
}
// look for explicit listings of coordinate axes
for (VarProcess vp : varList) {
VariableEnhanced ve = (VariableEnhanced) vp.v;
if (!vp.hasCoordinateSystem() && (vp.coordAxes != null) && vp.isData()) {
List<CoordinateAxis> dataAxesList = getAxes(vp, vp.coordAxes, vp.v.getFullName());
if (dataAxesList.size() > 1) {
String coordSysName = CoordinateSystem.makeName(dataAxesList);
CoordinateSystem cs = ncDataset.findCoordinateSystem(coordSysName);
if (cs != null) {
ve.addCoordinateSystem(cs);
parseInfo.format(" assigned explicit CoordSystem '%s' for var= %s%n", cs.getName(), vp.v.getFullName());
} else {
CoordinateSystem csnew = new CoordinateSystem(ncDataset, dataAxesList, null);
ve.addCoordinateSystem(csnew);
ncDataset.addCoordinateSystem(csnew);
parseInfo.format(" created explicit CoordSystem '%s' for var= %s%n", csnew.getName(), vp.v.getFullName());
}
}
}
}
} } | public class class_name {
protected void assignCoordinateSystemsExplicit(NetcdfDataset ncDataset) {
// look for explicit references to coord sys variables
for (VarProcess vp : varList) {
if (vp.coordSys != null && !vp.isCoordinateTransform) {
StringTokenizer stoker = new StringTokenizer(vp.coordSys);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap == null) {
parseInfo.format("***Cant find Coordinate System variable %s referenced from var= %s%n", vname, vp.v.getFullName());
// depends on control dependency: [if], data = [none]
userAdvice.format("***Cant find Coordinate System variable %s referenced from var= %s%n", vname, vp.v.getFullName());
// depends on control dependency: [if], data = [none]
continue;
}
if (ap.cs == null) {
parseInfo.format("***Not a Coordinate System variable %s referenced from var= %s%n", vname, vp.v.getFullName());
// depends on control dependency: [if], data = [none]
userAdvice.format("***Not a Coordinate System variable %s referenced from var= %s%n", vname, vp.v.getFullName());
// depends on control dependency: [if], data = [none]
continue;
}
VariableEnhanced ve = (VariableEnhanced) vp.v;
ve.addCoordinateSystem(ap.cs);
// depends on control dependency: [while], data = [none]
}
}
}
// look for explicit references from coord sys variables to data variables
for (VarProcess csVar : varList) {
if (!csVar.isCoordinateSystem || (csVar.coordSysFor == null))
continue;
// get list of dimensions from '_CoordinateSystemFor' attribute
List<Dimension> dimList = new ArrayList<>(6);
StringTokenizer stoker = new StringTokenizer(csVar.coordSysFor);
while (stoker.hasMoreTokens()) {
String dname = stoker.nextToken();
Dimension dim = ncDataset.getRootGroup().findDimension(dname);
if (dim == null) {
parseInfo.format("***Cant find Dimension %s referenced from CoordSys var= %s%n", dname, csVar.v.getFullName());
// depends on control dependency: [if], data = [none]
userAdvice.format("***Cant find Dimension %s referenced from CoordSys var= %s%n", dname, csVar.v.getFullName());
// depends on control dependency: [if], data = [none]
} else
dimList.add(dim);
}
// look for vars with those dimensions
for (VarProcess vp : varList) {
if (!vp.hasCoordinateSystem() && vp.isData() && (csVar.cs != null)) {
VariableEnhanced ve = (VariableEnhanced) vp.v;
if (CoordinateSystem.isSubset(dimList, vp.v.getDimensionsAll()) && CoordinateSystem.isSubset(vp.v.getDimensionsAll(), dimList))
ve.addCoordinateSystem(csVar.cs);
}
}
}
// look for explicit listings of coordinate axes
for (VarProcess vp : varList) {
VariableEnhanced ve = (VariableEnhanced) vp.v;
if (!vp.hasCoordinateSystem() && (vp.coordAxes != null) && vp.isData()) {
List<CoordinateAxis> dataAxesList = getAxes(vp, vp.coordAxes, vp.v.getFullName());
if (dataAxesList.size() > 1) {
String coordSysName = CoordinateSystem.makeName(dataAxesList);
CoordinateSystem cs = ncDataset.findCoordinateSystem(coordSysName);
if (cs != null) {
ve.addCoordinateSystem(cs);
// depends on control dependency: [if], data = [(cs]
parseInfo.format(" assigned explicit CoordSystem '%s' for var= %s%n", cs.getName(), vp.v.getFullName());
// depends on control dependency: [if], data = [none]
} else {
CoordinateSystem csnew = new CoordinateSystem(ncDataset, dataAxesList, null);
ve.addCoordinateSystem(csnew);
// depends on control dependency: [if], data = [(cs]
ncDataset.addCoordinateSystem(csnew);
// depends on control dependency: [if], data = [(cs]
parseInfo.format(" created explicit CoordSystem '%s' for var= %s%n", csnew.getName(), vp.v.getFullName());
// depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
public synchronized Object remove(String key) {
Object retVal;
retVal = primaryTable.remove(key);
if (retVal == null) {
retVal = secondaryTable.remove(key);
if (retVal == null) {
return tertiaryTable.remove(key);
}
}
return retVal;
} } | public class class_name {
public synchronized Object remove(String key) {
Object retVal;
retVal = primaryTable.remove(key);
if (retVal == null) {
retVal = secondaryTable.remove(key); // depends on control dependency: [if], data = [none]
if (retVal == null) {
return tertiaryTable.remove(key); // depends on control dependency: [if], data = [none]
}
}
return retVal;
} } |
public class class_name {
public static boolean containsIgnoreCase(CharSequence sequence, CharSequence subSequence) {
// Calling length() is the null pointer check (so do it before we can exit early).
int length = sequence.length();
if (sequence == subSequence) {
return true;
}
// if subSequence is longer than sequence, it is impossible for sequence to contain subSequence
if (subSequence.length() > length) {
return false;
}
return indexOfIgnoreCase(sequence, subSequence) > -1;
} } | public class class_name {
public static boolean containsIgnoreCase(CharSequence sequence, CharSequence subSequence) {
// Calling length() is the null pointer check (so do it before we can exit early).
int length = sequence.length();
if (sequence == subSequence) {
return true; // depends on control dependency: [if], data = [none]
}
// if subSequence is longer than sequence, it is impossible for sequence to contain subSequence
if (subSequence.length() > length) {
return false; // depends on control dependency: [if], data = [none]
}
return indexOfIgnoreCase(sequence, subSequence) > -1;
} } |
public class class_name {
public void marshall(ListIndicesRequest listIndicesRequest, ProtocolMarshaller protocolMarshaller) {
if (listIndicesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listIndicesRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listIndicesRequest.getMaxResults(), MAXRESULTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListIndicesRequest listIndicesRequest, ProtocolMarshaller protocolMarshaller) {
if (listIndicesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listIndicesRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listIndicesRequest.getMaxResults(), MAXRESULTS_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 {
protected void demoteSeverity(ValidationPlanResult planResult,
Severity maxSeverity) {
if (Severity.ERROR.equals(maxSeverity)) {
return;
}
for (ValidationMessage<?> message : planResult.getMessages()) {
switch (message.getSeverity()) {
case ERROR:
message.setSeverity(maxSeverity);
break;
case WARNING:
message.setSeverity(maxSeverity);
break;
}
}
} } | public class class_name {
protected void demoteSeverity(ValidationPlanResult planResult,
Severity maxSeverity) {
if (Severity.ERROR.equals(maxSeverity)) {
return; // depends on control dependency: [if], data = [none]
}
for (ValidationMessage<?> message : planResult.getMessages()) {
switch (message.getSeverity()) {
case ERROR:
message.setSeverity(maxSeverity);
break;
case WARNING:
message.setSeverity(maxSeverity);
break;
}
}
} } |
public class class_name {
@Override
public INDArray read(Kryo kryo, Input input, Class<INDArray> type) {
DataInputStream dis = new DataInputStream(input);
try {
return Nd4j.read(dis);
} catch (IOException e) {
throw new RuntimeException(e);
}
//Note: input should NOT be closed manually here - may be needed elsewhere (and closing here will cause serialization to fail)
} } | public class class_name {
@Override
public INDArray read(Kryo kryo, Input input, Class<INDArray> type) {
DataInputStream dis = new DataInputStream(input);
try {
return Nd4j.read(dis); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
//Note: input should NOT be closed manually here - may be needed elsewhere (and closing here will cause serialization to fail)
} } |
public class class_name {
public Notification withJobStatesToNotify(String... jobStatesToNotify) {
if (this.jobStatesToNotify == null) {
setJobStatesToNotify(new java.util.ArrayList<String>(jobStatesToNotify.length));
}
for (String ele : jobStatesToNotify) {
this.jobStatesToNotify.add(ele);
}
return this;
} } | public class class_name {
public Notification withJobStatesToNotify(String... jobStatesToNotify) {
if (this.jobStatesToNotify == null) {
setJobStatesToNotify(new java.util.ArrayList<String>(jobStatesToNotify.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : jobStatesToNotify) {
this.jobStatesToNotify.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
protected boolean getBooleanSetting(String name, boolean defaultValue) {
if (settings.containsKey(name)) {
String value = settings.get(name).toString();
return Boolean.parseBoolean(value);
} else {
return defaultValue;
}
} } | public class class_name {
protected boolean getBooleanSetting(String name, boolean defaultValue) {
if (settings.containsKey(name)) {
String value = settings.get(name).toString();
return Boolean.parseBoolean(value); // depends on control dependency: [if], data = [none]
} else {
return defaultValue; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public int getItemType(BaseCell item) {
// normally we use item.type as identity key
// note, this now only be executed in MainThread, atomic not actually needed
String stringType = item.stringType;
// if the item is a keyType, which means item.type is not the key, use it.
// when data custom the typeKey, we ignore the result of render service.
if (!TextUtils.isEmpty(item.typeKey)) {
// we should use getTypeKey()
stringType = item.typeKey;
} else if (item.componentInfo != null) {
// in MVHelper#isValid ensured a componentInfo's renderService could not be null, so just use it!
// if render service custom item type and not empty, use it as itemType
stringType += item.componentInfo.getVersion() + item.componentInfo.getType();
String renderType = mMvHelper.renderManager().getRenderService(item.componentInfo.getType()).getItemViewType(stringType, item.componentInfo);
if (!TextUtils.isEmpty(renderType)) {
stringType = renderType;
}
}
if (!mStrKeys.containsKey(stringType)) {
int newType = mTypeId.getAndIncrement();
mStrKeys.put(stringType, newType);
mId2Types.put(newType, item.stringType);
mLayoutManager.getRecyclerView().getRecycledViewPool().setMaxRecycledViews(newType, 20);
}
return mStrKeys.get(stringType);
} } | public class class_name {
@Override
public int getItemType(BaseCell item) {
// normally we use item.type as identity key
// note, this now only be executed in MainThread, atomic not actually needed
String stringType = item.stringType;
// if the item is a keyType, which means item.type is not the key, use it.
// when data custom the typeKey, we ignore the result of render service.
if (!TextUtils.isEmpty(item.typeKey)) {
// we should use getTypeKey()
stringType = item.typeKey; // depends on control dependency: [if], data = [none]
} else if (item.componentInfo != null) {
// in MVHelper#isValid ensured a componentInfo's renderService could not be null, so just use it!
// if render service custom item type and not empty, use it as itemType
stringType += item.componentInfo.getVersion() + item.componentInfo.getType(); // depends on control dependency: [if], data = [none]
String renderType = mMvHelper.renderManager().getRenderService(item.componentInfo.getType()).getItemViewType(stringType, item.componentInfo);
if (!TextUtils.isEmpty(renderType)) {
stringType = renderType; // depends on control dependency: [if], data = [none]
}
}
if (!mStrKeys.containsKey(stringType)) {
int newType = mTypeId.getAndIncrement();
mStrKeys.put(stringType, newType); // depends on control dependency: [if], data = [none]
mId2Types.put(newType, item.stringType); // depends on control dependency: [if], data = [none]
mLayoutManager.getRecyclerView().getRecycledViewPool().setMaxRecycledViews(newType, 20); // depends on control dependency: [if], data = [none]
}
return mStrKeys.get(stringType);
} } |
public class class_name {
@Override
protected String getVersion(JSONObject json, String fileName) {
String version = Constants.EMPTY_STRING;
if (json.has(RESOLUTION)) {
JSONObject jObj = json.getJSONObject(RESOLUTION);
if (jObj.has(Constants.TAG)) {
return jObj.getString(Constants.TAG);
}
logger.debug("version not found in file {}", fileName);
return Constants.EMPTY_STRING;
}
return version;
} } | public class class_name {
@Override
protected String getVersion(JSONObject json, String fileName) {
String version = Constants.EMPTY_STRING;
if (json.has(RESOLUTION)) {
JSONObject jObj = json.getJSONObject(RESOLUTION);
if (jObj.has(Constants.TAG)) {
return jObj.getString(Constants.TAG); // depends on control dependency: [if], data = [none]
}
logger.debug("version not found in file {}", fileName); // depends on control dependency: [if], data = [none]
return Constants.EMPTY_STRING; // depends on control dependency: [if], data = [none]
}
return version;
} } |
public class class_name {
public String toHexString() {
StringBuilder builder = new StringBuilder();
for (byte b : bytes) {
builder.append(String.format("%02x", b));
}
return builder.toString();
} } | public class class_name {
public String toHexString() {
StringBuilder builder = new StringBuilder();
for (byte b : bytes) {
builder.append(String.format("%02x", b)); // depends on control dependency: [for], data = [b]
}
return builder.toString();
} } |
public class class_name {
@Override
public void addHook(TrainingHook trainingHook) {
if (trainingHookList == null) {
trainingHookList = new ArrayList<>();
}
trainingHookList.add(trainingHook);
} } | public class class_name {
@Override
public void addHook(TrainingHook trainingHook) {
if (trainingHookList == null) {
trainingHookList = new ArrayList<>(); // depends on control dependency: [if], data = [none]
}
trainingHookList.add(trainingHook);
} } |
public class class_name {
public int updateSqlStatement(String query, Map<String, String> replacer, List<Object> params) throws SQLException {
String queryToExecute = query;
// Check if a map of replacements is given
if (replacer != null) {
queryToExecute = replaceTokens(query, replacer);
}
int result;
PreparedStatement stmt = null;
stmt = m_con.prepareStatement(queryToExecute);
try {
// Check the params
if (params != null) {
for (int i = 0; i < params.size(); i++) {
Object item = params.get(i);
// Check if the parameter is a string
if (item instanceof String) {
stmt.setString(i + 1, (String)item);
}
if (item instanceof Integer) {
Integer number = (Integer)item;
stmt.setInt(i + 1, number.intValue());
}
if (item instanceof Long) {
Long longNumber = (Long)item;
stmt.setLong(i + 1, longNumber.longValue());
}
// If item is none of types above set the statement to use the bytes
if (!(item instanceof Integer) && !(item instanceof String) && !(item instanceof Long)) {
try {
stmt.setBytes(i + 1, CmsDataTypeUtil.dataSerialize(item));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
if (!queryToExecute.startsWith("UPDATE CMS_ONLINE_STRUCTURE SET STRUCTURE_VERSION")
&& !queryToExecute.startsWith("UPDATE CMS_OFFLINE_STRUCTURE SET STRUCTURE_VERSION")) {
System.out.println("executing query: " + queryToExecute);
if ((params != null) && !params.isEmpty()) {
System.out.println("params: " + params);
}
}
result = stmt.executeUpdate();
} finally {
stmt.close();
}
return result;
} } | public class class_name {
public int updateSqlStatement(String query, Map<String, String> replacer, List<Object> params) throws SQLException {
String queryToExecute = query;
// Check if a map of replacements is given
if (replacer != null) {
queryToExecute = replaceTokens(query, replacer);
}
int result;
PreparedStatement stmt = null;
stmt = m_con.prepareStatement(queryToExecute);
try {
// Check the params
if (params != null) {
for (int i = 0; i < params.size(); i++) {
Object item = params.get(i);
// Check if the parameter is a string
if (item instanceof String) {
stmt.setString(i + 1, (String)item); // depends on control dependency: [if], data = [none]
}
if (item instanceof Integer) {
Integer number = (Integer)item;
stmt.setInt(i + 1, number.intValue()); // depends on control dependency: [if], data = [none]
}
if (item instanceof Long) {
Long longNumber = (Long)item;
stmt.setLong(i + 1, longNumber.longValue()); // depends on control dependency: [if], data = [none]
}
// If item is none of types above set the statement to use the bytes
if (!(item instanceof Integer) && !(item instanceof String) && !(item instanceof Long)) {
try {
stmt.setBytes(i + 1, CmsDataTypeUtil.dataSerialize(item)); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
}
}
if (!queryToExecute.startsWith("UPDATE CMS_ONLINE_STRUCTURE SET STRUCTURE_VERSION")
&& !queryToExecute.startsWith("UPDATE CMS_OFFLINE_STRUCTURE SET STRUCTURE_VERSION")) {
System.out.println("executing query: " + queryToExecute); // depends on control dependency: [if], data = [none]
if ((params != null) && !params.isEmpty()) {
System.out.println("params: " + params); // depends on control dependency: [if], data = [none]
}
}
result = stmt.executeUpdate();
} finally {
stmt.close();
}
return result;
} } |
public class class_name {
protected boolean distributeEnd() throws SystemException {
if (tc.isEntryEnabled())
Tr.entry(tc, "distributeEnd");
if (!getResources().distributeEnd(XAResource.TMSUCCESS)) {
setRBO();
}
if (_rollbackOnly) {
try {
_status.setState(TransactionState.STATE_ROLLING_BACK);
} catch (SystemException se) {
FFDCFilter.processException(se, "com.ibm.tx.jta.TransactionImpl.distributeEnd", "1731", this);
if (tc.isEntryEnabled())
Tr.exit(tc, "distributeEnd", se);
throw se;
}
}
if (tc.isEntryEnabled())
Tr.exit(tc, "distributeEnd", !_rollbackOnly);
return !_rollbackOnly;
} } | public class class_name {
protected boolean distributeEnd() throws SystemException {
if (tc.isEntryEnabled())
Tr.entry(tc, "distributeEnd");
if (!getResources().distributeEnd(XAResource.TMSUCCESS)) {
setRBO();
}
if (_rollbackOnly) {
try {
_status.setState(TransactionState.STATE_ROLLING_BACK); // depends on control dependency: [try], data = [none]
} catch (SystemException se) {
FFDCFilter.processException(se, "com.ibm.tx.jta.TransactionImpl.distributeEnd", "1731", this);
if (tc.isEntryEnabled())
Tr.exit(tc, "distributeEnd", se);
throw se;
} // depends on control dependency: [catch], data = [none]
}
if (tc.isEntryEnabled())
Tr.exit(tc, "distributeEnd", !_rollbackOnly);
return !_rollbackOnly;
} } |
public class class_name {
public String refresh(String label) {
Git git = null;
try {
git = createGitClient();
if (shouldPull(git)) {
FetchResult fetchStatus = fetch(git, label);
if (this.deleteUntrackedBranches && fetchStatus != null) {
deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(),
git);
}
// checkout after fetch so we can get any new branches, tags, ect.
checkout(git, label);
tryMerge(git, label);
}
else {
// nothing to update so just checkout and merge.
// Merge because remote branch could have been updated before
checkout(git, label);
tryMerge(git, label);
}
// always return what is currently HEAD as the version
return git.getRepository().findRef("HEAD").getObjectId().getName();
}
catch (RefNotFoundException e) {
throw new NoSuchLabelException("No such label: " + label, e);
}
catch (NoRemoteRepositoryException e) {
throw new NoSuchRepositoryException("No such repository: " + getUri(), e);
}
catch (GitAPIException e) {
throw new NoSuchRepositoryException(
"Cannot clone or checkout repository: " + getUri(), e);
}
catch (Exception e) {
throw new IllegalStateException("Cannot load environment", e);
}
finally {
try {
if (git != null) {
git.close();
}
}
catch (Exception e) {
this.logger.warn("Could not close git repository", e);
}
}
} } | public class class_name {
public String refresh(String label) {
Git git = null;
try {
git = createGitClient(); // depends on control dependency: [try], data = [none]
if (shouldPull(git)) {
FetchResult fetchStatus = fetch(git, label);
if (this.deleteUntrackedBranches && fetchStatus != null) {
deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(),
git); // depends on control dependency: [if], data = [none]
}
// checkout after fetch so we can get any new branches, tags, ect.
checkout(git, label); // depends on control dependency: [if], data = [none]
tryMerge(git, label); // depends on control dependency: [if], data = [none]
}
else {
// nothing to update so just checkout and merge.
// Merge because remote branch could have been updated before
checkout(git, label); // depends on control dependency: [if], data = [none]
tryMerge(git, label); // depends on control dependency: [if], data = [none]
}
// always return what is currently HEAD as the version
return git.getRepository().findRef("HEAD").getObjectId().getName(); // depends on control dependency: [try], data = [none]
}
catch (RefNotFoundException e) {
throw new NoSuchLabelException("No such label: " + label, e);
} // depends on control dependency: [catch], data = [none]
catch (NoRemoteRepositoryException e) {
throw new NoSuchRepositoryException("No such repository: " + getUri(), e);
} // depends on control dependency: [catch], data = [none]
catch (GitAPIException e) {
throw new NoSuchRepositoryException(
"Cannot clone or checkout repository: " + getUri(), e);
} // depends on control dependency: [catch], data = [none]
catch (Exception e) {
throw new IllegalStateException("Cannot load environment", e);
} // depends on control dependency: [catch], data = [none]
finally {
try {
if (git != null) {
git.close(); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e) {
this.logger.warn("Could not close git repository", e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static double cosineSimilarity(DoubleVector a, DoubleVector b) {
double dotProduct = 0.0;
double aMagnitude = a.magnitude();
double bMagnitude = b.magnitude();
// Check whether both vectors support fast iteration over their non-zero
// values. If so, use only the non-zero indices to speed up the
// computation by avoiding zero multiplications
if (a instanceof Iterable && b instanceof Iterable) {
// Check whether we can easily determine how many non-zero values
// are in each vector. This value is used to select the iteration
// order, which affects the number of get(value) calls.
boolean useA =
(a.length() < b.length() ||
(a instanceof SparseVector && b instanceof SparseVector) &&
((SparseVector)a).getNonZeroIndices().length <
((SparseVector)b).getNonZeroIndices().length);
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (useA) {
DoubleVector t = a;
a = b;
b = t;
}
for (DoubleEntry e : ((Iterable<DoubleEntry>)b)) {
int index = e.index();
double aValue = a.get(index);
double bValue = e.value();
dotProduct += aValue * bValue;
}
}
// Check whether both vectors are sparse. If so, use only the non-zero
// indices to speed up the computation by avoiding zero multiplications
else if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] nzA = svA.getNonZeroIndices();
int[] nzB = svB.getNonZeroIndices();
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (a.length() < b.length() ||
nzA.length < nzB.length) {
DoubleVector t = a;
a = b;
b = t;
}
for (int nz : nzB) {
double aValue = a.get(nz);
double bValue = b.get(nz);
dotProduct += aValue * bValue;
}
}
// Check if the second vector is sparse. If so, use only the non-zero
// indices of b to speed up the computation by avoiding zero
// multiplications.
else if (b instanceof SparseVector) {
SparseVector svB = (SparseVector)b;
for (int nz : svB.getNonZeroIndices())
dotProduct += b.get(nz) * a.get(nz);
}
// Check if the first vector is sparse. If so, use only the non-zero
// indices of a to speed up the computation by avoiding zero
// multiplications.
else if (a instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
for (int nz : svA.getNonZeroIndices())
dotProduct += b.get(nz) * a.get(nz);
}
// Otherwise, just assume both are dense and compute the full amount
else {
// Swap the vectors such that the b is the shorter vector and a is
// the longer vector, or of equal length. In the case that the two
// vectors of unequal length, this will prevent any calls to out of
// bounds values in the smaller vector.
if (a.length() < b.length()) {
DoubleVector t = a;
a = b;
b = t;
}
for (int i = 0; i < b.length(); i++) {
double aValue = a.get(i);
double bValue = b.get(i);
dotProduct += aValue * bValue;
}
}
return (aMagnitude == 0 || bMagnitude == 0)
? 0 : dotProduct / (aMagnitude * bMagnitude);
}
/**
* Returns the cosine similarity of the two {@code DoubleVector}.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
@SuppressWarnings("unchecked")
public static double cosineSimilarity(IntegerVector a, IntegerVector b) {
check(a,b);
int dotProduct = 0;
double aMagnitude = a.magnitude();
double bMagnitude = b.magnitude();
// Check whether both vectors support fast iteration over their non-zero
// values. If so, use only the non-zero indices to speed up the
// computation by avoiding zero multiplications
if (a instanceof Iterable && b instanceof Iterable) {
// Check whether we can easily determine how many non-zero values
// are in each vector. This value is used to select the iteration
// order, which affects the number of get(value) calls.
boolean useA =
(a instanceof SparseVector && b instanceof SparseVector)
&& ((SparseVector)a).getNonZeroIndices().length <
((SparseVector)b).getNonZeroIndices().length;
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (useA) {
IntegerVector t = a;
a = b;
b = t;
}
for (IntegerEntry e : ((Iterable<IntegerEntry>)b)) {
int index = e.index();
int aValue = a.get(index);
int bValue = e.value();
dotProduct += aValue * bValue;
}
}
// Check whether both vectors are sparse. If so, use only the non-zero
// indices to speed up the computation by avoiding zero multiplications
else if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] nzA = svA.getNonZeroIndices();
int[] nzB = svB.getNonZeroIndices();
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (nzA.length < nzB.length) {
for (int nz : nzA) {
int aValue = a.get(nz);
int bValue = b.get(nz);
dotProduct += aValue * bValue;
}
}
else {
for (int nz : nzB) {
int aValue = a.get(nz);
int bValue = b.get(nz);
dotProduct += aValue * bValue;
}
}
}
// Otherwise, just assume both are dense and compute the full amount
else {
for (int i = 0; i < b.length(); i++) {
int aValue = a.get(i);
int bValue = b.get(i);
dotProduct += aValue * bValue;
}
}
return (aMagnitude == 0 || bMagnitude == 0)
? 0 : dotProduct / (aMagnitude * bMagnitude);
}
/**
* Returns the cosine similarity of the two {@code DoubleVector}.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double cosineSimilarity(Vector a, Vector b) {
return
(a instanceof IntegerVector && b instanceof IntegerVector)
? cosineSimilarity((IntegerVector)a, (IntegerVector)b)
: cosineSimilarity(Vectors.asDouble(a), Vectors.asDouble(b));
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* arrays.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(double[] arr1, double[] arr2) {
check(arr1, arr2);
// REMINDER: this could be made more effecient by not looping
double xSum = 0;
double ySum = 0;
for (int i = 0; i < arr1.length; ++i) {
xSum += arr1[i];
ySum += arr2[i];
}
double xMean = xSum / arr1.length;
double yMean = ySum / arr1.length;
double numerator = 0, xSqSum = 0, ySqSum = 0;
for (int i = 0; i < arr1.length; ++i) {
double x = arr1[i] - xMean;
double y = arr2[i] - yMean;
numerator += x * y;
xSqSum += (x * x);
ySqSum += (y * y);
}
if (xSqSum == 0 || ySqSum == 0)
return 0;
return numerator / Math.sqrt(xSqSum * ySqSum);
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* arrays.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(int[] arr1, int[] arr2) {
check(arr1, arr2);
// REMINDER: this could be made more effecient by not looping
long xSum = 0;
long ySum = 0;
for (int i = 0; i < arr1.length; ++i) {
xSum += arr1[i];
ySum += arr2[i];
}
double xMean = xSum / (double)(arr1.length);
double yMean = ySum / (double)(arr1.length);
double numerator = 0, xSqSum = 0, ySqSum = 0;
for (int i = 0; i < arr1.length; ++i) {
double x = arr1[i] - xMean;
double y = arr2[i] - yMean;
numerator += x * y;
xSqSum += (x * x);
ySqSum += (y * y);
}
return numerator / Math.sqrt(xSqSum * ySqSum);
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* {@code Vector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(DoubleVector arr1, DoubleVector arr2) {
check(arr1, arr2);
check(arr1, arr2);
// REMINDER: this could be made more effecient by not looping
double xSum = 0;
double ySum = 0;
for (int i = 0; i < arr1.length(); ++i) {
xSum += arr1.get(i);
ySum += arr2.get(i);
}
double xMean = xSum / arr1.length();
double yMean = ySum / arr1.length();
double numerator = 0, xSqSum = 0, ySqSum = 0;
for (int i = 0; i < arr1.length(); ++i) {
double x = arr1.get(i) - xMean;
double y = arr2.get(i) - yMean;
numerator += x * y;
xSqSum += (x * x);
ySqSum += (y * y);
}
return numerator / Math.sqrt(xSqSum * ySqSum);
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* {@code Vector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(IntegerVector arr1, DoubleVector arr2) {
check(arr1, arr2);
// REMINDER: this could be made more effecient by not looping
double xSum = 0;
double ySum = 0;
for (int i = 0; i < arr1.length(); ++i) {
xSum += arr1.get(i);
ySum += arr2.get(i);
}
double xMean = xSum / arr1.length();
double yMean = ySum / arr1.length();
double numerator = 0, xSqSum = 0, ySqSum = 0;
for (int i = 0; i < arr1.length(); ++i) {
double x = arr1.get(i) - xMean;
double y = arr2.get(i) - yMean;
numerator += x * y;
xSqSum += (x * x);
ySqSum += (y * y);
}
return numerator / Math.sqrt(xSqSum * ySqSum);
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* {@code Vector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(Vector a, Vector b) {
return correlation(Vectors.asDouble(a), Vectors.asDouble(b));
}
/**
* Returns the euclidian distance between two arrays of {code double}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(double[] a, double[] b) {
check(a, b);
double sum = 0;
for (int i = 0; i < a.length; ++i)
sum += Math.pow((a[i] - b[i]), 2);
return Math.sqrt(sum);
}
/**
* Returns the euclidian distance between two arrays of {code double}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(int[] a, int[] b) {
check(a, b);
long sum = 0;
for (int i = 0; i < a.length; ++i)
sum += Math.pow(a[i] - b[i], 2);
return Math.sqrt(sum);
}
/**
* Returns the euclidian distance between two {@code DoubleVector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(DoubleVector a, DoubleVector b) {
check(a, b);
if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] aNonZero = svA.getNonZeroIndices();
int[] bNonZero = svB.getNonZeroIndices();
TIntSet union = new TIntHashSet(aNonZero);
union.addAll(bNonZero);
double sum = 0;
int[] nzIndices = union.toArray();
for (int nz : nzIndices) {
double x = a.get(nz);
double y = b.get(nz);
double diff = x - y;
sum += diff * diff;
}
return Math.sqrt(sum);
} else if (b instanceof SparseVector) {
// If b is sparse, use a special case where we use the cached
// magnitude of a and the sparsity of b to avoid most of the
// computations.
SparseVector sb = (SparseVector) b;
int[] bNonZero = sb.getNonZeroIndices();
double sum = 0;
// Get the magnitude for a. This value will often only be computed
// once for the first vector once since the DenseVector caches the
// magnitude, thus saving a large amount of computation.
double aMagnitude = Math.pow(a.magnitude(), 2);
// Compute the difference between the nonzero values of b and the
// corresponding values for a.
for (int index : bNonZero) {
double value = a.get(index);
// Decrement a's value at this index from it's magnitude.
aMagnitude -= Math.pow(value, 2);
sum += Math.pow(value - b.get(index), 2);
}
// Since the rest of b's values are 0, the difference between a and
// b for these values is simply the magnitude of indices which have
// not yet been traversed in a. This corresponds to the modified
// magnitude that was computed.
sum += aMagnitude;
return (sum < 0d) ? 0 : Math.sqrt(sum);
}
double sum = 0;
for (int i = 0; i < a.length(); ++i)
sum += Math.pow((a.get(i) - b.get(i)), 2);
return Math.sqrt(sum);
}
/**
* Returns the euclidian distance between two {@code DoubleVector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(IntegerVector a, IntegerVector b) {
check(a, b);
if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] aNonZero = svA.getNonZeroIndices();
int[] bNonZero = svB.getNonZeroIndices();
HashSet<Integer> sparseIndicesA = new HashSet<Integer>(
aNonZero.length);
double sum = 0;
for (int nonZero : aNonZero) {
sum += Math.pow((a.get(nonZero) - b.get(nonZero)), 2);
sparseIndicesA.add(nonZero);
}
for (int nonZero : bNonZero)
if (!sparseIndicesA.contains(bNonZero))
sum += Math.pow(b.get(nonZero), 2);
return sum;
}
double sum = 0;
for (int i = 0; i < a.length(); ++i)
sum += Math.pow((a.get(i) - b.get(i)), 2);
return Math.sqrt(sum);
}
/**
* Returns the euclidian distance between two {@code Vector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(Vector a, Vector b) {
return euclideanDistance(Vectors.asDouble(a), Vectors.asDouble(b));
}
/**
* Returns the euclidian similiarty between two arrays of values.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanSimilarity(int[] a, int[] b) {
return 1 / (1 + euclideanDistance(a,b));
}
/**
* Returns the euclidian similiarty between two arrays of values.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanSimilarity(double[] a, double[] b) {
return 1 / (1 + euclideanDistance(a,b));
}
/**
* Returns the euclidian similiarty between two arrays of values.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanSimilarity(Vector a, Vector b) {
return 1 / (1 + euclideanDistance(a,b));
}
/**
* Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
* index</a> of the two sets of elements.
*/
public static double jaccardIndex(Set<?> a, Set<?> b) {
int intersection = 0;
for (Object o : a) {
if (b.contains(o))
intersection++;
}
double union = a.size() + b.size() - intersection;
return intersection / union;
}
/**
* Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
* index</a> comparing the similarity both arrays when viewed as sets of
* samples.
*/
public static double jaccardIndex(double[] a, double[] b) {
Set<Double> intersection = new HashSet<Double>();
Set<Double> union = new HashSet<Double>();
for (double d : a) {
intersection.add(d);
union.add(d);
}
Set<Double> tmp = new HashSet<Double>();
for (double d : b) {
tmp.add(d);
union.add(d);
}
intersection.retainAll(tmp);
return ((double)(intersection.size())) / union.size();
}
/**
* Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
* index</a> comparing the similarity both arrays when viewed as sets of
* samples.
*/
public static double jaccardIndex(int[] a, int[] b) {
// The BitSets should be faster than a HashMap since it's back by an
// array and operations are just logical bit operations and require no
// auto-boxing. However, if a or b contains large values, then the cost
// of creating the necessary size for the BitSet may outweigh its
// performance. At some point, it would be useful to profile the two
// methods and their associated worst cases. -jurgens
BitSet c = new BitSet();
BitSet d = new BitSet();
BitSet union = new BitSet();
for (int i : a) {
c.set(i);
union.set(i);
}
for (int i : b) {
d.set(i);
union.set(i);
}
// get the intersection
c.and(d);
return ((double)(c.cardinality())) / union.cardinality();
} } | public class class_name {
@SuppressWarnings("unchecked")
public static double cosineSimilarity(DoubleVector a, DoubleVector b) {
double dotProduct = 0.0;
double aMagnitude = a.magnitude();
double bMagnitude = b.magnitude();
// Check whether both vectors support fast iteration over their non-zero
// values. If so, use only the non-zero indices to speed up the
// computation by avoiding zero multiplications
if (a instanceof Iterable && b instanceof Iterable) {
// Check whether we can easily determine how many non-zero values
// are in each vector. This value is used to select the iteration
// order, which affects the number of get(value) calls.
boolean useA =
(a.length() < b.length() ||
(a instanceof SparseVector && b instanceof SparseVector) &&
((SparseVector)a).getNonZeroIndices().length <
((SparseVector)b).getNonZeroIndices().length);
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (useA) {
DoubleVector t = a;
a = b; // depends on control dependency: [if], data = [none]
b = t; // depends on control dependency: [if], data = [none]
}
for (DoubleEntry e : ((Iterable<DoubleEntry>)b)) {
int index = e.index();
double aValue = a.get(index);
double bValue = e.value();
dotProduct += aValue * bValue; // depends on control dependency: [for], data = [e]
}
}
// Check whether both vectors are sparse. If so, use only the non-zero
// indices to speed up the computation by avoiding zero multiplications
else if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] nzA = svA.getNonZeroIndices();
int[] nzB = svB.getNonZeroIndices();
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (a.length() < b.length() ||
nzA.length < nzB.length) {
DoubleVector t = a;
a = b; // depends on control dependency: [if], data = [none]
b = t; // depends on control dependency: [if], data = [none]
}
for (int nz : nzB) {
double aValue = a.get(nz);
double bValue = b.get(nz);
dotProduct += aValue * bValue; // depends on control dependency: [for], data = [none]
}
}
// Check if the second vector is sparse. If so, use only the non-zero
// indices of b to speed up the computation by avoiding zero
// multiplications.
else if (b instanceof SparseVector) {
SparseVector svB = (SparseVector)b;
for (int nz : svB.getNonZeroIndices())
dotProduct += b.get(nz) * a.get(nz);
}
// Check if the first vector is sparse. If so, use only the non-zero
// indices of a to speed up the computation by avoiding zero
// multiplications.
else if (a instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
for (int nz : svA.getNonZeroIndices())
dotProduct += b.get(nz) * a.get(nz);
}
// Otherwise, just assume both are dense and compute the full amount
else {
// Swap the vectors such that the b is the shorter vector and a is
// the longer vector, or of equal length. In the case that the two
// vectors of unequal length, this will prevent any calls to out of
// bounds values in the smaller vector.
if (a.length() < b.length()) {
DoubleVector t = a;
a = b; // depends on control dependency: [if], data = [none]
b = t; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < b.length(); i++) {
double aValue = a.get(i);
double bValue = b.get(i);
dotProduct += aValue * bValue; // depends on control dependency: [for], data = [none]
}
}
return (aMagnitude == 0 || bMagnitude == 0)
? 0 : dotProduct / (aMagnitude * bMagnitude);
}
/**
* Returns the cosine similarity of the two {@code DoubleVector}.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
@SuppressWarnings("unchecked")
public static double cosineSimilarity(IntegerVector a, IntegerVector b) {
check(a,b);
int dotProduct = 0;
double aMagnitude = a.magnitude();
double bMagnitude = b.magnitude();
// Check whether both vectors support fast iteration over their non-zero
// values. If so, use only the non-zero indices to speed up the
// computation by avoiding zero multiplications
if (a instanceof Iterable && b instanceof Iterable) {
// Check whether we can easily determine how many non-zero values
// are in each vector. This value is used to select the iteration
// order, which affects the number of get(value) calls.
boolean useA =
(a instanceof SparseVector && b instanceof SparseVector)
&& ((SparseVector)a).getNonZeroIndices().length <
((SparseVector)b).getNonZeroIndices().length;
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (useA) {
IntegerVector t = a;
a = b; // depends on control dependency: [if], data = [none]
b = t; // depends on control dependency: [if], data = [none]
}
for (IntegerEntry e : ((Iterable<IntegerEntry>)b)) {
int index = e.index();
int aValue = a.get(index);
int bValue = e.value();
dotProduct += aValue * bValue; // depends on control dependency: [for], data = [e]
}
}
// Check whether both vectors are sparse. If so, use only the non-zero
// indices to speed up the computation by avoiding zero multiplications
else if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] nzA = svA.getNonZeroIndices();
int[] nzB = svB.getNonZeroIndices();
// Choose the smaller of the two to use in computing the dot
// product. Because it would be more expensive to compute the
// intersection of the two sets, we assume that any potential
// misses would be less of a performance hit.
if (nzA.length < nzB.length) {
for (int nz : nzA) {
int aValue = a.get(nz);
int bValue = b.get(nz);
dotProduct += aValue * bValue; // depends on control dependency: [for], data = [none]
}
}
else {
for (int nz : nzB) {
int aValue = a.get(nz);
int bValue = b.get(nz);
dotProduct += aValue * bValue; // depends on control dependency: [for], data = [none]
}
}
}
// Otherwise, just assume both are dense and compute the full amount
else {
for (int i = 0; i < b.length(); i++) {
int aValue = a.get(i);
int bValue = b.get(i);
dotProduct += aValue * bValue; // depends on control dependency: [for], data = [none]
}
}
return (aMagnitude == 0 || bMagnitude == 0)
? 0 : dotProduct / (aMagnitude * bMagnitude);
}
/**
* Returns the cosine similarity of the two {@code DoubleVector}.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double cosineSimilarity(Vector a, Vector b) {
return
(a instanceof IntegerVector && b instanceof IntegerVector)
? cosineSimilarity((IntegerVector)a, (IntegerVector)b)
: cosineSimilarity(Vectors.asDouble(a), Vectors.asDouble(b));
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* arrays.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(double[] arr1, double[] arr2) {
check(arr1, arr2);
// REMINDER: this could be made more effecient by not looping
double xSum = 0;
double ySum = 0;
for (int i = 0; i < arr1.length; ++i) {
xSum += arr1[i]; // depends on control dependency: [for], data = [i]
ySum += arr2[i]; // depends on control dependency: [for], data = [i]
}
double xMean = xSum / arr1.length;
double yMean = ySum / arr1.length;
double numerator = 0, xSqSum = 0, ySqSum = 0;
for (int i = 0; i < arr1.length; ++i) {
double x = arr1[i] - xMean;
double y = arr2[i] - yMean;
numerator += x * y; // depends on control dependency: [for], data = [none]
xSqSum += (x * x); // depends on control dependency: [for], data = [none]
ySqSum += (y * y); // depends on control dependency: [for], data = [none]
}
if (xSqSum == 0 || ySqSum == 0)
return 0;
return numerator / Math.sqrt(xSqSum * ySqSum);
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* arrays.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(int[] arr1, int[] arr2) {
check(arr1, arr2);
// REMINDER: this could be made more effecient by not looping
long xSum = 0;
long ySum = 0;
for (int i = 0; i < arr1.length; ++i) {
xSum += arr1[i]; // depends on control dependency: [for], data = [i]
ySum += arr2[i]; // depends on control dependency: [for], data = [i]
}
double xMean = xSum / (double)(arr1.length);
double yMean = ySum / (double)(arr1.length);
double numerator = 0, xSqSum = 0, ySqSum = 0;
for (int i = 0; i < arr1.length; ++i) {
double x = arr1[i] - xMean;
double y = arr2[i] - yMean;
numerator += x * y; // depends on control dependency: [for], data = [none]
xSqSum += (x * x); // depends on control dependency: [for], data = [none]
ySqSum += (y * y); // depends on control dependency: [for], data = [none]
}
return numerator / Math.sqrt(xSqSum * ySqSum);
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* {@code Vector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(DoubleVector arr1, DoubleVector arr2) {
check(arr1, arr2);
check(arr1, arr2);
// REMINDER: this could be made more effecient by not looping
double xSum = 0;
double ySum = 0;
for (int i = 0; i < arr1.length(); ++i) {
xSum += arr1.get(i); // depends on control dependency: [for], data = [i]
ySum += arr2.get(i); // depends on control dependency: [for], data = [i]
}
double xMean = xSum / arr1.length();
double yMean = ySum / arr1.length();
double numerator = 0, xSqSum = 0, ySqSum = 0;
for (int i = 0; i < arr1.length(); ++i) {
double x = arr1.get(i) - xMean;
double y = arr2.get(i) - yMean;
numerator += x * y; // depends on control dependency: [for], data = [none]
xSqSum += (x * x); // depends on control dependency: [for], data = [none]
ySqSum += (y * y); // depends on control dependency: [for], data = [none]
}
return numerator / Math.sqrt(xSqSum * ySqSum);
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* {@code Vector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(IntegerVector arr1, DoubleVector arr2) {
check(arr1, arr2);
// REMINDER: this could be made more effecient by not looping
double xSum = 0;
double ySum = 0;
for (int i = 0; i < arr1.length(); ++i) {
xSum += arr1.get(i); // depends on control dependency: [for], data = [i]
ySum += arr2.get(i); // depends on control dependency: [for], data = [i]
}
double xMean = xSum / arr1.length();
double yMean = ySum / arr1.length();
double numerator = 0, xSqSum = 0, ySqSum = 0;
for (int i = 0; i < arr1.length(); ++i) {
double x = arr1.get(i) - xMean;
double y = arr2.get(i) - yMean;
numerator += x * y; // depends on control dependency: [for], data = [none]
xSqSum += (x * x); // depends on control dependency: [for], data = [none]
ySqSum += (y * y); // depends on control dependency: [for], data = [none]
}
return numerator / Math.sqrt(xSqSum * ySqSum);
}
/**
* Returns the Pearson product-moment correlation coefficient of the two
* {@code Vector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double correlation(Vector a, Vector b) {
return correlation(Vectors.asDouble(a), Vectors.asDouble(b));
}
/**
* Returns the euclidian distance between two arrays of {code double}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(double[] a, double[] b) {
check(a, b);
double sum = 0;
for (int i = 0; i < a.length; ++i)
sum += Math.pow((a[i] - b[i]), 2);
return Math.sqrt(sum);
}
/**
* Returns the euclidian distance between two arrays of {code double}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(int[] a, int[] b) {
check(a, b);
long sum = 0;
for (int i = 0; i < a.length; ++i)
sum += Math.pow(a[i] - b[i], 2);
return Math.sqrt(sum);
}
/**
* Returns the euclidian distance between two {@code DoubleVector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(DoubleVector a, DoubleVector b) {
check(a, b);
if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] aNonZero = svA.getNonZeroIndices();
int[] bNonZero = svB.getNonZeroIndices();
TIntSet union = new TIntHashSet(aNonZero);
union.addAll(bNonZero); // depends on control dependency: [if], data = [none]
double sum = 0;
int[] nzIndices = union.toArray();
for (int nz : nzIndices) {
double x = a.get(nz);
double y = b.get(nz);
double diff = x - y;
sum += diff * diff; // depends on control dependency: [for], data = [none]
}
return Math.sqrt(sum); // depends on control dependency: [if], data = [none]
} else if (b instanceof SparseVector) {
// If b is sparse, use a special case where we use the cached
// magnitude of a and the sparsity of b to avoid most of the
// computations.
SparseVector sb = (SparseVector) b;
int[] bNonZero = sb.getNonZeroIndices();
double sum = 0;
// Get the magnitude for a. This value will often only be computed
// once for the first vector once since the DenseVector caches the
// magnitude, thus saving a large amount of computation.
double aMagnitude = Math.pow(a.magnitude(), 2);
// Compute the difference between the nonzero values of b and the
// corresponding values for a.
for (int index : bNonZero) {
double value = a.get(index);
// Decrement a's value at this index from it's magnitude.
aMagnitude -= Math.pow(value, 2); // depends on control dependency: [for], data = [none]
sum += Math.pow(value - b.get(index), 2); // depends on control dependency: [for], data = [index]
}
// Since the rest of b's values are 0, the difference between a and
// b for these values is simply the magnitude of indices which have
// not yet been traversed in a. This corresponds to the modified
// magnitude that was computed.
sum += aMagnitude; // depends on control dependency: [if], data = [none]
return (sum < 0d) ? 0 : Math.sqrt(sum); // depends on control dependency: [if], data = [none]
}
double sum = 0;
for (int i = 0; i < a.length(); ++i)
sum += Math.pow((a.get(i) - b.get(i)), 2);
return Math.sqrt(sum);
}
/**
* Returns the euclidian distance between two {@code DoubleVector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(IntegerVector a, IntegerVector b) {
check(a, b);
if (a instanceof SparseVector && b instanceof SparseVector) {
SparseVector svA = (SparseVector)a;
SparseVector svB = (SparseVector)b;
int[] aNonZero = svA.getNonZeroIndices();
int[] bNonZero = svB.getNonZeroIndices();
HashSet<Integer> sparseIndicesA = new HashSet<Integer>(
aNonZero.length);
double sum = 0;
for (int nonZero : aNonZero) {
sum += Math.pow((a.get(nonZero) - b.get(nonZero)), 2); // depends on control dependency: [for], data = [nonZero]
sparseIndicesA.add(nonZero); // depends on control dependency: [for], data = [nonZero]
}
for (int nonZero : bNonZero)
if (!sparseIndicesA.contains(bNonZero))
sum += Math.pow(b.get(nonZero), 2);
return sum; // depends on control dependency: [if], data = [none]
}
double sum = 0;
for (int i = 0; i < a.length(); ++i)
sum += Math.pow((a.get(i) - b.get(i)), 2);
return Math.sqrt(sum);
}
/**
* Returns the euclidian distance between two {@code Vector}s.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanDistance(Vector a, Vector b) {
return euclideanDistance(Vectors.asDouble(a), Vectors.asDouble(b));
}
/**
* Returns the euclidian similiarty between two arrays of values.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanSimilarity(int[] a, int[] b) {
return 1 / (1 + euclideanDistance(a,b));
}
/**
* Returns the euclidian similiarty between two arrays of values.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanSimilarity(double[] a, double[] b) {
return 1 / (1 + euclideanDistance(a,b));
}
/**
* Returns the euclidian similiarty between two arrays of values.
*
* @throws IllegalArgumentException when the length of the two vectors are
* not the same.
*/
public static double euclideanSimilarity(Vector a, Vector b) {
return 1 / (1 + euclideanDistance(a,b));
}
/**
* Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
* index</a> of the two sets of elements.
*/
public static double jaccardIndex(Set<?> a, Set<?> b) {
int intersection = 0;
for (Object o : a) {
if (b.contains(o))
intersection++;
}
double union = a.size() + b.size() - intersection;
return intersection / union;
}
/**
* Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
* index</a> comparing the similarity both arrays when viewed as sets of
* samples.
*/
public static double jaccardIndex(double[] a, double[] b) {
Set<Double> intersection = new HashSet<Double>();
Set<Double> union = new HashSet<Double>();
for (double d : a) {
intersection.add(d); // depends on control dependency: [for], data = [d]
union.add(d); // depends on control dependency: [for], data = [d]
}
Set<Double> tmp = new HashSet<Double>();
for (double d : b) {
tmp.add(d); // depends on control dependency: [for], data = [d]
union.add(d); // depends on control dependency: [for], data = [d]
}
intersection.retainAll(tmp);
return ((double)(intersection.size())) / union.size();
}
/**
* Computes the <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
* index</a> comparing the similarity both arrays when viewed as sets of
* samples.
*/
public static double jaccardIndex(int[] a, int[] b) {
// The BitSets should be faster than a HashMap since it's back by an
// array and operations are just logical bit operations and require no
// auto-boxing. However, if a or b contains large values, then the cost
// of creating the necessary size for the BitSet may outweigh its
// performance. At some point, it would be useful to profile the two
// methods and their associated worst cases. -jurgens
BitSet c = new BitSet();
BitSet d = new BitSet();
BitSet union = new BitSet();
for (int i : a) {
c.set(i); // depends on control dependency: [for], data = [i]
union.set(i); // depends on control dependency: [for], data = [i]
}
for (int i : b) {
d.set(i); // depends on control dependency: [for], data = [i]
union.set(i); // depends on control dependency: [for], data = [i]
}
// get the intersection
c.and(d);
return ((double)(c.cardinality())) / union.cardinality();
} } |
public class class_name {
@Override
public SegmentPublishResult perform(Task task, TaskActionToolbox toolbox)
{
TaskActionPreconditions.checkLockCoversSegments(task, toolbox.getTaskLockbox(), segments);
final SegmentPublishResult retVal;
try {
retVal = toolbox.getTaskLockbox().doInCriticalSection(
task,
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
CriticalAction.<SegmentPublishResult>builder()
.onValidLocks(
() -> toolbox.getIndexerMetadataStorageCoordinator().announceHistoricalSegments(
segments,
startMetadata,
endMetadata
)
)
.onInvalidLocks(
() -> SegmentPublishResult.fail(
"Invalid task locks. Maybe they are revoked by a higher priority task."
+ " Please check the overlord log for details."
)
)
.build()
);
}
catch (Exception e) {
throw new RuntimeException(e);
}
// Emit metrics
final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder();
IndexTaskUtils.setTaskDimensions(metricBuilder, task);
if (retVal.isSuccess()) {
toolbox.getEmitter().emit(metricBuilder.build("segment/txn/success", 1));
} else {
toolbox.getEmitter().emit(metricBuilder.build("segment/txn/failure", 1));
}
// getSegments() should return an empty set if announceHistoricalSegments() failed
for (DataSegment segment : retVal.getSegments()) {
metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString());
toolbox.getEmitter().emit(metricBuilder.build("segment/added/bytes", segment.getSize()));
}
return retVal;
} } | public class class_name {
@Override
public SegmentPublishResult perform(Task task, TaskActionToolbox toolbox)
{
TaskActionPreconditions.checkLockCoversSegments(task, toolbox.getTaskLockbox(), segments);
final SegmentPublishResult retVal;
try {
retVal = toolbox.getTaskLockbox().doInCriticalSection(
task,
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
CriticalAction.<SegmentPublishResult>builder()
.onValidLocks(
() -> toolbox.getIndexerMetadataStorageCoordinator().announceHistoricalSegments(
segments,
startMetadata,
endMetadata
)
)
.onInvalidLocks(
() -> SegmentPublishResult.fail(
"Invalid task locks. Maybe they are revoked by a higher priority task."
+ " Please check the overlord log for details."
)
)
.build()
); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
// Emit metrics
final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder();
IndexTaskUtils.setTaskDimensions(metricBuilder, task);
if (retVal.isSuccess()) {
toolbox.getEmitter().emit(metricBuilder.build("segment/txn/success", 1)); // depends on control dependency: [if], data = [none]
} else {
toolbox.getEmitter().emit(metricBuilder.build("segment/txn/failure", 1)); // depends on control dependency: [if], data = [none]
}
// getSegments() should return an empty set if announceHistoricalSegments() failed
for (DataSegment segment : retVal.getSegments()) {
metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString()); // depends on control dependency: [for], data = [segment]
toolbox.getEmitter().emit(metricBuilder.build("segment/added/bytes", segment.getSize())); // depends on control dependency: [for], data = [segment]
}
return retVal;
} } |
public class class_name {
public boolean canEncode(final CharSequence cs) {
if (cs == null) {
return true;
}
final String cstring = Objects.toString(cs);
final byte[] stringAsByte = this.charset.getBytes(cstring);
return Objects.equals(cstring, String.valueOf(
this.charset.decodeString(this.charset.getBytes(cstring), 0, stringAsByte.length)));
} } | public class class_name {
public boolean canEncode(final CharSequence cs) {
if (cs == null) {
return true; // depends on control dependency: [if], data = [none]
}
final String cstring = Objects.toString(cs);
final byte[] stringAsByte = this.charset.getBytes(cstring);
return Objects.equals(cstring, String.valueOf(
this.charset.decodeString(this.charset.getBytes(cstring), 0, stringAsByte.length)));
} } |
public class class_name {
public static Double getDouble(Config config, String path) {
try {
Object obj = config.getAnyRef(path);
return obj instanceof Number ? ((Number) obj).doubleValue() : null;
} catch (ConfigException.Missing | ConfigException.WrongType e) {
if (e instanceof ConfigException.WrongType) {
LOGGER.warn(e.getMessage(), e);
}
return null;
}
} } | public class class_name {
public static Double getDouble(Config config, String path) {
try {
Object obj = config.getAnyRef(path);
return obj instanceof Number ? ((Number) obj).doubleValue() : null; // depends on control dependency: [try], data = [none]
} catch (ConfigException.Missing | ConfigException.WrongType e) {
if (e instanceof ConfigException.WrongType) {
LOGGER.warn(e.getMessage(), e); // depends on control dependency: [if], data = [none]
}
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static int indexOfSubList(List<?> source, List<?> target) {
int sourceSize = source.size();
int targetSize = target.size();
int maxCandidate = sourceSize - targetSize;
if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
(source instanceof RandomAccess&&target instanceof RandomAccess)) {
nextCand:
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
for (int i=0, j=candidate; i<targetSize; i++, j++)
if (!eq(target.get(i), source.get(j)))
continue nextCand; // Element mismatch, try next cand
return candidate; // All elements of candidate matched target
}
} else { // Iterator version of above algorithm
ListIterator<?> si = source.listIterator();
nextCand:
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
ListIterator<?> ti = target.listIterator();
for (int i=0; i<targetSize; i++) {
if (!eq(ti.next(), si.next())) {
// Back up source iterator to next candidate
for (int j=0; j<i; j++)
si.previous();
continue nextCand;
}
}
return candidate;
}
}
return -1; // No candidate matched the target
} } | public class class_name {
public static int indexOfSubList(List<?> source, List<?> target) {
int sourceSize = source.size();
int targetSize = target.size();
int maxCandidate = sourceSize - targetSize;
if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
(source instanceof RandomAccess&&target instanceof RandomAccess)) {
nextCand:
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
for (int i=0, j=candidate; i<targetSize; i++, j++)
if (!eq(target.get(i), source.get(j)))
continue nextCand; // Element mismatch, try next cand
return candidate; // All elements of candidate matched target // depends on control dependency: [for], data = [candidate]
}
} else { // Iterator version of above algorithm
ListIterator<?> si = source.listIterator();
nextCand:
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
ListIterator<?> ti = target.listIterator();
for (int i=0; i<targetSize; i++) {
if (!eq(ti.next(), si.next())) {
// Back up source iterator to next candidate
for (int j=0; j<i; j++)
si.previous();
continue nextCand;
}
}
return candidate; // depends on control dependency: [for], data = [candidate]
}
}
return -1; // No candidate matched the target
} } |
public class class_name {
public V load(K key) {
final String value = store.load(toKeyString(key));
if (value != null) {
return toValueObject(value);
} else {
return null;
}
} } | public class class_name {
public V load(K key) {
final String value = store.load(toKeyString(key));
if (value != null) {
return toValueObject(value); // depends on control dependency: [if], data = [(value]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public double getBucketMaximum(int i) {
if (i < bucketLimits.length) {
return bucketLimits[i];
} else if (getBucketCount(i) == 0) {
// last bucket, but empty
return Double.MAX_VALUE;
} else {
return getMaximum();
}
} } | public class class_name {
public double getBucketMaximum(int i) {
if (i < bucketLimits.length) {
return bucketLimits[i]; // depends on control dependency: [if], data = [none]
} else if (getBucketCount(i) == 0) {
// last bucket, but empty
return Double.MAX_VALUE; // depends on control dependency: [if], data = [none]
} else {
return getMaximum(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void initialize() {
this.setContentPane(getJPanel());
this.pack();
if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) {
this.setSize(406, 193);
}
getConnPanel().passwordFocus();
} } | public class class_name {
private void initialize() {
this.setContentPane(getJPanel());
this.pack();
if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) {
this.setSize(406, 193);
// depends on control dependency: [if], data = [none]
}
getConnPanel().passwordFocus();
} } |
public class class_name {
public void marshall(TemporaryCredential temporaryCredential, ProtocolMarshaller protocolMarshaller) {
if (temporaryCredential == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(temporaryCredential.getUsername(), USERNAME_BINDING);
protocolMarshaller.marshall(temporaryCredential.getPassword(), PASSWORD_BINDING);
protocolMarshaller.marshall(temporaryCredential.getValidForInMinutes(), VALIDFORINMINUTES_BINDING);
protocolMarshaller.marshall(temporaryCredential.getInstanceId(), INSTANCEID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(TemporaryCredential temporaryCredential, ProtocolMarshaller protocolMarshaller) {
if (temporaryCredential == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(temporaryCredential.getUsername(), USERNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(temporaryCredential.getPassword(), PASSWORD_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(temporaryCredential.getValidForInMinutes(), VALIDFORINMINUTES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(temporaryCredential.getInstanceId(), INSTANCEID_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 {
static ObjectNode logsToJson(LinkedList<TelemetryData> telemetryData)
{
ObjectNode node = mapper.createObjectNode();
ArrayNode logs = mapper.createArrayNode();
for (TelemetryData data : telemetryData)
{
logs.add(data.toJson());
}
node.set("logs", logs);
return node;
} } | public class class_name {
static ObjectNode logsToJson(LinkedList<TelemetryData> telemetryData)
{
ObjectNode node = mapper.createObjectNode();
ArrayNode logs = mapper.createArrayNode();
for (TelemetryData data : telemetryData)
{
logs.add(data.toJson()); // depends on control dependency: [for], data = [data]
}
node.set("logs", logs);
return node;
} } |
public class class_name {
public ExtraLanguageTypeConverter getTypeConverter() {
ExtraLanguageTypeConverter converter = this.typeConverter;
if (converter == null) {
converter = createTypeConverterInstance(getTypeConverterInitializer(), null);
this.injector.injectMembers(converter);
this.typeConverter = converter;
}
return converter;
} } | public class class_name {
public ExtraLanguageTypeConverter getTypeConverter() {
ExtraLanguageTypeConverter converter = this.typeConverter;
if (converter == null) {
converter = createTypeConverterInstance(getTypeConverterInitializer(), null); // depends on control dependency: [if], data = [null)]
this.injector.injectMembers(converter); // depends on control dependency: [if], data = [(converter]
this.typeConverter = converter; // depends on control dependency: [if], data = [none]
}
return converter;
} } |
public class class_name {
public String[] getFileList()
{
String[] files = null;
String strFilename = this.getProperty("filename");
if (strFilename != null)
{
files = new String[1];
files[0] = strFilename;
}
String strDirname = this.getProperty("folder");
if (strDirname != null)
{
FileList list = new FileList(strDirname);
files = list.getFileNames();
if (!strDirname.endsWith("/"))
strDirname += "/";
for (int i = 0; i < files.length; i++)
{
files[i] = strDirname + files[i]; // Full pathname
}
}
return files;
} } | public class class_name {
public String[] getFileList()
{
String[] files = null;
String strFilename = this.getProperty("filename");
if (strFilename != null)
{
files = new String[1]; // depends on control dependency: [if], data = [none]
files[0] = strFilename; // depends on control dependency: [if], data = [none]
}
String strDirname = this.getProperty("folder");
if (strDirname != null)
{
FileList list = new FileList(strDirname);
files = list.getFileNames(); // depends on control dependency: [if], data = [none]
if (!strDirname.endsWith("/"))
strDirname += "/";
for (int i = 0; i < files.length; i++)
{
files[i] = strDirname + files[i]; // Full pathname // depends on control dependency: [for], data = [i]
}
}
return files;
} } |
public class class_name {
public String getSyntax() {
if (name != null && longName != null) {
return String.format("-%s (--%s)", name, longName);
}
else if (name != null) {
return String.format("-%s", name);
}
else if (longName != null) {
return String.format("--%s", longName);
}
throw new Error();
} } | public class class_name {
public String getSyntax() {
if (name != null && longName != null) {
return String.format("-%s (--%s)", name, longName); // depends on control dependency: [if], data = [none]
}
else if (name != null) {
return String.format("-%s", name); // depends on control dependency: [if], data = [none]
}
else if (longName != null) {
return String.format("--%s", longName); // depends on control dependency: [if], data = [none]
}
throw new Error();
} } |
public class class_name {
private DoubleMatrix solveEquationSystem(){
DoubleMatrix R=new DoubleMatrix(partition.getLength());
DoubleMatrix M=new DoubleMatrix(partition.getLength(),partition.getLength());
DoubleMatrix partitionAsVector=new DoubleMatrix(partition.getPoints());
DoubleMatrix shiftedPartition=new DoubleMatrix(partition.getLength());
for(int j=1; j<shiftedPartition.length;j++) {
shiftedPartition.put(j, partition.getPoint(j-1));
}
DoubleMatrix partitionIncrements= partitionAsVector.sub(shiftedPartition).put(0,1);
DoubleMatrix kernelValues=new DoubleMatrix(partition.getLength()-1);
DoubleMatrix M1_1= new DoubleMatrix(1);
DoubleMatrix MFirstCol= new DoubleMatrix(partition.getLength()-1);
DoubleMatrix MSubDiagonal= new DoubleMatrix(partition.getLength()-1);
DoubleMatrix MSubMatrix= new DoubleMatrix(partition.getLength()-1,partition.getLength()-1);
DoubleMatrix MSubMatrixSum= new DoubleMatrix(partition.getLength()-1);
for(int i=0;i<independentValues.length;i++){
DoubleMatrix oneZeroVector= new DoubleMatrix(partition.getLength());
DoubleMatrix kernelSum= new DoubleMatrix(partition.getLength());
DoubleMatrix shiftedKernelVector= new DoubleMatrix(partition.getLength());
for(int r=0;r<partition.getLength()-1;r++){
oneZeroVector.put(r, 1);
kernelValues.put( r,kernel.density((partition.getIntervalReferencePoint(r)-independentValues[i])/bandwidth));
shiftedKernelVector.put(r+1,kernelValues.get( r) );
kernelSum=kernelSum.add(oneZeroVector.mmul(kernelValues.get(r)));
}
R=R.add(shiftedPartition.neg().add(independentValues[i]).mul(shiftedKernelVector)
.add(partitionIncrements.mul(kernelSum)).mul(dependentValues[i]));
M1_1=M1_1.add( kernelSum.get(0));
MFirstCol=MFirstCol.add(
partitionAsVector.getRange(0,partitionAsVector.length-1).neg().add(independentValues[i])
.mul(kernelValues).add(
partitionIncrements.getRange(1,partitionAsVector.length)
.mul(kernelSum.getRange(1, kernelSum.length))));
MSubDiagonal=MSubDiagonal.add(
partitionAsVector.getRange(0,partitionAsVector.length-1).neg().add(independentValues[i])
.mul(partitionAsVector.getRange(0,partitionAsVector.length-1).neg().add(independentValues[i]))
.mul(kernelValues).add(
partitionIncrements.getRange(1,partitionAsVector.length)
.mul(partitionIncrements.getRange(1,partitionAsVector.length)
.mul(kernelSum.getRange(1, kernelSum.length)))));
MSubMatrixSum=MSubMatrixSum.add(
partitionAsVector.getRange(0, partitionAsVector.length-1).neg().add(independentValues[i])
.mul(kernelValues).add(
partitionIncrements.getRange(1, partitionIncrements.length)
.mul(kernelSum.getRange(1, kernelSum.length))));
}
DoubleMatrix partitionIncrementMatrix= new DoubleMatrix(partition.getLength()-1,partition.getLength()-1);
DoubleMatrix matrixDefine= DoubleMatrix.ones(partition.getLength()-1);
for(int m=0;m<matrixDefine.length-1;m++) {
matrixDefine.put(m, 0);
partitionIncrementMatrix.putColumn(m, matrixDefine.mul(partitionIncrements.get(m+1)));
}
MSubMatrix=partitionIncrementMatrix.mulColumnVector(MSubMatrixSum);
MSubMatrix=MSubMatrix.add(MSubMatrix.transpose()).add(DoubleMatrix.diag(MSubDiagonal));
int[] rowColIndex =new int[partition.getLength()-1];
for(int n=0;n<rowColIndex.length;n++) {
rowColIndex[n]=n+1;
}
M.put(0,0,M1_1.get(0));
M.put(rowColIndex, 0, MFirstCol);
M.put(0, rowColIndex, MFirstCol.transpose());
M.put(rowColIndex, rowColIndex, MSubMatrix);
return Solve.solve(M, R);
} } | public class class_name {
private DoubleMatrix solveEquationSystem(){
DoubleMatrix R=new DoubleMatrix(partition.getLength());
DoubleMatrix M=new DoubleMatrix(partition.getLength(),partition.getLength());
DoubleMatrix partitionAsVector=new DoubleMatrix(partition.getPoints());
DoubleMatrix shiftedPartition=new DoubleMatrix(partition.getLength());
for(int j=1; j<shiftedPartition.length;j++) {
shiftedPartition.put(j, partition.getPoint(j-1)); // depends on control dependency: [for], data = [j]
}
DoubleMatrix partitionIncrements= partitionAsVector.sub(shiftedPartition).put(0,1);
DoubleMatrix kernelValues=new DoubleMatrix(partition.getLength()-1);
DoubleMatrix M1_1= new DoubleMatrix(1);
DoubleMatrix MFirstCol= new DoubleMatrix(partition.getLength()-1);
DoubleMatrix MSubDiagonal= new DoubleMatrix(partition.getLength()-1);
DoubleMatrix MSubMatrix= new DoubleMatrix(partition.getLength()-1,partition.getLength()-1);
DoubleMatrix MSubMatrixSum= new DoubleMatrix(partition.getLength()-1);
for(int i=0;i<independentValues.length;i++){
DoubleMatrix oneZeroVector= new DoubleMatrix(partition.getLength());
DoubleMatrix kernelSum= new DoubleMatrix(partition.getLength());
DoubleMatrix shiftedKernelVector= new DoubleMatrix(partition.getLength());
for(int r=0;r<partition.getLength()-1;r++){
oneZeroVector.put(r, 1); // depends on control dependency: [for], data = [r]
kernelValues.put( r,kernel.density((partition.getIntervalReferencePoint(r)-independentValues[i])/bandwidth)); // depends on control dependency: [for], data = [r]
shiftedKernelVector.put(r+1,kernelValues.get( r) ); // depends on control dependency: [for], data = [r]
kernelSum=kernelSum.add(oneZeroVector.mmul(kernelValues.get(r))); // depends on control dependency: [for], data = [r]
}
R=R.add(shiftedPartition.neg().add(independentValues[i]).mul(shiftedKernelVector)
.add(partitionIncrements.mul(kernelSum)).mul(dependentValues[i])); // depends on control dependency: [for], data = [i]
M1_1=M1_1.add( kernelSum.get(0)); // depends on control dependency: [for], data = [none]
MFirstCol=MFirstCol.add(
partitionAsVector.getRange(0,partitionAsVector.length-1).neg().add(independentValues[i])
.mul(kernelValues).add(
partitionIncrements.getRange(1,partitionAsVector.length)
.mul(kernelSum.getRange(1, kernelSum.length)))); // depends on control dependency: [for], data = [none]
MSubDiagonal=MSubDiagonal.add(
partitionAsVector.getRange(0,partitionAsVector.length-1).neg().add(independentValues[i])
.mul(partitionAsVector.getRange(0,partitionAsVector.length-1).neg().add(independentValues[i]))
.mul(kernelValues).add(
partitionIncrements.getRange(1,partitionAsVector.length)
.mul(partitionIncrements.getRange(1,partitionAsVector.length)
.mul(kernelSum.getRange(1, kernelSum.length))))); // depends on control dependency: [for], data = [none]
MSubMatrixSum=MSubMatrixSum.add(
partitionAsVector.getRange(0, partitionAsVector.length-1).neg().add(independentValues[i])
.mul(kernelValues).add(
partitionIncrements.getRange(1, partitionIncrements.length)
.mul(kernelSum.getRange(1, kernelSum.length)))); // depends on control dependency: [for], data = [none]
}
DoubleMatrix partitionIncrementMatrix= new DoubleMatrix(partition.getLength()-1,partition.getLength()-1);
DoubleMatrix matrixDefine= DoubleMatrix.ones(partition.getLength()-1);
for(int m=0;m<matrixDefine.length-1;m++) {
matrixDefine.put(m, 0); // depends on control dependency: [for], data = [m]
partitionIncrementMatrix.putColumn(m, matrixDefine.mul(partitionIncrements.get(m+1))); // depends on control dependency: [for], data = [m]
}
MSubMatrix=partitionIncrementMatrix.mulColumnVector(MSubMatrixSum);
MSubMatrix=MSubMatrix.add(MSubMatrix.transpose()).add(DoubleMatrix.diag(MSubDiagonal));
int[] rowColIndex =new int[partition.getLength()-1];
for(int n=0;n<rowColIndex.length;n++) {
rowColIndex[n]=n+1; // depends on control dependency: [for], data = [n]
}
M.put(0,0,M1_1.get(0));
M.put(rowColIndex, 0, MFirstCol);
M.put(0, rowColIndex, MFirstCol.transpose());
M.put(rowColIndex, rowColIndex, MSubMatrix);
return Solve.solve(M, R);
} } |
public class class_name {
public Set nonReservedVisibleGrantees(boolean andPublic) {
Set grantees = visibleGrantees();
GranteeManager gm = granteeManager;
grantees.remove(gm.dbaRole);
grantees.remove(GranteeManager.systemAuthorisation);
if (!andPublic) {
grantees.remove(gm.publicRole);
}
return grantees;
} } | public class class_name {
public Set nonReservedVisibleGrantees(boolean andPublic) {
Set grantees = visibleGrantees();
GranteeManager gm = granteeManager;
grantees.remove(gm.dbaRole);
grantees.remove(GranteeManager.systemAuthorisation);
if (!andPublic) {
grantees.remove(gm.publicRole); // depends on control dependency: [if], data = [none]
}
return grantees;
} } |
public class class_name {
private void decreaseComponentLevelMarkedForDeletion()
{
//The common case is this co
if (!_componentsMarkedForDeletion.get(_deletionLevel).isEmpty())
{
_componentsMarkedForDeletion.get(_deletionLevel).clear();
}
_deletionLevel--;
} } | public class class_name {
private void decreaseComponentLevelMarkedForDeletion()
{
//The common case is this co
if (!_componentsMarkedForDeletion.get(_deletionLevel).isEmpty())
{
_componentsMarkedForDeletion.get(_deletionLevel).clear(); // depends on control dependency: [if], data = [none]
}
_deletionLevel--;
} } |
public class class_name {
private List<ScmMaterial> filterScmMaterials() {
List<ScmMaterial> scmMaterials = new ArrayList<>();
for (Material material : this) {
if (material instanceof ScmMaterial) {
scmMaterials.add((ScmMaterial) material);
}
}
return scmMaterials;
} } | public class class_name {
private List<ScmMaterial> filterScmMaterials() {
List<ScmMaterial> scmMaterials = new ArrayList<>();
for (Material material : this) {
if (material instanceof ScmMaterial) {
scmMaterials.add((ScmMaterial) material); // depends on control dependency: [if], data = [none]
}
}
return scmMaterials;
} } |
public class class_name {
void checkMEs(JsMessagingEngine[] MEList) throws ResourceException
{
final String methodName = "checkMEs";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
{
SibTr.entry(this, TRACE, methodName, new Object[] { MEList });
}
// Filter out any non preferred MEs. User specified target data is used to perform this filter.
// If no target data is set then all the MEs are considered "preferred" for point to point and
// non durable pub sub, but none of them are considered preferred for durable pub sub (which has
// a preference for the durable subscription home)
JsMessagingEngine[] preferredMEs = _destinationStrategy.getPreferredLocalMEs(MEList);
// TODO: Can we wrapper the connect call if a try catch block, if engine is being reloaded then absorb the
// exception (trace a warning) and let us kick off a timer (if one is needed).
// Try to connect to the list of filtered MEs.
try {
connect(preferredMEs, _targetType, _targetSignificance, _target, true);
SibTr.info(TRACE, "TARGETTED_CONNECTION_SUCCESSFUL_CWSIV0556", new Object[] { ((MDBMessageEndpointFactory) _messageEndpointFactory).getActivationSpecId(),
_endpointConfiguration.getDestination().getDestinationName() });
} catch (Exception e) {
// After attempting to create connections check to see if we should continue to check for more connections
// or not. If we should then kick of a timer to try again after a user specified interval.
SibTr.warning(TRACE, SibTr.Suppressor.ALL_FOR_A_WHILE, "CONNECT_FAILED_CWSIV0782",
new Object[] { _endpointConfiguration.getDestination().getDestinationName(),
_endpointConfiguration.getBusName(),
((MDBMessageEndpointFactory) _messageEndpointFactory).getActivationSpecId(),
e });
if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled())
{
SibTr.debug(TRACE, "Failed to obtain a connection - retry after a set interval");
}
clearTimer();
// deactivate will close the connections
// The connection might be successful but session might fail due to authorization error
// Hence before retrying, old connection must be closed
deactivate();
kickOffTimer();
}
//its possible that there was no exception thrown and connection was not successfull
// in that case a check is made to see if an retry attempt is needed
if (_destinationStrategy.isTimerNeeded())
{
clearTimer();
kickOffTimer();
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
{
SibTr.exit(TRACE, methodName);
}
} } | public class class_name {
void checkMEs(JsMessagingEngine[] MEList) throws ResourceException
{
final String methodName = "checkMEs";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
{
SibTr.entry(this, TRACE, methodName, new Object[] { MEList });
}
// Filter out any non preferred MEs. User specified target data is used to perform this filter.
// If no target data is set then all the MEs are considered "preferred" for point to point and
// non durable pub sub, but none of them are considered preferred for durable pub sub (which has
// a preference for the durable subscription home)
JsMessagingEngine[] preferredMEs = _destinationStrategy.getPreferredLocalMEs(MEList);
// TODO: Can we wrapper the connect call if a try catch block, if engine is being reloaded then absorb the
// exception (trace a warning) and let us kick off a timer (if one is needed).
// Try to connect to the list of filtered MEs.
try {
connect(preferredMEs, _targetType, _targetSignificance, _target, true);
SibTr.info(TRACE, "TARGETTED_CONNECTION_SUCCESSFUL_CWSIV0556", new Object[] { ((MDBMessageEndpointFactory) _messageEndpointFactory).getActivationSpecId(),
_endpointConfiguration.getDestination().getDestinationName() });
} catch (Exception e) {
// After attempting to create connections check to see if we should continue to check for more connections
// or not. If we should then kick of a timer to try again after a user specified interval.
SibTr.warning(TRACE, SibTr.Suppressor.ALL_FOR_A_WHILE, "CONNECT_FAILED_CWSIV0782",
new Object[] { _endpointConfiguration.getDestination().getDestinationName(),
_endpointConfiguration.getBusName(),
((MDBMessageEndpointFactory) _messageEndpointFactory).getActivationSpecId(),
e });
if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled())
{
SibTr.debug(TRACE, "Failed to obtain a connection - retry after a set interval"); // depends on control dependency: [if], data = [none]
}
clearTimer();
// deactivate will close the connections
// The connection might be successful but session might fail due to authorization error
// Hence before retrying, old connection must be closed
deactivate();
kickOffTimer();
}
//its possible that there was no exception thrown and connection was not successfull
// in that case a check is made to see if an retry attempt is needed
if (_destinationStrategy.isTimerNeeded())
{
clearTimer();
kickOffTimer();
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
{
SibTr.exit(TRACE, methodName);
}
} } |
public class class_name {
@Override
public boolean isHttpSessionListener() {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
String s = httpSessListener + appNameForLogging;
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, "isHttpSessionListener", s);
}
return httpSessListener;
} } | public class class_name {
@Override
public boolean isHttpSessionListener() {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
String s = httpSessListener + appNameForLogging;
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, "isHttpSessionListener", s); // depends on control dependency: [if], data = [none]
}
return httpSessListener;
} } |
public class class_name {
@Nullable
private AttributeType.DataType<?> validateAndGetTargetDataType(GraqlCompute.Statistics.Value query) {
AttributeType.DataType<?> dataType = null;
for (Type type : targetTypes(query)) {
// check if the selected type is a attribute type
if (!type.isAttributeType()) throw GraqlQueryException.mustBeAttributeType(type.label());
AttributeType<?> attributeType = type.asAttributeType();
if (dataType == null) {
// check if the attribute type has data-type LONG or DOUBLE
dataType = attributeType.dataType();
if (!dataType.equals(AttributeType.DataType.LONG) && !dataType.equals(AttributeType.DataType.DOUBLE)) {
throw GraqlQueryException.attributeMustBeANumber(dataType, attributeType.label());
}
} else {
// check if all the attribute types have the same data-type
if (!dataType.equals(attributeType.dataType())) {
throw GraqlQueryException.attributesWithDifferentDataTypes(query.of());
}
}
}
return dataType;
} } | public class class_name {
@Nullable
private AttributeType.DataType<?> validateAndGetTargetDataType(GraqlCompute.Statistics.Value query) {
AttributeType.DataType<?> dataType = null;
for (Type type : targetTypes(query)) {
// check if the selected type is a attribute type
if (!type.isAttributeType()) throw GraqlQueryException.mustBeAttributeType(type.label());
AttributeType<?> attributeType = type.asAttributeType();
if (dataType == null) {
// check if the attribute type has data-type LONG or DOUBLE
dataType = attributeType.dataType(); // depends on control dependency: [if], data = [none]
if (!dataType.equals(AttributeType.DataType.LONG) && !dataType.equals(AttributeType.DataType.DOUBLE)) {
throw GraqlQueryException.attributeMustBeANumber(dataType, attributeType.label());
}
} else {
// check if all the attribute types have the same data-type
if (!dataType.equals(attributeType.dataType())) {
throw GraqlQueryException.attributesWithDifferentDataTypes(query.of());
}
}
}
return dataType;
} } |
public class class_name {
protected Token nextText() throws ScanException {
builder.setLength(0);
int i = position;
int l = input.length();
boolean escaped = false;
while (i < l) {
char c = input.charAt(i);
switch (c) {
case '\\':
if (escaped) {
builder.append('\\');
} else {
escaped = true;
}
break;
case '#':
case '$':
if (i+1 < l && input.charAt(i+1) == '{') {
if (escaped) {
builder.append(c);
} else {
return token(Symbol.TEXT, builder.toString(), i - position);
}
} else {
if (escaped) {
builder.append('\\');
}
builder.append(c);
}
escaped = false;
break;
default:
if (escaped) {
builder.append('\\');
}
builder.append(c);
escaped = false;
}
i++;
}
if (escaped) {
builder.append('\\');
}
return token(Symbol.TEXT, builder.toString(), i - position);
} } | public class class_name {
protected Token nextText() throws ScanException {
builder.setLength(0);
int i = position;
int l = input.length();
boolean escaped = false;
while (i < l) {
char c = input.charAt(i);
switch (c) {
case '\\':
if (escaped) {
builder.append('\\'); // depends on control dependency: [if], data = [none]
} else {
escaped = true; // depends on control dependency: [if], data = [none]
}
break;
case '#':
case '$':
if (i+1 < l && input.charAt(i+1) == '{') {
if (escaped) {
builder.append(c); // depends on control dependency: [if], data = [none]
} else {
return token(Symbol.TEXT, builder.toString(), i - position); // depends on control dependency: [if], data = [none]
}
} else {
if (escaped) {
builder.append('\\'); // depends on control dependency: [if], data = [none]
}
builder.append(c); // depends on control dependency: [if], data = [none]
}
escaped = false;
break;
default:
if (escaped) {
builder.append('\\'); // depends on control dependency: [if], data = [none]
}
builder.append(c);
escaped = false;
}
i++;
}
if (escaped) {
builder.append('\\');
}
return token(Symbol.TEXT, builder.toString(), i - position);
} } |
public class class_name {
private void sendToDiscriminators(VirtualConnection inVC, TCPReadRequestContext req, boolean errorOnRead) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "sendToDiscriminators");
}
boolean doAgain;
req.setJITAllocateSize(0); // JIT Allocate was on for the initial read,
// reset it
TCPConnLink conn = ((TCPReadRequestContextImpl) req).getTCPConnLink();
VirtualConnection vc = inVC;
do {
doAgain = false;
int state;
try {
state = tcpChannel.getDiscriminationProcess().discriminate(vc, req.getBuffers(), conn);
} catch (DiscriminationProcessException dpe) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, "Exception occurred while discriminating data received from client " + req.getInterface().getRemoteAddress() + " "
+ req.getInterface().getRemotePort());
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, new IOException("Discrimination failed " + dpe.getMessage()));
break;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Discrimination returned " + state);
}
if (state == DiscriminationProcess.SUCCESS) {
ConnectionReadyCallback cb = conn.getApplicationCallback();
// is cb is null, then connlink may have been destroyed by channel stop
// if so, nothing more needs to be done
if (cb != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Calling application callback.ready method");
}
cb.ready(vc);
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "No application callback found, closing connection");
}
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, null);
}
} else if (state == DiscriminationProcess.AGAIN) {
if (errorOnRead) { // error on first read, don't retry
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, "First read timed out, and more than one discriminator asked for more data" + req.getInterface().getRemoteAddress() + " "
+ req.getInterface().getRemotePort());
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, null);
} else if (requestFull(req)) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, "Discrimination failed, no one claimed data even after 1 complete buffer presented - probably garbage passed in"
+ req.getInterface().getRemoteAddress()
+ " " + req.getInterface().getRemotePort());
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, null);
} else {
vc = req.read(1, this, false, TCPRequestContext.USE_CHANNEL_TIMEOUT);
if (vc != null) {
doAgain = true;
}
}
} else { // FAILURE
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, "Error occurred while discriminating data received from client " + req.getInterface().getRemoteAddress() + " "
+ req.getInterface().getRemotePort());
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, null);
}
} while (doAgain);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "sendToDiscriminators");
}
} } | public class class_name {
private void sendToDiscriminators(VirtualConnection inVC, TCPReadRequestContext req, boolean errorOnRead) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "sendToDiscriminators"); // depends on control dependency: [if], data = [none]
}
boolean doAgain;
req.setJITAllocateSize(0); // JIT Allocate was on for the initial read,
// reset it
TCPConnLink conn = ((TCPReadRequestContextImpl) req).getTCPConnLink();
VirtualConnection vc = inVC;
do {
doAgain = false;
int state;
try {
state = tcpChannel.getDiscriminationProcess().discriminate(vc, req.getBuffers(), conn); // depends on control dependency: [try], data = [none]
} catch (DiscriminationProcessException dpe) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, "Exception occurred while discriminating data received from client " + req.getInterface().getRemoteAddress() + " "
+ req.getInterface().getRemotePort());
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, new IOException("Discrimination failed " + dpe.getMessage()));
break;
} // depends on control dependency: [catch], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Discrimination returned " + state); // depends on control dependency: [if], data = [none]
}
if (state == DiscriminationProcess.SUCCESS) {
ConnectionReadyCallback cb = conn.getApplicationCallback();
// is cb is null, then connlink may have been destroyed by channel stop
// if so, nothing more needs to be done
if (cb != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Calling application callback.ready method"); // depends on control dependency: [if], data = [none]
}
cb.ready(vc); // depends on control dependency: [if], data = [none]
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "No application callback found, closing connection"); // depends on control dependency: [if], data = [none]
}
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, null); // depends on control dependency: [if], data = [null)]
}
} else if (state == DiscriminationProcess.AGAIN) {
if (errorOnRead) { // error on first read, don't retry
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, "First read timed out, and more than one discriminator asked for more data" + req.getInterface().getRemoteAddress() + " "
+ req.getInterface().getRemotePort());
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, null); // depends on control dependency: [if], data = [none]
} else if (requestFull(req)) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, "Discrimination failed, no one claimed data even after 1 complete buffer presented - probably garbage passed in"
+ req.getInterface().getRemoteAddress()
+ " " + req.getInterface().getRemotePort());
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, null); // depends on control dependency: [if], data = [none]
} else {
vc = req.read(1, this, false, TCPRequestContext.USE_CHANNEL_TIMEOUT); // depends on control dependency: [if], data = [none]
if (vc != null) {
doAgain = true; // depends on control dependency: [if], data = [none]
}
}
} else { // FAILURE
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, "Error occurred while discriminating data received from client " + req.getInterface().getRemoteAddress() + " "
+ req.getInterface().getRemotePort());
((TCPReadRequestContextImpl) req).getTCPConnLink().close(vc, null); // depends on control dependency: [if], data = [none]
}
} while (doAgain);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "sendToDiscriminators"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void setupNotifications() {
Log.i(TAG, "Enabling OAD notifications");
boolean oadIdentifyNotifying = enableNotifyForChar(oadIdentify);
boolean oadBlockNotifying = enableNotifyForChar(oadBlock);
if (oadIdentifyNotifying && oadBlockNotifying) {
Log.i(TAG, "Enable notifications successful");
} else {
Log.e(TAG, "Error while enabling notifications");
fail(BeanError.ENABLE_OAD_NOTIFY_FAILED);
}
} } | public class class_name {
private void setupNotifications() {
Log.i(TAG, "Enabling OAD notifications");
boolean oadIdentifyNotifying = enableNotifyForChar(oadIdentify);
boolean oadBlockNotifying = enableNotifyForChar(oadBlock);
if (oadIdentifyNotifying && oadBlockNotifying) {
Log.i(TAG, "Enable notifications successful"); // depends on control dependency: [if], data = [none]
} else {
Log.e(TAG, "Error while enabling notifications"); // depends on control dependency: [if], data = [none]
fail(BeanError.ENABLE_OAD_NOTIFY_FAILED); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void connectDatabase()
{
try
{
_con = DriverManager.getConnection(_url, _userName, _password);
}
catch(SQLException e)
{
log.warn("UserRealm " + getName()
+ " could not connect to database; will try later", e);
}
} } | public class class_name {
public void connectDatabase()
{
try
{
_con = DriverManager.getConnection(_url, _userName, _password); // depends on control dependency: [try], data = [none]
}
catch(SQLException e)
{
log.warn("UserRealm " + getName()
+ " could not connect to database; will try later", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static INDArray lte(INDArray x, INDArray y, INDArray z, int... dimensions) {
if(dimensions == null || dimensions.length == 0) {
validateShapesNoDimCase(x,y,z);
return Nd4j.getExecutioner().exec(new OldLessThanOrEqual(x,y,z));
}
return Nd4j.getExecutioner().exec(new BroadcastLessThanOrEqual(x,y,z,dimensions));
} } | public class class_name {
public static INDArray lte(INDArray x, INDArray y, INDArray z, int... dimensions) {
if(dimensions == null || dimensions.length == 0) {
validateShapesNoDimCase(x,y,z); // depends on control dependency: [if], data = [none]
return Nd4j.getExecutioner().exec(new OldLessThanOrEqual(x,y,z)); // depends on control dependency: [if], data = [none]
}
return Nd4j.getExecutioner().exec(new BroadcastLessThanOrEqual(x,y,z,dimensions));
} } |
public class class_name {
@Override
public String purgeObject(String pid, String logMessage, boolean force) {
LOG.debug("start: purgeObject, {}", pid);
assertInitialized();
try {
MessageContext ctx = context.getMessageContext();
return DateUtility.convertDateToString(m_management
.purgeObject(ReadOnlyContext.getSoapContext(ctx),
pid,
logMessage));
} catch (Throwable th) {
LOG.error("Error purging object", th);
throw CXFUtility.getFault(th);
} finally {
LOG.debug("end: purgeObject, {}", pid);
}
} } | public class class_name {
@Override
public String purgeObject(String pid, String logMessage, boolean force) {
LOG.debug("start: purgeObject, {}", pid);
assertInitialized();
try {
MessageContext ctx = context.getMessageContext();
return DateUtility.convertDateToString(m_management
.purgeObject(ReadOnlyContext.getSoapContext(ctx),
pid,
logMessage)); // depends on control dependency: [try], data = [none]
} catch (Throwable th) {
LOG.error("Error purging object", th);
throw CXFUtility.getFault(th);
} finally { // depends on control dependency: [catch], data = [none]
LOG.debug("end: purgeObject, {}", pid);
}
} } |
public class class_name {
public boolean containsVariableWithName(String name) {
for (Token token : this) {
if (token instanceof VariableToken && token.getText().equals(name)) {
return true;
}
}
return false;
} } | public class class_name {
public boolean containsVariableWithName(String name) {
for (Token token : this) {
if (token instanceof VariableToken && token.getText().equals(name)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
private MethodSymbol getFirstOverride(Symbol sym, Types types) {
ClassSymbol owner = sym.enclClass();
if (ignoreInterfaceOverrides && owner.isInterface()) {
// pretend the method does not override anything
return null;
}
for (Type s : types.closure(owner.type)) {
if (s == owner.type) {
continue;
}
for (Symbol m : s.tsym.members().getSymbolsByName(sym.name)) {
if (!(m instanceof MethodSymbol)) {
continue;
}
MethodSymbol msym = (MethodSymbol) m;
if (msym.isStatic()) {
continue;
}
if (sym.overrides(msym, owner, types, /* checkResult= */ false)) {
return msym;
}
}
}
return null;
} } | public class class_name {
private MethodSymbol getFirstOverride(Symbol sym, Types types) {
ClassSymbol owner = sym.enclClass();
if (ignoreInterfaceOverrides && owner.isInterface()) {
// pretend the method does not override anything
return null; // depends on control dependency: [if], data = [none]
}
for (Type s : types.closure(owner.type)) {
if (s == owner.type) {
continue;
}
for (Symbol m : s.tsym.members().getSymbolsByName(sym.name)) {
if (!(m instanceof MethodSymbol)) {
continue;
}
MethodSymbol msym = (MethodSymbol) m;
if (msym.isStatic()) {
continue;
}
if (sym.overrides(msym, owner, types, /* checkResult= */ false)) {
return msym; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public GetRestApisResult withItems(RestApi... items) {
if (this.items == null) {
setItems(new java.util.ArrayList<RestApi>(items.length));
}
for (RestApi ele : items) {
this.items.add(ele);
}
return this;
} } | public class class_name {
public GetRestApisResult withItems(RestApi... items) {
if (this.items == null) {
setItems(new java.util.ArrayList<RestApi>(items.length)); // depends on control dependency: [if], data = [none]
}
for (RestApi ele : items) {
this.items.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public final List<RegisteredService> loadServices() {
logger.info("Loading Registered Services from: [ {} ]...", this.servicesConfigFile);
final List<RegisteredService> resolvedServices = new ArrayList<RegisteredService>();
try {
final Map<String, List> m = unmarshalServicesRegistryResourceIntoMap();
if (m != null) {
final Iterator<Map> i = m.get(SERVICES_KEY).iterator();
while (i.hasNext()) {
final Map<?, ?> record = i.next();
final String svcId = ((String) record.get(SERVICES_ID_KEY));
final RegisteredService svc = getRegisteredServiceInstance(svcId);
if (svc != null) {
resolvedServices.add(this.objectMapper.convertValue(record, svc.getClass()));
logger.debug("Unmarshaled {}: {}", svc.getClass().getSimpleName(), record);
}
}
synchronized (this.mutexMonitor) {
this.delegateServiceRegistryDao.setRegisteredServices(resolvedServices);
}
}
} catch (final Throwable e) {
throw new RuntimeException(e);
}
return resolvedServices;
} } | public class class_name {
@SuppressWarnings("unchecked")
public final List<RegisteredService> loadServices() {
logger.info("Loading Registered Services from: [ {} ]...", this.servicesConfigFile);
final List<RegisteredService> resolvedServices = new ArrayList<RegisteredService>();
try {
final Map<String, List> m = unmarshalServicesRegistryResourceIntoMap();
if (m != null) {
final Iterator<Map> i = m.get(SERVICES_KEY).iterator();
while (i.hasNext()) {
final Map<?, ?> record = i.next();
final String svcId = ((String) record.get(SERVICES_ID_KEY));
final RegisteredService svc = getRegisteredServiceInstance(svcId);
if (svc != null) {
resolvedServices.add(this.objectMapper.convertValue(record, svc.getClass())); // depends on control dependency: [if], data = [none]
logger.debug("Unmarshaled {}: {}", svc.getClass().getSimpleName(), record); // depends on control dependency: [if], data = [none]
}
}
synchronized (this.mutexMonitor) { // depends on control dependency: [if], data = [none]
this.delegateServiceRegistryDao.setRegisteredServices(resolvedServices);
}
}
} catch (final Throwable e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
return resolvedServices;
} } |
public class class_name {
public static String buildGlueExpression(List<Column> partitionKeys, List<String> partitionValues)
{
if (partitionValues == null || partitionValues.isEmpty()) {
return null;
}
if (partitionKeys == null || partitionValues.size() != partitionKeys.size()) {
throw new PrestoException(HIVE_METASTORE_ERROR, "Incorrect number of partition values: " + partitionValues);
}
List<String> predicates = new LinkedList<>();
for (int i = 0; i < partitionValues.size(); i++) {
if (!Strings.isNullOrEmpty(partitionValues.get(i))) {
predicates.add(buildPredicate(partitionKeys.get(i), partitionValues.get(i)));
}
}
return JOINER.join(predicates);
} } | public class class_name {
public static String buildGlueExpression(List<Column> partitionKeys, List<String> partitionValues)
{
if (partitionValues == null || partitionValues.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
if (partitionKeys == null || partitionValues.size() != partitionKeys.size()) {
throw new PrestoException(HIVE_METASTORE_ERROR, "Incorrect number of partition values: " + partitionValues);
}
List<String> predicates = new LinkedList<>();
for (int i = 0; i < partitionValues.size(); i++) {
if (!Strings.isNullOrEmpty(partitionValues.get(i))) {
predicates.add(buildPredicate(partitionKeys.get(i), partitionValues.get(i))); // depends on control dependency: [if], data = [none]
}
}
return JOINER.join(predicates);
} } |
public class class_name {
private EREFiller toFiller(final Element xml, final String docid) {
final String id = generateID(XMLUtils.requiredAttribute(xml, "id"), docid);
final String type = XMLUtils.requiredAttribute(xml, "type");
final int extentStart = XMLUtils.requiredIntegerAttribute(xml, "offset");
final int extentEnd = extentStart + XMLUtils.requiredIntegerAttribute(xml, "length") - 1;
final String text = xml.getTextContent();
final ERESpan span = ERESpan.from(extentStart, extentEnd, text);
final EREFiller ereFiller;
if (xml.hasAttribute(NORMALIZED_TIME_ATTR)) {
ereFiller = EREFiller.fromTime(id, type, xml.getAttribute(NORMALIZED_TIME_ATTR), span);
} else {
ereFiller = EREFiller.from(id, type, span);
}
idMap.put(id, ereFiller);
return ereFiller;
} } | public class class_name {
private EREFiller toFiller(final Element xml, final String docid) {
final String id = generateID(XMLUtils.requiredAttribute(xml, "id"), docid);
final String type = XMLUtils.requiredAttribute(xml, "type");
final int extentStart = XMLUtils.requiredIntegerAttribute(xml, "offset");
final int extentEnd = extentStart + XMLUtils.requiredIntegerAttribute(xml, "length") - 1;
final String text = xml.getTextContent();
final ERESpan span = ERESpan.from(extentStart, extentEnd, text);
final EREFiller ereFiller;
if (xml.hasAttribute(NORMALIZED_TIME_ATTR)) {
ereFiller = EREFiller.fromTime(id, type, xml.getAttribute(NORMALIZED_TIME_ATTR), span); // depends on control dependency: [if], data = [none]
} else {
ereFiller = EREFiller.from(id, type, span); // depends on control dependency: [if], data = [none]
}
idMap.put(id, ereFiller);
return ereFiller;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static void executeCommand(String[] args) throws IOException {
OptionParser parser = getParser();
// declare parameters
List<String> metaKeys = null;
String url = null;
String dir = null;
List<Integer> nodeIds = null;
Boolean allNodes = true;
Boolean verbose = false;
// parse command-line input
args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET);
OptionSet options = parser.parse(args);
if(options.has(AdminParserUtils.OPT_HELP)) {
printHelp(System.out);
return;
}
// check required options and/or conflicting options
AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET);
AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);
AdminParserUtils.checkOptional(options,
AdminParserUtils.OPT_NODE,
AdminParserUtils.OPT_ALL_NODES);
// load parameters
metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);
url = (String) options.valueOf(AdminParserUtils.OPT_URL);
if(options.has(AdminParserUtils.OPT_DIR)) {
dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);
}
if(options.has(AdminParserUtils.OPT_NODE)) {
nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);
allNodes = false;
}
if(options.has(OPT_VERBOSE)) {
verbose = true;
}
// execute command
File directory = AdminToolUtils.createDir(dir);
AdminClient adminClient = AdminToolUtils.getAdminClient(url);
if(allNodes) {
nodeIds = AdminToolUtils.getAllNodeIds(adminClient);
}
if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {
metaKeys = Lists.newArrayList();
for(Object key: MetadataStore.METADATA_KEYS) {
metaKeys.add((String) key);
}
}
doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);
} } | public class class_name {
@SuppressWarnings("unchecked")
public static void executeCommand(String[] args) throws IOException {
OptionParser parser = getParser();
// declare parameters
List<String> metaKeys = null;
String url = null;
String dir = null;
List<Integer> nodeIds = null;
Boolean allNodes = true;
Boolean verbose = false;
// parse command-line input
args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET);
OptionSet options = parser.parse(args);
if(options.has(AdminParserUtils.OPT_HELP)) {
printHelp(System.out);
return;
}
// check required options and/or conflicting options
AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET);
AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);
AdminParserUtils.checkOptional(options,
AdminParserUtils.OPT_NODE,
AdminParserUtils.OPT_ALL_NODES);
// load parameters
metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);
url = (String) options.valueOf(AdminParserUtils.OPT_URL);
if(options.has(AdminParserUtils.OPT_DIR)) {
dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);
}
if(options.has(AdminParserUtils.OPT_NODE)) {
nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);
allNodes = false;
}
if(options.has(OPT_VERBOSE)) {
verbose = true;
}
// execute command
File directory = AdminToolUtils.createDir(dir);
AdminClient adminClient = AdminToolUtils.getAdminClient(url);
if(allNodes) {
nodeIds = AdminToolUtils.getAllNodeIds(adminClient);
}
if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {
metaKeys = Lists.newArrayList();
for(Object key: MetadataStore.METADATA_KEYS) {
metaKeys.add((String) key); // depends on control dependency: [for], data = [key]
}
}
doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);
} } |
public class class_name {
public void remapContainer(@Observes BeforeSetup event, CubeRegistry cubeRegistry,
ContainerRegistry containerRegistry) throws InstantiationException, IllegalAccessException {
Container container = ContainerUtil.getContainerByDeployableContainer(containerRegistry,
event.getDeployableContainer());
if (container == null) {
return;
}
Cube<?> cube = cubeRegistry.getCube(ContainerUtil.getCubeIDForContainer(container));
if (cube == null) {
return; // No Cube found matching Container name, not managed by Cube
}
HasPortBindings bindings = cube.getMetadata(HasPortBindings.class);
if (bindings == null) {
return;
}
ContainerDef containerConfiguration = container.getContainerConfiguration();
//Get the port property
List<String> portPropertiesFromArquillianConfigurationFile =
filterArquillianConfigurationPropertiesByPortAttribute(containerConfiguration);
//Get the AddressProperty property
List<String> addressPropertiesFromArquillianConfigurationFile =
filterArquillianConfigurationPropertiesByAddressAttribute(containerConfiguration);
Class<?> configurationClass = container.getDeployableContainer().getConfigurationClass();
//Get the port property
List<PropertyDescriptor> configurationClassPortFields =
filterConfigurationClassPropertiesByPortAttribute(configurationClass);
//Get the Address property
List<PropertyDescriptor> configurationClassAddressFields =
filterConfigurationClassPropertiesByAddressAttribute(configurationClass);
Object newConfigurationInstance = configurationClass.newInstance();
for (PropertyDescriptor configurationClassPortField : configurationClassPortFields) {
int containerPort = getDefaultPortFromConfigurationInstance(newConfigurationInstance,
configurationClass, configurationClassPortField);
mappingForPort = bindings.getMappedAddress(containerPort);
if (!portPropertiesFromArquillianConfigurationFile.contains(configurationClassPortField.getName()) && (
configurationClassPortField.getPropertyType().equals(Integer.class)
|| configurationClassPortField.getPropertyType().equals(int.class))) {
// This means that port has not configured in arquillian.xml and it will use default value.
// In this case is when remapping should be activated to adequate the situation according to
// Arquillian Cube exposed ports.
if (mappingForPort != null) {
containerConfiguration.overrideProperty(configurationClassPortField.getName(),
Integer.toString(mappingForPort.getPort()));
}
}
}
for (PropertyDescriptor configurationClassAddressField : configurationClassAddressFields) {
if (!addressPropertiesFromArquillianConfigurationFile.contains(configurationClassAddressField.getName()) && (
configurationClassAddressField.getPropertyType().equals(String.class)
|| configurationClassAddressField.getPropertyType().equals(String.class))) {
// If a property called portForwardBindAddress on openshift qualifier on arquillian.xml exists it will overrides the
// arquillian default|defined managementAddress with the IP address given on this property.
if (mappingForPort != null) {
containerConfiguration.overrideProperty(configurationClassAddressField.getName(),
mappingForPort.getIP());
}
}
}
} } | public class class_name {
public void remapContainer(@Observes BeforeSetup event, CubeRegistry cubeRegistry,
ContainerRegistry containerRegistry) throws InstantiationException, IllegalAccessException {
Container container = ContainerUtil.getContainerByDeployableContainer(containerRegistry,
event.getDeployableContainer());
if (container == null) {
return;
}
Cube<?> cube = cubeRegistry.getCube(ContainerUtil.getCubeIDForContainer(container));
if (cube == null) {
return; // No Cube found matching Container name, not managed by Cube
}
HasPortBindings bindings = cube.getMetadata(HasPortBindings.class);
if (bindings == null) {
return;
}
ContainerDef containerConfiguration = container.getContainerConfiguration();
//Get the port property
List<String> portPropertiesFromArquillianConfigurationFile =
filterArquillianConfigurationPropertiesByPortAttribute(containerConfiguration);
//Get the AddressProperty property
List<String> addressPropertiesFromArquillianConfigurationFile =
filterArquillianConfigurationPropertiesByAddressAttribute(containerConfiguration);
Class<?> configurationClass = container.getDeployableContainer().getConfigurationClass();
//Get the port property
List<PropertyDescriptor> configurationClassPortFields =
filterConfigurationClassPropertiesByPortAttribute(configurationClass);
//Get the Address property
List<PropertyDescriptor> configurationClassAddressFields =
filterConfigurationClassPropertiesByAddressAttribute(configurationClass);
Object newConfigurationInstance = configurationClass.newInstance();
for (PropertyDescriptor configurationClassPortField : configurationClassPortFields) {
int containerPort = getDefaultPortFromConfigurationInstance(newConfigurationInstance,
configurationClass, configurationClassPortField);
mappingForPort = bindings.getMappedAddress(containerPort);
if (!portPropertiesFromArquillianConfigurationFile.contains(configurationClassPortField.getName()) && (
configurationClassPortField.getPropertyType().equals(Integer.class)
|| configurationClassPortField.getPropertyType().equals(int.class))) {
// This means that port has not configured in arquillian.xml and it will use default value.
// In this case is when remapping should be activated to adequate the situation according to
// Arquillian Cube exposed ports.
if (mappingForPort != null) {
containerConfiguration.overrideProperty(configurationClassPortField.getName(),
Integer.toString(mappingForPort.getPort())); // depends on control dependency: [if], data = [none]
}
}
}
for (PropertyDescriptor configurationClassAddressField : configurationClassAddressFields) {
if (!addressPropertiesFromArquillianConfigurationFile.contains(configurationClassAddressField.getName()) && (
configurationClassAddressField.getPropertyType().equals(String.class)
|| configurationClassAddressField.getPropertyType().equals(String.class))) {
// If a property called portForwardBindAddress on openshift qualifier on arquillian.xml exists it will overrides the
// arquillian default|defined managementAddress with the IP address given on this property.
if (mappingForPort != null) {
containerConfiguration.overrideProperty(configurationClassAddressField.getName(),
mappingForPort.getIP()); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public synchronized void backupTrxLog(Object objMessage)
{
try {
this.getWriter().writeObject(objMessage);
m_lastWrite = System.currentTimeMillis();
} catch (IOException e) {
e.printStackTrace();
}
} } | public class class_name {
public synchronized void backupTrxLog(Object objMessage)
{
try {
this.getWriter().writeObject(objMessage); // depends on control dependency: [try], data = [none]
m_lastWrite = System.currentTimeMillis(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Observable<ServiceResponse<Page<P2SVpnServerConfigurationInner>>> listByVirtualWanNextWithServiceResponseAsync(final String nextPageLink) {
return listByVirtualWanNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<P2SVpnServerConfigurationInner>>, Observable<ServiceResponse<Page<P2SVpnServerConfigurationInner>>>>() {
@Override
public Observable<ServiceResponse<Page<P2SVpnServerConfigurationInner>>> call(ServiceResponse<Page<P2SVpnServerConfigurationInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByVirtualWanNextWithServiceResponseAsync(nextPageLink));
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<P2SVpnServerConfigurationInner>>> listByVirtualWanNextWithServiceResponseAsync(final String nextPageLink) {
return listByVirtualWanNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<P2SVpnServerConfigurationInner>>, Observable<ServiceResponse<Page<P2SVpnServerConfigurationInner>>>>() {
@Override
public Observable<ServiceResponse<Page<P2SVpnServerConfigurationInner>>> call(ServiceResponse<Page<P2SVpnServerConfigurationInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page); // depends on control dependency: [if], data = [none]
}
return Observable.just(page).concatWith(listByVirtualWanNextWithServiceResponseAsync(nextPageLink));
}
});
} } |
public class class_name {
public void run() {
System.out.println(HORIZONTAL_RULE);
System.out.println(" Getting initial database partition count");
long partitionCount = 0;
try {
VoltTable results[] = client.callProcedure("@GetPartitionKeys", "integer").getResults();
partitionCount = results[0].getRowCount();
updatePartitionCount(partitionCount);
} catch (IOException | ProcCallException e) {
System.out.print(HORIZONTAL_RULE);
System.out.println("Could not get partition information. Processing terminated. Error:" + e.getMessage());
e.printStackTrace();
shutdown();
System.out.print(HORIZONTAL_RULE);
return;
}
System.out.println(" Initial database partition count: " + partitionCount);
System.out.print(HORIZONTAL_RULE);
System.out.println(" Starting Processing");
System.out.println(HORIZONTAL_RULE);
// Print periodic stats/analysis to the console
scheduler.scheduleWithFixedDelay(reporter,
config.displayinterval,
config.displayinterval,
TimeUnit.SECONDS);
if (!config.inline) {
// Delete data as often as need be
// -- This will resubmit itself at varying rates according to insert load
scheduler.execute(deleter);
}
// Start tracking changes to the maximum value after a 5 second delay to
// let things settle a bit. Then check up to 100 times per second.
scheduler.scheduleWithFixedDelay(maxTracker,
5000,
10,
TimeUnit.MILLISECONDS);
// Run the benchmark loop for the requested duration
// The throughput may be throttled depending on client configuration
inserter.run();
System.out.print(HORIZONTAL_RULE);
System.out.println(" Processing Complete");
System.out.println(HORIZONTAL_RULE);
shutdown();
} } | public class class_name {
public void run() {
System.out.println(HORIZONTAL_RULE);
System.out.println(" Getting initial database partition count");
long partitionCount = 0;
try {
VoltTable results[] = client.callProcedure("@GetPartitionKeys", "integer").getResults();
partitionCount = results[0].getRowCount(); // depends on control dependency: [try], data = [none]
updatePartitionCount(partitionCount); // depends on control dependency: [try], data = [none]
} catch (IOException | ProcCallException e) {
System.out.print(HORIZONTAL_RULE);
System.out.println("Could not get partition information. Processing terminated. Error:" + e.getMessage());
e.printStackTrace();
shutdown();
System.out.print(HORIZONTAL_RULE);
return;
} // depends on control dependency: [catch], data = [none]
System.out.println(" Initial database partition count: " + partitionCount);
System.out.print(HORIZONTAL_RULE);
System.out.println(" Starting Processing");
System.out.println(HORIZONTAL_RULE);
// Print periodic stats/analysis to the console
scheduler.scheduleWithFixedDelay(reporter,
config.displayinterval,
config.displayinterval,
TimeUnit.SECONDS);
if (!config.inline) {
// Delete data as often as need be
// -- This will resubmit itself at varying rates according to insert load
scheduler.execute(deleter); // depends on control dependency: [if], data = [none]
}
// Start tracking changes to the maximum value after a 5 second delay to
// let things settle a bit. Then check up to 100 times per second.
scheduler.scheduleWithFixedDelay(maxTracker,
5000,
10,
TimeUnit.MILLISECONDS);
// Run the benchmark loop for the requested duration
// The throughput may be throttled depending on client configuration
inserter.run();
System.out.print(HORIZONTAL_RULE);
System.out.println(" Processing Complete");
System.out.println(HORIZONTAL_RULE);
shutdown();
} } |
public class class_name {
@Nullable
public URL getResource (final String name)
{
URL ret = null;
if (m_aBestCandidate != null)
{
ret = m_aBestCandidate.getResource (name);
if (ret != null)
return ret;
m_aBestCandidate = null;
}
IClassLoadHelper aLoadHelper = null;
final Iterator <IClassLoadHelper> iter = m_aLoadHelpers.iterator ();
while (iter.hasNext ())
{
aLoadHelper = iter.next ();
ret = aLoadHelper.getResource (name);
if (ret != null)
break;
}
m_aBestCandidate = aLoadHelper;
return ret;
} } | public class class_name {
@Nullable
public URL getResource (final String name)
{
URL ret = null;
if (m_aBestCandidate != null)
{
ret = m_aBestCandidate.getResource (name); // depends on control dependency: [if], data = [none]
if (ret != null)
return ret;
m_aBestCandidate = null; // depends on control dependency: [if], data = [none]
}
IClassLoadHelper aLoadHelper = null;
final Iterator <IClassLoadHelper> iter = m_aLoadHelpers.iterator ();
while (iter.hasNext ())
{
aLoadHelper = iter.next (); // depends on control dependency: [while], data = [none]
ret = aLoadHelper.getResource (name); // depends on control dependency: [while], data = [none]
if (ret != null)
break;
}
m_aBestCandidate = aLoadHelper;
return ret;
} } |
public class class_name {
public static Sort sorts( Sort... sorts ) {
if ( sorts == null || sorts.length == 0 ) {
return null;
}
Sort main = sorts[ 0 ];
for ( int index = 1; index < sorts.length; index++ ) {
main.then( sorts[ index ] );
}
return main;
} } | public class class_name {
public static Sort sorts( Sort... sorts ) {
if ( sorts == null || sorts.length == 0 ) {
return null; // depends on control dependency: [if], data = [none]
}
Sort main = sorts[ 0 ];
for ( int index = 1; index < sorts.length; index++ ) {
main.then( sorts[ index ] ); // depends on control dependency: [for], data = [index]
}
return main;
} } |
public class class_name {
private void loadAllWithAsyncLoader(final CacheOperationCompletionListener _listener, final Set<K> _keysToLoad) {
final AtomicInteger _countDown = new AtomicInteger(_keysToLoad.size());
EntryAction.ActionCompletedCallback cb = new EntryAction.ActionCompletedCallback() {
@Override
public void entryActionCompleted(final EntryAction ea) {
int v = _countDown.decrementAndGet();
if (v == 0) {
_listener.onCompleted();
return;
}
}
};
for (K k : _keysToLoad) {
final K key = k;
executeAsync(key, null, SPEC.GET, cb);
}
} } | public class class_name {
private void loadAllWithAsyncLoader(final CacheOperationCompletionListener _listener, final Set<K> _keysToLoad) {
final AtomicInteger _countDown = new AtomicInteger(_keysToLoad.size());
EntryAction.ActionCompletedCallback cb = new EntryAction.ActionCompletedCallback() {
@Override
public void entryActionCompleted(final EntryAction ea) {
int v = _countDown.decrementAndGet();
if (v == 0) {
_listener.onCompleted(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
};
for (K k : _keysToLoad) {
final K key = k;
executeAsync(key, null, SPEC.GET, cb); // depends on control dependency: [for], data = [k]
}
} } |
public class class_name {
public boolean isValid(HistoricDate date) {
if ((date == null) || this.isOutOfRange(date)) {
return false;
}
Calculus algorithm = this.getAlgorithm(date);
return ((algorithm != null) && algorithm.isValid(date));
} } | public class class_name {
public boolean isValid(HistoricDate date) {
if ((date == null) || this.isOutOfRange(date)) {
return false; // depends on control dependency: [if], data = [none]
}
Calculus algorithm = this.getAlgorithm(date);
return ((algorithm != null) && algorithm.isValid(date));
} } |
public class class_name {
public void releasePayload(Throwable cause) {
final Payload payload = payloadReference.get();
if (payload != null) {
payload.release(cause);
payloadReference.set(null);
}
} } | public class class_name {
public void releasePayload(Throwable cause) {
final Payload payload = payloadReference.get();
if (payload != null) {
payload.release(cause); // depends on control dependency: [if], data = [none]
payloadReference.set(null); // depends on control dependency: [if], data = [null)]
}
} } |
public class class_name {
public static String getPackageName(Class< ? > clazz,
Package pkg) {
String pkgName = "";
if ( pkg == null ) {
int index = clazz.getName().lastIndexOf( '.' );
if ( index != -1 ) pkgName = clazz.getName().substring( 0,
index );
} else {
pkgName = pkg.getName();
}
return pkgName;
} } | public class class_name {
public static String getPackageName(Class< ? > clazz,
Package pkg) {
String pkgName = "";
if ( pkg == null ) {
int index = clazz.getName().lastIndexOf( '.' );
if ( index != -1 ) pkgName = clazz.getName().substring( 0,
index );
} else {
pkgName = pkg.getName(); // depends on control dependency: [if], data = [none]
}
return pkgName;
} } |
public class class_name {
protected void setAdditionalAttributes(@Nullable HtmlElement<?> mediaElement, @NotNull Media media) {
if (mediaElement == null) {
return;
}
MediaArgs mediaArgs = media.getMediaRequest().getMediaArgs();
for (Entry<String, Object> entry : mediaArgs.getProperties().entrySet()) {
if (StringUtils.equals(entry.getKey(), MediaNameConstants.PROP_CSS_CLASS)) {
mediaElement.addCssClass(entry.getValue().toString());
}
else {
mediaElement.setAttribute(entry.getKey(), entry.getValue().toString());
}
}
} } | public class class_name {
protected void setAdditionalAttributes(@Nullable HtmlElement<?> mediaElement, @NotNull Media media) {
if (mediaElement == null) {
return; // depends on control dependency: [if], data = [none]
}
MediaArgs mediaArgs = media.getMediaRequest().getMediaArgs();
for (Entry<String, Object> entry : mediaArgs.getProperties().entrySet()) {
if (StringUtils.equals(entry.getKey(), MediaNameConstants.PROP_CSS_CLASS)) {
mediaElement.addCssClass(entry.getValue().toString()); // depends on control dependency: [if], data = [none]
}
else {
mediaElement.setAttribute(entry.getKey(), entry.getValue().toString()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void marshall(BuiltinSlotTypeMetadata builtinSlotTypeMetadata, ProtocolMarshaller protocolMarshaller) {
if (builtinSlotTypeMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(builtinSlotTypeMetadata.getSignature(), SIGNATURE_BINDING);
protocolMarshaller.marshall(builtinSlotTypeMetadata.getSupportedLocales(), SUPPORTEDLOCALES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BuiltinSlotTypeMetadata builtinSlotTypeMetadata, ProtocolMarshaller protocolMarshaller) {
if (builtinSlotTypeMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(builtinSlotTypeMetadata.getSignature(), SIGNATURE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(builtinSlotTypeMetadata.getSupportedLocales(), SUPPORTEDLOCALES_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public int write(byte[] b, int off, int len) {
if (isMutable) {
return sourceDataLine.write(b, off, len);
} else {
if (isMutedFromSystem) {
byte[] newArr = new byte[b.length];
return sourceDataLine.write(newArr, off, len);
} else {
return sourceDataLine.write(b, off, len);
}
}
} } | public class class_name {
@Override
public int write(byte[] b, int off, int len) {
if (isMutable) {
return sourceDataLine.write(b, off, len); // depends on control dependency: [if], data = [none]
} else {
if (isMutedFromSystem) {
byte[] newArr = new byte[b.length];
return sourceDataLine.write(newArr, off, len); // depends on control dependency: [if], data = [none]
} else {
return sourceDataLine.write(b, off, len); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static void internalSetAndInitRequestScope (@Nonnull final IRequestScope aRequestScope)
{
ValueEnforcer.notNull (aRequestScope, "RequestScope");
ValueEnforcer.isTrue (ScopeManager::isGlobalScopePresent,
"No global context present! May be the global context listener is not installed?");
// Happens if an internal redirect happens in a web-application (e.g. for
// 404 page)
final IRequestScope aExistingRequestScope = s_aRequestScopeTL.get ();
if (aExistingRequestScope != null)
{
if (LOGGER.isWarnEnabled ())
LOGGER.warn ("A request scope is already present - will overwrite it: " + aExistingRequestScope.toString ());
if (aExistingRequestScope.isValid ())
{
// The scope shall be destroyed here, as this is most probably a
// programming error!
LOGGER.warn ("Destroying the old request scope before the new one gets initialized!");
_destroyRequestScope (aExistingRequestScope);
}
}
// set request context
s_aRequestScopeTL.set (aRequestScope);
// Now init the scope
aRequestScope.initScope ();
// call SPIs
ScopeSPIManager.getInstance ().onRequestScopeBegin (aRequestScope);
} } | public class class_name {
public static void internalSetAndInitRequestScope (@Nonnull final IRequestScope aRequestScope)
{
ValueEnforcer.notNull (aRequestScope, "RequestScope");
ValueEnforcer.isTrue (ScopeManager::isGlobalScopePresent,
"No global context present! May be the global context listener is not installed?");
// Happens if an internal redirect happens in a web-application (e.g. for
// 404 page)
final IRequestScope aExistingRequestScope = s_aRequestScopeTL.get ();
if (aExistingRequestScope != null)
{
if (LOGGER.isWarnEnabled ())
LOGGER.warn ("A request scope is already present - will overwrite it: " + aExistingRequestScope.toString ());
if (aExistingRequestScope.isValid ())
{
// The scope shall be destroyed here, as this is most probably a
// programming error!
LOGGER.warn ("Destroying the old request scope before the new one gets initialized!"); // depends on control dependency: [if], data = [none]
_destroyRequestScope (aExistingRequestScope); // depends on control dependency: [if], data = [none]
}
}
// set request context
s_aRequestScopeTL.set (aRequestScope);
// Now init the scope
aRequestScope.initScope ();
// call SPIs
ScopeSPIManager.getInstance ().onRequestScopeBegin (aRequestScope);
} } |
public class class_name {
public static boolean equivalent(
@Nullable Network<?, ?> networkA, @Nullable Network<?, ?> networkB) {
if (networkA == networkB) {
return true;
}
if (networkA == null || networkB == null) {
return false;
}
if (networkA.isDirected() != networkB.isDirected()
|| !networkA.nodes().equals(networkB.nodes())
|| !networkA.edges().equals(networkB.edges())) {
return false;
}
for (Object edge : networkA.edges()) {
if (!networkA.incidentNodes(edge).equals(networkB.incidentNodes(edge))) {
return false;
}
}
return true;
} } | public class class_name {
public static boolean equivalent(
@Nullable Network<?, ?> networkA, @Nullable Network<?, ?> networkB) {
if (networkA == networkB) {
return true; // depends on control dependency: [if], data = [none]
}
if (networkA == null || networkB == null) {
return false; // depends on control dependency: [if], data = [none]
}
if (networkA.isDirected() != networkB.isDirected()
|| !networkA.nodes().equals(networkB.nodes())
|| !networkA.edges().equals(networkB.edges())) {
return false; // depends on control dependency: [if], data = [none]
}
for (Object edge : networkA.edges()) {
if (!networkA.incidentNodes(edge).equals(networkB.incidentNodes(edge))) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
@XmlTransient
public List<PackageMetaData> getAllPackages() {
List<PackageMetaData> result = new ArrayList<>();
if (packages != null) {
for (PackageMetaData pack : packages) {
result.addAll(getPackages(pack));
}
}
return result;
} } | public class class_name {
@XmlTransient
public List<PackageMetaData> getAllPackages() {
List<PackageMetaData> result = new ArrayList<>();
if (packages != null) {
for (PackageMetaData pack : packages) {
result.addAll(getPackages(pack));
// depends on control dependency: [for], data = [pack]
}
}
return result;
} } |
public class class_name {
public void setReference(final String propertyName, final BeanId value) {
Preconditions.checkNotNull(propertyName);
if (value == null) {
references.put(propertyName, null);
return;
}
checkCircularReference(value);
List<BeanId> values = new ArrayList<>();
values.add(value);
references.put(propertyName, values);
} } | public class class_name {
public void setReference(final String propertyName, final BeanId value) {
Preconditions.checkNotNull(propertyName);
if (value == null) {
references.put(propertyName, null); // depends on control dependency: [if], data = [null)]
return; // depends on control dependency: [if], data = [none]
}
checkCircularReference(value);
List<BeanId> values = new ArrayList<>();
values.add(value);
references.put(propertyName, values);
} } |
public class class_name {
public void registerJsonValueProcessor( Class beanClass, String key, JsonValueProcessor jsonValueProcessor ) {
if( beanClass != null && key != null && jsonValueProcessor != null ) {
beanKeyMap.put( beanClass, key, jsonValueProcessor );
}
} } | public class class_name {
public void registerJsonValueProcessor( Class beanClass, String key, JsonValueProcessor jsonValueProcessor ) {
if( beanClass != null && key != null && jsonValueProcessor != null ) {
beanKeyMap.put( beanClass, key, jsonValueProcessor ); // depends on control dependency: [if], data = [( beanClass]
}
} } |
public class class_name {
public void marshall(ListAcceleratorsRequest listAcceleratorsRequest, ProtocolMarshaller protocolMarshaller) {
if (listAcceleratorsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listAcceleratorsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(listAcceleratorsRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListAcceleratorsRequest listAcceleratorsRequest, ProtocolMarshaller protocolMarshaller) {
if (listAcceleratorsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listAcceleratorsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listAcceleratorsRequest.getNextToken(), NEXTTOKEN_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 boolean isHandledByFilter(Method method) {
// "Resource classes are POJOs that have at least one method annotated
// with @Path or a request method designator. [...]
//
// Resource methods are methods of a resource class annotated with a
// request method designator. [...] A request method designator is a
// runtime annotation that is annotated with the @HttpMethod
// annotation."
for (Annotation annotation : method.getAnnotations()) {
if (HttpMethod.class.isAssignableFrom(annotation.annotationType())) {
return true;
}
}
if (method.isAnnotationPresent(Path.class)) {
return true;
}
return false;
} } | public class class_name {
private boolean isHandledByFilter(Method method) {
// "Resource classes are POJOs that have at least one method annotated
// with @Path or a request method designator. [...]
//
// Resource methods are methods of a resource class annotated with a
// request method designator. [...] A request method designator is a
// runtime annotation that is annotated with the @HttpMethod
// annotation."
for (Annotation annotation : method.getAnnotations()) {
if (HttpMethod.class.isAssignableFrom(annotation.annotationType())) {
return true; // depends on control dependency: [if], data = [none]
}
}
if (method.isAnnotationPresent(Path.class)) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void renderDiv(DivTag.State state, TreeElement elem)
{
ArrayList al = _lists[TreeHtmlAttributeInfo.HTML_LOCATION_DIV];
assert(al != null);
if (al.size() == 0)
return;
int cnt = al.size();
for (int i = 0; i < cnt; i++) {
TreeHtmlAttributeInfo attr = (TreeHtmlAttributeInfo) al.get(i);
state.registerAttribute(AbstractHtmlState.ATTR_GENERAL, attr.getAttribute(), attr.getValue());
}
} } | public class class_name {
public void renderDiv(DivTag.State state, TreeElement elem)
{
ArrayList al = _lists[TreeHtmlAttributeInfo.HTML_LOCATION_DIV];
assert(al != null);
if (al.size() == 0)
return;
int cnt = al.size();
for (int i = 0; i < cnt; i++) {
TreeHtmlAttributeInfo attr = (TreeHtmlAttributeInfo) al.get(i);
state.registerAttribute(AbstractHtmlState.ATTR_GENERAL, attr.getAttribute(), attr.getValue()); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public void stop() throws Exception {
if (mSecondaryMasterThread != null) {
mSecondaryMaster.stop();
while (mSecondaryMasterThread.isAlive()) {
LOG.info("Stopping thread {}.", mSecondaryMasterThread.getName());
mSecondaryMasterThread.join(1000);
}
mSecondaryMasterThread = null;
}
if (mMasterThread != null) {
mMasterProcess.stop();
while (mMasterThread.isAlive()) {
LOG.info("Stopping thread {}.", mMasterThread.getName());
mMasterThread.interrupt();
mMasterThread.join(1000);
}
mMasterThread = null;
}
clearClients();
System.clearProperty("alluxio.web.resources");
System.clearProperty("alluxio.master.min.worker.threads");
} } | public class class_name {
public void stop() throws Exception {
if (mSecondaryMasterThread != null) {
mSecondaryMaster.stop();
while (mSecondaryMasterThread.isAlive()) {
LOG.info("Stopping thread {}.", mSecondaryMasterThread.getName());
mSecondaryMasterThread.join(1000);
}
mSecondaryMasterThread = null;
}
if (mMasterThread != null) {
mMasterProcess.stop();
while (mMasterThread.isAlive()) {
LOG.info("Stopping thread {}.", mMasterThread.getName()); // depends on control dependency: [while], data = [none]
mMasterThread.interrupt(); // depends on control dependency: [while], data = [none]
mMasterThread.join(1000); // depends on control dependency: [while], data = [none]
}
mMasterThread = null;
}
clearClients();
System.clearProperty("alluxio.web.resources");
System.clearProperty("alluxio.master.min.worker.threads");
} } |
public class class_name {
@Override
public final void setValue(JsonValue jsonValue) {
try {
this.setValue(convert(jsonValue));
} catch (Exception e) {
logger.error("Error while setting JSON value", e);
}
} } | public class class_name {
@Override
public final void setValue(JsonValue jsonValue) {
try {
this.setValue(convert(jsonValue)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("Error while setting JSON value", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void initEjbInterceptors() {
initClassDeclaredEjbInterceptors();
if (constructor != null) {
initConstructorDeclaredEjbInterceptors();
}
for (AnnotatedMethod<?> method : businessMethods) {
initMethodDeclaredEjbInterceptors(method);
}
} } | public class class_name {
private void initEjbInterceptors() {
initClassDeclaredEjbInterceptors();
if (constructor != null) {
initConstructorDeclaredEjbInterceptors(); // depends on control dependency: [if], data = [none]
}
for (AnnotatedMethod<?> method : businessMethods) {
initMethodDeclaredEjbInterceptors(method); // depends on control dependency: [for], data = [method]
}
} } |
public class class_name {
public static int decode(WsByteBuffer headerBlock, int N) {
// if (!headerBlock.hasRemaining()) {
// throw new HeaderFieldDecodingException("No length to decode");
// }
int I = HpackUtils.getLSB(headerBlock.get(), N);
if (I < HpackUtils.ipow(2, N) - 1) {
return I;
} else {
int M = 0;
boolean done = false;
byte b;
while (done == false) {
// If there are no further elements, this is an invalid HeaderBlock.
// If this decode method is called, there should always be header
// key value bytes after the integer representation.
// if (!headerBlock.hasRemaining()) {
// throw new HeaderFieldDecodingException("");
// }
b = headerBlock.get();
I = I + ((b) & 127) * HpackUtils.ipow(2, M);
M = M + 7;
if (((b & 128) == 128) == false)
done = true;
}
return I;
}
} } | public class class_name {
public static int decode(WsByteBuffer headerBlock, int N) {
// if (!headerBlock.hasRemaining()) {
// throw new HeaderFieldDecodingException("No length to decode");
// }
int I = HpackUtils.getLSB(headerBlock.get(), N);
if (I < HpackUtils.ipow(2, N) - 1) {
return I; // depends on control dependency: [if], data = [none]
} else {
int M = 0;
boolean done = false;
byte b;
while (done == false) {
// If there are no further elements, this is an invalid HeaderBlock.
// If this decode method is called, there should always be header
// key value bytes after the integer representation.
// if (!headerBlock.hasRemaining()) {
// throw new HeaderFieldDecodingException("");
// }
b = headerBlock.get(); // depends on control dependency: [while], data = [none]
I = I + ((b) & 127) * HpackUtils.ipow(2, M); // depends on control dependency: [while], data = [none]
M = M + 7; // depends on control dependency: [while], data = [none]
if (((b & 128) == 128) == false)
done = true;
}
return I; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public V get(String s, int offset, int len) {
int t = 0;
for (int i = 0; i < len; ) {
char c = s.charAt(offset + i++);
if (isCaseInsensitive() && c < 128)
c = StringUtils.lowercases[c];
while (true) {
int row = ROW_SIZE * t;
char n = _tree[row];
int diff = n - c;
if (diff == 0) {
t = _tree[row + EQ];
if (t == 0)
return null;
break;
}
t = _tree[row + hilo(diff)];
if (t == 0)
return null;
}
}
return _value[t];
} } | public class class_name {
@Override
public V get(String s, int offset, int len) {
int t = 0;
for (int i = 0; i < len; ) {
char c = s.charAt(offset + i++);
if (isCaseInsensitive() && c < 128)
c = StringUtils.lowercases[c];
while (true) {
int row = ROW_SIZE * t;
char n = _tree[row];
int diff = n - c;
if (diff == 0) {
t = _tree[row + EQ]; // depends on control dependency: [if], data = [none]
if (t == 0)
return null;
break;
}
t = _tree[row + hilo(diff)]; // depends on control dependency: [while], data = [none]
if (t == 0)
return null;
}
}
return _value[t];
} } |
public class class_name {
public final void onResume(@NonNull final Object serviceListener) {
logd("onResume");
mServiceListener = serviceListener;
mState = State.RESUMED;
if (!mStoredResults.isEmpty()) {
logd("has undelivered results");
final List<SoftReference<OperationDelivery<?>>> oldResults = new ArrayList<>(
mStoredResults);
mStoredResults.clear();
for (SoftReference<OperationDelivery<?>> result : oldResults) {
final OperationDelivery<?> delivery = result.get();
if (delivery != null) {
deliverResult(delivery);
}
}
logd("no more undelivered results");
} else {
logd("has no undelivered results");
}
} } | public class class_name {
public final void onResume(@NonNull final Object serviceListener) {
logd("onResume");
mServiceListener = serviceListener;
mState = State.RESUMED;
if (!mStoredResults.isEmpty()) {
logd("has undelivered results"); // depends on control dependency: [if], data = [none]
final List<SoftReference<OperationDelivery<?>>> oldResults = new ArrayList<>(
mStoredResults); // depends on control dependency: [if], data = [none]
mStoredResults.clear(); // depends on control dependency: [if], data = [none]
for (SoftReference<OperationDelivery<?>> result : oldResults) {
final OperationDelivery<?> delivery = result.get();
if (delivery != null) {
deliverResult(delivery);
}
}
logd("no more undelivered results");
} else {
logd("has no undelivered results");
}
} } |
public class class_name {
public InodePathPair lockInodePathPair(AlluxioURI path1, LockPattern lockPattern1,
AlluxioURI path2, LockPattern lockPattern2) throws InvalidPathException {
LockedInodePath lockedPath1 = null;
LockedInodePath lockedPath2 = null;
boolean valid = false;
try {
// Lock paths in a deterministic order.
if (path1.getPath().compareTo(path2.getPath()) > 0) {
lockedPath2 = lockInodePath(path2, lockPattern2);
lockedPath1 = lockInodePath(path1, lockPattern1);
} else {
lockedPath1 = lockInodePath(path1, lockPattern1);
lockedPath2 = lockInodePath(path2, lockPattern2);
}
valid = true;
return new InodePathPair(lockedPath1, lockedPath2);
} finally {
if (!valid) {
if (lockedPath1 != null) {
lockedPath1.close();
}
if (lockedPath2 != null) {
lockedPath2.close();
}
}
}
} } | public class class_name {
public InodePathPair lockInodePathPair(AlluxioURI path1, LockPattern lockPattern1,
AlluxioURI path2, LockPattern lockPattern2) throws InvalidPathException {
LockedInodePath lockedPath1 = null;
LockedInodePath lockedPath2 = null;
boolean valid = false;
try {
// Lock paths in a deterministic order.
if (path1.getPath().compareTo(path2.getPath()) > 0) {
lockedPath2 = lockInodePath(path2, lockPattern2); // depends on control dependency: [if], data = [none]
lockedPath1 = lockInodePath(path1, lockPattern1); // depends on control dependency: [if], data = [none]
} else {
lockedPath1 = lockInodePath(path1, lockPattern1); // depends on control dependency: [if], data = [none]
lockedPath2 = lockInodePath(path2, lockPattern2); // depends on control dependency: [if], data = [none]
}
valid = true;
return new InodePathPair(lockedPath1, lockedPath2);
} finally {
if (!valid) {
if (lockedPath1 != null) {
lockedPath1.close(); // depends on control dependency: [if], data = [none]
}
if (lockedPath2 != null) {
lockedPath2.close(); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
@Override
public CallSequence get(int index)
{
if (indics == null)
{
size();
}
Pair<Integer, Integer> v = indics.get(index);
int r = v.getFirst();
if (r == 0)
{
CallSequence seq = getVars();
CallStatement skip = new CallStatement()
{
public Object execute()
{
return Utils.VOID_VALUE;
}
@Override
public String toString()
{
return "skip";
}
};
seq.add(skip);
return seq;
} else
{
TestSequence rtests = repeat.getTests();
int count = rtests.size();
int[] c = new int[r];
for (int i = 0; i < r; i++)
{
c[i] = count;
}
Permutor p = new Permutor(c);
int[] select = null;
for (int i = 0; i < v.getSecond(); i++)
{
select = p.next();
}
CallSequence seq = getVars();
for (int i = 0; i < r; i++)
{
seq.addAll(rtests.get(select[i]));
}
return seq;
}
} } | public class class_name {
@Override
public CallSequence get(int index)
{
if (indics == null)
{
size(); // depends on control dependency: [if], data = [none]
}
Pair<Integer, Integer> v = indics.get(index);
int r = v.getFirst();
if (r == 0)
{
CallSequence seq = getVars();
CallStatement skip = new CallStatement()
{
public Object execute()
{
return Utils.VOID_VALUE;
}
@Override
public String toString()
{
return "skip";
}
};
seq.add(skip); // depends on control dependency: [if], data = [none]
return seq; // depends on control dependency: [if], data = [none]
} else
{
TestSequence rtests = repeat.getTests();
int count = rtests.size();
int[] c = new int[r];
for (int i = 0; i < r; i++)
{
c[i] = count; // depends on control dependency: [for], data = [i]
}
Permutor p = new Permutor(c);
int[] select = null;
for (int i = 0; i < v.getSecond(); i++)
{
select = p.next(); // depends on control dependency: [for], data = [none]
}
CallSequence seq = getVars();
for (int i = 0; i < r; i++)
{
seq.addAll(rtests.get(select[i])); // depends on control dependency: [for], data = [i]
}
return seq; // depends on control dependency: [if], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.