code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
public static double cosineOrHaversineRad(double lat1, double lon1, double lat2, double lon2) {
if(lat1 == lat2 && lon1 == lon2) {
return 0.;
}
final DoubleWrapper tmp = new DoubleWrapper(); // To return cosine
final double slat1 = sinAndCos(lat1, tmp), clat1 = tmp.value;
final double slat2 = sinAndCos(lat2, tmp), clat2 = tmp.value;
final double dlat = lat1 - lat2, dlon = lon1 - lon2;
// Use cosine, cheaper:
if(dlat > 0.01 || dlat < -0.01 || dlon > 0.01 || dlat < -0.01) {
final double a = slat1 * slat2 + clat1 * clat2 * cos(dlon);
return a < .9999_9999_9999_999 ? acos(a) : 0;
}
// Haversine formula, higher precision at < 1 meters
final double slat = sin(dlat * .5), slon = sin(dlon * .5);
return 2 * asin(sqrt(slat * slat + slon * slon * clat1 * clat2));
} }
|
public class class_name {
public static double cosineOrHaversineRad(double lat1, double lon1, double lat2, double lon2) {
if(lat1 == lat2 && lon1 == lon2) {
return 0.; // depends on control dependency: [if], data = [none]
}
final DoubleWrapper tmp = new DoubleWrapper(); // To return cosine
final double slat1 = sinAndCos(lat1, tmp), clat1 = tmp.value;
final double slat2 = sinAndCos(lat2, tmp), clat2 = tmp.value;
final double dlat = lat1 - lat2, dlon = lon1 - lon2;
// Use cosine, cheaper:
if(dlat > 0.01 || dlat < -0.01 || dlon > 0.01 || dlat < -0.01) {
final double a = slat1 * slat2 + clat1 * clat2 * cos(dlon);
return a < .9999_9999_9999_999 ? acos(a) : 0; // depends on control dependency: [if], data = [none]
}
// Haversine formula, higher precision at < 1 meters
final double slat = sin(dlat * .5), slon = sin(dlon * .5);
return 2 * asin(sqrt(slat * slat + slon * slon * clat1 * clat2));
} }
|
public class class_name {
public synchronized CuratorFramework getLocalConnection() throws IOException
{
if ( localConnection == null )
{
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString("localhost:" + configManager.getConfig().getInt(IntConfigs.CLIENT_PORT))
.sessionTimeoutMs(arguments.connectionTimeOutMs * 10)
.connectionTimeoutMs(arguments.connectionTimeOutMs)
.retryPolicy(new ExponentialBackoffRetry(1000, 3));
if ( arguments.aclProvider != null )
{
builder = builder.aclProvider(arguments.aclProvider);
}
localConnection = builder.build();
localConnection.start();
}
return localConnection;
} }
|
public class class_name {
public synchronized CuratorFramework getLocalConnection() throws IOException
{
if ( localConnection == null )
{
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString("localhost:" + configManager.getConfig().getInt(IntConfigs.CLIENT_PORT))
.sessionTimeoutMs(arguments.connectionTimeOutMs * 10)
.connectionTimeoutMs(arguments.connectionTimeOutMs)
.retryPolicy(new ExponentialBackoffRetry(1000, 3));
if ( arguments.aclProvider != null )
{
builder = builder.aclProvider(arguments.aclProvider); // depends on control dependency: [if], data = [none]
}
localConnection = builder.build(); // depends on control dependency: [if], data = [none]
localConnection.start(); // depends on control dependency: [if], data = [none]
}
return localConnection;
} }
|
public class class_name {
private SecurityConstraint createSecurityConstraint(SecurityMetadata securityMetadataFromDD, List<WebResourceCollection> webResourceCollections,
HttpConstraintElement httpConstraint, boolean fromHttpConstraint) {
List<String> roles = createRoles(httpConstraint);
List<String> allRoles = securityMetadataFromDD.getRoles();
for (String role : roles) {
if (!allRoles.contains(role)) {
allRoles.add(role);
}
}
boolean sslRequired = isSSLRequired(httpConstraint);
boolean accessPrecluded = isAccessPrecluded(httpConstraint);
boolean accessUncovered = isAccessUncovered(httpConstraint);
return new SecurityConstraint(webResourceCollections, roles, sslRequired, accessPrecluded, fromHttpConstraint, accessUncovered);
} }
|
public class class_name {
private SecurityConstraint createSecurityConstraint(SecurityMetadata securityMetadataFromDD, List<WebResourceCollection> webResourceCollections,
HttpConstraintElement httpConstraint, boolean fromHttpConstraint) {
List<String> roles = createRoles(httpConstraint);
List<String> allRoles = securityMetadataFromDD.getRoles();
for (String role : roles) {
if (!allRoles.contains(role)) {
allRoles.add(role); // depends on control dependency: [if], data = [none]
}
}
boolean sslRequired = isSSLRequired(httpConstraint);
boolean accessPrecluded = isAccessPrecluded(httpConstraint);
boolean accessUncovered = isAccessUncovered(httpConstraint);
return new SecurityConstraint(webResourceCollections, roles, sslRequired, accessPrecluded, fromHttpConstraint, accessUncovered);
} }
|
public class class_name {
private void createProxies() {
source = createProxy(sourceType);
destination = createProxy(destinationType);
for (VisitedMapping mapping : visitedMappings) {
createAccessorProxies(source, mapping.sourceAccessors);
createAccessorProxies(destination, mapping.destinationAccessors);
}
} }
|
public class class_name {
private void createProxies() {
source = createProxy(sourceType);
destination = createProxy(destinationType);
for (VisitedMapping mapping : visitedMappings) {
createAccessorProxies(source, mapping.sourceAccessors);
// depends on control dependency: [for], data = [mapping]
createAccessorProxies(destination, mapping.destinationAccessors);
// depends on control dependency: [for], data = [mapping]
}
} }
|
public class class_name {
public static double getPvalue(TransposeDataCollection transposeDataCollection) {
if(transposeDataCollection.size()!=2) {
throw new IllegalArgumentException("The collection must contain observations from 2 groups.");
}
Object[] keys = transposeDataCollection.keySet().toArray();
//counter of uncencored internalData in each group
Map<Object, Integer> r = new HashMap<>();
r.put(keys[0], 0);
r.put(keys[1], 0);
List<Object> mergedUncensoredData = new ArrayList<>();
for(Map.Entry<Object, FlatDataCollection> entry : transposeDataCollection.entrySet()) {
Object j = entry.getKey();
FlatDataCollection flatDataCollection = entry.getValue();
for(Object value : flatDataCollection) {
if(!value.toString().endsWith(CensoredDescriptives.CENSORED_NUMBER_POSTFIX)) { //only the uncencored internalData
mergedUncensoredData.add(value);
r.put(j, r.get(j)+1);
}
}
}
Collections.sort(mergedUncensoredData, (Object o1, Object o2) -> {
double v1 = TypeInference.toDouble(o1);
double v2 = TypeInference.toDouble(o2);
if(v1>v2) {
return 1;
}
else if(v1<v2) {
return -1;
}
return 0;
});
AssociativeArray2D testTable = new AssociativeArray2D();
for(Object ti : mergedUncensoredData) {
Double tiValue = TypeInference.toDouble(ti);
Object value = testTable.get2d(ti, "mi");
if(value==null) {
testTable.put2d(ti, "mi", 1);
testTable.put2d(ti, "r0ti", 0);
testTable.put2d(ti, "r1ti", 0);
}
else {
testTable.put2d(ti, "mi", ((Integer)value) +1);
continue; //continue in order not to count twice the r*ti below
}
//calculate the r*ti: the number of observations (both cencored and uncencored) which are larger than ti
for(Map.Entry<Object, FlatDataCollection> entry : transposeDataCollection.entrySet()) {
Object j = entry.getKey();
FlatDataCollection flatDataCollection = entry.getValue();
int jIndex = (j.equals(keys[1]))?1:0;
//calculate the r*ti: the number of observations (both cencored and uncencored) which are larger than $ti
String rJtiKey="r"+String.valueOf(jIndex)+"ti";
for(Object value2 : flatDataCollection) {
double v;
String str = value2.toString();
if(str.endsWith(CensoredDescriptives.CENSORED_NUMBER_POSTFIX)) {
//censored internalData encoded as 4.3+ or -4.3+
v = Double.valueOf(str.substring(0,str.length()-CensoredDescriptives.CENSORED_NUMBER_POSTFIX.length())); //remove the trailing char and convert it to double
}
else {
//uncensored internalData
v = TypeInference.toDouble(value2); //convert it to double
}
if(v>=tiValue) {
testTable.put2d(ti, rJtiKey, (Integer)testTable.get2d(ti, rJtiKey) +1);
}
}
}
}
//mergedUncensoredData = null;
double U = (double)r.get(keys[1]);
double VarU =0.0;
for(Map.Entry<Object, AssociativeArray> entry : testTable.entrySet()) {
//Object key = entry.getKey();
AssociativeArray testRow = entry.getValue();
double r0ti=testRow.getDouble("r0ti");
double r1ti=testRow.getDouble("r1ti");
double mi = testRow.getDouble("mi");
double rti= r0ti+r1ti;
double Ai= r1ti/rti;
U-=mi*Ai;
VarU+=((mi*(rti-mi))/(rti-1.0))*Ai*(1.0-Ai);
}
//testTable = null;
double Z=U/Math.sqrt(VarU);
double pvalue = scoreToPvalue(Z);
return pvalue;
} }
|
public class class_name {
public static double getPvalue(TransposeDataCollection transposeDataCollection) {
if(transposeDataCollection.size()!=2) {
throw new IllegalArgumentException("The collection must contain observations from 2 groups.");
}
Object[] keys = transposeDataCollection.keySet().toArray();
//counter of uncencored internalData in each group
Map<Object, Integer> r = new HashMap<>();
r.put(keys[0], 0);
r.put(keys[1], 0);
List<Object> mergedUncensoredData = new ArrayList<>();
for(Map.Entry<Object, FlatDataCollection> entry : transposeDataCollection.entrySet()) {
Object j = entry.getKey();
FlatDataCollection flatDataCollection = entry.getValue();
for(Object value : flatDataCollection) {
if(!value.toString().endsWith(CensoredDescriptives.CENSORED_NUMBER_POSTFIX)) { //only the uncencored internalData
mergedUncensoredData.add(value); // depends on control dependency: [if], data = [none]
r.put(j, r.get(j)+1); // depends on control dependency: [if], data = [none]
}
}
}
Collections.sort(mergedUncensoredData, (Object o1, Object o2) -> {
double v1 = TypeInference.toDouble(o1);
double v2 = TypeInference.toDouble(o2);
if(v1>v2) {
return 1; // depends on control dependency: [if], data = [none]
}
else if(v1<v2) {
return -1; // depends on control dependency: [if], data = [none]
}
return 0;
});
AssociativeArray2D testTable = new AssociativeArray2D();
for(Object ti : mergedUncensoredData) {
Double tiValue = TypeInference.toDouble(ti);
Object value = testTable.get2d(ti, "mi");
if(value==null) {
testTable.put2d(ti, "mi", 1); // depends on control dependency: [if], data = [none]
testTable.put2d(ti, "r0ti", 0); // depends on control dependency: [if], data = [none]
testTable.put2d(ti, "r1ti", 0); // depends on control dependency: [if], data = [none]
}
else {
testTable.put2d(ti, "mi", ((Integer)value) +1); // depends on control dependency: [if], data = [none]
continue; //continue in order not to count twice the r*ti below
}
//calculate the r*ti: the number of observations (both cencored and uncencored) which are larger than ti
for(Map.Entry<Object, FlatDataCollection> entry : transposeDataCollection.entrySet()) {
Object j = entry.getKey();
FlatDataCollection flatDataCollection = entry.getValue();
int jIndex = (j.equals(keys[1]))?1:0;
//calculate the r*ti: the number of observations (both cencored and uncencored) which are larger than $ti
String rJtiKey="r"+String.valueOf(jIndex)+"ti";
for(Object value2 : flatDataCollection) {
double v;
String str = value2.toString();
if(str.endsWith(CensoredDescriptives.CENSORED_NUMBER_POSTFIX)) {
//censored internalData encoded as 4.3+ or -4.3+
v = Double.valueOf(str.substring(0,str.length()-CensoredDescriptives.CENSORED_NUMBER_POSTFIX.length())); //remove the trailing char and convert it to double // depends on control dependency: [if], data = [none]
}
else {
//uncensored internalData
v = TypeInference.toDouble(value2); //convert it to double // depends on control dependency: [if], data = [none]
}
if(v>=tiValue) {
testTable.put2d(ti, rJtiKey, (Integer)testTable.get2d(ti, rJtiKey) +1); // depends on control dependency: [if], data = [none]
}
}
}
}
//mergedUncensoredData = null;
double U = (double)r.get(keys[1]);
double VarU =0.0;
for(Map.Entry<Object, AssociativeArray> entry : testTable.entrySet()) {
//Object key = entry.getKey();
AssociativeArray testRow = entry.getValue();
double r0ti=testRow.getDouble("r0ti");
double r1ti=testRow.getDouble("r1ti");
double mi = testRow.getDouble("mi");
double rti= r0ti+r1ti;
double Ai= r1ti/rti;
U-=mi*Ai;
VarU+=((mi*(rti-mi))/(rti-1.0))*Ai*(1.0-Ai);
}
//testTable = null;
double Z=U/Math.sqrt(VarU);
double pvalue = scoreToPvalue(Z);
return pvalue;
} }
|
public class class_name {
public static DataSource createDataSource(String source){
String typeAndConfig = configuration.getProperty(source);
if (typeAndConfig == null){
log.error("No configuration for data source: " + source);
return null;
}
String[] typeAndConfigArray = typeAndConfig.split(DELIMITORS, 2);
if (typeAndConfigArray.length < 2){
log.error("Wrong configuration format for data source '" + source + "': " + typeAndConfig);
return null;
}
String type = typeAndConfigArray[0];
String config = typeAndConfigArray[1];
return createDataSource(source, type, config);
} }
|
public class class_name {
public static DataSource createDataSource(String source){
String typeAndConfig = configuration.getProperty(source);
if (typeAndConfig == null){
log.error("No configuration for data source: " + source);
// depends on control dependency: [if], data = [none]
return null;
// depends on control dependency: [if], data = [none]
}
String[] typeAndConfigArray = typeAndConfig.split(DELIMITORS, 2);
if (typeAndConfigArray.length < 2){
log.error("Wrong configuration format for data source '" + source + "': " + typeAndConfig);
// depends on control dependency: [if], data = [none]
return null;
// depends on control dependency: [if], data = [none]
}
String type = typeAndConfigArray[0];
String config = typeAndConfigArray[1];
return createDataSource(source, type, config);
} }
|
public class class_name {
public static List<Field> getPersistableFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
List<Field> output = new ArrayList<>(fields.length);
for (Field field : fields) {
if (!(field.isAnnotationPresent(Ignore.class) || isStatic(field))) {
output.add(field);
}
}
return output;
} }
|
public class class_name {
public static List<Field> getPersistableFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
List<Field> output = new ArrayList<>(fields.length);
for (Field field : fields) {
if (!(field.isAnnotationPresent(Ignore.class) || isStatic(field))) {
output.add(field); // depends on control dependency: [if], data = [none]
}
}
return output;
} }
|
public class class_name {
public static final <T extends UIObject> void removeAnimationOnEnd(final T widget, final String animation) {
if (widget != null && animation != null) {
removeAnimationOnEnd(widget.getElement(), animation);
}
} }
|
public class class_name {
public static final <T extends UIObject> void removeAnimationOnEnd(final T widget, final String animation) {
if (widget != null && animation != null) {
removeAnimationOnEnd(widget.getElement(), animation); // depends on control dependency: [if], data = [(widget]
}
} }
|
public class class_name {
public void setDiskImages(java.util.Collection<DiskImage> diskImages) {
if (diskImages == null) {
this.diskImages = null;
return;
}
this.diskImages = new com.amazonaws.internal.SdkInternalList<DiskImage>(diskImages);
} }
|
public class class_name {
public void setDiskImages(java.util.Collection<DiskImage> diskImages) {
if (diskImages == null) {
this.diskImages = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.diskImages = new com.amazonaws.internal.SdkInternalList<DiskImage>(diskImages);
} }
|
public class class_name {
public String text2() {
StringBuilder text = new StringBuilder();
for (Change aDiff : getChangeList()) {
if (aDiff.operation != Operation.DELETE) {
text.append(aDiff.text);
}
}
return text.toString();
} }
|
public class class_name {
public String text2() {
StringBuilder text = new StringBuilder();
for (Change aDiff : getChangeList()) {
if (aDiff.operation != Operation.DELETE) {
text.append(aDiff.text); // depends on control dependency: [if], data = [none]
}
}
return text.toString();
} }
|
public class class_name {
@Override
public void setObserver(HttpOutputStreamObserver obs) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "obs ->" + obs);
}
this.obs = obs;
} }
|
public class class_name {
@Override
public void setObserver(HttpOutputStreamObserver obs) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "obs ->" + obs); // depends on control dependency: [if], data = [none]
}
this.obs = obs;
} }
|
public class class_name {
public void putAllWriteable(BeanMap map) {
Iterator<String> readableKeys = map.readMethods.keySet().iterator();
while (readableKeys.hasNext()) {
String key = readableKeys.next();
if (getWriteMethod(key) != null) {
this.put(key, map.get(key));
}
}
} }
|
public class class_name {
public void putAllWriteable(BeanMap map) {
Iterator<String> readableKeys = map.readMethods.keySet().iterator();
while (readableKeys.hasNext()) {
String key = readableKeys.next();
if (getWriteMethod(key) != null) {
this.put(key, map.get(key)); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public java.util.List<TransitGatewayAttachment> getTransitGatewayAttachments() {
if (transitGatewayAttachments == null) {
transitGatewayAttachments = new com.amazonaws.internal.SdkInternalList<TransitGatewayAttachment>();
}
return transitGatewayAttachments;
} }
|
public class class_name {
public java.util.List<TransitGatewayAttachment> getTransitGatewayAttachments() {
if (transitGatewayAttachments == null) {
transitGatewayAttachments = new com.amazonaws.internal.SdkInternalList<TransitGatewayAttachment>(); // depends on control dependency: [if], data = [none]
}
return transitGatewayAttachments;
} }
|
public class class_name {
public static Class<?> getTypeArgument(Class<?> clazz, Class<?> interfce) {
Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
Type type = clazz;
while (!declaresInterface(getClass(type), interfce)) {
if (type instanceof Class) {
type = ((Class<?>) type).getGenericSuperclass();
} else {
ParameterizedType parameterizedType = (ParameterizedType) type;
Class<?> rawType = (Class<?>) parameterizedType.getRawType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
for (int i = 0; i < actualTypeArguments.length; i++) {
resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
}
type = rawType.getGenericSuperclass();
}
}
Type actualTypeArgument;
if (type instanceof Class) {
actualTypeArgument = ((Class<?>) type).getTypeParameters()[0];
} else {
actualTypeArgument = ((ParameterizedType) type).getActualTypeArguments()[0];
}
Class<?> typeArgumentAsClass = null;
while (resolvedTypes.containsKey(actualTypeArgument)) {
actualTypeArgument = resolvedTypes.get(actualTypeArgument);
}
typeArgumentAsClass = getClass(actualTypeArgument);
return typeArgumentAsClass;
} }
|
public class class_name {
public static Class<?> getTypeArgument(Class<?> clazz, Class<?> interfce) {
Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
Type type = clazz;
while (!declaresInterface(getClass(type), interfce)) {
if (type instanceof Class) {
type = ((Class<?>) type).getGenericSuperclass(); // depends on control dependency: [if], data = [none]
} else {
ParameterizedType parameterizedType = (ParameterizedType) type;
Class<?> rawType = (Class<?>) parameterizedType.getRawType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
for (int i = 0; i < actualTypeArguments.length; i++) {
resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
}
type = rawType.getGenericSuperclass(); // depends on control dependency: [if], data = [none]
}
}
Type actualTypeArgument;
if (type instanceof Class) {
actualTypeArgument = ((Class<?>) type).getTypeParameters()[0];
} else {
actualTypeArgument = ((ParameterizedType) type).getActualTypeArguments()[0];
}
Class<?> typeArgumentAsClass = null;
while (resolvedTypes.containsKey(actualTypeArgument)) {
actualTypeArgument = resolvedTypes.get(actualTypeArgument);
}
typeArgumentAsClass = getClass(actualTypeArgument);
return typeArgumentAsClass;
} }
|
public class class_name {
protected boolean shouldApplyThisRuleTo(ClassNode classNode) {
// TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns
boolean shouldApply = true;
String applyTo = getApplyToClassNames();
String doNotApplyTo = getDoNotApplyToClassNames();
if (applyTo != null && applyTo.length() > 0) {
WildcardPattern pattern = new WildcardPattern(applyTo, true);
shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());
}
if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {
WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);
shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());
}
return shouldApply;
} }
|
public class class_name {
protected boolean shouldApplyThisRuleTo(ClassNode classNode) {
// TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns
boolean shouldApply = true;
String applyTo = getApplyToClassNames();
String doNotApplyTo = getDoNotApplyToClassNames();
if (applyTo != null && applyTo.length() > 0) {
WildcardPattern pattern = new WildcardPattern(applyTo, true);
shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());
// depends on control dependency: [if], data = [none]
}
if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {
WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);
shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());
// depends on control dependency: [if], data = [none]
}
return shouldApply;
} }
|
public class class_name {
public void marshall(GetConfigurationSetRequest getConfigurationSetRequest, ProtocolMarshaller protocolMarshaller) {
if (getConfigurationSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getConfigurationSetRequest.getConfigurationSetName(), CONFIGURATIONSETNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(GetConfigurationSetRequest getConfigurationSetRequest, ProtocolMarshaller protocolMarshaller) {
if (getConfigurationSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getConfigurationSetRequest.getConfigurationSetName(), CONFIGURATIONSETNAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private static String checkImageStorage(URI sharedImage, URI sharedEdits) {
if (sharedImage.getScheme().equals(NNStorage.LOCAL_URI_SCHEME)) {
// shared image is stored in file storage
return "";
} else if (sharedImage.getScheme().equals(
QuorumJournalManager.QJM_URI_SCHEME)
&& sharedImage.equals(sharedEdits)) {
// image is stored in qjm together with edits
return "";
}
return "Shared image uri: " + sharedImage + " must be either file storage"
+ " or be equal to shared edits storage " + sharedEdits + ". ";
} }
|
public class class_name {
private static String checkImageStorage(URI sharedImage, URI sharedEdits) {
if (sharedImage.getScheme().equals(NNStorage.LOCAL_URI_SCHEME)) {
// shared image is stored in file storage
return ""; // depends on control dependency: [if], data = [none]
} else if (sharedImage.getScheme().equals(
QuorumJournalManager.QJM_URI_SCHEME)
&& sharedImage.equals(sharedEdits)) {
// image is stored in qjm together with edits
return ""; // depends on control dependency: [if], data = [none]
}
return "Shared image uri: " + sharedImage + " must be either file storage"
+ " or be equal to shared edits storage " + sharedEdits + ". ";
} }
|
public class class_name {
public static <E extends Enum<E>> List<E> computeEnum(List<EnumItem<E>> roleTagList, TransformMatrixDictionary<E> transformMatrixDictionary)
{
int length = roleTagList.size() - 1;
List<E> tagList = new ArrayList<E>(roleTagList.size());
double[][] cost = new double[2][]; // 滚动数组
Iterator<EnumItem<E>> iterator = roleTagList.iterator();
EnumItem<E> start = iterator.next();
E pre = start.labelMap.entrySet().iterator().next().getKey();
// 第一个是确定的
tagList.add(pre);
// 第二个也可以简单地算出来
Set<E> preTagSet;
{
EnumItem<E> item = iterator.next();
cost[0] = new double[item.labelMap.size()];
int j = 0;
for (E cur : item.labelMap.keySet())
{
cost[0][j] = transformMatrixDictionary.transititon_probability[pre.ordinal()][cur.ordinal()] - Math.log((item.getFrequency(cur) + 1e-8) / transformMatrixDictionary.getTotalFrequency(cur));
++j;
}
preTagSet = item.labelMap.keySet();
}
// 第三个开始复杂一些
for (int i = 1; i < length; ++i)
{
int index_i = i & 1;
int index_i_1 = 1 - index_i;
EnumItem<E> item = iterator.next();
cost[index_i] = new double[item.labelMap.size()];
double perfect_cost_line = Double.MAX_VALUE;
int k = 0;
Set<E> curTagSet = item.labelMap.keySet();
for (E cur : curTagSet)
{
cost[index_i][k] = Double.MAX_VALUE;
int j = 0;
for (E p : preTagSet)
{
double now = cost[index_i_1][j] + transformMatrixDictionary.transititon_probability[p.ordinal()][cur.ordinal()] - Math.log((item.getFrequency(cur) + 1e-8) / transformMatrixDictionary.getTotalFrequency(cur));
if (now < cost[index_i][k])
{
cost[index_i][k] = now;
if (now < perfect_cost_line)
{
perfect_cost_line = now;
pre = p;
}
}
++j;
}
++k;
}
tagList.add(pre);
preTagSet = curTagSet;
}
tagList.add(tagList.get(0)); // 对于最后一个##末##
return tagList;
} }
|
public class class_name {
public static <E extends Enum<E>> List<E> computeEnum(List<EnumItem<E>> roleTagList, TransformMatrixDictionary<E> transformMatrixDictionary)
{
int length = roleTagList.size() - 1;
List<E> tagList = new ArrayList<E>(roleTagList.size());
double[][] cost = new double[2][]; // 滚动数组
Iterator<EnumItem<E>> iterator = roleTagList.iterator();
EnumItem<E> start = iterator.next();
E pre = start.labelMap.entrySet().iterator().next().getKey();
// 第一个是确定的
tagList.add(pre);
// 第二个也可以简单地算出来
Set<E> preTagSet;
{
EnumItem<E> item = iterator.next();
cost[0] = new double[item.labelMap.size()];
int j = 0;
for (E cur : item.labelMap.keySet())
{
cost[0][j] = transformMatrixDictionary.transititon_probability[pre.ordinal()][cur.ordinal()] - Math.log((item.getFrequency(cur) + 1e-8) / transformMatrixDictionary.getTotalFrequency(cur)); // depends on control dependency: [for], data = [cur]
++j; // depends on control dependency: [for], data = [none]
}
preTagSet = item.labelMap.keySet();
}
// 第三个开始复杂一些
for (int i = 1; i < length; ++i)
{
int index_i = i & 1;
int index_i_1 = 1 - index_i;
EnumItem<E> item = iterator.next();
cost[index_i] = new double[item.labelMap.size()]; // depends on control dependency: [for], data = [none]
double perfect_cost_line = Double.MAX_VALUE;
int k = 0;
Set<E> curTagSet = item.labelMap.keySet();
for (E cur : curTagSet)
{
cost[index_i][k] = Double.MAX_VALUE; // depends on control dependency: [for], data = [none]
int j = 0;
for (E p : preTagSet)
{
double now = cost[index_i_1][j] + transformMatrixDictionary.transititon_probability[p.ordinal()][cur.ordinal()] - Math.log((item.getFrequency(cur) + 1e-8) / transformMatrixDictionary.getTotalFrequency(cur));
if (now < cost[index_i][k])
{
cost[index_i][k] = now; // depends on control dependency: [if], data = [none]
if (now < perfect_cost_line)
{
perfect_cost_line = now; // depends on control dependency: [if], data = [none]
pre = p; // depends on control dependency: [if], data = [none]
}
}
++j; // depends on control dependency: [for], data = [none]
}
++k; // depends on control dependency: [for], data = [none]
}
tagList.add(pre); // depends on control dependency: [for], data = [none]
preTagSet = curTagSet; // depends on control dependency: [for], data = [none]
}
tagList.add(tagList.get(0)); // 对于最后一个##末##
return tagList;
} }
|
public class class_name {
public <S extends Storable> void resync(Class<S> type,
ResyncCapability.Listener<? super S> listener,
double desiredSpeed,
String filter,
Object... filterValues)
throws RepositoryException
{
ReplicationTrigger<S> replicationTrigger;
if (storageFor(type) instanceof ReplicatedStorage) {
replicationTrigger = ((ReplicatedStorage) storageFor(type)).getReplicationTrigger();
} else {
throw new UnsupportedTypeException("Storable type is not replicated", type);
}
Storage<S> replicaStorage, masterStorage;
replicaStorage = mReplicaRepository.storageFor(type);
masterStorage = mMasterRepository.storageFor(type);
Query<S> replicaQuery, masterQuery;
if (filter == null) {
replicaQuery = replicaStorage.query();
masterQuery = masterStorage.query();
} else {
replicaQuery = replicaStorage.query(filter).withValues(filterValues);
masterQuery = masterStorage.query(filter).withValues(filterValues);
}
// Order both queries the same so that they can be run in parallel.
// Favor natural order of replica, since cursors may be opened and
// re-opened on it.
String[] orderBy = selectNaturalOrder(mReplicaRepository, type, replicaQuery.getFilter());
if (orderBy == null) {
orderBy = selectNaturalOrder(mMasterRepository, type, masterQuery.getFilter());
if (orderBy == null) {
Set<String> pkSet =
StorableIntrospector.examine(type).getPrimaryKeyProperties().keySet();
orderBy = pkSet.toArray(new String[pkSet.size()]);
}
}
Comparator comparator = SortedCursor.createComparator(type, orderBy);
replicaQuery = replicaQuery.orderBy(orderBy);
masterQuery = masterQuery.orderBy(orderBy);
Throttle throttle;
if (desiredSpeed >= 1.0) {
throttle = null;
} else {
if (desiredSpeed < 0.0) {
desiredSpeed = 0.0;
}
// 50 samples
throttle = new Throttle(50);
}
Transaction replicaTxn = mReplicaRepository.enterTransaction();
try {
replicaTxn.setForUpdate(true);
resync(replicationTrigger,
replicaStorage, replicaQuery,
masterStorage, masterQuery,
listener,
throttle, desiredSpeed,
comparator, replicaTxn);
replicaTxn.commit();
} finally {
replicaTxn.exit();
}
} }
|
public class class_name {
public <S extends Storable> void resync(Class<S> type,
ResyncCapability.Listener<? super S> listener,
double desiredSpeed,
String filter,
Object... filterValues)
throws RepositoryException
{
ReplicationTrigger<S> replicationTrigger;
if (storageFor(type) instanceof ReplicatedStorage) {
replicationTrigger = ((ReplicatedStorage) storageFor(type)).getReplicationTrigger();
// depends on control dependency: [if], data = [none]
} else {
throw new UnsupportedTypeException("Storable type is not replicated", type);
}
Storage<S> replicaStorage, masterStorage;
replicaStorage = mReplicaRepository.storageFor(type);
masterStorage = mMasterRepository.storageFor(type);
Query<S> replicaQuery, masterQuery;
if (filter == null) {
replicaQuery = replicaStorage.query();
// depends on control dependency: [if], data = [none]
masterQuery = masterStorage.query();
// depends on control dependency: [if], data = [none]
} else {
replicaQuery = replicaStorage.query(filter).withValues(filterValues);
// depends on control dependency: [if], data = [(filter]
masterQuery = masterStorage.query(filter).withValues(filterValues);
// depends on control dependency: [if], data = [(filter]
}
// Order both queries the same so that they can be run in parallel.
// Favor natural order of replica, since cursors may be opened and
// re-opened on it.
String[] orderBy = selectNaturalOrder(mReplicaRepository, type, replicaQuery.getFilter());
if (orderBy == null) {
orderBy = selectNaturalOrder(mMasterRepository, type, masterQuery.getFilter());
// depends on control dependency: [if], data = [none]
if (orderBy == null) {
Set<String> pkSet =
StorableIntrospector.examine(type).getPrimaryKeyProperties().keySet();
orderBy = pkSet.toArray(new String[pkSet.size()]);
// depends on control dependency: [if], data = [none]
}
}
Comparator comparator = SortedCursor.createComparator(type, orderBy);
replicaQuery = replicaQuery.orderBy(orderBy);
masterQuery = masterQuery.orderBy(orderBy);
Throttle throttle;
if (desiredSpeed >= 1.0) {
throttle = null;
// depends on control dependency: [if], data = [none]
} else {
if (desiredSpeed < 0.0) {
desiredSpeed = 0.0;
// depends on control dependency: [if], data = [none]
}
// 50 samples
throttle = new Throttle(50);
// depends on control dependency: [if], data = [none]
}
Transaction replicaTxn = mReplicaRepository.enterTransaction();
try {
replicaTxn.setForUpdate(true);
// depends on control dependency: [try], data = [none]
resync(replicationTrigger,
replicaStorage, replicaQuery,
masterStorage, masterQuery,
listener,
throttle, desiredSpeed,
comparator, replicaTxn);
// depends on control dependency: [try], data = [none]
replicaTxn.commit();
// depends on control dependency: [try], data = [none]
} finally {
replicaTxn.exit();
}
} }
|
public class class_name {
public Task withContainers(Container... containers) {
if (this.containers == null) {
setContainers(new com.amazonaws.internal.SdkInternalList<Container>(containers.length));
}
for (Container ele : containers) {
this.containers.add(ele);
}
return this;
} }
|
public class class_name {
public Task withContainers(Container... containers) {
if (this.containers == null) {
setContainers(new com.amazonaws.internal.SdkInternalList<Container>(containers.length)); // depends on control dependency: [if], data = [none]
}
for (Container ele : containers) {
this.containers.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} }
|
public class class_name {
public void marshall(GetApiMappingRequest getApiMappingRequest, ProtocolMarshaller protocolMarshaller) {
if (getApiMappingRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getApiMappingRequest.getApiMappingId(), APIMAPPINGID_BINDING);
protocolMarshaller.marshall(getApiMappingRequest.getDomainName(), DOMAINNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(GetApiMappingRequest getApiMappingRequest, ProtocolMarshaller protocolMarshaller) {
if (getApiMappingRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getApiMappingRequest.getApiMappingId(), APIMAPPINGID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getApiMappingRequest.getDomainName(), DOMAINNAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private void checkSubArray(byte[] test, byte[] data, int offset) {
Preconditions.checkArgument(data.length >= test.length + offset);
for (int i = 0; i < test.length; i++) {
Preconditions.checkArgument(test[i] == data[i + offset]);
}
} }
|
public class class_name {
private void checkSubArray(byte[] test, byte[] data, int offset) {
Preconditions.checkArgument(data.length >= test.length + offset);
for (int i = 0; i < test.length; i++) {
Preconditions.checkArgument(test[i] == data[i + offset]); // depends on control dependency: [for], data = [i]
}
} }
|
public class class_name {
public SafeStyleBuilder fontFamilyAppend(String value, String... otherValues) {
sanitizeAndAppendToFontFamily(value);
for (String otherValue : otherValues) {
sanitizeAndAppendToFontFamily(otherValue);
}
return this;
} }
|
public class class_name {
public SafeStyleBuilder fontFamilyAppend(String value, String... otherValues) {
sanitizeAndAppendToFontFamily(value);
for (String otherValue : otherValues) {
sanitizeAndAppendToFontFamily(otherValue); // depends on control dependency: [for], data = [otherValue]
}
return this;
} }
|
public class class_name {
private static List<String> splitOuter(String str, char sepChr) {
List<String> result = new ArrayList<String>();
StringBuilder buffer = new StringBuilder();
int nesting = 0;
boolean bInQuote = false;
for (int index = 0; index < str.length(); index++) {
char ch = str.charAt(index);
switch (ch) {
case '(':
buffer.append(ch);
nesting++;
break;
case ')':
buffer.append(ch);
nesting--;
break;
case '\'':
case '"':
buffer.append(ch);
if (bInQuote) {
nesting--;
} else {
nesting++;
}
bInQuote = !bInQuote;
break;
case ',':
if (nesting == 0) {
result.add(buffer.toString());
buffer.setLength(0);
} else {
buffer.append(ch);
}
break;
default:
buffer.append(ch);
}
}
if (buffer.length() > 0) {
result.add(buffer.toString());
}
return result;
} }
|
public class class_name {
private static List<String> splitOuter(String str, char sepChr) {
List<String> result = new ArrayList<String>();
StringBuilder buffer = new StringBuilder();
int nesting = 0;
boolean bInQuote = false;
for (int index = 0; index < str.length(); index++) {
char ch = str.charAt(index);
switch (ch) {
case '(':
buffer.append(ch);
nesting++;
break;
case ')':
buffer.append(ch);
nesting--;
break;
case '\'':
case '"':
buffer.append(ch);
if (bInQuote) {
nesting--;
// depends on control dependency: [if], data = [none]
} else {
nesting++;
// depends on control dependency: [if], data = [none]
}
bInQuote = !bInQuote;
break;
case ',':
if (nesting == 0) {
result.add(buffer.toString());
// depends on control dependency: [if], data = [none]
buffer.setLength(0);
// depends on control dependency: [if], data = [0)]
} else {
buffer.append(ch);
// depends on control dependency: [if], data = [none]
}
break;
default:
buffer.append(ch);
}
}
if (buffer.length() > 0) {
result.add(buffer.toString());
// depends on control dependency: [if], data = [none]
}
return result;
} }
|
public class class_name {
public static NavigationAnimation createZoomIn(MapPresenter mapPresenter, Coordinate position) {
View endView = null;
int index = mapPresenter.getViewPort().getResolutionIndex(mapPresenter.getViewPort().getResolution());
if (index < mapPresenter.getViewPort().getResolutionCount() - 1) {
endView = new View(position, mapPresenter.getViewPort().getResolution(index + 1));
} else {
endView = new View(position, mapPresenter.getViewPort().getResolution());
}
return new NavigationAnimationImpl(mapPresenter.getViewPort(), mapPresenter.getEventBus(),
new LinearTrajectory(mapPresenter.getViewPort().getView(), endView), getMillis(mapPresenter));
} }
|
public class class_name {
public static NavigationAnimation createZoomIn(MapPresenter mapPresenter, Coordinate position) {
View endView = null;
int index = mapPresenter.getViewPort().getResolutionIndex(mapPresenter.getViewPort().getResolution());
if (index < mapPresenter.getViewPort().getResolutionCount() - 1) {
endView = new View(position, mapPresenter.getViewPort().getResolution(index + 1)); // depends on control dependency: [if], data = [(index]
} else {
endView = new View(position, mapPresenter.getViewPort().getResolution()); // depends on control dependency: [if], data = [none]
}
return new NavigationAnimationImpl(mapPresenter.getViewPort(), mapPresenter.getEventBus(),
new LinearTrajectory(mapPresenter.getViewPort().getView(), endView), getMillis(mapPresenter));
} }
|
public class class_name {
public final boolean addExpirable(Expirable expirable) throws SevereMessageStoreException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
{
SibTr.entry(tc, "addExpirable",
"objId="
+ (expirable == null ? "null" : String.valueOf(expirable.expirableGetID()))
+ " addEnabled="
+ addEnabled);
}
boolean reply = false;
// Ignore this entry if the expirer has ended or the given entry is null
if (addEnabled && expirable != null)
{
long expiryTime = expirable.expirableGetExpiryTime();
ExpirableReference expirableRef = new ExpirableReference(expirable);
expirableRef.setExpiryTime(expiryTime);
// Ignore this entry if the referenced item has already gone from the message store.
if (expirable.expirableIsInStore())
{
synchronized (lockObject)
{
// Add the expirable to the expiry index
reply = expiryIndex.put(expirableRef);
if (reply)
{
boolean scheduled = false;
if (runEnabled && expiryIndex.size() == 1) // We just added the first entry
{
scheduleAlarm(interval);
scheduled = true;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "Added: ET="+expirableRef.getExpiryTime()+", objId="+expirableRef.getID()+", scheduled="+scheduled);
}
}
else
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "Duplicate expirable: ET="+expirableRef.getExpiryTime()+", objId="+expirableRef.getID());
}
runEnabled = false; // End the expiry daemon thread
Object[] o = { expirableRef.getExpiryTime() + " : " + expirableRef.getID()};
SevereMessageStoreException e = new SevereMessageStoreException("DUPLICATE_EXPIRABLE_SIMS2000", o);
lastException = e;
lastExceptionTime = timeNow();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "addExpirable");
throw e;
}
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "addExpirable", "reply=" + reply);
return reply;
} }
|
public class class_name {
public final boolean addExpirable(Expirable expirable) throws SevereMessageStoreException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
{
SibTr.entry(tc, "addExpirable",
"objId="
+ (expirable == null ? "null" : String.valueOf(expirable.expirableGetID()))
+ " addEnabled="
+ addEnabled);
}
boolean reply = false;
// Ignore this entry if the expirer has ended or the given entry is null
if (addEnabled && expirable != null)
{
long expiryTime = expirable.expirableGetExpiryTime();
ExpirableReference expirableRef = new ExpirableReference(expirable);
expirableRef.setExpiryTime(expiryTime);
// Ignore this entry if the referenced item has already gone from the message store.
if (expirable.expirableIsInStore())
{
synchronized (lockObject) // depends on control dependency: [if], data = [none]
{
// Add the expirable to the expiry index
reply = expiryIndex.put(expirableRef);
if (reply)
{
boolean scheduled = false;
if (runEnabled && expiryIndex.size() == 1) // We just added the first entry
{
scheduleAlarm(interval); // depends on control dependency: [if], data = [none]
scheduled = true; // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "Added: ET="+expirableRef.getExpiryTime()+", objId="+expirableRef.getID()+", scheduled="+scheduled); // depends on control dependency: [if], data = [none]
}
}
else
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "Duplicate expirable: ET="+expirableRef.getExpiryTime()+", objId="+expirableRef.getID()); // depends on control dependency: [if], data = [none]
}
runEnabled = false; // End the expiry daemon thread // depends on control dependency: [if], data = [none]
Object[] o = { expirableRef.getExpiryTime() + " : " + expirableRef.getID()};
SevereMessageStoreException e = new SevereMessageStoreException("DUPLICATE_EXPIRABLE_SIMS2000", o);
lastException = e; // depends on control dependency: [if], data = [none]
lastExceptionTime = timeNow(); // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "addExpirable");
throw e;
}
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "addExpirable", "reply=" + reply);
return reply;
} }
|
public class class_name {
@Override
protected Tile retrieveTile(int x, int y, int zoom) {
Tile tile = null;
for (BoundedOverlay overlay : overlays) {
tile = overlay.retrieveTile(x, y, zoom);
if (tile != null) {
break;
}
}
return tile;
} }
|
public class class_name {
@Override
protected Tile retrieveTile(int x, int y, int zoom) {
Tile tile = null;
for (BoundedOverlay overlay : overlays) {
tile = overlay.retrieveTile(x, y, zoom); // depends on control dependency: [for], data = [overlay]
if (tile != null) {
break;
}
}
return tile;
} }
|
public class class_name {
public Double linearInterpolateY( Double xValue ) {
Double first = xList.get(0);
Double last = xList.get(xList.size() - 1);
// check out of range
if (first <= last) {
if (xValue < xList.get(0) || xValue > xList.get(xList.size() - 1)) {
return new Double(Double.NaN);
}
isInverse = false;
} else {
// inverse proportional
if (xValue > xList.get(0) || xValue < xList.get(xList.size() - 1)) {
return new Double(Double.NaN);
}
isInverse = true;
}
for( int i = 0; i < xList.size(); i++ ) {
Double x2 = xList.get(i);
// if equal to a number in the list
if (x2.equals(xValue)) {
return yList.get(i);
}// else interpolate
else if ((!isInverse && x2 > xValue) || (isInverse && x2 < xValue)) {
double x1 = xList.get(i - 1);
double y1 = yList.get(i - 1);
double y2 = yList.get(i);
double y = (y2 - y1) * (xValue - x1) / (x2 - x1) + y1;
return y;
}
}
return new Double(Double.NaN);
} }
|
public class class_name {
public Double linearInterpolateY( Double xValue ) {
Double first = xList.get(0);
Double last = xList.get(xList.size() - 1);
// check out of range
if (first <= last) {
if (xValue < xList.get(0) || xValue > xList.get(xList.size() - 1)) {
return new Double(Double.NaN); // depends on control dependency: [if], data = [none]
}
isInverse = false; // depends on control dependency: [if], data = [none]
} else {
// inverse proportional
if (xValue > xList.get(0) || xValue < xList.get(xList.size() - 1)) {
return new Double(Double.NaN); // depends on control dependency: [if], data = [none]
}
isInverse = true; // depends on control dependency: [if], data = [none]
}
for( int i = 0; i < xList.size(); i++ ) {
Double x2 = xList.get(i);
// if equal to a number in the list
if (x2.equals(xValue)) {
return yList.get(i); // depends on control dependency: [if], data = [none]
}// else interpolate
else if ((!isInverse && x2 > xValue) || (isInverse && x2 < xValue)) {
double x1 = xList.get(i - 1);
double y1 = yList.get(i - 1);
double y2 = yList.get(i);
double y = (y2 - y1) * (xValue - x1) / (x2 - x1) + y1;
return y; // depends on control dependency: [if], data = [none]
}
}
return new Double(Double.NaN);
} }
|
public class class_name {
public RESTResponse call(RESTClient restClient){
String methodName = getMethod();
String uri = getURI();
StringBuilder uriBuilder = new StringBuilder(Utils.isEmpty(restClient.getApiPrefix()) ? "" : "/" + restClient.getApiPrefix());
uriBuilder.append(substitute(uri));
uri = uriBuilder.toString();
try {
byte[] body = getBody(methodName);
RESTResponse response = sendRequest(restClient, methodName, uri, body);
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
} }
|
public class class_name {
public RESTResponse call(RESTClient restClient){
String methodName = getMethod();
String uri = getURI();
StringBuilder uriBuilder = new StringBuilder(Utils.isEmpty(restClient.getApiPrefix()) ? "" : "/" + restClient.getApiPrefix());
uriBuilder.append(substitute(uri));
uri = uriBuilder.toString();
try {
byte[] body = getBody(methodName);
RESTResponse response = sendRequest(restClient, methodName, uri, body);
return response; // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static List<String> findSchemas(JdbcTemplate jdbcTemplate, final String schemaPattern,
final DdlSchemaFilter ddlSchemaFilter) {
List<String> schemas = findSchemas(jdbcTemplate, schemaPattern);
if (ddlSchemaFilter == null) {
return schemas;
}
List<String> filterSchemas = new ArrayList<String>();
for (String schema : schemas) {
if (ddlSchemaFilter.accept(schema)) {
filterSchemas.add(schema);
}
}
return filterSchemas;
} }
|
public class class_name {
public static List<String> findSchemas(JdbcTemplate jdbcTemplate, final String schemaPattern,
final DdlSchemaFilter ddlSchemaFilter) {
List<String> schemas = findSchemas(jdbcTemplate, schemaPattern);
if (ddlSchemaFilter == null) {
return schemas; // depends on control dependency: [if], data = [none]
}
List<String> filterSchemas = new ArrayList<String>();
for (String schema : schemas) {
if (ddlSchemaFilter.accept(schema)) {
filterSchemas.add(schema); // depends on control dependency: [if], data = [none]
}
}
return filterSchemas;
} }
|
public class class_name {
public Map<Integer, Integer> getDegreeDistribution() {
if (degreeDistribution == null) { // has not been initialized
logger.debug("Calling setGraphParameters");
setGraphParameters();
}
return degreeDistribution;
} }
|
public class class_name {
public Map<Integer, Integer> getDegreeDistribution() {
if (degreeDistribution == null) { // has not been initialized
logger.debug("Calling setGraphParameters"); // depends on control dependency: [if], data = [none]
setGraphParameters(); // depends on control dependency: [if], data = [none]
}
return degreeDistribution;
} }
|
public class class_name {
private boolean isDependent(String style) {
if (!style.trim().startsWith("<")) {
return false;
}
Pattern p = Pattern.compile("rel\\s*=\\s*\"\\s*independent-parent\\s*\"");
Matcher m = p.matcher(style);
return m.find();
} }
|
public class class_name {
private boolean isDependent(String style) {
if (!style.trim().startsWith("<")) {
return false; // depends on control dependency: [if], data = [none]
}
Pattern p = Pattern.compile("rel\\s*=\\s*\"\\s*independent-parent\\s*\"");
Matcher m = p.matcher(style);
return m.find();
} }
|
public class class_name {
private void fireChangeFromNative() {
// skip firing the change event, if the external flag is set
if (m_initialized && !m_externalValueChange && m_active) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
try {
fireValueChange(false);
} catch (Throwable t) {
// this may happen when returning from full screen mode, nothing to be done
}
}
});
}
// reset the external flag
m_externalValueChange = false;
} }
|
public class class_name {
private void fireChangeFromNative() {
// skip firing the change event, if the external flag is set
if (m_initialized && !m_externalValueChange && m_active) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
try {
fireValueChange(false);
// depends on control dependency: [try], data = [none]
} catch (Throwable t) {
// this may happen when returning from full screen mode, nothing to be done
}
// depends on control dependency: [catch], data = [none]
}
});
// depends on control dependency: [if], data = [none]
}
// reset the external flag
m_externalValueChange = false;
} }
|
public class class_name {
public static Version getSpecificationVersionFor(Class<?> type)
{
Assert.notNull(type, "Type must not be null.");
final Version result;
Package pkg = type.getPackage();
if (pkg == null)
{
result = EmptyVersion.getInstance();
}
else
{
String version = pkg.getSpecificationVersion();
if (Strings.isNullOrEmpty(version))
{
result = EmptyVersion.getInstance();
}
else
{
result = SingleVersion.valueOf(version);
}
}
return result;
} }
|
public class class_name {
public static Version getSpecificationVersionFor(Class<?> type)
{
Assert.notNull(type, "Type must not be null.");
final Version result;
Package pkg = type.getPackage();
if (pkg == null)
{
result = EmptyVersion.getInstance(); // depends on control dependency: [if], data = [none]
}
else
{
String version = pkg.getSpecificationVersion();
if (Strings.isNullOrEmpty(version))
{
result = EmptyVersion.getInstance(); // depends on control dependency: [if], data = [none]
}
else
{
result = SingleVersion.valueOf(version); // depends on control dependency: [if], data = [none]
}
}
return result;
} }
|
public class class_name {
public String formatISO(
IsoDateStyle dateStyle,
IsoDecimalStyle decimalStyle,
ClockUnit precision,
ZonalOffset offset,
InfinityStyle infinityStyle
) {
MomentInterval interval = this.toCanonical();
StringBuilder buffer = new StringBuilder(65);
ChronoPrinter<Moment> printer = Iso8601Format.ofMoment(dateStyle, decimalStyle, precision, offset);
if (interval.getStart().isInfinite()) {
buffer.append(infinityStyle.displayPast(printer, Moment.axis()));
} else {
printer.print(interval.getStartAsMoment(), buffer);
}
buffer.append('/');
if (interval.getEnd().isInfinite()) {
buffer.append(infinityStyle.displayFuture(printer, Moment.axis()));
} else {
printer.print(interval.getEndAsMoment(), buffer);
}
return buffer.toString();
} }
|
public class class_name {
public String formatISO(
IsoDateStyle dateStyle,
IsoDecimalStyle decimalStyle,
ClockUnit precision,
ZonalOffset offset,
InfinityStyle infinityStyle
) {
MomentInterval interval = this.toCanonical();
StringBuilder buffer = new StringBuilder(65);
ChronoPrinter<Moment> printer = Iso8601Format.ofMoment(dateStyle, decimalStyle, precision, offset);
if (interval.getStart().isInfinite()) {
buffer.append(infinityStyle.displayPast(printer, Moment.axis())); // depends on control dependency: [if], data = [none]
} else {
printer.print(interval.getStartAsMoment(), buffer); // depends on control dependency: [if], data = [none]
}
buffer.append('/');
if (interval.getEnd().isInfinite()) {
buffer.append(infinityStyle.displayFuture(printer, Moment.axis())); // depends on control dependency: [if], data = [none]
} else {
printer.print(interval.getEndAsMoment(), buffer); // depends on control dependency: [if], data = [none]
}
return buffer.toString();
} }
|
public class class_name {
@Override
public void delete(DbSession dbSession, Collection<QProfileDto> profiles) {
if (profiles.isEmpty()) {
return;
}
Set<String> uuids = new HashSet<>();
List<QProfileDto> customProfiles = new ArrayList<>();
Set<String> rulesProfileUuidsOfCustomProfiles = new HashSet<>();
profiles.forEach(p -> {
uuids.add(p.getKee());
if (!p.isBuiltIn()) {
customProfiles.add(p);
rulesProfileUuidsOfCustomProfiles.add(p.getRulesProfileUuid());
}
});
// tables org_qprofiles, default_qprofiles and project_qprofiles
// are deleted whatever custom or built-in
db.qualityProfileDao().deleteProjectAssociationsByProfileUuids(dbSession, uuids);
db.defaultQProfileDao().deleteByQProfileUuids(dbSession, uuids);
db.qualityProfileDao().deleteOrgQProfilesByUuids(dbSession, uuids);
// Permissions are only available on custom profiles
db.qProfileEditUsersDao().deleteByQProfiles(dbSession, customProfiles);
db.qProfileEditGroupsDao().deleteByQProfiles(dbSession, customProfiles);
// tables related to rules_profiles and active_rules are deleted
// only for custom profiles. Built-in profiles are never
// deleted from table rules_profiles.
if (!rulesProfileUuidsOfCustomProfiles.isEmpty()) {
db.activeRuleDao().deleteParametersByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.activeRuleDao().deleteByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.qProfileChangeDao().deleteByRulesProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.qualityProfileDao().deleteRulesProfilesByUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
activeRuleIndexer.commitDeletionOfProfiles(dbSession, customProfiles);
} else {
dbSession.commit();
}
} }
|
public class class_name {
@Override
public void delete(DbSession dbSession, Collection<QProfileDto> profiles) {
if (profiles.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
Set<String> uuids = new HashSet<>();
List<QProfileDto> customProfiles = new ArrayList<>();
Set<String> rulesProfileUuidsOfCustomProfiles = new HashSet<>();
profiles.forEach(p -> {
uuids.add(p.getKee());
if (!p.isBuiltIn()) {
customProfiles.add(p); // depends on control dependency: [if], data = [none]
rulesProfileUuidsOfCustomProfiles.add(p.getRulesProfileUuid()); // depends on control dependency: [if], data = [none]
}
});
// tables org_qprofiles, default_qprofiles and project_qprofiles
// are deleted whatever custom or built-in
db.qualityProfileDao().deleteProjectAssociationsByProfileUuids(dbSession, uuids);
db.defaultQProfileDao().deleteByQProfileUuids(dbSession, uuids);
db.qualityProfileDao().deleteOrgQProfilesByUuids(dbSession, uuids);
// Permissions are only available on custom profiles
db.qProfileEditUsersDao().deleteByQProfiles(dbSession, customProfiles);
db.qProfileEditGroupsDao().deleteByQProfiles(dbSession, customProfiles);
// tables related to rules_profiles and active_rules are deleted
// only for custom profiles. Built-in profiles are never
// deleted from table rules_profiles.
if (!rulesProfileUuidsOfCustomProfiles.isEmpty()) {
db.activeRuleDao().deleteParametersByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.activeRuleDao().deleteByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.qProfileChangeDao().deleteByRulesProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.qualityProfileDao().deleteRulesProfilesByUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
activeRuleIndexer.commitDeletionOfProfiles(dbSession, customProfiles);
} else {
dbSession.commit();
}
} }
|
public class class_name {
@Override
public MediaPicture toPicture(MediaPicture output,
final BufferedImage input, long timestamp) {
// validate the image
validateImage(input);
if (output == null) {
output = MediaPicture.make(mPictureWidth,
mPictureHeight, getPictureType());
}
// get the image byte buffer buffer
DataBuffer imageBuffer = input.getRaster().getDataBuffer();
byte[] imageBytes = null;
int[] imageInts = null;
// handle byte buffer case
if (imageBuffer instanceof DataBufferByte) {
imageBytes = ((DataBufferByte) imageBuffer).getData();
}
// handle integer buffer case
else if (imageBuffer instanceof DataBufferInt) {
imageInts = ((DataBufferInt) imageBuffer).getData();
}
// if it's some other type, throw
else {
throw new IllegalArgumentException(
"Unsupported BufferedImage data buffer type: "
+ imageBuffer.getDataType());
}
// create the video picture and get it's underlying buffer
final AtomicReference<JNIReference> ref = new AtomicReference<JNIReference>(
null);
final MediaPicture picture = willResample() ? mResampleMediaPicture : output;
try {
Buffer buffer = picture.getData(0);
int size = picture.getDataPlaneSize(0);
ByteBuffer pictureByteBuffer = buffer.getByteBuffer(0,
size, ref);
buffer.delete();
buffer = null;
if (imageInts != null) {
pictureByteBuffer.order(ByteOrder.BIG_ENDIAN);
IntBuffer pictureIntBuffer = pictureByteBuffer.asIntBuffer();
pictureIntBuffer.put(imageInts);
} else {
pictureByteBuffer.put(imageBytes);
}
pictureByteBuffer = null;
picture.setTimeStamp(timestamp);
picture.setComplete(true);
// resample as needed
if (willResample()) {
resample(output, picture, mToPictureResampler);
}
return output;
} finally {
if (ref.get() != null)
ref.get().delete();
}
} }
|
public class class_name {
@Override
public MediaPicture toPicture(MediaPicture output,
final BufferedImage input, long timestamp) {
// validate the image
validateImage(input);
if (output == null) {
output = MediaPicture.make(mPictureWidth,
mPictureHeight, getPictureType()); // depends on control dependency: [if], data = [none]
}
// get the image byte buffer buffer
DataBuffer imageBuffer = input.getRaster().getDataBuffer();
byte[] imageBytes = null;
int[] imageInts = null;
// handle byte buffer case
if (imageBuffer instanceof DataBufferByte) {
imageBytes = ((DataBufferByte) imageBuffer).getData(); // depends on control dependency: [if], data = [none]
}
// handle integer buffer case
else if (imageBuffer instanceof DataBufferInt) {
imageInts = ((DataBufferInt) imageBuffer).getData(); // depends on control dependency: [if], data = [none]
}
// if it's some other type, throw
else {
throw new IllegalArgumentException(
"Unsupported BufferedImage data buffer type: "
+ imageBuffer.getDataType());
}
// create the video picture and get it's underlying buffer
final AtomicReference<JNIReference> ref = new AtomicReference<JNIReference>(
null);
final MediaPicture picture = willResample() ? mResampleMediaPicture : output;
try {
Buffer buffer = picture.getData(0);
int size = picture.getDataPlaneSize(0);
ByteBuffer pictureByteBuffer = buffer.getByteBuffer(0,
size, ref);
buffer.delete(); // depends on control dependency: [try], data = [none]
buffer = null; // depends on control dependency: [try], data = [none]
if (imageInts != null) {
pictureByteBuffer.order(ByteOrder.BIG_ENDIAN); // depends on control dependency: [if], data = [none]
IntBuffer pictureIntBuffer = pictureByteBuffer.asIntBuffer();
pictureIntBuffer.put(imageInts); // depends on control dependency: [if], data = [(imageInts]
} else {
pictureByteBuffer.put(imageBytes); // depends on control dependency: [if], data = [none]
}
pictureByteBuffer = null; // depends on control dependency: [try], data = [none]
picture.setTimeStamp(timestamp); // depends on control dependency: [try], data = [none]
picture.setComplete(true); // depends on control dependency: [try], data = [none]
// resample as needed
if (willResample()) {
resample(output, picture, mToPictureResampler); // depends on control dependency: [if], data = [none]
}
return output; // depends on control dependency: [try], data = [none]
} finally {
if (ref.get() != null)
ref.get().delete();
}
} }
|
public class class_name {
@SuppressWarnings("unchecked")
@Override
public Object commit(long batchId, Object state) {
List<Object> stateList = (List<Object>) state;
if (stateOperator != null) {
Object commitState = stateOperator.commit(batchId, stateList);
stateList.add(commitState);
}
return stateList;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
@Override
public Object commit(long batchId, Object state) {
List<Object> stateList = (List<Object>) state;
if (stateOperator != null) {
Object commitState = stateOperator.commit(batchId, stateList);
stateList.add(commitState); // depends on control dependency: [if], data = [none]
}
return stateList;
} }
|
public class class_name {
public org.openprovenance.prov.model.Value getValue() {
if (value==null) {
if (all!=null) { // TODO: inefficient, I search this list every time getValue is called, though there may be no value
for (Attribute attr: all) {
if (attr instanceof org.openprovenance.prov.model.Value) {
value=(Value)attr;
}
}
}
}
return value;
} }
|
public class class_name {
public org.openprovenance.prov.model.Value getValue() {
if (value==null) {
if (all!=null) { // TODO: inefficient, I search this list every time getValue is called, though there may be no value
for (Attribute attr: all) {
if (attr instanceof org.openprovenance.prov.model.Value) {
value=(Value)attr; // depends on control dependency: [if], data = [none]
}
}
}
}
return value;
} }
|
public class class_name {
public static Object invoke(Class<?> returnType, String className, String methodName) {
// If we have an explicit implementation for this method, invoke it
if (STUB_METHODS.containsKey(new ClassAndMethod(className, methodName))) {
return STUB_METHODS.get(new ClassAndMethod(className, methodName)).invoke();
}
// Otherwise return an appropriate basic type
if (returnType == String.class) {
return "";
} else if (returnType == Boolean.class) {
return false;
} else if (returnType == Byte.class) {
return (byte) 0;
} else if (returnType == Character.class) {
return (char) 0;
} else if (returnType == Double.class) {
return (double) 0;
} else if (returnType == Integer.class) {
return (int) 0;
} else if (returnType == Float.class) {
return (float) 0;
} else if (returnType == Long.class) {
return (long) 0;
} else if (returnType == Short.class) {
return (short) 0;
} else {
return Mockito.mock(returnType, new ReturnsCustomMocks());
}
} }
|
public class class_name {
public static Object invoke(Class<?> returnType, String className, String methodName) {
// If we have an explicit implementation for this method, invoke it
if (STUB_METHODS.containsKey(new ClassAndMethod(className, methodName))) {
return STUB_METHODS.get(new ClassAndMethod(className, methodName)).invoke(); // depends on control dependency: [if], data = [none]
}
// Otherwise return an appropriate basic type
if (returnType == String.class) {
return ""; // depends on control dependency: [if], data = [none]
} else if (returnType == Boolean.class) {
return false; // depends on control dependency: [if], data = [none]
} else if (returnType == Byte.class) {
return (byte) 0; // depends on control dependency: [if], data = [none]
} else if (returnType == Character.class) {
return (char) 0; // depends on control dependency: [if], data = [none]
} else if (returnType == Double.class) {
return (double) 0; // depends on control dependency: [if], data = [none]
} else if (returnType == Integer.class) {
return (int) 0; // depends on control dependency: [if], data = [none]
} else if (returnType == Float.class) {
return (float) 0; // depends on control dependency: [if], data = [none]
} else if (returnType == Long.class) {
return (long) 0; // depends on control dependency: [if], data = [none]
} else if (returnType == Short.class) {
return (short) 0; // depends on control dependency: [if], data = [none]
} else {
return Mockito.mock(returnType, new ReturnsCustomMocks()); // depends on control dependency: [if], data = [(returnType]
}
} }
|
public class class_name {
protected void processResource(Row row)
{
Integer uniqueID = row.getInteger("RES_UID");
if (uniqueID != null && uniqueID.intValue() >= 0)
{
Resource resource = m_project.addResource();
resource.setAccrueAt(AccrueType.getInstance(row.getInt("RES_ACCRUE_AT")));
resource.setActualCost(getDefaultOnNull(row.getCurrency("RES_ACT_COST"), NumberHelper.DOUBLE_ZERO));
resource.setActualOvertimeCost(row.getCurrency("RES_ACT_OVT_COST"));
resource.setActualOvertimeWork(row.getDuration("RES_ACT_OVT_WORK"));
//resource.setActualOvertimeWorkProtected();
resource.setActualWork(row.getDuration("RES_ACT_WORK"));
//resource.setActualWorkProtected();
//resource.setActveDirectoryGUID();
resource.setACWP(row.getCurrency("RES_ACWP"));
resource.setAvailableFrom(row.getDate("RES_AVAIL_FROM"));
resource.setAvailableTo(row.getDate("RES_AVAIL_TO"));
//resource.setBaseCalendar();
resource.setBaselineCost(getDefaultOnNull(row.getCurrency("RES_BASE_COST"), NumberHelper.DOUBLE_ZERO));
resource.setBaselineWork(row.getDuration("RES_BASE_WORK"));
resource.setBCWP(row.getCurrency("RES_BCWP"));
resource.setBCWS(row.getCurrency("RES_BCWS"));
//resource.setBookingType();
resource.setCanLevel(row.getBoolean("RES_CAN_LEVEL"));
//resource.setCode();
resource.setCost(getDefaultOnNull(row.getCurrency("RES_COST"), NumberHelper.DOUBLE_ZERO));
//resource.setCost1();
//resource.setCost2();
//resource.setCost3();
//resource.setCost4();
//resource.setCost5();
//resource.setCost6();
//resource.setCost7();
//resource.setCost8();
//resource.setCost9();
//resource.setCost10();
resource.setCostPerUse(row.getCurrency("RES_COST_PER_USE"));
//resource.setCreationDate();
//resource.setCV();
//resource.setDate1();
//resource.setDate2();
//resource.setDate3();
//resource.setDate4();
//resource.setDate5();
//resource.setDate6();
//resource.setDate7();
//resource.setDate8();
//resource.setDate9();
//resource.setDate10();
//resource.setDuration1();
//resource.setDuration2();
//resource.setDuration3();
//resource.setDuration4();
//resource.setDuration5();
//resource.setDuration6();
//resource.setDuration7();
//resource.setDuration8();
//resource.setDuration9();
//resource.setDuration10();
//resource.setEmailAddress();
//resource.setFinish();
//resource.setFinish1();
//resource.setFinish2();
//resource.setFinish3();
//resource.setFinish4();
//resource.setFinish5();
//resource.setFinish6();
//resource.setFinish7();
//resource.setFinish8();
//resource.setFinish9();
//resource.setFinish10();
//resource.setFlag1();
//resource.setFlag2();
//resource.setFlag3();
//resource.setFlag4();
//resource.setFlag5();
//resource.setFlag6();
//resource.setFlag7();
//resource.setFlag8();
//resource.setFlag9();
//resource.setFlag10();
//resource.setFlag11();
//resource.setFlag12();
//resource.setFlag13();
//resource.setFlag14();
//resource.setFlag15();
//resource.setFlag16();
//resource.setFlag17();
//resource.setFlag18();
//resource.setFlag19();
//resource.setFlag20();
//resource.setGroup();
//resource.setHyperlink();
//resource.setHyperlinkAddress();
//resource.setHyperlinkSubAddress();
resource.setID(row.getInteger("RES_ID"));
resource.setInitials(row.getString("RES_INITIALS"));
//resource.setIsEnterprise();
//resource.setIsGeneric();
//resource.setIsInactive();
//resource.setIsNull();
//resource.setLinkedFields();RES_HAS_LINKED_FIELDS = false ( java.lang.Boolean)
resource.setMaterialLabel(row.getString("RES_MATERIAL_LABEL"));
resource.setMaxUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble("RES_MAX_UNITS")) * 100));
resource.setName(row.getString("RES_NAME"));
//resource.setNtAccount();
//resource.setNumber1();
//resource.setNumber2();
//resource.setNumber3();
//resource.setNumber4();
//resource.setNumber5();
//resource.setNumber6();
//resource.setNumber7();
//resource.setNumber8();
//resource.setNumber9();
//resource.setNumber10();
//resource.setNumber11();
//resource.setNumber12();
//resource.setNumber13();
//resource.setNumber14();
//resource.setNumber15();
//resource.setNumber16();
//resource.setNumber17();
//resource.setNumber18();
//resource.setNumber19();
//resource.setNumber20();
resource.setObjects(getNullOnValue(row.getInteger("RES_NUM_OBJECTS"), 0));
//resource.setOutlineCode1();
//resource.setOutlineCode2();
//resource.setOutlineCode3();
//resource.setOutlineCode4();
//resource.setOutlineCode5();
//resource.setOutlineCode6();
//resource.setOutlineCode7();
//resource.setOutlineCode8();
//resource.setOutlineCode9();
//resource.setOutlineCode10();
resource.setOverAllocated(row.getBoolean("RES_IS_OVERALLOCATED"));
resource.setOvertimeCost(row.getCurrency("RES_OVT_COST"));
resource.setOvertimeRate(new Rate(row.getDouble("RES_OVT_RATE"), TimeUnit.HOURS));
resource.setOvertimeRateUnits(TimeUnit.getInstance(row.getInt("RES_OVT_RATE_FMT") - 1));
resource.setOvertimeWork(row.getDuration("RES_OVT_WORK"));
resource.setPeakUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble("RES_PEAK")) * 100));
//resource.setPercentWorkComplete();
resource.setPhonetics(row.getString("RES_PHONETICS"));
resource.setRegularWork(row.getDuration("RES_REG_WORK"));
resource.setRemainingCost(getDefaultOnNull(row.getCurrency("RES_REM_COST"), NumberHelper.DOUBLE_ZERO));
resource.setRemainingOvertimeCost(row.getCurrency("RES_REM_OVT_COST"));
resource.setRemainingOvertimeWork(row.getDuration("RES_REM_OVT_WORK"));
resource.setRemainingWork(row.getDuration("RES_REM_WORK"));
//resource.setResourceCalendar();RES_CAL_UID = null ( ) // CHECK THIS
resource.setStandardRate(new Rate(row.getDouble("RES_STD_RATE"), TimeUnit.HOURS));
resource.setStandardRateUnits(TimeUnit.getInstance(row.getInt("RES_STD_RATE_FMT") - 1));
//resource.setStart();
//resource.setStart1();
//resource.setStart2();
//resource.setStart3();
//resource.setStart4();
//resource.setStart5();
//resource.setStart6();
//resource.setStart7();
//resource.setStart8();
//resource.setStart9();
//resource.setStart10();
//resource.setText1();
//resource.setText2();
//resource.setText3();
//resource.setText4();
//resource.setText5();
//resource.setText6();
//resource.setText7();
//resource.setText8();
//resource.setText9();
//resource.setText10();
//resource.setText11();
//resource.setText12();
//resource.setText13();
//resource.setText14();
//resource.setText15();
//resource.setText16();
//resource.setText17();
//resource.setText18();
//resource.setText19();
//resource.setText20();
//resource.setText21();
//resource.setText22();
//resource.setText23();
//resource.setText24();
//resource.setText25();
//resource.setText26();
//resource.setText27();
//resource.setText28();
//resource.setText29();
//resource.setText30();
resource.setType(row.getBoolean("RES_TYPE") ? ResourceType.WORK : ResourceType.MATERIAL);
resource.setUniqueID(uniqueID);
resource.setWork(row.getDuration("RES_WORK"));
resource.setWorkGroup(WorkGroup.getInstance(row.getInt("RES_WORKGROUP_MESSAGING")));
String notes = row.getString("RES_RTF_NOTES");
if (notes != null)
{
if (m_preserveNoteFormatting == false)
{
notes = RtfHelper.strip(notes);
}
resource.setNotes(notes);
}
resource.setResourceCalendar(m_project.getCalendarByUniqueID(row.getInteger("RES_CAL_UID")));
//
// Calculate the cost variance
//
if (resource.getCost() != null && resource.getBaselineCost() != null)
{
resource.setCostVariance(NumberHelper.getDouble(resource.getCost().doubleValue() - resource.getBaselineCost().doubleValue()));
}
//
// Calculate the work variance
//
if (resource.getWork() != null && resource.getBaselineWork() != null)
{
resource.setWorkVariance(Duration.getInstance(resource.getWork().getDuration() - resource.getBaselineWork().getDuration(), TimeUnit.HOURS));
}
//
// Set the overallocated flag
//
resource.setOverAllocated(NumberHelper.getDouble(resource.getPeakUnits()) > NumberHelper.getDouble(resource.getMaxUnits()));
m_eventManager.fireResourceReadEvent(resource);
//
// Unused attributes
//
//EXT_EDIT_REF_DATA = null ( )
//RESERVED_DATA = null ( )
}
} }
|
public class class_name {
protected void processResource(Row row)
{
Integer uniqueID = row.getInteger("RES_UID");
if (uniqueID != null && uniqueID.intValue() >= 0)
{
Resource resource = m_project.addResource();
resource.setAccrueAt(AccrueType.getInstance(row.getInt("RES_ACCRUE_AT"))); // depends on control dependency: [if], data = [none]
resource.setActualCost(getDefaultOnNull(row.getCurrency("RES_ACT_COST"), NumberHelper.DOUBLE_ZERO)); // depends on control dependency: [if], data = [none]
resource.setActualOvertimeCost(row.getCurrency("RES_ACT_OVT_COST")); // depends on control dependency: [if], data = [none]
resource.setActualOvertimeWork(row.getDuration("RES_ACT_OVT_WORK")); // depends on control dependency: [if], data = [none]
//resource.setActualOvertimeWorkProtected();
resource.setActualWork(row.getDuration("RES_ACT_WORK")); // depends on control dependency: [if], data = [none]
//resource.setActualWorkProtected();
//resource.setActveDirectoryGUID();
resource.setACWP(row.getCurrency("RES_ACWP")); // depends on control dependency: [if], data = [none]
resource.setAvailableFrom(row.getDate("RES_AVAIL_FROM")); // depends on control dependency: [if], data = [none]
resource.setAvailableTo(row.getDate("RES_AVAIL_TO")); // depends on control dependency: [if], data = [none]
//resource.setBaseCalendar();
resource.setBaselineCost(getDefaultOnNull(row.getCurrency("RES_BASE_COST"), NumberHelper.DOUBLE_ZERO)); // depends on control dependency: [if], data = [none]
resource.setBaselineWork(row.getDuration("RES_BASE_WORK")); // depends on control dependency: [if], data = [none]
resource.setBCWP(row.getCurrency("RES_BCWP")); // depends on control dependency: [if], data = [none]
resource.setBCWS(row.getCurrency("RES_BCWS")); // depends on control dependency: [if], data = [none]
//resource.setBookingType();
resource.setCanLevel(row.getBoolean("RES_CAN_LEVEL")); // depends on control dependency: [if], data = [none]
//resource.setCode();
resource.setCost(getDefaultOnNull(row.getCurrency("RES_COST"), NumberHelper.DOUBLE_ZERO)); // depends on control dependency: [if], data = [none]
//resource.setCost1();
//resource.setCost2();
//resource.setCost3();
//resource.setCost4();
//resource.setCost5();
//resource.setCost6();
//resource.setCost7();
//resource.setCost8();
//resource.setCost9();
//resource.setCost10();
resource.setCostPerUse(row.getCurrency("RES_COST_PER_USE")); // depends on control dependency: [if], data = [none]
//resource.setCreationDate();
//resource.setCV();
//resource.setDate1();
//resource.setDate2();
//resource.setDate3();
//resource.setDate4();
//resource.setDate5();
//resource.setDate6();
//resource.setDate7();
//resource.setDate8();
//resource.setDate9();
//resource.setDate10();
//resource.setDuration1();
//resource.setDuration2();
//resource.setDuration3();
//resource.setDuration4();
//resource.setDuration5();
//resource.setDuration6();
//resource.setDuration7();
//resource.setDuration8();
//resource.setDuration9();
//resource.setDuration10();
//resource.setEmailAddress();
//resource.setFinish();
//resource.setFinish1();
//resource.setFinish2();
//resource.setFinish3();
//resource.setFinish4();
//resource.setFinish5();
//resource.setFinish6();
//resource.setFinish7();
//resource.setFinish8();
//resource.setFinish9();
//resource.setFinish10();
//resource.setFlag1();
//resource.setFlag2();
//resource.setFlag3();
//resource.setFlag4();
//resource.setFlag5();
//resource.setFlag6();
//resource.setFlag7();
//resource.setFlag8();
//resource.setFlag9();
//resource.setFlag10();
//resource.setFlag11();
//resource.setFlag12();
//resource.setFlag13();
//resource.setFlag14();
//resource.setFlag15();
//resource.setFlag16();
//resource.setFlag17();
//resource.setFlag18();
//resource.setFlag19();
//resource.setFlag20();
//resource.setGroup();
//resource.setHyperlink();
//resource.setHyperlinkAddress();
//resource.setHyperlinkSubAddress();
resource.setID(row.getInteger("RES_ID")); // depends on control dependency: [if], data = [none]
resource.setInitials(row.getString("RES_INITIALS")); // depends on control dependency: [if], data = [none]
//resource.setIsEnterprise();
//resource.setIsGeneric();
//resource.setIsInactive();
//resource.setIsNull();
//resource.setLinkedFields();RES_HAS_LINKED_FIELDS = false ( java.lang.Boolean)
resource.setMaterialLabel(row.getString("RES_MATERIAL_LABEL")); // depends on control dependency: [if], data = [none]
resource.setMaxUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble("RES_MAX_UNITS")) * 100)); // depends on control dependency: [if], data = [none]
resource.setName(row.getString("RES_NAME")); // depends on control dependency: [if], data = [none]
//resource.setNtAccount();
//resource.setNumber1();
//resource.setNumber2();
//resource.setNumber3();
//resource.setNumber4();
//resource.setNumber5();
//resource.setNumber6();
//resource.setNumber7();
//resource.setNumber8();
//resource.setNumber9();
//resource.setNumber10();
//resource.setNumber11();
//resource.setNumber12();
//resource.setNumber13();
//resource.setNumber14();
//resource.setNumber15();
//resource.setNumber16();
//resource.setNumber17();
//resource.setNumber18();
//resource.setNumber19();
//resource.setNumber20();
resource.setObjects(getNullOnValue(row.getInteger("RES_NUM_OBJECTS"), 0)); // depends on control dependency: [if], data = [none]
//resource.setOutlineCode1();
//resource.setOutlineCode2();
//resource.setOutlineCode3();
//resource.setOutlineCode4();
//resource.setOutlineCode5();
//resource.setOutlineCode6();
//resource.setOutlineCode7();
//resource.setOutlineCode8();
//resource.setOutlineCode9();
//resource.setOutlineCode10();
resource.setOverAllocated(row.getBoolean("RES_IS_OVERALLOCATED")); // depends on control dependency: [if], data = [none]
resource.setOvertimeCost(row.getCurrency("RES_OVT_COST")); // depends on control dependency: [if], data = [none]
resource.setOvertimeRate(new Rate(row.getDouble("RES_OVT_RATE"), TimeUnit.HOURS)); // depends on control dependency: [if], data = [none]
resource.setOvertimeRateUnits(TimeUnit.getInstance(row.getInt("RES_OVT_RATE_FMT") - 1)); // depends on control dependency: [if], data = [none]
resource.setOvertimeWork(row.getDuration("RES_OVT_WORK")); // depends on control dependency: [if], data = [none]
resource.setPeakUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble("RES_PEAK")) * 100)); // depends on control dependency: [if], data = [none]
//resource.setPercentWorkComplete();
resource.setPhonetics(row.getString("RES_PHONETICS")); // depends on control dependency: [if], data = [none]
resource.setRegularWork(row.getDuration("RES_REG_WORK")); // depends on control dependency: [if], data = [none]
resource.setRemainingCost(getDefaultOnNull(row.getCurrency("RES_REM_COST"), NumberHelper.DOUBLE_ZERO)); // depends on control dependency: [if], data = [none]
resource.setRemainingOvertimeCost(row.getCurrency("RES_REM_OVT_COST")); // depends on control dependency: [if], data = [none]
resource.setRemainingOvertimeWork(row.getDuration("RES_REM_OVT_WORK")); // depends on control dependency: [if], data = [none]
resource.setRemainingWork(row.getDuration("RES_REM_WORK")); // depends on control dependency: [if], data = [none]
//resource.setResourceCalendar();RES_CAL_UID = null ( ) // CHECK THIS
resource.setStandardRate(new Rate(row.getDouble("RES_STD_RATE"), TimeUnit.HOURS)); // depends on control dependency: [if], data = [none]
resource.setStandardRateUnits(TimeUnit.getInstance(row.getInt("RES_STD_RATE_FMT") - 1)); // depends on control dependency: [if], data = [none]
//resource.setStart();
//resource.setStart1();
//resource.setStart2();
//resource.setStart3();
//resource.setStart4();
//resource.setStart5();
//resource.setStart6();
//resource.setStart7();
//resource.setStart8();
//resource.setStart9();
//resource.setStart10();
//resource.setText1();
//resource.setText2();
//resource.setText3();
//resource.setText4();
//resource.setText5();
//resource.setText6();
//resource.setText7();
//resource.setText8();
//resource.setText9();
//resource.setText10();
//resource.setText11();
//resource.setText12();
//resource.setText13();
//resource.setText14();
//resource.setText15();
//resource.setText16();
//resource.setText17();
//resource.setText18();
//resource.setText19();
//resource.setText20();
//resource.setText21();
//resource.setText22();
//resource.setText23();
//resource.setText24();
//resource.setText25();
//resource.setText26();
//resource.setText27();
//resource.setText28();
//resource.setText29();
//resource.setText30();
resource.setType(row.getBoolean("RES_TYPE") ? ResourceType.WORK : ResourceType.MATERIAL); // depends on control dependency: [if], data = [none]
resource.setUniqueID(uniqueID); // depends on control dependency: [if], data = [(uniqueID]
resource.setWork(row.getDuration("RES_WORK")); // depends on control dependency: [if], data = [none]
resource.setWorkGroup(WorkGroup.getInstance(row.getInt("RES_WORKGROUP_MESSAGING"))); // depends on control dependency: [if], data = [none]
String notes = row.getString("RES_RTF_NOTES");
if (notes != null)
{
if (m_preserveNoteFormatting == false)
{
notes = RtfHelper.strip(notes); // depends on control dependency: [if], data = [none]
}
resource.setNotes(notes); // depends on control dependency: [if], data = [(notes]
}
resource.setResourceCalendar(m_project.getCalendarByUniqueID(row.getInteger("RES_CAL_UID"))); // depends on control dependency: [if], data = [none]
//
// Calculate the cost variance
//
if (resource.getCost() != null && resource.getBaselineCost() != null)
{
resource.setCostVariance(NumberHelper.getDouble(resource.getCost().doubleValue() - resource.getBaselineCost().doubleValue())); // depends on control dependency: [if], data = [(resource.getCost()]
}
//
// Calculate the work variance
//
if (resource.getWork() != null && resource.getBaselineWork() != null)
{
resource.setWorkVariance(Duration.getInstance(resource.getWork().getDuration() - resource.getBaselineWork().getDuration(), TimeUnit.HOURS)); // depends on control dependency: [if], data = [(resource.getWork()]
}
//
// Set the overallocated flag
//
resource.setOverAllocated(NumberHelper.getDouble(resource.getPeakUnits()) > NumberHelper.getDouble(resource.getMaxUnits())); // depends on control dependency: [if], data = [none]
m_eventManager.fireResourceReadEvent(resource); // depends on control dependency: [if], data = [none]
//
// Unused attributes
//
//EXT_EDIT_REF_DATA = null ( )
//RESERVED_DATA = null ( )
}
} }
|
public class class_name {
public void marshall(Resource resource, ProtocolMarshaller protocolMarshaller) {
if (resource == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resource.getName(), NAME_BINDING);
protocolMarshaller.marshall(resource.getType(), TYPE_BINDING);
protocolMarshaller.marshall(resource.getDoubleValue(), DOUBLEVALUE_BINDING);
protocolMarshaller.marshall(resource.getLongValue(), LONGVALUE_BINDING);
protocolMarshaller.marshall(resource.getIntegerValue(), INTEGERVALUE_BINDING);
protocolMarshaller.marshall(resource.getStringSetValue(), STRINGSETVALUE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(Resource resource, ProtocolMarshaller protocolMarshaller) {
if (resource == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resource.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(resource.getType(), TYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(resource.getDoubleValue(), DOUBLEVALUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(resource.getLongValue(), LONGVALUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(resource.getIntegerValue(), INTEGERVALUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(resource.getStringSetValue(), STRINGSETVALUE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private void downloadOneChunk(String accountId, String vaultName,
String jobId, RandomAccessFile output, long currentPosition,
long endPosition, ProgressListener progressListener) {
final long chunkSize = endPosition - currentPosition + 1;
TreeHashInputStream input = null;
int retries = 0;
while (true) {
try {
GetJobOutputRequest req = new GetJobOutputRequest()
.withAccountId(accountId)
.withVaultName(vaultName)
.withRange("bytes=" + currentPosition + "-" + endPosition)
.withJobId(jobId)
.withGeneralProgressListener(progressListener)
;
GetJobOutputResult jobOutputResult = glacier.getJobOutput(req);
try {
input = new TreeHashInputStream(new BufferedInputStream(jobOutputResult.getBody()));
appendToFile(output, input);
} catch (NoSuchAlgorithmException e) {
throw failure(e, "Unable to compute hash for data integrity");
} finally {
closeQuietly(input, log);
}
// Only do tree-hash check when the output checksum is returned from Glacier
if (null != jobOutputResult.getChecksum()) {
// Checksum does not match
if (!input.getTreeHash().equalsIgnoreCase(jobOutputResult.getChecksum())) {
// Discard the chunk of bytes received
publishResponseBytesDiscarded(progressListener, chunkSize);
if (log.isDebugEnabled())
log.debug("reverting " + chunkSize);
throw new IOException("Client side computed hash doesn't match server side hash; possible data corruption");
}
} else {
log.warn("Cannot validate the downloaded output since no tree-hash checksum is returned from Glacier. "
+ "Make sure the InitiateJob and GetJobOutput requests use tree-hash-aligned ranges.");
}
// Successfully download
return;
// We will retry IO exception
} catch (IOException ioe) {
if (retries < DEFAULT_MAX_RETRIES) {
retries++;
if (log.isDebugEnabled()) {
log.debug(retries
+ " retry downloadOneChunk accountId="
+ accountId + ", vaultName=" + vaultName
+ ", jobId=" + jobId + ", currentPosition="
+ currentPosition + " endPosition="
+ endPosition);
}
try {
output.seek(currentPosition);
} catch (IOException e) {
throw new AmazonClientException("Unable to download the archive: " + ioe.getMessage(), e);
}
} else {
throw new AmazonClientException("Unable to download the archive: " + ioe.getMessage(), ioe);
}
}
}
} }
|
public class class_name {
private void downloadOneChunk(String accountId, String vaultName,
String jobId, RandomAccessFile output, long currentPosition,
long endPosition, ProgressListener progressListener) {
final long chunkSize = endPosition - currentPosition + 1;
TreeHashInputStream input = null;
int retries = 0;
while (true) {
try {
GetJobOutputRequest req = new GetJobOutputRequest()
.withAccountId(accountId)
.withVaultName(vaultName)
.withRange("bytes=" + currentPosition + "-" + endPosition)
.withJobId(jobId)
.withGeneralProgressListener(progressListener)
;
GetJobOutputResult jobOutputResult = glacier.getJobOutput(req);
try {
input = new TreeHashInputStream(new BufferedInputStream(jobOutputResult.getBody())); // depends on control dependency: [try], data = [none]
appendToFile(output, input); // depends on control dependency: [try], data = [none]
} catch (NoSuchAlgorithmException e) {
throw failure(e, "Unable to compute hash for data integrity");
} finally { // depends on control dependency: [catch], data = [none]
closeQuietly(input, log);
}
// Only do tree-hash check when the output checksum is returned from Glacier
if (null != jobOutputResult.getChecksum()) {
// Checksum does not match
if (!input.getTreeHash().equalsIgnoreCase(jobOutputResult.getChecksum())) {
// Discard the chunk of bytes received
publishResponseBytesDiscarded(progressListener, chunkSize); // depends on control dependency: [if], data = [none]
if (log.isDebugEnabled())
log.debug("reverting " + chunkSize);
throw new IOException("Client side computed hash doesn't match server side hash; possible data corruption");
}
} else {
log.warn("Cannot validate the downloaded output since no tree-hash checksum is returned from Glacier. "
+ "Make sure the InitiateJob and GetJobOutput requests use tree-hash-aligned ranges."); // depends on control dependency: [if], data = [none]
}
// Successfully download
return; // depends on control dependency: [try], data = [none]
// We will retry IO exception
} catch (IOException ioe) {
if (retries < DEFAULT_MAX_RETRIES) {
retries++; // depends on control dependency: [if], data = [none]
if (log.isDebugEnabled()) {
log.debug(retries
+ " retry downloadOneChunk accountId="
+ accountId + ", vaultName=" + vaultName
+ ", jobId=" + jobId + ", currentPosition="
+ currentPosition + " endPosition="
+ endPosition); // depends on control dependency: [if], data = [none]
}
try {
output.seek(currentPosition); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new AmazonClientException("Unable to download the archive: " + ioe.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} else {
throw new AmazonClientException("Unable to download the archive: " + ioe.getMessage(), ioe);
}
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
protected synchronized void restore() {
try {
SharedPreferences prefs = WonderPushConfiguration.getSharedPreferences();
String jsonString = prefs.getString(getPrefName(), "[]");
JSONArray jsonArray = new JSONArray(jsonString);
mQueue.clear();
for (int i = 0 ; i < jsonArray.length() ; i++) {
try {
mQueue.add(new InternalJob(jsonArray.getJSONObject(i)));
} catch (JSONException ex) {
Log.e(TAG, "Failed to restore malformed job", ex);
} catch (Exception ex) {
Log.e(TAG, "Unexpected error while restoring a job", ex);
}
}
} catch (JSONException e) {
Log.e(TAG, "Could not restore job queue", e);
} catch (Exception e) {
Log.e(TAG, "Could not restore job queue", e);
}
} }
|
public class class_name {
protected synchronized void restore() {
try {
SharedPreferences prefs = WonderPushConfiguration.getSharedPreferences();
String jsonString = prefs.getString(getPrefName(), "[]");
JSONArray jsonArray = new JSONArray(jsonString);
mQueue.clear(); // depends on control dependency: [try], data = [none]
for (int i = 0 ; i < jsonArray.length() ; i++) {
try {
mQueue.add(new InternalJob(jsonArray.getJSONObject(i))); // depends on control dependency: [try], data = [none]
} catch (JSONException ex) {
Log.e(TAG, "Failed to restore malformed job", ex);
} catch (Exception ex) { // depends on control dependency: [catch], data = [none]
Log.e(TAG, "Unexpected error while restoring a job", ex);
} // depends on control dependency: [catch], data = [none]
}
} catch (JSONException e) {
Log.e(TAG, "Could not restore job queue", e);
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
Log.e(TAG, "Could not restore job queue", e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public ListenableFuture<?> reserve(QueryId queryId, String allocationTag, long bytes)
{
checkArgument(bytes >= 0, "bytes is negative");
ListenableFuture<?> result;
synchronized (this) {
if (bytes != 0) {
queryMemoryReservations.merge(queryId, bytes, Long::sum);
updateTaggedMemoryAllocations(queryId, allocationTag, bytes);
}
reservedBytes += bytes;
if (getFreeBytes() <= 0) {
if (future == null) {
future = NonCancellableMemoryFuture.create();
}
checkState(!future.isDone(), "future is already completed");
result = future;
}
else {
result = NOT_BLOCKED;
}
}
onMemoryReserved();
return result;
} }
|
public class class_name {
public ListenableFuture<?> reserve(QueryId queryId, String allocationTag, long bytes)
{
checkArgument(bytes >= 0, "bytes is negative");
ListenableFuture<?> result;
synchronized (this) {
if (bytes != 0) {
queryMemoryReservations.merge(queryId, bytes, Long::sum); // depends on control dependency: [if], data = [none]
updateTaggedMemoryAllocations(queryId, allocationTag, bytes); // depends on control dependency: [if], data = [none]
}
reservedBytes += bytes;
if (getFreeBytes() <= 0) {
if (future == null) {
future = NonCancellableMemoryFuture.create(); // depends on control dependency: [if], data = [none]
}
checkState(!future.isDone(), "future is already completed"); // depends on control dependency: [if], data = [none]
result = future; // depends on control dependency: [if], data = [none]
}
else {
result = NOT_BLOCKED; // depends on control dependency: [if], data = [none]
}
}
onMemoryReserved();
return result;
} }
|
public class class_name {
private HttpHandler configureUndertow(Configuration configuration, Undertow.Builder builder, HttpHandler rootHandler, URL undertowResource) {
try {
if (jaxb == null) {
// we don't want static references here
jaxb = JAXBContext.newInstance("org.ops4j.pax.web.service.undertow.internal.configuration.model",
UndertowConfiguration.class.getClassLoader());
}
Unmarshaller unmarshaller = jaxb.createUnmarshaller();
UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
Dictionary<String, Object> properties = new Hashtable<>();
if (configuration instanceof ConfigurationSource) {
Dictionary<String, Object> externalConfig = ((ConfigurationSource) configuration).getConfiguration();
if (externalConfig != null) {
for (Enumeration<String> e = externalConfig.keys(); e.hasMoreElements(); ) {
String key = e.nextElement();
properties.put(key, externalConfig.get(key));
}
}
}
if (properties.get(WebContainerConstants.PROPERTY_HTTP_PORT) == null && configuration.getHttpPort() != null) {
properties.put(WebContainerConstants.PROPERTY_HTTP_PORT, Integer.toString(configuration.getHttpPort()));
}
if (properties.get(WebContainerConstants.PROPERTY_HTTP_SECURE_PORT) == null && configuration.getHttpSecurePort() != null) {
properties.put(WebContainerConstants.PROPERTY_HTTP_SECURE_PORT, Integer.toString(configuration.getHttpSecurePort()));
}
// BundleContextPropertyResolver gives access to e.g., ${karaf.base}
final PropertyResolver resolver = new DictionaryPropertyResolver(properties,
new BundleContextPropertyResolver(bundleContext));
// indirect unmarslaling with property resolution *inside XML attribute values*
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
// tricky PropertyResolver -> Properties bridge
xmlReader.setContentHandler(new ResolvingContentHandler(new Properties() {
@Override
public String getProperty(String key) {
return resolver.get(key);
}
@Override
public String getProperty(String key, String defaultValue) {
String value = resolver.get(key);
return value == null ? defaultValue : value;
}
}, unmarshallerHandler));
try (InputStream stream = undertowResource.openStream()) {
xmlReader.parse(new InputSource(stream));
}
UndertowConfiguration cfg = (UndertowConfiguration) unmarshallerHandler.getResult();
if (cfg == null
|| cfg.getSocketBindings().size() == 0
|| cfg.getInterfaces().size() == 0
|| cfg.getSubsystem() == null
|| cfg.getSubsystem().getServer() == null) {
throw new IllegalArgumentException("Problem configuring Undertow server using \"" + undertowResource + "\": invalid XML");
}
cfg.init();
if (LOG.isDebugEnabled()) {
LOG.debug("Undertow XML configuration: {}", cfg);
}
// ok, we have everything unmarshalled from XML to config object
// we can configure all/some aspects of Undertow now
Server.HttpListener http = cfg.getSubsystem().getServer().getHttpListener();
Server.HttpsListener https = cfg.getSubsystem().getServer().getHttpsListener();
if (http == null && https == null) {
throw new IllegalArgumentException("No listener configuration available in \"" + undertowResource + "\". Please configure http and/or https listeners.");
}
// http listener
if (http != null) {
UndertowConfiguration.BindingInfo binding = cfg.bindingInfo(http.getSocketBindingName());
for (String address : binding.getAddresses()) {
LOG.info("Starting undertow http listener on " + address + ":" + binding.getPort());
builder.addHttpListener(binding.getPort(), address);
}
}
// https listener
if (https != null) {
UndertowConfiguration.BindingInfo binding = cfg.bindingInfo(https.getSocketBindingName());
SecurityRealm realm = cfg.securityRealm(https.getSecurityRealm());
if (realm == null) {
throw new IllegalArgumentException("No security realm with name \"" + https.getSecurityRealm() + "\" available for \"" + https.getName() + "\" https listener.");
}
for (String address : binding.getAddresses()) {
LOG.info("Starting undertow https listener on " + address + ":" + binding.getPort());
// TODO: could this be shared across interface:port bindings?
SSLContext sslContext = buildSSLContext(realm);
builder.addHttpsListener(binding.getPort(), address, sslContext);
// options - see io.undertow.protocols.ssl.UndertowAcceptingSslChannel()
// one of NOT_REQUESTED, REQUESTED, REQUIRED
builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, SslClientAuthMode.valueOf(https.getVerifyClient()));
SecurityRealm.Engine engine = realm.getIdentities().getSsl().getEngine();
if (engine != null) {
// could be taken from these as well:
// - https.getEnabledProtocols();
// - https.getEnabledCipherSuites();
if (engine.getEnabledProtocols().size() > 0) {
builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, Sequence.of(engine.getEnabledProtocols()));
}
if (engine.getEnabledCipherSuites().size() > 0) {
builder.setSocketOption(Options.SSL_ENABLED_CIPHER_SUITES, Sequence.of(engine.getEnabledCipherSuites()));
}
}
}
}
// identity manager - looked up in "default" security realm
SecurityRealm defaultRealm = cfg.securityRealm("default");
if (defaultRealm != null) {
SecurityRealm.JaasAuth jaasAuth = defaultRealm.getAuthentication().getJaas();
SecurityRealm.PropertiesAuth propertiesAuth = defaultRealm.getAuthentication().getProperties();
if (jaasAuth != null) {
String userPrincipalClassName = defaultRealm.getUserPrincipalClassName();
if (userPrincipalClassName == null || "".equals(userPrincipalClassName.trim())) {
userPrincipalClassName = "java.security.Principal";
}
Set<String> rolePrincipalClassNames = new LinkedHashSet<>(defaultRealm.getRolePrincipalClassNames());
identityManager = new JaasIdentityManager(jaasAuth.getName(),
userPrincipalClassName, rolePrincipalClassNames);
} else if (propertiesAuth != null) {
File userBase = new File(propertiesAuth.getPath());
if (!userBase.isFile()) {
throw new IllegalArgumentException(userBase.getCanonicalPath() + " is not accessible. Can't load users/groups information.");
}
Properties userProperties = new Properties();
Map<String, String> map = new HashMap<>();
try (FileInputStream stream = new FileInputStream(userBase)) {
userProperties.load(stream);
for (String user : userProperties.stringPropertyNames()) {
map.put(user, userProperties.getProperty(user));
}
}
identityManager = new PropertiesIdentityManager(map);
}
}
// /undertow/subsystem/server/host/location - file handlers for static context paths.
if (cfg.getSubsystem().getServer().getHost() != null) {
for (Server.Host.Location location : cfg.getSubsystem().getServer().getHost().getLocation()) {
String context = location.getName();
String handlerRef = location.getHandler();
UndertowSubsystem.FileHandler fileHandler = cfg.handler(handlerRef);
if (fileHandler == null) {
throw new IllegalArgumentException("No handler with name \"" + location.getHandler() + "\" available for " + location.getName() + " location.");
}
File base = new File(fileHandler.getPath());
if (!base.isDirectory()) {
throw new IllegalArgumentException(base.getCanonicalPath() + " is not accessible. Can't configure handler for " + location.getName() + " location.");
}
// fileHandler.path is simply filesystem directory
ResourceHandler rh = new ResourceHandler(new FileResourceManager(base, 4096));
if (cfg.getSubsystem().getServletContainer() != null) {
rh.setWelcomeFiles();
for (org.ops4j.pax.web.service.undertow.internal.configuration.model.ServletContainer.WelcomeFile wf : cfg.getSubsystem().getServletContainer().getWelcomeFiles()) {
rh.addWelcomeFiles(wf.getName());
}
}
if (rootHandler instanceof PathHandler) {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding resource handler for location \"" + context + "\" and base path \"" + base.getCanonicalPath() + "\".");
}
((PathHandler) rootHandler).addPrefixPath(context, rh);
}
}
}
// global filters (subsystem/filters/response-header and subsystem/filters/filter)
if (cfg.getSubsystem().getServer().getHost() != null) {
for (Server.Host.FilterRef fr : cfg.getSubsystem().getServer().getHost().getFilterRef()) {
UndertowSubsystem.AbstractFilter filter = cfg.filter(fr.getName());
if (filter == null) {
throw new IllegalArgumentException("No filter with name \"" + fr.getName() + "\" available.");
}
rootHandler = filter.configure(rootHandler);
}
}
// access log
if (cfg.getSubsystem().getServer().getHost() != null
&& cfg.getSubsystem().getServer().getHost().getAccessLog() != null) {
Server.Host.AccessLog accessLog = cfg.getSubsystem().getServer().getHost().getAccessLog();
Bundle bundle = FrameworkUtil.getBundle(ServerControllerImpl.class);
ClassLoader loader = bundle.adapt(BundleWiring.class).getClassLoader();
xnioWorker = UndertowUtil.createWorker(loader);
AccessLogReceiver logReceiver = DefaultAccessLogReceiver.builder()
.setLogWriteExecutor(xnioWorker)
.setOutputDirectory(new File(accessLog.getDirectory()).toPath())
.setLogBaseName(accessLog.getPrefix())
.setLogNameSuffix(accessLog.getSuffix())
.setRotate(Boolean.parseBoolean(accessLog.getRotate()))
.build();
rootHandler = new AccessLogHandler(rootHandler, logReceiver, accessLog.getPattern(),
AccessLogHandler.class.getClassLoader());
}
// session configuration and persistence
this.defaultSessionTimeoutInMinutes = 30;
try {
if (cfg.getSubsystem().getServletContainer() != null) {
String defaultSessionTimeout = cfg.getSubsystem().getServletContainer().getDefaultSessionTimeout();
if (defaultSessionTimeout != null && !"".equals(defaultSessionTimeout)) {
this.defaultSessionTimeoutInMinutes = Integer.parseInt(defaultSessionTimeout);
}
}
} catch (NumberFormatException ignored) {
}
PersistentSessionsConfig persistentSessions = cfg.getSubsystem().getServletContainer() == null ? null
: cfg.getSubsystem().getServletContainer().getPersistentSessions();
if (persistentSessions == null) {
// no sessions, but let's use InMemorySessionPersistence
LOG.info("Using in-memory session persistence");
sessionPersistenceManager = new InMemorySessionPersistence();
} else {
if (persistentSessions.getPath() != null && !"".equals(persistentSessions.getPath().trim())) {
// file persistence manager
File sessionsDir = new File(persistentSessions.getPath());
sessionsDir.mkdirs();
LOG.info("Using file session persistence. Location: " + sessionsDir.getCanonicalPath());
sessionPersistenceManager = new FileSessionPersistence(sessionsDir);
} else {
// in memory persistence manager
LOG.info("No path configured for persistent-sessions. Using in-memory session persistence.");
sessionPersistenceManager = new InMemorySessionPersistence();
}
}
} catch (Exception e) {
throw new IllegalArgumentException("Problem configuring Undertow server using \"" + undertowResource + "\": " + e.getMessage(), e);
}
return rootHandler;
} }
|
public class class_name {
private HttpHandler configureUndertow(Configuration configuration, Undertow.Builder builder, HttpHandler rootHandler, URL undertowResource) {
try {
if (jaxb == null) {
// we don't want static references here
jaxb = JAXBContext.newInstance("org.ops4j.pax.web.service.undertow.internal.configuration.model",
UndertowConfiguration.class.getClassLoader()); // depends on control dependency: [if], data = [none]
}
Unmarshaller unmarshaller = jaxb.createUnmarshaller();
UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
Dictionary<String, Object> properties = new Hashtable<>();
if (configuration instanceof ConfigurationSource) {
Dictionary<String, Object> externalConfig = ((ConfigurationSource) configuration).getConfiguration();
if (externalConfig != null) {
for (Enumeration<String> e = externalConfig.keys(); e.hasMoreElements(); ) {
String key = e.nextElement();
properties.put(key, externalConfig.get(key)); // depends on control dependency: [for], data = [none]
}
}
}
if (properties.get(WebContainerConstants.PROPERTY_HTTP_PORT) == null && configuration.getHttpPort() != null) {
properties.put(WebContainerConstants.PROPERTY_HTTP_PORT, Integer.toString(configuration.getHttpPort())); // depends on control dependency: [if], data = [none]
}
if (properties.get(WebContainerConstants.PROPERTY_HTTP_SECURE_PORT) == null && configuration.getHttpSecurePort() != null) {
properties.put(WebContainerConstants.PROPERTY_HTTP_SECURE_PORT, Integer.toString(configuration.getHttpSecurePort())); // depends on control dependency: [if], data = [none]
}
// BundleContextPropertyResolver gives access to e.g., ${karaf.base}
final PropertyResolver resolver = new DictionaryPropertyResolver(properties,
new BundleContextPropertyResolver(bundleContext));
// indirect unmarslaling with property resolution *inside XML attribute values*
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
// tricky PropertyResolver -> Properties bridge
xmlReader.setContentHandler(new ResolvingContentHandler(new Properties() {
@Override
public String getProperty(String key) {
return resolver.get(key);
}
@Override
public String getProperty(String key, String defaultValue) {
String value = resolver.get(key);
return value == null ? defaultValue : value;
}
}, unmarshallerHandler));
try (InputStream stream = undertowResource.openStream()) {
xmlReader.parse(new InputSource(stream));
}
UndertowConfiguration cfg = (UndertowConfiguration) unmarshallerHandler.getResult();
if (cfg == null
|| cfg.getSocketBindings().size() == 0
|| cfg.getInterfaces().size() == 0
|| cfg.getSubsystem() == null
|| cfg.getSubsystem().getServer() == null) {
throw new IllegalArgumentException("Problem configuring Undertow server using \"" + undertowResource + "\": invalid XML");
}
cfg.init();
if (LOG.isDebugEnabled()) {
LOG.debug("Undertow XML configuration: {}", cfg); // depends on control dependency: [if], data = [none]
}
// ok, we have everything unmarshalled from XML to config object
// we can configure all/some aspects of Undertow now
Server.HttpListener http = cfg.getSubsystem().getServer().getHttpListener();
Server.HttpsListener https = cfg.getSubsystem().getServer().getHttpsListener();
if (http == null && https == null) {
throw new IllegalArgumentException("No listener configuration available in \"" + undertowResource + "\". Please configure http and/or https listeners.");
}
// http listener
if (http != null) {
UndertowConfiguration.BindingInfo binding = cfg.bindingInfo(http.getSocketBindingName());
for (String address : binding.getAddresses()) {
LOG.info("Starting undertow http listener on " + address + ":" + binding.getPort()); // depends on control dependency: [for], data = [address]
builder.addHttpListener(binding.getPort(), address); // depends on control dependency: [for], data = [address]
}
}
// https listener
if (https != null) {
UndertowConfiguration.BindingInfo binding = cfg.bindingInfo(https.getSocketBindingName());
SecurityRealm realm = cfg.securityRealm(https.getSecurityRealm());
if (realm == null) {
throw new IllegalArgumentException("No security realm with name \"" + https.getSecurityRealm() + "\" available for \"" + https.getName() + "\" https listener.");
}
for (String address : binding.getAddresses()) {
LOG.info("Starting undertow https listener on " + address + ":" + binding.getPort()); // depends on control dependency: [for], data = [address]
// TODO: could this be shared across interface:port bindings?
SSLContext sslContext = buildSSLContext(realm);
builder.addHttpsListener(binding.getPort(), address, sslContext); // depends on control dependency: [for], data = [address]
// options - see io.undertow.protocols.ssl.UndertowAcceptingSslChannel()
// one of NOT_REQUESTED, REQUESTED, REQUIRED
builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, SslClientAuthMode.valueOf(https.getVerifyClient())); // depends on control dependency: [for], data = [none]
SecurityRealm.Engine engine = realm.getIdentities().getSsl().getEngine();
if (engine != null) {
// could be taken from these as well:
// - https.getEnabledProtocols();
// - https.getEnabledCipherSuites();
if (engine.getEnabledProtocols().size() > 0) {
builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, Sequence.of(engine.getEnabledProtocols())); // depends on control dependency: [if], data = [none]
}
if (engine.getEnabledCipherSuites().size() > 0) {
builder.setSocketOption(Options.SSL_ENABLED_CIPHER_SUITES, Sequence.of(engine.getEnabledCipherSuites())); // depends on control dependency: [if], data = [none]
}
}
}
}
// identity manager - looked up in "default" security realm
SecurityRealm defaultRealm = cfg.securityRealm("default");
if (defaultRealm != null) {
SecurityRealm.JaasAuth jaasAuth = defaultRealm.getAuthentication().getJaas();
SecurityRealm.PropertiesAuth propertiesAuth = defaultRealm.getAuthentication().getProperties();
if (jaasAuth != null) {
String userPrincipalClassName = defaultRealm.getUserPrincipalClassName();
if (userPrincipalClassName == null || "".equals(userPrincipalClassName.trim())) {
userPrincipalClassName = "java.security.Principal"; // depends on control dependency: [if], data = [none]
}
Set<String> rolePrincipalClassNames = new LinkedHashSet<>(defaultRealm.getRolePrincipalClassNames());
identityManager = new JaasIdentityManager(jaasAuth.getName(),
userPrincipalClassName, rolePrincipalClassNames); // depends on control dependency: [if], data = [(jaasAuth]
} else if (propertiesAuth != null) {
File userBase = new File(propertiesAuth.getPath());
if (!userBase.isFile()) {
throw new IllegalArgumentException(userBase.getCanonicalPath() + " is not accessible. Can't load users/groups information.");
}
Properties userProperties = new Properties();
Map<String, String> map = new HashMap<>();
try (FileInputStream stream = new FileInputStream(userBase)) {
userProperties.load(stream);
for (String user : userProperties.stringPropertyNames()) {
map.put(user, userProperties.getProperty(user)); // depends on control dependency: [for], data = [user]
}
}
identityManager = new PropertiesIdentityManager(map); // depends on control dependency: [if], data = [none]
}
}
// /undertow/subsystem/server/host/location - file handlers for static context paths.
if (cfg.getSubsystem().getServer().getHost() != null) {
for (Server.Host.Location location : cfg.getSubsystem().getServer().getHost().getLocation()) {
String context = location.getName();
String handlerRef = location.getHandler();
UndertowSubsystem.FileHandler fileHandler = cfg.handler(handlerRef);
if (fileHandler == null) {
throw new IllegalArgumentException("No handler with name \"" + location.getHandler() + "\" available for " + location.getName() + " location.");
}
File base = new File(fileHandler.getPath());
if (!base.isDirectory()) {
throw new IllegalArgumentException(base.getCanonicalPath() + " is not accessible. Can't configure handler for " + location.getName() + " location.");
}
// fileHandler.path is simply filesystem directory
ResourceHandler rh = new ResourceHandler(new FileResourceManager(base, 4096));
if (cfg.getSubsystem().getServletContainer() != null) {
rh.setWelcomeFiles(); // depends on control dependency: [if], data = [none]
for (org.ops4j.pax.web.service.undertow.internal.configuration.model.ServletContainer.WelcomeFile wf : cfg.getSubsystem().getServletContainer().getWelcomeFiles()) {
rh.addWelcomeFiles(wf.getName()); // depends on control dependency: [for], data = [wf]
}
}
if (rootHandler instanceof PathHandler) {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding resource handler for location \"" + context + "\" and base path \"" + base.getCanonicalPath() + "\"."); // depends on control dependency: [if], data = [none]
}
((PathHandler) rootHandler).addPrefixPath(context, rh); // depends on control dependency: [if], data = [none]
}
}
}
// global filters (subsystem/filters/response-header and subsystem/filters/filter)
if (cfg.getSubsystem().getServer().getHost() != null) {
for (Server.Host.FilterRef fr : cfg.getSubsystem().getServer().getHost().getFilterRef()) {
UndertowSubsystem.AbstractFilter filter = cfg.filter(fr.getName());
if (filter == null) {
throw new IllegalArgumentException("No filter with name \"" + fr.getName() + "\" available.");
}
rootHandler = filter.configure(rootHandler);
}
}
// access log
if (cfg.getSubsystem().getServer().getHost() != null
&& cfg.getSubsystem().getServer().getHost().getAccessLog() != null) {
Server.Host.AccessLog accessLog = cfg.getSubsystem().getServer().getHost().getAccessLog();
Bundle bundle = FrameworkUtil.getBundle(ServerControllerImpl.class);
ClassLoader loader = bundle.adapt(BundleWiring.class).getClassLoader();
xnioWorker = UndertowUtil.createWorker(loader);
AccessLogReceiver logReceiver = DefaultAccessLogReceiver.builder()
.setLogWriteExecutor(xnioWorker)
.setOutputDirectory(new File(accessLog.getDirectory()).toPath())
.setLogBaseName(accessLog.getPrefix())
.setLogNameSuffix(accessLog.getSuffix())
.setRotate(Boolean.parseBoolean(accessLog.getRotate()))
.build();
rootHandler = new AccessLogHandler(rootHandler, logReceiver, accessLog.getPattern(),
AccessLogHandler.class.getClassLoader());
}
// session configuration and persistence
this.defaultSessionTimeoutInMinutes = 30;
try {
if (cfg.getSubsystem().getServletContainer() != null) {
String defaultSessionTimeout = cfg.getSubsystem().getServletContainer().getDefaultSessionTimeout();
if (defaultSessionTimeout != null && !"".equals(defaultSessionTimeout)) {
this.defaultSessionTimeoutInMinutes = Integer.parseInt(defaultSessionTimeout);
}
}
} catch (NumberFormatException ignored) {
}
PersistentSessionsConfig persistentSessions = cfg.getSubsystem().getServletContainer() == null ? null
: cfg.getSubsystem().getServletContainer().getPersistentSessions();
if (persistentSessions == null) {
// no sessions, but let's use InMemorySessionPersistence
LOG.info("Using in-memory session persistence");
sessionPersistenceManager = new InMemorySessionPersistence();
} else {
if (persistentSessions.getPath() != null && !"".equals(persistentSessions.getPath().trim())) {
// file persistence manager
File sessionsDir = new File(persistentSessions.getPath());
sessionsDir.mkdirs();
LOG.info("Using file session persistence. Location: " + sessionsDir.getCanonicalPath());
sessionPersistenceManager = new FileSessionPersistence(sessionsDir);
} else {
// in memory persistence manager
LOG.info("No path configured for persistent-sessions. Using in-memory session persistence.");
sessionPersistenceManager = new InMemorySessionPersistence();
}
}
} catch (Exception e) {
throw new IllegalArgumentException("Problem configuring Undertow server using \"" + undertowResource + "\": " + e.getMessage(), e);
}
return rootHandler;
} }
|
public class class_name {
public static Constructor<?>[] getAllConstructorsOfClass(final Class<?> clazz, boolean accessible) {
if (clazz == null) {
return null;
}
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
if (constructors != null && constructors.length > 0) {
AccessibleObject.setAccessible(constructors, accessible);
}
return constructors;
} }
|
public class class_name {
public static Constructor<?>[] getAllConstructorsOfClass(final Class<?> clazz, boolean accessible) {
if (clazz == null) {
return null; // depends on control dependency: [if], data = [none]
}
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
if (constructors != null && constructors.length > 0) {
AccessibleObject.setAccessible(constructors, accessible); // depends on control dependency: [if], data = [(constructors]
}
return constructors;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
protected void handleGroupPrincipalCallback(GroupPrincipalCallback callback) throws CustomRegistryException, EntryNotFoundException, RemoteException {
Subject clientSubject = callback.getSubject();
Hashtable<String, Object> credData = null;
if (clientSubject != null) {
String[] groupsFromCallback = callback.getGroups();
if (groupsFromCallback != null && groupsFromCallback.length > 0) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Group names in Callback: ", Arrays.asList(groupsFromCallback));
}
credData = getSubjectCustomData(clientSubject);
List<String> groupsFromSubject = (List<String>) credData.get(AttributeNameConstants.WSCREDENTIAL_GROUPS);
if (groupsFromSubject == null) {
groupsFromSubject = new ArrayList<String>();
credData.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, groupsFromSubject);
}
for (int i = 0; i < groupsFromCallback.length; i++) {
String groupFromCallback = groupsFromCallback[i];
if (groupFromCallback == null || groupFromCallback.isEmpty()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Group is null or an empty string, it has been ignored.");
}
continue;
}
String group = mapGroup(groupFromCallback);
if (!groupsFromSubject.contains(group)) {
groupsFromSubject.add(group);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Added groupId: " + group);
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, group + " already exists in custom credential data, avoid duplicates.");
}
}
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Callback has no groups.");
}
}
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "handleGroupPrincipalCallback", credData);
}
} }
|
public class class_name {
@SuppressWarnings("unchecked")
protected void handleGroupPrincipalCallback(GroupPrincipalCallback callback) throws CustomRegistryException, EntryNotFoundException, RemoteException {
Subject clientSubject = callback.getSubject();
Hashtable<String, Object> credData = null;
if (clientSubject != null) {
String[] groupsFromCallback = callback.getGroups();
if (groupsFromCallback != null && groupsFromCallback.length > 0) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Group names in Callback: ", Arrays.asList(groupsFromCallback)); // depends on control dependency: [if], data = [none]
}
credData = getSubjectCustomData(clientSubject);
List<String> groupsFromSubject = (List<String>) credData.get(AttributeNameConstants.WSCREDENTIAL_GROUPS);
if (groupsFromSubject == null) {
groupsFromSubject = new ArrayList<String>(); // depends on control dependency: [if], data = [none]
credData.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, groupsFromSubject); // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < groupsFromCallback.length; i++) {
String groupFromCallback = groupsFromCallback[i];
if (groupFromCallback == null || groupFromCallback.isEmpty()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Group is null or an empty string, it has been ignored."); // depends on control dependency: [if], data = [none]
}
continue;
}
String group = mapGroup(groupFromCallback);
if (!groupsFromSubject.contains(group)) {
groupsFromSubject.add(group); // depends on control dependency: [if], data = [none]
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Added groupId: " + group); // depends on control dependency: [if], data = [none]
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, group + " already exists in custom credential data, avoid duplicates."); // depends on control dependency: [if], data = [none]
}
}
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Callback has no groups."); // depends on control dependency: [if], data = [none]
}
}
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "handleGroupPrincipalCallback", credData);
}
} }
|
public class class_name {
public double getSolution(double targetValue, double initGuess) {
double rMax = 1.0;
double oldValue = -1;
for (int i = 0; i < MAXIMUM_ITERATION; ++i) {
double value = targetFunction(rMax);
if (value >= targetValue) {
break;
}
if (equals(value, oldValue)) {
return rMax; // Target value is not feasible. Just return rMax
}
rMax *= 2;
}
double left = 0;
double right = rMax;
double mid = initGuess > left && initGuess < right ?
initGuess : (left + right) / 2.0;
for (int i = 0; i < MAXIMUM_ITERATION; ++i) {
double value = targetFunction(mid);
if (equals(value, targetValue)) {
return mid;
}
if (value < targetValue) {
left = mid;
} else {
right = mid;
}
mid = (left + right) / 2.0;
}
return right;
} }
|
public class class_name {
public double getSolution(double targetValue, double initGuess) {
double rMax = 1.0;
double oldValue = -1;
for (int i = 0; i < MAXIMUM_ITERATION; ++i) {
double value = targetFunction(rMax);
if (value >= targetValue) {
break;
}
if (equals(value, oldValue)) {
return rMax; // Target value is not feasible. Just return rMax // depends on control dependency: [if], data = [none]
}
rMax *= 2; // depends on control dependency: [for], data = [none]
}
double left = 0;
double right = rMax;
double mid = initGuess > left && initGuess < right ?
initGuess : (left + right) / 2.0;
for (int i = 0; i < MAXIMUM_ITERATION; ++i) {
double value = targetFunction(mid);
if (equals(value, targetValue)) {
return mid; // depends on control dependency: [if], data = [none]
}
if (value < targetValue) {
left = mid; // depends on control dependency: [if], data = [none]
} else {
right = mid; // depends on control dependency: [if], data = [none]
}
mid = (left + right) / 2.0; // depends on control dependency: [for], data = [none]
}
return right;
} }
|
public class class_name {
public static void rcvXA_getTxTimeout(CommsByteBuffer request, Conversation conversation,
int requestNumber, boolean allocatedFromBufferPool,
boolean partOfExchange)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvXA_getTxTimeout",
new Object[]
{
request,
conversation,
""+requestNumber,
""+allocatedFromBufferPool,
""+partOfExchange
});
try
{
int clientTransactionId = request.getInt();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "XAResource Object ID", clientTransactionId);
}
// Get the transaction out of the table
ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();
SITransaction tran = linkState.getTransactionTable().get(clientTransactionId, true);
int timeout = 0;
if ((tran != null) && (tran != IdToTransactionTable.INVALID_TRANSACTION))
{
// tran may be null if the client has got an XAResource
// but not called start on it.
// Get the actual transaction ...
SIXAResource xaResource = (SIXAResource) tran;
// Now call the method on the XA resource
timeout = xaResource.getTransactionTimeout();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Timeout: " + timeout);
CommsByteBuffer reply = poolManager.allocate();
reply.putInt(timeout);
try
{
conversation.send(reply,
JFapChannelConstants.SEG_XA_GETTXTIMEOUT_R,
requestNumber,
JFapChannelConstants.PRIORITY_MEDIUM,
true,
ThrottlingPolicy.BLOCK_THREAD,
null);
}
catch (SIException e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".rcvXA_getTxTimeout",
CommsConstants.STATICCATXATRANSACTION_GETTXTIMEOUT_01);
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2027", e);
}
}
catch (XAException e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".rcvXA_getTxTimeout",
CommsConstants.STATICCATXATRANSACTION_GETTXTIMEOUT_02);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "XAException - RC: " + e.errorCode, e);
StaticCATHelper.sendExceptionToClient(e,
CommsConstants.STATICCATXATRANSACTION_GETTXTIMEOUT_02,
conversation, requestNumber);
}
request.release(allocatedFromBufferPool);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvXA_getTxTimeout");
} }
|
public class class_name {
public static void rcvXA_getTxTimeout(CommsByteBuffer request, Conversation conversation,
int requestNumber, boolean allocatedFromBufferPool,
boolean partOfExchange)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvXA_getTxTimeout",
new Object[]
{
request,
conversation,
""+requestNumber,
""+allocatedFromBufferPool,
""+partOfExchange
});
try
{
int clientTransactionId = request.getInt();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "XAResource Object ID", clientTransactionId); // depends on control dependency: [if], data = [none]
}
// Get the transaction out of the table
ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();
SITransaction tran = linkState.getTransactionTable().get(clientTransactionId, true);
int timeout = 0;
if ((tran != null) && (tran != IdToTransactionTable.INVALID_TRANSACTION))
{
// tran may be null if the client has got an XAResource
// but not called start on it.
// Get the actual transaction ...
SIXAResource xaResource = (SIXAResource) tran;
// Now call the method on the XA resource
timeout = xaResource.getTransactionTimeout(); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Timeout: " + timeout);
CommsByteBuffer reply = poolManager.allocate();
reply.putInt(timeout); // depends on control dependency: [try], data = [none]
try
{
conversation.send(reply,
JFapChannelConstants.SEG_XA_GETTXTIMEOUT_R,
requestNumber,
JFapChannelConstants.PRIORITY_MEDIUM,
true,
ThrottlingPolicy.BLOCK_THREAD,
null); // depends on control dependency: [try], data = [none]
}
catch (SIException e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".rcvXA_getTxTimeout",
CommsConstants.STATICCATXATRANSACTION_GETTXTIMEOUT_01);
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2027", e);
} // depends on control dependency: [catch], data = [none]
}
catch (XAException e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".rcvXA_getTxTimeout",
CommsConstants.STATICCATXATRANSACTION_GETTXTIMEOUT_02);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "XAException - RC: " + e.errorCode, e);
StaticCATHelper.sendExceptionToClient(e,
CommsConstants.STATICCATXATRANSACTION_GETTXTIMEOUT_02,
conversation, requestNumber);
} // depends on control dependency: [catch], data = [none]
request.release(allocatedFromBufferPool);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvXA_getTxTimeout");
} }
|
public class class_name {
public void marshall(Input input, ProtocolMarshaller protocolMarshaller) {
if (input == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(input.getNamePrefix(), NAMEPREFIX_BINDING);
protocolMarshaller.marshall(input.getInputProcessingConfiguration(), INPUTPROCESSINGCONFIGURATION_BINDING);
protocolMarshaller.marshall(input.getKinesisStreamsInput(), KINESISSTREAMSINPUT_BINDING);
protocolMarshaller.marshall(input.getKinesisFirehoseInput(), KINESISFIREHOSEINPUT_BINDING);
protocolMarshaller.marshall(input.getInputParallelism(), INPUTPARALLELISM_BINDING);
protocolMarshaller.marshall(input.getInputSchema(), INPUTSCHEMA_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(Input input, ProtocolMarshaller protocolMarshaller) {
if (input == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(input.getNamePrefix(), NAMEPREFIX_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(input.getInputProcessingConfiguration(), INPUTPROCESSINGCONFIGURATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(input.getKinesisStreamsInput(), KINESISSTREAMSINPUT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(input.getKinesisFirehoseInput(), KINESISFIREHOSEINPUT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(input.getInputParallelism(), INPUTPARALLELISM_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(input.getInputSchema(), INPUTSCHEMA_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 UnicodeSet getEquivalentDecimals(String decimal, boolean strictParse) {
UnicodeSet equivSet = UnicodeSet.EMPTY;
if (strictParse) {
if (strictDotEquivalents.contains(decimal)) {
equivSet = strictDotEquivalents;
} else if (strictCommaEquivalents.contains(decimal)) {
equivSet = strictCommaEquivalents;
}
} else {
if (dotEquivalents.contains(decimal)) {
equivSet = dotEquivalents;
} else if (commaEquivalents.contains(decimal)) {
equivSet = commaEquivalents;
}
}
return equivSet;
} }
|
public class class_name {
private UnicodeSet getEquivalentDecimals(String decimal, boolean strictParse) {
UnicodeSet equivSet = UnicodeSet.EMPTY;
if (strictParse) {
if (strictDotEquivalents.contains(decimal)) {
equivSet = strictDotEquivalents; // depends on control dependency: [if], data = [none]
} else if (strictCommaEquivalents.contains(decimal)) {
equivSet = strictCommaEquivalents; // depends on control dependency: [if], data = [none]
}
} else {
if (dotEquivalents.contains(decimal)) {
equivSet = dotEquivalents; // depends on control dependency: [if], data = [none]
} else if (commaEquivalents.contains(decimal)) {
equivSet = commaEquivalents; // depends on control dependency: [if], data = [none]
}
}
return equivSet;
} }
|
public class class_name {
protected static synchronized long nextGlobalId() {
long newIdentifier = System.nanoTime();
while (newIdentifier <= currentIdentifier) {
newIdentifier = System.nanoTime();
}
currentIdentifier = newIdentifier;
return newIdentifier;
} }
|
public class class_name {
protected static synchronized long nextGlobalId() {
long newIdentifier = System.nanoTime();
while (newIdentifier <= currentIdentifier) {
newIdentifier = System.nanoTime(); // depends on control dependency: [while], data = [none]
}
currentIdentifier = newIdentifier;
return newIdentifier;
} }
|
public class class_name {
public List<InMemoryHistoryNode> getMetrics(final String metricName, final Date from,
final Date to,
final Boolean useStats) throws ClassCastException {
final LinkedList<InMemoryHistoryNode> selectedLists = new LinkedList<>();
if (this.historyListMapping.containsKey(metricName)) {
logger.debug("selecting snapshots within time frame");
synchronized (this.historyListMapping.get(metricName)) {
for (final InMemoryHistoryNode node : this.historyListMapping.get(metricName)) {
if (node.getTimestamp().after(from) && node.getTimestamp().before(to)) {
selectedLists.add(node);
}
if (node.getTimestamp().after(to)) {
break;
}
}
}
// selecting nodes if num of nodes > numInstances
if (useStats) {
statBasedSelectMetricHistory(selectedLists);
} else {
generalSelectMetricHistory(selectedLists);
}
}
cleanUsingTime(metricName, new Date());
return selectedLists;
} }
|
public class class_name {
public List<InMemoryHistoryNode> getMetrics(final String metricName, final Date from,
final Date to,
final Boolean useStats) throws ClassCastException {
final LinkedList<InMemoryHistoryNode> selectedLists = new LinkedList<>();
if (this.historyListMapping.containsKey(metricName)) {
logger.debug("selecting snapshots within time frame");
synchronized (this.historyListMapping.get(metricName)) {
for (final InMemoryHistoryNode node : this.historyListMapping.get(metricName)) {
if (node.getTimestamp().after(from) && node.getTimestamp().before(to)) {
selectedLists.add(node); // depends on control dependency: [if], data = [none]
}
if (node.getTimestamp().after(to)) {
break;
}
}
}
// selecting nodes if num of nodes > numInstances
if (useStats) {
statBasedSelectMetricHistory(selectedLists); // depends on control dependency: [if], data = [none]
} else {
generalSelectMetricHistory(selectedLists); // depends on control dependency: [if], data = [none]
}
}
cleanUsingTime(metricName, new Date());
return selectedLists;
} }
|
public class class_name {
public EnumSet<Script.VerifyFlag> getTransactionVerificationFlags(final Block block,
final Transaction transaction, final VersionTally tally, final Integer height) {
final EnumSet<Script.VerifyFlag> verifyFlags = EnumSet.noneOf(Script.VerifyFlag.class);
if (block.getTimeSeconds() >= NetworkParameters.BIP16_ENFORCE_TIME)
verifyFlags.add(Script.VerifyFlag.P2SH);
// Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
// blocks, when 75% of the network has upgraded:
if (block.getVersion() >= Block.BLOCK_VERSION_BIP65 &&
tally.getCountAtOrAbove(Block.BLOCK_VERSION_BIP65) > this.getMajorityEnforceBlockUpgrade()) {
verifyFlags.add(Script.VerifyFlag.CHECKLOCKTIMEVERIFY);
}
return verifyFlags;
} }
|
public class class_name {
public EnumSet<Script.VerifyFlag> getTransactionVerificationFlags(final Block block,
final Transaction transaction, final VersionTally tally, final Integer height) {
final EnumSet<Script.VerifyFlag> verifyFlags = EnumSet.noneOf(Script.VerifyFlag.class);
if (block.getTimeSeconds() >= NetworkParameters.BIP16_ENFORCE_TIME)
verifyFlags.add(Script.VerifyFlag.P2SH);
// Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
// blocks, when 75% of the network has upgraded:
if (block.getVersion() >= Block.BLOCK_VERSION_BIP65 &&
tally.getCountAtOrAbove(Block.BLOCK_VERSION_BIP65) > this.getMajorityEnforceBlockUpgrade()) {
verifyFlags.add(Script.VerifyFlag.CHECKLOCKTIMEVERIFY); // depends on control dependency: [if], data = [none]
}
return verifyFlags;
} }
|
public class class_name {
public void execute(Reader reader) {
try {
pushShell(this);
LineNumberReader lnr = new LineNumberReader(reader);
while (!m_exitCalled) {
String line = lnr.readLine();
if (m_interactive || m_echo) {
// print the prompt in front of the commands to process only when 'interactive'
if ((line != null) | m_interactive) {
printPrompt();
}
}
if (line == null) {
// if null the file has been read to the end
if (m_interactive) {
try {
Thread.sleep(500);
} catch (Throwable t) {
// noop
}
}
// end the while loop
break;
}
if (line.trim().startsWith("#")) {
m_out.println(line);
continue;
}
// In linux, the up and down arrows generate escape sequences that cannot be properly handled.
// If a escape sequence is detected, OpenCms prints a warning message
if (line.indexOf(KeyEvent.VK_ESCAPE) != -1) {
m_out.println(m_messages.key(Messages.GUI_SHELL_ESCAPE_SEQUENCES_NOT_SUPPORTED_0));
continue;
}
StringReader lineReader = new StringReader(line);
StreamTokenizer st = new StreamTokenizer(lineReader);
st.eolIsSignificant(true);
st.wordChars('*', '*');
// put all tokens into a List
List<String> parameters = new ArrayList<String>();
while (st.nextToken() != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_NUMBER) {
parameters.add(Integer.toString(new Double(st.nval).intValue()));
} else {
if (null != st.sval) {
parameters.add(st.sval);
}
}
}
lineReader.close();
if (parameters.size() == 0) {
// empty line, just need to check if echo is on
if (m_echo) {
m_out.println();
}
continue;
}
// extract command and arguments
String command = parameters.get(0);
List<String> arguments = parameters.subList(1, parameters.size());
// execute the command with the given arguments
executeCommand(command, arguments);
}
} catch (Throwable t) {
if (!(t instanceof CmsShellCommandException)) {
// in case it's a shell command exception, the stack trace has already been written
t.printStackTrace(m_err);
}
if (m_errorCode != -1) {
System.exit(m_errorCode);
}
} finally {
popShell();
}
} }
|
public class class_name {
public void execute(Reader reader) {
try {
pushShell(this); // depends on control dependency: [try], data = [none]
LineNumberReader lnr = new LineNumberReader(reader);
while (!m_exitCalled) {
String line = lnr.readLine();
if (m_interactive || m_echo) {
// print the prompt in front of the commands to process only when 'interactive'
if ((line != null) | m_interactive) {
printPrompt(); // depends on control dependency: [if], data = [none]
}
}
if (line == null) {
// if null the file has been read to the end
if (m_interactive) {
try {
Thread.sleep(500); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
// noop
} // depends on control dependency: [catch], data = [none]
}
// end the while loop
break;
}
if (line.trim().startsWith("#")) {
m_out.println(line); // depends on control dependency: [if], data = [none]
continue;
}
// In linux, the up and down arrows generate escape sequences that cannot be properly handled.
// If a escape sequence is detected, OpenCms prints a warning message
if (line.indexOf(KeyEvent.VK_ESCAPE) != -1) {
m_out.println(m_messages.key(Messages.GUI_SHELL_ESCAPE_SEQUENCES_NOT_SUPPORTED_0)); // depends on control dependency: [if], data = [none]
continue;
}
StringReader lineReader = new StringReader(line);
StreamTokenizer st = new StreamTokenizer(lineReader);
st.eolIsSignificant(true); // depends on control dependency: [while], data = [none]
st.wordChars('*', '*'); // depends on control dependency: [while], data = [none]
// put all tokens into a List
List<String> parameters = new ArrayList<String>();
while (st.nextToken() != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_NUMBER) {
parameters.add(Integer.toString(new Double(st.nval).intValue())); // depends on control dependency: [if], data = [none]
} else {
if (null != st.sval) {
parameters.add(st.sval); // depends on control dependency: [if], data = [st.sval)]
}
}
}
lineReader.close(); // depends on control dependency: [while], data = [none]
if (parameters.size() == 0) {
// empty line, just need to check if echo is on
if (m_echo) {
m_out.println(); // depends on control dependency: [if], data = [none]
}
continue;
}
// extract command and arguments
String command = parameters.get(0);
List<String> arguments = parameters.subList(1, parameters.size());
// execute the command with the given arguments
executeCommand(command, arguments); // depends on control dependency: [while], data = [none]
}
} catch (Throwable t) {
if (!(t instanceof CmsShellCommandException)) {
// in case it's a shell command exception, the stack trace has already been written
t.printStackTrace(m_err); // depends on control dependency: [if], data = [none]
}
if (m_errorCode != -1) {
System.exit(m_errorCode); // depends on control dependency: [if], data = [(m_errorCode]
}
} finally { // depends on control dependency: [catch], data = [none]
popShell();
}
} }
|
public class class_name {
public static String getSpaces( int SpacesCount ) {
//
if ( SpacesCount < 0 ) return "?";
//
String Info = "";
//
for ( int K = 1; K <= SpacesCount; K ++ ) {
Info += " ";
}
//
//
return Info;
} }
|
public class class_name {
public static String getSpaces( int SpacesCount ) {
//
if ( SpacesCount < 0 ) return "?";
//
String Info = "";
//
for ( int K = 1; K <= SpacesCount; K ++ ) {
Info += " "; // depends on control dependency: [for], data = [none]
}
//
//
return Info;
} }
|
public class class_name {
public void marshall(GetSearchSuggestionsRequest getSearchSuggestionsRequest, ProtocolMarshaller protocolMarshaller) {
if (getSearchSuggestionsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getSearchSuggestionsRequest.getResource(), RESOURCE_BINDING);
protocolMarshaller.marshall(getSearchSuggestionsRequest.getSuggestionQuery(), SUGGESTIONQUERY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(GetSearchSuggestionsRequest getSearchSuggestionsRequest, ProtocolMarshaller protocolMarshaller) {
if (getSearchSuggestionsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getSearchSuggestionsRequest.getResource(), RESOURCE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getSearchSuggestionsRequest.getSuggestionQuery(), SUGGESTIONQUERY_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public void setIoSession(IoSession protocolSession) {
SocketAddress remote = protocolSession.getRemoteAddress();
if (remote instanceof InetSocketAddress) {
remoteAddress = ((InetSocketAddress) remote).getAddress().getHostAddress();
remotePort = ((InetSocketAddress) remote).getPort();
} else {
remoteAddress = remote.toString();
remotePort = -1;
}
remoteAddresses = new ArrayList<String>(1);
remoteAddresses.add(remoteAddress);
remoteAddresses = Collections.unmodifiableList(remoteAddresses);
this.ioSession = protocolSession;
if (log.isTraceEnabled()) {
log.trace("setIoSession conn: {}", this);
}
} }
|
public class class_name {
public void setIoSession(IoSession protocolSession) {
SocketAddress remote = protocolSession.getRemoteAddress();
if (remote instanceof InetSocketAddress) {
remoteAddress = ((InetSocketAddress) remote).getAddress().getHostAddress();
// depends on control dependency: [if], data = [none]
remotePort = ((InetSocketAddress) remote).getPort();
// depends on control dependency: [if], data = [none]
} else {
remoteAddress = remote.toString();
// depends on control dependency: [if], data = [none]
remotePort = -1;
// depends on control dependency: [if], data = [none]
}
remoteAddresses = new ArrayList<String>(1);
remoteAddresses.add(remoteAddress);
remoteAddresses = Collections.unmodifiableList(remoteAddresses);
this.ioSession = protocolSession;
if (log.isTraceEnabled()) {
log.trace("setIoSession conn: {}", this);
// depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public Pooled<T> get(LogTarget lt) throws APIException {
Pooled<T> pt;
synchronized (list) {
if (list.isEmpty()) {
pt = null;
} else {
pt = list.remove();
--count;
creator.reuse(pt.content);
}
}
if (pt == null) {
if (spares < max_range)
++spares;
pt = new Pooled<T>(creator.create(), this, lt);
lt.log("Pool created ", creator.toString());
} else {
if (spares > 1)
--spares;
}
return pt;
} }
|
public class class_name {
public Pooled<T> get(LogTarget lt) throws APIException {
Pooled<T> pt;
synchronized (list) {
if (list.isEmpty()) {
pt = null; // depends on control dependency: [if], data = [none]
} else {
pt = list.remove(); // depends on control dependency: [if], data = [none]
--count; // depends on control dependency: [if], data = [none]
creator.reuse(pt.content); // depends on control dependency: [if], data = [none]
}
}
if (pt == null) {
if (spares < max_range)
++spares;
pt = new Pooled<T>(creator.create(), this, lt);
lt.log("Pool created ", creator.toString());
} else {
if (spares > 1)
--spares;
}
return pt;
} }
|
public class class_name {
protected void unsetJaasLoginContextEntry(ServiceReference<com.ibm.ws.security.jaas.common.JAASLoginContextEntry> svc) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(this, tc, "unsetJaasLoginContextEntry", svc);
}
jaasLoginContextEntryName = null;
} }
|
public class class_name {
protected void unsetJaasLoginContextEntry(ServiceReference<com.ibm.ws.security.jaas.common.JAASLoginContextEntry> svc) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(this, tc, "unsetJaasLoginContextEntry", svc); // depends on control dependency: [if], data = [none]
}
jaasLoginContextEntryName = null;
} }
|
public class class_name {
private static boolean isVMMultidexCapable() {
boolean isMultidexCapable = false;
String vmVersion = System.getProperty("java.vm.version");
try {
Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(vmVersion);
if (matcher.matches()) {
int major = Integer.parseInt(matcher.group(1));
int minor = Integer.parseInt(matcher.group(2));
isMultidexCapable = (major > 2) || ((major == 2) && (minor >= 1));
}
} catch (Exception ignore) {
}
String multidex = isMultidexCapable ? "has Multidex support" : "does not have Multidex support";
Log.i(AndServer.TAG, String.format("VM with version %s %s.", vmVersion, multidex));
return false;
} }
|
public class class_name {
private static boolean isVMMultidexCapable() {
boolean isMultidexCapable = false;
String vmVersion = System.getProperty("java.vm.version");
try {
Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(vmVersion);
if (matcher.matches()) {
int major = Integer.parseInt(matcher.group(1));
int minor = Integer.parseInt(matcher.group(2));
isMultidexCapable = (major > 2) || ((major == 2) && (minor >= 1)); // depends on control dependency: [if], data = [none]
}
} catch (Exception ignore) {
} // depends on control dependency: [catch], data = [none]
String multidex = isMultidexCapable ? "has Multidex support" : "does not have Multidex support";
Log.i(AndServer.TAG, String.format("VM with version %s %s.", vmVersion, multidex));
return false;
} }
|
public class class_name {
public String render(String template, Object... args) {
try {
ITemplate t = getTemplate(template, args);
return t.render();
} finally {
renderCleanUp();
}
} }
|
public class class_name {
public String render(String template, Object... args) {
try {
ITemplate t = getTemplate(template, args);
return t.render(); // depends on control dependency: [try], data = [none]
} finally {
renderCleanUp();
}
} }
|
public class class_name {
@Override
public boolean fileExists(String pRelativePath) {
String paths[] = this.getFilePaths();
for (String s : paths) {
if (s.equals(pRelativePath)) {
return true;
}
}
return false;
} }
|
public class class_name {
@Override
public boolean fileExists(String pRelativePath) {
String paths[] = this.getFilePaths();
for (String s : paths) {
if (s.equals(pRelativePath)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} }
|
public class class_name {
protected void notifyClose(ProxyQueue queue)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyClose", queue);
try
{
final short id = queue.getId();
idAllocator.releaseId(id);
//Remove the id from the map
synchronized(this)
{
idToProxyQueueMap.remove(new ImmutableId(id));
}
}
catch (IdAllocatorException e)
{
FFDCFilter.processException(e, CLASS_NAME + ".notifyClose",
CommsConstants.PROXYQUEUECONVGROUPIMPL_NOTIFYCLOSE_01, this); // D177231
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.exception(tc, e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyClose");
} }
|
public class class_name {
protected void notifyClose(ProxyQueue queue)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyClose", queue);
try
{
final short id = queue.getId();
idAllocator.releaseId(id); // depends on control dependency: [try], data = [none]
//Remove the id from the map
synchronized(this) // depends on control dependency: [try], data = [none]
{
idToProxyQueueMap.remove(new ImmutableId(id));
}
}
catch (IdAllocatorException e)
{
FFDCFilter.processException(e, CLASS_NAME + ".notifyClose",
CommsConstants.PROXYQUEUECONVGROUPIMPL_NOTIFYCLOSE_01, this); // D177231
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.exception(tc, e);
} // depends on control dependency: [catch], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyClose");
} }
|
public class class_name {
public static boolean deleteDir(File dirFile) {
if (!dirFile.exists()) {
return false;
}
if (dirFile.isFile()) {
return dirFile.delete();
} else {
File[] files = dirFile.listFiles();
if (files == null || files.length == 0) {
return dirFile.delete();
}
for (File file : files) {
deleteDir(file);
}
}
return dirFile.delete();
} }
|
public class class_name {
public static boolean deleteDir(File dirFile) {
if (!dirFile.exists()) {
return false; // depends on control dependency: [if], data = [none]
}
if (dirFile.isFile()) {
return dirFile.delete(); // depends on control dependency: [if], data = [none]
} else {
File[] files = dirFile.listFiles();
if (files == null || files.length == 0) {
return dirFile.delete(); // depends on control dependency: [if], data = [none]
}
for (File file : files) {
deleteDir(file); // depends on control dependency: [for], data = [file]
}
}
return dirFile.delete();
} }
|
public class class_name {
private void createOrUpdateTable(String tablename, HTableDescriptor hTableDescriptor)
{
try
{
if (admin.isTableAvailable(tablename))
{
admin.modifyTable(tablename, hTableDescriptor);
}
else
{
admin.createTable(hTableDescriptor);
}
}
catch (IOException ioex)
{
logger.error("Either table isn't in enabled state or some network problem, Caused by: ", ioex);
throw new SchemaGenerationException(ioex, "Either table isn't in enabled state or some network problem.");
}
} }
|
public class class_name {
private void createOrUpdateTable(String tablename, HTableDescriptor hTableDescriptor)
{
try
{
if (admin.isTableAvailable(tablename))
{
admin.modifyTable(tablename, hTableDescriptor); // depends on control dependency: [if], data = [none]
}
else
{
admin.createTable(hTableDescriptor); // depends on control dependency: [if], data = [none]
}
}
catch (IOException ioex)
{
logger.error("Either table isn't in enabled state or some network problem, Caused by: ", ioex);
throw new SchemaGenerationException(ioex, "Either table isn't in enabled state or some network problem.");
}
} }
|
public class class_name {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getStatistics(@QueryParam("selectLang") String locale) {
List<StatisticRepresentation> listResult = new ArrayList<>();
// select "All"
if (StringUtils.isBlank(locale)) {
List<LocaleRepresentation> availableLocales = localeFinder
.findAvailableLocales();
for (LocaleRepresentation localeRepresentation : availableLocales) {
statisticFinder.findStatisticRepresentation(
localeRepresentation, listResult);
}
// select a local
} else {
LocaleRepresentation localeRepresentation = localeFinder
.findAvailableLocale(locale);
statisticFinder.findStatisticRepresentation(localeRepresentation,
listResult);
}
if (!listResult.isEmpty()) {
return Response.ok(listResult).build();
}
return Response.noContent().build();
} }
|
public class class_name {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getStatistics(@QueryParam("selectLang") String locale) {
List<StatisticRepresentation> listResult = new ArrayList<>();
// select "All"
if (StringUtils.isBlank(locale)) {
List<LocaleRepresentation> availableLocales = localeFinder
.findAvailableLocales();
for (LocaleRepresentation localeRepresentation : availableLocales) {
statisticFinder.findStatisticRepresentation(
localeRepresentation, listResult); // depends on control dependency: [for], data = [none]
}
// select a local
} else {
LocaleRepresentation localeRepresentation = localeFinder
.findAvailableLocale(locale);
statisticFinder.findStatisticRepresentation(localeRepresentation,
listResult); // depends on control dependency: [if], data = [none]
}
if (!listResult.isEmpty()) {
return Response.ok(listResult).build(); // depends on control dependency: [if], data = [none]
}
return Response.noContent().build();
} }
|
public class class_name {
public List<StructureInterfaceCluster> getClusters(double contactOverlapScoreClusterCutoff) {
if (clusters!=null) {
return clusters;
}
clusters = new ArrayList<>();
// nothing to do if we have no interfaces
if (list.size()==0) return clusters;
double[][] matrix = new double[list.size()][list.size()];
for (int i=0;i<list.size();i++) {
for (int j=i+1;j<list.size();j++) {
StructureInterface iInterf = list.get(i);
StructureInterface jInterf = list.get(j);
double scoreDirect = iInterf.getContactOverlapScore(jInterf, false);
double scoreInvert = iInterf.getContactOverlapScore(jInterf, true);
double maxScore = Math.max(scoreDirect, scoreInvert);
matrix[i][j] = maxScore;
}
}
SingleLinkageClusterer slc = new SingleLinkageClusterer(matrix, true);
Map<Integer, Set<Integer>> clusteredIndices = slc.getClusters(contactOverlapScoreClusterCutoff);
for (int clusterIdx:clusteredIndices.keySet()) {
List<StructureInterface> members = new ArrayList<>();
for (int idx:clusteredIndices.get(clusterIdx)) {
members.add(list.get(idx));
}
StructureInterfaceCluster cluster = new StructureInterfaceCluster();
cluster.setMembers(members);
double averageScore = 0.0;
int countPairs = 0;
for (int i=0;i<members.size();i++) {
int iIdx = list.indexOf(members.get(i));
for (int j=i+1;j<members.size();j++) {
averageScore += matrix[iIdx][list.indexOf(members.get(j))];
countPairs++;
}
}
if (countPairs>0) {
averageScore = averageScore/countPairs;
} else {
// if only one interface in cluster we set the score to the maximum
averageScore = 1.0;
}
cluster.setAverageScore(averageScore);
clusters.add(cluster);
}
// finally we have to set the back-references in each StructureInterface
for (StructureInterfaceCluster cluster:clusters) {
for (StructureInterface interf:cluster.getMembers()) {
interf.setCluster(cluster);
}
}
// now we sort by areas (descending) and assign ids based on that sorting
clusters.sort((o1, o2) -> {
return Double.compare(o2.getTotalArea(), o1.getTotalArea()); //note we invert so that sorting is descending
});
int id = 1;
for (StructureInterfaceCluster cluster:clusters) {
cluster.setId(id);
id++;
}
return clusters;
} }
|
public class class_name {
public List<StructureInterfaceCluster> getClusters(double contactOverlapScoreClusterCutoff) {
if (clusters!=null) {
return clusters; // depends on control dependency: [if], data = [none]
}
clusters = new ArrayList<>();
// nothing to do if we have no interfaces
if (list.size()==0) return clusters;
double[][] matrix = new double[list.size()][list.size()];
for (int i=0;i<list.size();i++) {
for (int j=i+1;j<list.size();j++) {
StructureInterface iInterf = list.get(i);
StructureInterface jInterf = list.get(j);
double scoreDirect = iInterf.getContactOverlapScore(jInterf, false);
double scoreInvert = iInterf.getContactOverlapScore(jInterf, true);
double maxScore = Math.max(scoreDirect, scoreInvert);
matrix[i][j] = maxScore; // depends on control dependency: [for], data = [j]
}
}
SingleLinkageClusterer slc = new SingleLinkageClusterer(matrix, true);
Map<Integer, Set<Integer>> clusteredIndices = slc.getClusters(contactOverlapScoreClusterCutoff);
for (int clusterIdx:clusteredIndices.keySet()) {
List<StructureInterface> members = new ArrayList<>();
for (int idx:clusteredIndices.get(clusterIdx)) {
members.add(list.get(idx)); // depends on control dependency: [for], data = [idx]
}
StructureInterfaceCluster cluster = new StructureInterfaceCluster();
cluster.setMembers(members); // depends on control dependency: [for], data = [none]
double averageScore = 0.0;
int countPairs = 0;
for (int i=0;i<members.size();i++) {
int iIdx = list.indexOf(members.get(i));
for (int j=i+1;j<members.size();j++) {
averageScore += matrix[iIdx][list.indexOf(members.get(j))]; // depends on control dependency: [for], data = [j]
countPairs++; // depends on control dependency: [for], data = [none]
}
}
if (countPairs>0) {
averageScore = averageScore/countPairs; // depends on control dependency: [if], data = [none]
} else {
// if only one interface in cluster we set the score to the maximum
averageScore = 1.0; // depends on control dependency: [if], data = [none]
}
cluster.setAverageScore(averageScore); // depends on control dependency: [for], data = [none]
clusters.add(cluster); // depends on control dependency: [for], data = [none]
}
// finally we have to set the back-references in each StructureInterface
for (StructureInterfaceCluster cluster:clusters) {
for (StructureInterface interf:cluster.getMembers()) {
interf.setCluster(cluster); // depends on control dependency: [for], data = [interf]
}
}
// now we sort by areas (descending) and assign ids based on that sorting
clusters.sort((o1, o2) -> {
return Double.compare(o2.getTotalArea(), o1.getTotalArea()); //note we invert so that sorting is descending
});
int id = 1;
for (StructureInterfaceCluster cluster:clusters) {
cluster.setId(id); // depends on control dependency: [for], data = [cluster]
id++; // depends on control dependency: [for], data = [none]
}
return clusters;
} }
|
public class class_name {
public String findCmisName( String jcrName ) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).jcrName != null && list.get(i).jcrName.equals(jcrName)) {
return list.get(i).cmisName;
}
}
return jcrName;
} }
|
public class class_name {
public String findCmisName( String jcrName ) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).jcrName != null && list.get(i).jcrName.equals(jcrName)) {
return list.get(i).cmisName; // depends on control dependency: [if], data = [none]
}
}
return jcrName;
} }
|
public class class_name {
protected void sendEntryModifiedEvent(CacheEntryEvent<T> event)
{
for (org.xwiki.cache.event.CacheEntryListener<T> listener : this.cacheEntryListeners
.getListeners(org.xwiki.cache.event.CacheEntryListener.class)) {
listener.cacheEntryModified(event);
}
} }
|
public class class_name {
protected void sendEntryModifiedEvent(CacheEntryEvent<T> event)
{
for (org.xwiki.cache.event.CacheEntryListener<T> listener : this.cacheEntryListeners
.getListeners(org.xwiki.cache.event.CacheEntryListener.class)) {
listener.cacheEntryModified(event); // depends on control dependency: [for], data = [listener]
}
} }
|
public class class_name {
public static List<Tuple> extractTuplesFromObject(Object obj) {
if ( obj instanceof Iterable ) {
Iterable<?> it = (Iterable) obj;
return StreamSupport.stream( it.spliterator(), false )
.map( TupleExtractor::extractFromObject )
.collect( Collectors.toList() );
}
Tuple tuple = new Tuple();
tuple.put( "result", obj );
return Collections.singletonList( tuple );
} }
|
public class class_name {
public static List<Tuple> extractTuplesFromObject(Object obj) {
if ( obj instanceof Iterable ) {
Iterable<?> it = (Iterable) obj;
return StreamSupport.stream( it.spliterator(), false )
.map( TupleExtractor::extractFromObject )
.collect( Collectors.toList() ); // depends on control dependency: [if], data = [none]
}
Tuple tuple = new Tuple();
tuple.put( "result", obj );
return Collections.singletonList( tuple );
} }
|
public class class_name {
protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
if (compileStates.isDone(env, CompileState.FLOW)) {
results.add(env);
return;
}
try {
if (shouldStop(CompileState.FLOW))
return;
if (relax) {
results.add(env);
return;
}
if (verboseCompilePolicy)
printNote("[flow " + env.enclClass.sym + "]");
JavaFileObject prev = log.useSource(
env.enclClass.sym.sourcefile != null ?
env.enclClass.sym.sourcefile :
env.toplevel.sourcefile);
try {
make.at(Position.FIRSTPOS);
TreeMaker localMake = make.forToplevel(env.toplevel);
flow.analyzeTree(env, localMake);
compileStates.put(env, CompileState.FLOW);
if (shouldStop(CompileState.FLOW))
return;
results.add(env);
}
finally {
log.useSource(prev);
}
}
finally {
if (!taskListener.isEmpty()) {
TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
taskListener.finished(e);
}
}
} }
|
public class class_name {
protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
if (compileStates.isDone(env, CompileState.FLOW)) {
results.add(env); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
try {
if (shouldStop(CompileState.FLOW))
return;
if (relax) {
results.add(env); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (verboseCompilePolicy)
printNote("[flow " + env.enclClass.sym + "]");
JavaFileObject prev = log.useSource(
env.enclClass.sym.sourcefile != null ?
env.enclClass.sym.sourcefile :
env.toplevel.sourcefile);
try {
make.at(Position.FIRSTPOS); // depends on control dependency: [try], data = [none]
TreeMaker localMake = make.forToplevel(env.toplevel);
flow.analyzeTree(env, localMake); // depends on control dependency: [try], data = [none]
compileStates.put(env, CompileState.FLOW); // depends on control dependency: [try], data = [none]
if (shouldStop(CompileState.FLOW))
return;
results.add(env); // depends on control dependency: [try], data = [none]
}
finally {
log.useSource(prev);
}
}
finally {
if (!taskListener.isEmpty()) {
TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
taskListener.finished(e); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public int read()
{
if (_length <= _offset) {
if (_head == null)
return -1;
TempCharBuffer next = _head.getNext();
if (_isFree)
TempCharBuffer.free(_head);
_head = next;
if (_head == null)
return -1;
_buffer = _head.buffer();
_length = _head.getLength();
_offset = 0;
}
return _buffer[_offset++];
} }
|
public class class_name {
public int read()
{
if (_length <= _offset) {
if (_head == null)
return -1;
TempCharBuffer next = _head.getNext();
if (_isFree)
TempCharBuffer.free(_head);
_head = next; // depends on control dependency: [if], data = [none]
if (_head == null)
return -1;
_buffer = _head.buffer(); // depends on control dependency: [if], data = [none]
_length = _head.getLength(); // depends on control dependency: [if], data = [none]
_offset = 0; // depends on control dependency: [if], data = [none]
}
return _buffer[_offset++];
} }
|
public class class_name {
public Task<Void> remove(final CacheKey key) {
Preconditions.checkNotNull(key);
mStagingArea.remove(key);
try {
return Task.call(
new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("BufferedDiskCache#remove");
}
mStagingArea.remove(key);
mFileCache.remove(key);
} finally {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
}
return null;
}
},
mWriteExecutor);
} catch (Exception exception) {
// Log failure
// TODO: 3697790
FLog.w(TAG, exception, "Failed to schedule disk-cache remove for %s", key.getUriString());
return Task.forError(exception);
}
} }
|
public class class_name {
public Task<Void> remove(final CacheKey key) {
Preconditions.checkNotNull(key);
mStagingArea.remove(key);
try {
return Task.call(
new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("BufferedDiskCache#remove");
}
mStagingArea.remove(key);
mFileCache.remove(key);
} finally {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
}
return null;
}
},
mWriteExecutor);
} catch (Exception exception) {
// Log failure
// TODO: 3697790
FLog.w(TAG, exception, "Failed to schedule disk-cache remove for %s", key.getUriString());
return Task.forError(exception);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public void replot() {
width = co.size();
height = (int) Math.ceil(width * .2);
ratio = width / (double) height;
height = height < MIN_HEIGHT ? MIN_HEIGHT : height > MAX_HEIGHT ? MAX_HEIGHT : height;
if(scale == null) {
scale = computeScale(co);
}
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int x = 0;
for(DBIDIter it = co.iter(); it.valid(); it.advance()) {
double reach = co.getReachability(it);
final int y = scaleToPixel(reach);
try {
int col = colors.getColorForDBID(it);
for(int y2 = height - 1; y2 >= y; y2--) {
img.setRGB(x, y2, col);
}
}
catch(ArrayIndexOutOfBoundsException e) {
LOG.error("Plotting out of range: " + x + "," + y + " >= " + width + "x" + height);
}
x++;
}
plot = img;
} }
|
public class class_name {
public void replot() {
width = co.size();
height = (int) Math.ceil(width * .2);
ratio = width / (double) height;
height = height < MIN_HEIGHT ? MIN_HEIGHT : height > MAX_HEIGHT ? MAX_HEIGHT : height;
if(scale == null) {
scale = computeScale(co); // depends on control dependency: [if], data = [none]
}
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int x = 0;
for(DBIDIter it = co.iter(); it.valid(); it.advance()) {
double reach = co.getReachability(it);
final int y = scaleToPixel(reach);
try {
int col = colors.getColorForDBID(it);
for(int y2 = height - 1; y2 >= y; y2--) {
img.setRGB(x, y2, col); // depends on control dependency: [for], data = [y2]
}
}
catch(ArrayIndexOutOfBoundsException e) {
LOG.error("Plotting out of range: " + x + "," + y + " >= " + width + "x" + height);
} // depends on control dependency: [catch], data = [none]
x++; // depends on control dependency: [for], data = [none]
}
plot = img;
} }
|
public class class_name {
public <T> void generateFromStringTemplate(T model, String[] parameters, FileObject fileObject, String content) throws IOException {
if (fileObject.getName().endsWith(SOURCE_SUFFIX)) {
TypeDef newModel = createTypeFromTemplate(model, parameters, content);
if (processingEnv.getElementUtils().getTypeElement(newModel.getFullyQualifiedName()) != null) {
System.err.println("Skipping: " + fileObject.getName()+ ". File already exists.");
return;
}
if (classExists(newModel)) {
System.err.println("Skipping: " + newModel.getFullyQualifiedName()+ ". Class already exists.");
return;
}
}
System.err.println("Generating: "+fileObject.getName());
new CodeGeneratorBuilder<T>()
.withContext(context)
.withModel(model)
.withParameters(parameters)
.withWriter(fileObject.openWriter())
.withTemplateContent(content)
.build()
.generate();
} }
|
public class class_name {
public <T> void generateFromStringTemplate(T model, String[] parameters, FileObject fileObject, String content) throws IOException {
if (fileObject.getName().endsWith(SOURCE_SUFFIX)) {
TypeDef newModel = createTypeFromTemplate(model, parameters, content);
if (processingEnv.getElementUtils().getTypeElement(newModel.getFullyQualifiedName()) != null) {
System.err.println("Skipping: " + fileObject.getName()+ ". File already exists."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (classExists(newModel)) {
System.err.println("Skipping: " + newModel.getFullyQualifiedName()+ ". Class already exists."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
System.err.println("Generating: "+fileObject.getName());
new CodeGeneratorBuilder<T>()
.withContext(context)
.withModel(model)
.withParameters(parameters)
.withWriter(fileObject.openWriter())
.withTemplateContent(content)
.build()
.generate();
} }
|
public class class_name {
public void deleteObjects(Collection objects)
{
for (Iterator iterator = objects.iterator(); iterator.hasNext();)
{
getDatabase().deletePersistent(iterator.next());
}
} }
|
public class class_name {
public void deleteObjects(Collection objects)
{
for (Iterator iterator = objects.iterator(); iterator.hasNext();)
{
getDatabase().deletePersistent(iterator.next());
// depends on control dependency: [for], data = [iterator]
}
} }
|
public class class_name {
public ToStringBuilder append(String name, Map<?, ?> map) {
StringBuilder sb = new StringBuilder(START_OBJ);
for (Map.Entry<?, ?> entry : map.entrySet()) {
sb.append(entry.getKey()).append(FIELD_VALUE_SEPARATOR).append(formatValue(entry.getValue()));
}
sb.append(END_OBJ);
return appendFormattedValue(name, sb.toString());
} }
|
public class class_name {
public ToStringBuilder append(String name, Map<?, ?> map) {
StringBuilder sb = new StringBuilder(START_OBJ);
for (Map.Entry<?, ?> entry : map.entrySet()) {
sb.append(entry.getKey()).append(FIELD_VALUE_SEPARATOR).append(formatValue(entry.getValue())); // depends on control dependency: [for], data = [entry]
}
sb.append(END_OBJ);
return appendFormattedValue(name, sb.toString());
} }
|
public class class_name {
private SshConnection connect() {
if (sshConnection != null && sshConnection.isConnected()) {
return sshConnection;
}
while (!shutdownInProgress) {
SshConnection ssh = null;
try {
logger.debug("Connecting...");
ssh = SshConnectionFactory.getConnection(gerritHostName, gerritSshPort, gerritProxy,
authentication, authenticationUpdater);
gerritVersion = formatVersion(ssh.executeCommand("gerrit version"));
logger.debug("connection seems ok, returning it.");
return ssh;
} catch (SshConnectException sshConEx) {
logger.error("Could not connect to Gerrit server! "
+ "Host: {} Port: {}", gerritHostName, gerritSshPort);
logger.error(" Proxy: {}", gerritProxy);
logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
logger.error("ConnectionException: ", sshConEx);
} catch (SshAuthenticationException sshAuthEx) {
logger.error("Could not authenticate to Gerrit server!"
+ "\n\tUsername: {}\n\tKeyFile: {}\n\tPassword: {}",
new Object[]{authentication.getUsername(),
authentication.getPrivateKeyFile(),
authentication.getPrivateKeyFilePassword(), });
logger.error("AuthenticationException: ", sshAuthEx);
} catch (IOException ex) {
logger.error("Could not connect to Gerrit server! "
+ "Host: {} Port: {}", gerritHostName, gerritSshPort);
logger.error(" Proxy: {}", gerritProxy);
logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
logger.error("IOException: ", ex);
}
if (ssh != null) {
logger.trace("Disconnecting bad connection.");
try {
//The ssh lib used is starting at least one thread for each connection.
//The thread isn't shutdown properly when the connection goes down,
//so we need to close it "manually"
ssh.disconnect();
} catch (Exception ex) {
logger.warn("Error when disconnecting bad connection.", ex);
} finally {
ssh = null;
}
}
if (!shutdownInProgress) {
//If we end up here, sleep for a while and then go back up in the loop.
logger.trace("Sleeping for a bit.");
try {
Thread.sleep(CONNECT_SLEEP);
} catch (InterruptedException ex) {
logger.warn("Got interrupted while sleeping.", ex);
}
}
}
return null;
} }
|
public class class_name {
private SshConnection connect() {
if (sshConnection != null && sshConnection.isConnected()) {
return sshConnection; // depends on control dependency: [if], data = [none]
}
while (!shutdownInProgress) {
SshConnection ssh = null;
try {
logger.debug("Connecting..."); // depends on control dependency: [try], data = [none]
ssh = SshConnectionFactory.getConnection(gerritHostName, gerritSshPort, gerritProxy,
authentication, authenticationUpdater); // depends on control dependency: [try], data = [none]
gerritVersion = formatVersion(ssh.executeCommand("gerrit version")); // depends on control dependency: [try], data = [none]
logger.debug("connection seems ok, returning it."); // depends on control dependency: [try], data = [none]
return ssh; // depends on control dependency: [try], data = [none]
} catch (SshConnectException sshConEx) {
logger.error("Could not connect to Gerrit server! "
+ "Host: {} Port: {}", gerritHostName, gerritSshPort);
logger.error(" Proxy: {}", gerritProxy);
logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
logger.error("ConnectionException: ", sshConEx);
} catch (SshAuthenticationException sshAuthEx) { // depends on control dependency: [catch], data = [none]
logger.error("Could not authenticate to Gerrit server!"
+ "\n\tUsername: {}\n\tKeyFile: {}\n\tPassword: {}",
new Object[]{authentication.getUsername(),
authentication.getPrivateKeyFile(),
authentication.getPrivateKeyFilePassword(), });
logger.error("AuthenticationException: ", sshAuthEx);
} catch (IOException ex) { // depends on control dependency: [catch], data = [none]
logger.error("Could not connect to Gerrit server! "
+ "Host: {} Port: {}", gerritHostName, gerritSshPort);
logger.error(" Proxy: {}", gerritProxy);
logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
logger.error("IOException: ", ex);
} // depends on control dependency: [catch], data = [none]
if (ssh != null) {
logger.trace("Disconnecting bad connection."); // depends on control dependency: [if], data = [none]
try {
//The ssh lib used is starting at least one thread for each connection.
//The thread isn't shutdown properly when the connection goes down,
//so we need to close it "manually"
ssh.disconnect(); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
logger.warn("Error when disconnecting bad connection.", ex);
} finally { // depends on control dependency: [catch], data = [none]
ssh = null;
}
}
if (!shutdownInProgress) {
//If we end up here, sleep for a while and then go back up in the loop.
logger.trace("Sleeping for a bit."); // depends on control dependency: [if], data = [none]
try {
Thread.sleep(CONNECT_SLEEP); // depends on control dependency: [try], data = [none]
} catch (InterruptedException ex) {
logger.warn("Got interrupted while sleeping.", ex);
} // depends on control dependency: [catch], data = [none]
}
}
return null;
} }
|
public class class_name {
public static String regexFlags(final int flags) {
int processedFlags = flags;
StringBuilder buf = new StringBuilder();
for (int i = 0; i < FLAG_LOOKUP.length; i++) {
if ((processedFlags & FLAG_LOOKUP[i]) > 0) {
buf.append((char) i);
processedFlags -= FLAG_LOOKUP[i];
}
}
if (processedFlags > 0) {
throw new IllegalArgumentException("Some flags could not be recognized.");
}
return buf.toString();
} }
|
public class class_name {
public static String regexFlags(final int flags) {
int processedFlags = flags;
StringBuilder buf = new StringBuilder();
for (int i = 0; i < FLAG_LOOKUP.length; i++) {
if ((processedFlags & FLAG_LOOKUP[i]) > 0) {
buf.append((char) i); // depends on control dependency: [if], data = [none]
processedFlags -= FLAG_LOOKUP[i]; // depends on control dependency: [if], data = [none]
}
}
if (processedFlags > 0) {
throw new IllegalArgumentException("Some flags could not be recognized.");
}
return buf.toString();
} }
|
public class class_name {
public static final void fileDump(String fileName, byte[] data)
{
try
{
FileOutputStream os = new FileOutputStream(fileName);
os.write(data);
os.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
} }
|
public class class_name {
public static final void fileDump(String fileName, byte[] data)
{
try
{
FileOutputStream os = new FileOutputStream(fileName);
os.write(data); // depends on control dependency: [try], data = [none]
os.close(); // depends on control dependency: [try], data = [none]
}
catch (IOException ex)
{
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static void registerLogger(final Class<? extends LoggerFactory> factoryClass) {
if (loggerFactory == null) {
FACTORIES.add(0, factoryClass.getName());
} else {
throw new IllegalStateException("LoggerImplFactory must be registered before logging is initialized.");
}
} }
|
public class class_name {
public static void registerLogger(final Class<? extends LoggerFactory> factoryClass) {
if (loggerFactory == null) {
FACTORIES.add(0, factoryClass.getName()); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalStateException("LoggerImplFactory must be registered before logging is initialized.");
}
} }
|
public class class_name {
public CompositeByteBuf discardReadComponents() {
ensureAccessible();
final int readerIndex = readerIndex();
if (readerIndex == 0) {
return this;
}
// Discard everything if (readerIndex = writerIndex = capacity).
int writerIndex = writerIndex();
if (readerIndex == writerIndex && writerIndex == capacity()) {
for (int i = 0, size = componentCount; i < size; i++) {
components[i].free();
}
lastAccessed = null;
clearComps();
setIndex(0, 0);
adjustMarkers(readerIndex);
return this;
}
// Remove read components.
int firstComponentId = 0;
Component c = null;
for (int size = componentCount; firstComponentId < size; firstComponentId++) {
c = components[firstComponentId];
if (c.endOffset > readerIndex) {
break;
}
c.free();
}
if (firstComponentId == 0) {
return this; // Nothing to discard
}
Component la = lastAccessed;
if (la != null && la.endOffset <= readerIndex) {
lastAccessed = null;
}
removeCompRange(0, firstComponentId);
// Update indexes and markers.
int offset = c.offset;
updateComponentOffsets(0);
setIndex(readerIndex - offset, writerIndex - offset);
adjustMarkers(offset);
return this;
} }
|
public class class_name {
public CompositeByteBuf discardReadComponents() {
ensureAccessible();
final int readerIndex = readerIndex();
if (readerIndex == 0) {
return this; // depends on control dependency: [if], data = [none]
}
// Discard everything if (readerIndex = writerIndex = capacity).
int writerIndex = writerIndex();
if (readerIndex == writerIndex && writerIndex == capacity()) {
for (int i = 0, size = componentCount; i < size; i++) {
components[i].free(); // depends on control dependency: [for], data = [i]
}
lastAccessed = null; // depends on control dependency: [if], data = [none]
clearComps(); // depends on control dependency: [if], data = [none]
setIndex(0, 0); // depends on control dependency: [if], data = [none]
adjustMarkers(readerIndex); // depends on control dependency: [if], data = [(readerIndex]
return this; // depends on control dependency: [if], data = [none]
}
// Remove read components.
int firstComponentId = 0;
Component c = null;
for (int size = componentCount; firstComponentId < size; firstComponentId++) {
c = components[firstComponentId]; // depends on control dependency: [for], data = [none]
if (c.endOffset > readerIndex) {
break;
}
c.free(); // depends on control dependency: [for], data = [none]
}
if (firstComponentId == 0) {
return this; // Nothing to discard // depends on control dependency: [if], data = [none]
}
Component la = lastAccessed;
if (la != null && la.endOffset <= readerIndex) {
lastAccessed = null; // depends on control dependency: [if], data = [none]
}
removeCompRange(0, firstComponentId);
// Update indexes and markers.
int offset = c.offset;
updateComponentOffsets(0);
setIndex(readerIndex - offset, writerIndex - offset);
adjustMarkers(offset);
return this;
} }
|
public class class_name {
@Override
public EEnum getIfcElectricGeneratorTypeEnum() {
if (ifcElectricGeneratorTypeEnumEEnum == null) {
ifcElectricGeneratorTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(977);
}
return ifcElectricGeneratorTypeEnumEEnum;
} }
|
public class class_name {
@Override
public EEnum getIfcElectricGeneratorTypeEnum() {
if (ifcElectricGeneratorTypeEnumEEnum == null) {
ifcElectricGeneratorTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(977);
// depends on control dependency: [if], data = [none]
}
return ifcElectricGeneratorTypeEnumEEnum;
} }
|
public class class_name {
public int guessOrderFromAngle(double threshold, int maxOrder) {
double bestDelta = threshold;
int bestOrder = 1;
for (int order = 2; order < maxOrder; order++) {
double delta = Math.abs(2 * Math.PI / order - theta);
if (delta < bestDelta) {
bestOrder = order;
bestDelta = delta;
}
}
return bestOrder;
} }
|
public class class_name {
public int guessOrderFromAngle(double threshold, int maxOrder) {
double bestDelta = threshold;
int bestOrder = 1;
for (int order = 2; order < maxOrder; order++) {
double delta = Math.abs(2 * Math.PI / order - theta);
if (delta < bestDelta) {
bestOrder = order; // depends on control dependency: [if], data = [none]
bestDelta = delta; // depends on control dependency: [if], data = [none]
}
}
return bestOrder;
} }
|
public class class_name {
@Override
public void paint(Graphics g, Shape allocation) {
Rectangle r = (allocation instanceof Rectangle) ? (Rectangle) allocation : allocation.getBounds();
Color oldColor = g.getColor();
Integer lineNumber = getLineNumber();
Color highlightColor = highlight.getHighlight(lineNumber);
if (highlightColor != null) {
g.setColor(highlightColor);
g.fillRect(r.x, r.y, r.width, r.height);
g.setColor(oldColor);
}
// r.x += NUMBERS_WIDTH;
super.paint(g, r);
FontMetrics metrics = g.getFontMetrics();
g.setColor(Color.GRAY);
String lineNumberString = lineNumber.toString();
int width = metrics.stringWidth(lineNumberString);
int numberX = r.x - width - 9 + NUMBERS_WIDTH;
int numberY = r.y + metrics.getAscent();
g.drawString(lineNumberString, numberX, numberY);
g.setColor(oldColor);
// System.out.println("Drawing line for " + lineNumber + " @ " + numberX
// +"," + numberY);
// r.x -= NUMBERS_WIDTH;
} }
|
public class class_name {
@Override
public void paint(Graphics g, Shape allocation) {
Rectangle r = (allocation instanceof Rectangle) ? (Rectangle) allocation : allocation.getBounds();
Color oldColor = g.getColor();
Integer lineNumber = getLineNumber();
Color highlightColor = highlight.getHighlight(lineNumber);
if (highlightColor != null) {
g.setColor(highlightColor); // depends on control dependency: [if], data = [(highlightColor]
g.fillRect(r.x, r.y, r.width, r.height); // depends on control dependency: [if], data = [none]
g.setColor(oldColor); // depends on control dependency: [if], data = [none]
}
// r.x += NUMBERS_WIDTH;
super.paint(g, r);
FontMetrics metrics = g.getFontMetrics();
g.setColor(Color.GRAY);
String lineNumberString = lineNumber.toString();
int width = metrics.stringWidth(lineNumberString);
int numberX = r.x - width - 9 + NUMBERS_WIDTH;
int numberY = r.y + metrics.getAscent();
g.drawString(lineNumberString, numberX, numberY);
g.setColor(oldColor);
// System.out.println("Drawing line for " + lineNumber + " @ " + numberX
// +"," + numberY);
// r.x -= NUMBERS_WIDTH;
} }
|
public class class_name {
public static <T, E extends Throwable> List<T> filter(List<T> coll, APredicate<? super T, E> pred) throws E {
final List<T> result = createEmptyListOfType (coll, false);
for(T o: coll) {
if(pred.apply(o)) {
result.add(o);
}
}
return result;
} }
|
public class class_name {
public static <T, E extends Throwable> List<T> filter(List<T> coll, APredicate<? super T, E> pred) throws E {
final List<T> result = createEmptyListOfType (coll, false);
for(T o: coll) {
if(pred.apply(o)) {
result.add(o); // depends on control dependency: [if], data = [none]
}
}
return result;
} }
|
public class class_name {
private void validateTypeAnnotations(Node n, JSDocInfo info) {
if (info != null && info.hasType()) {
boolean valid = false;
switch (n.getToken()) {
// Function declarations are valid
case FUNCTION:
valid = NodeUtil.isFunctionDeclaration(n);
break;
// Object literal properties, catch declarations and variable
// initializers are valid.
case NAME:
valid = isTypeAnnotationAllowedForName(n);
break;
case ARRAY_PATTERN:
case OBJECT_PATTERN:
// allow JSDoc like
// function f(/** !Object */ {x}) {}
// function f(/** !Array */ [x]) {}
valid = n.getParent().isParamList();
break;
// Casts, exports, and Object literal properties are valid.
case CAST:
case EXPORT:
case STRING_KEY:
case GETTER_DEF:
case SETTER_DEF:
valid = true;
break;
// Declarations are valid iff they only contain simple names
// /** @type {number} */ var x = 3; // ok
// /** @type {number} */ var {x} = obj; // forbidden
case VAR:
case LET:
case CONST:
valid = !NodeUtil.isDestructuringDeclaration(n);
break;
// Property assignments are valid, if at the root of an expression.
case ASSIGN: {
Node lvalue = n.getFirstChild();
valid = n.getParent().isExprResult()
&& (lvalue.isGetProp()
|| lvalue.isGetElem()
|| lvalue.matchesQualifiedName("exports"));
break;
}
case GETPROP:
valid = n.getParent().isExprResult() && n.isQualifiedName();
break;
case CALL:
valid = info.isDefine();
break;
default:
break;
}
if (!valid) {
reportMisplaced(n, "type", "Type annotations are not allowed here. "
+ "Are you missing parentheses?");
}
}
} }
|
public class class_name {
private void validateTypeAnnotations(Node n, JSDocInfo info) {
if (info != null && info.hasType()) {
boolean valid = false;
switch (n.getToken()) { // depends on control dependency: [if], data = [none]
// Function declarations are valid
case FUNCTION:
valid = NodeUtil.isFunctionDeclaration(n);
break;
// Object literal properties, catch declarations and variable
// initializers are valid.
case NAME:
valid = isTypeAnnotationAllowedForName(n);
break;
case ARRAY_PATTERN:
case OBJECT_PATTERN:
// allow JSDoc like
// function f(/** !Object */ {x}) {}
// function f(/** !Array */ [x]) {}
valid = n.getParent().isParamList();
break;
// Casts, exports, and Object literal properties are valid.
case CAST:
case EXPORT:
case STRING_KEY:
case GETTER_DEF:
case SETTER_DEF:
valid = true;
break;
// Declarations are valid iff they only contain simple names
// /** @type {number} */ var x = 3; // ok
// /** @type {number} */ var {x} = obj; // forbidden
case VAR:
case LET:
case CONST:
valid = !NodeUtil.isDestructuringDeclaration(n);
break;
// Property assignments are valid, if at the root of an expression.
case ASSIGN: {
Node lvalue = n.getFirstChild();
valid = n.getParent().isExprResult()
&& (lvalue.isGetProp()
|| lvalue.isGetElem()
|| lvalue.matchesQualifiedName("exports"));
break;
}
case GETPROP:
valid = n.getParent().isExprResult() && n.isQualifiedName();
break;
case CALL:
valid = info.isDefine();
break;
default:
break;
}
if (!valid) {
reportMisplaced(n, "type", "Type annotations are not allowed here. "
+ "Are you missing parentheses?"); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
private static List<DiscoveryIncomingMessage> collectIncomingMessages(int pTimeout, List<Future<List<DiscoveryIncomingMessage>>> pFutures, LogHandler pLogHandler) throws UnknownHostException {
List<DiscoveryIncomingMessage> ret = new ArrayList<DiscoveryIncomingMessage>();
Set<String> seen = new HashSet<String>();
int nrCouldntSend = 0;
for (Future<List<DiscoveryIncomingMessage>> future : pFutures) {
try {
List<DiscoveryIncomingMessage> inMsgs = future.get(pTimeout + 500 /* some additional buffer */, TimeUnit.MILLISECONDS);
for (DiscoveryIncomingMessage inMsg : inMsgs) {
AgentDetails details = inMsg.getAgentDetails();
String id = details.getAgentId();
// There can be multiples answers with the same message id
if (!seen.contains(id)) {
ret.add(inMsg);
seen.add(id);
}
}
} catch (InterruptedException exp) {
// Try next one ...
} catch (ExecutionException e) {
Throwable exp = e.getCause();
if (exp instanceof CouldntSendDiscoveryPacketException) {
nrCouldntSend++;
pLogHandler.debug("--> Couldnt send discovery message from " +
((CouldntSendDiscoveryPacketException) exp).getAddress() + ": " + exp.getCause());
}
// Didn't worked a given address, which can happen e.g. when multicast is not routed or in other cases
// throw new IOException("Error while performing a discovery call " + e,e);
pLogHandler.debug("--> Exception during lookup: " + e);
} catch (TimeoutException e) {
// Timeout occurred while waiting for the results. So we go to the next one ...
}
}
if (nrCouldntSend == pFutures.size()) {
// No a single discovery message could be send out
throw new UnknownHostException("Cannot send a single multicast recovery request on any multicast enabled interface");
}
return ret;
} }
|
public class class_name {
private static List<DiscoveryIncomingMessage> collectIncomingMessages(int pTimeout, List<Future<List<DiscoveryIncomingMessage>>> pFutures, LogHandler pLogHandler) throws UnknownHostException {
List<DiscoveryIncomingMessage> ret = new ArrayList<DiscoveryIncomingMessage>();
Set<String> seen = new HashSet<String>();
int nrCouldntSend = 0;
for (Future<List<DiscoveryIncomingMessage>> future : pFutures) {
try {
List<DiscoveryIncomingMessage> inMsgs = future.get(pTimeout + 500 /* some additional buffer */, TimeUnit.MILLISECONDS);
for (DiscoveryIncomingMessage inMsg : inMsgs) {
AgentDetails details = inMsg.getAgentDetails();
String id = details.getAgentId();
// There can be multiples answers with the same message id
if (!seen.contains(id)) {
ret.add(inMsg); // depends on control dependency: [if], data = [none]
seen.add(id); // depends on control dependency: [if], data = [none]
}
}
} catch (InterruptedException exp) {
// Try next one ...
} catch (ExecutionException e) { // depends on control dependency: [catch], data = [none]
Throwable exp = e.getCause();
if (exp instanceof CouldntSendDiscoveryPacketException) {
nrCouldntSend++; // depends on control dependency: [if], data = [none]
pLogHandler.debug("--> Couldnt send discovery message from " +
((CouldntSendDiscoveryPacketException) exp).getAddress() + ": " + exp.getCause()); // depends on control dependency: [if], data = [none]
}
// Didn't worked a given address, which can happen e.g. when multicast is not routed or in other cases
// throw new IOException("Error while performing a discovery call " + e,e);
pLogHandler.debug("--> Exception during lookup: " + e);
} catch (TimeoutException e) { // depends on control dependency: [catch], data = [none]
// Timeout occurred while waiting for the results. So we go to the next one ...
} // depends on control dependency: [catch], data = [none]
}
if (nrCouldntSend == pFutures.size()) {
// No a single discovery message could be send out
throw new UnknownHostException("Cannot send a single multicast recovery request on any multicast enabled interface");
}
return ret;
} }
|
public class class_name {
public static String toLowerCamelCase( String s )
{
if (StringUtil.isBlank( s )) return s.trim();
StringBuilder sb = new StringBuilder();
String[] parts = s.trim().split( "\\s+" );
sb.append( parts[0].toLowerCase() );
for (int i = 1; i < parts.length; ++i)
{
sb.append( capitalize( parts[i] ) );
}
return sb.toString();
} }
|
public class class_name {
public static String toLowerCamelCase( String s )
{
if (StringUtil.isBlank( s )) return s.trim();
StringBuilder sb = new StringBuilder();
String[] parts = s.trim().split( "\\s+" );
sb.append( parts[0].toLowerCase() );
for (int i = 1; i < parts.length; ++i)
{
sb.append( capitalize( parts[i] ) ); // depends on control dependency: [for], data = [i]
}
return sb.toString();
} }
|
public class class_name {
private Node<K,V> leastNode(final Node<K,V> node, final int index) {
Node<K,V> lval = node;
if (lval != null) {
while (lval.getLeft(index) != null) {
lval = lval.getLeft(index);
}
}
return lval;
} }
|
public class class_name {
private Node<K,V> leastNode(final Node<K,V> node, final int index) {
Node<K,V> lval = node;
if (lval != null) {
while (lval.getLeft(index) != null) {
lval = lval.getLeft(index);
// depends on control dependency: [while], data = [none]
}
}
return lval;
} }
|
public class class_name {
public void setFormatByArgumentName(String argumentName, Format newFormat) {
int argNumber = MessagePattern.validateArgumentName(argumentName);
if (argNumber < MessagePattern.ARG_NAME_NOT_NUMBER) {
return;
}
for (int partIndex = 0; (partIndex = nextTopLevelArgStart(partIndex)) >= 0;) {
if (argNameMatches(partIndex + 1, argumentName, argNumber)) {
setCustomArgStartFormat(partIndex, newFormat);
}
}
} }
|
public class class_name {
public void setFormatByArgumentName(String argumentName, Format newFormat) {
int argNumber = MessagePattern.validateArgumentName(argumentName);
if (argNumber < MessagePattern.ARG_NAME_NOT_NUMBER) {
return; // depends on control dependency: [if], data = [none]
}
for (int partIndex = 0; (partIndex = nextTopLevelArgStart(partIndex)) >= 0;) {
if (argNameMatches(partIndex + 1, argumentName, argNumber)) {
setCustomArgStartFormat(partIndex, newFormat); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@Override
void setLocale(ULocale valid, ULocale actual) {
// This method is called
// by other protected functions that checks and makes sure that
// valid and actual are not null before passing
assert (valid == null) == (actual == null);
// Another check we could do is that the actual locale is at
// the same level or less specific than the valid locale.
// TODO: Starting with Java 7, use Objects.equals(a, b).
if(Utility.objectEquals(actual, tailoring.actualLocale)) {
actualLocaleIsSameAsValid = false;
} else {
assert(Utility.objectEquals(actual, valid));
actualLocaleIsSameAsValid = true;
}
// Do not modify tailoring.actualLocale:
// We cannot be sure that that would be thread-safe.
validLocale = valid;
} }
|
public class class_name {
@Override
void setLocale(ULocale valid, ULocale actual) {
// This method is called
// by other protected functions that checks and makes sure that
// valid and actual are not null before passing
assert (valid == null) == (actual == null);
// Another check we could do is that the actual locale is at
// the same level or less specific than the valid locale.
// TODO: Starting with Java 7, use Objects.equals(a, b).
if(Utility.objectEquals(actual, tailoring.actualLocale)) {
actualLocaleIsSameAsValid = false; // depends on control dependency: [if], data = [none]
} else {
assert(Utility.objectEquals(actual, valid)); // depends on control dependency: [if], data = [none]
actualLocaleIsSameAsValid = true; // depends on control dependency: [if], data = [none]
}
// Do not modify tailoring.actualLocale:
// We cannot be sure that that would be thread-safe.
validLocale = valid;
} }
|
public class class_name {
@Override
public boolean hasAccessToWebResource(String resource, String... methods) {
String appName = getApplicationName();
SecurityMetadata securityMetadata = WebConfigUtils.getSecurityMetadata();
SecurityConstraintCollection collection = null;
if (securityMetadata != null) {
collection = securityMetadata.getSecurityConstraintCollection();
}
if (null != collection) {
AuthorizationService authService = SecurityContextHelper.getAuthorizationService();
Subject callerSubject = getCallerSubject();
List<MatchResponse> matchResponses = collection.getMatchResponses(resource, methods);
for (MatchResponse response : matchResponses) {
if (response.equals(MatchResponse.NO_MATCH_RESPONSE)) {
// There are no constraints so user has access
return true;
}
if (response.isAccessPrecluded()) {
//This methods access is precluded proceed to next method
continue;
}
List<String> roles = response.getRoles();
if (roles != null && !roles.isEmpty()) {
if (authService.isAuthorized(appName, roles, callerSubject)) {
return true;
}
} else {
// there are no roles and access is not precluded the user has access
return true;
}
}
}
return false;
} }
|
public class class_name {
@Override
public boolean hasAccessToWebResource(String resource, String... methods) {
String appName = getApplicationName();
SecurityMetadata securityMetadata = WebConfigUtils.getSecurityMetadata();
SecurityConstraintCollection collection = null;
if (securityMetadata != null) {
collection = securityMetadata.getSecurityConstraintCollection(); // depends on control dependency: [if], data = [none]
}
if (null != collection) {
AuthorizationService authService = SecurityContextHelper.getAuthorizationService();
Subject callerSubject = getCallerSubject();
List<MatchResponse> matchResponses = collection.getMatchResponses(resource, methods);
for (MatchResponse response : matchResponses) {
if (response.equals(MatchResponse.NO_MATCH_RESPONSE)) {
// There are no constraints so user has access
return true; // depends on control dependency: [if], data = [none]
}
if (response.isAccessPrecluded()) {
//This methods access is precluded proceed to next method
continue;
}
List<String> roles = response.getRoles();
if (roles != null && !roles.isEmpty()) {
if (authService.isAuthorized(appName, roles, callerSubject)) {
return true; // depends on control dependency: [if], data = [none]
}
} else {
// there are no roles and access is not precluded the user has access
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} }
|
public class class_name {
@Override
public void onMouseUp(MouseUpEvent event) {
if (dragging) {
setDragging(false);
draggingMask.getRenderable().removeFromParent();
draggingMask = null;
onDragStop(event.getClientX(), event.getClientY());
release(invisibleClickArea);
}
} }
|
public class class_name {
@Override
public void onMouseUp(MouseUpEvent event) {
if (dragging) {
setDragging(false); // depends on control dependency: [if], data = [none]
draggingMask.getRenderable().removeFromParent(); // depends on control dependency: [if], data = [none]
draggingMask = null; // depends on control dependency: [if], data = [none]
onDragStop(event.getClientX(), event.getClientY()); // depends on control dependency: [if], data = [none]
release(invisibleClickArea); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public List<Database> listDatabases(String instanceId) {
// [START listDatabases]
Page<Database> page = dbAdminClient.listDatabases(instanceId, Options.pageSize(1));
List<Database> dbs = new ArrayList<>();
while (page != null) {
Database db = Iterables.getOnlyElement(page.getValues());
dbs.add(db);
page = page.getNextPage();
}
// [END listDatabases]
return dbs;
} }
|
public class class_name {
public List<Database> listDatabases(String instanceId) {
// [START listDatabases]
Page<Database> page = dbAdminClient.listDatabases(instanceId, Options.pageSize(1));
List<Database> dbs = new ArrayList<>();
while (page != null) {
Database db = Iterables.getOnlyElement(page.getValues());
dbs.add(db); // depends on control dependency: [while], data = [none]
page = page.getNextPage(); // depends on control dependency: [while], data = [none]
}
// [END listDatabases]
return dbs;
} }
|
public class class_name {
protected AccessBuilder readAccess(DatasetBuilder dataset, Element accessElem) {
String urlPath = accessElem.getAttributeValue("urlPath");
String serviceName = accessElem.getAttributeValue("serviceName");
String dataFormat = accessElem.getAttributeValue("dataFormat");
Service s = serviceMap.get(serviceName);
if (s == null) {
errlog.format("Cant find service name='%s'%n", serviceName);
logger.debug("Can't find service name='{}'", serviceName);
}
return new AccessBuilder(dataset, urlPath, s, dataFormat, readDataSize(accessElem));
} }
|
public class class_name {
protected AccessBuilder readAccess(DatasetBuilder dataset, Element accessElem) {
String urlPath = accessElem.getAttributeValue("urlPath");
String serviceName = accessElem.getAttributeValue("serviceName");
String dataFormat = accessElem.getAttributeValue("dataFormat");
Service s = serviceMap.get(serviceName);
if (s == null) {
errlog.format("Cant find service name='%s'%n", serviceName); // depends on control dependency: [if], data = [none]
logger.debug("Can't find service name='{}'", serviceName); // depends on control dependency: [if], data = [none]
}
return new AccessBuilder(dataset, urlPath, s, dataFormat, readDataSize(accessElem));
} }
|
public class class_name {
protected void repairAfterLazy() {
for (int k = 0; k < highLowContainer.size(); ++k) {
Container c = highLowContainer.getContainerAtIndex(k);
highLowContainer.setContainerAtIndex(k, c.repairAfterLazy());
}
} }
|
public class class_name {
protected void repairAfterLazy() {
for (int k = 0; k < highLowContainer.size(); ++k) {
Container c = highLowContainer.getContainerAtIndex(k);
highLowContainer.setContainerAtIndex(k, c.repairAfterLazy()); // depends on control dependency: [for], data = [k]
}
} }
|
public class class_name {
public void remoteInvalidate(String sessionId, boolean backendUpdate) {
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[REMOTE_INVALIDATE], "for app " + getId() + " id " + sessionId + " backendUpdate " + backendUpdate);
}
super.remoteInvalidate(sessionId, backendUpdate);
if (backendUpdate) {
((DatabaseHashMap) _sessions).setMaxInactToZero(sessionId, getId());
}
// now clean this session out of cache -- we do this even if not doing db inval
Vector v = new Vector(1);
v.add(sessionId);
((BackedHashMap) _sessions).handleDiscardedCacheItems(v.elements());
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[REMOTE_INVALIDATE], "for app " + getId() + " id " + sessionId);
}
} }
|
public class class_name {
public void remoteInvalidate(String sessionId, boolean backendUpdate) {
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[REMOTE_INVALIDATE], "for app " + getId() + " id " + sessionId + " backendUpdate " + backendUpdate); // depends on control dependency: [if], data = [none]
}
super.remoteInvalidate(sessionId, backendUpdate);
if (backendUpdate) {
((DatabaseHashMap) _sessions).setMaxInactToZero(sessionId, getId()); // depends on control dependency: [if], data = [none]
}
// now clean this session out of cache -- we do this even if not doing db inval
Vector v = new Vector(1);
v.add(sessionId);
((BackedHashMap) _sessions).handleDiscardedCacheItems(v.elements());
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[REMOTE_INVALIDATE], "for app " + getId() + " id " + sessionId); // 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.