code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
public static Class<?> getGenericClass(Field collectionField)
{
Class<?> genericClass = null;
if (collectionField == null)
{
return genericClass;
}
if (isCollection(collectionField.getType()))
{
Type[] parameters = ReflectUtils.getTypeArguments(collectionField);
if (parameters != null)
{
if (parameters.length == 1)
{
genericClass = toClass(parameters[0]);
}
else
{
throw new PropertyAccessException(
"Can't determine generic class from a field that has more than one parameters.");
}
}
}
if (collectionField.getType().isAssignableFrom(Map.class))
{
java.lang.reflect.Type[] arguments = ((ParameterizedType) collectionField.getGenericType())
.getActualTypeArguments();
if (arguments != null && arguments.length > 1)
{
genericClass = getTypedClass(arguments[1]);
}
}
return genericClass != null ? genericClass : collectionField.getType();
} }
|
public class class_name {
public static Class<?> getGenericClass(Field collectionField)
{
Class<?> genericClass = null;
if (collectionField == null)
{
return genericClass;
}
if (isCollection(collectionField.getType()))
{
Type[] parameters = ReflectUtils.getTypeArguments(collectionField);
if (parameters != null)
{
if (parameters.length == 1)
{
genericClass = toClass(parameters[0]);
// depends on control dependency: [if], data = [none]
}
else
{
throw new PropertyAccessException(
"Can't determine generic class from a field that has more than one parameters.");
}
}
}
if (collectionField.getType().isAssignableFrom(Map.class))
{
java.lang.reflect.Type[] arguments = ((ParameterizedType) collectionField.getGenericType())
.getActualTypeArguments();
if (arguments != null && arguments.length > 1)
{
genericClass = getTypedClass(arguments[1]);
// depends on control dependency: [if], data = [(arguments]
}
}
return genericClass != null ? genericClass : collectionField.getType();
} }
|
public class class_name {
public static WindowState getWindowState(String state) {
if (state == null) {
return null;
}
final WindowState windowState = WINDOW_STATES.get(state);
if (windowState != null) {
return windowState;
}
return new WindowState(state);
} }
|
public class class_name {
public static WindowState getWindowState(String state) {
if (state == null) {
return null; // depends on control dependency: [if], data = [none]
}
final WindowState windowState = WINDOW_STATES.get(state);
if (windowState != null) {
return windowState; // depends on control dependency: [if], data = [none]
}
return new WindowState(state);
} }
|
public class class_name {
public static void completeBackgroundTasks(long timeoutMillis) {
boolean fifoEmpty = false;
boolean asyncThreadsCompleted = false;
long absTimeout = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < absTimeout) {
synchronized (fifo) {
fifoEmpty = (fifo.size() == 0);
}
synchronized (JGoogleAnalyticsTracker.class) {
asyncThreadsCompleted = (asyncThreadsRunning == 0);
}
if (fifoEmpty && asyncThreadsCompleted) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
}
} }
|
public class class_name {
public static void completeBackgroundTasks(long timeoutMillis) {
boolean fifoEmpty = false;
boolean asyncThreadsCompleted = false;
long absTimeout = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < absTimeout) {
synchronized (fifo) { // depends on control dependency: [while], data = [none]
fifoEmpty = (fifo.size() == 0);
}
synchronized (JGoogleAnalyticsTracker.class) { // depends on control dependency: [while], data = [none]
asyncThreadsCompleted = (asyncThreadsRunning == 0);
}
if (fifoEmpty && asyncThreadsCompleted) {
break;
}
try {
Thread.sleep(100); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
break;
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
@Override
public void inactiveConnectionClosed(
Object connection, ManagedConnectionFactory managedConnectionFactory) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled()) {
Tr.entry(this, tc, "inactiveConnectionClosed");
}
// Ensure all connection handle lists are cleared of this handle.
// NOTE: The handle may exist in the EJB and Web container lists, but
// these lists are currently inaccessible to J2C.
if (isTraceOn && tc.isEntryEnabled()) {
Tr.exit(this, tc, "inactiveConnectionClosed");
}
} }
|
public class class_name {
@Override
public void inactiveConnectionClosed(
Object connection, ManagedConnectionFactory managedConnectionFactory) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled()) {
Tr.entry(this, tc, "inactiveConnectionClosed"); // depends on control dependency: [if], data = [none]
}
// Ensure all connection handle lists are cleared of this handle.
// NOTE: The handle may exist in the EJB and Web container lists, but
// these lists are currently inaccessible to J2C.
if (isTraceOn && tc.isEntryEnabled()) {
Tr.exit(this, tc, "inactiveConnectionClosed"); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private Token tryAndMatchOnLine(Token.Kind kind) {
int next = skipLineSpace(index);
if (next < tokens.size()) {
Token t = tokens.get(next);
if (t.kind == kind) {
index = next + 1;
return t;
}
}
return null;
} }
|
public class class_name {
private Token tryAndMatchOnLine(Token.Kind kind) {
int next = skipLineSpace(index);
if (next < tokens.size()) {
Token t = tokens.get(next);
if (t.kind == kind) {
index = next + 1; // depends on control dependency: [if], data = [none]
return t; // depends on control dependency: [if], data = [none]
}
}
return null;
} }
|
public class class_name {
public static int whichMax(double[] x) {
double m = Double.NEGATIVE_INFINITY;
int which = 0;
for (int i = 0; i < x.length; i++) {
if (x[i] > m) {
m = x[i];
which = i;
}
}
return which;
} }
|
public class class_name {
public static int whichMax(double[] x) {
double m = Double.NEGATIVE_INFINITY;
int which = 0;
for (int i = 0; i < x.length; i++) {
if (x[i] > m) {
m = x[i]; // depends on control dependency: [if], data = [none]
which = i; // depends on control dependency: [if], data = [none]
}
}
return which;
} }
|
public class class_name {
public void marshall(DeleteImagePermissionsRequest deleteImagePermissionsRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteImagePermissionsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteImagePermissionsRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(deleteImagePermissionsRequest.getSharedAccountId(), SHAREDACCOUNTID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(DeleteImagePermissionsRequest deleteImagePermissionsRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteImagePermissionsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteImagePermissionsRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deleteImagePermissionsRequest.getSharedAccountId(), SHAREDACCOUNTID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static Problem readProblem(File file, double bias) throws IOException, InvalidInputDataException {
BufferedReader fp = new BufferedReader(new FileReader(file));
List<Double> vy = new ArrayList<Double>();
List<Feature[]> vx = new ArrayList<Feature[]>();
int max_index = 0;
int lineNr = 0;
try {
while (true) {
String line = fp.readLine();
if (line == null) break;
lineNr++;
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
String token;
try {
token = st.nextToken();
} catch (NoSuchElementException e) {
throw new InvalidInputDataException("empty line", file, lineNr, e);
}
try {
vy.add(atof(token));
} catch (NumberFormatException e) {
throw new InvalidInputDataException("invalid label: " + token, file, lineNr, e);
}
int m = st.countTokens() / 2;
Feature[] x;
if (bias >= 0) {
x = new Feature[m + 1];
} else {
x = new Feature[m];
}
int indexBefore = 0;
for (int j = 0; j < m; j++) {
token = st.nextToken();
int index;
try {
index = atoi(token);
} catch (NumberFormatException e) {
throw new InvalidInputDataException("invalid index: " + token, file, lineNr, e);
}
// assert that indices are valid and sorted
if (index < 0) throw new InvalidInputDataException("invalid index: " + index, file, lineNr);
if (index <= indexBefore) throw new InvalidInputDataException("indices must be sorted in ascending order", file, lineNr);
indexBefore = index;
token = st.nextToken();
try {
double value = atof(token);
x[j] = new FeatureNode(index, value);
} catch (NumberFormatException e) {
throw new InvalidInputDataException("invalid value: " + token, file, lineNr);
}
}
if (m > 0) {
max_index = Math.max(max_index, x[m - 1].getIndex());
}
vx.add(x);
}
return constructProblem(vy, vx, max_index, bias);
}
finally {
fp.close();
}
} }
|
public class class_name {
public static Problem readProblem(File file, double bias) throws IOException, InvalidInputDataException {
BufferedReader fp = new BufferedReader(new FileReader(file));
List<Double> vy = new ArrayList<Double>();
List<Feature[]> vx = new ArrayList<Feature[]>();
int max_index = 0;
int lineNr = 0;
try {
while (true) {
String line = fp.readLine();
if (line == null) break;
lineNr++; // depends on control dependency: [while], data = [none]
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
String token;
try {
token = st.nextToken(); // depends on control dependency: [try], data = [none]
} catch (NoSuchElementException e) {
throw new InvalidInputDataException("empty line", file, lineNr, e);
} // depends on control dependency: [catch], data = [none]
try {
vy.add(atof(token)); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
throw new InvalidInputDataException("invalid label: " + token, file, lineNr, e);
} // depends on control dependency: [catch], data = [none]
int m = st.countTokens() / 2;
Feature[] x;
if (bias >= 0) {
x = new Feature[m + 1]; // depends on control dependency: [if], data = [none]
} else {
x = new Feature[m]; // depends on control dependency: [if], data = [none]
}
int indexBefore = 0;
for (int j = 0; j < m; j++) {
token = st.nextToken(); // depends on control dependency: [for], data = [none]
int index;
try {
index = atoi(token); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
throw new InvalidInputDataException("invalid index: " + token, file, lineNr, e);
} // depends on control dependency: [catch], data = [none]
// assert that indices are valid and sorted
if (index < 0) throw new InvalidInputDataException("invalid index: " + index, file, lineNr);
if (index <= indexBefore) throw new InvalidInputDataException("indices must be sorted in ascending order", file, lineNr);
indexBefore = index; // depends on control dependency: [for], data = [none]
token = st.nextToken(); // depends on control dependency: [for], data = [none]
try {
double value = atof(token);
x[j] = new FeatureNode(index, value); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
throw new InvalidInputDataException("invalid value: " + token, file, lineNr);
} // depends on control dependency: [catch], data = [none]
}
if (m > 0) {
max_index = Math.max(max_index, x[m - 1].getIndex()); // depends on control dependency: [if], data = [(m]
}
vx.add(x); // depends on control dependency: [while], data = [none]
}
return constructProblem(vy, vx, max_index, bias);
}
finally {
fp.close();
}
} }
|
public class class_name {
@Override
public void createCallableStatement(String sql) {
if (!endpointConfiguration.isAutoCreateStatement()) {
handleMessageAndCheckResponse(JdbcMessage.createCallableStatement(sql));
}
} }
|
public class class_name {
@Override
public void createCallableStatement(String sql) {
if (!endpointConfiguration.isAutoCreateStatement()) {
handleMessageAndCheckResponse(JdbcMessage.createCallableStatement(sql)); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public Filter convert(Criterion criterionDto, List<AttributeDescriptor> schema) {
FilterContext fc = new FilterContext();
fc.setSchema(schema);
criterionDto.accept(this, fc);
try {
log.debug("Filter converted : " + ECQL.toCQL(fc.getFilter()));
} catch (Exception e) {
// ignore
}
return fc.getFilter();
} }
|
public class class_name {
public Filter convert(Criterion criterionDto, List<AttributeDescriptor> schema) {
FilterContext fc = new FilterContext();
fc.setSchema(schema);
criterionDto.accept(this, fc);
try {
log.debug("Filter converted : " + ECQL.toCQL(fc.getFilter())); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// ignore
} // depends on control dependency: [catch], data = [none]
return fc.getFilter();
} }
|
public class class_name {
public void setErrors(java.util.Collection<TableVersionError> errors) {
if (errors == null) {
this.errors = null;
return;
}
this.errors = new java.util.ArrayList<TableVersionError>(errors);
} }
|
public class class_name {
public void setErrors(java.util.Collection<TableVersionError> errors) {
if (errors == null) {
this.errors = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.errors = new java.util.ArrayList<TableVersionError>(errors);
} }
|
public class class_name {
public static boolean handleAction(String strAction, Container target, Component source, int iOptions)
{
// First see if I can handle this action
if (target instanceof JBasePanel)
{ // This is a panel, handle the action.
if (((JBasePanel)target).doAction(strAction, iOptions))
return true;
}
else if (target instanceof BaseApplet)
{ // This is a applet, handle the action.
if (((BaseApplet)target).doAction(strAction, iOptions))
return true;
}
// Next, see if my children can handle this action
for (int iIndex = 0; iIndex < target.getComponentCount(); iIndex++)
{
Component component = target.getComponent(iIndex);
if (component != source)
{
if (component instanceof JBasePanel)
{ // This is a panel, handle the action.
if (((JBasePanel)component).handleAction(strAction, target, iOptions)) // and make sure this method is not called again for this object
return true;
}
else if (component instanceof Container)
{ // Call this for all the sub-panels for this parent
if (BaseApplet.handleAction(strAction, (Container)component, target, iOptions)) // Continue down thru the tree
return true;
}
}
}
// Last, see if my parents can handle this action
Container parent = target.getParent();
if (parent != source)
{
if (parent instanceof JBasePanel)
{
return ((JBasePanel)parent).handleAction(strAction, target, iOptions); // Continue up the chain.
}
else if (parent != null)
{
return BaseApplet.handleAction(strAction, parent, target, iOptions); // and make sure this method is not called again for this object
}
}
return false;
} }
|
public class class_name {
public static boolean handleAction(String strAction, Container target, Component source, int iOptions)
{
// First see if I can handle this action
if (target instanceof JBasePanel)
{ // This is a panel, handle the action.
if (((JBasePanel)target).doAction(strAction, iOptions))
return true;
}
else if (target instanceof BaseApplet)
{ // This is a applet, handle the action.
if (((BaseApplet)target).doAction(strAction, iOptions))
return true;
}
// Next, see if my children can handle this action
for (int iIndex = 0; iIndex < target.getComponentCount(); iIndex++)
{
Component component = target.getComponent(iIndex);
if (component != source)
{
if (component instanceof JBasePanel)
{ // This is a panel, handle the action.
if (((JBasePanel)component).handleAction(strAction, target, iOptions)) // and make sure this method is not called again for this object
return true;
}
else if (component instanceof Container)
{ // Call this for all the sub-panels for this parent
if (BaseApplet.handleAction(strAction, (Container)component, target, iOptions)) // Continue down thru the tree
return true;
}
}
}
// Last, see if my parents can handle this action
Container parent = target.getParent();
if (parent != source)
{
if (parent instanceof JBasePanel)
{
return ((JBasePanel)parent).handleAction(strAction, target, iOptions); // Continue up the chain. // depends on control dependency: [if], data = [none]
}
else if (parent != null)
{
return BaseApplet.handleAction(strAction, parent, target, iOptions); // and make sure this method is not called again for this object // depends on control dependency: [if], data = [none]
}
}
return false;
} }
|
public class class_name {
public List<T> nextCombinationAsList(List<T> destination)
{
generateNextCombinationIndices();
// Generate actual combination.
destination.clear();
for (int i : combinationIndices)
{
destination.add(elements[i]);
}
return destination;
} }
|
public class class_name {
public List<T> nextCombinationAsList(List<T> destination)
{
generateNextCombinationIndices();
// Generate actual combination.
destination.clear();
for (int i : combinationIndices)
{
destination.add(elements[i]); // depends on control dependency: [for], data = [i]
}
return destination;
} }
|
public class class_name {
@SuppressWarnings("unused") // Public API
public void removePositionUpdateListener(@NonNull PositionUpdateListener listener) {
listeners.remove(listener);
if (isReady()) {
getToView().getPositionAnimator().removePositionUpdateListener(listener);
}
} }
|
public class class_name {
@SuppressWarnings("unused") // Public API
public void removePositionUpdateListener(@NonNull PositionUpdateListener listener) {
listeners.remove(listener);
if (isReady()) {
getToView().getPositionAnimator().removePositionUpdateListener(listener); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static int[] RGBtoHSV (float r, float g, float b) {
float h, s, v;
float min, max, delta;
min = Math.min(Math.min(r, g), b);
max = Math.max(Math.max(r, g), b);
v = max;
delta = max - min;
if (max != 0)
s = delta / max;
else {
s = 0;
h = 0;
return new int[]{MathUtils.round(h), MathUtils.round(s), MathUtils.round(v)};
}
if (delta == 0)
h = 0;
else {
if (r == max)
h = (g - b) / delta;
else if (g == max)
h = 2 + (b - r) / delta;
else
h = 4 + (r - g) / delta;
}
h *= 60;
if (h < 0)
h += 360;
s *= 100;
v *= 100;
return new int[]{MathUtils.round(h), MathUtils.round(s), MathUtils.round(v)};
} }
|
public class class_name {
public static int[] RGBtoHSV (float r, float g, float b) {
float h, s, v;
float min, max, delta;
min = Math.min(Math.min(r, g), b);
max = Math.max(Math.max(r, g), b);
v = max;
delta = max - min;
if (max != 0)
s = delta / max;
else {
s = 0; // depends on control dependency: [if], data = [none]
h = 0; // depends on control dependency: [if], data = [none]
return new int[]{MathUtils.round(h), MathUtils.round(s), MathUtils.round(v)}; // depends on control dependency: [if], data = [none]
}
if (delta == 0)
h = 0;
else {
if (r == max)
h = (g - b) / delta;
else if (g == max)
h = 2 + (b - r) / delta;
else
h = 4 + (r - g) / delta;
}
h *= 60;
if (h < 0)
h += 360;
s *= 100;
v *= 100;
return new int[]{MathUtils.round(h), MathUtils.round(s), MathUtils.round(v)};
} }
|
public class class_name {
public static String getDefaultValueForType( JType type ) {
JPrimitiveType primitiveType = type.isPrimitive();
if ( null != primitiveType ) {
return primitiveType.getUninitializedFieldExpression();
}
return "null";
} }
|
public class class_name {
public static String getDefaultValueForType( JType type ) {
JPrimitiveType primitiveType = type.isPrimitive();
if ( null != primitiveType ) {
return primitiveType.getUninitializedFieldExpression(); // depends on control dependency: [if], data = [none]
}
return "null";
} }
|
public class class_name {
public Map<String, String> split(final CharSequence source) {
java.util.Objects.requireNonNull(source, "source");
Map<String, String> parameters = new HashMap<>();
Iterator<String> i = new StringIterator(source, pairSeparator);
while (i.hasNext()) {
String keyValue = i.next();
int keyValueSeparatorPosition = keyValueSeparatorStart(keyValue);
if (keyValueSeparatorPosition == 0 || keyValue.length() == 0) {
continue;
}
if (keyValueSeparatorPosition < 0) {
parameters.put(keyValue, null);
continue;
}
int keyStart = 0;
int keyEnd = keyValueSeparatorPosition;
while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyStart))) {
keyStart++;
}
while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyEnd - 1))) {
keyEnd--;
}
int valueStart = keyValueSeparatorPosition + keyValueSeparator.length();
int valueEnd = keyValue.length();
while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueStart))) {
valueStart++;
}
while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueEnd - 1))) {
valueEnd--;
}
String key = keyValue.substring(keyStart, keyEnd);
String value = keyValue.substring(valueStart, valueEnd);
parameters.put(key, value);
}
return parameters;
} }
|
public class class_name {
public Map<String, String> split(final CharSequence source) {
java.util.Objects.requireNonNull(source, "source");
Map<String, String> parameters = new HashMap<>();
Iterator<String> i = new StringIterator(source, pairSeparator);
while (i.hasNext()) {
String keyValue = i.next();
int keyValueSeparatorPosition = keyValueSeparatorStart(keyValue);
if (keyValueSeparatorPosition == 0 || keyValue.length() == 0) {
continue;
}
if (keyValueSeparatorPosition < 0) {
parameters.put(keyValue, null); // depends on control dependency: [if], data = [none]
continue;
}
int keyStart = 0;
int keyEnd = keyValueSeparatorPosition;
while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyStart))) {
keyStart++; // depends on control dependency: [while], data = [none]
}
while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyEnd - 1))) {
keyEnd--; // depends on control dependency: [while], data = [none]
}
int valueStart = keyValueSeparatorPosition + keyValueSeparator.length();
int valueEnd = keyValue.length();
while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueStart))) {
valueStart++; // depends on control dependency: [while], data = [none]
}
while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueEnd - 1))) {
valueEnd--; // depends on control dependency: [while], data = [none]
}
String key = keyValue.substring(keyStart, keyEnd);
String value = keyValue.substring(valueStart, valueEnd);
parameters.put(key, value); // depends on control dependency: [while], data = [none]
}
return parameters;
} }
|
public class class_name {
static InputStream getCachedImageStream(URI url, Context context) {
InputStream imageStream = null;
if (url != null) {
if (isCDNURL(url)) {
try {
FileLruCache cache = getCache(context);
imageStream = cache.get(url.toString());
} catch (IOException e) {
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, e.toString());
}
}
}
return imageStream;
} }
|
public class class_name {
static InputStream getCachedImageStream(URI url, Context context) {
InputStream imageStream = null;
if (url != null) {
if (isCDNURL(url)) {
try {
FileLruCache cache = getCache(context);
imageStream = cache.get(url.toString()); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, e.toString());
} // depends on control dependency: [catch], data = [none]
}
}
return imageStream;
} }
|
public class class_name {
public static String format(String pattern, Object... arguments) {
String msg = pattern;
if (arguments != null) {
for (int index = 0; index < arguments.length; index++) {
msg = msg.replaceAll("\\{" + (index + 1) + "\\}", String.valueOf(arguments[index]));
}
}
return msg;
} }
|
public class class_name {
public static String format(String pattern, Object... arguments) {
String msg = pattern;
if (arguments != null) {
for (int index = 0; index < arguments.length; index++) {
msg = msg.replaceAll("\\{" + (index + 1) + "\\}", String.valueOf(arguments[index])); // depends on control dependency: [for], data = [index]
}
}
return msg;
} }
|
public class class_name {
protected void printHeaders(final StringBuilder sb,
final long id,
final String prefix,
final MultivaluedMap<String, String> headers) {
getSortedHeaders(headers.entrySet()).forEach(h -> {
final List<?> values = h.getValue();
final String header = h.getKey();
final boolean isMaskedHeader = maskedHeaderNames.contains(header.toLowerCase());
if (values.size() == 1) {
String value = (isMaskedHeader ? "********" : values.get(0).toString());
appendId(sb, id).append(prefix).append(header).append(": ").append(value).append('\n');
} else {
final StringBuilder headerBuf = new StringBuilder();
for (final Object value : values) {
if (headerBuf.length() == 0) {
headerBuf.append(", ");
}
headerBuf.append(isMaskedHeader ? "********" : value.toString());
}
appendId(sb, id).append(prefix).append(header).append(": ").append(headerBuf.toString()).append('\n');
}
});
} }
|
public class class_name {
protected void printHeaders(final StringBuilder sb,
final long id,
final String prefix,
final MultivaluedMap<String, String> headers) {
getSortedHeaders(headers.entrySet()).forEach(h -> {
final List<?> values = h.getValue();
final String header = h.getKey();
final boolean isMaskedHeader = maskedHeaderNames.contains(header.toLowerCase());
if (values.size() == 1) {
String value = (isMaskedHeader ? "********" : values.get(0).toString());
appendId(sb, id).append(prefix).append(header).append(": ").append(value).append('\n');
// depends on control dependency: [if], data = [none]
} else {
final StringBuilder headerBuf = new StringBuilder();
for (final Object value : values) {
if (headerBuf.length() == 0) {
headerBuf.append(", ");
// depends on control dependency: [if], data = [none]
}
headerBuf.append(isMaskedHeader ? "********" : value.toString());
// depends on control dependency: [for], data = [value]
}
appendId(sb, id).append(prefix).append(header).append(": ").append(headerBuf.toString()).append('\n');
// depends on control dependency: [if], data = [none]
}
});
} }
|
public class class_name {
public static String simpleObjectName(Object object) {
if (object == null) {
return "<null>";
}
StringBuilder builder = new StringBuilder();
builder.append(simpleClassName(object.getClass()))
.append('#')
.append(objectId(object));
return builder.toString();
} }
|
public class class_name {
public static String simpleObjectName(Object object) {
if (object == null) {
return "<null>"; // depends on control dependency: [if], data = [none]
}
StringBuilder builder = new StringBuilder();
builder.append(simpleClassName(object.getClass()))
.append('#')
.append(objectId(object));
return builder.toString();
} }
|
public class class_name {
public Enumeration getValues(String name,final String separators)
{
final Enumeration e = getValues(name);
if (e==null)
return null;
return new Enumeration()
{
QuotedStringTokenizer tok=null;
public boolean hasMoreElements()
{
if (tok!=null && tok.hasMoreElements())
return true;
while (e.hasMoreElements())
{
String value=(String)e.nextElement();
tok=new QuotedStringTokenizer(value,separators,false,false);
if (tok.hasMoreElements())
return true;
}
tok=null;
return false;
}
public Object nextElement()
throws NoSuchElementException
{
if (!hasMoreElements())
throw new NoSuchElementException();
String next=(String) tok.nextElement();
if (next!=null)next=next.trim();
return next;
}
};
} }
|
public class class_name {
public Enumeration getValues(String name,final String separators)
{
final Enumeration e = getValues(name);
if (e==null)
return null;
return new Enumeration()
{
QuotedStringTokenizer tok=null;
public boolean hasMoreElements()
{
if (tok!=null && tok.hasMoreElements())
return true;
while (e.hasMoreElements())
{
String value=(String)e.nextElement();
tok=new QuotedStringTokenizer(value,separators,false,false); // depends on control dependency: [while], data = [none]
if (tok.hasMoreElements())
return true;
}
tok=null;
return false;
}
public Object nextElement()
throws NoSuchElementException
{
if (!hasMoreElements())
throw new NoSuchElementException();
String next=(String) tok.nextElement();
if (next!=null)next=next.trim();
return next;
}
};
} }
|
public class class_name {
public void setSchedules(java.util.Collection<Schedule> schedules) {
if (schedules == null) {
this.schedules = null;
return;
}
this.schedules = new java.util.ArrayList<Schedule>(schedules);
} }
|
public class class_name {
public void setSchedules(java.util.Collection<Schedule> schedules) {
if (schedules == null) {
this.schedules = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.schedules = new java.util.ArrayList<Schedule>(schedules);
} }
|
public class class_name {
public Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>> listMemberSchemasNextWithServiceResponseAsync(final String nextPageLink) {
return listMemberSchemasNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>, Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>> call(ServiceResponse<Page<SyncFullSchemaPropertiesInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listMemberSchemasNextWithServiceResponseAsync(nextPageLink));
}
});
} }
|
public class class_name {
public Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>> listMemberSchemasNextWithServiceResponseAsync(final String nextPageLink) {
return listMemberSchemasNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>, Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SyncFullSchemaPropertiesInner>>> call(ServiceResponse<Page<SyncFullSchemaPropertiesInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page); // depends on control dependency: [if], data = [none]
}
return Observable.just(page).concatWith(listMemberSchemasNextWithServiceResponseAsync(nextPageLink));
}
});
} }
|
public class class_name {
@POST
@Consumes("application/x.json-create-api-key")
public Response createApiKey(CreateEmoApiKeyRequest request, @QueryParam("key") String key,
@Authenticated Subject subject) {
if (key != null) {
request.setCustomRequestParameter("key", key);
}
CreateEmoApiKeyResponse response = _uac.createApiKey(subject, request);
return Response.created(URI.create(response.getId()))
.entity(response)
.build();
} }
|
public class class_name {
@POST
@Consumes("application/x.json-create-api-key")
public Response createApiKey(CreateEmoApiKeyRequest request, @QueryParam("key") String key,
@Authenticated Subject subject) {
if (key != null) {
request.setCustomRequestParameter("key", key); // depends on control dependency: [if], data = [none]
}
CreateEmoApiKeyResponse response = _uac.createApiKey(subject, request);
return Response.created(URI.create(response.getId()))
.entity(response)
.build();
} }
|
public class class_name {
public void dispose() {
LOGGER.debug("dispose all Filters for FilterFactory {}...", factory.getClass().getName());
synchronized (filterCache) {
if (maintainLifeCycle) {
Collection<Filter> values = filterCache.values();
for (Filter filter : values) {
try {
filter.destroy();
} catch (RuntimeException e) {
LOGGER.warn("RuntimeException while calling destroy() of filter {}", filter.getClass()
.getName(), e);
}
}
}
filterCache.clear();
}
} }
|
public class class_name {
public void dispose() {
LOGGER.debug("dispose all Filters for FilterFactory {}...", factory.getClass().getName());
synchronized (filterCache) {
if (maintainLifeCycle) {
Collection<Filter> values = filterCache.values();
for (Filter filter : values) {
try {
filter.destroy(); // depends on control dependency: [try], data = [none]
} catch (RuntimeException e) {
LOGGER.warn("RuntimeException while calling destroy() of filter {}", filter.getClass()
.getName(), e);
} // depends on control dependency: [catch], data = [none]
}
}
filterCache.clear();
}
} }
|
public class class_name {
static byte[] getCodecNameUTF8(String compressionCodecName) {
byte[] codecNameBytes = CODEC_NAME_CACHE.get(compressionCodecName);
if (codecNameBytes == null) {
try {
codecNameBytes = compressionCodecName.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
CODEC_NAME_CACHE.put(compressionCodecName, codecNameBytes);
}
return codecNameBytes;
} }
|
public class class_name {
static byte[] getCodecNameUTF8(String compressionCodecName) {
byte[] codecNameBytes = CODEC_NAME_CACHE.get(compressionCodecName);
if (codecNameBytes == null) {
try {
codecNameBytes = compressionCodecName.getBytes("UTF-8"); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
CODEC_NAME_CACHE.put(compressionCodecName, codecNameBytes); // depends on control dependency: [if], data = [none]
}
return codecNameBytes;
} }
|
public class class_name {
public CConfiguration read(Type type, String namespace) throws IOException {
String tableName = getTableName(namespace);
CConfiguration conf = null;
HTable table = null;
try {
table = new HTable(hbaseConf, tableName);
Get get = new Get(Bytes.toBytes(type.name()));
get.addFamily(FAMILY);
Result result = table.get(get);
int propertyCnt = 0;
if (result != null && !result.isEmpty()) {
conf = CConfiguration.create();
conf.clear();
Map<byte[], byte[]> kvs = result.getFamilyMap(FAMILY);
for (Map.Entry<byte[], byte[]> e : kvs.entrySet()) {
conf.set(Bytes.toString(e.getKey()), Bytes.toString(e.getValue()));
propertyCnt++;
}
}
LOG.info("Read " + propertyCnt + " properties from configuration table = " +
tableName + ", row = " + type.name());
} catch (TableNotFoundException e) {
// it's expected that this may occur when tables are created before Tigon has started
LOG.warn("Configuration table " + tableName + " does not yet exist.");
} finally {
if (table != null) {
try {
table.close();
} catch (IOException ioe) {
LOG.error("Error closing HTable for " + tableName, ioe);
}
}
}
return conf;
} }
|
public class class_name {
public CConfiguration read(Type type, String namespace) throws IOException {
String tableName = getTableName(namespace);
CConfiguration conf = null;
HTable table = null;
try {
table = new HTable(hbaseConf, tableName);
Get get = new Get(Bytes.toBytes(type.name()));
get.addFamily(FAMILY);
Result result = table.get(get);
int propertyCnt = 0;
if (result != null && !result.isEmpty()) {
conf = CConfiguration.create(); // depends on control dependency: [if], data = [none]
conf.clear(); // depends on control dependency: [if], data = [none]
Map<byte[], byte[]> kvs = result.getFamilyMap(FAMILY);
for (Map.Entry<byte[], byte[]> e : kvs.entrySet()) {
conf.set(Bytes.toString(e.getKey()), Bytes.toString(e.getValue())); // depends on control dependency: [for], data = [e]
propertyCnt++; // depends on control dependency: [for], data = [e]
}
}
LOG.info("Read " + propertyCnt + " properties from configuration table = " +
tableName + ", row = " + type.name());
} catch (TableNotFoundException e) {
// it's expected that this may occur when tables are created before Tigon has started
LOG.warn("Configuration table " + tableName + " does not yet exist.");
} finally {
if (table != null) {
try {
table.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
LOG.error("Error closing HTable for " + tableName, ioe);
} // depends on control dependency: [catch], data = [none]
}
}
return conf;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
private static void pinValueChangeCallback(int pin, double value) {
Vector<AnalogInputListener> listenersClone;
listenersClone = (Vector<AnalogInputListener>) listeners.clone();
for (int i = 0; i < listenersClone.size(); i++) {
AnalogInputListener listener = listenersClone.elementAt(i);
if(listener != null) {
AnalogInputEvent event = new AnalogInputEvent(listener, pin, value);
listener.pinValueChange(event);
}
}
} }
|
public class class_name {
@SuppressWarnings("unchecked")
private static void pinValueChangeCallback(int pin, double value) {
Vector<AnalogInputListener> listenersClone;
listenersClone = (Vector<AnalogInputListener>) listeners.clone();
for (int i = 0; i < listenersClone.size(); i++) {
AnalogInputListener listener = listenersClone.elementAt(i);
if(listener != null) {
AnalogInputEvent event = new AnalogInputEvent(listener, pin, value);
listener.pinValueChange(event); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@Override
public boolean validate(final Problems problems, final String compName, final String model) {
try {
Integer.parseInt(model);
} catch (final NumberFormatException e) {
problems.add(ValidationBundle.getMessage(IsAnIntegerValidator.class, "ERR_NOT_INTEGER", model)); // NOI18N
return false;
}
return true;
} }
|
public class class_name {
@Override
public boolean validate(final Problems problems, final String compName, final String model) {
try {
Integer.parseInt(model); // depends on control dependency: [try], data = [none]
} catch (final NumberFormatException e) {
problems.add(ValidationBundle.getMessage(IsAnIntegerValidator.class, "ERR_NOT_INTEGER", model)); // NOI18N
return false;
} // depends on control dependency: [catch], data = [none]
return true;
} }
|
public class class_name {
@Override
public BufferedImage drawUnindexedTile(int tileWidth, int tileHeight,
long totalFeatureCount, FeatureResultSet allFeatureResults) {
BufferedImage image = null;
if (drawUnindexedTiles) {
// Draw a tile indicating we have no idea if there are features
// inside.
// The table is not indexed and more features exist than the max
// feature count set.
image = drawTile(tileWidth, tileHeight, "?");
}
return image;
} }
|
public class class_name {
@Override
public BufferedImage drawUnindexedTile(int tileWidth, int tileHeight,
long totalFeatureCount, FeatureResultSet allFeatureResults) {
BufferedImage image = null;
if (drawUnindexedTiles) {
// Draw a tile indicating we have no idea if there are features
// inside.
// The table is not indexed and more features exist than the max
// feature count set.
image = drawTile(tileWidth, tileHeight, "?"); // depends on control dependency: [if], data = [none]
}
return image;
} }
|
public class class_name {
private void resetDefaultBorders() {
try {
// Etched Borders
Field highLightColor = EtchedBorder.class.getDeclaredField("highlight");
highLightColor.setAccessible(true);
Field shadowcolor = EtchedBorder.class.getDeclaredField("shadow");
shadowcolor.setAccessible(true);
Border etchedBorder = BorderFactory.createEtchedBorder();
highLightColor.set(etchedBorder, null);
shadowcolor.set(etchedBorder, null);
Border raisedEtchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
highLightColor.set(raisedEtchedBorder, null);
shadowcolor.set(raisedEtchedBorder, null);
// Bevel Borders
Field highlightOuter = BevelBorder.class.getDeclaredField("highlightOuter");
highlightOuter.setAccessible(true);
Field highlightInner = BevelBorder.class.getDeclaredField("highlightInner");
highlightInner.setAccessible(true);
Field shadowOuter = BevelBorder.class.getDeclaredField("shadowOuter");
shadowOuter.setAccessible(true);
Field shadowInner = BevelBorder.class.getDeclaredField("shadowInner");
shadowInner.setAccessible(true);
Border loweredBevelBorder = BorderFactory.createLoweredBevelBorder();
highlightOuter.set(loweredBevelBorder, null);
highlightInner.set(loweredBevelBorder, null);
shadowOuter.set(loweredBevelBorder, null);
shadowInner.set(loweredBevelBorder, null);
Border raisedBevelBorder = BorderFactory.createRaisedBevelBorder();
highlightOuter.set(raisedBevelBorder, null);
highlightInner.set(raisedBevelBorder, null);
shadowOuter.set(raisedBevelBorder, null);
shadowInner.set(raisedBevelBorder, null);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} }
|
public class class_name {
private void resetDefaultBorders() {
try {
// Etched Borders
Field highLightColor = EtchedBorder.class.getDeclaredField("highlight");
highLightColor.setAccessible(true); // depends on control dependency: [try], data = [none]
Field shadowcolor = EtchedBorder.class.getDeclaredField("shadow");
shadowcolor.setAccessible(true); // depends on control dependency: [try], data = [none]
Border etchedBorder = BorderFactory.createEtchedBorder();
highLightColor.set(etchedBorder, null); // depends on control dependency: [try], data = [none]
shadowcolor.set(etchedBorder, null); // depends on control dependency: [try], data = [none]
Border raisedEtchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
highLightColor.set(raisedEtchedBorder, null); // depends on control dependency: [try], data = [none]
shadowcolor.set(raisedEtchedBorder, null); // depends on control dependency: [try], data = [none]
// Bevel Borders
Field highlightOuter = BevelBorder.class.getDeclaredField("highlightOuter");
highlightOuter.setAccessible(true); // depends on control dependency: [try], data = [none]
Field highlightInner = BevelBorder.class.getDeclaredField("highlightInner");
highlightInner.setAccessible(true); // depends on control dependency: [try], data = [none]
Field shadowOuter = BevelBorder.class.getDeclaredField("shadowOuter");
shadowOuter.setAccessible(true); // depends on control dependency: [try], data = [none]
Field shadowInner = BevelBorder.class.getDeclaredField("shadowInner");
shadowInner.setAccessible(true); // depends on control dependency: [try], data = [none]
Border loweredBevelBorder = BorderFactory.createLoweredBevelBorder();
highlightOuter.set(loweredBevelBorder, null); // depends on control dependency: [try], data = [none]
highlightInner.set(loweredBevelBorder, null); // depends on control dependency: [try], data = [none]
shadowOuter.set(loweredBevelBorder, null); // depends on control dependency: [try], data = [none]
shadowInner.set(loweredBevelBorder, null); // depends on control dependency: [try], data = [none]
Border raisedBevelBorder = BorderFactory.createRaisedBevelBorder();
highlightOuter.set(raisedBevelBorder, null); // depends on control dependency: [try], data = [none]
highlightInner.set(raisedBevelBorder, null); // depends on control dependency: [try], data = [none]
shadowOuter.set(raisedBevelBorder, null); // depends on control dependency: [try], data = [none]
shadowInner.set(raisedBevelBorder, null); // depends on control dependency: [try], data = [none]
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) { // depends on control dependency: [catch], data = [none]
e.printStackTrace();
} catch (IllegalArgumentException e) { // depends on control dependency: [catch], data = [none]
e.printStackTrace();
} catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none]
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private boolean robustFitTrifocal(List<AssociatedTriple> associated) {
// Fit a trifocal tensor to the observations robustly
ransac.process(associated);
inliers = ransac.getMatchSet();
TrifocalTensor model = ransac.getModelParameters();
if( verbose != null )
verbose.println("Remaining after RANSAC "+inliers.size()+" / "+associated.size());
// estimate using all the inliers
// No need to re-scale the input because the estimator automatically adjusts the input on its own
if( !trifocalEstimator.process(inliers,model) ) {
if( verbose != null ) {
verbose.println("Trifocal estimator failed");
}
return false;
}
return true;
} }
|
public class class_name {
private boolean robustFitTrifocal(List<AssociatedTriple> associated) {
// Fit a trifocal tensor to the observations robustly
ransac.process(associated);
inliers = ransac.getMatchSet();
TrifocalTensor model = ransac.getModelParameters();
if( verbose != null )
verbose.println("Remaining after RANSAC "+inliers.size()+" / "+associated.size());
// estimate using all the inliers
// No need to re-scale the input because the estimator automatically adjusts the input on its own
if( !trifocalEstimator.process(inliers,model) ) {
if( verbose != null ) {
verbose.println("Trifocal estimator failed"); // depends on control dependency: [if], data = [none]
}
return false; // depends on control dependency: [if], data = [none]
}
return true;
} }
|
public class class_name {
public Label newLabelFromString(String labelStr) {
int first = labelStr.indexOf(divider);
int second = labelStr.lastIndexOf(divider);
if (first == second) {
return new WordLemmaTag(labelStr.substring(0, first), Morphology.stemStatic(labelStr.substring(0, first), labelStr.substring(first + 1)).word(), labelStr.substring(first + 1));
} else if (first >= 0) {
return new WordLemmaTag(labelStr.substring(0, first), labelStr.substring(first + 1, second), labelStr.substring(second + 1));
} else {
return new WordLemmaTag(labelStr);
}
} }
|
public class class_name {
public Label newLabelFromString(String labelStr) {
int first = labelStr.indexOf(divider);
int second = labelStr.lastIndexOf(divider);
if (first == second) {
return new WordLemmaTag(labelStr.substring(0, first), Morphology.stemStatic(labelStr.substring(0, first), labelStr.substring(first + 1)).word(), labelStr.substring(first + 1));
// depends on control dependency: [if], data = [(first]
} else if (first >= 0) {
return new WordLemmaTag(labelStr.substring(0, first), labelStr.substring(first + 1, second), labelStr.substring(second + 1));
// depends on control dependency: [if], data = [(first]
} else {
return new WordLemmaTag(labelStr);
// depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void configureForSubprocessGobbler(Props props, String logPattern) {
if (isAllLogsToConsoleEnabled(props)) {
LoggerContext ctx = getRootContext();
ctx.getLogger(ROOT_LOGGER_NAME).addAppender(newConsoleAppender(ctx, "root_console", logPattern));
}
} }
|
public class class_name {
public void configureForSubprocessGobbler(Props props, String logPattern) {
if (isAllLogsToConsoleEnabled(props)) {
LoggerContext ctx = getRootContext();
ctx.getLogger(ROOT_LOGGER_NAME).addAppender(newConsoleAppender(ctx, "root_console", logPattern)); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@Override
public Exception getLinkedException() {
//return (Exception) getCause();
Throwable t = getCause();
while (t != null) {
if (t instanceof Exception) {
return (Exception) t;
} else {
t = t.getCause();
}
}
return null;
} }
|
public class class_name {
@Override
public Exception getLinkedException() {
//return (Exception) getCause();
Throwable t = getCause();
while (t != null) {
if (t instanceof Exception) {
return (Exception) t; // depends on control dependency: [if], data = [none]
} else {
t = t.getCause(); // depends on control dependency: [if], data = [none]
}
}
return null;
} }
|
public class class_name {
public Filters withKeyUsage(String... keyUsage) {
if (this.keyUsage == null) {
setKeyUsage(new java.util.ArrayList<String>(keyUsage.length));
}
for (String ele : keyUsage) {
this.keyUsage.add(ele);
}
return this;
} }
|
public class class_name {
public Filters withKeyUsage(String... keyUsage) {
if (this.keyUsage == null) {
setKeyUsage(new java.util.ArrayList<String>(keyUsage.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : keyUsage) {
this.keyUsage.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} }
|
public class class_name {
public ConstraintValidatorFactory getConstraintValidatorFactoryOverride(Configuration<?> config) {
ValidationReleasable<ConstraintValidatorFactory> releasable = null;
String cvfClassName = config.getBootstrapConfiguration().getConstraintValidatorFactoryClassName();
// If the validation.xml ConstraintValidatorFactory is null AND the CDI feature is enabled
// we can try to create our own implementation of it.
if (cvfClassName == null && releasableFactory != null) {
releasable = releasableFactory.createConstraintValidatorFactory();
}
if (releasable != null) {
if (releasables == null) {
releasables = new LinkedList<ValidationReleasable<?>>();
}
releasables.add(releasable);
return releasable.getInstance();
}
return null;
} }
|
public class class_name {
public ConstraintValidatorFactory getConstraintValidatorFactoryOverride(Configuration<?> config) {
ValidationReleasable<ConstraintValidatorFactory> releasable = null;
String cvfClassName = config.getBootstrapConfiguration().getConstraintValidatorFactoryClassName();
// If the validation.xml ConstraintValidatorFactory is null AND the CDI feature is enabled
// we can try to create our own implementation of it.
if (cvfClassName == null && releasableFactory != null) {
releasable = releasableFactory.createConstraintValidatorFactory(); // depends on control dependency: [if], data = [none]
}
if (releasable != null) {
if (releasables == null) {
releasables = new LinkedList<ValidationReleasable<?>>(); // depends on control dependency: [if], data = [none]
}
releasables.add(releasable); // depends on control dependency: [if], data = [(releasable]
return releasable.getInstance(); // depends on control dependency: [if], data = [none]
}
return null;
} }
|
public class class_name {
private LocalThreadObjectPool getThreadLocalObjectPool() {
if (threadPoolSize <= 0) {
// no local thread pool needed.
return null;
}
LocalThreadObjectPool localPool = null;
if (threadLocals != null) {
localPool = threadLocals.get();
if (localPool == null) {
localPool = new LocalThreadObjectPool(threadPoolSize, null, destroyer); // @PK36998C
threadLocals.set(localPool);
localPool.setCleanUpOld(cleanUpOld);
}
}
return localPool;
} }
|
public class class_name {
private LocalThreadObjectPool getThreadLocalObjectPool() {
if (threadPoolSize <= 0) {
// no local thread pool needed.
return null; // depends on control dependency: [if], data = [none]
}
LocalThreadObjectPool localPool = null;
if (threadLocals != null) {
localPool = threadLocals.get(); // depends on control dependency: [if], data = [none]
if (localPool == null) {
localPool = new LocalThreadObjectPool(threadPoolSize, null, destroyer); // @PK36998C // depends on control dependency: [if], data = [none]
threadLocals.set(localPool); // depends on control dependency: [if], data = [(localPool]
localPool.setCleanUpOld(cleanUpOld); // depends on control dependency: [if], data = [none]
}
}
return localPool;
} }
|
public class class_name {
public static String getName(String pathAndName) {
int i = pathAndName.lastIndexOf('/');
int l = pathAndName.length();
if (i == -1) {
return pathAndName;
} else if (l == i) {
return "/";
} else {
return pathAndName.substring(i + 1);
}
} }
|
public class class_name {
public static String getName(String pathAndName) {
int i = pathAndName.lastIndexOf('/');
int l = pathAndName.length();
if (i == -1) {
return pathAndName; // depends on control dependency: [if], data = [none]
} else if (l == i) {
return "/"; // depends on control dependency: [if], data = [none]
} else {
return pathAndName.substring(i + 1); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static String checkPermitted(String sql)
{
/*
* IMPORTANT: Black-lists are checked first because they know more about
* what they don't like about a statement and can provide a better message.
* It requires that black-lists patterns be very selective and that they
* don't mind seeing statements that wouldn't pass the white-lists.
*/
//=== Check against blacklists, must not be rejected by any.
for (CheckedPattern cp : BLACKLISTS) {
CheckedPattern.Result result = cp.check(sql);
if (result.matcher != null) {
return String.format("%s, in statement: %s", result.explanation, sql);
}
}
//=== Check against whitelists, must be accepted by at least one.
boolean hadWLMatch = false;
for (CheckedPattern cp : WHITELISTS) {
if (cp.matches(sql)) {
hadWLMatch = true;
break;
}
}
if (!hadWLMatch) {
return String.format("AdHoc DDL contains an unsupported statement: %s", sql);
}
// The statement is permitted.
return null;
} }
|
public class class_name {
public static String checkPermitted(String sql)
{
/*
* IMPORTANT: Black-lists are checked first because they know more about
* what they don't like about a statement and can provide a better message.
* It requires that black-lists patterns be very selective and that they
* don't mind seeing statements that wouldn't pass the white-lists.
*/
//=== Check against blacklists, must not be rejected by any.
for (CheckedPattern cp : BLACKLISTS) {
CheckedPattern.Result result = cp.check(sql);
if (result.matcher != null) {
return String.format("%s, in statement: %s", result.explanation, sql); // depends on control dependency: [if], data = [none]
}
}
//=== Check against whitelists, must be accepted by at least one.
boolean hadWLMatch = false;
for (CheckedPattern cp : WHITELISTS) {
if (cp.matches(sql)) {
hadWLMatch = true; // depends on control dependency: [if], data = [none]
break;
}
}
if (!hadWLMatch) {
return String.format("AdHoc DDL contains an unsupported statement: %s", sql); // depends on control dependency: [if], data = [none]
}
// The statement is permitted.
return null;
} }
|
public class class_name {
public void init()
{
LOG.info("Scanning esjps for REST implementations");
try {
if (!Context.isThreadActive()) {
Context.begin(null, Context.Inheritance.Local);
Context.getThreadContext().setRequestAttribute(CONTEXTHINT, true);
}
registerClasses(new EsjpScanner().scan(Path.class, Provider.class));
} catch (final EFapsException e) {
LOG.error("Catched EFapsException", e);
}
registerClasses(Compile.class);
registerClasses(Update.class);
registerClasses(RestEQLInvoker.class);
registerClasses(RestContext.class);
registerClasses(Search.class);
registerClasses(ObjectMapperResolver.class);
if (EFapsResourceConfig.LOG.isInfoEnabled() && !getClasses().isEmpty()) {
final Set<Class<?>> rootResourceClasses = get(Path.class);
if (rootResourceClasses.isEmpty()) {
EFapsResourceConfig.LOG.info("No root resource classes found.");
} else {
logClasses("Root resource classes found:", rootResourceClasses);
}
final Set<Class<?>> providerClasses = get(Provider.class);
if (providerClasses.isEmpty()) {
EFapsResourceConfig.LOG.info("No provider classes found.");
} else {
logClasses("Provider classes found:", providerClasses);
}
}
this.cachedClasses.clear();
this.cachedClasses.addAll(getClasses());
} }
|
public class class_name {
public void init()
{
LOG.info("Scanning esjps for REST implementations");
try {
if (!Context.isThreadActive()) {
Context.begin(null, Context.Inheritance.Local); // depends on control dependency: [if], data = [none]
Context.getThreadContext().setRequestAttribute(CONTEXTHINT, true); // depends on control dependency: [if], data = [none]
}
registerClasses(new EsjpScanner().scan(Path.class, Provider.class)); // depends on control dependency: [try], data = [none]
} catch (final EFapsException e) {
LOG.error("Catched EFapsException", e);
} // depends on control dependency: [catch], data = [none]
registerClasses(Compile.class);
registerClasses(Update.class);
registerClasses(RestEQLInvoker.class);
registerClasses(RestContext.class);
registerClasses(Search.class);
registerClasses(ObjectMapperResolver.class);
if (EFapsResourceConfig.LOG.isInfoEnabled() && !getClasses().isEmpty()) {
final Set<Class<?>> rootResourceClasses = get(Path.class);
if (rootResourceClasses.isEmpty()) {
EFapsResourceConfig.LOG.info("No root resource classes found.");
} else {
logClasses("Root resource classes found:", rootResourceClasses);
}
final Set<Class<?>> providerClasses = get(Provider.class);
if (providerClasses.isEmpty()) {
EFapsResourceConfig.LOG.info("No provider classes found.");
} else {
logClasses("Provider classes found:", providerClasses);
}
}
this.cachedClasses.clear();
this.cachedClasses.addAll(getClasses());
} }
|
public class class_name {
@Override
public void redraw() {
if (!isDrawn()) {
draw();
} else {
try {
beforeLoad();
beforeDataSetLookup();
dataSetHandler.lookupDataSet(new DataSetReadyCallback() {
public void callback(DataSet result) {
try {
dataSet = result;
afterDataSetLookup(result);
updateVisualization();
// Redraw done
afterRedraw();
} catch (Exception e) {
// Give feedback on any initialization error
showError(new ClientRuntimeError(e));
}
}
public void notFound() {
String uuid = displayerSettings.getDataSetLookup().getDataSetUUID();
getView().errorDataSetNotFound(uuid);
handleError("Data set not found: " + uuid);
}
@Override
public boolean onError(final ClientRuntimeError error) {
showError(error);
return false;
}
});
} catch (Exception e) {
showError(new ClientRuntimeError(e));
}
}
} }
|
public class class_name {
@Override
public void redraw() {
if (!isDrawn()) {
draw(); // depends on control dependency: [if], data = [none]
} else {
try {
beforeLoad(); // depends on control dependency: [try], data = [none]
beforeDataSetLookup(); // depends on control dependency: [try], data = [none]
dataSetHandler.lookupDataSet(new DataSetReadyCallback() {
public void callback(DataSet result) {
try {
dataSet = result; // depends on control dependency: [try], data = [none]
afterDataSetLookup(result); // depends on control dependency: [try], data = [none]
updateVisualization(); // depends on control dependency: [try], data = [none]
// Redraw done
afterRedraw(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// Give feedback on any initialization error
showError(new ClientRuntimeError(e));
} // depends on control dependency: [catch], data = [none]
}
public void notFound() {
String uuid = displayerSettings.getDataSetLookup().getDataSetUUID();
getView().errorDataSetNotFound(uuid);
handleError("Data set not found: " + uuid);
}
@Override
public boolean onError(final ClientRuntimeError error) {
showError(error);
return false;
}
}); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
showError(new ClientRuntimeError(e));
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
private void ensureInitialized() {
if (!mInitialized) {
lock.lock();
try {
if (!mInitialized) {
mInternalPath = Environment.getDataDirectory();
mExternalPath = Environment.getExternalStorageDirectory();
updateStats();
mInitialized = true;
}
} finally {
lock.unlock();
}
}
} }
|
public class class_name {
private void ensureInitialized() {
if (!mInitialized) {
lock.lock(); // depends on control dependency: [if], data = [none]
try {
if (!mInitialized) {
mInternalPath = Environment.getDataDirectory(); // depends on control dependency: [if], data = [none]
mExternalPath = Environment.getExternalStorageDirectory(); // depends on control dependency: [if], data = [none]
updateStats(); // depends on control dependency: [if], data = [none]
mInitialized = true; // depends on control dependency: [if], data = [none]
}
} finally {
lock.unlock();
}
}
} }
|
public class class_name {
public String getEditURI() {
for (int i = 0; i < getOtherLinks().size(); i++) {
final Link link = getOtherLinks().get(i);
if (link.getRel() != null && link.getRel().equals("edit")) {
return link.getHrefResolved();
}
}
return null;
} }
|
public class class_name {
public String getEditURI() {
for (int i = 0; i < getOtherLinks().size(); i++) {
final Link link = getOtherLinks().get(i);
if (link.getRel() != null && link.getRel().equals("edit")) {
return link.getHrefResolved(); // depends on control dependency: [if], data = [none]
}
}
return null;
} }
|
public class class_name {
public static Long getLong(final LdapEntry entry, final String attribute, final Long nullValue) {
val v = getString(entry, attribute, nullValue.toString());
if (NumberUtils.isCreatable(v)) {
return Long.valueOf(v);
}
return nullValue;
} }
|
public class class_name {
public static Long getLong(final LdapEntry entry, final String attribute, final Long nullValue) {
val v = getString(entry, attribute, nullValue.toString());
if (NumberUtils.isCreatable(v)) {
return Long.valueOf(v); // depends on control dependency: [if], data = [none]
}
return nullValue;
} }
|
public class class_name {
private static void setIncomeBudgetPeriods(PHS398Checklist13 phsChecklist,
List<? extends BudgetProjectIncomeContract> projectIncomes) {
if (projectIncomes.isEmpty()) {
phsChecklist.setProgramIncome(YesNoDataType.N_NO);
} else {
phsChecklist.setProgramIncome(YesNoDataType.Y_YES);
}
phsChecklist.setIncomeBudgetPeriodArray(getIncomeBudgetPeriod(projectIncomes));
} }
|
public class class_name {
private static void setIncomeBudgetPeriods(PHS398Checklist13 phsChecklist,
List<? extends BudgetProjectIncomeContract> projectIncomes) {
if (projectIncomes.isEmpty()) {
phsChecklist.setProgramIncome(YesNoDataType.N_NO); // depends on control dependency: [if], data = [none]
} else {
phsChecklist.setProgramIncome(YesNoDataType.Y_YES); // depends on control dependency: [if], data = [none]
}
phsChecklist.setIncomeBudgetPeriodArray(getIncomeBudgetPeriod(projectIncomes));
} }
|
public class class_name {
public void marshall(DeleteResourceDefinitionRequest deleteResourceDefinitionRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteResourceDefinitionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteResourceDefinitionRequest.getResourceDefinitionId(), RESOURCEDEFINITIONID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(DeleteResourceDefinitionRequest deleteResourceDefinitionRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteResourceDefinitionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteResourceDefinitionRequest.getResourceDefinitionId(), RESOURCEDEFINITIONID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static SerializableException deserializeFromBuffer(ByteBuffer b) {
final int length = b.getInt();
if (length == 0) {
return null;
}
final int ordinal = b.get();
assert (ordinal != SerializableExceptions.None.ordinal());
return SerializableExceptions.values()[ordinal].deserializeException(b);
} }
|
public class class_name {
public static SerializableException deserializeFromBuffer(ByteBuffer b) {
final int length = b.getInt();
if (length == 0) {
return null; // depends on control dependency: [if], data = [none]
}
final int ordinal = b.get();
assert (ordinal != SerializableExceptions.None.ordinal());
return SerializableExceptions.values()[ordinal].deserializeException(b);
} }
|
public class class_name {
@Override
public Content getPackageHeader(String heading) {
HtmlTree bodyTree = getBody(true, getWindowTitle(utils.getPackageName(packageElement)));
HtmlTree htmlTree = (configuration.allowTag(HtmlTag.HEADER))
? HtmlTree.HEADER()
: bodyTree;
addTop(htmlTree);
addNavLinks(true, htmlTree);
if (configuration.allowTag(HtmlTag.HEADER)) {
bodyTree.addContent(htmlTree);
}
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.header);
if (configuration.showModules) {
ModuleElement mdle = configuration.docEnv.getElementUtils().getModuleOf(packageElement);
Content classModuleLabel = HtmlTree.SPAN(HtmlStyle.moduleLabelInPackage, contents.moduleLabel);
Content moduleNameDiv = HtmlTree.DIV(HtmlStyle.subTitle, classModuleLabel);
moduleNameDiv.addContent(Contents.SPACE);
moduleNameDiv.addContent(getModuleLink(mdle,
new StringContent(mdle.getQualifiedName().toString())));
div.addContent(moduleNameDiv);
}
Content annotationContent = new HtmlTree(HtmlTag.P);
addAnnotationInfo(packageElement, annotationContent);
div.addContent(annotationContent);
Content tHeading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, true,
HtmlStyle.title, contents.packageLabel);
tHeading.addContent(Contents.SPACE);
Content packageHead = new StringContent(heading);
tHeading.addContent(packageHead);
div.addContent(tHeading);
if (configuration.allowTag(HtmlTag.MAIN)) {
mainTree.addContent(div);
} else {
bodyTree.addContent(div);
}
return bodyTree;
} }
|
public class class_name {
@Override
public Content getPackageHeader(String heading) {
HtmlTree bodyTree = getBody(true, getWindowTitle(utils.getPackageName(packageElement)));
HtmlTree htmlTree = (configuration.allowTag(HtmlTag.HEADER))
? HtmlTree.HEADER()
: bodyTree;
addTop(htmlTree);
addNavLinks(true, htmlTree);
if (configuration.allowTag(HtmlTag.HEADER)) {
bodyTree.addContent(htmlTree); // depends on control dependency: [if], data = [none]
}
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.header);
if (configuration.showModules) {
ModuleElement mdle = configuration.docEnv.getElementUtils().getModuleOf(packageElement);
Content classModuleLabel = HtmlTree.SPAN(HtmlStyle.moduleLabelInPackage, contents.moduleLabel);
Content moduleNameDiv = HtmlTree.DIV(HtmlStyle.subTitle, classModuleLabel);
moduleNameDiv.addContent(Contents.SPACE); // depends on control dependency: [if], data = [none]
moduleNameDiv.addContent(getModuleLink(mdle,
new StringContent(mdle.getQualifiedName().toString()))); // depends on control dependency: [if], data = [none]
div.addContent(moduleNameDiv); // depends on control dependency: [if], data = [none]
}
Content annotationContent = new HtmlTree(HtmlTag.P);
addAnnotationInfo(packageElement, annotationContent);
div.addContent(annotationContent);
Content tHeading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, true,
HtmlStyle.title, contents.packageLabel);
tHeading.addContent(Contents.SPACE);
Content packageHead = new StringContent(heading);
tHeading.addContent(packageHead);
div.addContent(tHeading);
if (configuration.allowTag(HtmlTag.MAIN)) {
mainTree.addContent(div); // depends on control dependency: [if], data = [none]
} else {
bodyTree.addContent(div); // depends on control dependency: [if], data = [none]
}
return bodyTree;
} }
|
public class class_name {
private boolean htmlSentenceTerminatorFound(String str, int index) {
for (int i = 0; i < sentenceTerminators.length; i++) {
String terminator = sentenceTerminators[i];
if (str.regionMatches(true, index, terminator,
0, terminator.length())) {
return true;
}
}
return false;
} }
|
public class class_name {
private boolean htmlSentenceTerminatorFound(String str, int index) {
for (int i = 0; i < sentenceTerminators.length; i++) {
String terminator = sentenceTerminators[i];
if (str.regionMatches(true, index, terminator,
0, terminator.length())) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} }
|
public class class_name {
private List<ClassNameWrapper> getLocalClassNames (String packageName) {
if (packageName == null || packageName.equals("")) {
return Collections.emptyList();
}
String folder = packageName.replace('.', '/');
URL local = AddOnLoader.class.getClassLoader().getResource(folder);
if (local == null) {
return Collections.emptyList();
}
String jarFile = null;
if (local.getProtocol().equals("jar")) {
jarFile = local.toString().substring("jar:".length());
int pos = jarFile.indexOf("!");
jarFile = jarFile.substring(0, pos);
try {
// ZAP: Changed to take into account the package name
return getJarClassNames(this.getClass().getClassLoader(), new File(new URI(jarFile)), packageName);
} catch (URISyntaxException e) {
logger.error(e.getMessage(), e);
}
} else {
try {
// ZAP: Changed to pass a FileFilter (ClassRecurseDirFileFilter)
// and to pass the "packageName" with the dots already replaced.
return parseClassDir(this.getClass().getClassLoader(), new File(new URI(local.toString())),
packageName.replace('.', File.separatorChar),
new ClassRecurseDirFileFilter(true));
} catch (URISyntaxException e) {
logger.error(e.getMessage(), e);
}
}
return Collections.emptyList();
} }
|
public class class_name {
private List<ClassNameWrapper> getLocalClassNames (String packageName) {
if (packageName == null || packageName.equals("")) {
return Collections.emptyList();
// depends on control dependency: [if], data = [none]
}
String folder = packageName.replace('.', '/');
URL local = AddOnLoader.class.getClassLoader().getResource(folder);
if (local == null) {
return Collections.emptyList();
// depends on control dependency: [if], data = [none]
}
String jarFile = null;
if (local.getProtocol().equals("jar")) {
jarFile = local.toString().substring("jar:".length());
// depends on control dependency: [if], data = [none]
int pos = jarFile.indexOf("!");
jarFile = jarFile.substring(0, pos);
// depends on control dependency: [if], data = [none]
try {
// ZAP: Changed to take into account the package name
return getJarClassNames(this.getClass().getClassLoader(), new File(new URI(jarFile)), packageName);
// depends on control dependency: [try], data = [none]
} catch (URISyntaxException e) {
logger.error(e.getMessage(), e);
}
// depends on control dependency: [catch], data = [none]
} else {
try {
// ZAP: Changed to pass a FileFilter (ClassRecurseDirFileFilter)
// and to pass the "packageName" with the dots already replaced.
return parseClassDir(this.getClass().getClassLoader(), new File(new URI(local.toString())),
packageName.replace('.', File.separatorChar),
new ClassRecurseDirFileFilter(true));
// depends on control dependency: [try], data = [none]
} catch (URISyntaxException e) {
logger.error(e.getMessage(), e);
}
// depends on control dependency: [catch], data = [none]
}
return Collections.emptyList();
} }
|
public class class_name {
public void marshall(DescribePipelineRequest describePipelineRequest, ProtocolMarshaller protocolMarshaller) {
if (describePipelineRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describePipelineRequest.getPipelineName(), PIPELINENAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(DescribePipelineRequest describePipelineRequest, ProtocolMarshaller protocolMarshaller) {
if (describePipelineRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describePipelineRequest.getPipelineName(), PIPELINENAME_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 Map<String, StatsSnapshot> getStatsSnapshots(boolean isReceived) {
SortedMap<String, StatsSnapshot> map = Maps.newTreeMap(); // Sorted by method name.
if (isReceived) {
getStatsSnapshots(map, SERVER_RPC_CUMULATIVE_VIEWS);
getStatsSnapshots(map, SERVER_RPC_MINUTE_VIEWS);
getStatsSnapshots(map, SERVER_RPC_HOUR_VIEWS);
} else {
getStatsSnapshots(map, CLIENT_RPC_CUMULATIVE_VIEWS);
getStatsSnapshots(map, CLIENT_RPC_MINUTE_VIEWS);
getStatsSnapshots(map, CLIENT_RPC_HOUR_VIEWS);
}
return map;
} }
|
public class class_name {
private Map<String, StatsSnapshot> getStatsSnapshots(boolean isReceived) {
SortedMap<String, StatsSnapshot> map = Maps.newTreeMap(); // Sorted by method name.
if (isReceived) {
getStatsSnapshots(map, SERVER_RPC_CUMULATIVE_VIEWS); // depends on control dependency: [if], data = [none]
getStatsSnapshots(map, SERVER_RPC_MINUTE_VIEWS); // depends on control dependency: [if], data = [none]
getStatsSnapshots(map, SERVER_RPC_HOUR_VIEWS); // depends on control dependency: [if], data = [none]
} else {
getStatsSnapshots(map, CLIENT_RPC_CUMULATIVE_VIEWS); // depends on control dependency: [if], data = [none]
getStatsSnapshots(map, CLIENT_RPC_MINUTE_VIEWS); // depends on control dependency: [if], data = [none]
getStatsSnapshots(map, CLIENT_RPC_HOUR_VIEWS); // depends on control dependency: [if], data = [none]
}
return map;
} }
|
public class class_name {
private static boolean isClosest(long ts, long[] timeStamps, int curIdx) {
if (curIdx >= (timeStamps.length - 1)) {
// curIdx is the last one so it must be the closest
return true;
}
if (ts == timeStamps[curIdx]) {
return true;
}
return closer(ts, timeStamps[curIdx], timeStamps[curIdx + 1]);
} }
|
public class class_name {
private static boolean isClosest(long ts, long[] timeStamps, int curIdx) {
if (curIdx >= (timeStamps.length - 1)) {
// curIdx is the last one so it must be the closest
return true; // depends on control dependency: [if], data = [none]
}
if (ts == timeStamps[curIdx]) {
return true; // depends on control dependency: [if], data = [none]
}
return closer(ts, timeStamps[curIdx], timeStamps[curIdx + 1]);
} }
|
public class class_name {
private CmsUUID readOptionalUUID(JSONValue val) {
String id = readOptionalString(val);
if (null != id) {
try {
CmsUUID uuid = CmsUUID.valueOf(id);
return uuid;
} catch (@SuppressWarnings("unused") NumberFormatException e) {
// Do nothing, just return null
}
}
return null;
} }
|
public class class_name {
private CmsUUID readOptionalUUID(JSONValue val) {
String id = readOptionalString(val);
if (null != id) {
try {
CmsUUID uuid = CmsUUID.valueOf(id);
return uuid; // depends on control dependency: [try], data = [none]
} catch (@SuppressWarnings("unused") NumberFormatException e) {
// Do nothing, just return null
} // depends on control dependency: [catch], data = [none]
}
return null;
} }
|
public class class_name {
public final String getTags(final Priority priority) {
if (priority == Priority.HIGH) {
return high;
}
else if (priority == Priority.NORMAL) {
return normal;
}
else {
return low;
}
} }
|
public class class_name {
public final String getTags(final Priority priority) {
if (priority == Priority.HIGH) {
return high; // depends on control dependency: [if], data = [none]
}
else if (priority == Priority.NORMAL) {
return normal; // depends on control dependency: [if], data = [none]
}
else {
return low; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static byte[] stringToUid(final String uid, final short uid_length) {
if (uid == null || uid.isEmpty()) {
throw new IllegalArgumentException("UID was empty");
}
String id = uid;
if (uid_length > 0) {
while (id.length() < uid_length * 2) {
id = "0" + id;
}
} else {
if (id.length() % 2 > 0) {
id = "0" + id;
}
}
return DatatypeConverter.parseHexBinary(id);
} }
|
public class class_name {
public static byte[] stringToUid(final String uid, final short uid_length) {
if (uid == null || uid.isEmpty()) {
throw new IllegalArgumentException("UID was empty");
}
String id = uid;
if (uid_length > 0) {
while (id.length() < uid_length * 2) {
id = "0" + id; // depends on control dependency: [while], data = [none]
}
} else {
if (id.length() % 2 > 0) {
id = "0" + id; // depends on control dependency: [if], data = [none]
}
}
return DatatypeConverter.parseHexBinary(id);
} }
|
public class class_name {
public void marshall(CoreDefinitionVersion coreDefinitionVersion, ProtocolMarshaller protocolMarshaller) {
if (coreDefinitionVersion == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(coreDefinitionVersion.getCores(), CORES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(CoreDefinitionVersion coreDefinitionVersion, ProtocolMarshaller protocolMarshaller) {
if (coreDefinitionVersion == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(coreDefinitionVersion.getCores(), CORES_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
@Override
public Tuple getNext() throws IOException {
LzoW3CLogRecordReader w3CLogRecordReader = (LzoW3CLogRecordReader) reader;
if (w3CLogRecordReader == null) {
return null;
}
MapWritable value_;
try {
if (w3CLogRecordReader.nextKeyValue()
&& (value_ = w3CLogRecordReader.getCurrentValue()) != null) {
Map<String, String> values = Maps.newHashMap();
for (Writable key : value_.keySet()) {
Writable value = value_.get(key);
values.put(key.toString(), value != null ? value.toString() : null);
}
incrCounter(LzoW3CLogLoaderCounters.LinesW3CDecoded, 1L);
incrCounter(LzoW3CLogLoaderCounters.UnparseableLines,
w3CLogRecordReader.getBadRecordsSkipped());
return tupleFactory_.newTuple(values);
}
} catch (InterruptedException e) {
int errCode = 6018;
String errMsg = "Error while reading input";
throw new ExecException(errMsg, errCode,
PigException.REMOTE_ENVIRONMENT, e);
}
return null;
} }
|
public class class_name {
@Override
public Tuple getNext() throws IOException {
LzoW3CLogRecordReader w3CLogRecordReader = (LzoW3CLogRecordReader) reader;
if (w3CLogRecordReader == null) {
return null;
}
MapWritable value_;
try {
if (w3CLogRecordReader.nextKeyValue()
&& (value_ = w3CLogRecordReader.getCurrentValue()) != null) {
Map<String, String> values = Maps.newHashMap();
for (Writable key : value_.keySet()) {
Writable value = value_.get(key);
values.put(key.toString(), value != null ? value.toString() : null); // depends on control dependency: [for], data = [key]
}
incrCounter(LzoW3CLogLoaderCounters.LinesW3CDecoded, 1L);
incrCounter(LzoW3CLogLoaderCounters.UnparseableLines,
w3CLogRecordReader.getBadRecordsSkipped());
return tupleFactory_.newTuple(values);
}
} catch (InterruptedException e) {
int errCode = 6018;
String errMsg = "Error while reading input";
throw new ExecException(errMsg, errCode,
PigException.REMOTE_ENVIRONMENT, e);
}
return null;
} }
|
public class class_name {
private boolean isInDoNotEngageZone(final int x, final int y) {
for (final Rectangle zone : doNotEnganeZones) {
if (zone.contains(x, y)) {
return true;
}
}
return false;
} }
|
public class class_name {
private boolean isInDoNotEngageZone(final int x, final int y) {
for (final Rectangle zone : doNotEnganeZones) {
if (zone.contains(x, y)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} }
|
public class class_name {
public Path downloadIfNecessary(
String version, Log log, boolean requiresAppEngineComponents, boolean offline) {
ManagedCloudSdk managedCloudSdk = managedCloudSdkFactory.apply(version);
if (offline) { // in offline mode, don't download anything
return managedCloudSdk.getSdkHome();
}
try {
ProgressListener progressListener = new NoOpProgressListener();
ConsoleListener consoleListener = new CloudSdkDownloaderConsoleListener(log);
if (!managedCloudSdk.isInstalled()) {
managedCloudSdk.newInstaller().install(progressListener, consoleListener);
}
if (requiresAppEngineComponents
&& !managedCloudSdk.hasComponent(SdkComponent.APP_ENGINE_JAVA)) {
managedCloudSdk
.newComponentInstaller()
.installComponent(SdkComponent.APP_ENGINE_JAVA, progressListener, consoleListener);
}
if (!managedCloudSdk.isUpToDate()) {
managedCloudSdk.newUpdater().update(progressListener, consoleListener);
}
return managedCloudSdk.getSdkHome();
} catch (IOException
| SdkInstallerException
| ManagedSdkVersionMismatchException
| InterruptedException
| CommandExecutionException
| CommandExitException
| ManagedSdkVerificationException ex) {
throw new RuntimeException(ex);
}
} }
|
public class class_name {
public Path downloadIfNecessary(
String version, Log log, boolean requiresAppEngineComponents, boolean offline) {
ManagedCloudSdk managedCloudSdk = managedCloudSdkFactory.apply(version);
if (offline) { // in offline mode, don't download anything
return managedCloudSdk.getSdkHome(); // depends on control dependency: [if], data = [none]
}
try {
ProgressListener progressListener = new NoOpProgressListener();
ConsoleListener consoleListener = new CloudSdkDownloaderConsoleListener(log);
if (!managedCloudSdk.isInstalled()) {
managedCloudSdk.newInstaller().install(progressListener, consoleListener); // depends on control dependency: [if], data = [none]
}
if (requiresAppEngineComponents
&& !managedCloudSdk.hasComponent(SdkComponent.APP_ENGINE_JAVA)) {
managedCloudSdk
.newComponentInstaller()
.installComponent(SdkComponent.APP_ENGINE_JAVA, progressListener, consoleListener); // depends on control dependency: [if], data = [none]
}
if (!managedCloudSdk.isUpToDate()) {
managedCloudSdk.newUpdater().update(progressListener, consoleListener); // depends on control dependency: [if], data = [none]
}
return managedCloudSdk.getSdkHome(); // depends on control dependency: [try], data = [none]
} catch (IOException
| SdkInstallerException
| ManagedSdkVersionMismatchException
| InterruptedException
| CommandExecutionException
| CommandExitException
| ManagedSdkVerificationException ex) {
throw new RuntimeException(ex);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public void bindNamespaceUri(String prefix, String namespaceUri) {
Assert.notNull(prefix, "No prefix given");
Assert.notNull(namespaceUri, "No namespaceUri given");
if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) {
defaultNamespaceUri = namespaceUri;
} else {
prefixToNamespaceUri.put(prefix, namespaceUri);
getPrefixesInternal(namespaceUri).add(prefix);
}
} }
|
public class class_name {
public void bindNamespaceUri(String prefix, String namespaceUri) {
Assert.notNull(prefix, "No prefix given");
Assert.notNull(namespaceUri, "No namespaceUri given");
if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) {
defaultNamespaceUri = namespaceUri; // depends on control dependency: [if], data = [none]
} else {
prefixToNamespaceUri.put(prefix, namespaceUri); // depends on control dependency: [if], data = [none]
getPrefixesInternal(namespaceUri).add(prefix); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public String confusionToString() {
int nClasses = confusion().getClasses().size();
//First: work out the longest label size
int maxLabelSize = 0;
for (String s : labelsList) {
maxLabelSize = Math.max(maxLabelSize, s.length());
}
//Build the formatting for the rows:
int labelSize = Math.max(maxLabelSize + 5, 10);
StringBuilder sb = new StringBuilder();
sb.append("%-3d");
sb.append("%-");
sb.append(labelSize);
sb.append("s | ");
StringBuilder headerFormat = new StringBuilder();
headerFormat.append(" %-").append(labelSize).append("s ");
for (int i = 0; i < nClasses; i++) {
sb.append("%7d");
headerFormat.append("%7d");
}
String rowFormat = sb.toString();
StringBuilder out = new StringBuilder();
//First: header row
Object[] headerArgs = new Object[nClasses + 1];
headerArgs[0] = "Predicted:";
for (int i = 0; i < nClasses; i++)
headerArgs[i + 1] = i;
out.append(String.format(headerFormat.toString(), headerArgs)).append("\n");
//Second: divider rows
out.append(" Actual:\n");
//Finally: data rows
for (int i = 0; i < nClasses; i++) {
Object[] args = new Object[nClasses + 2];
args[0] = i;
args[1] = labelsList.get(i);
for (int j = 0; j < nClasses; j++) {
args[j + 2] = confusion().getCount(i, j);
}
out.append(String.format(rowFormat, args));
out.append("\n");
}
return out.toString();
} }
|
public class class_name {
public String confusionToString() {
int nClasses = confusion().getClasses().size();
//First: work out the longest label size
int maxLabelSize = 0;
for (String s : labelsList) {
maxLabelSize = Math.max(maxLabelSize, s.length()); // depends on control dependency: [for], data = [s]
}
//Build the formatting for the rows:
int labelSize = Math.max(maxLabelSize + 5, 10);
StringBuilder sb = new StringBuilder();
sb.append("%-3d");
sb.append("%-");
sb.append(labelSize);
sb.append("s | ");
StringBuilder headerFormat = new StringBuilder();
headerFormat.append(" %-").append(labelSize).append("s ");
for (int i = 0; i < nClasses; i++) {
sb.append("%7d"); // depends on control dependency: [for], data = [none]
headerFormat.append("%7d"); // depends on control dependency: [for], data = [none]
}
String rowFormat = sb.toString();
StringBuilder out = new StringBuilder();
//First: header row
Object[] headerArgs = new Object[nClasses + 1];
headerArgs[0] = "Predicted:";
for (int i = 0; i < nClasses; i++)
headerArgs[i + 1] = i;
out.append(String.format(headerFormat.toString(), headerArgs)).append("\n");
//Second: divider rows
out.append(" Actual:\n");
//Finally: data rows
for (int i = 0; i < nClasses; i++) {
Object[] args = new Object[nClasses + 2];
args[0] = i; // depends on control dependency: [for], data = [i]
args[1] = labelsList.get(i); // depends on control dependency: [for], data = [i]
for (int j = 0; j < nClasses; j++) {
args[j + 2] = confusion().getCount(i, j); // depends on control dependency: [for], data = [j]
}
out.append(String.format(rowFormat, args)); // depends on control dependency: [for], data = [none]
out.append("\n"); // depends on control dependency: [for], data = [none]
}
return out.toString();
} }
|
public class class_name {
@Override
public <Instance> boolean isInstance(Instance instance) {
if (instance instanceof CompositeObject) {
Object delegate = ((CompositeObject) instance).getDelegate();
return isDatastoreType(delegate);
}
return false;
} }
|
public class class_name {
@Override
public <Instance> boolean isInstance(Instance instance) {
if (instance instanceof CompositeObject) {
Object delegate = ((CompositeObject) instance).getDelegate();
return isDatastoreType(delegate); // depends on control dependency: [if], data = [none]
}
return false;
} }
|
public class class_name {
private void secureCookie(Cookie cookie, HttpServletRequest request){
// if we can mark the cookie HTTP only, do so to protect this cookie even in case of XSS vulnerability.
if (SET_HTTP_ONLY!=null) {
try {
SET_HTTP_ONLY.invoke(cookie,true);
} catch (IllegalAccessException | InvocationTargetException e) {
// ignore
}
}
// if the user is running Jenkins over HTTPS, we also want to prevent the cookie from leaking in HTTP.
// whether the login is done over HTTPS or not would be a good enough approximation of whether Jenkins runs in
// HTTPS or not, so use that.
cookie.setSecure(request.isSecure());
} }
|
public class class_name {
private void secureCookie(Cookie cookie, HttpServletRequest request){
// if we can mark the cookie HTTP only, do so to protect this cookie even in case of XSS vulnerability.
if (SET_HTTP_ONLY!=null) {
try {
SET_HTTP_ONLY.invoke(cookie,true); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException | InvocationTargetException e) {
// ignore
} // depends on control dependency: [catch], data = [none]
}
// if the user is running Jenkins over HTTPS, we also want to prevent the cookie from leaking in HTTP.
// whether the login is done over HTTPS or not would be a good enough approximation of whether Jenkins runs in
// HTTPS or not, so use that.
cookie.setSecure(request.isSecure());
} }
|
public class class_name {
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the PlacementService.
PlacementServiceInterface placementService =
adManagerServices.get(session, PlacementServiceInterface.class);
// Get all ad units.
List<AdUnit> adUnits = getAllAdUnits(adManagerServices, session);
// Partition ad units by their size.
Set<String> mediumSquareAdUnitIds = Sets.newHashSet();
Set<String> skyscraperAdUnitIds = Sets.newHashSet();
Set<String> bannerAdUnitIds = Sets.newHashSet();
for (AdUnit adUnit : adUnits) {
if (adUnit.getParentId() != null && adUnit.getAdUnitSizes() != null) {
for (AdUnitSize adUnitSize : adUnit.getAdUnitSizes()) {
Size size = adUnitSize.getSize();
if (size.getWidth() == 300 && size.getHeight() == 250) {
mediumSquareAdUnitIds.add(adUnit.getId());
} else if (size.getWidth() == 120 && size.getHeight() == 600) {
skyscraperAdUnitIds.add(adUnit.getId());
} else if (size.getWidth() == 468 && size.getHeight() == 60) {
bannerAdUnitIds.add(adUnit.getId());
}
}
}
}
List<Placement> placementsToCreate = new ArrayList<>();
// Only create placements with one or more ad unit.
if (!mediumSquareAdUnitIds.isEmpty()) {
// Create medium square placement.
Placement mediumSquareAdUnitPlacement = new Placement();
mediumSquareAdUnitPlacement.setName(
"Medium Square AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
mediumSquareAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 300x250");
mediumSquareAdUnitPlacement.setTargetedAdUnitIds(
mediumSquareAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(mediumSquareAdUnitPlacement);
}
if (!skyscraperAdUnitIds.isEmpty()) {
// Create skyscraper placement.
Placement skyscraperAdUnitPlacement = new Placement();
skyscraperAdUnitPlacement.setName(
"Skyscraper AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
skyscraperAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 120x600");
skyscraperAdUnitPlacement.setTargetedAdUnitIds(skyscraperAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(skyscraperAdUnitPlacement);
}
if (!bannerAdUnitIds.isEmpty()) {
// Create banner placement.
Placement bannerAdUnitPlacement = new Placement();
bannerAdUnitPlacement.setName(
"Banner AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
bannerAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 468x60");
bannerAdUnitPlacement.setTargetedAdUnitIds(bannerAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(bannerAdUnitPlacement);
}
if (!placementsToCreate.isEmpty()) {
// Create the placements on the server.
Placement[] placements =
placementService.createPlacements(placementsToCreate.toArray(new Placement[] {}));
for (Placement createdPlacement : placements) {
System.out.printf(
"A placement with ID %d, name '%s', and containing ad units [%s] was created.%n",
createdPlacement.getId(),
createdPlacement.getName(),
Joiner.on(", ").join(createdPlacement.getTargetedAdUnitIds()));
}
} else {
System.out.println("No placements were created.");
}
} }
|
public class class_name {
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the PlacementService.
PlacementServiceInterface placementService =
adManagerServices.get(session, PlacementServiceInterface.class);
// Get all ad units.
List<AdUnit> adUnits = getAllAdUnits(adManagerServices, session);
// Partition ad units by their size.
Set<String> mediumSquareAdUnitIds = Sets.newHashSet();
Set<String> skyscraperAdUnitIds = Sets.newHashSet();
Set<String> bannerAdUnitIds = Sets.newHashSet();
for (AdUnit adUnit : adUnits) {
if (adUnit.getParentId() != null && adUnit.getAdUnitSizes() != null) {
for (AdUnitSize adUnitSize : adUnit.getAdUnitSizes()) {
Size size = adUnitSize.getSize();
if (size.getWidth() == 300 && size.getHeight() == 250) {
mediumSquareAdUnitIds.add(adUnit.getId()); // depends on control dependency: [if], data = [none]
} else if (size.getWidth() == 120 && size.getHeight() == 600) {
skyscraperAdUnitIds.add(adUnit.getId()); // depends on control dependency: [if], data = [none]
} else if (size.getWidth() == 468 && size.getHeight() == 60) {
bannerAdUnitIds.add(adUnit.getId()); // depends on control dependency: [if], data = [none]
}
}
}
}
List<Placement> placementsToCreate = new ArrayList<>();
// Only create placements with one or more ad unit.
if (!mediumSquareAdUnitIds.isEmpty()) {
// Create medium square placement.
Placement mediumSquareAdUnitPlacement = new Placement();
mediumSquareAdUnitPlacement.setName(
"Medium Square AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
mediumSquareAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 300x250");
mediumSquareAdUnitPlacement.setTargetedAdUnitIds(
mediumSquareAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(mediumSquareAdUnitPlacement);
}
if (!skyscraperAdUnitIds.isEmpty()) {
// Create skyscraper placement.
Placement skyscraperAdUnitPlacement = new Placement();
skyscraperAdUnitPlacement.setName(
"Skyscraper AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
skyscraperAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 120x600");
skyscraperAdUnitPlacement.setTargetedAdUnitIds(skyscraperAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(skyscraperAdUnitPlacement);
}
if (!bannerAdUnitIds.isEmpty()) {
// Create banner placement.
Placement bannerAdUnitPlacement = new Placement();
bannerAdUnitPlacement.setName(
"Banner AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
bannerAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 468x60");
bannerAdUnitPlacement.setTargetedAdUnitIds(bannerAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(bannerAdUnitPlacement);
}
if (!placementsToCreate.isEmpty()) {
// Create the placements on the server.
Placement[] placements =
placementService.createPlacements(placementsToCreate.toArray(new Placement[] {}));
for (Placement createdPlacement : placements) {
System.out.printf(
"A placement with ID %d, name '%s', and containing ad units [%s] was created.%n",
createdPlacement.getId(),
createdPlacement.getName(),
Joiner.on(", ").join(createdPlacement.getTargetedAdUnitIds()));
}
} else {
System.out.println("No placements were created.");
}
} }
|
public class class_name {
public static void load(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
{
for (Object arg : args) {
String file = Context.toString(arg);
try {
Main.processFile(cx, thisObj, file);
} catch (IOException ioex) {
String msg = ToolErrorReporter.getMessage(
"msg.couldnt.read.source", file, ioex.getMessage());
throw Context.reportRuntimeError(msg);
} catch (VirtualMachineError ex) {
// Treat StackOverflow and OutOfMemory as runtime errors
ex.printStackTrace();
String msg = ToolErrorReporter.getMessage(
"msg.uncaughtJSException", ex.toString());
throw Context.reportRuntimeError(msg);
}
}
} }
|
public class class_name {
public static void load(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
{
for (Object arg : args) {
String file = Context.toString(arg);
try {
Main.processFile(cx, thisObj, file); // depends on control dependency: [try], data = [none]
} catch (IOException ioex) {
String msg = ToolErrorReporter.getMessage(
"msg.couldnt.read.source", file, ioex.getMessage());
throw Context.reportRuntimeError(msg);
} catch (VirtualMachineError ex) { // depends on control dependency: [catch], data = [none]
// Treat StackOverflow and OutOfMemory as runtime errors
ex.printStackTrace();
String msg = ToolErrorReporter.getMessage(
"msg.uncaughtJSException", ex.toString());
throw Context.reportRuntimeError(msg);
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
private void handleBatchUpdateException(
Collection<Record> failedRecords, SQLException e, List<OnRecordErrorException> errorRecords
) throws StageException {
if (jdbcUtil.isDataError(getCustomDataSqlStateCodes(), getConnectionString(), e)) {
String formattedError = JdbcErrors.JDBC_79.getMessage();
LOG.error(formattedError);
LOG.debug(formattedError, e);
if (!getRollbackOnError() && e instanceof BatchUpdateException &&
((BatchUpdateException) e).getUpdateCounts().length > 0) {
BatchUpdateException bue = (BatchUpdateException) e;
int i = 0;
for (Record record : failedRecords) {
if (i >= bue.getUpdateCounts().length || bue.getUpdateCounts()[i] == PreparedStatement.EXECUTE_FAILED) {
errorRecords.add(new OnRecordErrorException(
record,
JDBC_14,
e.getSQLState(),
e.getErrorCode(),
e.getMessage(),
jdbcUtil.formatSqlException(e),
e
));
}
i++;
}
} else {
for (Record record : failedRecords) {
errorRecords.add(new OnRecordErrorException(
record,
JDBC_14,
e.getSQLState(),
e.getErrorCode(),
e.getMessage(),
jdbcUtil.formatSqlException(e),
e
));
}
}
} else {
handleSqlException(e);
}
} }
|
public class class_name {
private void handleBatchUpdateException(
Collection<Record> failedRecords, SQLException e, List<OnRecordErrorException> errorRecords
) throws StageException {
if (jdbcUtil.isDataError(getCustomDataSqlStateCodes(), getConnectionString(), e)) {
String formattedError = JdbcErrors.JDBC_79.getMessage();
LOG.error(formattedError);
LOG.debug(formattedError, e);
if (!getRollbackOnError() && e instanceof BatchUpdateException &&
((BatchUpdateException) e).getUpdateCounts().length > 0) {
BatchUpdateException bue = (BatchUpdateException) e;
int i = 0;
for (Record record : failedRecords) {
if (i >= bue.getUpdateCounts().length || bue.getUpdateCounts()[i] == PreparedStatement.EXECUTE_FAILED) {
errorRecords.add(new OnRecordErrorException(
record,
JDBC_14,
e.getSQLState(),
e.getErrorCode(),
e.getMessage(),
jdbcUtil.formatSqlException(e),
e
)); // depends on control dependency: [if], data = [none]
}
i++; // depends on control dependency: [for], data = [none]
}
} else {
for (Record record : failedRecords) {
errorRecords.add(new OnRecordErrorException(
record,
JDBC_14,
e.getSQLState(),
e.getErrorCode(),
e.getMessage(),
jdbcUtil.formatSqlException(e),
e
)); // depends on control dependency: [for], data = [none]
}
}
} else {
handleSqlException(e);
}
} }
|
public class class_name {
public void applyPattern(String pattern) {
this.pattern = pattern;
if (msgPattern == null) {
msgPattern = new MessagePattern();
}
try {
msgPattern.parseSelectStyle(pattern);
} catch(RuntimeException e) {
reset();
throw e;
}
} }
|
public class class_name {
public void applyPattern(String pattern) {
this.pattern = pattern;
if (msgPattern == null) {
msgPattern = new MessagePattern(); // depends on control dependency: [if], data = [none]
}
try {
msgPattern.parseSelectStyle(pattern); // depends on control dependency: [try], data = [none]
} catch(RuntimeException e) {
reset();
throw e;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
protected void updatePacketListener() {
removeAsyncPacketListener();
LOGGER.fine("UpdatePacketListener");
packetListener = new StanzaListener() {
@Override
public void processStanza(Stanza packet) {
try {
receivePacketAndRespond((IQ) packet);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "exception", e);
}
}
};
packetFilter = new StanzaFilter() {
@Override
public boolean accept(Stanza packet) {
if (packet instanceof IQ) {
IQ iq = (IQ) packet;
Jid me = getConnection().getUser();
if (!iq.getTo().equals(me)) {
return false;
}
Jid other = getResponder().equals(me) ? getInitiator() : getResponder();
if (iq.getFrom() == null || !iq.getFrom().equals(other == null ? "" : other)) {
return false;
}
if (iq instanceof Jingle) {
Jingle jin = (Jingle) iq;
String sid = jin.getSid();
if (sid == null || !sid.equals(getSid())) {
LOGGER.fine("Ignored Jingle(SID) " + sid + "|" + getSid() + " :" + iq.toXML());
return false;
}
Jid ini = jin.getInitiator();
if (!ini.equals(getInitiator())) {
LOGGER.fine("Ignored Jingle(INI): " + iq.toXML());
return false;
}
} else {
// We accept some non-Jingle IQ packets: ERRORs and ACKs
if (iq.getType().equals(IQ.Type.set)) {
LOGGER.fine("Ignored Jingle(TYPE): " + iq.toXML());
return false;
} else if (iq.getType().equals(IQ.Type.get)) {
LOGGER.fine("Ignored Jingle(TYPE): " + iq.toXML());
return false;
}
}
return true;
}
return false;
}
};
getConnection().addAsyncStanzaListener(packetListener, packetFilter);
} }
|
public class class_name {
protected void updatePacketListener() {
removeAsyncPacketListener();
LOGGER.fine("UpdatePacketListener");
packetListener = new StanzaListener() {
@Override
public void processStanza(Stanza packet) {
try {
receivePacketAndRespond((IQ) packet); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOGGER.log(Level.WARNING, "exception", e);
} // depends on control dependency: [catch], data = [none]
}
};
packetFilter = new StanzaFilter() {
@Override
public boolean accept(Stanza packet) {
if (packet instanceof IQ) {
IQ iq = (IQ) packet;
Jid me = getConnection().getUser();
if (!iq.getTo().equals(me)) {
return false; // depends on control dependency: [if], data = [none]
}
Jid other = getResponder().equals(me) ? getInitiator() : getResponder();
if (iq.getFrom() == null || !iq.getFrom().equals(other == null ? "" : other)) {
return false; // depends on control dependency: [if], data = [none]
}
if (iq instanceof Jingle) {
Jingle jin = (Jingle) iq;
String sid = jin.getSid();
if (sid == null || !sid.equals(getSid())) {
LOGGER.fine("Ignored Jingle(SID) " + sid + "|" + getSid() + " :" + iq.toXML()); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
Jid ini = jin.getInitiator();
if (!ini.equals(getInitiator())) {
LOGGER.fine("Ignored Jingle(INI): " + iq.toXML()); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
} else {
// We accept some non-Jingle IQ packets: ERRORs and ACKs
if (iq.getType().equals(IQ.Type.set)) {
LOGGER.fine("Ignored Jingle(TYPE): " + iq.toXML()); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
} else if (iq.getType().equals(IQ.Type.get)) {
LOGGER.fine("Ignored Jingle(TYPE): " + iq.toXML()); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
}
return true; // depends on control dependency: [if], data = [none]
}
return false;
}
};
getConnection().addAsyncStanzaListener(packetListener, packetFilter);
} }
|
public class class_name {
public void marshall(BatchListObjectChildrenResponse batchListObjectChildrenResponse, ProtocolMarshaller protocolMarshaller) {
if (batchListObjectChildrenResponse == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchListObjectChildrenResponse.getChildren(), CHILDREN_BINDING);
protocolMarshaller.marshall(batchListObjectChildrenResponse.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(BatchListObjectChildrenResponse batchListObjectChildrenResponse, ProtocolMarshaller protocolMarshaller) {
if (batchListObjectChildrenResponse == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchListObjectChildrenResponse.getChildren(), CHILDREN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchListObjectChildrenResponse.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
@Deprecated
public static ParagraphVectors readParagraphVectorsFromText(@NonNull InputStream stream) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
ArrayList<String> labels = new ArrayList<>();
ArrayList<INDArray> arrays = new ArrayList<>();
VocabCache<VocabWord> vocabCache = new AbstractCache.Builder<VocabWord>().build();
String line = "";
while ((line = reader.readLine()) != null) {
String[] split = line.split(" ");
split[1] = split[1].replaceAll(WHITESPACE_REPLACEMENT, " ");
VocabWord word = new VocabWord(1.0, split[1]);
if (split[0].equals("L")) {
// we have label element here
word.setSpecial(true);
word.markAsLabel(true);
labels.add(word.getLabel());
} else if (split[0].equals("E")) {
// we have usual element, aka word here
word.setSpecial(false);
word.markAsLabel(false);
} else
throw new IllegalStateException(
"Source stream doesn't looks like ParagraphVectors serialized model");
// this particular line is just for backward compatibility with InMemoryLookupCache
word.setIndex(vocabCache.numWords());
vocabCache.addToken(word);
vocabCache.addWordToIndex(word.getIndex(), word.getLabel());
// backward compatibility code
vocabCache.putVocabWord(word.getLabel());
float[] vector = new float[split.length - 2];
for (int i = 2; i < split.length; i++) {
vector[i - 2] = Float.parseFloat(split[i]);
}
INDArray row = Nd4j.create(vector);
arrays.add(row);
}
// now we create syn0 matrix, using previously fetched rows
/*INDArray syn = Nd4j.create(new int[]{arrays.size(), arrays.get(0).columns()});
for (int i = 0; i < syn.rows(); i++) {
syn.putRow(i, arrays.get(i));
}*/
INDArray syn = Nd4j.vstack(arrays);
InMemoryLookupTable<VocabWord> lookupTable =
(InMemoryLookupTable<VocabWord>) new InMemoryLookupTable.Builder<VocabWord>()
.vectorLength(arrays.get(0).columns()).useAdaGrad(false).cache(vocabCache)
.build();
Nd4j.clearNans(syn);
lookupTable.setSyn0(syn);
LabelsSource source = new LabelsSource(labels);
ParagraphVectors vectors = new ParagraphVectors.Builder().labelsSource(source).vocabCache(vocabCache)
.lookupTable(lookupTable).modelUtils(new BasicModelUtils<VocabWord>()).build();
try {
reader.close();
} catch (Exception e) {
}
vectors.extractLabels();
return vectors;
} catch (Exception e) {
throw new RuntimeException(e);
}
} }
|
public class class_name {
@Deprecated
public static ParagraphVectors readParagraphVectorsFromText(@NonNull InputStream stream) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
ArrayList<String> labels = new ArrayList<>();
ArrayList<INDArray> arrays = new ArrayList<>();
VocabCache<VocabWord> vocabCache = new AbstractCache.Builder<VocabWord>().build();
String line = "";
while ((line = reader.readLine()) != null) {
String[] split = line.split(" ");
split[1] = split[1].replaceAll(WHITESPACE_REPLACEMENT, " "); // depends on control dependency: [while], data = [none]
VocabWord word = new VocabWord(1.0, split[1]);
if (split[0].equals("L")) {
// we have label element here
word.setSpecial(true); // depends on control dependency: [if], data = [none]
word.markAsLabel(true); // depends on control dependency: [if], data = [none]
labels.add(word.getLabel()); // depends on control dependency: [if], data = [none]
} else if (split[0].equals("E")) {
// we have usual element, aka word here
word.setSpecial(false); // depends on control dependency: [if], data = [none]
word.markAsLabel(false); // depends on control dependency: [if], data = [none]
} else
throw new IllegalStateException(
"Source stream doesn't looks like ParagraphVectors serialized model");
// this particular line is just for backward compatibility with InMemoryLookupCache
word.setIndex(vocabCache.numWords()); // depends on control dependency: [while], data = [none]
vocabCache.addToken(word); // depends on control dependency: [while], data = [none]
vocabCache.addWordToIndex(word.getIndex(), word.getLabel()); // depends on control dependency: [while], data = [none]
// backward compatibility code
vocabCache.putVocabWord(word.getLabel()); // depends on control dependency: [while], data = [none]
float[] vector = new float[split.length - 2];
for (int i = 2; i < split.length; i++) {
vector[i - 2] = Float.parseFloat(split[i]); // depends on control dependency: [for], data = [i]
}
INDArray row = Nd4j.create(vector);
arrays.add(row); // depends on control dependency: [while], data = [none]
}
// now we create syn0 matrix, using previously fetched rows
/*INDArray syn = Nd4j.create(new int[]{arrays.size(), arrays.get(0).columns()});
for (int i = 0; i < syn.rows(); i++) {
syn.putRow(i, arrays.get(i));
}*/
INDArray syn = Nd4j.vstack(arrays);
InMemoryLookupTable<VocabWord> lookupTable =
(InMemoryLookupTable<VocabWord>) new InMemoryLookupTable.Builder<VocabWord>()
.vectorLength(arrays.get(0).columns()).useAdaGrad(false).cache(vocabCache)
.build();
Nd4j.clearNans(syn); // depends on control dependency: [try], data = [none]
lookupTable.setSyn0(syn); // depends on control dependency: [try], data = [none]
LabelsSource source = new LabelsSource(labels);
ParagraphVectors vectors = new ParagraphVectors.Builder().labelsSource(source).vocabCache(vocabCache)
.lookupTable(lookupTable).modelUtils(new BasicModelUtils<VocabWord>()).build();
try {
reader.close(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
} // depends on control dependency: [catch], data = [none]
vectors.extractLabels(); // depends on control dependency: [try], data = [none]
return vectors; // 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 void initFromSetupBean(String webapp) {
String db = m_setupBean.getDatabase();
CmsSetupBean bean = m_setupBean;
Map<String, String[]> params = new HashMap<>();
m_setupPanel.setVisible(true);
switch (db) {
case "mysql":
case "mssql":
setVisible(
m_dbCreateUser,
m_dbCreatePwd,
m_dbWorkUser,
m_dbWorkPwd,
m_dbCreateConStr,
m_dbName,
m_createDb,
m_dropDatabase);
m_dbCreateUser.setValue(bean.getDbCreateUser());
m_dbCreatePwd.setValue(bean.getDbCreatePwd());
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_dbCreateConStr.setValue(bean.getDbCreateConStr());
m_dbName.setValue(webapp != null ? webapp : bean.getDb());
m_createDb.setValue(true);
m_createDb.setCaption("Create database and tables");
m_dropDatabase.setValue(false);
break;
case "postgresql":
setVisible(
m_dbCreateUser,
m_dbCreatePwd,
m_dbWorkUser,
m_dbWorkPwd,
m_dbCreateConStr,
m_dbName,
m_createDb,
m_createTables,
m_dropDatabase,
m_templateDb);
m_dbCreateUser.setValue(bean.getDbCreateUser());
m_dbCreatePwd.setValue(bean.getDbCreatePwd());
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_dbCreateConStr.setValue(bean.getDbCreateConStr());
m_dbName.setValue(webapp != null ? webapp : bean.getDb());
m_createDb.setValue(true);
m_createDb.setCaption("Create database and user");
m_templateDb.setValue(dbProp("templateDb"));
m_createTables.setValue(true);
m_dropDatabase.setValue(false);
break;
case "hsqldb":
setVisible(
m_dbCreateUser,
m_dbCreatePwd,
m_dbWorkUser,
m_dbWorkPwd,
m_dbCreateConStr,
m_createDb,
m_dropDatabase);
m_dbCreateUser.setValue(bean.getDbCreateUser());
m_dbCreatePwd.setValue(bean.getDbCreatePwd());
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_createDb.setValue(true);
m_createDb.setCaption("Create database and tables");
m_dropDatabase.setValue(false);
String origCreateConStr = bean.getDbProperty("hsqldb.constr");
String createConStr = bean.getDbCreateConStr();
if ((origCreateConStr != null) && origCreateConStr.equals(createConStr)) {
createConStr = "jdbc:hsqldb:file:"
+ bean.getWebAppRfsPath()
+ "WEB-INF"
+ File.separatorChar
+ "hsqldb"
+ File.separatorChar
+ "opencms;shutdown=false";
}
m_dbCreateConStr.setValue(createConStr);
break;
case "oracle":
setVisible(
m_dbCreateUser,
m_dbCreatePwd,
m_dbWorkUser,
m_dbWorkPwd,
m_dbCreateConStr,
m_createDb,
m_createTables,
m_dropDatabase,
m_temporaryTablespace,
m_indexTablespace,
m_defaultTablespace);
m_dbCreateUser.setValue(bean.getDbCreateUser());
m_dbCreatePwd.setValue(bean.getDbCreatePwd());
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_dbCreateConStr.setValue(bean.getDbCreateConStr());
m_dbName.setValue(webapp != null ? webapp : bean.getDb());
m_createDb.setValue(true);
m_createDb.setCaption("Create user");
m_createTables.setValue(true);
m_dropDatabase.setValue(false);
m_temporaryTablespace.setValue(dbProp("temporaryTablespace"));
m_indexTablespace.setValue(dbProp("indexTablespace"));
m_defaultTablespace.setValue(dbProp("defaultTablespace"));
break;
case "db2":
case "as400":
setVisible(m_dbWorkUser, m_dbWorkPwd, m_dbCreateConStr, m_dbName, m_createTables);
m_setupPanel.setVisible(false);
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_dbCreateConStr.setValue(bean.getDbCreateConStr());
m_dbName.setValue(webapp != null ? webapp : bean.getDb());
m_createDb.setValue(false);
m_createTables.setValue(true);
m_dropDatabase.setValue(true);
break;
default:
break;
}
} }
|
public class class_name {
public void initFromSetupBean(String webapp) {
String db = m_setupBean.getDatabase();
CmsSetupBean bean = m_setupBean;
Map<String, String[]> params = new HashMap<>();
m_setupPanel.setVisible(true);
switch (db) {
case "mysql":
case "mssql":
setVisible(
m_dbCreateUser,
m_dbCreatePwd,
m_dbWorkUser,
m_dbWorkPwd,
m_dbCreateConStr,
m_dbName,
m_createDb,
m_dropDatabase);
m_dbCreateUser.setValue(bean.getDbCreateUser());
m_dbCreatePwd.setValue(bean.getDbCreatePwd());
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_dbCreateConStr.setValue(bean.getDbCreateConStr());
m_dbName.setValue(webapp != null ? webapp : bean.getDb());
m_createDb.setValue(true);
m_createDb.setCaption("Create database and tables");
m_dropDatabase.setValue(false);
break;
case "postgresql":
setVisible(
m_dbCreateUser,
m_dbCreatePwd,
m_dbWorkUser,
m_dbWorkPwd,
m_dbCreateConStr,
m_dbName,
m_createDb,
m_createTables,
m_dropDatabase,
m_templateDb);
m_dbCreateUser.setValue(bean.getDbCreateUser());
m_dbCreatePwd.setValue(bean.getDbCreatePwd());
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_dbCreateConStr.setValue(bean.getDbCreateConStr());
m_dbName.setValue(webapp != null ? webapp : bean.getDb());
m_createDb.setValue(true);
m_createDb.setCaption("Create database and user");
m_templateDb.setValue(dbProp("templateDb"));
m_createTables.setValue(true);
m_dropDatabase.setValue(false);
break;
case "hsqldb":
setVisible(
m_dbCreateUser,
m_dbCreatePwd,
m_dbWorkUser,
m_dbWorkPwd,
m_dbCreateConStr,
m_createDb,
m_dropDatabase);
m_dbCreateUser.setValue(bean.getDbCreateUser());
m_dbCreatePwd.setValue(bean.getDbCreatePwd());
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_createDb.setValue(true);
m_createDb.setCaption("Create database and tables");
m_dropDatabase.setValue(false);
String origCreateConStr = bean.getDbProperty("hsqldb.constr");
String createConStr = bean.getDbCreateConStr();
if ((origCreateConStr != null) && origCreateConStr.equals(createConStr)) {
createConStr = "jdbc:hsqldb:file:"
+ bean.getWebAppRfsPath()
+ "WEB-INF"
+ File.separatorChar
+ "hsqldb"
+ File.separatorChar
+ "opencms;shutdown=false"; // depends on control dependency: [if], data = [none]
}
m_dbCreateConStr.setValue(createConStr);
break;
case "oracle":
setVisible(
m_dbCreateUser,
m_dbCreatePwd,
m_dbWorkUser,
m_dbWorkPwd,
m_dbCreateConStr,
m_createDb,
m_createTables,
m_dropDatabase,
m_temporaryTablespace,
m_indexTablespace,
m_defaultTablespace);
m_dbCreateUser.setValue(bean.getDbCreateUser());
m_dbCreatePwd.setValue(bean.getDbCreatePwd());
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_dbCreateConStr.setValue(bean.getDbCreateConStr());
m_dbName.setValue(webapp != null ? webapp : bean.getDb());
m_createDb.setValue(true);
m_createDb.setCaption("Create user");
m_createTables.setValue(true);
m_dropDatabase.setValue(false);
m_temporaryTablespace.setValue(dbProp("temporaryTablespace"));
m_indexTablespace.setValue(dbProp("indexTablespace"));
m_defaultTablespace.setValue(dbProp("defaultTablespace"));
break;
case "db2":
case "as400":
setVisible(m_dbWorkUser, m_dbWorkPwd, m_dbCreateConStr, m_dbName, m_createTables);
m_setupPanel.setVisible(false);
m_dbWorkUser.setValue(bean.getDbWorkUser());
m_dbWorkPwd.setValue(bean.getDbWorkPwd());
m_dbCreateConStr.setValue(bean.getDbCreateConStr());
m_dbName.setValue(webapp != null ? webapp : bean.getDb());
m_createDb.setValue(false);
m_createTables.setValue(true);
m_dropDatabase.setValue(true);
break;
default:
break;
}
} }
|
public class class_name {
protected final Section getSection (int x, int y, boolean create)
{
int key = key(x, y);
Section sect = _sections.get(key);
if (sect == null && create) {
short sx = (short)(MathUtil.floorDiv(x, swidth)*swidth);
short sy = (short)(MathUtil.floorDiv(y, sheight)*sheight);
_sections.put(key, sect = new Section(sx, sy, swidth, sheight));
// Log.info("Created new section " + sect + ".");
}
return sect;
} }
|
public class class_name {
protected final Section getSection (int x, int y, boolean create)
{
int key = key(x, y);
Section sect = _sections.get(key);
if (sect == null && create) {
short sx = (short)(MathUtil.floorDiv(x, swidth)*swidth);
short sy = (short)(MathUtil.floorDiv(y, sheight)*sheight);
_sections.put(key, sect = new Section(sx, sy, swidth, sheight)); // depends on control dependency: [if], data = [none]
// Log.info("Created new section " + sect + ".");
}
return sect;
} }
|
public class class_name {
private State reservePermissions(final RateLimiterConfig config, final long timeoutInNanos,
final long cycle, final int permissions, final long nanosToWait) {
boolean canAcquireInTime = timeoutInNanos >= nanosToWait;
int permissionsWithReservation = permissions;
if (canAcquireInTime) {
permissionsWithReservation--;
}
return new State(config, cycle, permissionsWithReservation, nanosToWait);
} }
|
public class class_name {
private State reservePermissions(final RateLimiterConfig config, final long timeoutInNanos,
final long cycle, final int permissions, final long nanosToWait) {
boolean canAcquireInTime = timeoutInNanos >= nanosToWait;
int permissionsWithReservation = permissions;
if (canAcquireInTime) {
permissionsWithReservation--; // depends on control dependency: [if], data = [none]
}
return new State(config, cycle, permissionsWithReservation, nanosToWait);
} }
|
public class class_name {
public static Throwable getRootCause(Throwable t) {
if (t == null) {
return null;
}
while (t.getCause() != null) {
t = t.getCause();
}
return t;
} }
|
public class class_name {
public static Throwable getRootCause(Throwable t) {
if (t == null) {
return null; // depends on control dependency: [if], data = [none]
}
while (t.getCause() != null) {
t = t.getCause(); // depends on control dependency: [while], data = [none]
}
return t;
} }
|
public class class_name {
public static void startSplashScreen()
{
int width=275,height=148;
Window win=new Window( new Frame() );
win.pack();
BshCanvas can=new BshCanvas();
can.setSize( width, height ); // why is this necessary?
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension dim=tk.getScreenSize();
win.setBounds(
dim.width/2-width/2, dim.height/2-height/2, width, height );
win.add("Center", can);
Image img=tk.getImage(
Interpreter.class.getResource("/bsh/util/lib/splash.gif") );
MediaTracker mt=new MediaTracker(can);
mt.addImage(img,0);
try { mt.waitForAll(); } catch ( Exception e ) { }
Graphics gr=can.getBufferedGraphics();
gr.drawImage(img, 0, 0, can);
win.setVisible(true);
win.toFront();
splashScreen = win;
} }
|
public class class_name {
public static void startSplashScreen()
{
int width=275,height=148;
Window win=new Window( new Frame() );
win.pack();
BshCanvas can=new BshCanvas();
can.setSize( width, height ); // why is this necessary?
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension dim=tk.getScreenSize();
win.setBounds(
dim.width/2-width/2, dim.height/2-height/2, width, height );
win.add("Center", can);
Image img=tk.getImage(
Interpreter.class.getResource("/bsh/util/lib/splash.gif") );
MediaTracker mt=new MediaTracker(can);
mt.addImage(img,0);
try { mt.waitForAll(); } catch ( Exception e ) { } // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none]
Graphics gr=can.getBufferedGraphics();
gr.drawImage(img, 0, 0, can);
win.setVisible(true);
win.toFront();
splashScreen = win;
} }
|
public class class_name {
private CouchbaseResponse handleBucketStreamingResponse(final ChannelHandlerContext ctx,
final HttpResponse header) {
SocketAddress addr = ctx.channel().remoteAddress();
String host = addr instanceof InetSocketAddress ? ((InetSocketAddress) addr).getAddress().getHostAddress()
: addr.toString();
ResponseStatus status = ResponseStatusConverter.fromHttp(header.getStatus().code());
Observable<String> scheduledObservable = null;
if (status.isSuccess()) {
streamingConfigObservable = BehaviorSubject.create();
scheduledObservable = streamingConfigObservable.onBackpressureBuffer().observeOn(env().scheduler());
}
return new BucketStreamingResponse(
scheduledObservable,
host,
status,
currentRequest()
);
} }
|
public class class_name {
private CouchbaseResponse handleBucketStreamingResponse(final ChannelHandlerContext ctx,
final HttpResponse header) {
SocketAddress addr = ctx.channel().remoteAddress();
String host = addr instanceof InetSocketAddress ? ((InetSocketAddress) addr).getAddress().getHostAddress()
: addr.toString();
ResponseStatus status = ResponseStatusConverter.fromHttp(header.getStatus().code());
Observable<String> scheduledObservable = null;
if (status.isSuccess()) {
streamingConfigObservable = BehaviorSubject.create(); // depends on control dependency: [if], data = [none]
scheduledObservable = streamingConfigObservable.onBackpressureBuffer().observeOn(env().scheduler()); // depends on control dependency: [if], data = [none]
}
return new BucketStreamingResponse(
scheduledObservable,
host,
status,
currentRequest()
);
} }
|
public class class_name {
private int getDegreesFromCoords(float pointX, float pointY, boolean forceLegal,
final Boolean[] isInnerCircle) {
int currentItem = getCurrentItemShowing();
if (currentItem == HOUR_INDEX) {
return mHourRadialSelectorView.getDegreesFromCoords(
pointX, pointY, forceLegal, isInnerCircle);
} else if (currentItem == MINUTE_INDEX) {
return mMinuteRadialSelectorView.getDegreesFromCoords(
pointX, pointY, forceLegal, isInnerCircle);
} else {
return -1;
}
} }
|
public class class_name {
private int getDegreesFromCoords(float pointX, float pointY, boolean forceLegal,
final Boolean[] isInnerCircle) {
int currentItem = getCurrentItemShowing();
if (currentItem == HOUR_INDEX) {
return mHourRadialSelectorView.getDegreesFromCoords(
pointX, pointY, forceLegal, isInnerCircle); // depends on control dependency: [if], data = [none]
} else if (currentItem == MINUTE_INDEX) {
return mMinuteRadialSelectorView.getDegreesFromCoords(
pointX, pointY, forceLegal, isInnerCircle); // depends on control dependency: [if], data = [none]
} else {
return -1; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public Annotation[] getRuntimeInvisibleAnnotations() {
for (int i = mAttributes.size(); --i >= 0; ) {
Attribute attr = mAttributes.get(i);
if (attr instanceof RuntimeInvisibleAnnotationsAttr) {
return ((AnnotationsAttr) attr).getAnnotations();
}
}
return new Annotation[0];
} }
|
public class class_name {
public Annotation[] getRuntimeInvisibleAnnotations() {
for (int i = mAttributes.size(); --i >= 0; ) {
Attribute attr = mAttributes.get(i);
if (attr instanceof RuntimeInvisibleAnnotationsAttr) {
return ((AnnotationsAttr) attr).getAnnotations(); // depends on control dependency: [if], data = [none]
}
}
return new Annotation[0];
} }
|
public class class_name {
private void compilePattern() throws ParseException {
StringBuilder sb = new StringBuilder();
boolean escaped = false;
final List<GlobPattern> patterns = new ArrayList<>();
for (int a = 0; a < _patternSource.length(); a++) {
final char c = _patternSource.charAt(a);
// Test escape-char
if (c == '\\') {
if (escaped) {
sb.append('\\');
escaped = false;
} else {
escaped = true;
}
} else {
if (escaped) {
if (c != GLOB_SINGLE && c != GLOB_MULTIPLE) {
sb.append("\\");
} else {
// Globbing chars escaped
sb.append(c);
escaped = false;
}
} else {
// No escape character, test whether it matches on of the globbing characters.
if (c == GLOB_MULTIPLE || c == GLOB_SINGLE) {
if (sb.length() > 0) {
patterns.add(new GlobPattern(TEXT, sb.toString()));
sb = new StringBuilder();
}
patterns.add(new GlobPattern(c));
} else {
sb.append(c);
}
}
}
}
if (sb.length() > 0) {
patterns.add(new GlobPattern(TEXT, sb.toString()));
}
// Add meta information and correct the elements
addMetaInformation(patterns);
_compiledPattern = new GlobPattern[patterns.size()];
patterns.toArray(_compiledPattern);
} }
|
public class class_name {
private void compilePattern() throws ParseException {
StringBuilder sb = new StringBuilder();
boolean escaped = false;
final List<GlobPattern> patterns = new ArrayList<>();
for (int a = 0; a < _patternSource.length(); a++) {
final char c = _patternSource.charAt(a);
// Test escape-char
if (c == '\\') {
if (escaped) {
sb.append('\\'); // depends on control dependency: [if], data = [none]
escaped = false; // depends on control dependency: [if], data = [none]
} else {
escaped = true; // depends on control dependency: [if], data = [none]
}
} else {
if (escaped) {
if (c != GLOB_SINGLE && c != GLOB_MULTIPLE) {
sb.append("\\"); // depends on control dependency: [if], data = [none]
} else {
// Globbing chars escaped
sb.append(c); // depends on control dependency: [if], data = [(c]
escaped = false; // depends on control dependency: [if], data = [none]
}
} else {
// No escape character, test whether it matches on of the globbing characters.
if (c == GLOB_MULTIPLE || c == GLOB_SINGLE) {
if (sb.length() > 0) {
patterns.add(new GlobPattern(TEXT, sb.toString())); // depends on control dependency: [if], data = [none]
sb = new StringBuilder(); // depends on control dependency: [if], data = [none]
}
patterns.add(new GlobPattern(c)); // depends on control dependency: [if], data = [(c]
} else {
sb.append(c); // depends on control dependency: [if], data = [(c]
}
}
}
}
if (sb.length() > 0) {
patterns.add(new GlobPattern(TEXT, sb.toString()));
}
// Add meta information and correct the elements
addMetaInformation(patterns);
_compiledPattern = new GlobPattern[patterns.size()];
patterns.toArray(_compiledPattern);
} }
|
public class class_name {
public final synchronized Date evalDateBalanceStoreStart(
final Map<String, Object> pAddParam) throws Exception {
Date dateBalanceStoreStart = lazyGetBalanceAtAllDirtyCheck(pAddParam)
.getDateBalanceStoreStart();
Date leastAccountingEntryDate = this.balanceAtAllDirtyCheck
.getLeastAccountingEntryDate();
if (dateBalanceStoreStart.getTime() == this.initDateLong
&& leastAccountingEntryDate.getTime() == this.initDateLong) {
//the first time with no acc-entries, it's start of current ACC year:
Calendar cal = Calendar.getInstance(new Locale("en", "US"));
cal.setTime(getSrvAccSettings().lazyGetAccSettings(pAddParam)
.getCurrentAccYear());
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
this.balanceAtAllDirtyCheck
.setDateBalanceStoreStart(cal.getTime());
getSrvOrm()
.updateEntity(pAddParam, this.balanceAtAllDirtyCheck);
} else if (dateBalanceStoreStart.getTime() == this.initDateLong
&& leastAccountingEntryDate.getTime() > this.initDateLong) {
//there is at least 1 acc entry
//the start is start of nearest period to the first acc entry:
Long dateFirstEntryLong = this.srvDatabase
.evalLongResult("select min(ITSDATE) as MINIMUMDATE "
+ "from ACCOUNTINGENTRY where REVERSEDID is null;", "MINIMUMDATE");
if (dateFirstEntryLong == null) {
//e.g. dirty reversed acc entry
getLogger().info(null, SrvBalanceStd.class,
"There is no single acc entry, so use current acc year for start balance!");
Calendar cal = Calendar.getInstance(new Locale("en", "US"));
cal.setTime(getSrvAccSettings().lazyGetAccSettings(pAddParam)
.getCurrentAccYear());
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
this.balanceAtAllDirtyCheck
.setDateBalanceStoreStart(cal.getTime());
} else {
this.balanceAtAllDirtyCheck.setDateBalanceStoreStart(
evalDatePeriodStartFor(pAddParam, new Date(dateFirstEntryLong)));
}
getSrvOrm()
.updateEntity(pAddParam, this.balanceAtAllDirtyCheck);
}
return this.balanceAtAllDirtyCheck.getDateBalanceStoreStart();
} }
|
public class class_name {
public final synchronized Date evalDateBalanceStoreStart(
final Map<String, Object> pAddParam) throws Exception {
Date dateBalanceStoreStart = lazyGetBalanceAtAllDirtyCheck(pAddParam)
.getDateBalanceStoreStart();
Date leastAccountingEntryDate = this.balanceAtAllDirtyCheck
.getLeastAccountingEntryDate();
if (dateBalanceStoreStart.getTime() == this.initDateLong
&& leastAccountingEntryDate.getTime() == this.initDateLong) {
//the first time with no acc-entries, it's start of current ACC year:
Calendar cal = Calendar.getInstance(new Locale("en", "US"));
cal.setTime(getSrvAccSettings().lazyGetAccSettings(pAddParam)
.getCurrentAccYear());
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
this.balanceAtAllDirtyCheck
.setDateBalanceStoreStart(cal.getTime());
getSrvOrm()
.updateEntity(pAddParam, this.balanceAtAllDirtyCheck);
} else if (dateBalanceStoreStart.getTime() == this.initDateLong
&& leastAccountingEntryDate.getTime() > this.initDateLong) {
//there is at least 1 acc entry
//the start is start of nearest period to the first acc entry:
Long dateFirstEntryLong = this.srvDatabase
.evalLongResult("select min(ITSDATE) as MINIMUMDATE "
+ "from ACCOUNTINGENTRY where REVERSEDID is null;", "MINIMUMDATE");
if (dateFirstEntryLong == null) {
//e.g. dirty reversed acc entry
getLogger().info(null, SrvBalanceStd.class,
"There is no single acc entry, so use current acc year for start balance!"); // depends on control dependency: [if], data = [none]
Calendar cal = Calendar.getInstance(new Locale("en", "US"));
cal.setTime(getSrvAccSettings().lazyGetAccSettings(pAddParam)
.getCurrentAccYear()); // depends on control dependency: [if], data = [none]
cal.set(Calendar.MONTH, 0); // depends on control dependency: [if], data = [none]
cal.set(Calendar.DAY_OF_MONTH, 1); // depends on control dependency: [if], data = [none]
cal.set(Calendar.HOUR_OF_DAY, 0); // depends on control dependency: [if], data = [none]
cal.set(Calendar.MINUTE, 0); // depends on control dependency: [if], data = [none]
cal.set(Calendar.SECOND, 0); // depends on control dependency: [if], data = [none]
cal.set(Calendar.MILLISECOND, 0); // depends on control dependency: [if], data = [none]
this.balanceAtAllDirtyCheck
.setDateBalanceStoreStart(cal.getTime()); // depends on control dependency: [if], data = [none]
} else {
this.balanceAtAllDirtyCheck.setDateBalanceStoreStart(
evalDatePeriodStartFor(pAddParam, new Date(dateFirstEntryLong))); // depends on control dependency: [if], data = [none]
}
getSrvOrm()
.updateEntity(pAddParam, this.balanceAtAllDirtyCheck);
}
return this.balanceAtAllDirtyCheck.getDateBalanceStoreStart();
} }
|
public class class_name {
private Map<String, InputColumn<?>> readSourceColumns(final SourceColumnMapping sourceColumnMapping,
final AnalysisJobBuilder analysisJobBuilder, final SourceType source) {
final Map<String, InputColumn<?>> inputColumns = new HashMap<>();
final ColumnsType columnsType = source.getColumns();
if (columnsType != null) {
final List<ColumnType> columns = columnsType.getColumn();
for (final ColumnType column : columns) {
final String path = column.getPath();
if (StringUtils.isNullOrEmpty(path)) {
throw new IllegalStateException("Column path cannot be null");
}
final Column physicalColumn = sourceColumnMapping.getColumn(path);
if (physicalColumn == null) {
logger.error("Column {} not found in {}", path, sourceColumnMapping);
throw new NoSuchColumnException(path);
}
final MetaModelInputColumn inputColumn = new MetaModelInputColumn(physicalColumn);
final String id = column.getId();
if (StringUtils.isNullOrEmpty(id)) {
throw new IllegalStateException("Source column id cannot be null");
}
final String expectedType = column.getType();
if (expectedType != null) {
final org.apache.metamodel.schema.ColumnType actualType = physicalColumn.getType();
if (actualType != null && !expectedType.equals(actualType.toString())) {
logger.warn("Column '{}' had type '{}', but '{}' was expected.",
new Object[] { path, actualType, expectedType });
}
}
registerInputColumn(inputColumns, id, inputColumn);
analysisJobBuilder.addSourceColumn(inputColumn);
}
}
return inputColumns;
} }
|
public class class_name {
private Map<String, InputColumn<?>> readSourceColumns(final SourceColumnMapping sourceColumnMapping,
final AnalysisJobBuilder analysisJobBuilder, final SourceType source) {
final Map<String, InputColumn<?>> inputColumns = new HashMap<>();
final ColumnsType columnsType = source.getColumns();
if (columnsType != null) {
final List<ColumnType> columns = columnsType.getColumn();
for (final ColumnType column : columns) {
final String path = column.getPath();
if (StringUtils.isNullOrEmpty(path)) {
throw new IllegalStateException("Column path cannot be null");
}
final Column physicalColumn = sourceColumnMapping.getColumn(path);
if (physicalColumn == null) {
logger.error("Column {} not found in {}", path, sourceColumnMapping); // depends on control dependency: [if], data = [none]
throw new NoSuchColumnException(path);
}
final MetaModelInputColumn inputColumn = new MetaModelInputColumn(physicalColumn);
final String id = column.getId();
if (StringUtils.isNullOrEmpty(id)) {
throw new IllegalStateException("Source column id cannot be null");
}
final String expectedType = column.getType();
if (expectedType != null) {
final org.apache.metamodel.schema.ColumnType actualType = physicalColumn.getType();
if (actualType != null && !expectedType.equals(actualType.toString())) {
logger.warn("Column '{}' had type '{}', but '{}' was expected.",
new Object[] { path, actualType, expectedType }); // depends on control dependency: [if], data = [none]
}
}
registerInputColumn(inputColumns, id, inputColumn);
analysisJobBuilder.addSourceColumn(inputColumn);
}
}
return inputColumns;
} }
|
public class class_name {
public String getWorkerMemParameter(LocalAssignment assignment,
Map totalConf,
String topologyId,
Integer port) {
long memSize = assignment.getMem();
long memMinSize = ConfigExtension.getMemMinSizePerWorker(totalConf);
long memGsize = memSize / JStormUtils.SIZE_1_G;
int gcThreadsNum = memGsize > 4 ? (int) (memGsize * 1.5) : 4;
String childOpts = getChildOpts(totalConf);
childOpts += getGcDumpParam(topologyId, port, totalConf);
StringBuilder commandSB = new StringBuilder();
memMinSize = memMinSize < memSize ? memMinSize : memSize;
commandSB.append(" -Xms").append(memMinSize).append(" -Xmx").append(memSize).append(" ");
if (memMinSize <= (memSize / 2)) {
commandSB.append(" -Xmn").append(memMinSize / 2).append(" ");
} else {
commandSB.append(" -Xmn").append(memSize / 2).append(" ");
}
// PermSize is deprecated in jdk1.8
if (JDKInfo.isJdk7() || JDKInfo.lessThanJdk7()) {
if (memGsize >= 2) {
commandSB.append(" -XX:PermSize=").append(memSize / 32);
} else {
commandSB.append(" -XX:PermSize=").append(memSize / 16);
}
commandSB.append(" -XX:MaxPermSize=").append(memSize / 16);
} else if (JDKInfo.isJdk8()) {
if (memGsize >= 2) {
commandSB.append(" -XX:MetaspaceSize=").append(memSize / 32);
} else {
commandSB.append(" -XX:MetaspaceSize=").append(memSize / 16);
}
commandSB.append(" -XX:MaxMetaspaceSize=").append(memSize / 16);
}
commandSB.append(" -XX:ParallelGCThreads=").append(gcThreadsNum);
commandSB.append(" ").append(childOpts);
if (!StringUtils.isBlank(assignment.getJvm())) {
commandSB.append(" ").append(assignment.getJvm());
}
return commandSB.toString();
} }
|
public class class_name {
public String getWorkerMemParameter(LocalAssignment assignment,
Map totalConf,
String topologyId,
Integer port) {
long memSize = assignment.getMem();
long memMinSize = ConfigExtension.getMemMinSizePerWorker(totalConf);
long memGsize = memSize / JStormUtils.SIZE_1_G;
int gcThreadsNum = memGsize > 4 ? (int) (memGsize * 1.5) : 4;
String childOpts = getChildOpts(totalConf);
childOpts += getGcDumpParam(topologyId, port, totalConf);
StringBuilder commandSB = new StringBuilder();
memMinSize = memMinSize < memSize ? memMinSize : memSize;
commandSB.append(" -Xms").append(memMinSize).append(" -Xmx").append(memSize).append(" ");
if (memMinSize <= (memSize / 2)) {
commandSB.append(" -Xmn").append(memMinSize / 2).append(" "); // depends on control dependency: [if], data = [(memMinSize]
} else {
commandSB.append(" -Xmn").append(memSize / 2).append(" "); // depends on control dependency: [if], data = [none]
}
// PermSize is deprecated in jdk1.8
if (JDKInfo.isJdk7() || JDKInfo.lessThanJdk7()) {
if (memGsize >= 2) {
commandSB.append(" -XX:PermSize=").append(memSize / 32); // depends on control dependency: [if], data = [none]
} else {
commandSB.append(" -XX:PermSize=").append(memSize / 16); // depends on control dependency: [if], data = [none]
}
commandSB.append(" -XX:MaxPermSize=").append(memSize / 16); // depends on control dependency: [if], data = [none]
} else if (JDKInfo.isJdk8()) {
if (memGsize >= 2) {
commandSB.append(" -XX:MetaspaceSize=").append(memSize / 32); // depends on control dependency: [if], data = [none]
} else {
commandSB.append(" -XX:MetaspaceSize=").append(memSize / 16); // depends on control dependency: [if], data = [none]
}
commandSB.append(" -XX:MaxMetaspaceSize=").append(memSize / 16); // depends on control dependency: [if], data = [none]
}
commandSB.append(" -XX:ParallelGCThreads=").append(gcThreadsNum);
commandSB.append(" ").append(childOpts);
if (!StringUtils.isBlank(assignment.getJvm())) {
commandSB.append(" ").append(assignment.getJvm()); // depends on control dependency: [if], data = [none]
}
return commandSB.toString();
} }
|
public class class_name {
AtomSymbol generatePeriodicSymbol(final int number, final int hydrogens, final int mass, final int charge,
final int unpaired, HydrogenPosition position) {
TextOutline element = number == 0 ? new TextOutline("*", font)
: new TextOutline(Elements.ofNumber(number).symbol(), font);
TextOutline hydrogenAdjunct = defaultHydrogenLabel;
// the hydrogen count, charge, and mass adjuncts are script size
TextOutline hydrogenCount = new TextOutline(Integer.toString(hydrogens), font).resize(scriptSize, scriptSize);
TextOutline chargeAdjunct = new TextOutline(chargeAdjunctText(charge, unpaired), font).resize(scriptSize,
scriptSize);
TextOutline massAdjunct = new TextOutline(Integer.toString(mass), font).resize(scriptSize, scriptSize);
// position each adjunct relative to the element label and each other
hydrogenAdjunct = positionHydrogenLabel(position, element, hydrogenAdjunct);
hydrogenCount = positionSubscript(hydrogenAdjunct, hydrogenCount);
chargeAdjunct = positionChargeLabel(hydrogens, position, chargeAdjunct, element, hydrogenAdjunct);
massAdjunct = positionMassLabel(massAdjunct, element);
// when the hydrogen label is positioned to the left we may need to nudge it
// over to account for the hydrogen count and/or the mass adjunct colliding
// with the element label
if (position == Left) {
final double nudgeX = hydrogenXDodge(hydrogens, mass, element, hydrogenAdjunct, hydrogenCount, massAdjunct);
hydrogenAdjunct = hydrogenAdjunct.translate(nudgeX, 0);
hydrogenCount = hydrogenCount.translate(nudgeX, 0);
}
final List<TextOutline> adjuncts = new ArrayList<TextOutline>(4);
if (hydrogens > 0) adjuncts.add(hydrogenAdjunct);
if (hydrogens > 1) adjuncts.add(hydrogenCount);
if (charge != 0 || unpaired > 0) adjuncts.add(chargeAdjunct);
if (mass > 0) adjuncts.add(massAdjunct);
return new AtomSymbol(element, adjuncts);
} }
|
public class class_name {
AtomSymbol generatePeriodicSymbol(final int number, final int hydrogens, final int mass, final int charge,
final int unpaired, HydrogenPosition position) {
TextOutline element = number == 0 ? new TextOutline("*", font)
: new TextOutline(Elements.ofNumber(number).symbol(), font);
TextOutline hydrogenAdjunct = defaultHydrogenLabel;
// the hydrogen count, charge, and mass adjuncts are script size
TextOutline hydrogenCount = new TextOutline(Integer.toString(hydrogens), font).resize(scriptSize, scriptSize);
TextOutline chargeAdjunct = new TextOutline(chargeAdjunctText(charge, unpaired), font).resize(scriptSize,
scriptSize);
TextOutline massAdjunct = new TextOutline(Integer.toString(mass), font).resize(scriptSize, scriptSize);
// position each adjunct relative to the element label and each other
hydrogenAdjunct = positionHydrogenLabel(position, element, hydrogenAdjunct);
hydrogenCount = positionSubscript(hydrogenAdjunct, hydrogenCount);
chargeAdjunct = positionChargeLabel(hydrogens, position, chargeAdjunct, element, hydrogenAdjunct);
massAdjunct = positionMassLabel(massAdjunct, element);
// when the hydrogen label is positioned to the left we may need to nudge it
// over to account for the hydrogen count and/or the mass adjunct colliding
// with the element label
if (position == Left) {
final double nudgeX = hydrogenXDodge(hydrogens, mass, element, hydrogenAdjunct, hydrogenCount, massAdjunct);
hydrogenAdjunct = hydrogenAdjunct.translate(nudgeX, 0); // depends on control dependency: [if], data = [none]
hydrogenCount = hydrogenCount.translate(nudgeX, 0); // depends on control dependency: [if], data = [none]
}
final List<TextOutline> adjuncts = new ArrayList<TextOutline>(4);
if (hydrogens > 0) adjuncts.add(hydrogenAdjunct);
if (hydrogens > 1) adjuncts.add(hydrogenCount);
if (charge != 0 || unpaired > 0) adjuncts.add(chargeAdjunct);
if (mass > 0) adjuncts.add(massAdjunct);
return new AtomSymbol(element, adjuncts);
} }
|
public class class_name {
@Override
public DescriptorValue calculate(IBond aBond, IAtomContainer atomContainer) {
IAtomContainer ac;
IBond bond;
try {
ac = (IAtomContainer) atomContainer.clone();
bond = ac.getBond(atomContainer.indexOf(aBond));
AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(ac);
} catch (CDKException e) {
return getDummyDescriptorValue(e);
} catch (CloneNotSupportedException e) {
return getDummyDescriptorValue(e);
}
if (maxIterations != -1 && maxIterations != 0) electronegativity.setMaxIterations(maxIterations);
double electroAtom1 = electronegativity.calculateSigmaElectronegativity(ac, bond.getBegin());
double electroAtom2 = electronegativity.calculateSigmaElectronegativity(ac, bond.getEnd());
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(
Math.abs(electroAtom1 - electroAtom2)), NAMES);
} }
|
public class class_name {
@Override
public DescriptorValue calculate(IBond aBond, IAtomContainer atomContainer) {
IAtomContainer ac;
IBond bond;
try {
ac = (IAtomContainer) atomContainer.clone(); // depends on control dependency: [try], data = [none]
bond = ac.getBond(atomContainer.indexOf(aBond)); // depends on control dependency: [try], data = [none]
AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(ac); // depends on control dependency: [try], data = [none]
} catch (CDKException e) {
return getDummyDescriptorValue(e);
} catch (CloneNotSupportedException e) { // depends on control dependency: [catch], data = [none]
return getDummyDescriptorValue(e);
} // depends on control dependency: [catch], data = [none]
if (maxIterations != -1 && maxIterations != 0) electronegativity.setMaxIterations(maxIterations);
double electroAtom1 = electronegativity.calculateSigmaElectronegativity(ac, bond.getBegin());
double electroAtom2 = electronegativity.calculateSigmaElectronegativity(ac, bond.getEnd());
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(
Math.abs(electroAtom1 - electroAtom2)), NAMES);
} }
|
public class class_name {
public Observable<ServiceResponse<ResourceGroupExportResultInner>> exportTemplateWithServiceResponseAsync(String resourceGroupName, ExportTemplateRequest parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
Validator.validate(parameters);
return service.exportTemplate(resourceGroupName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ResourceGroupExportResultInner>>>() {
@Override
public Observable<ServiceResponse<ResourceGroupExportResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ResourceGroupExportResultInner> clientResponse = exportTemplateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} }
|
public class class_name {
public Observable<ServiceResponse<ResourceGroupExportResultInner>> exportTemplateWithServiceResponseAsync(String resourceGroupName, ExportTemplateRequest parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
Validator.validate(parameters);
return service.exportTemplate(resourceGroupName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ResourceGroupExportResultInner>>>() {
@Override
public Observable<ServiceResponse<ResourceGroupExportResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ResourceGroupExportResultInner> clientResponse = exportTemplateDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} }
|
public class class_name {
public Producer<CloseableReference<PooledByteBuffer>>
getNetworkFetchEncodedImageProducerSequence() {
synchronized (this) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection(
"ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence");
}
if (mNetworkEncodedImageProducerSequence == null) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection(
"ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence:init");
}
mNetworkEncodedImageProducerSequence =
new RemoveImageTransformMetaDataProducer(
getBackgroundNetworkFetchToEncodedMemorySequence());
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
}
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
}
return mNetworkEncodedImageProducerSequence;
} }
|
public class class_name {
public Producer<CloseableReference<PooledByteBuffer>>
getNetworkFetchEncodedImageProducerSequence() {
synchronized (this) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection(
"ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence"); // depends on control dependency: [if], data = [none]
}
if (mNetworkEncodedImageProducerSequence == null) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection(
"ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence:init"); // depends on control dependency: [if], data = [none]
}
mNetworkEncodedImageProducerSequence =
new RemoveImageTransformMetaDataProducer(
getBackgroundNetworkFetchToEncodedMemorySequence()); // depends on control dependency: [if], data = [none]
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection(); // depends on control dependency: [if], data = [none]
}
}
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection(); // depends on control dependency: [if], data = [none]
}
}
return mNetworkEncodedImageProducerSequence;
} }
|
public class class_name {
@Override
public void beginList(WikiParameters params, boolean ordered)
{
if (ordered) {
listOrdering.push(ListOrdering.ORDERED);
} else {
listOrdering.push(ListOrdering.UNORDERED);
}
if (listItemWritten) { // new line for each new list
println();
}
} }
|
public class class_name {
@Override
public void beginList(WikiParameters params, boolean ordered)
{
if (ordered) {
listOrdering.push(ListOrdering.ORDERED); // depends on control dependency: [if], data = [none]
} else {
listOrdering.push(ListOrdering.UNORDERED); // depends on control dependency: [if], data = [none]
}
if (listItemWritten) { // new line for each new list
println(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public java.util.List<RecordPatch> getRecordPatches() {
if (recordPatches == null) {
recordPatches = new com.amazonaws.internal.SdkInternalList<RecordPatch>();
}
return recordPatches;
} }
|
public class class_name {
public java.util.List<RecordPatch> getRecordPatches() {
if (recordPatches == null) {
recordPatches = new com.amazonaws.internal.SdkInternalList<RecordPatch>(); // depends on control dependency: [if], data = [none]
}
return recordPatches;
} }
|
public class class_name {
@Override
public void register(Builder.Registry registry) {
registry.add(new AzureAdTokenFactory());
registry.add(MediaContract.class, MediaExceptionProcessor.class);
registry.add(MediaRestProxy.class);
registry.add(OAuthFilter.class);
registry.add(ResourceLocationManager.class);
registry.add(RedirectFilter.class);
registry.add(VersionHeadersFilter.class);
registry.add(UserAgentFilter.class);
registry.alter(MediaContract.class, ClientConfig.class,
new Builder.Alteration<ClientConfig>() {
@SuppressWarnings("rawtypes")
@Override
public ClientConfig alter(String profile,
ClientConfig instance, Builder builder,
Map<String, Object> properties) {
instance.getProperties().put(
JSONConfiguration.FEATURE_POJO_MAPPING, true);
// Turn off auto-follow redirects, because Media
// Services rest calls break if it's on
instance.getProperties().put(
ClientConfig.PROPERTY_FOLLOW_REDIRECTS, false);
try {
instance.getSingletons().add(
new ODataEntityProvider());
instance.getSingletons().add(
new ODataEntityCollectionProvider());
instance.getSingletons().add(
new MediaContentProvider());
instance.getSingletons().add(
new BatchMimeMultipartBodyWritter());
} catch (JAXBException e) {
throw new RuntimeException(e);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
return instance;
}
});
} }
|
public class class_name {
@Override
public void register(Builder.Registry registry) {
registry.add(new AzureAdTokenFactory());
registry.add(MediaContract.class, MediaExceptionProcessor.class);
registry.add(MediaRestProxy.class);
registry.add(OAuthFilter.class);
registry.add(ResourceLocationManager.class);
registry.add(RedirectFilter.class);
registry.add(VersionHeadersFilter.class);
registry.add(UserAgentFilter.class);
registry.alter(MediaContract.class, ClientConfig.class,
new Builder.Alteration<ClientConfig>() {
@SuppressWarnings("rawtypes")
@Override
public ClientConfig alter(String profile,
ClientConfig instance, Builder builder,
Map<String, Object> properties) {
instance.getProperties().put(
JSONConfiguration.FEATURE_POJO_MAPPING, true);
// Turn off auto-follow redirects, because Media
// Services rest calls break if it's on
instance.getProperties().put(
ClientConfig.PROPERTY_FOLLOW_REDIRECTS, false);
try {
instance.getSingletons().add(
new ODataEntityProvider()); // depends on control dependency: [try], data = [none]
instance.getSingletons().add(
new ODataEntityCollectionProvider()); // depends on control dependency: [try], data = [none]
instance.getSingletons().add(
new MediaContentProvider()); // depends on control dependency: [try], data = [none]
instance.getSingletons().add(
new BatchMimeMultipartBodyWritter()); // depends on control dependency: [try], data = [none]
} catch (JAXBException e) {
throw new RuntimeException(e);
} catch (ParserConfigurationException e) { // depends on control dependency: [catch], data = [none]
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
return instance;
}
});
} }
|
public class class_name {
protected Content getNavSummaryLink(TypeElement typeElement, boolean link) {
if (link) {
return writer.getHyperLink(
SectionName.ANNOTATION_TYPE_FIELD_SUMMARY,
contents.navField);
} else {
return contents.navField;
}
} }
|
public class class_name {
protected Content getNavSummaryLink(TypeElement typeElement, boolean link) {
if (link) {
return writer.getHyperLink(
SectionName.ANNOTATION_TYPE_FIELD_SUMMARY,
contents.navField); // depends on control dependency: [if], data = [none]
} else {
return contents.navField; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void marshall(ListBulkDeploymentsRequest listBulkDeploymentsRequest, ProtocolMarshaller protocolMarshaller) {
if (listBulkDeploymentsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listBulkDeploymentsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(listBulkDeploymentsRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(ListBulkDeploymentsRequest listBulkDeploymentsRequest, ProtocolMarshaller protocolMarshaller) {
if (listBulkDeploymentsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listBulkDeploymentsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listBulkDeploymentsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private void jobBizLog(JobPo jobPo, BizLogCode code) {
if (jobPo == null) {
return;
}
try {
// 记录日志
JobLogPo jobLogPo = JobDomainConverter.convertJobLog(jobPo);
jobLogPo.setSuccess(true);
jobLogPo.setLogType(LogType.RECEIVE);
jobLogPo.setLogTime(SystemClock.now());
switch (code) {
case SUCCESS:
jobLogPo.setLevel(Level.INFO);
jobLogPo.setMsg("Receive Success");
break;
case DUP_IGNORE:
jobLogPo.setLevel(Level.WARN);
jobLogPo.setMsg("Already Exist And Ignored");
break;
case DUP_FAILED:
jobLogPo.setLevel(Level.ERROR);
jobLogPo.setMsg("Already Exist And Update Failed");
break;
case DUP_REPLACE:
jobLogPo.setLevel(Level.INFO);
jobLogPo.setMsg("Already Exist And Update Success");
break;
}
appContext.getJobLogger().log(jobLogPo);
} catch (Throwable t) { // 日志记录失败不影响正常运行
LOGGER.error("Receive Job Log error ", t);
}
} }
|
public class class_name {
private void jobBizLog(JobPo jobPo, BizLogCode code) {
if (jobPo == null) {
return; // depends on control dependency: [if], data = [none]
}
try {
// 记录日志
JobLogPo jobLogPo = JobDomainConverter.convertJobLog(jobPo);
jobLogPo.setSuccess(true); // depends on control dependency: [try], data = [none]
jobLogPo.setLogType(LogType.RECEIVE); // depends on control dependency: [try], data = [none]
jobLogPo.setLogTime(SystemClock.now()); // depends on control dependency: [try], data = [none]
switch (code) {
case SUCCESS:
jobLogPo.setLevel(Level.INFO);
jobLogPo.setMsg("Receive Success");
break;
case DUP_IGNORE:
jobLogPo.setLevel(Level.WARN);
jobLogPo.setMsg("Already Exist And Ignored");
break;
case DUP_FAILED:
jobLogPo.setLevel(Level.ERROR);
jobLogPo.setMsg("Already Exist And Update Failed");
break;
case DUP_REPLACE:
jobLogPo.setLevel(Level.INFO);
jobLogPo.setMsg("Already Exist And Update Success");
break;
}
appContext.getJobLogger().log(jobLogPo); // depends on control dependency: [try], data = [none]
} catch (Throwable t) { // 日志记录失败不影响正常运行
LOGGER.error("Receive Job Log error ", t);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static void popPreferredClassLoader() {
final ClassLoader sysLoader = ClassLoaderFinder.class.getClassLoader();
if ((dynamicLoader == null) || (dynamicLoader == sysLoader)) {
dynamicLoader = null;
final Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
for (final Thread t : threads) {
if (t != null) {
t.setContextClassLoader(sysLoader);
}
}
return;
}
final ClassLoader parent = dynamicLoader.getParent();
dynamicLoader = (parent == sysLoader) ? null : parent;
final Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
for (final Thread t : threads) {
if (t != null) {
t.setContextClassLoader(parent);
}
}
} }
|
public class class_name {
public static void popPreferredClassLoader() {
final ClassLoader sysLoader = ClassLoaderFinder.class.getClassLoader();
if ((dynamicLoader == null) || (dynamicLoader == sysLoader)) {
dynamicLoader = null; // depends on control dependency: [if], data = [none]
final Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads); // depends on control dependency: [if], data = [none]
for (final Thread t : threads) {
if (t != null) {
t.setContextClassLoader(sysLoader); // depends on control dependency: [if], data = [none]
}
}
return; // depends on control dependency: [if], data = [none]
}
final ClassLoader parent = dynamicLoader.getParent();
dynamicLoader = (parent == sysLoader) ? null : parent;
final Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
for (final Thread t : threads) {
if (t != null) {
t.setContextClassLoader(parent); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public boolean continueAfterUnprotectedURI(WebRequest webRequest) {
if (taiServiceRef.getService() != null) {
TAIService taiService = taiServiceRef.getService();
if (!taiService.isContinueAfterUnprotectedURI() && taiService.isInvokeForUnprotectedURI() && webRequest.isUnprotectedURI()
&& !webRequest.isProviderSpecialUnprotectedURI()) {
webRequest.setContinueAfterUnprotectedURI(false);
} else {
webRequest.setContinueAfterUnprotectedURI(true);
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "continueAfterUnprotectedURI from configuration=" + taiService.isContinueAfterUnprotectedURI() +
" Caclulated value: isContinueAfterUnprotectedURI= " + webRequest.isContinueAfterUnprotectedURI());
}
}
return webRequest.isContinueAfterUnprotectedURI();
} }
|
public class class_name {
public boolean continueAfterUnprotectedURI(WebRequest webRequest) {
if (taiServiceRef.getService() != null) {
TAIService taiService = taiServiceRef.getService();
if (!taiService.isContinueAfterUnprotectedURI() && taiService.isInvokeForUnprotectedURI() && webRequest.isUnprotectedURI()
&& !webRequest.isProviderSpecialUnprotectedURI()) {
webRequest.setContinueAfterUnprotectedURI(false); // depends on control dependency: [if], data = [none]
} else {
webRequest.setContinueAfterUnprotectedURI(true); // depends on control dependency: [if], data = [none]
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "continueAfterUnprotectedURI from configuration=" + taiService.isContinueAfterUnprotectedURI() +
" Caclulated value: isContinueAfterUnprotectedURI= " + webRequest.isContinueAfterUnprotectedURI()); // depends on control dependency: [if], data = [none]
}
}
return webRequest.isContinueAfterUnprotectedURI();
} }
|
public class class_name {
private void doResource(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
boolean success = true;
String resource = (String) req.getParameter("id");
if (!isEmpty(resource))
{
if (resource.endsWith(".js"))
{
resp.setContentType("text/javascript");
} else if (resource.endsWith(".css"))
{
resp.setContentType("text/css");
} else if (resource.endsWith(".html"))
{
resp.setContentType("text/html");
} else
{
resp.setContentType("text/plain");
}
String contents = resourceLoader.getResource(resource, resourceReplacements);
if (contents != null)
{
if (resourceCacheHours > 0)
{
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR, resourceCacheHours);
resp.setHeader("Cache-Control", "public, must-revalidate");
resp.setHeader("Expires", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(c.getTime()));
} else
{
resp.setHeader("Cache-Control", "no-cache");
}
PrintWriter w = resp.getWriter();
w.print(contents);
} else
{
success = false;
}
}
if (!success)
{
resp.sendError(404);
}
} }
|
public class class_name {
private void doResource(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
boolean success = true;
String resource = (String) req.getParameter("id");
if (!isEmpty(resource))
{
if (resource.endsWith(".js"))
{
resp.setContentType("text/javascript"); // depends on control dependency: [if], data = [none]
} else if (resource.endsWith(".css"))
{
resp.setContentType("text/css"); // depends on control dependency: [if], data = [none]
} else if (resource.endsWith(".html"))
{
resp.setContentType("text/html"); // depends on control dependency: [if], data = [none]
} else
{
resp.setContentType("text/plain"); // depends on control dependency: [if], data = [none]
}
String contents = resourceLoader.getResource(resource, resourceReplacements);
if (contents != null)
{
if (resourceCacheHours > 0)
{
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR, resourceCacheHours); // depends on control dependency: [if], data = [none]
resp.setHeader("Cache-Control", "public, must-revalidate"); // depends on control dependency: [if], data = [none]
resp.setHeader("Expires", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(c.getTime())); // depends on control dependency: [if], data = [none]
} else
{
resp.setHeader("Cache-Control", "no-cache"); // depends on control dependency: [if], data = [none]
}
PrintWriter w = resp.getWriter();
w.print(contents); // depends on control dependency: [if], data = [(contents]
} else
{
success = false; // depends on control dependency: [if], data = [none]
}
}
if (!success)
{
resp.sendError(404);
}
} }
|
public class class_name {
public StringBuilder onWhereClause(StringBuilder builder, Class fieldClazz, String field, Object value,
String clause, boolean useToken)
{
if (clause.trim().equals(IN_CLAUSE))
{
useToken = false;
}
builder = ensureCase(builder, field, useToken);
builder.append(SPACE_STRING);
if (fieldClazz.isAssignableFrom(List.class) || fieldClazz.isAssignableFrom(Map.class)
|| fieldClazz.isAssignableFrom(Set.class))
{
builder.append("CONTAINS");
}
else
{
builder.append(clause);
}
builder.append(SPACE_STRING);
if (clause.trim().equals(IN_CLAUSE))
{
builder.append(OPEN_BRACKET);
String itemValues = String.valueOf(value);
itemValues = itemValues.startsWith(OPEN_BRACKET) && itemValues.endsWith(CLOSE_BRACKET) ? itemValues
.substring(1, itemValues.length() - 1) : itemValues;
List<String> items = Arrays.asList(((String) itemValues).split("\\s*,\\s*"));
int counter = 0;
for (String str : items)
{
str = str.trim();
str = (str.startsWith(Constants.ESCAPE_QUOTE) && str.endsWith(Constants.ESCAPE_QUOTE))
|| (str.startsWith("'") && str.endsWith("'")) ? str.substring(1, str.length() - 1) : str;
appendValue(builder, fieldClazz, str, false, false);
counter++;
if (counter < items.size())
{
builder.append(COMMA_STR);
}
}
builder.append(CLOSE_BRACKET);
}
else
{
appendValue(builder, fieldClazz, value, false, useToken);
}
return builder;
} }
|
public class class_name {
public StringBuilder onWhereClause(StringBuilder builder, Class fieldClazz, String field, Object value,
String clause, boolean useToken)
{
if (clause.trim().equals(IN_CLAUSE))
{
useToken = false; // depends on control dependency: [if], data = [none]
}
builder = ensureCase(builder, field, useToken);
builder.append(SPACE_STRING);
if (fieldClazz.isAssignableFrom(List.class) || fieldClazz.isAssignableFrom(Map.class)
|| fieldClazz.isAssignableFrom(Set.class))
{
builder.append("CONTAINS"); // depends on control dependency: [if], data = [none]
}
else
{
builder.append(clause); // depends on control dependency: [if], data = [none]
}
builder.append(SPACE_STRING);
if (clause.trim().equals(IN_CLAUSE))
{
builder.append(OPEN_BRACKET); // depends on control dependency: [if], data = [none]
String itemValues = String.valueOf(value);
itemValues = itemValues.startsWith(OPEN_BRACKET) && itemValues.endsWith(CLOSE_BRACKET) ? itemValues
.substring(1, itemValues.length() - 1) : itemValues; // depends on control dependency: [if], data = [none]
List<String> items = Arrays.asList(((String) itemValues).split("\\s*,\\s*"));
int counter = 0;
for (String str : items)
{
str = str.trim(); // depends on control dependency: [for], data = [str]
str = (str.startsWith(Constants.ESCAPE_QUOTE) && str.endsWith(Constants.ESCAPE_QUOTE))
|| (str.startsWith("'") && str.endsWith("'")) ? str.substring(1, str.length() - 1) : str; // depends on control dependency: [for], data = [str]
appendValue(builder, fieldClazz, str, false, false); // depends on control dependency: [for], data = [str]
counter++; // depends on control dependency: [for], data = [none]
if (counter < items.size())
{
builder.append(COMMA_STR); // depends on control dependency: [if], data = [none]
}
}
builder.append(CLOSE_BRACKET); // depends on control dependency: [if], data = [none]
}
else
{
appendValue(builder, fieldClazz, value, false, useToken); // depends on control dependency: [if], data = [none]
}
return builder;
} }
|
public class class_name {
private Set<RelationshipTuple> getRels(String relsDatastreamName) {
List<Datastream> relsDatastreamVersions = m_datastreams.get(relsDatastreamName);
if (relsDatastreamVersions == null || relsDatastreamVersions.size() == 0) {
return new HashSet<RelationshipTuple>();
}
Datastream latestRels = relsDatastreamVersions.get(0);
for (Datastream v : relsDatastreamVersions) {
if (v.DSCreateDT == null){
latestRels = v;
break;
}
if (v.DSCreateDT.getTime() > latestRels.DSCreateDT.getTime()) {
latestRels = v;
}
}
try {
return RDFRelationshipReader.readRelationships(latestRels);
} catch (ServerException e) {
throw new RuntimeException("Error reading object relationships in " + relsDatastreamName, e);
}
} }
|
public class class_name {
private Set<RelationshipTuple> getRels(String relsDatastreamName) {
List<Datastream> relsDatastreamVersions = m_datastreams.get(relsDatastreamName);
if (relsDatastreamVersions == null || relsDatastreamVersions.size() == 0) {
return new HashSet<RelationshipTuple>(); // depends on control dependency: [if], data = [none]
}
Datastream latestRels = relsDatastreamVersions.get(0);
for (Datastream v : relsDatastreamVersions) {
if (v.DSCreateDT == null){
latestRels = v; // depends on control dependency: [if], data = [none]
break;
}
if (v.DSCreateDT.getTime() > latestRels.DSCreateDT.getTime()) {
latestRels = v; // depends on control dependency: [if], data = [none]
}
}
try {
return RDFRelationshipReader.readRelationships(latestRels); // depends on control dependency: [try], data = [none]
} catch (ServerException e) {
throw new RuntimeException("Error reading object relationships in " + relsDatastreamName, e);
} // depends on control dependency: [catch], data = [none]
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.