code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public static String document(ContainerTag htmlTag) {
if (htmlTag.getTagName().equals("html")) {
return document().render() + htmlTag.render();
}
throw new IllegalArgumentException("Only HTML-tag can follow document declaration");
} } | public class class_name {
public static String document(ContainerTag htmlTag) {
if (htmlTag.getTagName().equals("html")) {
return document().render() + htmlTag.render(); // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException("Only HTML-tag can follow document declaration");
} } |
public class class_name {
public static Label.Builder replace(final Label.Builder label, final String oldLabel, final String newLabel) {
for (final MapFieldEntry.Builder entryBuilder : label.getEntryBuilderList()) {
final List<String> valueList = new ArrayList<>(entryBuilder.getValueList());
entryBuilder.clearValue();
for (String value : valueList) {
if (StringProcessor.removeWhiteSpaces(value).equalsIgnoreCase(StringProcessor.removeWhiteSpaces(oldLabel))) {
entryBuilder.addValue(newLabel);
} else {
entryBuilder.addValue(value);
}
}
}
return label;
} } | public class class_name {
public static Label.Builder replace(final Label.Builder label, final String oldLabel, final String newLabel) {
for (final MapFieldEntry.Builder entryBuilder : label.getEntryBuilderList()) {
final List<String> valueList = new ArrayList<>(entryBuilder.getValueList());
entryBuilder.clearValue(); // depends on control dependency: [for], data = [entryBuilder]
for (String value : valueList) {
if (StringProcessor.removeWhiteSpaces(value).equalsIgnoreCase(StringProcessor.removeWhiteSpaces(oldLabel))) {
entryBuilder.addValue(newLabel); // depends on control dependency: [if], data = [none]
} else {
entryBuilder.addValue(value); // depends on control dependency: [if], data = [none]
}
}
}
return label;
} } |
public class class_name {
protected String createSortQuery(final List<DefaultKeyValue<String, Boolean>> fields) {
StringBuilder builder = new StringBuilder("{");
Iterator<DefaultKeyValue<String, Boolean>> iter = fields.iterator();
while (iter.hasNext()) {
DefaultKeyValue<String, Boolean> field = iter.next();
builder.append("\"");
builder.append(field.getKey());
builder.append("\"");
builder.append(":");
if (field.getValue()) {
builder.append(1);
} else {
builder.append(-1);
}
if (iter.hasNext()) {
builder.append(",");
}
}
builder.append("}");
return builder.toString();
} } | public class class_name {
protected String createSortQuery(final List<DefaultKeyValue<String, Boolean>> fields) {
StringBuilder builder = new StringBuilder("{");
Iterator<DefaultKeyValue<String, Boolean>> iter = fields.iterator();
while (iter.hasNext()) {
DefaultKeyValue<String, Boolean> field = iter.next();
builder.append("\""); // depends on control dependency: [while], data = [none]
builder.append(field.getKey()); // depends on control dependency: [while], data = [none]
builder.append("\""); // depends on control dependency: [while], data = [none]
builder.append(":"); // depends on control dependency: [while], data = [none]
if (field.getValue()) {
builder.append(1); // depends on control dependency: [if], data = [none]
} else {
builder.append(-1); // depends on control dependency: [if], data = [none]
}
if (iter.hasNext()) {
builder.append(","); // depends on control dependency: [if], data = [none]
}
}
builder.append("}");
return builder.toString();
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static <E> ImmutableSortedMultiset<E> copyOf(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
if (elements instanceof ImmutableSortedMultiset) {
@SuppressWarnings("unchecked") // immutable collections are always safe for covariant casts
ImmutableSortedMultiset<E> multiset = (ImmutableSortedMultiset<E>) elements;
if (comparator.equals(multiset.comparator())) {
if (multiset.isPartialView()) {
return copyOfSortedEntries(comparator, multiset.entrySet().asList());
} else {
return multiset;
}
}
}
return new ImmutableSortedMultiset.Builder<E>(comparator).addAll(elements).build();
} } | public class class_name {
@SuppressWarnings("unchecked")
public static <E> ImmutableSortedMultiset<E> copyOf(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
if (elements instanceof ImmutableSortedMultiset) {
@SuppressWarnings("unchecked") // immutable collections are always safe for covariant casts
ImmutableSortedMultiset<E> multiset = (ImmutableSortedMultiset<E>) elements;
if (comparator.equals(multiset.comparator())) {
if (multiset.isPartialView()) {
return copyOfSortedEntries(comparator, multiset.entrySet().asList()); // depends on control dependency: [if], data = [none]
} else {
return multiset; // depends on control dependency: [if], data = [none]
}
}
}
return new ImmutableSortedMultiset.Builder<E>(comparator).addAll(elements).build();
} } |
public class class_name {
public void doValidRecord(boolean bDisplayOption)
{ // Copy the key field to the master file and BYPASS the BEHAVIORS
super.doValidRecord(bDisplayOption);
if (m_bMoveOnValid)
{
int iMoveType = DBConstants.SCREEN_MOVE; // Do trigger a record change.
this.moveTheData(bDisplayOption, iMoveType);
}
} } | public class class_name {
public void doValidRecord(boolean bDisplayOption)
{ // Copy the key field to the master file and BYPASS the BEHAVIORS
super.doValidRecord(bDisplayOption);
if (m_bMoveOnValid)
{
int iMoveType = DBConstants.SCREEN_MOVE; // Do trigger a record change.
this.moveTheData(bDisplayOption, iMoveType); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Sql[] generateSql(CreateSynonymStatement statement, Database database, SqlGeneratorChain chain) {
StringBuilder sql = new StringBuilder("CREATE ");
if (statement.isReplace() != null && statement.isReplace()) {
sql.append("OR REPLACE ");
}
if (statement.isPublic() != null && statement.isPublic()) {
sql.append("PUBLIC ");
}
sql.append("SYNONYM ");
if (statement.getSynonymSchemaName() != null) {
sql.append(statement.getSynonymSchemaName()).append(".");
}
sql.append(statement.getSynonymName());
sql.append(" FOR ");
if (statement.getObjectSchemaName() != null) {
sql.append(statement.getObjectSchemaName()).append(".");
}
sql.append(statement.getObjectName());
return new Sql[] { new UnparsedSql(sql.toString()) };
} } | public class class_name {
public Sql[] generateSql(CreateSynonymStatement statement, Database database, SqlGeneratorChain chain) {
StringBuilder sql = new StringBuilder("CREATE ");
if (statement.isReplace() != null && statement.isReplace()) {
sql.append("OR REPLACE "); // depends on control dependency: [if], data = [none]
}
if (statement.isPublic() != null && statement.isPublic()) {
sql.append("PUBLIC "); // depends on control dependency: [if], data = [none]
}
sql.append("SYNONYM ");
if (statement.getSynonymSchemaName() != null) {
sql.append(statement.getSynonymSchemaName()).append("."); // depends on control dependency: [if], data = [(statement.getSynonymSchemaName()]
}
sql.append(statement.getSynonymName());
sql.append(" FOR ");
if (statement.getObjectSchemaName() != null) {
sql.append(statement.getObjectSchemaName()).append("."); // depends on control dependency: [if], data = [(statement.getObjectSchemaName()]
}
sql.append(statement.getObjectName());
return new Sql[] { new UnparsedSql(sql.toString()) };
} } |
public class class_name {
public static ModuleConfig ensureModuleConfig( String modulePath, ServletContext context )
{
try
{
ModuleConfig ret = getModuleConfig( modulePath, context );
if ( ret != null )
{
return ret;
}
else
{
ActionServlet as = getActionServlet( context );
if ( as instanceof AutoRegisterActionServlet )
{
return ( ( AutoRegisterActionServlet ) as ).ensureModuleRegistered( modulePath );
}
}
}
catch ( IOException e )
{
_log.error( "Error while registering Struts module " + modulePath, e );
}
catch ( ServletException e )
{
_log.error( "Error while registering Struts module " + modulePath, e );
}
return null;
} } | public class class_name {
public static ModuleConfig ensureModuleConfig( String modulePath, ServletContext context )
{
try
{
ModuleConfig ret = getModuleConfig( modulePath, context );
if ( ret != null )
{
return ret; // depends on control dependency: [if], data = [none]
}
else
{
ActionServlet as = getActionServlet( context );
if ( as instanceof AutoRegisterActionServlet )
{
return ( ( AutoRegisterActionServlet ) as ).ensureModuleRegistered( modulePath ); // depends on control dependency: [if], data = [none]
}
}
}
catch ( IOException e )
{
_log.error( "Error while registering Struts module " + modulePath, e );
} // depends on control dependency: [catch], data = [none]
catch ( ServletException e )
{
_log.error( "Error while registering Struts module " + modulePath, e );
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
private AttributeType getEnrichedType(AttributeType guess, Object value) {
if (guess == null || value == null) {
return guess;
}
if (guess.equals(STRING)) {
String stringValue = value.toString();
if (stringValue.length() > MAX_STRING_LENGTH) {
return TEXT;
}
if (canValueBeUsedAsDate(value)) {
return DATE;
}
} else if (guess.equals(DECIMAL)) {
if (value instanceof Integer) {
return INT;
} else if (value instanceof Long) {
Long longValue = (Long) value;
return longValue > Integer.MIN_VALUE && longValue < Integer.MAX_VALUE ? INT : LONG;
} else if (value instanceof Double) {
Double doubleValue = (Double) value;
if (doubleValue != Math.rint(doubleValue)) {
return DECIMAL;
}
if (doubleValue > Integer.MIN_VALUE && doubleValue < Integer.MAX_VALUE) {
return INT;
}
if (doubleValue > Long.MIN_VALUE && doubleValue < Long.MAX_VALUE) {
return LONG;
}
}
}
return guess;
} } | public class class_name {
private AttributeType getEnrichedType(AttributeType guess, Object value) {
if (guess == null || value == null) {
return guess; // depends on control dependency: [if], data = [none]
}
if (guess.equals(STRING)) {
String stringValue = value.toString();
if (stringValue.length() > MAX_STRING_LENGTH) {
return TEXT; // depends on control dependency: [if], data = [none]
}
if (canValueBeUsedAsDate(value)) {
return DATE; // depends on control dependency: [if], data = [none]
}
} else if (guess.equals(DECIMAL)) {
if (value instanceof Integer) {
return INT; // depends on control dependency: [if], data = [none]
} else if (value instanceof Long) {
Long longValue = (Long) value;
return longValue > Integer.MIN_VALUE && longValue < Integer.MAX_VALUE ? INT : LONG; // depends on control dependency: [if], data = [none]
} else if (value instanceof Double) {
Double doubleValue = (Double) value;
if (doubleValue != Math.rint(doubleValue)) {
return DECIMAL; // depends on control dependency: [if], data = [none]
}
if (doubleValue > Integer.MIN_VALUE && doubleValue < Integer.MAX_VALUE) {
return INT; // depends on control dependency: [if], data = [none]
}
if (doubleValue > Long.MIN_VALUE && doubleValue < Long.MAX_VALUE) {
return LONG; // depends on control dependency: [if], data = [none]
}
}
}
return guess;
} } |
public class class_name {
public static void reset(Object object) {
if (object instanceof Activity) {
reset(object, ((Activity) object).getWindow().getDecorView().findViewById(android.R.id.content));
} else if (object instanceof Fragment) {
reset(object, ((Fragment) object).getView());
} else if (object instanceof View) {
reset(object, (View) object);
}
} } | public class class_name {
public static void reset(Object object) {
if (object instanceof Activity) {
reset(object, ((Activity) object).getWindow().getDecorView().findViewById(android.R.id.content)); // depends on control dependency: [if], data = [none]
} else if (object instanceof Fragment) {
reset(object, ((Fragment) object).getView()); // depends on control dependency: [if], data = [none]
} else if (object instanceof View) {
reset(object, (View) object); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setAttributeValues(java.util.Collection<String> attributeValues) {
if (attributeValues == null) {
this.attributeValues = null;
return;
}
this.attributeValues = new com.amazonaws.internal.SdkInternalList<String>(attributeValues);
} } | public class class_name {
public void setAttributeValues(java.util.Collection<String> attributeValues) {
if (attributeValues == null) {
this.attributeValues = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.attributeValues = new com.amazonaws.internal.SdkInternalList<String>(attributeValues);
} } |
public class class_name {
public synchronized void stop() {
if (timer != null) {
timer.keepRunning = false;
timer.interrupt();
timer = null;
}
// Remove this manager from the space alert list
LogRepositorySpaceAlert.getInstance().removeRepositoryInfo(this);
} } | public class class_name {
public synchronized void stop() {
if (timer != null) {
timer.keepRunning = false; // depends on control dependency: [if], data = [none]
timer.interrupt(); // depends on control dependency: [if], data = [none]
timer = null; // depends on control dependency: [if], data = [none]
}
// Remove this manager from the space alert list
LogRepositorySpaceAlert.getInstance().removeRepositoryInfo(this);
} } |
public class class_name {
public void acceptPrompt() {
String action = "Clicking 'OK' on a prompt";
String expected = "Prompt is present to be clicked";
if (isNotPrompt(action, expected, "click")) {
return;
}
accept(action, expected, "prompt");
} } | public class class_name {
public void acceptPrompt() {
String action = "Clicking 'OK' on a prompt";
String expected = "Prompt is present to be clicked";
if (isNotPrompt(action, expected, "click")) {
return; // depends on control dependency: [if], data = [none]
}
accept(action, expected, "prompt");
} } |
public class class_name {
public ProxyTargetLocator createProxyTargetLocator(BundleContext callingContext, Field field, Class<?> page,
Map<String, String> overwrites) {
BundleContext context;
if (page.getClassLoader() instanceof BundleReference) {
// Fetch the Bundlecontext of the page class to locate the service
BundleReference reference = (BundleReference) page.getClassLoader();
context = reference.getBundle().getBundleContext();
LOGGER.debug("Using the Bundlereference of class {} for locating services", page);
} else {
context = callingContext;
LOGGER.debug("Using the PAX Wicket BundlereContext for locating services");
}
Filter filter = getFilter(context, field);
// is it am Iterable?
Class<?> type = field.getType();
if (type.equals(Iterable.class)) {
Class<?> argument = BundleAnalysingComponentInstantiationListener.getGenericTypeArgument(field);
LOGGER.debug("Inject Iterable for type {}", argument);
return new StaticProxyTargetLocator(createIterable(argument, filter, context), page);
}
// or a supported collection...
if (type.equals(Collection.class) || type.equals(Set.class) || type.equals(List.class)) {
Class<?> argument = BundleAnalysingComponentInstantiationListener.getGenericTypeArgument(field);
LOGGER.debug("Inject Collection, Set or List for type {}", argument);
return new StaticProxyTargetLocator(createCollection(argument, filter, context), page);
}
OSGiServiceRegistryProxyTargetLocator locator =
new OSGiServiceRegistryProxyTargetLocator(context, filter,
type, page);
if (locator.fetchReferences() != null) {
return locator;
} else {
return null;
}
} } | public class class_name {
public ProxyTargetLocator createProxyTargetLocator(BundleContext callingContext, Field field, Class<?> page,
Map<String, String> overwrites) {
BundleContext context;
if (page.getClassLoader() instanceof BundleReference) {
// Fetch the Bundlecontext of the page class to locate the service
BundleReference reference = (BundleReference) page.getClassLoader();
context = reference.getBundle().getBundleContext(); // depends on control dependency: [if], data = [none]
LOGGER.debug("Using the Bundlereference of class {} for locating services", page); // depends on control dependency: [if], data = [none]
} else {
context = callingContext; // depends on control dependency: [if], data = [none]
LOGGER.debug("Using the PAX Wicket BundlereContext for locating services"); // depends on control dependency: [if], data = [none]
}
Filter filter = getFilter(context, field);
// is it am Iterable?
Class<?> type = field.getType();
if (type.equals(Iterable.class)) {
Class<?> argument = BundleAnalysingComponentInstantiationListener.getGenericTypeArgument(field);
LOGGER.debug("Inject Iterable for type {}", argument); // depends on control dependency: [if], data = [none]
return new StaticProxyTargetLocator(createIterable(argument, filter, context), page); // depends on control dependency: [if], data = [none]
}
// or a supported collection...
if (type.equals(Collection.class) || type.equals(Set.class) || type.equals(List.class)) {
Class<?> argument = BundleAnalysingComponentInstantiationListener.getGenericTypeArgument(field);
LOGGER.debug("Inject Collection, Set or List for type {}", argument); // depends on control dependency: [if], data = [none]
return new StaticProxyTargetLocator(createCollection(argument, filter, context), page); // depends on control dependency: [if], data = [none]
}
OSGiServiceRegistryProxyTargetLocator locator =
new OSGiServiceRegistryProxyTargetLocator(context, filter,
type, page);
if (locator.fetchReferences() != null) {
return locator; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static List<DrMemoryError> parse(File file, String charset) {
List<DrMemoryError> result = new ArrayList<>();
List<String> elements = getElements(file, charset);
for (String element : elements) {
Matcher m = RX_MESSAGE_FINDER.matcher(element);
if (m.find()) {
DrMemoryError error = new DrMemoryError();
error.type = extractErrorType(m.group(1));
String[] elementSplitted = CxxUtils.EOL_PATTERN.split(element);
error.message = elementSplitted[0];
for (String elementPart : elementSplitted) {
Matcher locationMatcher = RX_FILE_FINDER.matcher(elementPart);
if (locationMatcher.find()) {
Location location = new Location();
location.file = locationMatcher.group(1);
location.line = Integer.valueOf(locationMatcher.group(2));
error.stackTrace.add(location);
}
}
result.add(error);
}
}
return result;
} } | public class class_name {
public static List<DrMemoryError> parse(File file, String charset) {
List<DrMemoryError> result = new ArrayList<>();
List<String> elements = getElements(file, charset);
for (String element : elements) {
Matcher m = RX_MESSAGE_FINDER.matcher(element);
if (m.find()) {
DrMemoryError error = new DrMemoryError();
error.type = extractErrorType(m.group(1)); // depends on control dependency: [if], data = [none]
String[] elementSplitted = CxxUtils.EOL_PATTERN.split(element);
error.message = elementSplitted[0]; // depends on control dependency: [if], data = [none]
for (String elementPart : elementSplitted) {
Matcher locationMatcher = RX_FILE_FINDER.matcher(elementPart);
if (locationMatcher.find()) {
Location location = new Location();
location.file = locationMatcher.group(1); // depends on control dependency: [if], data = [none]
location.line = Integer.valueOf(locationMatcher.group(2)); // depends on control dependency: [if], data = [none]
error.stackTrace.add(location); // depends on control dependency: [if], data = [none]
}
}
result.add(error); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
protected Map<CmsUUID, CmsContainerConfigurationGroup> loadFromIds(Collection<CmsUUID> structureIds) {
Map<CmsUUID, CmsContainerConfigurationGroup> result = Maps.newHashMap();
for (CmsUUID id : structureIds) {
CmsContainerConfigurationGroup parsedGroup = null;
try {
CmsResource resource = m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = m_cms.readFile(resource);
CmsContainerConfigurationParser parser = new CmsContainerConfigurationParser(m_cms);
parser.parse(file);
parsedGroup = new CmsContainerConfigurationGroup(parser.getParsedResults());
parsedGroup.setResource(resource);
} catch (CmsVfsResourceNotFoundException e) {
LOG.debug(e.getLocalizedMessage(), e);
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
}
// if the group couldn't be read or parsed for some reason, the map value is null
result.put(id, parsedGroup);
}
return result;
} } | public class class_name {
protected Map<CmsUUID, CmsContainerConfigurationGroup> loadFromIds(Collection<CmsUUID> structureIds) {
Map<CmsUUID, CmsContainerConfigurationGroup> result = Maps.newHashMap();
for (CmsUUID id : structureIds) {
CmsContainerConfigurationGroup parsedGroup = null;
try {
CmsResource resource = m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = m_cms.readFile(resource);
CmsContainerConfigurationParser parser = new CmsContainerConfigurationParser(m_cms);
parser.parse(file);
// depends on control dependency: [try], data = [none]
parsedGroup = new CmsContainerConfigurationGroup(parser.getParsedResults());
// depends on control dependency: [try], data = [none]
parsedGroup.setResource(resource);
// depends on control dependency: [try], data = [none]
} catch (CmsVfsResourceNotFoundException e) {
LOG.debug(e.getLocalizedMessage(), e);
} catch (Throwable e) {
// depends on control dependency: [catch], data = [none]
LOG.error(e.getLocalizedMessage(), e);
}
// depends on control dependency: [catch], data = [none]
// if the group couldn't be read or parsed for some reason, the map value is null
result.put(id, parsedGroup);
// depends on control dependency: [for], data = [id]
}
return result;
} } |
public class class_name {
boolean updateTaskTrackerStatus(String trackerName,
TaskTrackerStatus status) {
TaskTracker tt = getTaskTracker(trackerName);
TaskTrackerStatus oldStatus = (tt == null) ? null : tt.getStatus();
// update the total cluster capacity first
if (status != null) {
// we have a fresh tasktracker status
if (!faultyTrackers.isBlacklisted(status.getHost())) {
// if the task tracker host is not blacklisted - then
// we update the cluster capacity with the capacity
// reported by the tasktracker
updateTotalTaskCapacity(status);
} else {
// if the tasktracker is blacklisted - then it's capacity
// is already removed and will only be added back to the
// cluster capacity when it's unblacklisted
}
} else {
if (oldStatus != null) {
// old status exists - but no new status. in this case
// we are removing the tracker from the cluster.
if (!faultyTrackers.isBlacklisted(oldStatus.getHost())) {
// we update the total task capacity based on the old status
// this seems redundant - but this call is idempotent - so just
// make it. the danger of not making it is that we may accidentally
// remove something we never had
updateTotalTaskCapacity(oldStatus);
removeTaskTrackerCapacity(oldStatus);
} else {
// if the host is blacklisted - then the tracker's capacity
// has already been removed and there's nothing to do
}
}
}
if (oldStatus != null) {
totalMaps -= oldStatus.countMapTasks();
totalReduces -= oldStatus.countReduceTasks();
occupiedMapSlots -= oldStatus.countOccupiedMapSlots();
occupiedReduceSlots -= oldStatus.countOccupiedReduceSlots();
getInstrumentation().decRunningMaps(oldStatus.countMapTasks());
getInstrumentation().decRunningReduces(oldStatus.countReduceTasks());
getInstrumentation().decOccupiedMapSlots(oldStatus.countOccupiedMapSlots());
getInstrumentation().decOccupiedReduceSlots(oldStatus.countOccupiedReduceSlots());
if (status == null) {
taskTrackers.remove(trackerName);
Integer numTaskTrackersInHost =
uniqueHostsMap.get(oldStatus.getHost());
if (numTaskTrackersInHost != null) {
numTaskTrackersInHost --;
if (numTaskTrackersInHost > 0) {
uniqueHostsMap.put(oldStatus.getHost(), numTaskTrackersInHost);
}
else {
uniqueHostsMap.remove(oldStatus.getHost());
}
}
}
}
if (status != null) {
totalMaps += status.countMapTasks();
totalReduces += status.countReduceTasks();
occupiedMapSlots += status.countOccupiedMapSlots();
occupiedReduceSlots += status.countOccupiedReduceSlots();
getInstrumentation().addRunningMaps(status.countMapTasks());
getInstrumentation().addRunningReduces(status.countReduceTasks());
getInstrumentation().addOccupiedMapSlots(status.countOccupiedMapSlots());
getInstrumentation().addOccupiedReduceSlots(status.countOccupiedReduceSlots());
boolean alreadyPresent = false;
TaskTracker taskTracker = taskTrackers.get(trackerName);
if (taskTracker != null) {
alreadyPresent = true;
} else {
taskTracker = new TaskTracker(trackerName);
}
taskTracker.setStatus(status);
taskTrackers.put(trackerName, taskTracker);
if (LOG.isDebugEnabled()) {
int runningMaps = 0, runningReduces = 0;
int commitPendingMaps = 0, commitPendingReduces = 0;
int unassignedMaps = 0, unassignedReduces = 0;
int miscMaps = 0, miscReduces = 0;
List<TaskStatus> taskReports = status.getTaskReports();
for (Iterator<TaskStatus> it = taskReports.iterator(); it.hasNext();) {
TaskStatus ts = (TaskStatus) it.next();
boolean isMap = ts.getIsMap();
TaskStatus.State state = ts.getRunState();
if (state == TaskStatus.State.RUNNING) {
if (isMap) { ++runningMaps; }
else { ++runningReduces; }
} else if (state == TaskStatus.State.UNASSIGNED) {
if (isMap) { ++unassignedMaps; }
else { ++unassignedReduces; }
} else if (state == TaskStatus.State.COMMIT_PENDING) {
if (isMap) { ++commitPendingMaps; }
else { ++commitPendingReduces; }
} else {
if (isMap) { ++miscMaps; }
else { ++miscReduces; }
}
}
LOG.debug(trackerName + ": Status -" +
" running(m) = " + runningMaps +
" unassigned(m) = " + unassignedMaps +
" commit_pending(m) = " + commitPendingMaps +
" misc(m) = " + miscMaps +
" running(r) = " + runningReduces +
" unassigned(r) = " + unassignedReduces +
" commit_pending(r) = " + commitPendingReduces +
" misc(r) = " + miscReduces);
}
if (!alreadyPresent) {
Integer numTaskTrackersInHost =
uniqueHostsMap.get(status.getHost());
if (numTaskTrackersInHost == null) {
numTaskTrackersInHost = 0;
}
numTaskTrackersInHost ++;
uniqueHostsMap.put(status.getHost(), numTaskTrackersInHost);
}
}
getInstrumentation().setMapSlots(totalMapTaskCapacity);
getInstrumentation().setReduceSlots(totalReduceTaskCapacity);
return oldStatus != null;
} } | public class class_name {
boolean updateTaskTrackerStatus(String trackerName,
TaskTrackerStatus status) {
TaskTracker tt = getTaskTracker(trackerName);
TaskTrackerStatus oldStatus = (tt == null) ? null : tt.getStatus();
// update the total cluster capacity first
if (status != null) {
// we have a fresh tasktracker status
if (!faultyTrackers.isBlacklisted(status.getHost())) {
// if the task tracker host is not blacklisted - then
// we update the cluster capacity with the capacity
// reported by the tasktracker
updateTotalTaskCapacity(status); // depends on control dependency: [if], data = [none]
} else {
// if the tasktracker is blacklisted - then it's capacity
// is already removed and will only be added back to the
// cluster capacity when it's unblacklisted
}
} else {
if (oldStatus != null) {
// old status exists - but no new status. in this case
// we are removing the tracker from the cluster.
if (!faultyTrackers.isBlacklisted(oldStatus.getHost())) {
// we update the total task capacity based on the old status
// this seems redundant - but this call is idempotent - so just
// make it. the danger of not making it is that we may accidentally
// remove something we never had
updateTotalTaskCapacity(oldStatus); // depends on control dependency: [if], data = [none]
removeTaskTrackerCapacity(oldStatus); // depends on control dependency: [if], data = [none]
} else {
// if the host is blacklisted - then the tracker's capacity
// has already been removed and there's nothing to do
}
}
}
if (oldStatus != null) {
totalMaps -= oldStatus.countMapTasks(); // depends on control dependency: [if], data = [none]
totalReduces -= oldStatus.countReduceTasks(); // depends on control dependency: [if], data = [none]
occupiedMapSlots -= oldStatus.countOccupiedMapSlots(); // depends on control dependency: [if], data = [none]
occupiedReduceSlots -= oldStatus.countOccupiedReduceSlots(); // depends on control dependency: [if], data = [none]
getInstrumentation().decRunningMaps(oldStatus.countMapTasks()); // depends on control dependency: [if], data = [(oldStatus]
getInstrumentation().decRunningReduces(oldStatus.countReduceTasks()); // depends on control dependency: [if], data = [(oldStatus]
getInstrumentation().decOccupiedMapSlots(oldStatus.countOccupiedMapSlots()); // depends on control dependency: [if], data = [(oldStatus]
getInstrumentation().decOccupiedReduceSlots(oldStatus.countOccupiedReduceSlots()); // depends on control dependency: [if], data = [(oldStatus]
if (status == null) {
taskTrackers.remove(trackerName); // depends on control dependency: [if], data = [none]
Integer numTaskTrackersInHost =
uniqueHostsMap.get(oldStatus.getHost());
if (numTaskTrackersInHost != null) {
numTaskTrackersInHost --; // depends on control dependency: [if], data = [none]
if (numTaskTrackersInHost > 0) {
uniqueHostsMap.put(oldStatus.getHost(), numTaskTrackersInHost); // depends on control dependency: [if], data = [none]
}
else {
uniqueHostsMap.remove(oldStatus.getHost()); // depends on control dependency: [if], data = [none]
}
}
}
}
if (status != null) {
totalMaps += status.countMapTasks(); // depends on control dependency: [if], data = [none]
totalReduces += status.countReduceTasks(); // depends on control dependency: [if], data = [none]
occupiedMapSlots += status.countOccupiedMapSlots(); // depends on control dependency: [if], data = [none]
occupiedReduceSlots += status.countOccupiedReduceSlots(); // depends on control dependency: [if], data = [none]
getInstrumentation().addRunningMaps(status.countMapTasks()); // depends on control dependency: [if], data = [(status]
getInstrumentation().addRunningReduces(status.countReduceTasks()); // depends on control dependency: [if], data = [(status]
getInstrumentation().addOccupiedMapSlots(status.countOccupiedMapSlots()); // depends on control dependency: [if], data = [(status]
getInstrumentation().addOccupiedReduceSlots(status.countOccupiedReduceSlots()); // depends on control dependency: [if], data = [(status]
boolean alreadyPresent = false;
TaskTracker taskTracker = taskTrackers.get(trackerName);
if (taskTracker != null) {
alreadyPresent = true; // depends on control dependency: [if], data = [none]
} else {
taskTracker = new TaskTracker(trackerName); // depends on control dependency: [if], data = [none]
}
taskTracker.setStatus(status); // depends on control dependency: [if], data = [(status]
taskTrackers.put(trackerName, taskTracker); // depends on control dependency: [if], data = [none]
if (LOG.isDebugEnabled()) {
int runningMaps = 0, runningReduces = 0;
int commitPendingMaps = 0, commitPendingReduces = 0;
int unassignedMaps = 0, unassignedReduces = 0;
int miscMaps = 0, miscReduces = 0;
List<TaskStatus> taskReports = status.getTaskReports();
for (Iterator<TaskStatus> it = taskReports.iterator(); it.hasNext();) {
TaskStatus ts = (TaskStatus) it.next();
boolean isMap = ts.getIsMap();
TaskStatus.State state = ts.getRunState();
if (state == TaskStatus.State.RUNNING) {
if (isMap) { ++runningMaps; } // depends on control dependency: [if], data = [none]
else { ++runningReduces; } // depends on control dependency: [if], data = [none]
} else if (state == TaskStatus.State.UNASSIGNED) {
if (isMap) { ++unassignedMaps; } // depends on control dependency: [if], data = [none]
else { ++unassignedReduces; } // depends on control dependency: [if], data = [none]
} else if (state == TaskStatus.State.COMMIT_PENDING) {
if (isMap) { ++commitPendingMaps; } // depends on control dependency: [if], data = [none]
else { ++commitPendingReduces; } // depends on control dependency: [if], data = [none]
} else {
if (isMap) { ++miscMaps; } // depends on control dependency: [if], data = [none]
else { ++miscReduces; } // depends on control dependency: [if], data = [none]
}
}
LOG.debug(trackerName + ": Status -" +
" running(m) = " + runningMaps +
" unassigned(m) = " + unassignedMaps +
" commit_pending(m) = " + commitPendingMaps +
" misc(m) = " + miscMaps +
" running(r) = " + runningReduces +
" unassigned(r) = " + unassignedReduces +
" commit_pending(r) = " + commitPendingReduces +
" misc(r) = " + miscReduces); // depends on control dependency: [if], data = [none]
}
if (!alreadyPresent) {
Integer numTaskTrackersInHost =
uniqueHostsMap.get(status.getHost());
if (numTaskTrackersInHost == null) {
numTaskTrackersInHost = 0; // depends on control dependency: [if], data = [none]
}
numTaskTrackersInHost ++; // depends on control dependency: [if], data = [none]
uniqueHostsMap.put(status.getHost(), numTaskTrackersInHost); // depends on control dependency: [if], data = [none]
}
}
getInstrumentation().setMapSlots(totalMapTaskCapacity);
getInstrumentation().setReduceSlots(totalReduceTaskCapacity);
return oldStatus != null;
} } |
public class class_name {
public void minus(LinearSparseVector sv) {
for (int r = 0; r < sv.length; r++) {
int p = Arrays.binarySearch(index, sv.index[r]);
if (p >= 0) {
data[p] = (float) data[p] - (float) sv.data[r];
} else {
put(sv.index[r], -(float) sv.data[r]);
}
}
} } | public class class_name {
public void minus(LinearSparseVector sv) {
for (int r = 0; r < sv.length; r++) {
int p = Arrays.binarySearch(index, sv.index[r]);
if (p >= 0) {
data[p] = (float) data[p] - (float) sv.data[r]; // depends on control dependency: [if], data = [none]
} else {
put(sv.index[r], -(float) sv.data[r]); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static boolean validateAuthorizationRequest(AuthRequestDto authRequestDto, OAuthApplicationDto oAuthApplicationDto) throws OAuthException {
if (StringUtils.isNotBlank(oAuthApplicationDto.getClientId()) && oAuthApplicationDto.getClientId().equals(authRequestDto.getClientId())) {
try {
String decodedRedirectUri = java.net.URLDecoder.decode(authRequestDto.getRedirectUri(), "UTF-8");
if (StringUtils.isNotBlank(oAuthApplicationDto.getRedirectUri()) && oAuthApplicationDto.getRedirectUri().equals(decodedRedirectUri)) {
return true;
} else {
_logger.info("Request Redirect URI '" + authRequestDto.getRedirectUri() + "' mismatch");
throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST);
}
} catch (UnsupportedEncodingException e) {
_logger.info("Request Redirect URI '" + authRequestDto.getRedirectUri() + "' mismatch");
throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST);
}
} else {
_logger.info("Request Client ID '" + authRequestDto.getClientId() + "' mismatch");
throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_CLIENT_ID, HttpResponseStatus.BAD_REQUEST);
}
} } | public class class_name {
public static boolean validateAuthorizationRequest(AuthRequestDto authRequestDto, OAuthApplicationDto oAuthApplicationDto) throws OAuthException {
if (StringUtils.isNotBlank(oAuthApplicationDto.getClientId()) && oAuthApplicationDto.getClientId().equals(authRequestDto.getClientId())) {
try {
String decodedRedirectUri = java.net.URLDecoder.decode(authRequestDto.getRedirectUri(), "UTF-8");
if (StringUtils.isNotBlank(oAuthApplicationDto.getRedirectUri()) && oAuthApplicationDto.getRedirectUri().equals(decodedRedirectUri)) {
return true; // depends on control dependency: [if], data = [none]
} else {
_logger.info("Request Redirect URI '" + authRequestDto.getRedirectUri() + "' mismatch"); // depends on control dependency: [if], data = [none]
throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST);
}
} catch (UnsupportedEncodingException e) {
_logger.info("Request Redirect URI '" + authRequestDto.getRedirectUri() + "' mismatch");
throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST);
} // depends on control dependency: [catch], data = [none]
} else {
_logger.info("Request Client ID '" + authRequestDto.getClientId() + "' mismatch");
throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_CLIENT_ID, HttpResponseStatus.BAD_REQUEST);
}
} } |
public class class_name {
protected Rectangle getRectWithOlds (Rectangle r, List<BubbleGlyph> oldbubs)
{
int n = oldbubs.size();
// if no old bubs, just return the new one.
if (n == 0) {
return r;
}
// otherwise, encompass all the oldies
Rectangle bigR = null;
for (int ii=0; ii < n; ii++) {
BubbleGlyph bub = oldbubs.get(ii);
if (ii == 0) {
bigR = bub.getBubbleBounds();
} else {
bigR = bigR.union(bub.getBubbleBounds());
}
}
// and add space for the new boy
bigR.width = Math.max(bigR.width, r.width);
bigR.height += r.height;
return bigR;
} } | public class class_name {
protected Rectangle getRectWithOlds (Rectangle r, List<BubbleGlyph> oldbubs)
{
int n = oldbubs.size();
// if no old bubs, just return the new one.
if (n == 0) {
return r; // depends on control dependency: [if], data = [none]
}
// otherwise, encompass all the oldies
Rectangle bigR = null;
for (int ii=0; ii < n; ii++) {
BubbleGlyph bub = oldbubs.get(ii);
if (ii == 0) {
bigR = bub.getBubbleBounds(); // depends on control dependency: [if], data = [none]
} else {
bigR = bigR.union(bub.getBubbleBounds()); // depends on control dependency: [if], data = [none]
}
}
// and add space for the new boy
bigR.width = Math.max(bigR.width, r.width);
bigR.height += r.height;
return bigR;
} } |
public class class_name {
@SuppressWarnings({"unchecked", "rawtypes"})
public <T extends BaseWrapper<T>> T create(final Object entity, boolean isRevision, final Class<T> wrapperClass) {
if (entity == null) {
return null;
}
// Create the key
final DBWrapperKey key = new DBWrapperKey(entity, wrapperClass);
// Check to see if a wrapper has already been cached for the key
final DBBaseWrapper cachedWrapper = wrapperCache.get(key);
if (cachedWrapper != null) {
return (T) cachedWrapper;
}
final DBBaseWrapper wrapper;
boolean local = true;
if (entity instanceof TagToCategory && wrapperClass == TagInCategoryWrapper.class) {
wrapper = new DBTagInCategoryWrapper(getProviderFactory(), (TagToCategory) entity, isRevision);
} else if (entity instanceof TagToCategory && wrapperClass == CategoryInTagWrapper.class) {
wrapper = new DBCategoryInTagWrapper(getProviderFactory(), (TagToCategory) entity, isRevision);
} else if (entity instanceof ContentSpec && wrapperClass == ContentSpecWrapper.class) {
// CONTENT SPEC
wrapper = new DBContentSpecWrapper(getProviderFactory(), (ContentSpec) entity, isRevision);
} else if (entity instanceof ContentSpec && wrapperClass == TextContentSpecWrapper.class) {
// TEXT CONTENT SPEC
wrapper = new DBTextContentSpecWrapper(getProviderFactory(), (ContentSpec) entity, isRevision);
} else if (entity instanceof TranslationServer && wrapperClass == TranslationServerWrapper.class) {
// TRANSLATION SERVER
wrapper = new DBTranslationServerWrapper(getProviderFactory(), (TranslationServer) entity);
} else if (entity instanceof TranslationServer && wrapperClass == TranslationServerWrapper.class) {
// TRANSLATION SERVER EXTENDED
wrapper = new DBTranslationServerWrapper(getProviderFactory(), (TranslationServer) entity);
} else {
wrapper = create(entity, isRevision);
local = false;
}
// Add the wrapper to the cache if it was found in this method
if (local) {
wrapperCache.put(key, wrapper);
}
return (T) wrapper;
} } | public class class_name {
@SuppressWarnings({"unchecked", "rawtypes"})
public <T extends BaseWrapper<T>> T create(final Object entity, boolean isRevision, final Class<T> wrapperClass) {
if (entity == null) {
return null; // depends on control dependency: [if], data = [none]
}
// Create the key
final DBWrapperKey key = new DBWrapperKey(entity, wrapperClass);
// Check to see if a wrapper has already been cached for the key
final DBBaseWrapper cachedWrapper = wrapperCache.get(key);
if (cachedWrapper != null) {
return (T) cachedWrapper; // depends on control dependency: [if], data = [none]
}
final DBBaseWrapper wrapper;
boolean local = true;
if (entity instanceof TagToCategory && wrapperClass == TagInCategoryWrapper.class) {
wrapper = new DBTagInCategoryWrapper(getProviderFactory(), (TagToCategory) entity, isRevision); // depends on control dependency: [if], data = [none]
} else if (entity instanceof TagToCategory && wrapperClass == CategoryInTagWrapper.class) {
wrapper = new DBCategoryInTagWrapper(getProviderFactory(), (TagToCategory) entity, isRevision); // depends on control dependency: [if], data = [none]
} else if (entity instanceof ContentSpec && wrapperClass == ContentSpecWrapper.class) {
// CONTENT SPEC
wrapper = new DBContentSpecWrapper(getProviderFactory(), (ContentSpec) entity, isRevision); // depends on control dependency: [if], data = [none]
} else if (entity instanceof ContentSpec && wrapperClass == TextContentSpecWrapper.class) {
// TEXT CONTENT SPEC
wrapper = new DBTextContentSpecWrapper(getProviderFactory(), (ContentSpec) entity, isRevision); // depends on control dependency: [if], data = [none]
} else if (entity instanceof TranslationServer && wrapperClass == TranslationServerWrapper.class) {
// TRANSLATION SERVER
wrapper = new DBTranslationServerWrapper(getProviderFactory(), (TranslationServer) entity); // depends on control dependency: [if], data = [none]
} else if (entity instanceof TranslationServer && wrapperClass == TranslationServerWrapper.class) {
// TRANSLATION SERVER EXTENDED
wrapper = new DBTranslationServerWrapper(getProviderFactory(), (TranslationServer) entity); // depends on control dependency: [if], data = [none]
} else {
wrapper = create(entity, isRevision); // depends on control dependency: [if], data = [none]
local = false; // depends on control dependency: [if], data = [none]
}
// Add the wrapper to the cache if it was found in this method
if (local) {
wrapperCache.put(key, wrapper); // depends on control dependency: [if], data = [none]
}
return (T) wrapper;
} } |
public class class_name {
public static int getAbsoluteLevel(@NotNull String path) {
if (StringUtils.isEmpty(path) || StringUtils.equals(path, "/")) {
return -1;
}
return StringUtils.countMatches(path, "/") - 1;
} } | public class class_name {
public static int getAbsoluteLevel(@NotNull String path) {
if (StringUtils.isEmpty(path) || StringUtils.equals(path, "/")) {
return -1; // depends on control dependency: [if], data = [none]
}
return StringUtils.countMatches(path, "/") - 1;
} } |
public class class_name {
public synchronized static Bitmap load(InputStream is, int width, int height) {
BitmapFactory.Options opt = null;
try {
opt = new BitmapFactory.Options();
if (width > 0 && height > 0) {
if (is.markSupported()) {
is.mark(is.available());
opt.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, opt);
opt.inSampleSize = calculateInSampleSize(opt, width, height);
is.reset();
}
}
opt.inJustDecodeBounds = false;
opt.inPurgeable = true;
opt.inInputShareable = true;
return BitmapFactory.decodeStream(new FlushedInputStream(is), null, opt);
} catch (Exception e) {
Log.e(TAG, "", e);
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.out.print(e.toString());
}
}
opt = null;
}
} } | public class class_name {
public synchronized static Bitmap load(InputStream is, int width, int height) {
BitmapFactory.Options opt = null;
try {
opt = new BitmapFactory.Options(); // depends on control dependency: [try], data = [none]
if (width > 0 && height > 0) {
if (is.markSupported()) {
is.mark(is.available()); // depends on control dependency: [if], data = [none]
opt.inJustDecodeBounds = true; // depends on control dependency: [if], data = [none]
BitmapFactory.decodeStream(is, null, opt); // depends on control dependency: [if], data = [none]
opt.inSampleSize = calculateInSampleSize(opt, width, height); // depends on control dependency: [if], data = [none]
is.reset(); // depends on control dependency: [if], data = [none]
}
}
opt.inJustDecodeBounds = false; // depends on control dependency: [try], data = [none]
opt.inPurgeable = true; // depends on control dependency: [try], data = [none]
opt.inInputShareable = true; // depends on control dependency: [try], data = [none]
return BitmapFactory.decodeStream(new FlushedInputStream(is), null, opt); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
Log.e(TAG, "", e);
return null;
} finally { // depends on control dependency: [catch], data = [none]
if (is != null) {
try {
is.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
System.out.print(e.toString());
} // depends on control dependency: [catch], data = [none]
}
opt = null;
}
} } |
public class class_name {
public Properties getProperties(String sslAliasName) throws SSLException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "getProperties", new Object[] { sslAliasName });
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Performing Java 2 Security Permission Check ...");
Tr.debug(tc, "Expecting : " + GET_SSLCONFIG.toString());
}
sm.checkPermission(GET_SSLCONFIG);
}
try {
// direct selection
if (sslAliasName != null && sslAliasName.length() > 0) {
Properties directSelectionProperties = SSLConfigManager.getInstance().getProperties(sslAliasName);
if (directSelectionProperties != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "getProperties -> direct");
return directSelectionProperties;
}
}
} catch (Exception e) {
FFDCFilter.processException(e, getClass().getName(), "getProperties", this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "The following exception occurred in getProperties().", new Object[] { e });
throw asSSLException(e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "getProperties -> null");
return null;
} } | public class class_name {
public Properties getProperties(String sslAliasName) throws SSLException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "getProperties", new Object[] { sslAliasName });
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Performing Java 2 Security Permission Check ..."); // depends on control dependency: [if], data = [none]
Tr.debug(tc, "Expecting : " + GET_SSLCONFIG.toString()); // depends on control dependency: [if], data = [none]
}
sm.checkPermission(GET_SSLCONFIG); // depends on control dependency: [if], data = [none]
}
try {
// direct selection
if (sslAliasName != null && sslAliasName.length() > 0) {
Properties directSelectionProperties = SSLConfigManager.getInstance().getProperties(sslAliasName);
if (directSelectionProperties != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "getProperties -> direct");
return directSelectionProperties; // depends on control dependency: [if], data = [none]
}
}
} catch (Exception e) {
FFDCFilter.processException(e, getClass().getName(), "getProperties", this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "The following exception occurred in getProperties().", new Object[] { e });
throw asSSLException(e);
} // depends on control dependency: [catch], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "getProperties -> null");
return null;
} } |
public class class_name {
public static CharIterator oF(final Supplier<char[]> arraySupplier) {
N.checkArgNotNull(arraySupplier, "arraySupplier");
return new CharIterator() {
private char[] aar = null;
private int len = 0;
private int cur = 0;
private boolean isInitialized = false;
@Override
public boolean hasNext() {
if (isInitialized == false) {
init();
}
return cur < len;
}
@Override
public char nextChar() {
if (isInitialized == false) {
init();
}
if (cur >= len) {
throw new NoSuchElementException();
}
return aar[cur++];
}
private void init() {
if (isInitialized == false) {
isInitialized = true;
aar = arraySupplier.get();
len = N.len(aar);
}
}
};
} } | public class class_name {
public static CharIterator oF(final Supplier<char[]> arraySupplier) {
N.checkArgNotNull(arraySupplier, "arraySupplier");
return new CharIterator() {
private char[] aar = null;
private int len = 0;
private int cur = 0;
private boolean isInitialized = false;
@Override
public boolean hasNext() {
if (isInitialized == false) {
init();
// depends on control dependency: [if], data = [none]
}
return cur < len;
}
@Override
public char nextChar() {
if (isInitialized == false) {
init();
// depends on control dependency: [if], data = [none]
}
if (cur >= len) {
throw new NoSuchElementException();
}
return aar[cur++];
}
private void init() {
if (isInitialized == false) {
isInitialized = true;
// depends on control dependency: [if], data = [none]
aar = arraySupplier.get();
// depends on control dependency: [if], data = [none]
len = N.len(aar);
// depends on control dependency: [if], data = [none]
}
}
};
} } |
public class class_name {
private void addPattern(MethodSpec.Builder method, String pattern) {
// Parse the pattern and populate the method body with instructions to format the date.
for (Node node : DATETIME_PARSER.parse(pattern)) {
if (node instanceof Text) {
method.addStatement("b.append($S)", ((Text)node).text());
} else if (node instanceof Field) {
Field field = (Field)node;
method.addStatement("formatField(d, '$L', $L, b)", field.ch(), field.width());
}
}
} } | public class class_name {
private void addPattern(MethodSpec.Builder method, String pattern) {
// Parse the pattern and populate the method body with instructions to format the date.
for (Node node : DATETIME_PARSER.parse(pattern)) {
if (node instanceof Text) {
method.addStatement("b.append($S)", ((Text)node).text()); // depends on control dependency: [if], data = [none]
} else if (node instanceof Field) {
Field field = (Field)node;
method.addStatement("formatField(d, '$L', $L, b)", field.ch(), field.width()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private String translateSchema(String schemaName) throws SQLException {
if (useSchemaDefault && schemaName != null
&& schemaName.length() == 0) {
ResultSet rs = executeSelect("SYSTEM_SCHEMAS", "IS_DEFAULT=TRUE");
if (rs.next()) {
return rs.getString(1);
}
return schemaName;
}
return schemaName;
} } | public class class_name {
private String translateSchema(String schemaName) throws SQLException {
if (useSchemaDefault && schemaName != null
&& schemaName.length() == 0) {
ResultSet rs = executeSelect("SYSTEM_SCHEMAS", "IS_DEFAULT=TRUE");
if (rs.next()) {
return rs.getString(1); // depends on control dependency: [if], data = [none]
}
return schemaName;
}
return schemaName;
} } |
public class class_name {
public static String parseBareAddress(String XMPPAddress) {
if (XMPPAddress == null) {
return null;
}
int slashIndex = XMPPAddress.indexOf("/");
if (slashIndex < 0) {
return XMPPAddress;
} else if (slashIndex == 0) {
return "";
} else {
return XMPPAddress.substring(0, slashIndex);
}
} } | public class class_name {
public static String parseBareAddress(String XMPPAddress) {
if (XMPPAddress == null) {
return null; // depends on control dependency: [if], data = [none]
}
int slashIndex = XMPPAddress.indexOf("/");
if (slashIndex < 0) {
return XMPPAddress; // depends on control dependency: [if], data = [none]
} else if (slashIndex == 0) {
return ""; // depends on control dependency: [if], data = [none]
} else {
return XMPPAddress.substring(0, slashIndex); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setAveragingEnabled(final boolean ENABLED) {
if (null == averagingEnabled) {
_averagingEnabled = ENABLED;
fireUpdateEvent(REDRAW_EVENT);
} else {
averagingEnabled.set(ENABLED);
}
} } | public class class_name {
public void setAveragingEnabled(final boolean ENABLED) {
if (null == averagingEnabled) {
_averagingEnabled = ENABLED; // depends on control dependency: [if], data = [none]
fireUpdateEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none]
} else {
averagingEnabled.set(ENABLED); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setSelection(int[] selectedIndicies) {
for (int index : selectedIndicies) {
if (index >= 0 && index < mSelection.length) {
mSelection[index] = true;
} else {
throw new IllegalArgumentException("Index " + index + " is out of bounds.");
}
}
refreshDisplayValue();
} } | public class class_name {
public void setSelection(int[] selectedIndicies) {
for (int index : selectedIndicies) {
if (index >= 0 && index < mSelection.length) {
mSelection[index] = true; // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Index " + index + " is out of bounds.");
}
}
refreshDisplayValue();
} } |
public class class_name {
public void marshall(ConfirmPublicVirtualInterfaceRequest confirmPublicVirtualInterfaceRequest, ProtocolMarshaller protocolMarshaller) {
if (confirmPublicVirtualInterfaceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(confirmPublicVirtualInterfaceRequest.getVirtualInterfaceId(), VIRTUALINTERFACEID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ConfirmPublicVirtualInterfaceRequest confirmPublicVirtualInterfaceRequest, ProtocolMarshaller protocolMarshaller) {
if (confirmPublicVirtualInterfaceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(confirmPublicVirtualInterfaceRequest.getVirtualInterfaceId(), VIRTUALINTERFACEID_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 boolean isLabeled(final String iEdgeLabel, final String[] iLabels) {
if (iLabels != null && iLabels.length > 0) {
// FILTER LABEL
if (iEdgeLabel != null)
for (String l : iLabels)
if (l.equals(iEdgeLabel))
// FOUND
return true;
// NOT FOUND
return false;
}
// NO LABELS
return true;
} } | public class class_name {
public static boolean isLabeled(final String iEdgeLabel, final String[] iLabels) {
if (iLabels != null && iLabels.length > 0) {
// FILTER LABEL
if (iEdgeLabel != null)
for (String l : iLabels)
if (l.equals(iEdgeLabel))
// FOUND
return true;
// NOT FOUND
return false; // depends on control dependency: [if], data = [none]
}
// NO LABELS
return true;
} } |
public class class_name {
protected void mergeEntityProperty(EntityPropertyDesc dest, EntityPropertyInfo src) {
dest.setEntityClassName(src.entityClass.getName());
dest.setPropertyClassName(src.propertyField.getType().getName());
Class<?> maybeNumberClass =
ClassUtil.toBoxedPrimitiveTypeIfPossible(src.propertyField.getType());
if (Number.class.isAssignableFrom(maybeNumberClass)) {
dest.setNumber(true);
}
if (src.version != null) {
dest.setVersion(true);
}
if (src.id != null) {
dest.setId(true);
if (src.generatedValue != null) {
switch (src.generatedValue.strategy()) {
case IDENTITY:
dest.setGenerationType(GenerationType.IDENTITY);
break;
case SEQUENCE:
dest.setGenerationType(GenerationType.SEQUENCE);
if (src.sequenceGenerator != null) {
dest.setInitialValue(src.sequenceGenerator.initialValue());
dest.setAllocationSize(src.sequenceGenerator.allocationSize());
dest.setAllocationSize(src.sequenceGenerator.allocationSize());
}
break;
case TABLE:
dest.setGenerationType(GenerationType.TABLE);
if (src.tableGenerator != null) {
dest.setInitialValue(src.tableGenerator.initialValue());
dest.setAllocationSize(src.tableGenerator.allocationSize());
dest.setAllocationSize(src.tableGenerator.allocationSize());
}
break;
default:
break;
}
}
}
} } | public class class_name {
protected void mergeEntityProperty(EntityPropertyDesc dest, EntityPropertyInfo src) {
dest.setEntityClassName(src.entityClass.getName());
dest.setPropertyClassName(src.propertyField.getType().getName());
Class<?> maybeNumberClass =
ClassUtil.toBoxedPrimitiveTypeIfPossible(src.propertyField.getType());
if (Number.class.isAssignableFrom(maybeNumberClass)) {
dest.setNumber(true); // depends on control dependency: [if], data = [none]
}
if (src.version != null) {
dest.setVersion(true); // depends on control dependency: [if], data = [none]
}
if (src.id != null) {
dest.setId(true); // depends on control dependency: [if], data = [none]
if (src.generatedValue != null) {
switch (src.generatedValue.strategy()) {
case IDENTITY:
dest.setGenerationType(GenerationType.IDENTITY);
break;
case SEQUENCE:
dest.setGenerationType(GenerationType.SEQUENCE);
if (src.sequenceGenerator != null) {
dest.setInitialValue(src.sequenceGenerator.initialValue()); // depends on control dependency: [if], data = [(src.sequenceGenerator]
dest.setAllocationSize(src.sequenceGenerator.allocationSize()); // depends on control dependency: [if], data = [(src.sequenceGenerator]
dest.setAllocationSize(src.sequenceGenerator.allocationSize()); // depends on control dependency: [if], data = [(src.sequenceGenerator]
}
break;
case TABLE:
dest.setGenerationType(GenerationType.TABLE);
if (src.tableGenerator != null) {
dest.setInitialValue(src.tableGenerator.initialValue()); // depends on control dependency: [if], data = [(src.tableGenerator]
dest.setAllocationSize(src.tableGenerator.allocationSize()); // depends on control dependency: [if], data = [(src.tableGenerator]
dest.setAllocationSize(src.tableGenerator.allocationSize()); // depends on control dependency: [if], data = [(src.tableGenerator]
}
break;
default:
break;
}
}
}
} } |
public class class_name {
public void setPartitionValues(java.util.Collection<String> partitionValues) {
if (partitionValues == null) {
this.partitionValues = null;
return;
}
this.partitionValues = new java.util.ArrayList<String>(partitionValues);
} } | public class class_name {
public void setPartitionValues(java.util.Collection<String> partitionValues) {
if (partitionValues == null) {
this.partitionValues = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.partitionValues = new java.util.ArrayList<String>(partitionValues);
} } |
public class class_name {
@Override
public double calculateScaleForBondLength(double modelBondLength) {
if (Double.isNaN(modelBondLength) || modelBondLength == 0) {
return DEFAULT_SCALE;
} else {
return rendererModel.getParameter(BondLength.class).getValue() / modelBondLength;
}
} } | public class class_name {
@Override
public double calculateScaleForBondLength(double modelBondLength) {
if (Double.isNaN(modelBondLength) || modelBondLength == 0) {
return DEFAULT_SCALE; // depends on control dependency: [if], data = [none]
} else {
return rendererModel.getParameter(BondLength.class).getValue() / modelBondLength; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Handler
@SuppressWarnings("PMD.ConfusingTernary")
public void onConfigurationUpdate(ConfigurationUpdate event) {
event.values(componentPath()).ifPresent(values -> {
String hostname = values.get("hostname");
if (hostname != null) {
setServerAddress(new InetSocketAddress(hostname,
Integer.parseInt(values.getOrDefault("port", "0"))));
} else if (values.containsKey("port")) {
setServerAddress(new InetSocketAddress(
Integer.parseInt(values.get("port"))));
}
Optional.ofNullable(values.get("backlog")).ifPresent(
value -> setBacklog(Integer.parseInt(value)));
Optional.ofNullable(values.get("bufferSize")).ifPresent(
value -> setBufferSize(Integer.parseInt(value)));
});
} } | public class class_name {
@Handler
@SuppressWarnings("PMD.ConfusingTernary")
public void onConfigurationUpdate(ConfigurationUpdate event) {
event.values(componentPath()).ifPresent(values -> {
String hostname = values.get("hostname");
if (hostname != null) {
setServerAddress(new InetSocketAddress(hostname,
Integer.parseInt(values.getOrDefault("port", "0")))); // depends on control dependency: [if], data = [(hostname]
} else if (values.containsKey("port")) {
setServerAddress(new InetSocketAddress(
Integer.parseInt(values.get("port")))); // depends on control dependency: [if], data = [none]
}
Optional.ofNullable(values.get("backlog")).ifPresent(
value -> setBacklog(Integer.parseInt(value)));
Optional.ofNullable(values.get("bufferSize")).ifPresent(
value -> setBufferSize(Integer.parseInt(value)));
});
} } |
public class class_name {
@Override
public void serve(Data data) throws IOException {
if (!isRegistered()) {
register();
}
if (data.getContent().size() >= SegmentationHelper.DEFAULT_SEGMENT_SIZE) {
InputStream stream = new ByteArrayInputStream(data.getContent().getImmutableArray());
List<Data> segments = SegmentationHelper.segment(data, stream);
for (Data segment : segments) {
logger.fine("Adding segment: " + segment.getName().toUri());
repository.put(segment);
}
} else {
logger.fine("Adding segment: " + data.getName().toUri());
repository.put(data);
}
} } | public class class_name {
@Override
public void serve(Data data) throws IOException {
if (!isRegistered()) {
register();
}
if (data.getContent().size() >= SegmentationHelper.DEFAULT_SEGMENT_SIZE) {
InputStream stream = new ByteArrayInputStream(data.getContent().getImmutableArray());
List<Data> segments = SegmentationHelper.segment(data, stream);
for (Data segment : segments) {
logger.fine("Adding segment: " + segment.getName().toUri()); // depends on control dependency: [for], data = [segment]
repository.put(segment); // depends on control dependency: [for], data = [segment]
}
} else {
logger.fine("Adding segment: " + data.getName().toUri());
repository.put(data);
}
} } |
public class class_name {
public synchronized Map<String, String> hashURLs(URL[] urls) {
Map<String, String> hashes = new HashMap<String, String>();
for (URL url : urls) {
if (url != null) {
String externalForm = url.toExternalForm();
String hash = hashURL(url, externalForm);
hashes.put(externalForm, hash);
}
}
return hashes;
} } | public class class_name {
public synchronized Map<String, String> hashURLs(URL[] urls) {
Map<String, String> hashes = new HashMap<String, String>();
for (URL url : urls) {
if (url != null) {
String externalForm = url.toExternalForm();
String hash = hashURL(url, externalForm);
hashes.put(externalForm, hash); // depends on control dependency: [if], data = [none]
}
}
return hashes;
} } |
public class class_name {
@Override
public void initDownstream()
{
if (direction == RIGHT_TO_LEFT)
{
for (PhysicalEntity pe : conv.getLeft())
{
addToDownstream(pe, getGraph());
}
}
else
{
for (PhysicalEntity pe : conv.getRight())
{
addToDownstream(pe, getGraph());
}
}
} } | public class class_name {
@Override
public void initDownstream()
{
if (direction == RIGHT_TO_LEFT)
{
for (PhysicalEntity pe : conv.getLeft())
{
addToDownstream(pe, getGraph());
// depends on control dependency: [for], data = [pe]
}
}
else
{
for (PhysicalEntity pe : conv.getRight())
{
addToDownstream(pe, getGraph());
// depends on control dependency: [for], data = [pe]
}
}
} } |
public class class_name {
public static void printTableMeta(String outputDirPath, File pdfFile, String meta) {
try {
File middleDir = new File(outputDirPath, "metadata");
if (!middleDir.exists()) {
middleDir.mkdirs();
}
File tableMetaFile = new File(middleDir, pdfFile.getName() + ".metadata");
BufferedWriter bw0 = new BufferedWriter(new FileWriter(tableMetaFile));
//System.out.println(meta);
bw0.write(meta);
bw0.close();
}
catch (IOException e){
System.out.printf("[Debug Error] IOException\n");
}
} } | public class class_name {
public static void printTableMeta(String outputDirPath, File pdfFile, String meta) {
try {
File middleDir = new File(outputDirPath, "metadata");
if (!middleDir.exists()) {
middleDir.mkdirs();
// depends on control dependency: [if], data = [none]
}
File tableMetaFile = new File(middleDir, pdfFile.getName() + ".metadata");
BufferedWriter bw0 = new BufferedWriter(new FileWriter(tableMetaFile));
//System.out.println(meta);
bw0.write(meta);
// depends on control dependency: [try], data = [none]
bw0.close();
// depends on control dependency: [try], data = [none]
}
catch (IOException e){
System.out.printf("[Debug Error] IOException\n");
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T> ConfigurationOptionBuilder<T> serviceLoaderStrategyOption(Class<T> serviceLoaderInterface) {
final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(ClassInstanceValueConverter.of(serviceLoaderInterface), serviceLoaderInterface);
for (T impl : ServiceLoader.load(serviceLoaderInterface, ConfigurationOption.class.getClassLoader())) {
optionBuilder.addValidOption(impl);
}
optionBuilder.sealValidOptions();
return optionBuilder;
} } | public class class_name {
public static <T> ConfigurationOptionBuilder<T> serviceLoaderStrategyOption(Class<T> serviceLoaderInterface) {
final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(ClassInstanceValueConverter.of(serviceLoaderInterface), serviceLoaderInterface);
for (T impl : ServiceLoader.load(serviceLoaderInterface, ConfigurationOption.class.getClassLoader())) {
optionBuilder.addValidOption(impl); // depends on control dependency: [for], data = [impl]
}
optionBuilder.sealValidOptions();
return optionBuilder;
} } |
public class class_name {
public @NonNull AbstractQuery set(@NonNull String name, @Nullable Object value) {
if (value == null) {
parameters.remove(name);
} else {
parameters.put(name, value.toString());
}
return this;
} } | public class class_name {
public @NonNull AbstractQuery set(@NonNull String name, @Nullable Object value) {
if (value == null) {
parameters.remove(name); // depends on control dependency: [if], data = [none]
} else {
parameters.put(name, value.toString()); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
protected String toSignMessageURI(String uri) {
LoaEnum loa = LoaEnum.parse(uri);
if (loa == null) {
return null;
}
if (loa.isSignatureMessageUri()) {
return uri;
}
for (LoaEnum l : LoaEnum.values()) {
if (l.getBaseUri().equals(loa.getBaseUri()) && l.isSignatureMessageUri() && l.isNotified() == loa.isNotified()) {
return l.getUri();
}
}
return null;
} } | public class class_name {
protected String toSignMessageURI(String uri) {
LoaEnum loa = LoaEnum.parse(uri);
if (loa == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (loa.isSignatureMessageUri()) {
return uri; // depends on control dependency: [if], data = [none]
}
for (LoaEnum l : LoaEnum.values()) {
if (l.getBaseUri().equals(loa.getBaseUri()) && l.isSignatureMessageUri() && l.isNotified() == loa.isNotified()) {
return l.getUri(); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public void storeKeys(Iterator<K> iterator) {
long startedNanos = System.nanoTime();
FileOutputStream fos = null;
try {
buf = allocate(BUFFER_SIZE);
lastWrittenBytes = 0;
lastKeyCount = 0;
fos = new FileOutputStream(tmpStoreFile, false);
// write header and keys
writeInt(fos, MAGIC_BYTES);
writeInt(fos, FileFormat.INTERLEAVED_LENGTH_FIELD.ordinal());
writeKeySet(fos, fos.getChannel(), iterator);
// cleanup if no keys have been written
if (lastKeyCount == 0) {
deleteQuietly(storeFile);
updatePersistenceStats(startedNanos);
return;
}
fos.flush();
closeResource(fos);
rename(tmpStoreFile, storeFile);
updatePersistenceStats(startedNanos);
} catch (Exception e) {
logger.warning(format("Could not store keys of Near Cache %s (%s)", nearCacheName, storeFile.getAbsolutePath()), e);
nearCacheStats.addPersistenceFailure(e);
} finally {
closeResource(fos);
deleteQuietly(tmpStoreFile);
}
} } | public class class_name {
public void storeKeys(Iterator<K> iterator) {
long startedNanos = System.nanoTime();
FileOutputStream fos = null;
try {
buf = allocate(BUFFER_SIZE); // depends on control dependency: [try], data = [none]
lastWrittenBytes = 0; // depends on control dependency: [try], data = [none]
lastKeyCount = 0; // depends on control dependency: [try], data = [none]
fos = new FileOutputStream(tmpStoreFile, false); // depends on control dependency: [try], data = [none]
// write header and keys
writeInt(fos, MAGIC_BYTES); // depends on control dependency: [try], data = [none]
writeInt(fos, FileFormat.INTERLEAVED_LENGTH_FIELD.ordinal()); // depends on control dependency: [try], data = [none]
writeKeySet(fos, fos.getChannel(), iterator); // depends on control dependency: [try], data = [none]
// cleanup if no keys have been written
if (lastKeyCount == 0) {
deleteQuietly(storeFile); // depends on control dependency: [if], data = [none]
updatePersistenceStats(startedNanos); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
fos.flush(); // depends on control dependency: [try], data = [none]
closeResource(fos); // depends on control dependency: [try], data = [none]
rename(tmpStoreFile, storeFile); // depends on control dependency: [try], data = [none]
updatePersistenceStats(startedNanos); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.warning(format("Could not store keys of Near Cache %s (%s)", nearCacheName, storeFile.getAbsolutePath()), e);
nearCacheStats.addPersistenceFailure(e);
} finally { // depends on control dependency: [catch], data = [none]
closeResource(fos);
deleteQuietly(tmpStoreFile);
}
} } |
public class class_name {
public void resolve(@Nullable View view, @NonNull HttpRequest request, @NonNull HttpResponse response) {
if (view == null) return;
Object output = view.output();
if (output == null) return;
if (view.rest()) {
resolveRest(output, request, response);
} else {
resolvePath(output, request, response);
}
} } | public class class_name {
public void resolve(@Nullable View view, @NonNull HttpRequest request, @NonNull HttpResponse response) {
if (view == null) return;
Object output = view.output();
if (output == null) return;
if (view.rest()) {
resolveRest(output, request, response); // depends on control dependency: [if], data = [none]
} else {
resolvePath(output, request, response); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
List<Object> getSortedRules() {
List<Object> result = new ArrayList<Object>();
for (RuleEntry entry : getSortedEntries()) {
result.add(entry.rule);
}
return result;
} } | public class class_name {
List<Object> getSortedRules() {
List<Object> result = new ArrayList<Object>();
for (RuleEntry entry : getSortedEntries()) {
result.add(entry.rule); // depends on control dependency: [for], data = [entry]
}
return result;
} } |
public class class_name {
public void marshall(EventSubscription eventSubscription, ProtocolMarshaller protocolMarshaller) {
if (eventSubscription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(eventSubscription.getCustomerAwsId(), CUSTOMERAWSID_BINDING);
protocolMarshaller.marshall(eventSubscription.getCustSubscriptionId(), CUSTSUBSCRIPTIONID_BINDING);
protocolMarshaller.marshall(eventSubscription.getSnsTopicArn(), SNSTOPICARN_BINDING);
protocolMarshaller.marshall(eventSubscription.getStatus(), STATUS_BINDING);
protocolMarshaller.marshall(eventSubscription.getSubscriptionCreationTime(), SUBSCRIPTIONCREATIONTIME_BINDING);
protocolMarshaller.marshall(eventSubscription.getSourceType(), SOURCETYPE_BINDING);
protocolMarshaller.marshall(eventSubscription.getSourceIdsList(), SOURCEIDSLIST_BINDING);
protocolMarshaller.marshall(eventSubscription.getEventCategoriesList(), EVENTCATEGORIESLIST_BINDING);
protocolMarshaller.marshall(eventSubscription.getEnabled(), ENABLED_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(EventSubscription eventSubscription, ProtocolMarshaller protocolMarshaller) {
if (eventSubscription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(eventSubscription.getCustomerAwsId(), CUSTOMERAWSID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eventSubscription.getCustSubscriptionId(), CUSTSUBSCRIPTIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eventSubscription.getSnsTopicArn(), SNSTOPICARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eventSubscription.getStatus(), STATUS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eventSubscription.getSubscriptionCreationTime(), SUBSCRIPTIONCREATIONTIME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eventSubscription.getSourceType(), SOURCETYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eventSubscription.getSourceIdsList(), SOURCEIDSLIST_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eventSubscription.getEventCategoriesList(), EVENTCATEGORIESLIST_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(eventSubscription.getEnabled(), ENABLED_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 register(final Object listener) {
for (Class clazz = listener.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (!m.isAnnotationPresent(Subscribe.class)) continue;
Class[] params = m.getParameterTypes();
if (params.length != 1)
throw new IllegalArgumentException("Method " + m + " has @Subscribe annotation" +
"and requires " + params.length +
" arguments, but event-handling methods must require just one argument");
Class event = params[0];
EventHandler handler = new EventHandler(listener, m);
this.handlersByEventType.put(event, handler);
}
}
} } | public class class_name {
public void register(final Object listener) {
for (Class clazz = listener.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (!m.isAnnotationPresent(Subscribe.class)) continue;
Class[] params = m.getParameterTypes();
if (params.length != 1)
throw new IllegalArgumentException("Method " + m + " has @Subscribe annotation" +
"and requires " + params.length +
" arguments, but event-handling methods must require just one argument");
Class event = params[0];
EventHandler handler = new EventHandler(listener, m);
this.handlersByEventType.put(event, handler); // depends on control dependency: [for], data = [none]
}
}
} } |
public class class_name {
private static boolean parseInputArgs(String[] args) {
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(OPTIONS, args);
} catch (ParseException e) {
System.out.println("Failed to parse input args: " + e);
return false;
}
sHelp = cmd.hasOption("help");
sMaster = cmd.getOptionValue("master", "FileSystemMaster");
sStart = Long.decode(cmd.getOptionValue("start", "0"));
sEnd = Long.decode(cmd.getOptionValue("end", Long.valueOf(Long.MAX_VALUE).toString()));
sOutputDir =
new File(cmd.getOptionValue("outputDir", "journal_dump-" + System.currentTimeMillis()))
.getAbsolutePath();
sCheckpointsDir = PathUtils.concatPath(sOutputDir, "checkpoints");
sJournalEntryFile = PathUtils.concatPath(sOutputDir, "edits.txt");
return true;
} } | public class class_name {
private static boolean parseInputArgs(String[] args) {
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(OPTIONS, args); // depends on control dependency: [try], data = [none]
} catch (ParseException e) {
System.out.println("Failed to parse input args: " + e);
return false;
} // depends on control dependency: [catch], data = [none]
sHelp = cmd.hasOption("help");
sMaster = cmd.getOptionValue("master", "FileSystemMaster");
sStart = Long.decode(cmd.getOptionValue("start", "0"));
sEnd = Long.decode(cmd.getOptionValue("end", Long.valueOf(Long.MAX_VALUE).toString()));
sOutputDir =
new File(cmd.getOptionValue("outputDir", "journal_dump-" + System.currentTimeMillis()))
.getAbsolutePath();
sCheckpointsDir = PathUtils.concatPath(sOutputDir, "checkpoints");
sJournalEntryFile = PathUtils.concatPath(sOutputDir, "edits.txt");
return true;
} } |
public class class_name {
private int recoverTransaction(final int iTxId) throws IOException {
int recordsRecovered = 0;
final ORecordId rid = new ORecordId();
final List<Long> txRecordPositions = new ArrayList<Long>();
// BROWSE ALL THE ENTRIES
for (long beginEntry = 0; eof(beginEntry); beginEntry = nextEntry(beginEntry)) {
long offset = beginEntry;
final byte status = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
if (status != STATUS_FREE) {
// DIRTY TX LOG ENTRY
offset += OBinaryProtocol.SIZE_BYTE;
final int txId = file.readInt(offset);
if (txId == iTxId) {
txRecordPositions.add(beginEntry);
}
}
}
for (int i = txRecordPositions.size() - 1; i >= 0; i--) {
final long beginEntry = txRecordPositions.get(i);
long offset = beginEntry;
final byte status = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
// DIRTY TX LOG ENTRY
final byte operation = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
// TX ID FOUND
final int txId = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
rid.clusterId = file.readShort(offset);
offset += OBinaryProtocol.SIZE_SHORT;
rid.clusterPosition = file.readLong(offset);
offset += OBinaryProtocol.SIZE_LONG;
final byte recordType = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
final int recordVersion = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final int dataSegmentId = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final int recordSize = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final byte[] buffer;
if (recordSize > 0) {
buffer = new byte[recordSize];
file.read(offset, buffer, recordSize);
offset += recordSize;
} else
buffer = null;
recoverTransactionEntry(status, operation, txId, rid, recordType, recordVersion, buffer, dataSegmentId);
recordsRecovered++;
// CLEAR THE ENTRY BY WRITING '0'
file.writeByte(beginEntry, STATUS_FREE);
}
return recordsRecovered;
} } | public class class_name {
private int recoverTransaction(final int iTxId) throws IOException {
int recordsRecovered = 0;
final ORecordId rid = new ORecordId();
final List<Long> txRecordPositions = new ArrayList<Long>();
// BROWSE ALL THE ENTRIES
for (long beginEntry = 0; eof(beginEntry); beginEntry = nextEntry(beginEntry)) {
long offset = beginEntry;
final byte status = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
if (status != STATUS_FREE) {
// DIRTY TX LOG ENTRY
offset += OBinaryProtocol.SIZE_BYTE;
// depends on control dependency: [if], data = [none]
final int txId = file.readInt(offset);
if (txId == iTxId) {
txRecordPositions.add(beginEntry);
// depends on control dependency: [if], data = [none]
}
}
}
for (int i = txRecordPositions.size() - 1; i >= 0; i--) {
final long beginEntry = txRecordPositions.get(i);
long offset = beginEntry;
final byte status = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
// DIRTY TX LOG ENTRY
final byte operation = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
// TX ID FOUND
final int txId = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
rid.clusterId = file.readShort(offset);
offset += OBinaryProtocol.SIZE_SHORT;
rid.clusterPosition = file.readLong(offset);
offset += OBinaryProtocol.SIZE_LONG;
final byte recordType = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
final int recordVersion = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final int dataSegmentId = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final int recordSize = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final byte[] buffer;
if (recordSize > 0) {
buffer = new byte[recordSize];
// depends on control dependency: [if], data = [none]
file.read(offset, buffer, recordSize);
// depends on control dependency: [if], data = [none]
offset += recordSize;
// depends on control dependency: [if], data = [none]
} else
buffer = null;
recoverTransactionEntry(status, operation, txId, rid, recordType, recordVersion, buffer, dataSegmentId);
recordsRecovered++;
// CLEAR THE ENTRY BY WRITING '0'
file.writeByte(beginEntry, STATUS_FREE);
}
return recordsRecovered;
} } |
public class class_name {
@Deprecated
public void reset() {
if (!isIoAligned() || getIoThread() == Thread.currentThread()) {
reset0();
}
else {
getIoExecutor().execute(new Runnable() {
@Override
public void run() {
reset0();
}
});
}
} } | public class class_name {
@Deprecated
public void reset() {
if (!isIoAligned() || getIoThread() == Thread.currentThread()) {
reset0(); // depends on control dependency: [if], data = [none]
}
else {
getIoExecutor().execute(new Runnable() {
@Override
public void run() {
reset0();
}
}); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected boolean containsRel100(Message message) {
ListIterator<SIPHeader> requireHeaders = message.getHeaders(RequireHeader.NAME);
if(requireHeaders != null) {
while (requireHeaders.hasNext()) {
if(REL100_OPTION_TAG.equals(requireHeaders.next().getValue())) {
return true;
}
}
}
ListIterator<SIPHeader> supportedHeaders = message.getHeaders(SupportedHeader.NAME);
if(supportedHeaders != null) {
while (supportedHeaders.hasNext()) {
if(REL100_OPTION_TAG.equals(supportedHeaders.next().getValue())) {
return true;
}
}
}
return false;
} } | public class class_name {
protected boolean containsRel100(Message message) {
ListIterator<SIPHeader> requireHeaders = message.getHeaders(RequireHeader.NAME);
if(requireHeaders != null) {
while (requireHeaders.hasNext()) {
if(REL100_OPTION_TAG.equals(requireHeaders.next().getValue())) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
ListIterator<SIPHeader> supportedHeaders = message.getHeaders(SupportedHeader.NAME);
if(supportedHeaders != null) {
while (supportedHeaders.hasNext()) {
if(REL100_OPTION_TAG.equals(supportedHeaders.next().getValue())) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
protected MongodbQueueFactory<T, ID, DATA> setDefaultMongoClient(MongoClient mongoClient,
boolean setMyOwnMongoClient) {
if (myOwnMongoClient && this.defaultMongoClient != null) {
this.defaultMongoClient.close();
}
this.defaultMongoClient = mongoClient;
myOwnMongoClient = setMyOwnMongoClient;
return this;
} } | public class class_name {
protected MongodbQueueFactory<T, ID, DATA> setDefaultMongoClient(MongoClient mongoClient,
boolean setMyOwnMongoClient) {
if (myOwnMongoClient && this.defaultMongoClient != null) {
this.defaultMongoClient.close(); // depends on control dependency: [if], data = [none]
}
this.defaultMongoClient = mongoClient;
myOwnMongoClient = setMyOwnMongoClient;
return this;
} } |
public class class_name {
private void encodePropertyStates(CodeAssembler a, LocalVariable encodedVar,
int offset, StorableProperty<S>[] properties)
{
LocalVariable stateFieldVar = a.createLocalVariable(null, TypeDesc.INT);
int lastFieldOrdinal = -1;
LocalVariable accumVar = a.createLocalVariable(null, TypeDesc.INT);
int accumShift = 0;
for (int i=0; i<properties.length; i++) {
StorableProperty<S> property = properties[i];
int fieldOrdinal = property.getNumber() >> 4;
if (fieldOrdinal == lastFieldOrdinal) {
a.loadLocal(stateFieldVar);
} else {
a.loadThis();
a.loadField(PROPERTY_STATE_FIELD_NAME + fieldOrdinal, TypeDesc.INT);
a.storeLocal(stateFieldVar);
a.loadLocal(stateFieldVar);
lastFieldOrdinal = fieldOrdinal;
}
int stateShift = (property.getNumber() & 0xf) * 2;
int accumPack = 2;
int mask = PROPERTY_STATE_MASK << stateShift;
// Try to pack more state properties into one operation.
while ((accumShift + accumPack) < 8) {
if (i + 1 >= properties.length) {
// No more properties to encode.
break;
}
StorableProperty<S> nextProperty = properties[i + 1];
if (property.getNumber() + 1 != nextProperty.getNumber()) {
// Properties are not consecutive.
break;
}
if (fieldOrdinal != (nextProperty.getNumber() >> 4)) {
// Property states are stored in different fields.
break;
}
accumPack += 2;
mask |= PROPERTY_STATE_MASK << ((nextProperty.getNumber() & 0xf) * 2);
property = nextProperty;
i++;
}
a.loadConstant(mask);
a.math(Opcode.IAND);
if (stateShift < accumShift) {
a.loadConstant(accumShift - stateShift);
a.math(Opcode.ISHL);
} else if (stateShift > accumShift) {
a.loadConstant(stateShift - accumShift);
a.math(Opcode.IUSHR);
}
if (accumShift != 0) {
a.loadLocal(accumVar);
a.math(Opcode.IOR);
}
a.storeLocal(accumVar);
if ((accumShift += accumPack) >= 8) {
// Accumulator is full, so copy it to byte array.
a.loadLocal(encodedVar);
a.loadConstant(offset++);
a.loadLocal(accumVar);
a.storeToArray(TypeDesc.BYTE);
accumShift = 0;
}
}
if (accumShift > 0) {
// Copy remaining states.
a.loadLocal(encodedVar);
a.loadConstant(offset++);
a.loadLocal(accumVar);
a.storeToArray(TypeDesc.BYTE);
}
} } | public class class_name {
private void encodePropertyStates(CodeAssembler a, LocalVariable encodedVar,
int offset, StorableProperty<S>[] properties)
{
LocalVariable stateFieldVar = a.createLocalVariable(null, TypeDesc.INT);
int lastFieldOrdinal = -1;
LocalVariable accumVar = a.createLocalVariable(null, TypeDesc.INT);
int accumShift = 0;
for (int i=0; i<properties.length; i++) {
StorableProperty<S> property = properties[i];
int fieldOrdinal = property.getNumber() >> 4;
if (fieldOrdinal == lastFieldOrdinal) {
a.loadLocal(stateFieldVar);
// depends on control dependency: [if], data = [none]
} else {
a.loadThis();
// depends on control dependency: [if], data = [none]
a.loadField(PROPERTY_STATE_FIELD_NAME + fieldOrdinal, TypeDesc.INT);
// depends on control dependency: [if], data = [none]
a.storeLocal(stateFieldVar);
// depends on control dependency: [if], data = [none]
a.loadLocal(stateFieldVar);
// depends on control dependency: [if], data = [none]
lastFieldOrdinal = fieldOrdinal;
// depends on control dependency: [if], data = [none]
}
int stateShift = (property.getNumber() & 0xf) * 2;
int accumPack = 2;
int mask = PROPERTY_STATE_MASK << stateShift;
// Try to pack more state properties into one operation.
while ((accumShift + accumPack) < 8) {
if (i + 1 >= properties.length) {
// No more properties to encode.
break;
}
StorableProperty<S> nextProperty = properties[i + 1];
if (property.getNumber() + 1 != nextProperty.getNumber()) {
// Properties are not consecutive.
break;
}
if (fieldOrdinal != (nextProperty.getNumber() >> 4)) {
// Property states are stored in different fields.
break;
}
accumPack += 2;
// depends on control dependency: [while], data = [none]
mask |= PROPERTY_STATE_MASK << ((nextProperty.getNumber() & 0xf) * 2);
// depends on control dependency: [while], data = [none]
property = nextProperty;
// depends on control dependency: [while], data = [none]
i++;
// depends on control dependency: [while], data = [none]
}
a.loadConstant(mask);
// depends on control dependency: [for], data = [none]
a.math(Opcode.IAND);
// depends on control dependency: [for], data = [none]
if (stateShift < accumShift) {
a.loadConstant(accumShift - stateShift);
// depends on control dependency: [if], data = [none]
a.math(Opcode.ISHL);
// depends on control dependency: [if], data = [none]
} else if (stateShift > accumShift) {
a.loadConstant(stateShift - accumShift);
// depends on control dependency: [if], data = [(stateShift]
a.math(Opcode.IUSHR);
// depends on control dependency: [if], data = [none]
}
if (accumShift != 0) {
a.loadLocal(accumVar);
// depends on control dependency: [if], data = [none]
a.math(Opcode.IOR);
// depends on control dependency: [if], data = [none]
}
a.storeLocal(accumVar);
// depends on control dependency: [for], data = [none]
if ((accumShift += accumPack) >= 8) {
// Accumulator is full, so copy it to byte array.
a.loadLocal(encodedVar);
// depends on control dependency: [if], data = [none]
a.loadConstant(offset++);
// depends on control dependency: [if], data = [none]
a.loadLocal(accumVar);
// depends on control dependency: [if], data = [none]
a.storeToArray(TypeDesc.BYTE);
// depends on control dependency: [if], data = [none]
accumShift = 0;
// depends on control dependency: [if], data = [none]
}
}
if (accumShift > 0) {
// Copy remaining states.
a.loadLocal(encodedVar);
// depends on control dependency: [if], data = [none]
a.loadConstant(offset++);
// depends on control dependency: [if], data = [none]
a.loadLocal(accumVar);
// depends on control dependency: [if], data = [none]
a.storeToArray(TypeDesc.BYTE);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String data() {
if (datasets.isEmpty()) {
return "";
} else {
final StringBuilder ret = new StringBuilder();
int biggestSize = 0;
for (final Dataset dataset : datasets) {
biggestSize = Math.max(biggestSize, dataset.numPoints());
}
for (int row = 0; row < biggestSize; ++row) {
ret.append(valueOrBlank(datasets.get(0), row));
// all dataset vlaues but first are prefixed with tab
for (final Dataset dataset : Iterables.skip(datasets, 1)) {
ret.append("\t");
ret.append(valueOrBlank(dataset, row));
}
ret.append("\n");
}
return ret.toString();
}
} } | public class class_name {
private String data() {
if (datasets.isEmpty()) {
return ""; // depends on control dependency: [if], data = [none]
} else {
final StringBuilder ret = new StringBuilder();
int biggestSize = 0;
for (final Dataset dataset : datasets) {
biggestSize = Math.max(biggestSize, dataset.numPoints()); // depends on control dependency: [for], data = [dataset]
}
for (int row = 0; row < biggestSize; ++row) {
ret.append(valueOrBlank(datasets.get(0), row)); // depends on control dependency: [for], data = [row]
// all dataset vlaues but first are prefixed with tab
for (final Dataset dataset : Iterables.skip(datasets, 1)) {
ret.append("\t"); // depends on control dependency: [for], data = [none]
ret.append(valueOrBlank(dataset, row)); // depends on control dependency: [for], data = [dataset]
}
ret.append("\n"); // depends on control dependency: [for], data = [none]
}
return ret.toString(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void readPrevAvgRecordMillis(SourceState state) {
Map<String, List<Double>> prevAvgMillis = Maps.newHashMap();
for (WorkUnitState workUnitState : state.getPreviousWorkUnitStates()) {
List<KafkaPartition> partitions = KafkaUtils.getPartitions(workUnitState);
for (KafkaPartition partition : partitions) {
if (KafkaUtils.containsPartitionAvgRecordMillis(workUnitState, partition)) {
double prevAvgMillisForPartition = KafkaUtils.getPartitionAvgRecordMillis(workUnitState, partition);
if (prevAvgMillis.containsKey(partition.getTopicName())) {
prevAvgMillis.get(partition.getTopicName()).add(prevAvgMillisForPartition);
} else {
prevAvgMillis.put(partition.getTopicName(), Lists.newArrayList(prevAvgMillisForPartition));
}
}
}
}
this.estAvgMillis.clear();
if (prevAvgMillis.isEmpty()) {
this.avgEstAvgMillis = 1.0;
} else {
List<Double> allEstAvgMillis = Lists.newArrayList();
for (Map.Entry<String, List<Double>> entry : prevAvgMillis.entrySet()) {
String topic = entry.getKey();
List<Double> prevAvgMillisForPartitions = entry.getValue();
// If a topic has k partitions, and in the previous run, each partition recorded its avg time to pull
// a record, then use the geometric mean of these k numbers as the estimated avg time to pull
// a record in this run.
double estAvgMillisForTopic = geometricMean(prevAvgMillisForPartitions);
this.estAvgMillis.put(topic, estAvgMillisForTopic);
LOG.info(String.format("Estimated avg time to pull a record for topic %s is %f milliseconds", topic,
estAvgMillisForTopic));
allEstAvgMillis.add(estAvgMillisForTopic);
}
// If a topic was not pulled in the previous run, use this.avgEstAvgMillis as the estimated avg time
// to pull a record in this run, which is the geometric mean of all topics whose avg times to pull
// a record in the previous run are known.
this.avgEstAvgMillis = geometricMean(allEstAvgMillis);
}
LOG.info("For all topics not pulled in the previous run, estimated avg time to pull a record is "
+ this.avgEstAvgMillis + " milliseconds");
} } | public class class_name {
private void readPrevAvgRecordMillis(SourceState state) {
Map<String, List<Double>> prevAvgMillis = Maps.newHashMap();
for (WorkUnitState workUnitState : state.getPreviousWorkUnitStates()) {
List<KafkaPartition> partitions = KafkaUtils.getPartitions(workUnitState);
for (KafkaPartition partition : partitions) {
if (KafkaUtils.containsPartitionAvgRecordMillis(workUnitState, partition)) {
double prevAvgMillisForPartition = KafkaUtils.getPartitionAvgRecordMillis(workUnitState, partition);
if (prevAvgMillis.containsKey(partition.getTopicName())) {
prevAvgMillis.get(partition.getTopicName()).add(prevAvgMillisForPartition); // depends on control dependency: [if], data = [none]
} else {
prevAvgMillis.put(partition.getTopicName(), Lists.newArrayList(prevAvgMillisForPartition)); // depends on control dependency: [if], data = [none]
}
}
}
}
this.estAvgMillis.clear();
if (prevAvgMillis.isEmpty()) {
this.avgEstAvgMillis = 1.0; // depends on control dependency: [if], data = [none]
} else {
List<Double> allEstAvgMillis = Lists.newArrayList();
for (Map.Entry<String, List<Double>> entry : prevAvgMillis.entrySet()) {
String topic = entry.getKey();
List<Double> prevAvgMillisForPartitions = entry.getValue();
// If a topic has k partitions, and in the previous run, each partition recorded its avg time to pull
// a record, then use the geometric mean of these k numbers as the estimated avg time to pull
// a record in this run.
double estAvgMillisForTopic = geometricMean(prevAvgMillisForPartitions);
this.estAvgMillis.put(topic, estAvgMillisForTopic); // depends on control dependency: [for], data = [none]
LOG.info(String.format("Estimated avg time to pull a record for topic %s is %f milliseconds", topic,
estAvgMillisForTopic)); // depends on control dependency: [for], data = [none]
allEstAvgMillis.add(estAvgMillisForTopic); // depends on control dependency: [for], data = [none]
}
// If a topic was not pulled in the previous run, use this.avgEstAvgMillis as the estimated avg time
// to pull a record in this run, which is the geometric mean of all topics whose avg times to pull
// a record in the previous run are known.
this.avgEstAvgMillis = geometricMean(allEstAvgMillis); // depends on control dependency: [if], data = [none]
}
LOG.info("For all topics not pulled in the previous run, estimated avg time to pull a record is "
+ this.avgEstAvgMillis + " milliseconds");
} } |
public class class_name {
@Override
public int countByC_C(long CPDefinitionId, String CPInstanceUuid) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_C_C;
Object[] finderArgs = new Object[] { CPDefinitionId, CPInstanceUuid };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_CPINSTANCE_WHERE);
query.append(_FINDER_COLUMN_C_C_CPDEFINITIONID_2);
boolean bindCPInstanceUuid = false;
if (CPInstanceUuid == null) {
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_1);
}
else if (CPInstanceUuid.equals("")) {
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_3);
}
else {
bindCPInstanceUuid = true;
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(CPDefinitionId);
if (bindCPInstanceUuid) {
qPos.add(CPInstanceUuid);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} } | public class class_name {
@Override
public int countByC_C(long CPDefinitionId, String CPInstanceUuid) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_C_C;
Object[] finderArgs = new Object[] { CPDefinitionId, CPInstanceUuid };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_CPINSTANCE_WHERE); // depends on control dependency: [if], data = [none]
query.append(_FINDER_COLUMN_C_C_CPDEFINITIONID_2); // depends on control dependency: [if], data = [none]
boolean bindCPInstanceUuid = false;
if (CPInstanceUuid == null) {
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_1); // depends on control dependency: [if], data = [none]
}
else if (CPInstanceUuid.equals("")) {
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_3); // depends on control dependency: [if], data = [none]
}
else {
bindCPInstanceUuid = true; // depends on control dependency: [if], data = [none]
query.append(_FINDER_COLUMN_C_C_CPINSTANCEUUID_2); // depends on control dependency: [if], data = [none]
}
String sql = query.toString();
Session session = null;
try {
session = openSession(); // depends on control dependency: [try], data = [none]
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(CPDefinitionId); // depends on control dependency: [try], data = [none]
if (bindCPInstanceUuid) {
qPos.add(CPInstanceUuid); // depends on control dependency: [if], data = [none]
}
count = (Long)q.uniqueResult(); // depends on control dependency: [try], data = [none]
finderCache.putResult(finderPath, finderArgs, count); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
} // depends on control dependency: [catch], data = [none]
finally {
closeSession(session);
}
}
return count.intValue();
} } |
public class class_name {
@Override
public CollectionAttribute<X, ?> getDeclaredCollection(String paramName)
{
PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);
if (isCollectionAttribute(declaredAttrib))
{
return (CollectionAttribute<X, ?>) declaredAttrib;
}
throw new IllegalArgumentException(
"attribute of the given name and type is not present in the managed type, for name:" + paramName);
} } | public class class_name {
@Override
public CollectionAttribute<X, ?> getDeclaredCollection(String paramName)
{
PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);
if (isCollectionAttribute(declaredAttrib))
{
return (CollectionAttribute<X, ?>) declaredAttrib; // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException(
"attribute of the given name and type is not present in the managed type, for name:" + paramName);
} } |
public class class_name {
public boolean isModifiedOnVersion(String version) {
if (version == null || version.isEmpty()) {
return true;
}
for (ModificationRecord record : this.modificationRecordList) {
if (record.isModifiedOnVersion(version)) {
return true;
}
}
return false;
} } | public class class_name {
public boolean isModifiedOnVersion(String version) {
if (version == null || version.isEmpty()) {
return true; // depends on control dependency: [if], data = [none]
}
for (ModificationRecord record : this.modificationRecordList) {
if (record.isModifiedOnVersion(version)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public String toWKT() {
StringBuffer sb = new StringBuffer();
sb.append("POLYGON (");
boolean isFirstLoop = true;
for (List<XYZPoint> loop : m_loops) {
if (!isFirstLoop) {
sb.append(", ");
}
sb.append("(");
int startIdx = (isFirstLoop ? 1 : loop.size()-1);
int endIdx = (isFirstLoop ? loop.size() : 0);
int increment = (isFirstLoop ? 1 : -1);
sb.append(loop.get(0).toGeographyPointValue().formatLngLat()).append(", ");
for (int idx = startIdx; idx != endIdx; idx += increment) {
XYZPoint xyz = loop.get(idx);
sb.append(xyz.toGeographyPointValue().formatLngLat());
sb.append(", ");
}
// Repeat the start vertex to close the loop as WKT requires.
sb.append(loop.get(0).toGeographyPointValue().formatLngLat());
sb.append(")");
isFirstLoop = false;
}
sb.append(")");
return sb.toString();
} } | public class class_name {
public String toWKT() {
StringBuffer sb = new StringBuffer();
sb.append("POLYGON (");
boolean isFirstLoop = true;
for (List<XYZPoint> loop : m_loops) {
if (!isFirstLoop) {
sb.append(", "); // depends on control dependency: [if], data = [none]
}
sb.append("("); // depends on control dependency: [for], data = [none]
int startIdx = (isFirstLoop ? 1 : loop.size()-1);
int endIdx = (isFirstLoop ? loop.size() : 0);
int increment = (isFirstLoop ? 1 : -1);
sb.append(loop.get(0).toGeographyPointValue().formatLngLat()).append(", "); // depends on control dependency: [for], data = [loop]
for (int idx = startIdx; idx != endIdx; idx += increment) {
XYZPoint xyz = loop.get(idx);
sb.append(xyz.toGeographyPointValue().formatLngLat()); // depends on control dependency: [for], data = [none]
sb.append(", "); // depends on control dependency: [for], data = [none]
}
// Repeat the start vertex to close the loop as WKT requires.
sb.append(loop.get(0).toGeographyPointValue().formatLngLat()); // depends on control dependency: [for], data = [loop]
sb.append(")"); // depends on control dependency: [for], data = [none]
isFirstLoop = false; // depends on control dependency: [for], data = [none]
}
sb.append(")");
return sb.toString();
} } |
public class class_name {
static <T> ProtofieldEncoder<T> makeNullableFieldEncoder(final ProtofieldEncoder<T> baseEncoder, final boolean isNullable) {
if ( isNullable ) {
return (ProtoStreamWriter outProtobuf, T value) -> {
if ( value != null ) {
baseEncoder.encode( outProtobuf, value );
}
};
}
else {
return baseEncoder;
}
} } | public class class_name {
static <T> ProtofieldEncoder<T> makeNullableFieldEncoder(final ProtofieldEncoder<T> baseEncoder, final boolean isNullable) {
if ( isNullable ) {
return (ProtoStreamWriter outProtobuf, T value) -> {
if ( value != null ) { // depends on control dependency: [if], data = [none]
baseEncoder.encode( outProtobuf, value );
}
};
}
else {
return baseEncoder;
}
} } |
public class class_name {
protected void appendMapKey(StringBuilder buffer, Map<String, Object> params) {
if (params==null || params.isEmpty()) {
buffer.append(EMPTY_MAP_STRING);
buffer.append(OPENING_BRACKET);
} else {
buffer.append(OPENING_BRACKET);
Map map = new LinkedHashMap<>(params);
final String requestControllerName = getRequestStateLookupStrategy().getControllerName();
if (map.get(UrlMapping.ACTION) != null && map.get(UrlMapping.CONTROLLER) == null && map.get(RESOURCE_PREFIX) == null) {
Object action = map.remove(UrlMapping.ACTION);
map.put(UrlMapping.CONTROLLER, requestControllerName);
map.put(UrlMapping.ACTION, action);
}
if (map.get(UrlMapping.NAMESPACE) == null && map.get(UrlMapping.CONTROLLER) == requestControllerName) {
String namespace = getRequestStateLookupStrategy().getControllerNamespace();
if (GrailsStringUtils.isNotEmpty(namespace)) {
map.put(UrlMapping.NAMESPACE, namespace);
}
}
boolean first = true;
for (Object o : map.entrySet()) {
Map.Entry entry = (Map.Entry) o;
Object value = entry.getValue();
if (value == null) continue;
first = appendCommaIfNotFirst(buffer, first);
Object key = entry.getKey();
if (RESOURCE_PREFIX.equals(key)) {
value = getCacheKeyValueForResource(value);
}
appendKeyValue(buffer, map, key, value);
}
}
buffer.append(CLOSING_BRACKET);
} } | public class class_name {
protected void appendMapKey(StringBuilder buffer, Map<String, Object> params) {
if (params==null || params.isEmpty()) {
buffer.append(EMPTY_MAP_STRING); // depends on control dependency: [if], data = [none]
buffer.append(OPENING_BRACKET); // depends on control dependency: [if], data = [none]
} else {
buffer.append(OPENING_BRACKET); // depends on control dependency: [if], data = [none]
Map map = new LinkedHashMap<>(params);
final String requestControllerName = getRequestStateLookupStrategy().getControllerName();
if (map.get(UrlMapping.ACTION) != null && map.get(UrlMapping.CONTROLLER) == null && map.get(RESOURCE_PREFIX) == null) {
Object action = map.remove(UrlMapping.ACTION);
map.put(UrlMapping.CONTROLLER, requestControllerName); // depends on control dependency: [if], data = [none]
map.put(UrlMapping.ACTION, action); // depends on control dependency: [if], data = [none]
}
if (map.get(UrlMapping.NAMESPACE) == null && map.get(UrlMapping.CONTROLLER) == requestControllerName) {
String namespace = getRequestStateLookupStrategy().getControllerNamespace();
if (GrailsStringUtils.isNotEmpty(namespace)) {
map.put(UrlMapping.NAMESPACE, namespace); // depends on control dependency: [if], data = [none]
}
}
boolean first = true;
for (Object o : map.entrySet()) {
Map.Entry entry = (Map.Entry) o;
Object value = entry.getValue();
if (value == null) continue;
first = appendCommaIfNotFirst(buffer, first); // depends on control dependency: [for], data = [o]
Object key = entry.getKey();
if (RESOURCE_PREFIX.equals(key)) {
value = getCacheKeyValueForResource(value); // depends on control dependency: [if], data = [none]
}
appendKeyValue(buffer, map, key, value); // depends on control dependency: [for], data = [none]
}
}
buffer.append(CLOSING_BRACKET);
} } |
public class class_name {
public static <T> Class<T> box(Class<T> type)
{
Class<T> boxedType;
if (Boolean.TYPE.equals(type))
{
boxedType = (Class<T>) Boolean.class;
}
else if (Byte.TYPE.equals(type))
{
boxedType = (Class<T>) Byte.class;
}
else if (Short.TYPE.equals(type))
{
boxedType = (Class<T>) Short.class;
}
else if (Integer.TYPE.equals(type))
{
boxedType = (Class<T>) Integer.class;
}
else if (Long.TYPE.equals(type))
{
boxedType = (Class<T>) Long.class;
}
else if (Character.TYPE.equals(type))
{
boxedType = (Class<T>) Character.class;
}
else if (Float.TYPE.equals(type))
{
boxedType = (Class<T>) Float.class;
}
else if (Double.TYPE.equals(type))
{
boxedType = (Class<T>) Double.class;
}
else
{
boxedType = type;
}
return boxedType;
} } | public class class_name {
public static <T> Class<T> box(Class<T> type)
{
Class<T> boxedType;
if (Boolean.TYPE.equals(type))
{
boxedType = (Class<T>) Boolean.class; // depends on control dependency: [if], data = [none]
}
else if (Byte.TYPE.equals(type))
{
boxedType = (Class<T>) Byte.class; // depends on control dependency: [if], data = [none]
}
else if (Short.TYPE.equals(type))
{
boxedType = (Class<T>) Short.class; // depends on control dependency: [if], data = [none]
}
else if (Integer.TYPE.equals(type))
{
boxedType = (Class<T>) Integer.class; // depends on control dependency: [if], data = [none]
}
else if (Long.TYPE.equals(type))
{
boxedType = (Class<T>) Long.class; // depends on control dependency: [if], data = [none]
}
else if (Character.TYPE.equals(type))
{
boxedType = (Class<T>) Character.class; // depends on control dependency: [if], data = [none]
}
else if (Float.TYPE.equals(type))
{
boxedType = (Class<T>) Float.class; // depends on control dependency: [if], data = [none]
}
else if (Double.TYPE.equals(type))
{
boxedType = (Class<T>) Double.class; // depends on control dependency: [if], data = [none]
}
else
{
boxedType = type; // depends on control dependency: [if], data = [none]
}
return boxedType;
} } |
public class class_name {
private static void deleteOldFile(final File file) {
if (!file.exists()) {
return;
}
LOG.debug("删除旧文件:{}", file);
boolean success = file.delete();
if (!success) {
LOG.warn("删除文件失败:{}", file);
}
} } | public class class_name {
private static void deleteOldFile(final File file) {
if (!file.exists()) {
return;
// depends on control dependency: [if], data = [none]
}
LOG.debug("删除旧文件:{}", file);
boolean success = file.delete();
if (!success) {
LOG.warn("删除文件失败:{}", file);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Nonnull
public DataBuilder appendBrowserPattern(@Nonnull final BrowserPattern pattern) {
Check.notNull(pattern, "pattern");
if (!browserPatterns.containsKey(pattern.getId())) {
browserPatterns.put(pattern.getId(), new TreeSet<BrowserPattern>(BROWSER_PATTERN_COMPARATOR));
}
browserPatterns.get(pattern.getId()).add(pattern);
return this;
} } | public class class_name {
@Nonnull
public DataBuilder appendBrowserPattern(@Nonnull final BrowserPattern pattern) {
Check.notNull(pattern, "pattern");
if (!browserPatterns.containsKey(pattern.getId())) {
browserPatterns.put(pattern.getId(), new TreeSet<BrowserPattern>(BROWSER_PATTERN_COMPARATOR)); // depends on control dependency: [if], data = [none]
}
browserPatterns.get(pattern.getId()).add(pattern);
return this;
} } |
public class class_name {
private void readPackageListFromFile(String path, DocFile pkgListPath)
throws Fault {
DocFile file = pkgListPath.resolve(DocPaths.PACKAGE_LIST);
if (! (file.isAbsolute() || linkoffline)){
file = file.resolveAgainst(DocumentationTool.Location.DOCUMENTATION_OUTPUT);
}
try {
if (file.exists() && file.canRead()) {
boolean pathIsRelative =
!DocFile.createFileForInput(configuration, path).isAbsolute()
&& !isUrl(path);
readPackageList(file.openInputStream(), path, pathIsRelative);
} else {
throw new Fault(configuration.getText("doclet.File_error", file.getPath()), null);
}
} catch (IOException exc) {
throw new Fault(configuration.getText("doclet.File_error", file.getPath()), exc);
}
} } | public class class_name {
private void readPackageListFromFile(String path, DocFile pkgListPath)
throws Fault {
DocFile file = pkgListPath.resolve(DocPaths.PACKAGE_LIST);
if (! (file.isAbsolute() || linkoffline)){
file = file.resolveAgainst(DocumentationTool.Location.DOCUMENTATION_OUTPUT);
}
try {
if (file.exists() && file.canRead()) {
boolean pathIsRelative =
!DocFile.createFileForInput(configuration, path).isAbsolute()
&& !isUrl(path);
readPackageList(file.openInputStream(), path, pathIsRelative); // depends on control dependency: [if], data = [none]
} else {
throw new Fault(configuration.getText("doclet.File_error", file.getPath()), null);
}
} catch (IOException exc) {
throw new Fault(configuration.getText("doclet.File_error", file.getPath()), exc);
}
} } |
public class class_name {
private boolean isCurrentRepositoryBackup(File log)
{
for (RepositoryBackupChain chain : currentRepositoryBackups)
{
if (log.getName().equals(new File(chain.getLogFilePath()).getName()))
{
return true;
}
}
return false;
} } | public class class_name {
private boolean isCurrentRepositoryBackup(File log)
{
for (RepositoryBackupChain chain : currentRepositoryBackups)
{
if (log.getName().equals(new File(chain.getLogFilePath()).getName()))
{
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Override
protected int doHashCode() {
final OtpErlangObject.Hash hash = new OtpErlangObject.Hash(7);
hash.combine(creation, ids[0]);
if (isNewRef()) {
hash.combine(ids[1], ids[2]);
}
return hash.valueOf();
} } | public class class_name {
@Override
protected int doHashCode() {
final OtpErlangObject.Hash hash = new OtpErlangObject.Hash(7);
hash.combine(creation, ids[0]);
if (isNewRef()) {
hash.combine(ids[1], ids[2]); // depends on control dependency: [if], data = [none]
}
return hash.valueOf();
} } |
public class class_name {
public FindingFilter withRuleNames(String... ruleNames) {
if (this.ruleNames == null) {
setRuleNames(new java.util.ArrayList<String>(ruleNames.length));
}
for (String ele : ruleNames) {
this.ruleNames.add(ele);
}
return this;
} } | public class class_name {
public FindingFilter withRuleNames(String... ruleNames) {
if (this.ruleNames == null) {
setRuleNames(new java.util.ArrayList<String>(ruleNames.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : ruleNames) {
this.ruleNames.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void addSwipeListener(SwipeListener listener) {
if (mListeners == null) {
mListeners = new ArrayList<SwipeListener>();
}
mListeners.add(listener);
} } | public class class_name {
public void addSwipeListener(SwipeListener listener) {
if (mListeners == null) {
mListeners = new ArrayList<SwipeListener>();
// depends on control dependency: [if], data = [none]
}
mListeners.add(listener);
} } |
public class class_name {
private void processAsyncSessionStoppedCallback (CommsByteBuffer buffer, Conversation conversation) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "processAsyncSessionStoppedCallback", new Object[]{buffer, conversation});
final short connectionObjectId = buffer.getShort();
final short clientSessionId = buffer.getShort();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "connectionObjectId="+connectionObjectId);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "clientSessionId="+clientSessionId);
// Obtain the proxy queue group
final ClientConversationState convState = (ClientConversationState) conversation.getAttachment();
final ProxyQueueConversationGroup pqcg = convState.getProxyQueueConversationGroup();
if (pqcg == null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "ProxyQueueConversationGroup=null");
SIErrorException e = new SIErrorException(nls.getFormattedMessage("NULL_PROXY_QUEUE_CONV_GROUP_CWSICO8020", new Object[] {}, null));
FFDCFilter.processException(e, CLASS_NAME + ".processAsyncSessionStoppedCallback", CommsConstants.PROXYRECEIVELISTENER_SESSION_STOPPED_01, this);
SibTr.error(tc, "NULL_PROXY_QUEUE_CONV_GROUP_CWSICO8020", e);
throw e;
}
// Obtain the required proxy queue from the proxy queue group and ensure its of the right class (ie not read ahead)
final ProxyQueue proxyQueue = pqcg.find(clientSessionId);
if (proxyQueue instanceof AsynchConsumerProxyQueue) {
final ConsumerSessionProxy consumerSessionProxy = ((AsynchConsumerProxyQueue)proxyQueue).getConsumerSessionProxy();
//Drive the ConsumerSessionProxy.stoppableConsumerSessionStopped method on a different thread.
ClientAsynchEventThreadPool.getInstance().dispatchStoppableConsumerSessionStopped(consumerSessionProxy);
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "proxyQueue not an instance of AsynchConsumerProxyQueue is an instance of "+ proxyQueue.getClass().getName());
SIErrorException e = new SIErrorException(nls.getFormattedMessage("WRONG_CLASS_CWSICO8021", new Object[] {proxyQueue.getClass().getName()}, null));
FFDCFilter.processException(e, CLASS_NAME + ".processAsyncSessionStoppedCallback", CommsConstants.PROXYRECEIVELISTENER_SESSION_STOPPED_02, this);
SibTr.error(tc, "WRONG_CLASS_CWSICO8021", e);
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "processAsyncSessionStoppedCallback");
} } | public class class_name {
private void processAsyncSessionStoppedCallback (CommsByteBuffer buffer, Conversation conversation) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "processAsyncSessionStoppedCallback", new Object[]{buffer, conversation});
final short connectionObjectId = buffer.getShort();
final short clientSessionId = buffer.getShort();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "connectionObjectId="+connectionObjectId);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "clientSessionId="+clientSessionId);
// Obtain the proxy queue group
final ClientConversationState convState = (ClientConversationState) conversation.getAttachment();
final ProxyQueueConversationGroup pqcg = convState.getProxyQueueConversationGroup();
if (pqcg == null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "ProxyQueueConversationGroup=null");
SIErrorException e = new SIErrorException(nls.getFormattedMessage("NULL_PROXY_QUEUE_CONV_GROUP_CWSICO8020", new Object[] {}, null));
FFDCFilter.processException(e, CLASS_NAME + ".processAsyncSessionStoppedCallback", CommsConstants.PROXYRECEIVELISTENER_SESSION_STOPPED_01, this); // depends on control dependency: [if], data = [none]
SibTr.error(tc, "NULL_PROXY_QUEUE_CONV_GROUP_CWSICO8020", e); // depends on control dependency: [if], data = [none]
throw e;
}
// Obtain the required proxy queue from the proxy queue group and ensure its of the right class (ie not read ahead)
final ProxyQueue proxyQueue = pqcg.find(clientSessionId);
if (proxyQueue instanceof AsynchConsumerProxyQueue) {
final ConsumerSessionProxy consumerSessionProxy = ((AsynchConsumerProxyQueue)proxyQueue).getConsumerSessionProxy();
//Drive the ConsumerSessionProxy.stoppableConsumerSessionStopped method on a different thread.
ClientAsynchEventThreadPool.getInstance().dispatchStoppableConsumerSessionStopped(consumerSessionProxy); // depends on control dependency: [if], data = [none]
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "proxyQueue not an instance of AsynchConsumerProxyQueue is an instance of "+ proxyQueue.getClass().getName());
SIErrorException e = new SIErrorException(nls.getFormattedMessage("WRONG_CLASS_CWSICO8021", new Object[] {proxyQueue.getClass().getName()}, null));
FFDCFilter.processException(e, CLASS_NAME + ".processAsyncSessionStoppedCallback", CommsConstants.PROXYRECEIVELISTENER_SESSION_STOPPED_02, this); // depends on control dependency: [if], data = [none]
SibTr.error(tc, "WRONG_CLASS_CWSICO8021", e); // depends on control dependency: [if], data = [none]
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "processAsyncSessionStoppedCallback");
} } |
public class class_name {
@Subscribe
public synchronized void renew(final DisabledStateChangedEvent disabledStateChangedEvent) {
OrchestrationShardingSchema shardingSchema = disabledStateChangedEvent.getShardingSchema();
if (ShardingConstant.LOGIC_SCHEMA_NAME.equals(shardingSchema.getSchemaName())) {
((OrchestrationMasterSlaveRule) dataSource.getMasterSlaveRule()).updateDisabledDataSourceNames(shardingSchema.getDataSourceName(), disabledStateChangedEvent.isDisabled());
}
} } | public class class_name {
@Subscribe
public synchronized void renew(final DisabledStateChangedEvent disabledStateChangedEvent) {
OrchestrationShardingSchema shardingSchema = disabledStateChangedEvent.getShardingSchema();
if (ShardingConstant.LOGIC_SCHEMA_NAME.equals(shardingSchema.getSchemaName())) {
((OrchestrationMasterSlaveRule) dataSource.getMasterSlaveRule()).updateDisabledDataSourceNames(shardingSchema.getDataSourceName(), disabledStateChangedEvent.isDisabled()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void justificationOfRVFDatum(RVFDatum<L, F> example, PrintWriter pw) {
int featureLength = 0;
int labelLength = 6;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
if (nf instanceof DecimalFormat) {
((DecimalFormat) nf).setPositivePrefix(" ");
}
Counter<F> features = example.asFeaturesCounter();
for (F f : features.keySet()) {
featureLength = Math.max(featureLength, f.toString().length() + 2 +
nf.format(features.getCount(f)).length());
}
// make as wide as total printout
featureLength = Math.max(featureLength, "Total:".length());
// don't make it ridiculously wide
featureLength = Math.min(featureLength, MAX_FEATURE_ALIGN_WIDTH);
for (Object l : labels()) {
labelLength = Math.max(labelLength, l.toString().length());
}
StringBuilder header = new StringBuilder("");
for (int s = 0; s < featureLength; s++) {
header.append(' ');
}
for (L l : labels()) {
header.append(' ');
header.append(StringUtils.pad(l, labelLength));
}
pw.println(header);
for (F f : features.keySet()) {
String fStr = f.toString();
StringBuilder line = new StringBuilder(fStr);
line.append("[").append(nf.format(features.getCount(f))).append("]");
fStr = line.toString();
for (int s = fStr.length(); s < featureLength; s++) {
line.append(' ');
}
for (L l : labels()) {
String lStr = nf.format(weight(f, l));
line.append(' ');
line.append(lStr);
for (int s = lStr.length(); s < labelLength; s++) {
line.append(' ');
}
}
pw.println(line);
}
Counter<L> scores = scoresOfRVFDatum(example);
StringBuilder footer = new StringBuilder("Total:");
for (int s = footer.length(); s < featureLength; s++) {
footer.append(' ');
}
for (L l : labels()) {
footer.append(' ');
String str = nf.format(scores.getCount(l));
footer.append(str);
for (int s = str.length(); s < labelLength; s++) {
footer.append(' ');
}
}
pw.println(footer);
Distribution<L> distr = Distribution.distributionFromLogisticCounter(scores);
footer = new StringBuilder("Prob:");
for (int s = footer.length(); s < featureLength; s++) {
footer.append(' ');
}
for (L l : labels()) {
footer.append(' ');
String str = nf.format(distr.getCount(l));
footer.append(str);
for (int s = str.length(); s < labelLength; s++) {
footer.append(' ');
}
}
pw.println(footer);
} } | public class class_name {
private void justificationOfRVFDatum(RVFDatum<L, F> example, PrintWriter pw) {
int featureLength = 0;
int labelLength = 6;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
if (nf instanceof DecimalFormat) {
((DecimalFormat) nf).setPositivePrefix(" ");
// depends on control dependency: [if], data = [none]
}
Counter<F> features = example.asFeaturesCounter();
for (F f : features.keySet()) {
featureLength = Math.max(featureLength, f.toString().length() + 2 +
nf.format(features.getCount(f)).length());
// depends on control dependency: [for], data = [f]
}
// make as wide as total printout
featureLength = Math.max(featureLength, "Total:".length());
// don't make it ridiculously wide
featureLength = Math.min(featureLength, MAX_FEATURE_ALIGN_WIDTH);
for (Object l : labels()) {
labelLength = Math.max(labelLength, l.toString().length());
// depends on control dependency: [for], data = [l]
}
StringBuilder header = new StringBuilder("");
for (int s = 0; s < featureLength; s++) {
header.append(' ');
// depends on control dependency: [for], data = [none]
}
for (L l : labels()) {
header.append(' ');
// depends on control dependency: [for], data = [none]
header.append(StringUtils.pad(l, labelLength));
// depends on control dependency: [for], data = [l]
}
pw.println(header);
for (F f : features.keySet()) {
String fStr = f.toString();
StringBuilder line = new StringBuilder(fStr);
line.append("[").append(nf.format(features.getCount(f))).append("]");
// depends on control dependency: [for], data = [f]
fStr = line.toString();
// depends on control dependency: [for], data = [f]
for (int s = fStr.length(); s < featureLength; s++) {
line.append(' ');
// depends on control dependency: [for], data = [none]
}
for (L l : labels()) {
String lStr = nf.format(weight(f, l));
line.append(' ');
// depends on control dependency: [for], data = [l]
line.append(lStr);
// depends on control dependency: [for], data = [l]
for (int s = lStr.length(); s < labelLength; s++) {
line.append(' ');
// depends on control dependency: [for], data = [none]
}
}
pw.println(line);
// depends on control dependency: [for], data = [none]
}
Counter<L> scores = scoresOfRVFDatum(example);
StringBuilder footer = new StringBuilder("Total:");
for (int s = footer.length(); s < featureLength; s++) {
footer.append(' ');
// depends on control dependency: [for], data = [none]
}
for (L l : labels()) {
footer.append(' ');
// depends on control dependency: [for], data = [none]
String str = nf.format(scores.getCount(l));
footer.append(str);
// depends on control dependency: [for], data = [none]
for (int s = str.length(); s < labelLength; s++) {
footer.append(' ');
// depends on control dependency: [for], data = [none]
}
}
pw.println(footer);
Distribution<L> distr = Distribution.distributionFromLogisticCounter(scores);
footer = new StringBuilder("Prob:");
for (int s = footer.length(); s < featureLength; s++) {
footer.append(' ');
// depends on control dependency: [for], data = [none]
}
for (L l : labels()) {
footer.append(' ');
// depends on control dependency: [for], data = [none]
String str = nf.format(distr.getCount(l));
footer.append(str);
// depends on control dependency: [for], data = [none]
for (int s = str.length(); s < labelLength; s++) {
footer.append(' ');
// depends on control dependency: [for], data = [none]
}
}
pw.println(footer);
} } |
public class class_name {
public static IConjunct remainder( IConjunct conjunct, IAssertion assertion)
{
Conjunction rest = new Conjunction();
for( Iterator<IDisjunct> disjuncts = conjunct.getDisjuncts();
disjuncts.hasNext();)
{
IDisjunct disjunct = disjuncts.next();
if( !disjunct.contains( assertion))
{
rest.add( disjunct);
}
}
return rest;
} } | public class class_name {
public static IConjunct remainder( IConjunct conjunct, IAssertion assertion)
{
Conjunction rest = new Conjunction();
for( Iterator<IDisjunct> disjuncts = conjunct.getDisjuncts();
disjuncts.hasNext();)
{
IDisjunct disjunct = disjuncts.next();
if( !disjunct.contains( assertion))
{
rest.add( disjunct); // depends on control dependency: [if], data = [none]
}
}
return rest;
} } |
public class class_name {
protected Drawable handleCloseableStaticBitmap(
CloseableStaticBitmap closeableStaticBitmap, ImageOptions imageOptions) {
RoundingOptions roundingOptions = imageOptions.getRoundingOptions();
BorderOptions borderOptions = imageOptions.getBorderOptions();
if (borderOptions != null && borderOptions.width > 0) {
return rotatedDrawable(
closeableStaticBitmap,
roundedDrawableWithBorder(closeableStaticBitmap, borderOptions, roundingOptions));
} else {
return rotatedDrawable(
closeableStaticBitmap,
roundedDrawableWithoutBorder(closeableStaticBitmap, roundingOptions));
}
} } | public class class_name {
protected Drawable handleCloseableStaticBitmap(
CloseableStaticBitmap closeableStaticBitmap, ImageOptions imageOptions) {
RoundingOptions roundingOptions = imageOptions.getRoundingOptions();
BorderOptions borderOptions = imageOptions.getBorderOptions();
if (borderOptions != null && borderOptions.width > 0) {
return rotatedDrawable(
closeableStaticBitmap,
roundedDrawableWithBorder(closeableStaticBitmap, borderOptions, roundingOptions)); // depends on control dependency: [if], data = [none]
} else {
return rotatedDrawable(
closeableStaticBitmap,
roundedDrawableWithoutBorder(closeableStaticBitmap, roundingOptions)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected static CommonContent transformCommonContent(CSNodeWrapper node) {
final CommonContent commonContent;
if (node.getNodeType() == CommonConstants.CS_NODE_COMMON_CONTENT) {
commonContent = new CommonContent(node.getTitle());
} else {
throw new IllegalArgumentException("The passed node is not a Comment");
}
commonContent.setUniqueId(node.getId() == null ? null : node.getId().toString());
return commonContent;
} } | public class class_name {
protected static CommonContent transformCommonContent(CSNodeWrapper node) {
final CommonContent commonContent;
if (node.getNodeType() == CommonConstants.CS_NODE_COMMON_CONTENT) {
commonContent = new CommonContent(node.getTitle()); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("The passed node is not a Comment");
}
commonContent.setUniqueId(node.getId() == null ? null : node.getId().toString());
return commonContent;
} } |
public class class_name {
public static base_responses delete(nitro_service client, cacheforwardproxy resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
cacheforwardproxy deleteresources[] = new cacheforwardproxy[resources.length];
for (int i=0;i<resources.length;i++){
deleteresources[i] = new cacheforwardproxy();
deleteresources[i].ipaddress = resources[i].ipaddress;
deleteresources[i].port = resources[i].port;
}
result = delete_bulk_request(client, deleteresources);
}
return result;
} } | public class class_name {
public static base_responses delete(nitro_service client, cacheforwardproxy resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
cacheforwardproxy deleteresources[] = new cacheforwardproxy[resources.length];
for (int i=0;i<resources.length;i++){
deleteresources[i] = new cacheforwardproxy(); // depends on control dependency: [for], data = [i]
deleteresources[i].ipaddress = resources[i].ipaddress; // depends on control dependency: [for], data = [i]
deleteresources[i].port = resources[i].port; // depends on control dependency: [for], data = [i]
}
result = delete_bulk_request(client, deleteresources);
}
return result;
} } |
public class class_name {
public void setGroupId(java.util.Collection<String> groupId) {
if (groupId == null) {
this.groupId = null;
return;
}
this.groupId = new com.amazonaws.internal.SdkInternalList<String>(groupId);
} } | public class class_name {
public void setGroupId(java.util.Collection<String> groupId) {
if (groupId == null) {
this.groupId = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.groupId = new com.amazonaws.internal.SdkInternalList<String>(groupId);
} } |
public class class_name {
public static INDArray col2im(INDArray col, int sy, int sx, int ph, int pw, int h, int w) {
//number of images
long n = col.size(0);
//number of columns
long c = col.size(1);
//kernel height
long kh = col.size(2);
//kernel width
long kw = col.size(3);
//out height
long outH = col.size(4);
//out width
long outW = col.size(5);
INDArray img = Nd4j.create(n, c, h + 2 * ph + sy - 1, w + 2 * pw + sx - 1);
for (int i = 0; i < kh; i++) {
//iterate over the kernel rows
long iLim = i + sy * outH;
for (int j = 0; j < kw; j++) {
//iterate over the kernel columns
long jLim = j + sx * outW;
INDArrayIndex[] indices = new INDArrayIndex[] {NDArrayIndex.all(), NDArrayIndex.all(),
NDArrayIndex.interval(i, sy, iLim), NDArrayIndex.interval(j, sx, jLim)};
INDArray get = img.get(indices);
INDArray colAdd = col.get(NDArrayIndex.all(), NDArrayIndex.all(), NDArrayIndex.point(i),
NDArrayIndex.point(j), NDArrayIndex.all(), NDArrayIndex.all());
get.addi(colAdd);
img.put(indices, get);
}
}
//return the subset of the padded image relative to the height/width of the image and the padding width/height
return img.get(NDArrayIndex.all(), NDArrayIndex.all(), NDArrayIndex.interval(ph, ph + h),
NDArrayIndex.interval(pw, pw + w));
} } | public class class_name {
public static INDArray col2im(INDArray col, int sy, int sx, int ph, int pw, int h, int w) {
//number of images
long n = col.size(0);
//number of columns
long c = col.size(1);
//kernel height
long kh = col.size(2);
//kernel width
long kw = col.size(3);
//out height
long outH = col.size(4);
//out width
long outW = col.size(5);
INDArray img = Nd4j.create(n, c, h + 2 * ph + sy - 1, w + 2 * pw + sx - 1);
for (int i = 0; i < kh; i++) {
//iterate over the kernel rows
long iLim = i + sy * outH;
for (int j = 0; j < kw; j++) {
//iterate over the kernel columns
long jLim = j + sx * outW;
INDArrayIndex[] indices = new INDArrayIndex[] {NDArrayIndex.all(), NDArrayIndex.all(),
NDArrayIndex.interval(i, sy, iLim), NDArrayIndex.interval(j, sx, jLim)};
INDArray get = img.get(indices);
INDArray colAdd = col.get(NDArrayIndex.all(), NDArrayIndex.all(), NDArrayIndex.point(i),
NDArrayIndex.point(j), NDArrayIndex.all(), NDArrayIndex.all());
get.addi(colAdd); // depends on control dependency: [for], data = [none]
img.put(indices, get); // depends on control dependency: [for], data = [none]
}
}
//return the subset of the padded image relative to the height/width of the image and the padding width/height
return img.get(NDArrayIndex.all(), NDArrayIndex.all(), NDArrayIndex.interval(ph, ph + h),
NDArrayIndex.interval(pw, pw + w));
} } |
public class class_name {
@Validate
public void start(){
//Publish the monitor extension
for(Asset asset : assets.assets()) {
if (asset.getPath().matches("^"+RAML_ASSET_DIR+"[A-Za-z0-9_-]+\\"+RAML_EXT+"$")){
String name = asset.getPath().substring(RAML_ASSET_DIR.length(), asset.getPath().length() - RAML_EXT.length());
if(!names.add(name)){ //skip if two Controller have the same name, it's impossible
continue;
}
registrations.add(context.registerService(MonitorExtension.class, new RamlMonitorConsole(name), null));
}
}
} } | public class class_name {
@Validate
public void start(){
//Publish the monitor extension
for(Asset asset : assets.assets()) {
if (asset.getPath().matches("^"+RAML_ASSET_DIR+"[A-Za-z0-9_-]+\\"+RAML_EXT+"$")){
String name = asset.getPath().substring(RAML_ASSET_DIR.length(), asset.getPath().length() - RAML_EXT.length());
if(!names.add(name)){ //skip if two Controller have the same name, it's impossible
continue;
}
registrations.add(context.registerService(MonitorExtension.class, new RamlMonitorConsole(name), null)); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private static boolean handleLegacyWeightInitFromJson(String json, Layer l, ObjectMapper mapper, JsonNode confs, int layerCount) {
if ((l instanceof BaseLayer) && ((BaseLayer) l).getWeightInitFn() == null) {
try {
JsonNode jsonNode = mapper.readTree(json);
if (confs == null) {
confs = jsonNode.get("confs");
}
if (confs instanceof ArrayNode) {
ArrayNode layerConfs = (ArrayNode) confs;
JsonNode outputLayerNNCNode = layerConfs.get(layerCount);
if (outputLayerNNCNode == null)
return false; //Should never happen...
JsonNode layerWrapperNode = outputLayerNNCNode.get("layer");
if (layerWrapperNode == null || layerWrapperNode.size() != 1) {
return true;
}
JsonNode layerNode = layerWrapperNode.elements().next();
JsonNode weightInit = layerNode.get("weightInit"); //Should only have 1 element: "dense", "output", etc
JsonNode distribution = layerNode.get("dist");
Distribution dist = null;
if(distribution != null) {
dist = mapper.treeToValue(distribution, Distribution.class);
}
if (weightInit != null) {
final IWeightInit wi = WeightInit.valueOf(weightInit.asText()).getWeightInitFunction(dist);
((BaseLayer) l).setWeightInitFn(wi);
}
}
} catch (IOException e) {
log.warn("Layer with null WeightInit detected: " + l.getLayerName() + ", could not parse JSON",
e);
}
}
return true;
} } | public class class_name {
private static boolean handleLegacyWeightInitFromJson(String json, Layer l, ObjectMapper mapper, JsonNode confs, int layerCount) {
if ((l instanceof BaseLayer) && ((BaseLayer) l).getWeightInitFn() == null) {
try {
JsonNode jsonNode = mapper.readTree(json);
if (confs == null) {
confs = jsonNode.get("confs"); // depends on control dependency: [if], data = [none]
}
if (confs instanceof ArrayNode) {
ArrayNode layerConfs = (ArrayNode) confs;
JsonNode outputLayerNNCNode = layerConfs.get(layerCount);
if (outputLayerNNCNode == null)
return false; //Should never happen...
JsonNode layerWrapperNode = outputLayerNNCNode.get("layer");
if (layerWrapperNode == null || layerWrapperNode.size() != 1) {
return true; // depends on control dependency: [if], data = [none]
}
JsonNode layerNode = layerWrapperNode.elements().next();
JsonNode weightInit = layerNode.get("weightInit"); //Should only have 1 element: "dense", "output", etc
JsonNode distribution = layerNode.get("dist");
Distribution dist = null;
if(distribution != null) {
dist = mapper.treeToValue(distribution, Distribution.class); // depends on control dependency: [if], data = [(distribution]
}
if (weightInit != null) {
final IWeightInit wi = WeightInit.valueOf(weightInit.asText()).getWeightInitFunction(dist);
((BaseLayer) l).setWeightInitFn(wi); // depends on control dependency: [if], data = [none]
}
}
} catch (IOException e) {
log.warn("Layer with null WeightInit detected: " + l.getLayerName() + ", could not parse JSON",
e);
} // depends on control dependency: [catch], data = [none]
}
return true;
} } |
public class class_name {
public static boolean isBasicElementCollectionField(Field collectionField)
{
if (!Collection.class.isAssignableFrom(collectionField.getType())
&& !Map.class.isAssignableFrom(collectionField.getType()))
{
return false;
}
List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses(collectionField);
for (Class genericClass : genericClasses)
{
if (genericClass.getAnnotation(Embeddable.class) != null)
{
return false;
}
}
return true;
} } | public class class_name {
public static boolean isBasicElementCollectionField(Field collectionField)
{
if (!Collection.class.isAssignableFrom(collectionField.getType())
&& !Map.class.isAssignableFrom(collectionField.getType()))
{
return false;
// depends on control dependency: [if], data = [none]
}
List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses(collectionField);
for (Class genericClass : genericClasses)
{
if (genericClass.getAnnotation(Embeddable.class) != null)
{
return false;
// depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public static void closeQuietly(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (AssertionError e) {
if (!isAndroidGetsocknameError(e)) throw e;
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
} } | public class class_name {
public static void closeQuietly(Socket socket) {
if (socket != null) {
try {
socket.close(); // depends on control dependency: [try], data = [none]
} catch (AssertionError e) {
if (!isAndroidGetsocknameError(e)) throw e;
} catch (RuntimeException rethrown) { // depends on control dependency: [catch], data = [none]
throw rethrown;
} catch (Exception ignored) { // depends on control dependency: [catch], data = [none]
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private static String typeVariableToString(final TypeVariable<?> v) {
final StringBuilder buf = new StringBuilder(v.getName());
final Type[] bounds = v.getBounds();
if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(bounds[0]))) {
buf.append(" extends ");
appendAllTo(buf, " & ", v.getBounds());
}
return buf.toString();
} } | public class class_name {
private static String typeVariableToString(final TypeVariable<?> v) {
final StringBuilder buf = new StringBuilder(v.getName());
final Type[] bounds = v.getBounds();
if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(bounds[0]))) {
buf.append(" extends "); // depends on control dependency: [if], data = [none]
appendAllTo(buf, " & ", v.getBounds()); // depends on control dependency: [if], data = [none]
}
return buf.toString();
} } |
public class class_name {
private WButton makeImageButtonWithPosition(final String text, final ImagePosition pos,
final Boolean asLink) {
WButton button = new WButton(text);
button.setImage("/image/tick.png");
if (pos != null) {
button.setImagePosition(pos);
}
button.setActionObject(button);
button.setAction(new ExampleButtonAction());
if (asLink) {
button.setRenderAsLink(true);
}
return button;
} } | public class class_name {
private WButton makeImageButtonWithPosition(final String text, final ImagePosition pos,
final Boolean asLink) {
WButton button = new WButton(text);
button.setImage("/image/tick.png");
if (pos != null) {
button.setImagePosition(pos); // depends on control dependency: [if], data = [(pos]
}
button.setActionObject(button);
button.setAction(new ExampleButtonAction());
if (asLink) {
button.setRenderAsLink(true); // depends on control dependency: [if], data = [none]
}
return button;
} } |
public class class_name {
public void marshall(DescribeTagsRequest describeTagsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeTagsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeTagsRequest.getResourceArns(), RESOURCEARNS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DescribeTagsRequest describeTagsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeTagsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeTagsRequest.getResourceArns(), RESOURCEARNS_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 String decodeUri(String url)
{
int index1 = url.indexOf(sessUrlRewritePrefix);
int index2 = url.indexOf(qMark);
String tmp = null;
if (index2 != -1 && index2 > index1)
{
tmp = url.substring(index2);
}
if (index1 != -1)
{
url = url.substring(0, index1);
if (tmp != null)
{
url = url + tmp;
}
}
return url;
} } | public class class_name {
public static String decodeUri(String url)
{
int index1 = url.indexOf(sessUrlRewritePrefix);
int index2 = url.indexOf(qMark);
String tmp = null;
if (index2 != -1 && index2 > index1)
{
tmp = url.substring(index2); // depends on control dependency: [if], data = [(index2]
}
if (index1 != -1)
{
url = url.substring(0, index1); // depends on control dependency: [if], data = [none]
if (tmp != null)
{
url = url + tmp; // depends on control dependency: [if], data = [none]
}
}
return url;
} } |
public class class_name {
public String authenticate(final String username, final String password) {
String principal = null;
try {
if (getServer() != null) {
// dbName parameter is null because we don't need to filter any roles for this.
OUser user = getServer().getSecurity().getSystemUser(username, null);
if (user != null && user.getAccountStatus() == OSecurityUser.STATUSES.ACTIVE) {
if (user.checkPassword(password))
principal = username;
}
}
} catch (Exception ex) {
OLogManager.instance().error(this, "authenticate()", ex);
}
return principal;
} } | public class class_name {
public String authenticate(final String username, final String password) {
String principal = null;
try {
if (getServer() != null) {
// dbName parameter is null because we don't need to filter any roles for this.
OUser user = getServer().getSecurity().getSystemUser(username, null);
if (user != null && user.getAccountStatus() == OSecurityUser.STATUSES.ACTIVE) {
if (user.checkPassword(password))
principal = username;
}
}
} catch (Exception ex) {
OLogManager.instance().error(this, "authenticate()", ex);
} // depends on control dependency: [catch], data = [none]
return principal;
} } |
public class class_name {
static void deleteOrResetFreePos(Database database, String filename) {
ScaledRAFile raFile = null;
database.getFileAccess().removeElement(filename);
// OOo related code
if (database.isStoredFileAccess()) {
return;
}
// OOo end
if (!database.getFileAccess().isStreamElement(filename)) {
return;
}
try {
raFile = new ScaledRAFile(database, filename, false);
raFile.seek(LONG_FREE_POS_POS);
raFile.writeLong(INITIAL_FREE_POS);
} catch (IOException e) {
database.logger.appLog.logContext(e, null);
} finally {
if (raFile != null) {
try {
raFile.close();
} catch (IOException e) {
database.logger.appLog.logContext(e, null);
}
}
}
} } | public class class_name {
static void deleteOrResetFreePos(Database database, String filename) {
ScaledRAFile raFile = null;
database.getFileAccess().removeElement(filename);
// OOo related code
if (database.isStoredFileAccess()) {
return; // depends on control dependency: [if], data = [none]
}
// OOo end
if (!database.getFileAccess().isStreamElement(filename)) {
return; // depends on control dependency: [if], data = [none]
}
try {
raFile = new ScaledRAFile(database, filename, false); // depends on control dependency: [try], data = [none]
raFile.seek(LONG_FREE_POS_POS); // depends on control dependency: [try], data = [none]
raFile.writeLong(INITIAL_FREE_POS); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
database.logger.appLog.logContext(e, null);
} finally { // depends on control dependency: [catch], data = [none]
if (raFile != null) {
try {
raFile.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
database.logger.appLog.logContext(e, null);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
CdmrFeatureProto.CoordAxis.Builder encodeCoordAxis(CoverageCoordAxis axis) {
CdmrFeatureProto.CoordAxis.Builder builder = CdmrFeatureProto.CoordAxis.newBuilder();
builder.setName(axis.getName());
builder.setDataType(NcStream.convertDataType(axis.getDataType()));
builder.setAxisType(convertAxisType(axis.getAxisType()));
builder.setNvalues(axis.getNcoords());
if (axis.getUnits() != null) builder.setUnits(axis.getUnits());
if (axis.getDescription() != null) builder.setDescription(axis.getDescription());
builder.setDepend(convertDependenceType(axis.getDependenceType()));
for (String s : axis.getDependsOnList())
builder.addDependsOn(s);
if (axis instanceof LatLonAxis2D) {
LatLonAxis2D latlon2D = (LatLonAxis2D) axis;
for (int shape : latlon2D.getShape())
builder.addShape(shape);
}
for (Attribute att : axis.getAttributes())
builder.addAtts(NcStream.encodeAtt(att));
builder.setSpacing(convertSpacing(axis.getSpacing()));
builder.setStartValue(axis.getStartValue());
builder.setEndValue(axis.getEndValue());
builder.setResolution(axis.getResolution());
if (!axis.isRegular() && axis.getNcoords() < MAX_INLINE_NVALUES) {
double[] values = axis.getValues();
ByteBuffer bb = ByteBuffer.allocate(8 * values.length);
DoubleBuffer db = bb.asDoubleBuffer();
db.put(values);
builder.setValues(ByteString.copyFrom(bb.array()));
}
return builder;
} } | public class class_name {
CdmrFeatureProto.CoordAxis.Builder encodeCoordAxis(CoverageCoordAxis axis) {
CdmrFeatureProto.CoordAxis.Builder builder = CdmrFeatureProto.CoordAxis.newBuilder();
builder.setName(axis.getName());
builder.setDataType(NcStream.convertDataType(axis.getDataType()));
builder.setAxisType(convertAxisType(axis.getAxisType()));
builder.setNvalues(axis.getNcoords());
if (axis.getUnits() != null) builder.setUnits(axis.getUnits());
if (axis.getDescription() != null) builder.setDescription(axis.getDescription());
builder.setDepend(convertDependenceType(axis.getDependenceType()));
for (String s : axis.getDependsOnList())
builder.addDependsOn(s);
if (axis instanceof LatLonAxis2D) {
LatLonAxis2D latlon2D = (LatLonAxis2D) axis;
for (int shape : latlon2D.getShape())
builder.addShape(shape);
}
for (Attribute att : axis.getAttributes())
builder.addAtts(NcStream.encodeAtt(att));
builder.setSpacing(convertSpacing(axis.getSpacing()));
builder.setStartValue(axis.getStartValue());
builder.setEndValue(axis.getEndValue());
builder.setResolution(axis.getResolution());
if (!axis.isRegular() && axis.getNcoords() < MAX_INLINE_NVALUES) {
double[] values = axis.getValues();
ByteBuffer bb = ByteBuffer.allocate(8 * values.length);
DoubleBuffer db = bb.asDoubleBuffer();
db.put(values); // depends on control dependency: [if], data = [none]
builder.setValues(ByteString.copyFrom(bb.array())); // depends on control dependency: [if], data = [none]
}
return builder;
} } |
public class class_name {
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
if(len <= 0) {
return;
}
// if we havn't last seen a newline, and don't get a CR, insert a newline.
if(charsSinceNewline > 0) {
if(cbuf[off] != CARRIAGE_RETURN) {
super.write(NEWLINEC, 0, NEWLINEC.length);
charsSinceNewline = 0;
}
else {
// length of this line:
int nonnl = countNonNewline(cbuf, off + 1, len - 1);
// clear the existing chars.
if(nonnl < charsSinceNewline) {
super.write(CARRIAGE_RETURN);
while(charsSinceNewline > 0) {
final int n = Math.min(charsSinceNewline, WHITESPACE.length());
super.write(WHITESPACE, 0, n);
charsSinceNewline -= n;
}
}
else {
charsSinceNewline = 0;
}
}
}
charsSinceNewline = tailingNonNewline(cbuf, off, len);
super.write(cbuf, off, len);
flush();
} } | public class class_name {
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
if(len <= 0) {
return;
}
// if we havn't last seen a newline, and don't get a CR, insert a newline.
if(charsSinceNewline > 0) {
if(cbuf[off] != CARRIAGE_RETURN) {
super.write(NEWLINEC, 0, NEWLINEC.length);
charsSinceNewline = 0;
}
else {
// length of this line:
int nonnl = countNonNewline(cbuf, off + 1, len - 1);
// clear the existing chars.
if(nonnl < charsSinceNewline) {
super.write(CARRIAGE_RETURN); // depends on control dependency: [if], data = [none]
while(charsSinceNewline > 0) {
final int n = Math.min(charsSinceNewline, WHITESPACE.length());
super.write(WHITESPACE, 0, n); // depends on control dependency: [while], data = [none]
charsSinceNewline -= n; // depends on control dependency: [while], data = [none]
}
}
else {
charsSinceNewline = 0; // depends on control dependency: [if], data = [none]
}
}
}
charsSinceNewline = tailingNonNewline(cbuf, off, len);
super.write(cbuf, off, len);
flush();
} } |
public class class_name {
public TemporalAccessor parse(CharSequence text) {
Objects.requireNonNull(text, "text");
try {
return parseResolved0(text, null);
} catch (DateTimeParseException ex) {
throw ex;
} catch (RuntimeException ex) {
throw createError(text, ex);
}
} } | public class class_name {
public TemporalAccessor parse(CharSequence text) {
Objects.requireNonNull(text, "text");
try {
return parseResolved0(text, null); // depends on control dependency: [try], data = [none]
} catch (DateTimeParseException ex) {
throw ex;
} catch (RuntimeException ex) { // depends on control dependency: [catch], data = [none]
throw createError(text, ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void update(Bbox mapBounds) {
for (final SnappingRule condition : snappingRules) {
condition.getSourceProvider().update(mapBounds);
condition.getSourceProvider().getSnappingSources(new GeometryArrayFunction() {
public void execute(Geometry[] geometries) {
condition.getAlgorithm().setGeometries(geometries);
}
});
}
} } | public class class_name {
public void update(Bbox mapBounds) {
for (final SnappingRule condition : snappingRules) {
condition.getSourceProvider().update(mapBounds); // depends on control dependency: [for], data = [condition]
condition.getSourceProvider().getSnappingSources(new GeometryArrayFunction() {
public void execute(Geometry[] geometries) {
condition.getAlgorithm().setGeometries(geometries);
}
}); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public void freeDependent()
{
if (m_recDependent != null) // If close and file is still open
if (!m_recDependent.isInFree())
{
this.setDependentListener(null); // In case you want to delete me!
if (m_recDependent != null)
{
if (m_bCloseOnFree)
m_recDependent.close(); // File is still open, and my listener is still there, close it!
else
m_recDependent.free(); // File is still open, and my listener is still there, close it!
}
}
m_recDependent = null;
if (m_freeable != null)
m_freeable.free();
m_freeable = null;
} } | public class class_name {
public void freeDependent()
{
if (m_recDependent != null) // If close and file is still open
if (!m_recDependent.isInFree())
{
this.setDependentListener(null); // In case you want to delete me! // depends on control dependency: [if], data = [none]
if (m_recDependent != null)
{
if (m_bCloseOnFree)
m_recDependent.close(); // File is still open, and my listener is still there, close it!
else
m_recDependent.free(); // File is still open, and my listener is still there, close it!
}
}
m_recDependent = null;
if (m_freeable != null)
m_freeable.free();
m_freeable = null;
} } |
public class class_name {
public void setIcon(final Image IMAGE) {
if (null == icon) {
_icon = IMAGE;
} else {
icon.set(IMAGE);
}
} } | public class class_name {
public void setIcon(final Image IMAGE) {
if (null == icon) {
_icon = IMAGE; // depends on control dependency: [if], data = [none]
} else {
icon.set(IMAGE); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public SslProtocol sslProtocol() {
String protocol = reader.getString(SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL).replace(".", "_");
try {
return SslProtocol.valueOf(protocol);
} catch (IllegalArgumentException e) {
throw new ConfigurationException("unknown SSL protocol: " + protocol, e);
}
} } | public class class_name {
public SslProtocol sslProtocol() {
String protocol = reader.getString(SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL).replace(".", "_");
try {
return SslProtocol.valueOf(protocol); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
throw new ConfigurationException("unknown SSL protocol: " + protocol, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private Boolean booleanProperty(PropertyKey propertyKey) {
Boolean value = null;
String property = properties.getProperty(propertyKey.getKey());
if (property != null) {
value = Boolean.valueOf(property);
}
return value;
} } | public class class_name {
private Boolean booleanProperty(PropertyKey propertyKey) {
Boolean value = null;
String property = properties.getProperty(propertyKey.getKey());
if (property != null) {
value = Boolean.valueOf(property); // depends on control dependency: [if], data = [(property]
}
return value;
} } |
public class class_name {
public static int getCRC16(byte[] bytes, int s, int e) {
int crc = 0x0000;
for (int i = s; i < e; i++) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (bytes[i] & 0xFF)) & 0xFF]);
}
return crc & 0xFFFF;
} } | public class class_name {
public static int getCRC16(byte[] bytes, int s, int e) {
int crc = 0x0000;
for (int i = s; i < e; i++) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (bytes[i] & 0xFF)) & 0xFF]); // depends on control dependency: [for], data = [i]
}
return crc & 0xFFFF;
} } |
public class class_name {
public static InetSocketAddress readSocketAddress(ChannelBuffer buffer)
{
String remoteHost = NettyUtils.readString(buffer);
int remotePort = 0;
if (buffer.readableBytes() >= 4)
{
remotePort = buffer.readInt();
}
else
{
return null;
}
InetSocketAddress remoteAddress = null;
if (null != remoteHost)
{
remoteAddress = new InetSocketAddress(remoteHost, remotePort);
}
return remoteAddress;
} } | public class class_name {
public static InetSocketAddress readSocketAddress(ChannelBuffer buffer)
{
String remoteHost = NettyUtils.readString(buffer);
int remotePort = 0;
if (buffer.readableBytes() >= 4)
{
remotePort = buffer.readInt(); // depends on control dependency: [if], data = [none]
}
else
{
return null; // depends on control dependency: [if], data = [none]
}
InetSocketAddress remoteAddress = null;
if (null != remoteHost)
{
remoteAddress = new InetSocketAddress(remoteHost, remotePort); // depends on control dependency: [if], data = [none]
}
return remoteAddress;
} } |
public class class_name {
public void marshall(BatchReadSuccessfulResponse batchReadSuccessfulResponse, ProtocolMarshaller protocolMarshaller) {
if (batchReadSuccessfulResponse == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectAttributes(), LISTOBJECTATTRIBUTES_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectChildren(), LISTOBJECTCHILDREN_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getGetObjectInformation(), GETOBJECTINFORMATION_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getGetObjectAttributes(), GETOBJECTATTRIBUTES_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListAttachedIndices(), LISTATTACHEDINDICES_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectParentPaths(), LISTOBJECTPARENTPATHS_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectPolicies(), LISTOBJECTPOLICIES_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListPolicyAttachments(), LISTPOLICYATTACHMENTS_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getLookupPolicy(), LOOKUPPOLICY_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListIndex(), LISTINDEX_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListOutgoingTypedLinks(), LISTOUTGOINGTYPEDLINKS_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListIncomingTypedLinks(), LISTINCOMINGTYPEDLINKS_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getGetLinkAttributes(), GETLINKATTRIBUTES_BINDING);
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectParents(), LISTOBJECTPARENTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BatchReadSuccessfulResponse batchReadSuccessfulResponse, ProtocolMarshaller protocolMarshaller) {
if (batchReadSuccessfulResponse == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectAttributes(), LISTOBJECTATTRIBUTES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectChildren(), LISTOBJECTCHILDREN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getGetObjectInformation(), GETOBJECTINFORMATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getGetObjectAttributes(), GETOBJECTATTRIBUTES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListAttachedIndices(), LISTATTACHEDINDICES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectParentPaths(), LISTOBJECTPARENTPATHS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectPolicies(), LISTOBJECTPOLICIES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListPolicyAttachments(), LISTPOLICYATTACHMENTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getLookupPolicy(), LOOKUPPOLICY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListIndex(), LISTINDEX_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListOutgoingTypedLinks(), LISTOUTGOINGTYPEDLINKS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListIncomingTypedLinks(), LISTINCOMINGTYPEDLINKS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getGetLinkAttributes(), GETLINKATTRIBUTES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchReadSuccessfulResponse.getListObjectParents(), LISTOBJECTPARENTS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void drawDashedLine(final Context2D context, double x, double y, final double x2, final double y2, final double[] da, final double plus)
{
final int dashCount = da.length;
final double dx = (x2 - x);
final double dy = (y2 - y);
final boolean xbig = (Math.abs(dx) > Math.abs(dy));
final double slope = (xbig) ? dy / dx : dx / dy;
context.moveTo(x, y);
double distRemaining = Math.sqrt((dx * dx) + (dy * dy)) + plus;
int dashIndex = 0;
while (distRemaining >= 0.1)
{
final double dashLength = Math.min(distRemaining, da[dashIndex % dashCount]);
double step = Math.sqrt((dashLength * dashLength) / (1 + (slope * slope)));
if (xbig)
{
if (dx < 0)
{
step = -step;
}
x += step;
y += slope * step;
}
else
{
if (dy < 0)
{
step = -step;
}
x += slope * step;
y += step;
}
if ((dashIndex % 2) == 0)
{
context.lineTo(x, y);
}
else
{
context.moveTo(x, y);
}
distRemaining -= dashLength;
dashIndex++;
}
} } | public class class_name {
protected void drawDashedLine(final Context2D context, double x, double y, final double x2, final double y2, final double[] da, final double plus)
{
final int dashCount = da.length;
final double dx = (x2 - x);
final double dy = (y2 - y);
final boolean xbig = (Math.abs(dx) > Math.abs(dy));
final double slope = (xbig) ? dy / dx : dx / dy;
context.moveTo(x, y);
double distRemaining = Math.sqrt((dx * dx) + (dy * dy)) + plus;
int dashIndex = 0;
while (distRemaining >= 0.1)
{
final double dashLength = Math.min(distRemaining, da[dashIndex % dashCount]);
double step = Math.sqrt((dashLength * dashLength) / (1 + (slope * slope)));
if (xbig)
{
if (dx < 0)
{
step = -step; // depends on control dependency: [if], data = [none]
}
x += step; // depends on control dependency: [if], data = [none]
y += slope * step; // depends on control dependency: [if], data = [none]
}
else
{
if (dy < 0)
{
step = -step; // depends on control dependency: [if], data = [none]
}
x += slope * step; // depends on control dependency: [if], data = [none]
y += step; // depends on control dependency: [if], data = [none]
}
if ((dashIndex % 2) == 0)
{
context.lineTo(x, y); // depends on control dependency: [if], data = [none]
}
else
{
context.moveTo(x, y); // depends on control dependency: [if], data = [none]
}
distRemaining -= dashLength; // depends on control dependency: [while], data = [none]
dashIndex++; // depends on control dependency: [while], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.