code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
@Override
public synchronized AcceleratedScreen getAcceleratedScreen(
int[] attributes) throws GLException {
if (accScreen == null) {
accScreen = new AndroidAcceleratedScreen(attributes);
}
return accScreen;
} } | public class class_name {
@Override
public synchronized AcceleratedScreen getAcceleratedScreen(
int[] attributes) throws GLException {
if (accScreen == null) {
accScreen = new AndroidAcceleratedScreen(attributes); // depends on control dependency: [if], data = [none]
}
return accScreen;
} } |
public class class_name {
private static boolean isIllPosed(double minMass, double maxMass, MolecularFormulaRange mfRange) {
// when the number of integers to decompose is incredible large
// we have to adjust the internal settings (e.g. precision!)
// instead we simply fallback to the full enumeration method
if (maxMass - minMass >= 1) return true;
if (maxMass > 400000) return true;
// if the number of elements to decompose is very small
// we fall back to the full enumeration methods as the
// minimal decomposable mass of a certain residue class might
// exceed the 32 bit integer space
if (mfRange.getIsotopeCount() <= 2) return true;
// if the mass of the smallest element in alphabet is large
// it is more efficient to use the full enumeration method
double smallestMass = Double.POSITIVE_INFINITY;
for (IIsotope i : mfRange.isotopes()) {
smallestMass = Math.min(smallestMass, i.getExactMass());
}
return smallestMass > 5;
} } | public class class_name {
private static boolean isIllPosed(double minMass, double maxMass, MolecularFormulaRange mfRange) {
// when the number of integers to decompose is incredible large
// we have to adjust the internal settings (e.g. precision!)
// instead we simply fallback to the full enumeration method
if (maxMass - minMass >= 1) return true;
if (maxMass > 400000) return true;
// if the number of elements to decompose is very small
// we fall back to the full enumeration methods as the
// minimal decomposable mass of a certain residue class might
// exceed the 32 bit integer space
if (mfRange.getIsotopeCount() <= 2) return true;
// if the mass of the smallest element in alphabet is large
// it is more efficient to use the full enumeration method
double smallestMass = Double.POSITIVE_INFINITY;
for (IIsotope i : mfRange.isotopes()) {
smallestMass = Math.min(smallestMass, i.getExactMass()); // depends on control dependency: [for], data = [i]
}
return smallestMass > 5;
} } |
public class class_name {
protected final boolean stateCheckVal(int s, int snum) {
if (stateCheckBuff != null) {
int x = stateCheckPos(s, snum);
return (stateCheckBuff[x / 8] & (1 << (x % 8))) != 0;
}
return false;
} } | public class class_name {
protected final boolean stateCheckVal(int s, int snum) {
if (stateCheckBuff != null) {
int x = stateCheckPos(s, snum);
return (stateCheckBuff[x / 8] & (1 << (x % 8))) != 0; // depends on control dependency: [if], data = [(stateCheckBuff]
}
return false;
} } |
public class class_name {
public SetBase<T> forEach($.Visitor<? super T> visitor) throws $.Break {
for (T t : this) {
try {
visitor.apply(t);
} catch (NotAppliedException e) {
// ignore
}
}
return this;
} } | public class class_name {
public SetBase<T> forEach($.Visitor<? super T> visitor) throws $.Break {
for (T t : this) {
try {
visitor.apply(t); // depends on control dependency: [try], data = [none]
} catch (NotAppliedException e) {
// ignore
} // depends on control dependency: [catch], data = [none]
}
return this;
} } |
public class class_name {
@Deprecated
protected Object readResolve() {
// If we get invalid state from the configuration, fallback to unknown
if (StringUtils.isBlank(name)) {
LOGGER.log(Level.WARNING, "Read install state with blank name: ''{0}''. It will be ignored", name);
return UNKNOWN;
}
InstallState state = InstallState.valueOf(name);
if (state == null) {
LOGGER.log(Level.WARNING, "Cannot locate an extension point for the state ''{0}''. It will be ignored", name);
return UNKNOWN;
}
// Otherwise we return the actual state
return state;
} } | public class class_name {
@Deprecated
protected Object readResolve() {
// If we get invalid state from the configuration, fallback to unknown
if (StringUtils.isBlank(name)) {
LOGGER.log(Level.WARNING, "Read install state with blank name: ''{0}''. It will be ignored", name); // depends on control dependency: [if], data = [none]
return UNKNOWN; // depends on control dependency: [if], data = [none]
}
InstallState state = InstallState.valueOf(name);
if (state == null) {
LOGGER.log(Level.WARNING, "Cannot locate an extension point for the state ''{0}''. It will be ignored", name); // depends on control dependency: [if], data = [none]
return UNKNOWN; // depends on control dependency: [if], data = [none]
}
// Otherwise we return the actual state
return state;
} } |
public class class_name {
public static @CheckForNull
BugCollection doAnalysis(@Nonnull Project p) {
requireNonNull(p, "null project");
RedoAnalysisCallback ac = new RedoAnalysisCallback();
AnalyzingDialog.show(p, ac, true);
if (ac.finished) {
return ac.getBugCollection();
} else {
return null;
}
} } | public class class_name {
public static @CheckForNull
BugCollection doAnalysis(@Nonnull Project p) {
requireNonNull(p, "null project");
RedoAnalysisCallback ac = new RedoAnalysisCallback();
AnalyzingDialog.show(p, ac, true);
if (ac.finished) {
return ac.getBugCollection(); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Result getScript(boolean indexRoots) {
Result r = Result.newSingleColumnResult("COMMAND", Type.SQL_VARCHAR);
String[] list = getSettingsSQL();
addRows(r, list);
list = getGranteeManager().getSQL();
addRows(r, list);
// schemas and schema objects such as tables, sequences, etc.
list = schemaManager.getSQLArray();
addRows(r, list);
// index roots
if (indexRoots) {
list = schemaManager.getIndexRootsSQL();
addRows(r, list);
}
// user session start schema names
list = getUserManager().getInitialSchemaSQL();
addRows(r, list);
// grantee rights
list = getGranteeManager().getRightstSQL();
addRows(r, list);
list = getPropertiesSQL();
addRows(r, list);
return r;
} } | public class class_name {
public Result getScript(boolean indexRoots) {
Result r = Result.newSingleColumnResult("COMMAND", Type.SQL_VARCHAR);
String[] list = getSettingsSQL();
addRows(r, list);
list = getGranteeManager().getSQL();
addRows(r, list);
// schemas and schema objects such as tables, sequences, etc.
list = schemaManager.getSQLArray();
addRows(r, list);
// index roots
if (indexRoots) {
list = schemaManager.getIndexRootsSQL(); // depends on control dependency: [if], data = [none]
addRows(r, list); // depends on control dependency: [if], data = [none]
}
// user session start schema names
list = getUserManager().getInitialSchemaSQL();
addRows(r, list);
// grantee rights
list = getGranteeManager().getRightstSQL();
addRows(r, list);
list = getPropertiesSQL();
addRows(r, list);
return r;
} } |
public class class_name {
private long lastModified(URL url) {
if (url.getProtocol().equals("file")) {
return new File(url.getFile()).lastModified();
} else {
try {
URLConnection conn = url.openConnection();
if (conn instanceof JarURLConnection) {
URL jarURL = ((JarURLConnection) conn).getJarFileURL();
if (jarURL.getProtocol().equals("file")) { return new File(jarURL.getFile()).lastModified(); }
}
} catch (IOException e1) {
return -1;
}
return -1;
}
} } | public class class_name {
private long lastModified(URL url) {
if (url.getProtocol().equals("file")) {
return new File(url.getFile()).lastModified(); // depends on control dependency: [if], data = [none]
} else {
try {
URLConnection conn = url.openConnection();
if (conn instanceof JarURLConnection) {
URL jarURL = ((JarURLConnection) conn).getJarFileURL();
if (jarURL.getProtocol().equals("file")) { return new File(jarURL.getFile()).lastModified(); } // depends on control dependency: [if], data = [none]
}
} catch (IOException e1) {
return -1;
} // depends on control dependency: [catch], data = [none]
return -1; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static List<ClassInfo> getAnnotatedClasses(List<AnnotationInstance> instances) {
List<ClassInfo> result = new ArrayList<ClassInfo>();
for (AnnotationInstance instance : instances) {
AnnotationTarget target = instance.target();
if (target instanceof ClassInfo) {
result.add((ClassInfo) target);
}
}
return result;
} } | public class class_name {
public static List<ClassInfo> getAnnotatedClasses(List<AnnotationInstance> instances) {
List<ClassInfo> result = new ArrayList<ClassInfo>();
for (AnnotationInstance instance : instances) {
AnnotationTarget target = instance.target();
if (target instanceof ClassInfo) {
result.add((ClassInfo) target); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
protected static Properties loadConfig(String name) {
try {
URL url = new URL(name);
return loadConfig(url);
} catch (Exception ex) {
return loadConfig(new File(name));
}
} } | public class class_name {
protected static Properties loadConfig(String name) {
try {
URL url = new URL(name);
return loadConfig(url); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
return loadConfig(new File(name));
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private JSType getJSType(Node n) {
JSType type = n.getJSType();
if (type == null) {
// TODO(bradfordcsmith): This branch indicates a compiler bug. It should throw an exception.
return compiler.getTypeRegistry().getNativeType(JSTypeNative.UNKNOWN_TYPE);
} else {
return type;
}
} } | public class class_name {
private JSType getJSType(Node n) {
JSType type = n.getJSType();
if (type == null) {
// TODO(bradfordcsmith): This branch indicates a compiler bug. It should throw an exception.
return compiler.getTypeRegistry().getNativeType(JSTypeNative.UNKNOWN_TYPE); // depends on control dependency: [if], data = [none]
} else {
return type; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void pingServerIfNecessary() {
final XMPPConnection connection = connection();
if (connection == null) {
// connection has been collected by GC
// which means we can stop the thread by breaking the loop
return;
}
if (pingInterval <= 0) {
// Ping has been disabled
return;
}
long lastStanzaReceived = connection.getLastStanzaReceived();
if (lastStanzaReceived > 0) {
long now = System.currentTimeMillis();
// Delta since the last stanza was received
int deltaInSeconds = (int) ((now - lastStanzaReceived) / 1000);
// If the delta is small then the ping interval, then we can defer the ping
if (deltaInSeconds < pingInterval) {
maybeSchedulePingServerTask(deltaInSeconds);
return;
}
}
if (!connection.isAuthenticated()) {
LOGGER.warning(connection + " was not authenticated");
return;
}
final long minimumTimeout = TimeUnit.MINUTES.toMillis(2);
final long connectionReplyTimeout = connection.getReplyTimeout();
final long timeout = connectionReplyTimeout > minimumTimeout ? connectionReplyTimeout : minimumTimeout;
SmackFuture<Boolean, Exception> pingFuture = pingAsync(connection.getXMPPServiceDomain(), timeout);
pingFuture.onSuccess(new SuccessCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
// Ping was successful, wind-up the periodic task again
maybeSchedulePingServerTask();
}
});
pingFuture.onError(new ExceptionCallback<Exception>() {
@Override
public void processException(Exception exception) {
long lastStanzaReceived = connection.getLastStanzaReceived();
if (lastStanzaReceived > 0) {
long now = System.currentTimeMillis();
// Delta since the last stanza was received
int deltaInSeconds = (int) ((now - lastStanzaReceived) / 1000);
// If the delta is smaller then the ping interval, we have got an valid stanza in time
// So not error notification needed
if (deltaInSeconds < pingInterval) {
maybeSchedulePingServerTask(deltaInSeconds);
return;
}
}
for (PingFailedListener l : pingFailedListeners) {
l.pingFailed();
}
}
});
} } | public class class_name {
public void pingServerIfNecessary() {
final XMPPConnection connection = connection();
if (connection == null) {
// connection has been collected by GC
// which means we can stop the thread by breaking the loop
return; // depends on control dependency: [if], data = [none]
}
if (pingInterval <= 0) {
// Ping has been disabled
return; // depends on control dependency: [if], data = [none]
}
long lastStanzaReceived = connection.getLastStanzaReceived();
if (lastStanzaReceived > 0) {
long now = System.currentTimeMillis();
// Delta since the last stanza was received
int deltaInSeconds = (int) ((now - lastStanzaReceived) / 1000);
// If the delta is small then the ping interval, then we can defer the ping
if (deltaInSeconds < pingInterval) {
maybeSchedulePingServerTask(deltaInSeconds); // depends on control dependency: [if], data = [(deltaInSeconds]
return; // depends on control dependency: [if], data = [none]
}
}
if (!connection.isAuthenticated()) {
LOGGER.warning(connection + " was not authenticated"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final long minimumTimeout = TimeUnit.MINUTES.toMillis(2);
final long connectionReplyTimeout = connection.getReplyTimeout();
final long timeout = connectionReplyTimeout > minimumTimeout ? connectionReplyTimeout : minimumTimeout;
SmackFuture<Boolean, Exception> pingFuture = pingAsync(connection.getXMPPServiceDomain(), timeout);
pingFuture.onSuccess(new SuccessCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
// Ping was successful, wind-up the periodic task again
maybeSchedulePingServerTask();
}
});
pingFuture.onError(new ExceptionCallback<Exception>() {
@Override
public void processException(Exception exception) {
long lastStanzaReceived = connection.getLastStanzaReceived();
if (lastStanzaReceived > 0) {
long now = System.currentTimeMillis();
// Delta since the last stanza was received
int deltaInSeconds = (int) ((now - lastStanzaReceived) / 1000);
// If the delta is smaller then the ping interval, we have got an valid stanza in time
// So not error notification needed
if (deltaInSeconds < pingInterval) {
maybeSchedulePingServerTask(deltaInSeconds); // depends on control dependency: [if], data = [(deltaInSeconds]
return; // depends on control dependency: [if], data = [none]
}
}
for (PingFailedListener l : pingFailedListeners) {
l.pingFailed(); // depends on control dependency: [for], data = [l]
}
}
});
} } |
public class class_name {
private synchronized void doNodeLeft(final String nodeID) {
log.info(String.format("%s - %s left the cluster", this, nodeID));
context.run(new Runnable() {
@Override
public void run() {
synchronized (nodes) {
// If we were the first node to remove the nodes then we need
// to inform listeners that the node left the cluster over the
// event bus.
Collection<String> removedNodes = nodes.remove(nodeID);
if (removedNodes != null) {
synchronized (groups) {
for (final String node : removedNodes) {
for (final String group : groups.keySet()) {
groups.remove(group, node);
vertx.runOnContext(new Handler<Void>() {
@Override
public void handle(Void event) {
vertx.eventBus().publish(String.format("%s.leave", group), node);
}
});
}
vertx.runOnContext(new Handler<Void>() {
@Override
public void handle(Void event) {
vertx.eventBus().publish(String.format("%s.leave", cluster), node);
}
});
}
}
// Check for any network masters that left the cluster.
synchronized (networks) {
for (final String name : networks) {
String address = nodeSelectors.get(name);
if (address != null && removedNodes.contains(address)) {
// If the node to which the network was assigned is one of the nodes
// that left the cluster then redeploy the network. If no changes
// have been made to the network then this will simply result in the
// network's manager being redeployed.
selectNode(name, new Handler<AsyncResult<String>>() {
@Override
public void handle(AsyncResult<String> result) {
if (result.succeeded() && result.result() != null) {
// Just redeploy the network by sending a deploy message to the appropriate node.
JsonObject message = new JsonObject()
.putString("action", "deploy")
.putString("type", "network")
.putString("network", name);
vertx.eventBus().send(result.result(), message);
}
}
});
}
}
}
// Redeploy any failed deployments.
synchronized (deployments) {
Collection<String> sdeploymentsInfo = deployments.get(cluster);
for (final String sdeploymentInfo : sdeploymentsInfo) {
final JsonObject deploymentInfo = new JsonObject(sdeploymentInfo);
// If the deployment node is equal to the node that left the cluster then
// remove the deployment from the deployments list and attempt to redeploy it.
if (deploymentInfo.getString("node").equals(nodeID)) {
// If the deployment is an HA deployment then attempt to redeploy it on this node.
if (deployments.remove(cluster, sdeploymentInfo) && deploymentInfo.getBoolean("ha", false)) {
doRedeploy(deploymentInfo);
}
}
}
}
}
}
}
});
} } | public class class_name {
private synchronized void doNodeLeft(final String nodeID) {
log.info(String.format("%s - %s left the cluster", this, nodeID));
context.run(new Runnable() {
@Override
public void run() {
synchronized (nodes) {
// If we were the first node to remove the nodes then we need
// to inform listeners that the node left the cluster over the
// event bus.
Collection<String> removedNodes = nodes.remove(nodeID);
if (removedNodes != null) {
synchronized (groups) { // depends on control dependency: [if], data = [none]
for (final String node : removedNodes) {
for (final String group : groups.keySet()) {
groups.remove(group, node); // depends on control dependency: [for], data = [group]
vertx.runOnContext(new Handler<Void>() {
@Override
public void handle(Void event) {
vertx.eventBus().publish(String.format("%s.leave", group), node);
}
}); // depends on control dependency: [for], data = [none]
}
vertx.runOnContext(new Handler<Void>() {
@Override
public void handle(Void event) {
vertx.eventBus().publish(String.format("%s.leave", cluster), node);
}
}); // depends on control dependency: [for], data = [none]
}
}
// Check for any network masters that left the cluster.
synchronized (networks) { // depends on control dependency: [if], data = [none]
for (final String name : networks) {
String address = nodeSelectors.get(name);
if (address != null && removedNodes.contains(address)) {
// If the node to which the network was assigned is one of the nodes
// that left the cluster then redeploy the network. If no changes
// have been made to the network then this will simply result in the
// network's manager being redeployed.
selectNode(name, new Handler<AsyncResult<String>>() {
@Override
public void handle(AsyncResult<String> result) {
if (result.succeeded() && result.result() != null) {
// Just redeploy the network by sending a deploy message to the appropriate node.
JsonObject message = new JsonObject()
.putString("action", "deploy")
.putString("type", "network")
.putString("network", name);
vertx.eventBus().send(result.result(), message); // depends on control dependency: [if], data = [none]
}
}
}); // depends on control dependency: [if], data = [none]
}
}
}
// Redeploy any failed deployments.
synchronized (deployments) { // depends on control dependency: [if], data = [none]
Collection<String> sdeploymentsInfo = deployments.get(cluster);
for (final String sdeploymentInfo : sdeploymentsInfo) {
final JsonObject deploymentInfo = new JsonObject(sdeploymentInfo);
// If the deployment node is equal to the node that left the cluster then
// remove the deployment from the deployments list and attempt to redeploy it.
if (deploymentInfo.getString("node").equals(nodeID)) {
// If the deployment is an HA deployment then attempt to redeploy it on this node.
if (deployments.remove(cluster, sdeploymentInfo) && deploymentInfo.getBoolean("ha", false)) {
doRedeploy(deploymentInfo); // depends on control dependency: [if], data = [none]
}
}
}
}
}
}
}
});
} } |
public class class_name {
@SuppressWarnings("unchecked")
protected static <TGraph extends DirectedAcyclicGraph<TVertex, TValue, TProcessedValue>, TVertex extends IVertex<TValue>, TValue extends Object, TProcessedValue extends Object> TGraph copyGraph(final TGraph graph) {
try {
final Class g_class = graph.getClass();
final Constructor<? extends DirectedAcyclicGraph<TVertex, TValue, TProcessedValue>> construct = g_class.getDeclaredConstructor();
construct.setAccessible(true);
final TGraph g = (TGraph)construct.newInstance();
g.vertices = new LinkedHashSet<TVertex>(graph.vertices);
g.edges = new LinkedHashSet<IEdge<TVertex>>(graph.edges);
return g;
} catch(Throwable t) {
return null;
}
} } | public class class_name {
@SuppressWarnings("unchecked")
protected static <TGraph extends DirectedAcyclicGraph<TVertex, TValue, TProcessedValue>, TVertex extends IVertex<TValue>, TValue extends Object, TProcessedValue extends Object> TGraph copyGraph(final TGraph graph) {
try {
final Class g_class = graph.getClass();
final Constructor<? extends DirectedAcyclicGraph<TVertex, TValue, TProcessedValue>> construct = g_class.getDeclaredConstructor();
construct.setAccessible(true); // depends on control dependency: [try], data = [none]
final TGraph g = (TGraph)construct.newInstance();
g.vertices = new LinkedHashSet<TVertex>(graph.vertices); // depends on control dependency: [try], data = [none]
g.edges = new LinkedHashSet<IEdge<TVertex>>(graph.edges); // depends on control dependency: [try], data = [none]
return g; // depends on control dependency: [try], data = [none]
} catch(Throwable t) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (a.length < count)
a = (T[]) java.lang.reflect.Array.newInstance
(a.getClass().getComponentType(), count);
int k = 0;
for (Node<E> p = first; p != null; p = p.next)
a[k++] = (T) p.item;
if (a.length > k)
a[k] = null;
return a;
} finally {
lock.unlock();
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (a.length < count)
a = (T[]) java.lang.reflect.Array.newInstance
(a.getClass().getComponentType(), count);
int k = 0;
for (Node<E> p = first; p != null; p = p.next)
a[k++] = (T) p.item;
if (a.length > k)
a[k] = null;
return a; // depends on control dependency: [try], data = [none]
} finally {
lock.unlock();
}
} } |
public class class_name {
public static List<Field> getRelatedColumns(Class<?> clazz) {
if(clazz == null) {
return new ArrayList<Field>();
}
List<Class<?>> classLink = new ArrayList<Class<?>>();
Class<?> curClass = clazz;
while (curClass != null) {
classLink.add(curClass);
curClass = curClass.getSuperclass();
}
// 父类优先
List<Field> result = new ArrayList<Field>();
for (int i = classLink.size() - 1; i >= 0; i--) {
Field[] fields = classLink.get(i).getDeclaredFields();
for (Field field : fields) {
if (field.getAnnotation(RelatedColumn.class) != null) {
result.add(field);
}
}
}
return result;
} } | public class class_name {
public static List<Field> getRelatedColumns(Class<?> clazz) {
if(clazz == null) {
return new ArrayList<Field>(); // depends on control dependency: [if], data = [none]
}
List<Class<?>> classLink = new ArrayList<Class<?>>();
Class<?> curClass = clazz;
while (curClass != null) {
classLink.add(curClass); // depends on control dependency: [while], data = [(curClass]
curClass = curClass.getSuperclass(); // depends on control dependency: [while], data = [none]
}
// 父类优先
List<Field> result = new ArrayList<Field>();
for (int i = classLink.size() - 1; i >= 0; i--) {
Field[] fields = classLink.get(i).getDeclaredFields();
for (Field field : fields) {
if (field.getAnnotation(RelatedColumn.class) != null) {
result.add(field); // depends on control dependency: [if], data = [none]
}
}
}
return result;
} } |
public class class_name {
public static Map createHeadersMap(PageContext pContext)
{
final HttpServletRequest request =
(HttpServletRequest) pContext.getRequest();
return new EnumeratedMap()
{
public Enumeration enumerateKeys()
{
return request.getHeaderNames();
}
public Object getValue(Object pKey)
{
if (pKey instanceof String) {
// Drain the header enumeration
List l = new ArrayList();
Enumeration enum_ = request.getHeaders((String) pKey);
if (enum_ != null) {
while (enum_.hasMoreElements()) {
l.add(enum_.nextElement());
}
}
String[] ret = (String[]) l.toArray(new String[l.size()]);
return ret;
} else {
return null;
}
}
public boolean isMutable()
{
return false;
}
};
} } | public class class_name {
public static Map createHeadersMap(PageContext pContext)
{
final HttpServletRequest request =
(HttpServletRequest) pContext.getRequest();
return new EnumeratedMap()
{
public Enumeration enumerateKeys()
{
return request.getHeaderNames();
}
public Object getValue(Object pKey)
{
if (pKey instanceof String) {
// Drain the header enumeration
List l = new ArrayList();
Enumeration enum_ = request.getHeaders((String) pKey);
if (enum_ != null) {
while (enum_.hasMoreElements()) {
l.add(enum_.nextElement()); // depends on control dependency: [while], data = [none]
}
}
String[] ret = (String[]) l.toArray(new String[l.size()]);
return ret; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
}
public boolean isMutable()
{
return false;
}
};
} } |
public class class_name {
public void register(Authenticator authenticator) {
if (this.authenticator == null) {
this.authenticator = authenticator;
} else if (!authenticator.getClass().getSimpleName().equals(this.authenticator.getClass().getSimpleName())) {
throw new ConfigurationException("attempt to replace authenticator " +
this.authenticator.getClass().getSimpleName() + " by " +
authenticator.getClass().getSimpleName());
}
} } | public class class_name {
public void register(Authenticator authenticator) {
if (this.authenticator == null) {
this.authenticator = authenticator; // depends on control dependency: [if], data = [none]
} else if (!authenticator.getClass().getSimpleName().equals(this.authenticator.getClass().getSimpleName())) {
throw new ConfigurationException("attempt to replace authenticator " +
this.authenticator.getClass().getSimpleName() + " by " +
authenticator.getClass().getSimpleName());
}
} } |
public class class_name {
private void readBitFields(MppBitFlag[] flags, FieldContainer container, byte[] data)
{
for (MppBitFlag flag : flags)
{
flag.setValue(container, data);
}
} } | public class class_name {
private void readBitFields(MppBitFlag[] flags, FieldContainer container, byte[] data)
{
for (MppBitFlag flag : flags)
{
flag.setValue(container, data); // depends on control dependency: [for], data = [flag]
}
} } |
public class class_name {
private static FeatureDetailWidgetBuilder getCustomBuilder(Layer<?> layer) {
FeatureDetailWidgetBuilder b = null;
try {
if (layer != null) {
ClientWidgetInfo cwi = layer.getLayerInfo().getWidgetInfo(WidgetBuilderInfo.IDENTIFIER);
if (cwi != null) {
if (cwi instanceof WidgetBuilderInfo) {
WidgetBuilderInfo lcfdii = (WidgetBuilderInfo) cwi;
WidgetBuilder wb = WidgetFactory.get(lcfdii);
if (wb instanceof FeatureDetailWidgetBuilder) {
return (FeatureDetailWidgetBuilder) wb;
} else {
GWT.log("Builder is not of type FeatureDetailWidgetBuilder: " + lcfdii.getBuilderName());
}
} else {
GWT.log("ClientWidgetInfo is not of class type LayerCustomFeatureDetailInfoInfo!! (layer type: "
+ layer.getServerLayerId() + ")");
}
}
}
} catch (Exception e) { // NOSONAR
Log.logError("Error getting custom detail widget: " + e.getMessage());
}
if (b == null) {
if (layer instanceof VectorLayer && defaultVectorFeatureDetailWidgetBuilder != null) {
b = defaultVectorFeatureDetailWidgetBuilder;
} else if (layer instanceof RasterLayer && defaultRasterFeatureDetailWidgetBuilder != null) {
b = defaultRasterFeatureDetailWidgetBuilder;
}
}
return b;
} } | public class class_name {
private static FeatureDetailWidgetBuilder getCustomBuilder(Layer<?> layer) {
FeatureDetailWidgetBuilder b = null;
try {
if (layer != null) {
ClientWidgetInfo cwi = layer.getLayerInfo().getWidgetInfo(WidgetBuilderInfo.IDENTIFIER);
if (cwi != null) {
if (cwi instanceof WidgetBuilderInfo) {
WidgetBuilderInfo lcfdii = (WidgetBuilderInfo) cwi;
WidgetBuilder wb = WidgetFactory.get(lcfdii);
if (wb instanceof FeatureDetailWidgetBuilder) {
return (FeatureDetailWidgetBuilder) wb; // depends on control dependency: [if], data = [none]
} else {
GWT.log("Builder is not of type FeatureDetailWidgetBuilder: " + lcfdii.getBuilderName()); // depends on control dependency: [if], data = [none]
}
} else {
GWT.log("ClientWidgetInfo is not of class type LayerCustomFeatureDetailInfoInfo!! (layer type: "
+ layer.getServerLayerId() + ")"); // depends on control dependency: [if], data = [none]
}
}
}
} catch (Exception e) { // NOSONAR
Log.logError("Error getting custom detail widget: " + e.getMessage());
} // depends on control dependency: [catch], data = [none]
if (b == null) {
if (layer instanceof VectorLayer && defaultVectorFeatureDetailWidgetBuilder != null) {
b = defaultVectorFeatureDetailWidgetBuilder; // depends on control dependency: [if], data = [none]
} else if (layer instanceof RasterLayer && defaultRasterFeatureDetailWidgetBuilder != null) {
b = defaultRasterFeatureDetailWidgetBuilder; // depends on control dependency: [if], data = [none]
}
}
return b;
} } |
public class class_name {
@Override
public void set(String propName, Object value) {
if (propName.equals("cn")) {
setCn(((String) value));
}
super.set(propName, value);
} } | public class class_name {
@Override
public void set(String propName, Object value) {
if (propName.equals("cn")) {
setCn(((String) value)); // depends on control dependency: [if], data = [none]
}
super.set(propName, value);
} } |
public class class_name {
public Set<MessageDescriptor<? extends M>> getSubtypes() {
if (subtypes != null) {
return subtypes;
}
Set<MessageDescriptor<? extends M>> list = new HashSet<MessageDescriptor<? extends M>>();
for (Provider<MessageDescriptor<? extends M>> provider : subtypeProviders) {
MessageDescriptor<? extends M> subtype = provider.get();
list.add(subtype);
}
Map<Enum<?>, MessageDescriptor<? extends M>> map = new HashMap<Enum<?>,
MessageDescriptor<? extends M>>();
for (MessageDescriptor<? extends M> subtype : list) {
map.put(subtype.getDiscriminatorValue(), subtype);
}
subtypes = ImmutableCollections.set(list);
subtypeMap = ImmutableCollections.map(map);
return subtypes;
} } | public class class_name {
public Set<MessageDescriptor<? extends M>> getSubtypes() {
if (subtypes != null) {
return subtypes; // depends on control dependency: [if], data = [none]
}
Set<MessageDescriptor<? extends M>> list = new HashSet<MessageDescriptor<? extends M>>();
for (Provider<MessageDescriptor<? extends M>> provider : subtypeProviders) {
MessageDescriptor<? extends M> subtype = provider.get();
list.add(subtype);
}
Map<Enum<?>, MessageDescriptor<? extends M>> map = new HashMap<Enum<?>,
MessageDescriptor<? extends M>>();
for (MessageDescriptor<? extends M> subtype : list) {
map.put(subtype.getDiscriminatorValue(), subtype);
}
subtypes = ImmutableCollections.set(list);
subtypeMap = ImmutableCollections.map(map);
return subtypes;
} } |
public class class_name {
public synchronized BigtableInstanceClient getInstanceAdminClient() throws IOException {
if (instanceAdminClient == null) {
ManagedChannel channel = createManagedPool(options.getAdminHost(), 1);
instanceAdminClient = new BigtableInstanceGrpcClient(channel);
}
return instanceAdminClient;
} } | public class class_name {
public synchronized BigtableInstanceClient getInstanceAdminClient() throws IOException {
if (instanceAdminClient == null) {
ManagedChannel channel = createManagedPool(options.getAdminHost(), 1);
instanceAdminClient = new BigtableInstanceGrpcClient(channel); // depends on control dependency: [if], data = [none]
}
return instanceAdminClient;
} } |
public class class_name {
public String getToken() {
if (isNull()){
return NullOidToken;
}
StringBuilder res = new StringBuilder();
res.append(_type.getToken()).append(SEPARATOR).append(_id);
if (hasMoment()) {
res.append(SEPARATOR).append(_moment);
}
return res.toString();
} } | public class class_name {
public String getToken() {
if (isNull()){
return NullOidToken; // depends on control dependency: [if], data = [none]
}
StringBuilder res = new StringBuilder();
res.append(_type.getToken()).append(SEPARATOR).append(_id);
if (hasMoment()) {
res.append(SEPARATOR).append(_moment); // depends on control dependency: [if], data = [none]
}
return res.toString();
} } |
public class class_name {
@Override
public List<byte[]> mGet(byte[]... keys) {
try {
if (isPipelined()) {
pipeline(new JedisResult(pipeline.mget(keys)));
return null;
}
return client.mget(keys);
} catch (Exception ex) {
throw convertException(ex);
}
} } | public class class_name {
@Override
public List<byte[]> mGet(byte[]... keys) {
try {
if (isPipelined()) {
pipeline(new JedisResult(pipeline.mget(keys))); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
return client.mget(keys); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
throw convertException(ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static ElementType[] getTargetType(Class<? extends Annotation> annotationType) {
final Target target = annotationType.getAnnotation(Target.class);
if (null == target) {
return new ElementType[] { ElementType.TYPE, //
ElementType.FIELD, //
ElementType.METHOD, //
ElementType.PARAMETER, //
ElementType.CONSTRUCTOR, //
ElementType.LOCAL_VARIABLE, //
ElementType.ANNOTATION_TYPE, //
ElementType.PACKAGE//
};
}
return target.value();
} } | public class class_name {
public static ElementType[] getTargetType(Class<? extends Annotation> annotationType) {
final Target target = annotationType.getAnnotation(Target.class);
if (null == target) {
return new ElementType[] { ElementType.TYPE, //
ElementType.FIELD, //
ElementType.METHOD, //
ElementType.PARAMETER, //
ElementType.CONSTRUCTOR, //
ElementType.LOCAL_VARIABLE, //
ElementType.ANNOTATION_TYPE, //
ElementType.PACKAGE//
};
// depends on control dependency: [if], data = [none]
}
return target.value();
} } |
public class class_name {
public void notifyOfError(Throwable error) {
if (error != null && this.error == null) {
this.error = error;
// this should wake up any blocking calls
try {
connectedSocket.close();
} catch (Throwable ignored) {}
try {
socket.close();
} catch (Throwable ignored) {}
}
} } | public class class_name {
public void notifyOfError(Throwable error) {
if (error != null && this.error == null) {
this.error = error; // depends on control dependency: [if], data = [none]
// this should wake up any blocking calls
try {
connectedSocket.close(); // depends on control dependency: [try], data = [none]
} catch (Throwable ignored) {} // depends on control dependency: [catch], data = [none]
try {
socket.close(); // depends on control dependency: [try], data = [none]
} catch (Throwable ignored) {} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
String generateAuthorizationHeader(String method, String url, HttpParameter[] params, String nonce, String timestamp, OAuthToken otoken) {
if (null == params) {
params = new HttpParameter[0];
}
List<HttpParameter> oauthHeaderParams = new ArrayList<HttpParameter>(5);
oauthHeaderParams.add(new HttpParameter("oauth_consumer_key", consumerKey));
oauthHeaderParams.add(OAUTH_SIGNATURE_METHOD);
oauthHeaderParams.add(new HttpParameter("oauth_timestamp", timestamp));
oauthHeaderParams.add(new HttpParameter("oauth_nonce", nonce));
oauthHeaderParams.add(new HttpParameter("oauth_version", "1.0"));
if (otoken != null) {
oauthHeaderParams.add(new HttpParameter("oauth_token", otoken.getToken()));
}
List<HttpParameter> signatureBaseParams = new ArrayList<HttpParameter>(oauthHeaderParams.size() + params.length);
signatureBaseParams.addAll(oauthHeaderParams);
if (!HttpParameter.containsFile(params)) {
signatureBaseParams.addAll(toParamList(params));
}
parseGetParameters(url, signatureBaseParams);
StringBuilder base = new StringBuilder(method).append("&")
.append(HttpParameter.encode(constructRequestURL(url))).append("&");
base.append(HttpParameter.encode(normalizeRequestParameters(signatureBaseParams)));
String oauthBaseString = base.toString();
logger.debug("OAuth base string: ", oauthBaseString);
String signature = generateSignature(oauthBaseString, otoken);
logger.debug("OAuth signature: ", signature);
oauthHeaderParams.add(new HttpParameter("oauth_signature", signature));
// http://oauth.net/core/1.0/#rfc.section.9.1.1
if (realm != null) {
oauthHeaderParams.add(new HttpParameter("realm", realm));
}
return "OAuth " + encodeParameters(oauthHeaderParams, ",", true);
} } | public class class_name {
String generateAuthorizationHeader(String method, String url, HttpParameter[] params, String nonce, String timestamp, OAuthToken otoken) {
if (null == params) {
params = new HttpParameter[0]; // depends on control dependency: [if], data = [none]
}
List<HttpParameter> oauthHeaderParams = new ArrayList<HttpParameter>(5);
oauthHeaderParams.add(new HttpParameter("oauth_consumer_key", consumerKey));
oauthHeaderParams.add(OAUTH_SIGNATURE_METHOD);
oauthHeaderParams.add(new HttpParameter("oauth_timestamp", timestamp));
oauthHeaderParams.add(new HttpParameter("oauth_nonce", nonce));
oauthHeaderParams.add(new HttpParameter("oauth_version", "1.0"));
if (otoken != null) {
oauthHeaderParams.add(new HttpParameter("oauth_token", otoken.getToken())); // depends on control dependency: [if], data = [none]
}
List<HttpParameter> signatureBaseParams = new ArrayList<HttpParameter>(oauthHeaderParams.size() + params.length);
signatureBaseParams.addAll(oauthHeaderParams);
if (!HttpParameter.containsFile(params)) {
signatureBaseParams.addAll(toParamList(params)); // depends on control dependency: [if], data = [none]
}
parseGetParameters(url, signatureBaseParams);
StringBuilder base = new StringBuilder(method).append("&")
.append(HttpParameter.encode(constructRequestURL(url))).append("&");
base.append(HttpParameter.encode(normalizeRequestParameters(signatureBaseParams)));
String oauthBaseString = base.toString();
logger.debug("OAuth base string: ", oauthBaseString);
String signature = generateSignature(oauthBaseString, otoken);
logger.debug("OAuth signature: ", signature);
oauthHeaderParams.add(new HttpParameter("oauth_signature", signature));
// http://oauth.net/core/1.0/#rfc.section.9.1.1
if (realm != null) {
oauthHeaderParams.add(new HttpParameter("realm", realm)); // depends on control dependency: [if], data = [none]
}
return "OAuth " + encodeParameters(oauthHeaderParams, ",", true);
} } |
public class class_name {
public static String getUniqueId(URI resourceUri, URI basePath) {
String result = null;
URI relativeUri = basePath.relativize(resourceUri);
// If it is relative the first part of the path is the Unique ID
if (!relativeUri.isAbsolute()) {
result = relativeUri.toASCIIString();
int slashIndex = result.indexOf('/');
int hashIndex = result.indexOf('#');
if (slashIndex > -1) {
result = result.substring(0, slashIndex);
} else if (hashIndex > -1) {
result = result.substring(0, hashIndex);
}
}
return result;
} } | public class class_name {
public static String getUniqueId(URI resourceUri, URI basePath) {
String result = null;
URI relativeUri = basePath.relativize(resourceUri);
// If it is relative the first part of the path is the Unique ID
if (!relativeUri.isAbsolute()) {
result = relativeUri.toASCIIString(); // depends on control dependency: [if], data = [none]
int slashIndex = result.indexOf('/');
int hashIndex = result.indexOf('#');
if (slashIndex > -1) {
result = result.substring(0, slashIndex); // depends on control dependency: [if], data = [none]
} else if (hashIndex > -1) {
result = result.substring(0, hashIndex); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
@JsonProperty("duration")
public Long getDuration() {
if (start != null && end != null) {
return start.until(end, ChronoUnit.MILLIS);
} else {
return null;
}
} } | public class class_name {
@JsonProperty("duration")
public Long getDuration() {
if (start != null && end != null) {
return start.until(end, ChronoUnit.MILLIS); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void onCanvasRightClicked(final MouseEvent me) {
_linkPainter.cancelLink();
final JPopupMenu popup = new JPopupMenu();
final Point point = me.getPoint();
final AnalysisJobBuilder analysisJobBuilder = _graphContext.getMainAnalysisJobBuilder();
final DataCleanerConfiguration configuration = analysisJobBuilder.getConfiguration();
// add component options
final Set<ComponentSuperCategory> superCategories =
configuration.getEnvironment().getDescriptorProvider().getComponentSuperCategories();
for (final ComponentSuperCategory superCategory : superCategories) {
final DescriptorMenuBuilder menuBuilder =
new DescriptorMenuBuilder(analysisJobBuilder, superCategory, point);
final JMenu menu = new JMenu(superCategory.getName());
menu.setIcon(IconUtils.getComponentSuperCategoryIcon(superCategory, IconUtils.ICON_SIZE_MENU_ITEM));
menuBuilder.addItemsToMenu(menu);
popup.add(menu);
}
// add (datastore and job) metadata option
{
final JMenuItem menuItem = WidgetFactory.createMenuItem("Job metadata", IconUtils.MODEL_METADATA);
menuItem.addActionListener(e -> {
final MetadataDialog dialog = new MetadataDialog(_windowContext, analysisJobBuilder);
dialog.open();
});
popup.add(menuItem);
}
popup.show(_graphContext.getVisualizationViewer(), me.getX(), me.getY());
} } | public class class_name {
public void onCanvasRightClicked(final MouseEvent me) {
_linkPainter.cancelLink();
final JPopupMenu popup = new JPopupMenu();
final Point point = me.getPoint();
final AnalysisJobBuilder analysisJobBuilder = _graphContext.getMainAnalysisJobBuilder();
final DataCleanerConfiguration configuration = analysisJobBuilder.getConfiguration();
// add component options
final Set<ComponentSuperCategory> superCategories =
configuration.getEnvironment().getDescriptorProvider().getComponentSuperCategories();
for (final ComponentSuperCategory superCategory : superCategories) {
final DescriptorMenuBuilder menuBuilder =
new DescriptorMenuBuilder(analysisJobBuilder, superCategory, point);
final JMenu menu = new JMenu(superCategory.getName());
menu.setIcon(IconUtils.getComponentSuperCategoryIcon(superCategory, IconUtils.ICON_SIZE_MENU_ITEM)); // depends on control dependency: [for], data = [superCategory]
menuBuilder.addItemsToMenu(menu); // depends on control dependency: [for], data = [none]
popup.add(menu); // depends on control dependency: [for], data = [none]
}
// add (datastore and job) metadata option
{
final JMenuItem menuItem = WidgetFactory.createMenuItem("Job metadata", IconUtils.MODEL_METADATA);
menuItem.addActionListener(e -> {
final MetadataDialog dialog = new MetadataDialog(_windowContext, analysisJobBuilder);
dialog.open();
});
popup.add(menuItem);
}
popup.show(_graphContext.getVisualizationViewer(), me.getX(), me.getY());
} } |
public class class_name {
public void register(Bundler bundler) {
if (bundler == null) throw new NullPointerException("Cannot register null bundler.");
if (runner.state == BundleServiceRunner.State.SAVING) {
throw new IllegalStateException("Cannot register during onSave");
}
if (bundlers.add(bundler)) bundler.onEnterScope(scope);
String mortarBundleKey = bundler.getMortarBundleKey();
if (mortarBundleKey == null || mortarBundleKey.trim().equals("")) {
throw new IllegalArgumentException(format("%s has null or empty bundle key", bundler));
}
switch (runner.state) {
case IDLE:
toBeLoaded.add(bundler);
runner.servicesToBeLoaded.add(this);
runner.finishLoading();
break;
case LOADING:
if (!toBeLoaded.contains(bundler)) {
toBeLoaded.add(bundler);
runner.servicesToBeLoaded.add(this);
}
break;
default:
throw new AssertionError("Unexpected state " + runner.state);
}
} } | public class class_name {
public void register(Bundler bundler) {
if (bundler == null) throw new NullPointerException("Cannot register null bundler.");
if (runner.state == BundleServiceRunner.State.SAVING) {
throw new IllegalStateException("Cannot register during onSave");
}
if (bundlers.add(bundler)) bundler.onEnterScope(scope);
String mortarBundleKey = bundler.getMortarBundleKey();
if (mortarBundleKey == null || mortarBundleKey.trim().equals("")) {
throw new IllegalArgumentException(format("%s has null or empty bundle key", bundler));
}
switch (runner.state) {
case IDLE:
toBeLoaded.add(bundler);
runner.servicesToBeLoaded.add(this);
runner.finishLoading();
break;
case LOADING:
if (!toBeLoaded.contains(bundler)) {
toBeLoaded.add(bundler); // depends on control dependency: [if], data = [none]
runner.servicesToBeLoaded.add(this); // depends on control dependency: [if], data = [none]
}
break;
default:
throw new AssertionError("Unexpected state " + runner.state);
}
} } |
public class class_name {
public void shutdown()
{
try {
thread.signalShutdown();
thread.join();
thread = null;
} catch (InterruptedException e) {
LOGGER.warn("Interrupted while waiting for queue shutdown, may not have completed cleanly", e);
}
} } | public class class_name {
public void shutdown()
{
try {
thread.signalShutdown(); // depends on control dependency: [try], data = [none]
thread.join(); // depends on control dependency: [try], data = [none]
thread = null; // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
LOGGER.warn("Interrupted while waiting for queue shutdown, may not have completed cleanly", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void readContents(int maxFrames) {
// Read GIF file content blocks.
boolean done = false;
while (!(done || err() || header.frameCount > maxFrames)) {
int code = read();
switch (code) {
// Image separator.
case 0x2C:
// The graphics control extension is optional, but will always come first if it exists.
// If one did
// exist, there will be a non-null current frame which we should use. However if one
// did not exist,
// the current frame will be null and we must create it here. See issue #134.
if (header.currentFrame == null) {
header.currentFrame = new GifFrame();
}
readBitmap();
break;
// Extension.
case 0x21:
code = read();
switch (code) {
// Graphics control extension.
case 0xf9:
// Start a new frame.
header.currentFrame = new GifFrame();
readGraphicControlExt();
break;
// Application extension.
case 0xff:
readBlock();
String app = "";
for (int i = 0; i < 11; i++) {
app += (char) block[i];
}
if (app.equals("NETSCAPE2.0")) {
readNetscapeExt();
} else {
// Don't care.
skip();
}
break;
// Comment extension.
case 0xfe:
skip();
break;
// Plain text extension.
case 0x01:
skip();
break;
// Uninteresting extension.
default:
skip();
}
break;
// Terminator.
case 0x3b:
done = true;
break;
// Bad byte, but keep going and see what happens break;
case 0x00:
default:
header.status = GifDecoder.STATUS_FORMAT_ERROR;
}
}
} } | public class class_name {
private void readContents(int maxFrames) {
// Read GIF file content blocks.
boolean done = false;
while (!(done || err() || header.frameCount > maxFrames)) {
int code = read();
switch (code) {
// Image separator.
case 0x2C:
// The graphics control extension is optional, but will always come first if it exists.
// If one did
// exist, there will be a non-null current frame which we should use. However if one
// did not exist,
// the current frame will be null and we must create it here. See issue #134.
if (header.currentFrame == null) {
header.currentFrame = new GifFrame(); // depends on control dependency: [if], data = [none]
}
readBitmap();
break;
// Extension.
case 0x21:
code = read();
switch (code) {
// Graphics control extension.
case 0xf9:
// Start a new frame.
header.currentFrame = new GifFrame();
readGraphicControlExt();
break;
// Application extension.
case 0xff:
readBlock();
String app = "";
for (int i = 0; i < 11; i++) {
app += (char) block[i]; // depends on control dependency: [for], data = [i]
}
if (app.equals("NETSCAPE2.0")) {
readNetscapeExt(); // depends on control dependency: [if], data = [none]
} else {
// Don't care.
skip(); // depends on control dependency: [if], data = [none]
}
break;
// Comment extension.
case 0xfe:
skip();
break;
// Plain text extension.
case 0x01:
skip();
break;
// Uninteresting extension.
default:
skip();
}
break;
// Terminator.
case 0x3b:
done = true;
break;
// Bad byte, but keep going and see what happens break;
case 0x00:
default:
header.status = GifDecoder.STATUS_FORMAT_ERROR;
}
}
} } |
public class class_name {
public BaseTable makeResourceTable(Record record, BaseTable table, BaseDatabase databaseBase, boolean bHierarchicalTable)
{ // Create a mirrored record in the locale database
Record record2 = (Record)ClassServiceUtility.getClassService().makeObjectFromClassName(record.getClass().getName());
if (record2 != null)
{
BaseTable table2 = databaseBase.makeTable(record2);
record2.setTable(table2);
RecordOwner recordOwner = Record.findRecordOwner(record);
record2.init(recordOwner);
recordOwner.removeRecord(record2); // This is okay as ResourceTable will remove this table on close.
record.setTable(table); // This is necessary to link-up ResourceTable
if (!bHierarchicalTable)
table = new org.jbundle.base.db.util.ResourceTable(null, record);
else
table = new org.jbundle.base.db.util.HierarchicalTable(null, record);
table.addTable(table2);
}
return table;
} } | public class class_name {
public BaseTable makeResourceTable(Record record, BaseTable table, BaseDatabase databaseBase, boolean bHierarchicalTable)
{ // Create a mirrored record in the locale database
Record record2 = (Record)ClassServiceUtility.getClassService().makeObjectFromClassName(record.getClass().getName());
if (record2 != null)
{
BaseTable table2 = databaseBase.makeTable(record2);
record2.setTable(table2); // depends on control dependency: [if], data = [none]
RecordOwner recordOwner = Record.findRecordOwner(record);
record2.init(recordOwner); // depends on control dependency: [if], data = [none]
recordOwner.removeRecord(record2); // This is okay as ResourceTable will remove this table on close. // depends on control dependency: [if], data = [(record2]
record.setTable(table); // This is necessary to link-up ResourceTable // depends on control dependency: [if], data = [none]
if (!bHierarchicalTable)
table = new org.jbundle.base.db.util.ResourceTable(null, record);
else
table = new org.jbundle.base.db.util.HierarchicalTable(null, record);
table.addTable(table2); // depends on control dependency: [if], data = [none]
}
return table;
} } |
public class class_name {
@Nullable
public Object toRawData(JavaType javaType) {
if (this.data.isEmpty()) {
return null;
}
if (PRIMITIVE_TYPES.contains(javaType.getRawClass())) {
return this.data.get(0).getValue();
}
return PropertyUtils.createObjectFromProperties(javaType.getRawClass(), //
this.data.stream().collect(Collectors.toMap(CollectionJsonData::getName, CollectionJsonData::getValue)));
} } | public class class_name {
@Nullable
public Object toRawData(JavaType javaType) {
if (this.data.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
if (PRIMITIVE_TYPES.contains(javaType.getRawClass())) {
return this.data.get(0).getValue(); // depends on control dependency: [if], data = [none]
}
return PropertyUtils.createObjectFromProperties(javaType.getRawClass(), //
this.data.stream().collect(Collectors.toMap(CollectionJsonData::getName, CollectionJsonData::getValue)));
} } |
public class class_name {
private void searchJars(Container moduleContainer, List<String> classList) {
Entry webinfLibEntry = moduleContainer.getEntry("WEB-INF/lib");
//No need to look for jars if there is no WEB-INF/lib
if (webinfLibEntry == null)
return;
try {
Container c = webinfLibEntry.adapt(Container.class);
Iterator<Entry> ie = c.iterator();
while (ie.hasNext()) {
Entry current = ie.next();
if (current.getName().endsWith(".jar")) {
//Again, convert to a container
try {
Container jarContainer = current.adapt(Container.class);
if (jarContainer != null) {
addConfigFileBeans(jarContainer.getEntry("META-INF/faces-config.xml"), classList);
//Spec says we have to look for any file in META-INF that ends with .faces-config.xml
Entry metainf = jarContainer.getEntry("META-INF");
if (metainf == null)
return;
Container metainfContainer = metainf.adapt(Container.class);
Iterator<Entry> metaInfIterator = metainfContainer.iterator();
while (metaInfIterator.hasNext()) {
Entry currentEntry = metaInfIterator.next();
if (currentEntry.getName().endsWith(".faces-config.xml")) {
addConfigFileBeans(currentEntry, classList);
}
}
}
} catch (UnableToAdaptException e) {
if (log.isLoggable(Level.FINE)) {
log.logp(Level.FINE, CLASS_NAME, "searchJars", "unable to adapt jar or META-INF dir in jar named " + current.getName() + " to a container", e);
}
}
}
}
} catch (UnableToAdaptException e) {
if (log.isLoggable(Level.FINE)) {
log.logp(Level.FINE, CLASS_NAME, "searchJars", "unable to adapt WEB-INF/lib to a container", e);
}
}
} } | public class class_name {
private void searchJars(Container moduleContainer, List<String> classList) {
Entry webinfLibEntry = moduleContainer.getEntry("WEB-INF/lib");
//No need to look for jars if there is no WEB-INF/lib
if (webinfLibEntry == null)
return;
try {
Container c = webinfLibEntry.adapt(Container.class);
Iterator<Entry> ie = c.iterator();
while (ie.hasNext()) {
Entry current = ie.next();
if (current.getName().endsWith(".jar")) {
//Again, convert to a container
try {
Container jarContainer = current.adapt(Container.class);
if (jarContainer != null) {
addConfigFileBeans(jarContainer.getEntry("META-INF/faces-config.xml"), classList); // depends on control dependency: [if], data = [(jarContainer]
//Spec says we have to look for any file in META-INF that ends with .faces-config.xml
Entry metainf = jarContainer.getEntry("META-INF");
if (metainf == null)
return;
Container metainfContainer = metainf.adapt(Container.class);
Iterator<Entry> metaInfIterator = metainfContainer.iterator();
while (metaInfIterator.hasNext()) {
Entry currentEntry = metaInfIterator.next();
if (currentEntry.getName().endsWith(".faces-config.xml")) {
addConfigFileBeans(currentEntry, classList);
}
}
}
} catch (UnableToAdaptException e) {
if (log.isLoggable(Level.FINE)) {
log.logp(Level.FINE, CLASS_NAME, "searchJars", "unable to adapt jar or META-INF dir in jar named " + current.getName() + " to a container", e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
}
} catch (UnableToAdaptException e) {
if (log.isLoggable(Level.FINE)) {
log.logp(Level.FINE, CLASS_NAME, "searchJars", "unable to adapt WEB-INF/lib to a container", e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
void handleFileTreeValueChange() {
Item resourceItem = m_treeContainer.getItem(m_fileTree.getValue());
if (resourceItem != null) {
if ((resourceItem.getItemProperty(CmsResourceTableProperty.PROPERTY_DISABLED).getValue() != null)
&& ((Boolean)resourceItem.getItemProperty(
CmsResourceTableProperty.PROPERTY_DISABLED).getValue()).booleanValue()) {
// in case the folder is disabled due to missing visibility, reset the value to the previous one
m_fileTree.setValue(m_selectTreeFolder);
} else {
m_selectTreeFolder = (CmsUUID)m_fileTree.getValue();
}
}
} } | public class class_name {
void handleFileTreeValueChange() {
Item resourceItem = m_treeContainer.getItem(m_fileTree.getValue());
if (resourceItem != null) {
if ((resourceItem.getItemProperty(CmsResourceTableProperty.PROPERTY_DISABLED).getValue() != null)
&& ((Boolean)resourceItem.getItemProperty(
CmsResourceTableProperty.PROPERTY_DISABLED).getValue()).booleanValue()) {
// in case the folder is disabled due to missing visibility, reset the value to the previous one
m_fileTree.setValue(m_selectTreeFolder); // depends on control dependency: [if], data = [none]
} else {
m_selectTreeFolder = (CmsUUID)m_fileTree.getValue(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static void printThreadStackTrace(TraceComponent logger, Thread thread) {
if (logger.isDebugEnabled()) {
chTrace.traceThreadStack(logger, thread);
}
} } | public class class_name {
public static void printThreadStackTrace(TraceComponent logger, Thread thread) {
if (logger.isDebugEnabled()) {
chTrace.traceThreadStack(logger, thread); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private byte[] toBytes(Object object, Schema writer, Integer writerVersion) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Encoder encoder = new BinaryEncoder(output);
GenericDatumWriter<Object> datumWriter = null;
output.write(writerVersion.byteValue());
try {
datumWriter = new GenericDatumWriter<Object>(writer);
datumWriter.write(object, encoder);
encoder.flush();
} catch(IOException e) {
throw new SerializationException(e);
} catch(SerializationException sE) {
throw sE;
} finally {
SerializationUtils.close(output);
}
return output.toByteArray();
} } | public class class_name {
private byte[] toBytes(Object object, Schema writer, Integer writerVersion) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Encoder encoder = new BinaryEncoder(output);
GenericDatumWriter<Object> datumWriter = null;
output.write(writerVersion.byteValue());
try {
datumWriter = new GenericDatumWriter<Object>(writer); // depends on control dependency: [try], data = [none]
datumWriter.write(object, encoder); // depends on control dependency: [try], data = [none]
encoder.flush(); // depends on control dependency: [try], data = [none]
} catch(IOException e) {
throw new SerializationException(e);
} catch(SerializationException sE) { // depends on control dependency: [catch], data = [none]
throw sE;
} finally { // depends on control dependency: [catch], data = [none]
SerializationUtils.close(output);
}
return output.toByteArray();
} } |
public class class_name {
private static CronField parseField(String field, int minValue, int maxValue) {
// asterisk: *
if ("*".equals(field)) {
return new CronField(minValue, maxValue, 1, true);
}
// asterisk with step: */3
if (field.startsWith("*/")) {
int step = Integer.parseInt(field.substring(2));
if(step > 0 & step <= maxValue) {
return new CronField(minValue, maxValue, step);
} else {
throw new IllegalArgumentException("Illegal step: '" + step + "'");
}
}
// simple number: 2
if (field.matches("[0-9]{1,2}")) {
int value = Integer.parseInt(field);
if ((value >= minValue) && (value <= maxValue)) {
return new CronField(value, value, 1);
} else {
throw new IllegalArgumentException("Parameter not within range: '" + field + "'");
}
}
// range: 4-6
if (field.matches("[0-9]{1,2}-[0-9]{1,2}")) {
String[] rangeValues = field.split("[-]+");
if (rangeValues.length == 2) {
int start = Integer.parseInt(rangeValues[0]);
int end = Integer.parseInt(rangeValues[1]);
if ((start >= minValue) && (start <= maxValue) && (end >= minValue) && (end <= maxValue)) {
return new CronField(start, end, 1);
} else {
throw new IllegalArgumentException("Parameters not within range: '" + field + "'");
}
} else {
throw new IllegalArgumentException("Invalid range: '" + field + "'");
}
}
// list: 4,6
if (field.contains(",")) {
final String[] listValues = field.split("[,]+");
final List<Integer> values = new LinkedList<>();
for (final String value : listValues) {
try {
values.add(Integer.parseInt(value));
} catch (Throwable t) {
throw new IllegalArgumentException("Invalid list value: '" + value + "'");
}
}
return new CronField(values);
}
// range with step: 4-6/3
if (field.matches("[0-9]{1,2}-[0-9]{1,2}/[0-9]{1,2}")) {
throw new UnsupportedOperationException("Steps are not supported yet.");
}
throw new IllegalArgumentException("Invalid field: '" + field + "'");
} } | public class class_name {
private static CronField parseField(String field, int minValue, int maxValue) {
// asterisk: *
if ("*".equals(field)) {
return new CronField(minValue, maxValue, 1, true); // depends on control dependency: [if], data = [none]
}
// asterisk with step: */3
if (field.startsWith("*/")) {
int step = Integer.parseInt(field.substring(2));
if(step > 0 & step <= maxValue) {
return new CronField(minValue, maxValue, step); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Illegal step: '" + step + "'");
}
}
// simple number: 2
if (field.matches("[0-9]{1,2}")) {
int value = Integer.parseInt(field);
if ((value >= minValue) && (value <= maxValue)) {
return new CronField(value, value, 1); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Parameter not within range: '" + field + "'");
}
}
// range: 4-6
if (field.matches("[0-9]{1,2}-[0-9]{1,2}")) {
String[] rangeValues = field.split("[-]+");
if (rangeValues.length == 2) {
int start = Integer.parseInt(rangeValues[0]);
int end = Integer.parseInt(rangeValues[1]);
if ((start >= minValue) && (start <= maxValue) && (end >= minValue) && (end <= maxValue)) {
return new CronField(start, end, 1); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Parameters not within range: '" + field + "'");
}
} else {
throw new IllegalArgumentException("Invalid range: '" + field + "'");
}
}
// list: 4,6
if (field.contains(",")) {
final String[] listValues = field.split("[,]+");
final List<Integer> values = new LinkedList<>();
for (final String value : listValues) {
try {
values.add(Integer.parseInt(value)); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
throw new IllegalArgumentException("Invalid list value: '" + value + "'");
} // depends on control dependency: [catch], data = [none]
}
return new CronField(values); // depends on control dependency: [if], data = [none]
}
// range with step: 4-6/3
if (field.matches("[0-9]{1,2}-[0-9]{1,2}/[0-9]{1,2}")) {
throw new UnsupportedOperationException("Steps are not supported yet.");
}
throw new IllegalArgumentException("Invalid field: '" + field + "'");
} } |
public class class_name {
public boolean canBypassConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
Assert.notNull(targetType, "The targetType to convert to cannot be null");
if (sourceType == null) {
return true;
}
GenericConverter converter = getConverter(sourceType, targetType);
return (converter == NO_OP_CONVERTER);
} } | public class class_name {
public boolean canBypassConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
Assert.notNull(targetType, "The targetType to convert to cannot be null");
if (sourceType == null) {
return true; // depends on control dependency: [if], data = [none]
}
GenericConverter converter = getConverter(sourceType, targetType);
return (converter == NO_OP_CONVERTER);
} } |
public class class_name {
@Override
public boolean set(HttpCookie cookie, byte[] attribValue) {
if (null == cookie || null == attribValue || 0 == attribValue.length) {
return false;
}
// Start parsing the byte array here to set the expiry date
// For example: 24-Jun-03 16:01:45 GMT is a valid attrib value
// Using the HttpDateFormat class
try {
Date expiryDate = HttpDispatcher.getDateFormatter().parseTime(attribValue);
long remainingTime = expiryDate.getTime() - HttpDispatcher.getApproxTime();
if (-1 < remainingTime) {
cookie.setMaxAge((int) (remainingTime / 1000L));
} else {
// PK62826 - old date will translate to a 0 max-age (immediate
// expiration)
cookie.setMaxAge(0);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Expires/max-age set to " + cookie.getMaxAge());
}
return true;
} catch (ParseException e) {
// No FFDC required
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Error parsing expires date: " + GenericUtils.getEnglishString(attribValue));
}
}
return false;
} } | public class class_name {
@Override
public boolean set(HttpCookie cookie, byte[] attribValue) {
if (null == cookie || null == attribValue || 0 == attribValue.length) {
return false; // depends on control dependency: [if], data = [none]
}
// Start parsing the byte array here to set the expiry date
// For example: 24-Jun-03 16:01:45 GMT is a valid attrib value
// Using the HttpDateFormat class
try {
Date expiryDate = HttpDispatcher.getDateFormatter().parseTime(attribValue);
long remainingTime = expiryDate.getTime() - HttpDispatcher.getApproxTime();
if (-1 < remainingTime) {
cookie.setMaxAge((int) (remainingTime / 1000L)); // depends on control dependency: [if], data = [none]
} else {
// PK62826 - old date will translate to a 0 max-age (immediate
// expiration)
cookie.setMaxAge(0); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Expires/max-age set to " + cookie.getMaxAge()); // depends on control dependency: [if], data = [none]
}
return true; // depends on control dependency: [try], data = [none]
} catch (ParseException e) {
// No FFDC required
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Error parsing expires date: " + GenericUtils.getEnglishString(attribValue)); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
return false;
} } |
public class class_name {
public static String getNotEmptyParameter(HttpServletRequest request, String paramName) {
String result = request.getParameter(paramName);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {
result = null;
}
return result;
} } | public class class_name {
public static String getNotEmptyParameter(HttpServletRequest request, String paramName) {
String result = request.getParameter(paramName);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {
result = null; // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
@Override
public INDArray getWordVectors(@NonNull Collection<String> labels) {
int indexes[] = new int[labels.size()];
int cnt = 0;
boolean useIndexUnknown = useUnknown && vocab.containsWord(getUNK());
for (String label : labels) {
if (vocab.containsWord(label)) {
indexes[cnt] = vocab.indexOf(label);
} else
indexes[cnt] = useIndexUnknown ? vocab.indexOf(getUNK()) : -1;
cnt++;
}
while (ArrayUtils.contains(indexes, -1)) {
indexes = ArrayUtils.removeElement(indexes, -1);
}
if (indexes.length == 0) {
return Nd4j.empty(((InMemoryLookupTable)lookupTable).getSyn0().dataType());
}
INDArray result = Nd4j.pullRows(lookupTable.getWeights(), 1, indexes);
return result;
} } | public class class_name {
@Override
public INDArray getWordVectors(@NonNull Collection<String> labels) {
int indexes[] = new int[labels.size()];
int cnt = 0;
boolean useIndexUnknown = useUnknown && vocab.containsWord(getUNK());
for (String label : labels) {
if (vocab.containsWord(label)) {
indexes[cnt] = vocab.indexOf(label); // depends on control dependency: [if], data = [none]
} else
indexes[cnt] = useIndexUnknown ? vocab.indexOf(getUNK()) : -1;
cnt++; // depends on control dependency: [for], data = [none]
}
while (ArrayUtils.contains(indexes, -1)) {
indexes = ArrayUtils.removeElement(indexes, -1); // depends on control dependency: [while], data = [none]
}
if (indexes.length == 0) {
return Nd4j.empty(((InMemoryLookupTable)lookupTable).getSyn0().dataType()); // depends on control dependency: [if], data = [none]
}
INDArray result = Nd4j.pullRows(lookupTable.getWeights(), 1, indexes);
return result;
} } |
public class class_name {
private boolean isEqual(Object fld1, Object fld2)
{
if (fld1 == null || fld2 == null)
{
return (fld1 == fld2);
}
else if ((fld1 instanceof BigDecimal) && (fld2 instanceof BigDecimal))
{
return (((BigDecimal) fld1).compareTo((BigDecimal) fld2) == 0);
}
else if ((fld1 instanceof Date) && (fld2 instanceof Date))
{
return (((Date) fld1).getTime() == ((Date) fld2).getTime());
}
else
{
return fld1.equals(fld2);
}
} } | public class class_name {
private boolean isEqual(Object fld1, Object fld2)
{
if (fld1 == null || fld2 == null)
{
return (fld1 == fld2);
// depends on control dependency: [if], data = [(fld1]
}
else if ((fld1 instanceof BigDecimal) && (fld2 instanceof BigDecimal))
{
return (((BigDecimal) fld1).compareTo((BigDecimal) fld2) == 0);
// depends on control dependency: [if], data = [none]
}
else if ((fld1 instanceof Date) && (fld2 instanceof Date))
{
return (((Date) fld1).getTime() == ((Date) fld2).getTime());
// depends on control dependency: [if], data = [none]
}
else
{
return fld1.equals(fld2);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Properties getProperties(final String propertiesPath) throws PropertiesException {
Properties properties;
String propertiesFilePath = getPropertiesFilePath(propertiesPath);
if (propertiesFilePath == null) {
throw new PropertiesException(String.format(
"Loading '%s' properties failed, no such properties.", propertiesPath));
}
FileInputStream fileInputStream = null;
try {
properties = new Properties();
fileInputStream = new FileInputStream(propertiesFilePath);
properties.load(fileInputStream);
fileInputStream.close();
return properties;
} catch (Exception e) {
try {
if (fileInputStream != null)
fileInputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new PropertiesException(String.format("Loading '%s' properties failed.",
propertiesPath), e);
}
} } | public class class_name {
public static Properties getProperties(final String propertiesPath) throws PropertiesException {
Properties properties;
String propertiesFilePath = getPropertiesFilePath(propertiesPath);
if (propertiesFilePath == null) {
throw new PropertiesException(String.format(
"Loading '%s' properties failed, no such properties.", propertiesPath));
}
FileInputStream fileInputStream = null;
try {
properties = new Properties();
fileInputStream = new FileInputStream(propertiesFilePath);
properties.load(fileInputStream);
fileInputStream.close();
return properties;
} catch (Exception e) {
try {
if (fileInputStream != null)
fileInputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
} // depends on control dependency: [catch], data = [none]
throw new PropertiesException(String.format("Loading '%s' properties failed.",
propertiesPath), e);
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public T create(Map<String, Object> data)
{
Object[] args = new Object[arguments.length];
for(int i=0, n=args.length; i<n; i++)
{
args[i] = arguments[i].getValue(data);
}
try
{
return (T) raw.newInstance(args);
}
catch(IllegalArgumentException e)
{
throw new SerializationException("Unable to create; " + e.getMessage(), e);
}
catch(InstantiationException e)
{
throw new SerializationException("Unable to create; " + e.getMessage(), e);
}
catch(IllegalAccessException e)
{
throw new SerializationException("Unable to create; " + e.getMessage(), e);
}
catch(InvocationTargetException e)
{
throw new SerializationException("Unable to create; " + e.getCause().getMessage(), e.getCause());
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public T create(Map<String, Object> data)
{
Object[] args = new Object[arguments.length];
for(int i=0, n=args.length; i<n; i++)
{
args[i] = arguments[i].getValue(data); // depends on control dependency: [for], data = [i]
}
try
{
return (T) raw.newInstance(args); // depends on control dependency: [try], data = [none]
}
catch(IllegalArgumentException e)
{
throw new SerializationException("Unable to create; " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
catch(InstantiationException e)
{
throw new SerializationException("Unable to create; " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
catch(IllegalAccessException e)
{
throw new SerializationException("Unable to create; " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
catch(InvocationTargetException e)
{
throw new SerializationException("Unable to create; " + e.getCause().getMessage(), e.getCause());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void startElementNode(final Attributes attributes) {
LOG.debug("Found node");
try {
this.nodeStack.push(this.newNode(this.nodeStack.peek(), attributes));
} catch (final RepositoryException e) {
throw new AssertionError("Could not create node", e);
}
} } | public class class_name {
private void startElementNode(final Attributes attributes) {
LOG.debug("Found node");
try {
this.nodeStack.push(this.newNode(this.nodeStack.peek(), attributes)); // depends on control dependency: [try], data = [none]
} catch (final RepositoryException e) {
throw new AssertionError("Could not create node", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static synchronized void initializeLog4JSubSystem(String configFile)
{
LoggerFactory.getBootLogger().info("Initializing Log4J using file: '" + configFile + "'");
if(configFile == null || "".equals(configFile.trim()))
{
// no configuration available
LoggerFactory.getBootLogger().warn("No log4j configuration file specified");
}
else
{
// try resource look in classpath
URL url = ClassHelper.getResource(configFile);
LoggerFactory.getBootLogger().info("Initializing Log4J : resource from config file:" + url);
if (url != null)
{
PropertyConfigurator.configure(url);
}
// if file is not in classpath try ordinary filesystem lookup
else
{
PropertyConfigurator.configure(configFile);
}
}
log4jConfigured = true;
} } | public class class_name {
private static synchronized void initializeLog4JSubSystem(String configFile)
{
LoggerFactory.getBootLogger().info("Initializing Log4J using file: '" + configFile + "'");
if(configFile == null || "".equals(configFile.trim()))
{
// no configuration available
LoggerFactory.getBootLogger().warn("No log4j configuration file specified");
// depends on control dependency: [if], data = [none]
}
else
{
// try resource look in classpath
URL url = ClassHelper.getResource(configFile);
LoggerFactory.getBootLogger().info("Initializing Log4J : resource from config file:" + url);
// depends on control dependency: [if], data = [none]
if (url != null)
{
PropertyConfigurator.configure(url);
// depends on control dependency: [if], data = [(url]
}
// if file is not in classpath try ordinary filesystem lookup
else
{
PropertyConfigurator.configure(configFile);
// depends on control dependency: [if], data = [none]
}
}
log4jConfigured = true;
} } |
public class class_name {
public String rowGet(String key) {
String resolvedKey = resolveRowKey(key);
String cachedValue = rowMapCache.get(resolvedKey);
if (cachedValue != null) {
return cachedValue;
}
String value = rowMap.get(resolvedKey);
if (value == null && parent != null) {
value = parent.rowGet(resolvedKey);
}
if (value == null) {
return null;
}
String expandedString = expand(value, false);
rowMapCache.put(resolvedKey, expandedString);
return expandedString;
} } | public class class_name {
public String rowGet(String key) {
String resolvedKey = resolveRowKey(key);
String cachedValue = rowMapCache.get(resolvedKey);
if (cachedValue != null) {
return cachedValue; // depends on control dependency: [if], data = [none]
}
String value = rowMap.get(resolvedKey);
if (value == null && parent != null) {
value = parent.rowGet(resolvedKey); // depends on control dependency: [if], data = [none]
}
if (value == null) {
return null; // depends on control dependency: [if], data = [none]
}
String expandedString = expand(value, false);
rowMapCache.put(resolvedKey, expandedString);
return expandedString;
} } |
public class class_name {
public void rawWarning(int pos, String msg) {
if (nwarnings < MaxWarnings && emitWarnings) {
printRawError(pos, "warning: " + msg);
}
prompt();
nwarnings++;
errWriter.flush();
} } | public class class_name {
public void rawWarning(int pos, String msg) {
if (nwarnings < MaxWarnings && emitWarnings) {
printRawError(pos, "warning: " + msg); // depends on control dependency: [if], data = [none]
}
prompt();
nwarnings++;
errWriter.flush();
} } |
public class class_name {
protected List<Locale> getContentLocales(CmsObject cms, CmsResource resource, I_CmsExtractionResult extraction) {
// try to detect locale by filename
Locale detectedLocale = CmsStringUtil.getLocaleForName(resource.getRootPath());
if (!OpenCms.getLocaleManager().getAvailableLocales(cms, resource).contains(detectedLocale)) {
detectedLocale = null;
}
// try to detect locale by language detector
if (getIndex().isLanguageDetection()
&& (detectedLocale == null)
&& (extraction != null)
&& (extraction.getContent() != null)) {
detectedLocale = CmsStringUtil.getLocaleForText(extraction.getContent());
}
// take the detected locale or use the first configured default locale for this resource
List<Locale> result = new ArrayList<Locale>();
if (detectedLocale != null) {
// take the found locale
result.add(detectedLocale);
} else {
// take all locales set via locale-available or the configured default locales as fall-back for this resource
result.addAll(OpenCms.getLocaleManager().getAvailableLocales(cms, resource));
LOG.debug(Messages.get().getBundle().key(Messages.LOG_LANGUAGE_DETECTION_FAILED_1, resource));
}
return result;
} } | public class class_name {
protected List<Locale> getContentLocales(CmsObject cms, CmsResource resource, I_CmsExtractionResult extraction) {
// try to detect locale by filename
Locale detectedLocale = CmsStringUtil.getLocaleForName(resource.getRootPath());
if (!OpenCms.getLocaleManager().getAvailableLocales(cms, resource).contains(detectedLocale)) {
detectedLocale = null; // depends on control dependency: [if], data = [none]
}
// try to detect locale by language detector
if (getIndex().isLanguageDetection()
&& (detectedLocale == null)
&& (extraction != null)
&& (extraction.getContent() != null)) {
detectedLocale = CmsStringUtil.getLocaleForText(extraction.getContent()); // depends on control dependency: [if], data = [none]
}
// take the detected locale or use the first configured default locale for this resource
List<Locale> result = new ArrayList<Locale>();
if (detectedLocale != null) {
// take the found locale
result.add(detectedLocale); // depends on control dependency: [if], data = [(detectedLocale]
} else {
// take all locales set via locale-available or the configured default locales as fall-back for this resource
result.addAll(OpenCms.getLocaleManager().getAvailableLocales(cms, resource)); // depends on control dependency: [if], data = [none]
LOG.debug(Messages.get().getBundle().key(Messages.LOG_LANGUAGE_DETECTION_FAILED_1, resource)); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public final String loadProfileName() {
final String profileEnvVarOverride = getEnvProfileName();
if (!StringUtils.isNullOrEmpty(profileEnvVarOverride)) {
return profileEnvVarOverride;
} else {
final String profileSysPropOverride = getSysPropertyProfileName();
if (!StringUtils.isNullOrEmpty(profileSysPropOverride)) {
return profileSysPropOverride;
} else {
return DEFAULT_PROFILE_NAME;
}
}
} } | public class class_name {
public final String loadProfileName() {
final String profileEnvVarOverride = getEnvProfileName();
if (!StringUtils.isNullOrEmpty(profileEnvVarOverride)) {
return profileEnvVarOverride; // depends on control dependency: [if], data = [none]
} else {
final String profileSysPropOverride = getSysPropertyProfileName();
if (!StringUtils.isNullOrEmpty(profileSysPropOverride)) {
return profileSysPropOverride; // depends on control dependency: [if], data = [none]
} else {
return DEFAULT_PROFILE_NAME; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
if (builder.tableNames == null) {
throw new SQLiteHelperException("The array of String tableNames can't be null!!");
}
builder.onUpgradeCallback.onUpgrade(db, oldVersion, newVersion);
} catch (SQLiteHelperException e) {
Log.e(this.getClass().toString(), Log.getStackTraceString(e), e);
}
} } | public class class_name {
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
if (builder.tableNames == null) {
throw new SQLiteHelperException("The array of String tableNames can't be null!!");
}
builder.onUpgradeCallback.onUpgrade(db, oldVersion, newVersion); // depends on control dependency: [try], data = [none]
} catch (SQLiteHelperException e) {
Log.e(this.getClass().toString(), Log.getStackTraceString(e), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(UnprocessedTraceSegment unprocessedTraceSegment, ProtocolMarshaller protocolMarshaller) {
if (unprocessedTraceSegment == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(unprocessedTraceSegment.getId(), ID_BINDING);
protocolMarshaller.marshall(unprocessedTraceSegment.getErrorCode(), ERRORCODE_BINDING);
protocolMarshaller.marshall(unprocessedTraceSegment.getMessage(), MESSAGE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UnprocessedTraceSegment unprocessedTraceSegment, ProtocolMarshaller protocolMarshaller) {
if (unprocessedTraceSegment == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(unprocessedTraceSegment.getId(), ID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(unprocessedTraceSegment.getErrorCode(), ERRORCODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(unprocessedTraceSegment.getMessage(), MESSAGE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(ContainerProperties containerProperties, ProtocolMarshaller protocolMarshaller) {
if (containerProperties == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(containerProperties.getImage(), IMAGE_BINDING);
protocolMarshaller.marshall(containerProperties.getVcpus(), VCPUS_BINDING);
protocolMarshaller.marshall(containerProperties.getMemory(), MEMORY_BINDING);
protocolMarshaller.marshall(containerProperties.getCommand(), COMMAND_BINDING);
protocolMarshaller.marshall(containerProperties.getJobRoleArn(), JOBROLEARN_BINDING);
protocolMarshaller.marshall(containerProperties.getVolumes(), VOLUMES_BINDING);
protocolMarshaller.marshall(containerProperties.getEnvironment(), ENVIRONMENT_BINDING);
protocolMarshaller.marshall(containerProperties.getMountPoints(), MOUNTPOINTS_BINDING);
protocolMarshaller.marshall(containerProperties.getReadonlyRootFilesystem(), READONLYROOTFILESYSTEM_BINDING);
protocolMarshaller.marshall(containerProperties.getPrivileged(), PRIVILEGED_BINDING);
protocolMarshaller.marshall(containerProperties.getUlimits(), ULIMITS_BINDING);
protocolMarshaller.marshall(containerProperties.getUser(), USER_BINDING);
protocolMarshaller.marshall(containerProperties.getInstanceType(), INSTANCETYPE_BINDING);
protocolMarshaller.marshall(containerProperties.getResourceRequirements(), RESOURCEREQUIREMENTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ContainerProperties containerProperties, ProtocolMarshaller protocolMarshaller) {
if (containerProperties == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(containerProperties.getImage(), IMAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getVcpus(), VCPUS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getMemory(), MEMORY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getCommand(), COMMAND_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getJobRoleArn(), JOBROLEARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getVolumes(), VOLUMES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getEnvironment(), ENVIRONMENT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getMountPoints(), MOUNTPOINTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getReadonlyRootFilesystem(), READONLYROOTFILESYSTEM_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getPrivileged(), PRIVILEGED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getUlimits(), ULIMITS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getUser(), USER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getInstanceType(), INSTANCETYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerProperties.getResourceRequirements(), RESOURCEREQUIREMENTS_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 CacheSubnetGroup withSubnets(Subnet... subnets) {
if (this.subnets == null) {
setSubnets(new com.amazonaws.internal.SdkInternalList<Subnet>(subnets.length));
}
for (Subnet ele : subnets) {
this.subnets.add(ele);
}
return this;
} } | public class class_name {
public CacheSubnetGroup withSubnets(Subnet... subnets) {
if (this.subnets == null) {
setSubnets(new com.amazonaws.internal.SdkInternalList<Subnet>(subnets.length)); // depends on control dependency: [if], data = [none]
}
for (Subnet ele : subnets) {
this.subnets.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void onReadFailure(Throwable t) {
ConnectionState event = null;
synchronized (this) {
if (this.state == ConnectionState.CLOSED) {
// already closed
return;
}
// Build out Close Reason
String reason = "WebSocket Read Failure";
if (t instanceof EOFException) {
reason = "WebSocket Read EOF";
Throwable cause = t.getCause();
if ((cause != null) && (StringUtils.hasText(cause.getMessage()))) {
reason = "EOF: " + cause.getMessage();
}
} else {
if (StringUtils.hasText(t.getMessage())) {
reason = t.getMessage();
}
}
CloseInfo close = new CloseInfo(StatusCode.ABNORMAL, reason);
finalClose.compareAndSet(null, close);
this.cleanClose = false;
this.state = ConnectionState.CLOSED;
this.closeInfo = close;
this.inputAvailable = false;
this.outputAvailable = false;
this.closeHandshakeSource = CloseHandshakeSource.ABNORMAL;
event = this.state;
}
notifyStateListeners(event);
} } | public class class_name {
public void onReadFailure(Throwable t) {
ConnectionState event = null;
synchronized (this) {
if (this.state == ConnectionState.CLOSED) {
// already closed
return; // depends on control dependency: [if], data = [none]
}
// Build out Close Reason
String reason = "WebSocket Read Failure";
if (t instanceof EOFException) {
reason = "WebSocket Read EOF"; // depends on control dependency: [if], data = [none]
Throwable cause = t.getCause();
if ((cause != null) && (StringUtils.hasText(cause.getMessage()))) {
reason = "EOF: " + cause.getMessage(); // depends on control dependency: [if], data = [none]
}
} else {
if (StringUtils.hasText(t.getMessage())) {
reason = t.getMessage(); // depends on control dependency: [if], data = [none]
}
}
CloseInfo close = new CloseInfo(StatusCode.ABNORMAL, reason);
finalClose.compareAndSet(null, close);
this.cleanClose = false;
this.state = ConnectionState.CLOSED;
this.closeInfo = close;
this.inputAvailable = false;
this.outputAvailable = false;
this.closeHandshakeSource = CloseHandshakeSource.ABNORMAL;
event = this.state;
}
notifyStateListeners(event);
} } |
public class class_name {
public BufferedImage filter(BufferedImage src, BufferedImage dest) {
if (dest == null) {
dest = createCompatibleDestImage(src, null);
}
// Make image faded/washed out/red-ish
// DARK WARM
float[] scales = new float[] { 2.2f, 2.0f, 1.55f};
float[] offsets = new float[] {-20.0f, -90.0f, -110.0f};
// BRIGHT NATURAL
// float[] scales = new float[] { 1.1f, .9f, .7f};
// float[] offsets = new float[] {20, 30, 80};
// Faded, old-style
// float[] scales = new float[] { 1.1f, .7f, .3f};
// float[] offsets = new float[] {20, 30, 80};
// float[] scales = new float[] { 1.2f, .4f, .4f};
// float[] offsets = new float[] {0, 120, 120};
// BRIGHT WARM
// float[] scales = new float[] {1.1f, .8f, 1.6f};
// float[] offsets = new float[] {60, 70, -80};
BufferedImage image = new RescaleOp(scales, offsets, getRenderingHints()).filter(src, null);
// Blur
image = ImageUtil.blur(image, 2.5f);
Graphics2D g = dest.createGraphics();
try {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g.drawImage(image, 0, 0, null);
// Rotate it slightly for a more analogue feeling
double angle = .0055;
g.rotate(angle);
// Scratches
g.setComposite(AlphaComposite.SrcOver.derive(.025f));
for (int i = 0; i < 100; i++) {
g.setColor(random.nextBoolean() ? Color.WHITE : Color.BLACK);
g.setStroke(new BasicStroke(random.nextFloat() * 2f));
int x = random.nextInt(image.getWidth());
int off = random.nextInt(100);
for (int j = random.nextInt(3); j > 0; j--) {
g.drawLine(x + j, 0, x + off - 50 + j, image.getHeight());
}
}
// Vignette/border
g.setComposite(AlphaComposite.SrcOver.derive(.75f));
int focus = Math.min(image.getWidth() / 8, image.getHeight() / 8);
g.setPaint(new RadialGradientPaint(
new Point(image.getWidth() / 2, image.getHeight() / 2),
Math.max(image.getWidth(), image.getHeight()) / 1.6f,
new Point(focus, focus),
new float[] {0, .3f, .9f, 1f},
new Color[] {new Color(0x99FFFFFF, true), new Color(0x00FFFFFF, true), new Color(0x0, true), Color.BLACK},
MultipleGradientPaint.CycleMethod.NO_CYCLE
));
g.fillRect(-2, -2, image.getWidth() + 4, image.getHeight() + 4);
g.rotate(-angle);
g.setComposite(AlphaComposite.SrcOver.derive(.35f));
g.setPaint(new RadialGradientPaint(
new Point(image.getWidth() / 2, image.getHeight() / 2),
Math.max(image.getWidth(), image.getHeight()) / 1.65f,
new Point(image.getWidth() / 2, image.getHeight() / 2),
new float[] {0, .85f, 1f},
new Color[] {new Color(0x0, true), new Color(0x0, true), Color.BLACK},
MultipleGradientPaint.CycleMethod.NO_CYCLE
));
g.fillRect(0, 0, image.getWidth(), image.getHeight());
// Highlight
g.setComposite(AlphaComposite.SrcOver.derive(.35f));
g.setPaint(new RadialGradientPaint(
new Point(image.getWidth(), image.getHeight()),
Math.max(image.getWidth(), image.getHeight()) * 1.1f,
new Point(image.getWidth() / 2, image.getHeight() / 2),
new float[] {0, .75f, 1f},
new Color[] {new Color(0x00FFFFFF, true), new Color(0x00FFFFFF, true), Color.PINK},
MultipleGradientPaint.CycleMethod.NO_CYCLE
));
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
finally {
g.dispose();
}
// Noise
NoiseFilter noise = new NoiseFilter();
noise.setAmount(10);
noise.setDensity(2);
dest = noise.filter(dest, dest);
// Round corners
BufferedImage foo = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = foo.createGraphics();
try {
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
graphics.setColor(Color.WHITE);
double angle = (random.nextDouble() * .01) - .005;
graphics.rotate(angle);
graphics.fillRoundRect(4, 4, image.getWidth() - 8, image.getHeight() - 8, 20, 20);
}
finally {
graphics.dispose();
}
noise.setAmount(20);
noise.setDensity(1);
noise.setMonochrome(true);
foo = noise.filter(foo, foo);
foo = ImageUtil.blur(foo, 4.5f);
// Compose image into rounded corners
graphics = foo.createGraphics();
try {
graphics.setComposite(AlphaComposite.SrcIn);
graphics.drawImage(dest, 0, 0, null);
}
finally {
graphics.dispose();
}
// Draw it all back to dest
g = dest.createGraphics();
try {
if (dest.getTransparency() != Transparency.OPAQUE) {
g.setComposite(AlphaComposite.Clear);
}
g.setColor(Color.WHITE);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setComposite(AlphaComposite.SrcOver);
g.drawImage(foo, 0, 0, null);
}
finally {
g.dispose();
}
return dest;
} } | public class class_name {
public BufferedImage filter(BufferedImage src, BufferedImage dest) {
if (dest == null) {
dest = createCompatibleDestImage(src, null); // depends on control dependency: [if], data = [null)]
}
// Make image faded/washed out/red-ish
// DARK WARM
float[] scales = new float[] { 2.2f, 2.0f, 1.55f};
float[] offsets = new float[] {-20.0f, -90.0f, -110.0f};
// BRIGHT NATURAL
// float[] scales = new float[] { 1.1f, .9f, .7f};
// float[] offsets = new float[] {20, 30, 80};
// Faded, old-style
// float[] scales = new float[] { 1.1f, .7f, .3f};
// float[] offsets = new float[] {20, 30, 80};
// float[] scales = new float[] { 1.2f, .4f, .4f};
// float[] offsets = new float[] {0, 120, 120};
// BRIGHT WARM
// float[] scales = new float[] {1.1f, .8f, 1.6f};
// float[] offsets = new float[] {60, 70, -80};
BufferedImage image = new RescaleOp(scales, offsets, getRenderingHints()).filter(src, null);
// Blur
image = ImageUtil.blur(image, 2.5f);
Graphics2D g = dest.createGraphics();
try {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // depends on control dependency: [try], data = [none]
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); // depends on control dependency: [try], data = [none]
g.drawImage(image, 0, 0, null); // depends on control dependency: [try], data = [none]
// Rotate it slightly for a more analogue feeling
double angle = .0055;
g.rotate(angle); // depends on control dependency: [try], data = [none]
// Scratches
g.setComposite(AlphaComposite.SrcOver.derive(.025f)); // depends on control dependency: [try], data = [none]
for (int i = 0; i < 100; i++) {
g.setColor(random.nextBoolean() ? Color.WHITE : Color.BLACK); // depends on control dependency: [for], data = [none]
g.setStroke(new BasicStroke(random.nextFloat() * 2f)); // depends on control dependency: [for], data = [none]
int x = random.nextInt(image.getWidth());
int off = random.nextInt(100);
for (int j = random.nextInt(3); j > 0; j--) {
g.drawLine(x + j, 0, x + off - 50 + j, image.getHeight()); // depends on control dependency: [for], data = [j]
}
}
// Vignette/border
g.setComposite(AlphaComposite.SrcOver.derive(.75f)); // depends on control dependency: [try], data = [none]
int focus = Math.min(image.getWidth() / 8, image.getHeight() / 8);
g.setPaint(new RadialGradientPaint(
new Point(image.getWidth() / 2, image.getHeight() / 2),
Math.max(image.getWidth(), image.getHeight()) / 1.6f,
new Point(focus, focus),
new float[] {0, .3f, .9f, 1f},
new Color[] {new Color(0x99FFFFFF, true), new Color(0x00FFFFFF, true), new Color(0x0, true), Color.BLACK},
MultipleGradientPaint.CycleMethod.NO_CYCLE
)); // depends on control dependency: [try], data = [none]
g.fillRect(-2, -2, image.getWidth() + 4, image.getHeight() + 4); // depends on control dependency: [try], data = [none]
g.rotate(-angle); // depends on control dependency: [try], data = [none]
g.setComposite(AlphaComposite.SrcOver.derive(.35f)); // depends on control dependency: [try], data = [none]
g.setPaint(new RadialGradientPaint(
new Point(image.getWidth() / 2, image.getHeight() / 2),
Math.max(image.getWidth(), image.getHeight()) / 1.65f,
new Point(image.getWidth() / 2, image.getHeight() / 2),
new float[] {0, .85f, 1f},
new Color[] {new Color(0x0, true), new Color(0x0, true), Color.BLACK},
MultipleGradientPaint.CycleMethod.NO_CYCLE
)); // depends on control dependency: [try], data = [none]
g.fillRect(0, 0, image.getWidth(), image.getHeight()); // depends on control dependency: [try], data = [none]
// Highlight
g.setComposite(AlphaComposite.SrcOver.derive(.35f)); // depends on control dependency: [try], data = [none]
g.setPaint(new RadialGradientPaint(
new Point(image.getWidth(), image.getHeight()),
Math.max(image.getWidth(), image.getHeight()) * 1.1f,
new Point(image.getWidth() / 2, image.getHeight() / 2),
new float[] {0, .75f, 1f},
new Color[] {new Color(0x00FFFFFF, true), new Color(0x00FFFFFF, true), Color.PINK},
MultipleGradientPaint.CycleMethod.NO_CYCLE
)); // depends on control dependency: [try], data = [none]
g.fillRect(0, 0, image.getWidth(), image.getHeight()); // depends on control dependency: [try], data = [none]
}
finally {
g.dispose();
}
// Noise
NoiseFilter noise = new NoiseFilter();
noise.setAmount(10);
noise.setDensity(2);
dest = noise.filter(dest, dest);
// Round corners
BufferedImage foo = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = foo.createGraphics();
try {
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // depends on control dependency: [try], data = [none]
graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); // depends on control dependency: [try], data = [none]
graphics.setColor(Color.WHITE); // depends on control dependency: [try], data = [none]
double angle = (random.nextDouble() * .01) - .005;
graphics.rotate(angle); // depends on control dependency: [try], data = [none]
graphics.fillRoundRect(4, 4, image.getWidth() - 8, image.getHeight() - 8, 20, 20); // depends on control dependency: [try], data = [none]
}
finally {
graphics.dispose();
}
noise.setAmount(20);
noise.setDensity(1);
noise.setMonochrome(true);
foo = noise.filter(foo, foo);
foo = ImageUtil.blur(foo, 4.5f);
// Compose image into rounded corners
graphics = foo.createGraphics();
try {
graphics.setComposite(AlphaComposite.SrcIn); // depends on control dependency: [try], data = [none]
graphics.drawImage(dest, 0, 0, null); // depends on control dependency: [try], data = [none]
}
finally {
graphics.dispose();
}
// Draw it all back to dest
g = dest.createGraphics();
try {
if (dest.getTransparency() != Transparency.OPAQUE) {
g.setComposite(AlphaComposite.Clear); // depends on control dependency: [if], data = [none]
}
g.setColor(Color.WHITE); // depends on control dependency: [try], data = [none]
g.fillRect(0, 0, image.getWidth(), image.getHeight()); // depends on control dependency: [try], data = [none]
g.setComposite(AlphaComposite.SrcOver); // depends on control dependency: [try], data = [none]
g.drawImage(foo, 0, 0, null); // depends on control dependency: [try], data = [none]
}
finally {
g.dispose();
}
return dest;
} } |
public class class_name {
public ClassSymbol enterClass(ModuleSymbol msym, Name name, TypeSymbol owner) {
Assert.checkNonNull(msym);
Name flatname = TypeSymbol.formFlatName(name, owner);
ClassSymbol c = getClass(msym, flatname);
if (c == null) {
c = defineClass(name, owner);
doEnterClass(msym, c);
} else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
// reassign fields of classes that might have been loaded with
// their flat names.
c.owner.members().remove(c);
c.name = name;
c.owner = owner;
c.fullname = ClassSymbol.formFullName(name, owner);
}
return c;
} } | public class class_name {
public ClassSymbol enterClass(ModuleSymbol msym, Name name, TypeSymbol owner) {
Assert.checkNonNull(msym);
Name flatname = TypeSymbol.formFlatName(name, owner);
ClassSymbol c = getClass(msym, flatname);
if (c == null) {
c = defineClass(name, owner); // depends on control dependency: [if], data = [none]
doEnterClass(msym, c); // depends on control dependency: [if], data = [none]
} else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
// reassign fields of classes that might have been loaded with
// their flat names.
c.owner.members().remove(c); // depends on control dependency: [if], data = [none]
c.name = name; // depends on control dependency: [if], data = [none]
c.owner = owner; // depends on control dependency: [if], data = [none]
c.fullname = ClassSymbol.formFullName(name, owner); // depends on control dependency: [if], data = [none]
}
return c;
} } |
public class class_name {
@Override
public void executeImpl(SensorContext context) {
try {
LOG.info("Searching reports by relative path with basedir '{}' and search prop '{}'",
context.fileSystem().baseDir(), getReportPathKey());
List<File> reports = getReports(context.config(), context.fileSystem().baseDir(), getReportPathKey());
violationsPerFileCount.clear();
violationsPerModuleCount = 0;
for (File report : reports) {
int prevViolationsCount = violationsPerModuleCount;
LOG.info("Processing report '{}'", report);
executeReport(context, report, prevViolationsCount);
}
Metric<Integer> metric = getLanguage().getMetric(this.getMetricKey());
LOG.info("{} processed = {}", metric.getKey(), violationsPerModuleCount);
for (Map.Entry<InputFile, Integer> entry : violationsPerFileCount.entrySet()) {
context.<Integer>newMeasure()
.forMetric(metric)
.on(entry.getKey())
.withValue(entry.getValue())
.save();
}
// this sensor could be executed on module without any files
// (possible for hierarchical multi-module projects)
// don't publish 0 as module metric,
// let AggregateMeasureComputer calculate the correct value
if (violationsPerModuleCount != 0) {
context.<Integer>newMeasure()
.forMetric(metric)
.on(context.module())
.withValue(violationsPerModuleCount)
.save();
}
} catch (Exception e) {
String msg = new StringBuilder(256)
.append("Cannot feed the data into sonar, details: '")
.append(CxxUtils.getStackTrace(e))
.append("'")
.toString();
LOG.error(msg);
CxxUtils.validateRecovery(e, getLanguage());
}
} } | public class class_name {
@Override
public void executeImpl(SensorContext context) {
try {
LOG.info("Searching reports by relative path with basedir '{}' and search prop '{}'",
context.fileSystem().baseDir(), getReportPathKey());
// depends on control dependency: [try], data = [none]
List<File> reports = getReports(context.config(), context.fileSystem().baseDir(), getReportPathKey());
violationsPerFileCount.clear();
// depends on control dependency: [try], data = [none]
violationsPerModuleCount = 0;
// depends on control dependency: [try], data = [none]
for (File report : reports) {
int prevViolationsCount = violationsPerModuleCount;
LOG.info("Processing report '{}'", report);
// depends on control dependency: [for], data = [report]
executeReport(context, report, prevViolationsCount);
// depends on control dependency: [for], data = [report]
}
Metric<Integer> metric = getLanguage().getMetric(this.getMetricKey());
LOG.info("{} processed = {}", metric.getKey(), violationsPerModuleCount);
// depends on control dependency: [try], data = [none]
for (Map.Entry<InputFile, Integer> entry : violationsPerFileCount.entrySet()) {
context.<Integer>newMeasure()
.forMetric(metric)
.on(entry.getKey())
.withValue(entry.getValue())
.save();
// depends on control dependency: [for], data = [none]
}
// this sensor could be executed on module without any files
// (possible for hierarchical multi-module projects)
// don't publish 0 as module metric,
// let AggregateMeasureComputer calculate the correct value
if (violationsPerModuleCount != 0) {
context.<Integer>newMeasure()
.forMetric(metric)
.on(context.module())
.withValue(violationsPerModuleCount)
.save();
// depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
String msg = new StringBuilder(256)
.append("Cannot feed the data into sonar, details: '")
.append(CxxUtils.getStackTrace(e))
.append("'")
.toString();
LOG.error(msg);
CxxUtils.validateRecovery(e, getLanguage());
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public byte[] encode(final NamingLookupResponse obj) {
final List<AvroNamingAssignment> assignments = new ArrayList<>(obj.getNameAssignments().size());
for (final NameAssignment nameAssignment : obj.getNameAssignments()) {
assignments.add(AvroNamingAssignment.newBuilder()
.setId(nameAssignment.getIdentifier().toString())
.setHost(nameAssignment.getAddress().getHostName())
.setPort(nameAssignment.getAddress().getPort())
.build());
}
return AvroUtils.toBytes(
AvroNamingLookupResponse.newBuilder().setTuples(assignments).build(), AvroNamingLookupResponse.class
);
} } | public class class_name {
@Override
public byte[] encode(final NamingLookupResponse obj) {
final List<AvroNamingAssignment> assignments = new ArrayList<>(obj.getNameAssignments().size());
for (final NameAssignment nameAssignment : obj.getNameAssignments()) {
assignments.add(AvroNamingAssignment.newBuilder()
.setId(nameAssignment.getIdentifier().toString())
.setHost(nameAssignment.getAddress().getHostName())
.setPort(nameAssignment.getAddress().getPort())
.build()); // depends on control dependency: [for], data = [none]
}
return AvroUtils.toBytes(
AvroNamingLookupResponse.newBuilder().setTuples(assignments).build(), AvroNamingLookupResponse.class
);
} } |
public class class_name {
protected LdapSearchScope processLdapSearchScope(String name, String expression, LdapSearchScope value, boolean immediateOnly) {
LdapSearchScope result;
boolean immediate = false;
/*
* The expression language value takes precedence over the direct setting.
*/
if (expression.isEmpty()) {
/*
* Direct setting.
*/
result = value;
} else {
/*
* Evaluate the EL expression to get the value.
*/
Object obj = evaluateElExpression(expression);
if (obj instanceof LdapSearchScope) {
result = (LdapSearchScope) obj;
immediate = isImmediateExpression(expression);
} else if (obj instanceof String) {
result = LdapSearchScope.valueOf(((String) obj).toUpperCase());
immediate = isImmediateExpression(expression);
} else {
throw new IllegalArgumentException("Expected '" + name + "' to evaluate to an LdapSearchScope type.");
}
}
return (immediateOnly && !immediate) ? null : result;
} } | public class class_name {
protected LdapSearchScope processLdapSearchScope(String name, String expression, LdapSearchScope value, boolean immediateOnly) {
LdapSearchScope result;
boolean immediate = false;
/*
* The expression language value takes precedence over the direct setting.
*/
if (expression.isEmpty()) {
/*
* Direct setting.
*/
result = value; // depends on control dependency: [if], data = [none]
} else {
/*
* Evaluate the EL expression to get the value.
*/
Object obj = evaluateElExpression(expression);
if (obj instanceof LdapSearchScope) {
result = (LdapSearchScope) obj; // depends on control dependency: [if], data = [none]
immediate = isImmediateExpression(expression); // depends on control dependency: [if], data = [none]
} else if (obj instanceof String) {
result = LdapSearchScope.valueOf(((String) obj).toUpperCase()); // depends on control dependency: [if], data = [none]
immediate = isImmediateExpression(expression); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Expected '" + name + "' to evaluate to an LdapSearchScope type.");
}
}
return (immediateOnly && !immediate) ? null : result;
} } |
public class class_name {
public static KeyGenerator getKeyGenerator(String algorithm) {
final Provider provider = GlobalBouncyCastleProvider.INSTANCE.getProvider();
KeyGenerator generator;
try {
generator = (null == provider) //
? KeyGenerator.getInstance(getMainAlgorithm(algorithm)) //
: KeyGenerator.getInstance(getMainAlgorithm(algorithm), provider);
} catch (NoSuchAlgorithmException e) {
throw new CryptoException(e);
}
return generator;
} } | public class class_name {
public static KeyGenerator getKeyGenerator(String algorithm) {
final Provider provider = GlobalBouncyCastleProvider.INSTANCE.getProvider();
KeyGenerator generator;
try {
generator = (null == provider) //
? KeyGenerator.getInstance(getMainAlgorithm(algorithm)) //
: KeyGenerator.getInstance(getMainAlgorithm(algorithm), provider);
// depends on control dependency: [try], data = [none]
} catch (NoSuchAlgorithmException e) {
throw new CryptoException(e);
}
// depends on control dependency: [catch], data = [none]
return generator;
} } |
public class class_name {
private View inflateHintView(@Nullable final ViewGroup parent) {
TextView view = (TextView) LayoutInflater.from(context).inflate(hintViewId, parent, false);
view.setText(hint);
if (hintColor != null) {
view.setTextColor(hintColor);
}
return view;
} } | public class class_name {
private View inflateHintView(@Nullable final ViewGroup parent) {
TextView view = (TextView) LayoutInflater.from(context).inflate(hintViewId, parent, false);
view.setText(hint);
if (hintColor != null) {
view.setTextColor(hintColor); // depends on control dependency: [if], data = [(hintColor]
}
return view;
} } |
public class class_name {
public void addVariable(String attribute, String varName, String value) {
Bindings binds = rslTree.getBindings(attribute);
if (binds == null) {
binds = new Bindings(attribute);
rslTree.put(binds);
}
binds.add(new Binding(varName, value));
} } | public class class_name {
public void addVariable(String attribute, String varName, String value) {
Bindings binds = rslTree.getBindings(attribute);
if (binds == null) {
binds = new Bindings(attribute); // depends on control dependency: [if], data = [none]
rslTree.put(binds); // depends on control dependency: [if], data = [(binds]
}
binds.add(new Binding(varName, value));
} } |
public class class_name {
public boolean doesBucketExist(DoesBucketExistRequest request) {
checkNotNull(request, "request should not be null.");
try {
this.invokeHttpClient(this.createRequest(request, HttpMethodName.HEAD), BosResponse.class);
return true;
} catch (BceServiceException e) {
// Forbidden means that the bucket exists.
if (e.getStatusCode() == StatusCodes.FORBIDDEN) {
return true;
}
if (e.getStatusCode() == StatusCodes.NOT_FOUND) {
return false;
}
throw e;
}
} } | public class class_name {
public boolean doesBucketExist(DoesBucketExistRequest request) {
checkNotNull(request, "request should not be null.");
try {
this.invokeHttpClient(this.createRequest(request, HttpMethodName.HEAD), BosResponse.class); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} catch (BceServiceException e) {
// Forbidden means that the bucket exists.
if (e.getStatusCode() == StatusCodes.FORBIDDEN) {
return true; // depends on control dependency: [if], data = [none]
}
if (e.getStatusCode() == StatusCodes.NOT_FOUND) {
return false; // depends on control dependency: [if], data = [none]
}
throw e;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public Result<Void> getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) {
TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB);
try {
String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional);
resp.getOutputStream().print(content);
setContentType(resp,content.contains("<?xml")?TYPE.XML:TYPE.JSON);
return Result.ok();
} catch (Exception e) {
trans.error().log(e,IN,API_EXAMPLE);
return Result.err(Result.ERR_NotImplemented,e.getMessage());
} finally {
tt.done();
}
} } | public class class_name {
@Override
public Result<Void> getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) {
TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB);
try {
String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional);
resp.getOutputStream().print(content);
// depends on control dependency: [try], data = [none]
setContentType(resp,content.contains("<?xml")?TYPE.XML:TYPE.JSON);
// depends on control dependency: [try], data = [none]
return Result.ok();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
trans.error().log(e,IN,API_EXAMPLE);
return Result.err(Result.ERR_NotImplemented,e.getMessage());
} finally {
// depends on control dependency: [catch], data = [none]
tt.done();
}
} } |
public class class_name {
public void setProjectsNotFound(java.util.Collection<String> projectsNotFound) {
if (projectsNotFound == null) {
this.projectsNotFound = null;
return;
}
this.projectsNotFound = new java.util.ArrayList<String>(projectsNotFound);
} } | public class class_name {
public void setProjectsNotFound(java.util.Collection<String> projectsNotFound) {
if (projectsNotFound == null) {
this.projectsNotFound = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.projectsNotFound = new java.util.ArrayList<String>(projectsNotFound);
} } |
public class class_name {
public static ParseRecallResults parseRecallStatement(String statement, int lineMax)
{
Matcher matcher = RecallToken.matcher(statement);
if (matcher.matches()) {
String commandWordTerminator = matcher.group(1);
String lineNumberText = matcher.group(2);
String error;
if (OneWhitespace.matcher(commandWordTerminator).matches()) {
String trailings = matcher.group(3) + ";" + matcher.group(4);
// In a valid command, both "trailings" groups should be empty.
if (trailings.equals(";")) {
try {
int line = Integer.parseInt(lineNumberText) - 1;
if (line < 0 || line > lineMax) {
throw new NumberFormatException();
}
// Return the recall line number.
return new ParseRecallResults(line);
}
catch (NumberFormatException e) {
error = "Invalid RECALL line number argument: '" + lineNumberText + "'";
}
}
// For an invalid form of the command,
// return an approximation of the garbage input.
else {
error = "Invalid RECALL line number argument: '" +
lineNumberText + " " + trailings + "'";
}
}
else if (commandWordTerminator.equals("") || commandWordTerminator.equals(";")) {
error = "Incomplete RECALL command. RECALL expects a line number argument.";
} else {
error = "Invalid RECALL command: a space and line number are required after 'recall'";
}
return new ParseRecallResults(error);
}
return null;
} } | public class class_name {
public static ParseRecallResults parseRecallStatement(String statement, int lineMax)
{
Matcher matcher = RecallToken.matcher(statement);
if (matcher.matches()) {
String commandWordTerminator = matcher.group(1);
String lineNumberText = matcher.group(2);
String error;
if (OneWhitespace.matcher(commandWordTerminator).matches()) {
String trailings = matcher.group(3) + ";" + matcher.group(4);
// In a valid command, both "trailings" groups should be empty.
if (trailings.equals(";")) {
try {
int line = Integer.parseInt(lineNumberText) - 1;
if (line < 0 || line > lineMax) {
throw new NumberFormatException();
}
// Return the recall line number.
return new ParseRecallResults(line); // depends on control dependency: [try], data = [none]
}
catch (NumberFormatException e) {
error = "Invalid RECALL line number argument: '" + lineNumberText + "'";
} // depends on control dependency: [catch], data = [none]
}
// For an invalid form of the command,
// return an approximation of the garbage input.
else {
error = "Invalid RECALL line number argument: '" + // depends on control dependency: [if], data = [none]
lineNumberText + " " + trailings + "'"; // depends on control dependency: [if], data = [none]
}
}
else if (commandWordTerminator.equals("") || commandWordTerminator.equals(";")) {
error = "Incomplete RECALL command. RECALL expects a line number argument."; // depends on control dependency: [if], data = [none]
} else {
error = "Invalid RECALL command: a space and line number are required after 'recall'"; // depends on control dependency: [if], data = [none]
}
return new ParseRecallResults(error); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static BaseType createGenericClass(Class<?> type)
{
TypeVariable<?> []typeParam = type.getTypeParameters();
if (typeParam == null || typeParam.length == 0)
return ClassType.create(type);
BaseType []args = new BaseType[typeParam.length];
HashMap<String,BaseType> newParamMap = new HashMap<String,BaseType>();
String paramDeclName = null;
for (int i = 0; i < args.length; i++) {
args[i] = create(typeParam[i],
newParamMap, paramDeclName,
ClassFill.TARGET);
if (args[i] == null) {
throw new NullPointerException("unsupported BaseType: " + type);
}
newParamMap.put(typeParam[i].getName(), args[i]);
}
// ioc/07f2
return new GenericParamType(type, args, newParamMap);
} } | public class class_name {
public static BaseType createGenericClass(Class<?> type)
{
TypeVariable<?> []typeParam = type.getTypeParameters();
if (typeParam == null || typeParam.length == 0)
return ClassType.create(type);
BaseType []args = new BaseType[typeParam.length];
HashMap<String,BaseType> newParamMap = new HashMap<String,BaseType>();
String paramDeclName = null;
for (int i = 0; i < args.length; i++) {
args[i] = create(typeParam[i],
newParamMap, paramDeclName,
ClassFill.TARGET); // depends on control dependency: [for], data = [i]
if (args[i] == null) {
throw new NullPointerException("unsupported BaseType: " + type);
}
newParamMap.put(typeParam[i].getName(), args[i]); // depends on control dependency: [for], data = [i]
}
// ioc/07f2
return new GenericParamType(type, args, newParamMap);
} } |
public class class_name {
public boolean process(ContentEvent event) {
InstanceContentEvent inEvent = (InstanceContentEvent) event; //((s4Event) event).getContentEvent();
//InstanceEvent inEvent = (InstanceEvent) event;
if (inEvent.getInstanceIndex() < 0) {
// End learning
predictionStream.put(event);
return false;
}
if (inEvent.isTesting()){
Instance trainInst = inEvent.getInstance();
for (int i = 0; i < sizeEnsemble; i++) {
Instance weightedInst = trainInst.copy();
//weightedInst.setWeight(trainInst.weight() * k);
InstanceContentEvent instanceContentEvent = new InstanceContentEvent(
inEvent.getInstanceIndex(), weightedInst, false, true);
instanceContentEvent.setClassifierIndex(i);
instanceContentEvent.setEvaluationIndex(inEvent.getEvaluationIndex());
predictionStream.put(instanceContentEvent);
}
}
/* Estimate model parameters using the training data. */
if (inEvent.isTraining()) {
train(inEvent);
}
return false;
} } | public class class_name {
public boolean process(ContentEvent event) {
InstanceContentEvent inEvent = (InstanceContentEvent) event; //((s4Event) event).getContentEvent();
//InstanceEvent inEvent = (InstanceEvent) event;
if (inEvent.getInstanceIndex() < 0) {
// End learning
predictionStream.put(event); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
if (inEvent.isTesting()){
Instance trainInst = inEvent.getInstance();
for (int i = 0; i < sizeEnsemble; i++) {
Instance weightedInst = trainInst.copy();
//weightedInst.setWeight(trainInst.weight() * k);
InstanceContentEvent instanceContentEvent = new InstanceContentEvent(
inEvent.getInstanceIndex(), weightedInst, false, true);
instanceContentEvent.setClassifierIndex(i); // depends on control dependency: [for], data = [i]
instanceContentEvent.setEvaluationIndex(inEvent.getEvaluationIndex()); // depends on control dependency: [for], data = [none]
predictionStream.put(instanceContentEvent); // depends on control dependency: [for], data = [none]
}
}
/* Estimate model parameters using the training data. */
if (inEvent.isTraining()) {
train(inEvent); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
protected void handleMulticastSrvRqst(SrvRqst srvRqst, InetSocketAddress localAddress, InetSocketAddress remoteAddress)
{
// Match previous responders
String responder = remoteAddress.getAddress().getHostAddress();
if (srvRqst.containsResponder(responder))
{
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " dropping message " + srvRqst + ": already contains responder " + responder);
return;
}
// Match scopes: RFC 2608, 11.1
if (!scopes.weakMatch(srvRqst.getScopes()))
{
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " dropping message " + srvRqst + ": no scopes match among DA scopes " + scopes + " and message scopes " + srvRqst.getScopes());
return;
}
ServiceType serviceType = srvRqst.getServiceType();
if (!DirectoryAgentInfo.SERVICE_TYPE.equals(serviceType))
{
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " dropping message " + srvRqst + ": SrvRqst for service type " + serviceType + " must be unicast");
return;
}
String address = NetUtils.convertWildcardAddress(localAddress.getAddress()).getHostAddress();
DirectoryAgentInfo directoryAgent = directoryAgents.get(address);
if (directoryAgent == null)
{
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " dropping message " + srvRqst + ": arrived to unknown address " + address);
return;
}
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " sending UDP unicast reply to " + remoteAddress);
udpDAAdvert.perform(localAddress, remoteAddress, directoryAgent, srvRqst);
} } | public class class_name {
protected void handleMulticastSrvRqst(SrvRqst srvRqst, InetSocketAddress localAddress, InetSocketAddress remoteAddress)
{
// Match previous responders
String responder = remoteAddress.getAddress().getHostAddress();
if (srvRqst.containsResponder(responder))
{
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " dropping message " + srvRqst + ": already contains responder " + responder);
return; // depends on control dependency: [if], data = [none]
}
// Match scopes: RFC 2608, 11.1
if (!scopes.weakMatch(srvRqst.getScopes()))
{
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " dropping message " + srvRqst + ": no scopes match among DA scopes " + scopes + " and message scopes " + srvRqst.getScopes());
return; // depends on control dependency: [if], data = [none]
}
ServiceType serviceType = srvRqst.getServiceType();
if (!DirectoryAgentInfo.SERVICE_TYPE.equals(serviceType))
{
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " dropping message " + srvRqst + ": SrvRqst for service type " + serviceType + " must be unicast");
return; // depends on control dependency: [if], data = [none]
}
String address = NetUtils.convertWildcardAddress(localAddress.getAddress()).getHostAddress();
DirectoryAgentInfo directoryAgent = directoryAgents.get(address);
if (directoryAgent == null)
{
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " dropping message " + srvRqst + ": arrived to unknown address " + address);
return; // depends on control dependency: [if], data = [none]
}
if (logger.isLoggable(Level.FINE))
logger.fine("DirectoryAgent " + this + " sending UDP unicast reply to " + remoteAddress);
udpDAAdvert.perform(localAddress, remoteAddress, directoryAgent, srvRqst);
} } |
public class class_name {
public boolean writeArrayElementIfMatching(Class arrayComponentClass, Object o, boolean showType, Writer output)
{
if (!o.getClass().isAssignableFrom(arrayComponentClass) || notCustom.contains(o.getClass()))
{
return false;
}
try
{
return writeCustom(arrayComponentClass, o, showType, output);
}
catch (IOException e)
{
throw new JsonIoException("Unable to write custom formatted object as array element:", e);
}
} } | public class class_name {
public boolean writeArrayElementIfMatching(Class arrayComponentClass, Object o, boolean showType, Writer output)
{
if (!o.getClass().isAssignableFrom(arrayComponentClass) || notCustom.contains(o.getClass()))
{
return false; // depends on control dependency: [if], data = [none]
}
try
{
return writeCustom(arrayComponentClass, o, showType, output); // depends on control dependency: [try], data = [none]
}
catch (IOException e)
{
throw new JsonIoException("Unable to write custom formatted object as array element:", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(NetworkInterface networkInterface, ProtocolMarshaller protocolMarshaller) {
if (networkInterface == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(networkInterface.getSubnetId(), SUBNETID_BINDING);
protocolMarshaller.marshall(networkInterface.getNetworkInterfaceId(), NETWORKINTERFACEID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(NetworkInterface networkInterface, ProtocolMarshaller protocolMarshaller) {
if (networkInterface == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(networkInterface.getSubnetId(), SUBNETID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(networkInterface.getNetworkInterfaceId(), NETWORKINTERFACEID_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 void insert(final FinderObject owner, final FinderObject fob) {
final GedObject gob = (GedObject) fob;
try {
logger.debug("Starting insert: " + gob.getString());
final GedDocumentMongo<?> gedDoc =
toDocConverter.createGedDocument(gob);
final TopLevelGedDocumentMongoVisitor visitor =
new SaveVisitor(repositoryManager);
gedDoc.accept(visitor);
} catch (DataAccessException e) {
logger.error("Error saving: " + gob.getString(), e);
}
logger.debug("Ending insert: " + gob.getString());
} } | public class class_name {
@Override
public void insert(final FinderObject owner, final FinderObject fob) {
final GedObject gob = (GedObject) fob;
try {
logger.debug("Starting insert: " + gob.getString()); // depends on control dependency: [try], data = [none]
final GedDocumentMongo<?> gedDoc =
toDocConverter.createGedDocument(gob);
final TopLevelGedDocumentMongoVisitor visitor =
new SaveVisitor(repositoryManager);
gedDoc.accept(visitor); // depends on control dependency: [try], data = [none]
} catch (DataAccessException e) {
logger.error("Error saving: " + gob.getString(), e);
} // depends on control dependency: [catch], data = [none]
logger.debug("Ending insert: " + gob.getString());
} } |
public class class_name {
@Override
public UserProfile convert(String text)
{
if(text == null || text.trim().length() == 0)
return null;
String[] lines = text.split("\\\n");
BiConsumer<String,UserProfile> strategy = null;
UserProfile userProfile = null;
String lineUpper = null;
for (String line : lines)
{
//get first term
int index = line.indexOf(";");
if(index < 0)
continue; //skip line
//
String term = line.substring(0, index);
strategy = strategies.get(term.toLowerCase());
lineUpper = line.toUpperCase();
if(strategy == null)
{
//check for a different format
//N:Green;Gregory;;;
if(lineUpper.startsWith("N:"))
strategy = strategies.get("n");
else if(lineUpper.startsWith("FN:"))
strategy = strategies.get("fn");
else if(lineUpper.contains("EMAIL;"))
strategy = strategies.get("email");
else
continue; //skip
}
if(userProfile == null)
{
userProfile = ClassPath.newInstance(this.userProfileClass);
}
strategy.accept(line, userProfile);
}
return userProfile;
} } | public class class_name {
@Override
public UserProfile convert(String text)
{
if(text == null || text.trim().length() == 0)
return null;
String[] lines = text.split("\\\n");
BiConsumer<String,UserProfile> strategy = null;
UserProfile userProfile = null;
String lineUpper = null;
for (String line : lines)
{
//get first term
int index = line.indexOf(";");
if(index < 0)
continue; //skip line
//
String term = line.substring(0, index);
strategy = strategies.get(term.toLowerCase()); // depends on control dependency: [for], data = [none]
lineUpper = line.toUpperCase(); // depends on control dependency: [for], data = [line]
if(strategy == null)
{
//check for a different format
//N:Green;Gregory;;;
if(lineUpper.startsWith("N:"))
strategy = strategies.get("n");
else if(lineUpper.startsWith("FN:"))
strategy = strategies.get("fn");
else if(lineUpper.contains("EMAIL;"))
strategy = strategies.get("email");
else
continue; //skip
}
if(userProfile == null)
{
userProfile = ClassPath.newInstance(this.userProfileClass); // depends on control dependency: [if], data = [none]
}
strategy.accept(line, userProfile); // depends on control dependency: [for], data = [line]
}
return userProfile;
} } |
public class class_name {
public static String[] extractNames(Scope[] scopes)
{
if (scopes == null)
{
return null;
}
// Create an array for scope names.
String[] names = new String[scopes.length];
// For each scope.
for (int i = 0; i < scopes.length; ++i)
{
// Scope at the index.
Scope scope = scopes[i];
// Extract the scope name.
names[i] = (scope == null) ? null : scope.getName();
}
// Extracted scope names.
return names;
} } | public class class_name {
public static String[] extractNames(Scope[] scopes)
{
if (scopes == null)
{
return null;
// depends on control dependency: [if], data = [none]
}
// Create an array for scope names.
String[] names = new String[scopes.length];
// For each scope.
for (int i = 0; i < scopes.length; ++i)
{
// Scope at the index.
Scope scope = scopes[i];
// Extract the scope name.
names[i] = (scope == null) ? null : scope.getName();
// depends on control dependency: [for], data = [i]
}
// Extracted scope names.
return names;
} } |
public class class_name {
public Collection<Peer> getPeers(EnumSet<PeerRole> roles) {
Set<Peer> ret = new HashSet<>(getPeers().size());
for (PeerRole peerRole : roles) {
ret.addAll(peerRoleSetMap.get(peerRole));
}
return Collections.unmodifiableCollection(ret);
} } | public class class_name {
public Collection<Peer> getPeers(EnumSet<PeerRole> roles) {
Set<Peer> ret = new HashSet<>(getPeers().size());
for (PeerRole peerRole : roles) {
ret.addAll(peerRoleSetMap.get(peerRole)); // depends on control dependency: [for], data = [peerRole]
}
return Collections.unmodifiableCollection(ret);
} } |
public class class_name {
private IRing toRing(IAtomContainer container, EdgeToBondMap edges, int[] cycle) {
IRing ring = container.getBuilder().newInstance(IRing.class, 0);
int len = cycle.length - 1;
IAtom[] atoms = new IAtom[len];
IBond[] bonds = new IBond[len];
for (int i = 0; i < len; i++) {
atoms[i] = container.getAtom(cycle[i]);
bonds[i] = edges.get(cycle[i], cycle[i + 1]);
atoms[i].setFlag(CDKConstants.ISINRING, true);
}
ring.setAtoms(atoms);
ring.setBonds(bonds);
return ring;
} } | public class class_name {
private IRing toRing(IAtomContainer container, EdgeToBondMap edges, int[] cycle) {
IRing ring = container.getBuilder().newInstance(IRing.class, 0);
int len = cycle.length - 1;
IAtom[] atoms = new IAtom[len];
IBond[] bonds = new IBond[len];
for (int i = 0; i < len; i++) {
atoms[i] = container.getAtom(cycle[i]); // depends on control dependency: [for], data = [i]
bonds[i] = edges.get(cycle[i], cycle[i + 1]); // depends on control dependency: [for], data = [i]
atoms[i].setFlag(CDKConstants.ISINRING, true); // depends on control dependency: [for], data = [i]
}
ring.setAtoms(atoms);
ring.setBonds(bonds);
return ring;
} } |
public class class_name {
private static int[] getDims(VarSet vars) {
int[] dims = new int[vars.size()];
for (int i=0; i<vars.size(); i++) {
dims[i] = vars.get(i).getNumStates();
}
return dims;
} } | public class class_name {
private static int[] getDims(VarSet vars) {
int[] dims = new int[vars.size()];
for (int i=0; i<vars.size(); i++) {
dims[i] = vars.get(i).getNumStates(); // depends on control dependency: [for], data = [i]
}
return dims;
} } |
public class class_name {
@Override
public void onApplicationEvent(final ApplicationEvent applicationEvent) {
if (!(applicationEvent instanceof TenantAwareEvent)) {
return;
}
final TenantAwareEvent event = (TenantAwareEvent) applicationEvent;
collectRolloutEvent(event);
// to dispatch too many events which are not interested on the UI
if (!isEventProvided(event)) {
LOG.trace("Event is not supported in the UI!!! Dropped event is {}", event);
return;
}
offerEvent(event);
} } | public class class_name {
@Override
public void onApplicationEvent(final ApplicationEvent applicationEvent) {
if (!(applicationEvent instanceof TenantAwareEvent)) {
return; // depends on control dependency: [if], data = [none]
}
final TenantAwareEvent event = (TenantAwareEvent) applicationEvent;
collectRolloutEvent(event);
// to dispatch too many events which are not interested on the UI
if (!isEventProvided(event)) {
LOG.trace("Event is not supported in the UI!!! Dropped event is {}", event); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
offerEvent(event);
} } |
public class class_name {
public ConfigFile read() {
List<Declaration> declarations = new ArrayList<>();
skipWhiteSpace();
while (index < tokens.size()) {
Token lookahead = tokens.get(index);
if (lookahead.kind == LeftSquare) {
declarations.add(parseSection());
} else {
declarations.add(parseKeyValuePair());
}
skipWhiteSpace();
}
// FIXME: why do we need this?
file.setDeclarations(new Tuple<>(declarations));
return file;
} } | public class class_name {
public ConfigFile read() {
List<Declaration> declarations = new ArrayList<>();
skipWhiteSpace();
while (index < tokens.size()) {
Token lookahead = tokens.get(index);
if (lookahead.kind == LeftSquare) {
declarations.add(parseSection()); // depends on control dependency: [if], data = [none]
} else {
declarations.add(parseKeyValuePair()); // depends on control dependency: [if], data = [none]
}
skipWhiteSpace(); // depends on control dependency: [while], data = [none]
}
// FIXME: why do we need this?
file.setDeclarations(new Tuple<>(declarations));
return file;
} } |
public class class_name {
private boolean methodExists(Class clazz, String name) {
Method[] methods = clazz.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(name)) {
return true;
}
}
if (clazz.getSuperclass() != null
&& methodExists(clazz.getSuperclass(), name)) {
return true;
}
Class[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (methodExists(interfaces[i], name)) {
return true;
}
}
return false;
} } | public class class_name {
private boolean methodExists(Class clazz, String name) {
Method[] methods = clazz.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(name)) {
return true;
// depends on control dependency: [if], data = [none]
}
}
if (clazz.getSuperclass() != null
&& methodExists(clazz.getSuperclass(), name)) {
return true;
// depends on control dependency: [if], data = [none]
}
Class[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (methodExists(interfaces[i], name)) {
return true;
// depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public DiffBuilder append(final String fieldName,
final DiffResult diffResult) {
validateFieldNameNotNull(fieldName);
Validate.isTrue(diffResult != null, "Diff result cannot be null");
if (objectsTriviallyEqual) {
return this;
}
for (final Diff<?> diff : diffResult.getDiffs()) {
append(fieldName + "." + diff.getFieldName(),
diff.getLeft(), diff.getRight());
}
return this;
} } | public class class_name {
public DiffBuilder append(final String fieldName,
final DiffResult diffResult) {
validateFieldNameNotNull(fieldName);
Validate.isTrue(diffResult != null, "Diff result cannot be null");
if (objectsTriviallyEqual) {
return this; // depends on control dependency: [if], data = [none]
}
for (final Diff<?> diff : diffResult.getDiffs()) {
append(fieldName + "." + diff.getFieldName(),
diff.getLeft(), diff.getRight()); // depends on control dependency: [for], data = [diff]
}
return this;
} } |
public class class_name {
private void setPageTotalCount(Connection connection, MappedStatement mappedStatement, BoundSql boundSql) {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(createCountSql(boundSql.getSql()));
ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, boundSql.getParameterObject(), boundSql);
parameterHandler.setParameters(preparedStatement);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
((PageEntity) boundSql.getParameterObject()).setTotalCount(resultSet.getLong(1));
}
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
} } | public class class_name {
private void setPageTotalCount(Connection connection, MappedStatement mappedStatement, BoundSql boundSql) {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(createCountSql(boundSql.getSql())); // depends on control dependency: [try], data = [none]
ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, boundSql.getParameterObject(), boundSql);
parameterHandler.setParameters(preparedStatement); // depends on control dependency: [try], data = [none]
resultSet = preparedStatement.executeQuery(); // depends on control dependency: [try], data = [none]
if (resultSet.next()) {
((PageEntity) boundSql.getParameterObject()).setTotalCount(resultSet.getLong(1)); // depends on control dependency: [if], data = [none]
}
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static AtlasCardinality createCardinality(Cardinality cardinality) {
if (cardinality == Cardinality.SINGLE) {
return AtlasCardinality.SINGLE;
} else if (cardinality == Cardinality.LIST) {
return AtlasCardinality.LIST;
}
return AtlasCardinality.SET;
} } | public class class_name {
public static AtlasCardinality createCardinality(Cardinality cardinality) {
if (cardinality == Cardinality.SINGLE) {
return AtlasCardinality.SINGLE; // depends on control dependency: [if], data = [none]
} else if (cardinality == Cardinality.LIST) {
return AtlasCardinality.LIST; // depends on control dependency: [if], data = [none]
}
return AtlasCardinality.SET;
} } |
public class class_name {
protected void removeDestination(DestinationHandler dh)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "removeDestination", dh);
if (dh.isLink())
{
if (linkIndex.containsKey(dh))
{
linkIndex.remove(dh);
}
}
else
{
if (destinationIndex.containsKey(dh))
{
destinationIndex.remove(dh);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "removeDestination");
} } | public class class_name {
protected void removeDestination(DestinationHandler dh)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "removeDestination", dh);
if (dh.isLink())
{
if (linkIndex.containsKey(dh))
{
linkIndex.remove(dh); // depends on control dependency: [if], data = [none]
}
}
else
{
if (destinationIndex.containsKey(dh))
{
destinationIndex.remove(dh); // depends on control dependency: [if], data = [none]
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "removeDestination");
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static <T> T performMethodInvocation(Object tested, Method methodToInvoke, Object... arguments)
throws Exception {
final boolean accessible = methodToInvoke.isAccessible();
if (!accessible) {
methodToInvoke.setAccessible(true);
}
try {
if (isPotentialVarArgsMethod(methodToInvoke, arguments)) {
Class<?>[] parameterTypes = methodToInvoke.getParameterTypes();
final int varArgsIndex = parameterTypes.length - 1;
Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();
Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);
Object[] completeArgumentList = new Object[parameterTypes.length];
System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);
completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;
return (T) methodToInvoke.invoke(tested, completeArgumentList);
} else {
return (T) methodToInvoke.invoke(tested, arguments == null ? new Object[]{arguments} : arguments);
}
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new MethodInvocationException(cause);
}
} finally {
if (!accessible) {
methodToInvoke.setAccessible(false);
}
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public static <T> T performMethodInvocation(Object tested, Method methodToInvoke, Object... arguments)
throws Exception {
final boolean accessible = methodToInvoke.isAccessible();
if (!accessible) {
methodToInvoke.setAccessible(true);
}
try {
if (isPotentialVarArgsMethod(methodToInvoke, arguments)) {
Class<?>[] parameterTypes = methodToInvoke.getParameterTypes();
final int varArgsIndex = parameterTypes.length - 1;
Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();
Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);
Object[] completeArgumentList = new Object[parameterTypes.length];
System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);
completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;
return (T) methodToInvoke.invoke(tested, completeArgumentList);
} else {
return (T) methodToInvoke.invoke(tested, arguments == null ? new Object[]{arguments} : arguments);
}
} catch (InvocationTargetException e) { // depends on control dependency: [if], data = [none]
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new MethodInvocationException(cause);
}
} finally { // depends on control dependency: [if], data = [none]
if (!accessible) {
methodToInvoke.setAccessible(false); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private List<String> wordsForArguments(String command, List<String> words) {
int wordsUsedForCommandKey = command.split(" ").length;
List<String> args = words.subList(wordsUsedForCommandKey, words.size());
int last = args.size() - 1;
if (last >= 0 && "".equals(args.get(last))) {
args.remove(last);
}
return args;
} } | public class class_name {
private List<String> wordsForArguments(String command, List<String> words) {
int wordsUsedForCommandKey = command.split(" ").length;
List<String> args = words.subList(wordsUsedForCommandKey, words.size());
int last = args.size() - 1;
if (last >= 0 && "".equals(args.get(last))) {
args.remove(last); // depends on control dependency: [if], data = [(last]
}
return args;
} } |
public class class_name {
public void marshall(CreateExportTaskRequest createExportTaskRequest, ProtocolMarshaller protocolMarshaller) {
if (createExportTaskRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createExportTaskRequest.getTaskName(), TASKNAME_BINDING);
protocolMarshaller.marshall(createExportTaskRequest.getLogGroupName(), LOGGROUPNAME_BINDING);
protocolMarshaller.marshall(createExportTaskRequest.getLogStreamNamePrefix(), LOGSTREAMNAMEPREFIX_BINDING);
protocolMarshaller.marshall(createExportTaskRequest.getFrom(), FROM_BINDING);
protocolMarshaller.marshall(createExportTaskRequest.getTo(), TO_BINDING);
protocolMarshaller.marshall(createExportTaskRequest.getDestination(), DESTINATION_BINDING);
protocolMarshaller.marshall(createExportTaskRequest.getDestinationPrefix(), DESTINATIONPREFIX_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateExportTaskRequest createExportTaskRequest, ProtocolMarshaller protocolMarshaller) {
if (createExportTaskRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createExportTaskRequest.getTaskName(), TASKNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createExportTaskRequest.getLogGroupName(), LOGGROUPNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createExportTaskRequest.getLogStreamNamePrefix(), LOGSTREAMNAMEPREFIX_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createExportTaskRequest.getFrom(), FROM_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createExportTaskRequest.getTo(), TO_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createExportTaskRequest.getDestination(), DESTINATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createExportTaskRequest.getDestinationPrefix(), DESTINATIONPREFIX_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 DataFetcher wrapDataFetcher(DataFetcher delegateDataFetcher, BiFunction<DataFetchingEnvironment, Object, Object> mapFunction) {
return environment -> {
Object value = delegateDataFetcher.get(environment);
if (value instanceof CompletionStage) {
//noinspection unchecked
return ((CompletionStage<Object>) value).thenApply(v -> mapFunction.apply(environment, v));
} else {
return mapFunction.apply(environment, value);
}
};
} } | public class class_name {
public static DataFetcher wrapDataFetcher(DataFetcher delegateDataFetcher, BiFunction<DataFetchingEnvironment, Object, Object> mapFunction) {
return environment -> {
Object value = delegateDataFetcher.get(environment);
if (value instanceof CompletionStage) {
//noinspection unchecked
return ((CompletionStage<Object>) value).thenApply(v -> mapFunction.apply(environment, v)); // depends on control dependency: [if], data = [none]
} else {
return mapFunction.apply(environment, value); // depends on control dependency: [if], data = [none]
}
};
} } |
public class class_name {
public static Object getObjectValue(Object target,String propertyName){
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, target.getClass());
return descriptor.getReadMethod().invoke(target);
} catch (Exception e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static Object getObjectValue(Object target,String propertyName){
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, target.getClass());
return descriptor.getReadMethod().invoke(target); // 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 List<String> getSearchDimensions() {
List<String> dimensions = new ArrayList<String>();
for (int i = 0; i < m_Space.dimensions(); ++i) {
dimensions.add(m_Space.getDimension(i).getLabel());
}
return dimensions;
} } | public class class_name {
public List<String> getSearchDimensions() {
List<String> dimensions = new ArrayList<String>();
for (int i = 0; i < m_Space.dimensions(); ++i) {
dimensions.add(m_Space.getDimension(i).getLabel()); // depends on control dependency: [for], data = [i]
}
return dimensions;
} } |
public class class_name {
private void computeLast() {
for (int k = 0; k < last.length; k++) {
last[k] = -1;
}
for (int j = pattern.length()-1; j >= 0; j--) {
if (last[pattern.charAt(j)] < 0) {
last[pattern.charAt(j)] = j;
}
}
} } | public class class_name {
private void computeLast() {
for (int k = 0; k < last.length; k++) {
last[k] = -1; // depends on control dependency: [for], data = [k]
}
for (int j = pattern.length()-1; j >= 0; j--) {
if (last[pattern.charAt(j)] < 0) {
last[pattern.charAt(j)] = j; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@ExceptionHandler(MultipartException.class)
public ResponseEntity<ExceptionInfo> handleMultipartException(final HttpServletRequest request,
final Exception ex) {
logRequest(request, ex);
final List<Throwable> throwables = ExceptionUtils.getThrowableList(ex);
final Throwable responseCause = Iterables.getLast(throwables);
if (responseCause.getMessage().isEmpty()) {
LOG.warn("Request {} lead to MultipartException without root cause message:\n{}", request.getRequestURL(),
ex.getStackTrace());
}
final ExceptionInfo response = createExceptionInfo(new MultiPartFileUploadException(responseCause));
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
} } | public class class_name {
@ExceptionHandler(MultipartException.class)
public ResponseEntity<ExceptionInfo> handleMultipartException(final HttpServletRequest request,
final Exception ex) {
logRequest(request, ex);
final List<Throwable> throwables = ExceptionUtils.getThrowableList(ex);
final Throwable responseCause = Iterables.getLast(throwables);
if (responseCause.getMessage().isEmpty()) {
LOG.warn("Request {} lead to MultipartException without root cause message:\n{}", request.getRequestURL(),
ex.getStackTrace()); // depends on control dependency: [if], data = [none]
}
final ExceptionInfo response = createExceptionInfo(new MultiPartFileUploadException(responseCause));
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
} } |
public class class_name {
public static String file2String(Class clazz, String relativePath, String encoding) throws IOException {
InputStream is = null;
InputStreamReader reader = null;
BufferedReader bufferedReader = null;
try {
is = clazz.getResourceAsStream(relativePath);
reader = new InputStreamReader(is, encoding);
bufferedReader = new BufferedReader(reader);
StringBuilder context = new StringBuilder();
String lineText;
while ((lineText = bufferedReader.readLine()) != null) {
context.append(lineText).append(LINE_SEPARATOR);
}
return context.toString();
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (reader != null) {
reader.close();
}
if (is != null) {
is.close();
}
}
} } | public class class_name {
public static String file2String(Class clazz, String relativePath, String encoding) throws IOException {
InputStream is = null;
InputStreamReader reader = null;
BufferedReader bufferedReader = null;
try {
is = clazz.getResourceAsStream(relativePath);
reader = new InputStreamReader(is, encoding);
bufferedReader = new BufferedReader(reader);
StringBuilder context = new StringBuilder();
String lineText;
while ((lineText = bufferedReader.readLine()) != null) {
context.append(lineText).append(LINE_SEPARATOR); // depends on control dependency: [while], data = [none]
}
return context.toString();
} finally {
if (bufferedReader != null) {
bufferedReader.close(); // depends on control dependency: [if], data = [none]
}
if (reader != null) {
reader.close(); // depends on control dependency: [if], data = [none]
}
if (is != null) {
is.close(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private boolean isHeteroRingSystem(IAtomContainer ac) {
if (ac != null) {
for (int i = 0; i < ac.getAtomCount(); i++) {
if (!(ac.getAtom(i).getSymbol()).equals("H") && !(ac.getAtom(i).getSymbol()).equals("C")) {
return true;
}
}
}
return false;
} } | public class class_name {
private boolean isHeteroRingSystem(IAtomContainer ac) {
if (ac != null) {
for (int i = 0; i < ac.getAtomCount(); i++) {
if (!(ac.getAtom(i).getSymbol()).equals("H") && !(ac.getAtom(i).getSymbol()).equals("C")) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
private void handleQueueParamsEvent(QueueParamsEvent event)
{
AsteriskQueueImpl queue;
final String name = event.getQueue();
final Integer max = event.getMax();
final String strategy = event.getStrategy();
final Integer serviceLevel = event.getServiceLevel();
final Integer weight = event.getWeight();
final Integer calls = event.getCalls();
final Integer holdTime = event.getHoldTime();
final Integer talkTime = event.getTalkTime();
final Integer completed = event.getCompleted();
final Integer abandoned = event.getAbandoned();
final Double serviceLevelPerf = event.getServiceLevelPerf();
queue = getInternalQueueByName(name);
if (queue == null)
{
queue = new AsteriskQueueImpl(server, name, max, strategy, serviceLevel, weight, calls, holdTime, talkTime,
completed, abandoned, serviceLevelPerf);
logger.info("Adding new queue " + queue);
addQueue(queue);
}
else
{
// We should never reach that code as this method is only called for
// initialization
// So the queue should never be in the queues list
synchronized (queue)
{
synchronized (queuesLRU)
{
if (queue.setMax(max) | queue.setServiceLevel(serviceLevel) | queue.setWeight(weight)
| queue.setCalls(calls) | queue.setHoldTime(holdTime) | queue.setTalkTime(talkTime)
| queue.setCompleted(completed) | queue.setAbandoned(abandoned)
| queue.setServiceLevelPerf(serviceLevelPerf))
{
queuesLRU.remove(queue.getName());
queuesLRU.put(queue.getName(), queue);
}
}
}
}
} } | public class class_name {
private void handleQueueParamsEvent(QueueParamsEvent event)
{
AsteriskQueueImpl queue;
final String name = event.getQueue();
final Integer max = event.getMax();
final String strategy = event.getStrategy();
final Integer serviceLevel = event.getServiceLevel();
final Integer weight = event.getWeight();
final Integer calls = event.getCalls();
final Integer holdTime = event.getHoldTime();
final Integer talkTime = event.getTalkTime();
final Integer completed = event.getCompleted();
final Integer abandoned = event.getAbandoned();
final Double serviceLevelPerf = event.getServiceLevelPerf();
queue = getInternalQueueByName(name);
if (queue == null)
{
queue = new AsteriskQueueImpl(server, name, max, strategy, serviceLevel, weight, calls, holdTime, talkTime,
completed, abandoned, serviceLevelPerf); // depends on control dependency: [if], data = [none]
logger.info("Adding new queue " + queue); // depends on control dependency: [if], data = [none]
addQueue(queue); // depends on control dependency: [if], data = [(queue]
}
else
{
// We should never reach that code as this method is only called for
// initialization
// So the queue should never be in the queues list
synchronized (queue) // depends on control dependency: [if], data = [(queue]
{
synchronized (queuesLRU)
{
if (queue.setMax(max) | queue.setServiceLevel(serviceLevel) | queue.setWeight(weight)
| queue.setCalls(calls) | queue.setHoldTime(holdTime) | queue.setTalkTime(talkTime)
| queue.setCompleted(completed) | queue.setAbandoned(abandoned)
| queue.setServiceLevelPerf(serviceLevelPerf))
{
queuesLRU.remove(queue.getName()); // depends on control dependency: [if], data = [none]
queuesLRU.put(queue.getName(), queue); // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.