code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public static CmsModuleImportExportHandler getExportHandler(
CmsObject cms,
final CmsModule module,
final String handlerDescription) {
// check if all resources are valid
List<String> resListCopy = new ArrayList<String>();
String moduleName = module.getName();
try {
cms = OpenCms.initCmsObject(cms);
String importSite = module.getSite();
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(importSite)) {
cms.getRequestContext().setSiteRoot(importSite);
}
} catch (CmsException e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
}
try {
resListCopy = CmsModule.calculateModuleResourceNames(cms, module);
} catch (CmsException e) {
// some resource did not exist / could not be read
if (LOG.isInfoEnabled()) {
LOG.warn(Messages.get().getBundle().key(Messages.ERR_READ_MODULE_RESOURCES_1, module.getName()), e);
}
}
resListCopy = CmsFileUtil.removeRedundancies(resListCopy);
String[] resources = new String[resListCopy.size()];
for (int i = 0; i < resListCopy.size(); i++) {
resources[i] = resListCopy.get(i);
}
String filename = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
OpenCms.getSystemInfo().getPackagesRfsPath()
+ CmsSystemInfo.FOLDER_MODULES
+ moduleName
+ "_"
+ "%(version)");
CmsModuleImportExportHandler moduleExportHandler = new CmsModuleImportExportHandler();
moduleExportHandler.setFileName(filename);
moduleExportHandler.setModuleName(moduleName.replace('\\', '/'));
moduleExportHandler.setAdditionalResources(resources);
moduleExportHandler.setDescription(handlerDescription);
return moduleExportHandler;
} } | public class class_name {
public static CmsModuleImportExportHandler getExportHandler(
CmsObject cms,
final CmsModule module,
final String handlerDescription) {
// check if all resources are valid
List<String> resListCopy = new ArrayList<String>();
String moduleName = module.getName();
try {
cms = OpenCms.initCmsObject(cms); // depends on control dependency: [try], data = [none]
String importSite = module.getSite();
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(importSite)) {
cms.getRequestContext().setSiteRoot(importSite); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
try {
resListCopy = CmsModule.calculateModuleResourceNames(cms, module); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// some resource did not exist / could not be read
if (LOG.isInfoEnabled()) {
LOG.warn(Messages.get().getBundle().key(Messages.ERR_READ_MODULE_RESOURCES_1, module.getName()), e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
resListCopy = CmsFileUtil.removeRedundancies(resListCopy);
String[] resources = new String[resListCopy.size()];
for (int i = 0; i < resListCopy.size(); i++) {
resources[i] = resListCopy.get(i); // depends on control dependency: [for], data = [i]
}
String filename = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
OpenCms.getSystemInfo().getPackagesRfsPath()
+ CmsSystemInfo.FOLDER_MODULES
+ moduleName
+ "_"
+ "%(version)");
CmsModuleImportExportHandler moduleExportHandler = new CmsModuleImportExportHandler();
moduleExportHandler.setFileName(filename);
moduleExportHandler.setModuleName(moduleName.replace('\\', '/'));
moduleExportHandler.setAdditionalResources(resources);
moduleExportHandler.setDescription(handlerDescription);
return moduleExportHandler;
} } |
public class class_name {
public static long parseBytes(String text) throws IllegalArgumentException {
checkNotNull(text, "text");
final String trimmed = text.trim();
checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string");
final int len = trimmed.length();
int pos = 0;
char current;
while (pos < len && (current = trimmed.charAt(pos)) >= '0' && current <= '9') {
pos++;
}
final String number = trimmed.substring(0, pos);
final String unit = trimmed.substring(pos).trim().toLowerCase(Locale.US);
if (number.isEmpty()) {
throw new NumberFormatException("text does not start with a number");
}
final long value;
try {
value = Long.parseLong(number); // this throws a NumberFormatException on overflow
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("The value '" + number +
"' cannot be re represented as 64bit number (numeric overflow).");
}
final long multiplier;
if (unit.isEmpty()) {
multiplier = 1L;
}
else {
if (matchesAny(unit, BYTES)) {
multiplier = 1L;
}
else if (matchesAny(unit, KILO_BYTES)) {
multiplier = 1024L;
}
else if (matchesAny(unit, MEGA_BYTES)) {
multiplier = 1024L * 1024L;
}
else if (matchesAny(unit, GIGA_BYTES)) {
multiplier = 1024L * 1024L * 1024L;
}
else if (matchesAny(unit, TERA_BYTES)) {
multiplier = 1024L * 1024L * 1024L * 1024L;
}
else {
throw new IllegalArgumentException("Memory size unit '" + unit +
"' does not match any of the recognized units: " + MemoryUnit.getAllUnits());
}
}
final long result = value * multiplier;
// check for overflow
if (result / multiplier != value) {
throw new IllegalArgumentException("The value '" + text +
"' cannot be re represented as 64bit number of bytes (numeric overflow).");
}
return result;
} } | public class class_name {
public static long parseBytes(String text) throws IllegalArgumentException {
checkNotNull(text, "text");
final String trimmed = text.trim();
checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string");
final int len = trimmed.length();
int pos = 0;
char current;
while (pos < len && (current = trimmed.charAt(pos)) >= '0' && current <= '9') {
pos++;
}
final String number = trimmed.substring(0, pos);
final String unit = trimmed.substring(pos).trim().toLowerCase(Locale.US);
if (number.isEmpty()) {
throw new NumberFormatException("text does not start with a number");
}
final long value;
try {
value = Long.parseLong(number); // this throws a NumberFormatException on overflow
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("The value '" + number +
"' cannot be re represented as 64bit number (numeric overflow).");
}
final long multiplier;
if (unit.isEmpty()) {
multiplier = 1L;
}
else {
if (matchesAny(unit, BYTES)) {
multiplier = 1L; // depends on control dependency: [if], data = [none]
}
else if (matchesAny(unit, KILO_BYTES)) {
multiplier = 1024L; // depends on control dependency: [if], data = [none]
}
else if (matchesAny(unit, MEGA_BYTES)) {
multiplier = 1024L * 1024L; // depends on control dependency: [if], data = [none]
}
else if (matchesAny(unit, GIGA_BYTES)) {
multiplier = 1024L * 1024L * 1024L; // depends on control dependency: [if], data = [none]
}
else if (matchesAny(unit, TERA_BYTES)) {
multiplier = 1024L * 1024L * 1024L * 1024L; // depends on control dependency: [if], data = [none]
}
else {
throw new IllegalArgumentException("Memory size unit '" + unit +
"' does not match any of the recognized units: " + MemoryUnit.getAllUnits());
}
}
final long result = value * multiplier;
// check for overflow
if (result / multiplier != value) {
throw new IllegalArgumentException("The value '" + text +
"' cannot be re represented as 64bit number of bytes (numeric overflow).");
}
return result;
} } |
public class class_name {
public void loadArgArray() {
push(argumentTypes.length);
newArray(OBJECT_TYPE);
for (int i = 0; i < argumentTypes.length; i++) {
dup();
push(i);
loadArg(i);
box(argumentTypes[i]);
arrayStore(OBJECT_TYPE);
}
} } | public class class_name {
public void loadArgArray() {
push(argumentTypes.length);
newArray(OBJECT_TYPE);
for (int i = 0; i < argumentTypes.length; i++) {
dup(); // depends on control dependency: [for], data = [none]
push(i); // depends on control dependency: [for], data = [i]
loadArg(i); // depends on control dependency: [for], data = [i]
box(argumentTypes[i]); // depends on control dependency: [for], data = [i]
arrayStore(OBJECT_TYPE); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public synchronized List<E> getAll() {
ArrayList<E> list = new ArrayList<E>();
for (E element : listElements) {
if (element != null) {
list.add(element);
}
}
return list;
} } | public class class_name {
public synchronized List<E> getAll() {
ArrayList<E> list = new ArrayList<E>();
for (E element : listElements) {
if (element != null) {
list.add(element); // depends on control dependency: [if], data = [(element]
}
}
return list;
} } |
public class class_name {
private void destroyService(ServiceHandle<S> serviceHandle) {
try {
_serviceFactory.destroy(serviceHandle.getEndPoint(), serviceHandle.getService());
} catch (Exception e) {
// this should not happen, but if it does, swallow the exception and log it
LOG.warn("Error destroying serviceHandle", e);
}
} } | public class class_name {
private void destroyService(ServiceHandle<S> serviceHandle) {
try {
_serviceFactory.destroy(serviceHandle.getEndPoint(), serviceHandle.getService()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// this should not happen, but if it does, swallow the exception and log it
LOG.warn("Error destroying serviceHandle", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public List<NutResource> scan(String src, String regex) {
if (src.isEmpty())
throw new RuntimeException("emtry src is NOT allow");
if ("/".equals(src))
throw new RuntimeException("root path is NOT allow");
List<NutResource> list = new ArrayList<NutResource>();
Pattern pattern = regex == null ? null : Pattern.compile(regex);
// 先看看是不是文件系统上一个具体的文件
if (src.startsWith("~/"))
src = Disks.normalize(src);
File srcFile = new File(src);
if (srcFile.exists()) {
if (srcFile.isDirectory()) {
Disks.visitFile(srcFile,
new ResourceFileVisitor(list, src, 250),
new ResourceFileFilter(pattern));
} else {
list.add(new FileResource(src, srcFile).setPriority(250));
}
}
for (ResourceLocation location : locations.values()) {
location.scan(src, pattern, list);
}
// 如果啥都没找到,那么,用增强扫描
if (list.isEmpty()) {
try {
Enumeration<URL> enu = ClassTools.getClassLoader().getResources(src);
if (enu != null && enu.hasMoreElements()) {
while (enu.hasMoreElements()) {
try {
URL url = enu.nextElement();
ResourceLocation loc = makeResourceLocation(url);
if (url.toString().contains("jar!"))
loc.scan(src, pattern, list);
else
loc.scan("", pattern, list);
}
catch (Throwable e) {
if (log.isTraceEnabled())
log.trace("", e);
}
}
}
}
catch (Throwable e) {
if (log.isDebugEnabled())
log.debug("Fail to run deep scan!", e);
}
// 依然是空?
if (list.isEmpty() && !src.endsWith("/")) {
try {
ClassLoader classLoader = getClass().getClassLoader();
InputStream tmp = classLoader.getResourceAsStream(src + "/");
if (tmp != null) {
tmp.close();
} else {
InputStream ins = classLoader.getResourceAsStream(src);
if (ins != null) {
list.add(new SimpleResource(src, src, ins));
}
}
}
catch (Exception e) {
}
}
}
List<NutResource> _list = new ArrayList<NutResource>();
OUT: for (NutResource nr : list) {
Iterator<NutResource> it = _list.iterator();
while (it.hasNext()) {
NutResource nr2 = it.next();
if (nr.equals(nr2)) {
if (nr.priority > nr2.priority) {
it.remove();
} else {
continue OUT;
}
}
}
_list.add(nr);
}
list = _list;
Collections.sort(list);
if (log.isDebugEnabled())
log.debugf("Found %s resource by src( %s ) , regex( %s )", list.size(), src, regex);
return list;
} } | public class class_name {
public List<NutResource> scan(String src, String regex) {
if (src.isEmpty())
throw new RuntimeException("emtry src is NOT allow");
if ("/".equals(src))
throw new RuntimeException("root path is NOT allow");
List<NutResource> list = new ArrayList<NutResource>();
Pattern pattern = regex == null ? null : Pattern.compile(regex);
// 先看看是不是文件系统上一个具体的文件
if (src.startsWith("~/"))
src = Disks.normalize(src);
File srcFile = new File(src);
if (srcFile.exists()) {
if (srcFile.isDirectory()) {
Disks.visitFile(srcFile,
new ResourceFileVisitor(list, src, 250),
new ResourceFileFilter(pattern));
// depends on control dependency: [if], data = [none]
} else {
list.add(new FileResource(src, srcFile).setPriority(250));
// depends on control dependency: [if], data = [none]
}
}
for (ResourceLocation location : locations.values()) {
location.scan(src, pattern, list);
// depends on control dependency: [for], data = [location]
}
// 如果啥都没找到,那么,用增强扫描
if (list.isEmpty()) {
try {
Enumeration<URL> enu = ClassTools.getClassLoader().getResources(src);
if (enu != null && enu.hasMoreElements()) {
while (enu.hasMoreElements()) {
try {
URL url = enu.nextElement();
ResourceLocation loc = makeResourceLocation(url);
if (url.toString().contains("jar!"))
loc.scan(src, pattern, list);
else
loc.scan("", pattern, list);
}
catch (Throwable e) {
if (log.isTraceEnabled())
log.trace("", e);
}
// depends on control dependency: [catch], data = [none]
}
}
}
catch (Throwable e) {
if (log.isDebugEnabled())
log.debug("Fail to run deep scan!", e);
}
// depends on control dependency: [catch], data = [none]
// 依然是空?
if (list.isEmpty() && !src.endsWith("/")) {
try {
ClassLoader classLoader = getClass().getClassLoader();
InputStream tmp = classLoader.getResourceAsStream(src + "/");
if (tmp != null) {
tmp.close();
// depends on control dependency: [if], data = [none]
} else {
InputStream ins = classLoader.getResourceAsStream(src);
if (ins != null) {
list.add(new SimpleResource(src, src, ins));
// depends on control dependency: [if], data = [none]
}
}
}
catch (Exception e) {
}
// depends on control dependency: [catch], data = [none]
}
}
List<NutResource> _list = new ArrayList<NutResource>();
OUT: for (NutResource nr : list) {
Iterator<NutResource> it = _list.iterator();
while (it.hasNext()) {
NutResource nr2 = it.next();
if (nr.equals(nr2)) {
if (nr.priority > nr2.priority) {
it.remove();
// depends on control dependency: [if], data = [none]
} else {
continue OUT;
}
}
}
_list.add(nr);
// depends on control dependency: [for], data = [nr]
}
list = _list;
Collections.sort(list);
if (log.isDebugEnabled())
log.debugf("Found %s resource by src( %s ) , regex( %s )", list.size(), src, regex);
return list;
} } |
public class class_name {
@Override
public void storeNotification(NamespaceNotification notification) {
int notificationsCount = 0;
historyLock.writeLock().lock();
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Storing into history: " + NotifierUtils.asString(notification));
}
String[] paths = DFSUtil.split(notification.path, Path.SEPARATOR_CHAR);
long timestamp = System.currentTimeMillis();
HistoryTreeEntry entry = new HistoryTreeEntry(timestamp, notification.txId, notification.type);
// Store the notification
HistoryNode node = historyTree;
for (String path : paths) {
if (path.trim().length() == 0) {
continue;
}
node = node.addOrGetChild(path);
}
if (node.notifications == null) {
node.notifications = new HashMap<Byte, List<HistoryTreeEntry>>();
}
if (!node.notifications.containsKey(notification.type)) {
node.notifications.put(notification.type, new LinkedList<HistoryTreeEntry>());
}
entry.node = node;
node.notifications.get(notification.type).add(entry);
orderedHistoryList.add(entry);
notificationsCount = orderedHistoryList.size();
} finally {
historyLock.writeLock().unlock();
}
core.getMetrics().historySize.set(notificationsCount);
core.getMetrics().historyQueues.set(historyQueuesCount);
if (LOG.isDebugEnabled()) {
LOG.debug("Notification stored.");
}
} } | public class class_name {
@Override
public void storeNotification(NamespaceNotification notification) {
int notificationsCount = 0;
historyLock.writeLock().lock();
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Storing into history: " + NotifierUtils.asString(notification)); // depends on control dependency: [if], data = [none]
}
String[] paths = DFSUtil.split(notification.path, Path.SEPARATOR_CHAR);
long timestamp = System.currentTimeMillis();
HistoryTreeEntry entry = new HistoryTreeEntry(timestamp, notification.txId, notification.type);
// Store the notification
HistoryNode node = historyTree;
for (String path : paths) {
if (path.trim().length() == 0) {
continue;
}
node = node.addOrGetChild(path); // depends on control dependency: [for], data = [path]
}
if (node.notifications == null) {
node.notifications = new HashMap<Byte, List<HistoryTreeEntry>>(); // depends on control dependency: [if], data = [none]
}
if (!node.notifications.containsKey(notification.type)) {
node.notifications.put(notification.type, new LinkedList<HistoryTreeEntry>()); // depends on control dependency: [if], data = [none]
}
entry.node = node; // depends on control dependency: [try], data = [none]
node.notifications.get(notification.type).add(entry); // depends on control dependency: [try], data = [none]
orderedHistoryList.add(entry); // depends on control dependency: [try], data = [none]
notificationsCount = orderedHistoryList.size(); // depends on control dependency: [try], data = [none]
} finally {
historyLock.writeLock().unlock();
}
core.getMetrics().historySize.set(notificationsCount);
core.getMetrics().historyQueues.set(historyQueuesCount);
if (LOG.isDebugEnabled()) {
LOG.debug("Notification stored."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean syncClonedListener(BaseField field, FieldListener listener, boolean bInitCalled)
{
if (!bInitCalled)
{
BaseField fldSource = this.getSyncedListenersField(m_fldSource, listener);
((InitFieldHandler)listener).init(null, fldSource, m_objSource, m_bInitIfSourceNull, m_bOnlyInitIfDestNull);
}
return super.syncClonedListener(field, listener, true);
} } | public class class_name {
public boolean syncClonedListener(BaseField field, FieldListener listener, boolean bInitCalled)
{
if (!bInitCalled)
{
BaseField fldSource = this.getSyncedListenersField(m_fldSource, listener);
((InitFieldHandler)listener).init(null, fldSource, m_objSource, m_bInitIfSourceNull, m_bOnlyInitIfDestNull); // depends on control dependency: [if], data = [none]
}
return super.syncClonedListener(field, listener, true);
} } |
public class class_name {
@Override
public void visit(NodeVisitor v) {
if (v.visit(this)) {
expression.visit(v);
for (SwitchCase sc: getCases()) {
sc.visit(v);
}
}
} } | public class class_name {
@Override
public void visit(NodeVisitor v) {
if (v.visit(this)) {
expression.visit(v); // depends on control dependency: [if], data = [none]
for (SwitchCase sc: getCases()) {
sc.visit(v); // depends on control dependency: [for], data = [sc]
}
}
} } |
public class class_name {
OrderedHashSet getContainingConstraints(int colIndex) {
OrderedHashSet set = new OrderedHashSet();
for (int i = 0, size = constraintList.length; i < size; i++) {
Constraint c = constraintList[i];
if (c.hasColumnPlus(colIndex)) {
set.add(c);
}
}
return set;
} } | public class class_name {
OrderedHashSet getContainingConstraints(int colIndex) {
OrderedHashSet set = new OrderedHashSet();
for (int i = 0, size = constraintList.length; i < size; i++) {
Constraint c = constraintList[i];
if (c.hasColumnPlus(colIndex)) {
set.add(c); // depends on control dependency: [if], data = [none]
}
}
return set;
} } |
public class class_name {
@Override
@SuppressWarnings("unchecked")
public Handle<K, V> findMin() {
if (size == 0) {
throw new NoSuchElementException();
} else if (size == 1) {
return free;
} else if (size % 2 == 0) {
return minHeap.findMin().getValue().outer;
} else {
AddressableHeap.Handle<K, HandleMap<K, V>> minInnerHandle = minHeap.findMin();
int c;
if (comparator == null) {
c = ((Comparable<? super K>) minInnerHandle.getKey()).compareTo(free.key);
} else {
c = comparator.compare(minInnerHandle.getKey(), free.key);
}
if (c < 0) {
return minInnerHandle.getValue().outer;
} else {
return free;
}
}
} } | public class class_name {
@Override
@SuppressWarnings("unchecked")
public Handle<K, V> findMin() {
if (size == 0) {
throw new NoSuchElementException();
} else if (size == 1) {
return free; // depends on control dependency: [if], data = [none]
} else if (size % 2 == 0) {
return minHeap.findMin().getValue().outer; // depends on control dependency: [if], data = [none]
} else {
AddressableHeap.Handle<K, HandleMap<K, V>> minInnerHandle = minHeap.findMin();
int c;
if (comparator == null) {
c = ((Comparable<? super K>) minInnerHandle.getKey()).compareTo(free.key); // depends on control dependency: [if], data = [none]
} else {
c = comparator.compare(minInnerHandle.getKey(), free.key); // depends on control dependency: [if], data = [none]
}
if (c < 0) {
return minInnerHandle.getValue().outer; // depends on control dependency: [if], data = [none]
} else {
return free; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected String bodyInsertContent(ReplayParseContext context) {
if (jspInsertPath == null)
return null;
JSPExecutor jspExec = context.getJspExec();
// FIXME bad chain of references. add method to ReplayParseContext?
WaybackRequest wbRequest = jspExec.getUiResults().getWbRequest();
// isAnyEmbeddedContext() used as shorthand for (isFrameWrapperContext()
// && isIFrameWrapperContext()).
if (wbRequest.isAnyEmbeddedContext())
return null;
try {
return jspExec.jspToString(jspInsertPath);
} catch (ServletException ex) {
LOGGER.log(Level.WARNING, "execution of " + jspInsertPath +
" failed", ex);
return null;
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "erorr executing " + jspInsertPath, ex);
return null;
}
} } | public class class_name {
protected String bodyInsertContent(ReplayParseContext context) {
if (jspInsertPath == null)
return null;
JSPExecutor jspExec = context.getJspExec();
// FIXME bad chain of references. add method to ReplayParseContext?
WaybackRequest wbRequest = jspExec.getUiResults().getWbRequest();
// isAnyEmbeddedContext() used as shorthand for (isFrameWrapperContext()
// && isIFrameWrapperContext()).
if (wbRequest.isAnyEmbeddedContext())
return null;
try {
return jspExec.jspToString(jspInsertPath); // depends on control dependency: [try], data = [none]
} catch (ServletException ex) {
LOGGER.log(Level.WARNING, "execution of " + jspInsertPath +
" failed", ex);
return null;
} catch (IOException ex) { // depends on control dependency: [catch], data = [none]
LOGGER.log(Level.WARNING, "erorr executing " + jspInsertPath, ex);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public synchronized byte[] getBytes(
int parameterIndex) throws SQLException {
Object x = getColumnInType(parameterIndex, Type.SQL_VARBINARY);
if (x == null) {
return null;
}
return ((BinaryData) x).getBytes();
} } | public class class_name {
public synchronized byte[] getBytes(
int parameterIndex) throws SQLException {
Object x = getColumnInType(parameterIndex, Type.SQL_VARBINARY);
if (x == null) {
return null; // depends on control dependency: [if], data = [none]
}
return ((BinaryData) x).getBytes();
} } |
public class class_name {
void resetTail(long index) {
for (SegmentedJournalReader reader : readers) {
if (reader.getNextIndex() >= index) {
reader.reset(index);
}
}
} } | public class class_name {
void resetTail(long index) {
for (SegmentedJournalReader reader : readers) {
if (reader.getNextIndex() >= index) {
reader.reset(index); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public boolean findInList(int[] address) {
int len = address.length;
if (len < IP_ADDR_NUMBERS) {
int j = IP_ADDR_NUMBERS - 1;
// for performace, hard code the size here
int a[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
// int a[] = new int[IP_ADDR_NUMBERS];
// for (int i = 0; i < IP_ADDR_NUMBERS; i++)
// {
// a[i] = 0;
// }
for (int i = len; i > 0; i--, j--) {
a[j] = address[i - 1];
}
return findInList(a, 0, firstCell, 7);
}
return findInList(address, 0, firstCell, (address.length - 1));
} } | public class class_name {
public boolean findInList(int[] address) {
int len = address.length;
if (len < IP_ADDR_NUMBERS) {
int j = IP_ADDR_NUMBERS - 1;
// for performace, hard code the size here
int a[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
// int a[] = new int[IP_ADDR_NUMBERS];
// for (int i = 0; i < IP_ADDR_NUMBERS; i++)
// {
// a[i] = 0;
// }
for (int i = len; i > 0; i--, j--) {
a[j] = address[i - 1]; // depends on control dependency: [for], data = [i]
}
return findInList(a, 0, firstCell, 7); // depends on control dependency: [if], data = [none]
}
return findInList(address, 0, firstCell, (address.length - 1));
} } |
public class class_name {
@DELETE
@RequiresPermissions(I18nPermissions.LOCALE_DELETE)
public Response deleteAllAvailableLocales() {
List<Locale> locales = localeRepository.loadAll();
for (Locale locale : locales) {
localeRepository.remove(locale);
}
return Response.noContent().build();
} } | public class class_name {
@DELETE
@RequiresPermissions(I18nPermissions.LOCALE_DELETE)
public Response deleteAllAvailableLocales() {
List<Locale> locales = localeRepository.loadAll();
for (Locale locale : locales) {
localeRepository.remove(locale); // depends on control dependency: [for], data = [locale]
}
return Response.noContent().build();
} } |
public class class_name {
public void setLocal(Object key, Object value) {
if (data == null) {
data = new HashMap();
}
data.put(key, value);
} } | public class class_name {
public void setLocal(Object key, Object value) {
if (data == null) {
data = new HashMap();
// depends on control dependency: [if], data = [none]
}
data.put(key, value);
} } |
public class class_name {
public void clear() {
Iterator<E> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
} } | public class class_name {
public void clear() {
Iterator<E> it = iterator();
while (it.hasNext()) {
it.next(); // depends on control dependency: [while], data = [none]
it.remove(); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map,
final K key, final ConcurrentInitializer<V> init) {
try {
return createIfAbsent(map, key, init);
} catch (final ConcurrentException cex) {
throw new ConcurrentRuntimeException(cex.getCause());
}
} } | public class class_name {
public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map,
final K key, final ConcurrentInitializer<V> init) {
try {
return createIfAbsent(map, key, init); // depends on control dependency: [try], data = [none]
} catch (final ConcurrentException cex) {
throw new ConcurrentRuntimeException(cex.getCause());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private long adjustItems(long size) {
while (size > maxSize && buffer.size() > 0) {
CBuffRecord old = buffer.removeFirst();
size -= old.bytes.length;
}
return size;
} } | public class class_name {
private long adjustItems(long size) {
while (size > maxSize && buffer.size() > 0) {
CBuffRecord old = buffer.removeFirst();
size -= old.bytes.length; // depends on control dependency: [while], data = [none]
}
return size;
} } |
public class class_name {
public static ParsedSql parseSqlStatement(final String sql) {
Assert.notNull(sql, "SQL must not be null");
Set<String> namedParameters = new HashSet<>();
String sqlToUse = sql;
List<ParameterHolder> parameterList = new ArrayList<>();
char[] statement = sql.toCharArray();
int namedParameterCount = 0;
int unnamedParameterCount = 0;
int totalParameterCount = 0;
int escapes = 0;
int i = 0;
while (i < statement.length) {
int skipToPosition;
while (i < statement.length) {
skipToPosition = skipCommentsAndQuotes(statement, i);
if (i == skipToPosition) {
break;
} else {
i = skipToPosition;
}
}
if (i >= statement.length) {
break;
}
char c = statement[i];
if (c == ':' || c == '&') {
int j = i + 1;
if (j < statement.length && statement[j] == ':' && c == ':') {
// Postgres-style "::" casting operator should be skipped
i = i + 2;
continue;
}
String parameter;
if (j < statement.length && c == ':' && statement[j] == '{') {
// :{x} style parameter
while (j < statement.length && !('}' == statement[j])) {
j++;
if (':' == statement[j] || '{' == statement[j]) {
throw new CommonRuntimeException("Parameter name contains invalid character '" +
statement[j] + "' at position " + i + " in statement: " + sql);
}
}
if (j >= statement.length) {
throw new CommonRuntimeException(
"Non-terminated named parameter declaration at position " + i + " in statement: " + sql);
}
if (j - i > 3) {
parameter = sql.substring(i + 2, j);
namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter);
}
j++;
} else {
while (j < statement.length && !isParameterSeparator(statement[j])) {
j++;
}
if (j - i > 1) {
parameter = sql.substring(i + 1, j);
namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter);
}
}
i = j - 1;
} else {
if (c == '\\') {
int j = i + 1;
if (j < statement.length && statement[j] == ':') {
// escaped ":" should be skipped
sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1);
escapes++;
i = i + 2;
continue;
}
}
if (c == '?') {
int j = i + 1;
if (j < statement.length && (statement[j] == '?' || statement[j] == '|' || statement[j] == '&')) {
// Postgres-style "??", "?|", "?&" operator should be skipped
i = i + 2;
continue;
}
unnamedParameterCount++;
totalParameterCount++;
}
}
i++;
}
ParsedSql parsedSql = new ParsedSql(sqlToUse);
parsedSql.setParameterList(parameterList);
parsedSql.setNamedParameterCount(namedParameterCount);
parsedSql.setUnnamedParameterCount(unnamedParameterCount);
parsedSql.setTotalParameterCount(totalParameterCount);
return parsedSql;
} } | public class class_name {
public static ParsedSql parseSqlStatement(final String sql) {
Assert.notNull(sql, "SQL must not be null");
Set<String> namedParameters = new HashSet<>();
String sqlToUse = sql;
List<ParameterHolder> parameterList = new ArrayList<>();
char[] statement = sql.toCharArray();
int namedParameterCount = 0;
int unnamedParameterCount = 0;
int totalParameterCount = 0;
int escapes = 0;
int i = 0;
while (i < statement.length) {
int skipToPosition;
while (i < statement.length) {
skipToPosition = skipCommentsAndQuotes(statement, i); // depends on control dependency: [while], data = [none]
if (i == skipToPosition) {
break;
} else {
i = skipToPosition; // depends on control dependency: [if], data = [none]
}
}
if (i >= statement.length) {
break;
}
char c = statement[i];
if (c == ':' || c == '&') {
int j = i + 1;
if (j < statement.length && statement[j] == ':' && c == ':') {
// Postgres-style "::" casting operator should be skipped
i = i + 2; // depends on control dependency: [if], data = [none]
continue;
}
String parameter;
if (j < statement.length && c == ':' && statement[j] == '{') {
// :{x} style parameter
while (j < statement.length && !('}' == statement[j])) {
j++; // depends on control dependency: [while], data = [none]
if (':' == statement[j] || '{' == statement[j]) {
throw new CommonRuntimeException("Parameter name contains invalid character '" +
statement[j] + "' at position " + i + " in statement: " + sql);
}
}
if (j >= statement.length) {
throw new CommonRuntimeException(
"Non-terminated named parameter declaration at position " + i + " in statement: " + sql);
}
if (j - i > 3) {
parameter = sql.substring(i + 2, j); // depends on control dependency: [if], data = [none]
namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter); // depends on control dependency: [if], data = [none]
totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter); // depends on control dependency: [if], data = [none]
}
j++; // depends on control dependency: [if], data = [none]
} else {
while (j < statement.length && !isParameterSeparator(statement[j])) {
j++; // depends on control dependency: [while], data = [none]
}
if (j - i > 1) {
parameter = sql.substring(i + 1, j); // depends on control dependency: [if], data = [none]
namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter); // depends on control dependency: [if], data = [none]
totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter); // depends on control dependency: [if], data = [none]
}
}
i = j - 1; // depends on control dependency: [if], data = [none]
} else {
if (c == '\\') {
int j = i + 1;
if (j < statement.length && statement[j] == ':') {
// escaped ":" should be skipped
sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1); // depends on control dependency: [if], data = [none]
escapes++; // depends on control dependency: [if], data = [none]
i = i + 2; // depends on control dependency: [if], data = [none]
continue;
}
}
if (c == '?') {
int j = i + 1;
if (j < statement.length && (statement[j] == '?' || statement[j] == '|' || statement[j] == '&')) {
// Postgres-style "??", "?|", "?&" operator should be skipped
i = i + 2; // depends on control dependency: [if], data = [none]
continue;
}
unnamedParameterCount++; // depends on control dependency: [if], data = [none]
totalParameterCount++; // depends on control dependency: [if], data = [none]
}
}
i++; // depends on control dependency: [while], data = [none]
}
ParsedSql parsedSql = new ParsedSql(sqlToUse);
parsedSql.setParameterList(parameterList);
parsedSql.setNamedParameterCount(namedParameterCount);
parsedSql.setUnnamedParameterCount(unnamedParameterCount);
parsedSql.setTotalParameterCount(totalParameterCount);
return parsedSql;
} } |
public class class_name {
private void boundaryLineExteriorPoint_(int cluster, int id_a, int id_b,
int cluster_index_a) {
if (m_matrix[MatrixPredicate.BoundaryExterior] == 0)
return;
int clusterParentage = m_topo_graph.getClusterParentage(cluster);
if ((clusterParentage & id_a) != 0 && (clusterParentage & id_b) == 0) {
int index = m_topo_graph.getClusterUserIndex(cluster,
cluster_index_a);
if (index % 2 != 0) {
m_matrix[MatrixPredicate.BoundaryExterior] = 0;
}
}
} } | public class class_name {
private void boundaryLineExteriorPoint_(int cluster, int id_a, int id_b,
int cluster_index_a) {
if (m_matrix[MatrixPredicate.BoundaryExterior] == 0)
return;
int clusterParentage = m_topo_graph.getClusterParentage(cluster);
if ((clusterParentage & id_a) != 0 && (clusterParentage & id_b) == 0) {
int index = m_topo_graph.getClusterUserIndex(cluster,
cluster_index_a);
if (index % 2 != 0) {
m_matrix[MatrixPredicate.BoundaryExterior] = 0; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void execute() throws MojoExecutionException {
synchronized (lock) {
injectDependencyDefaults();
resolveArtifacts();
// Install project dependencies into classloader's class path
// and execute xjc2.
final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader classLoader = createClassLoader(currentClassLoader);
Thread.currentThread().setContextClassLoader(classLoader);
final Locale currentDefaultLocale = Locale.getDefault();
try {
final Locale locale = LocaleUtils.valueOf(getLocale());
Locale.setDefault(locale);
//
doExecute();
} finally {
Locale.setDefault(currentDefaultLocale);
// Set back the old classloader
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
} } | public class class_name {
public void execute() throws MojoExecutionException {
synchronized (lock) {
injectDependencyDefaults();
resolveArtifacts();
// Install project dependencies into classloader's class path
// and execute xjc2.
final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader classLoader = createClassLoader(currentClassLoader);
Thread.currentThread().setContextClassLoader(classLoader);
final Locale currentDefaultLocale = Locale.getDefault();
try {
final Locale locale = LocaleUtils.valueOf(getLocale());
Locale.setDefault(locale);
// depends on control dependency: [try], data = [none]
//
doExecute();
// depends on control dependency: [try], data = [none]
} finally {
Locale.setDefault(currentDefaultLocale);
// Set back the old classloader
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
} } |
public class class_name {
public Set<InstallLicense> getFeatureLicense(Collection<String> featureIds, File fromDir, String toExtension, boolean offlineOnly, Locale locale) throws InstallException {
Set<InstallLicense> licenses = new HashSet<InstallLicense>();
ArrayList<InstallAsset> installAssets = new ArrayList<InstallAsset>();
ArrayList<String> unresolvedFeatures = new ArrayList<String>();
Collection<ESAAsset> autoFeatures = getResolveDirector().getAutoFeature(fromDir, toExtension);
getResolveDirector().resolve(featureIds, fromDir, toExtension, offlineOnly, installAssets, unresolvedFeatures);
if (!offlineOnly && !unresolvedFeatures.isEmpty()) {
log(Level.FINEST, "getFeatureLicense() determined unresolved features: " + unresolvedFeatures.toString() + " from " + fromDir.getAbsolutePath());
licenses = getFeatureLicense(unresolvedFeatures, locale, null, null);
}
if (installAssets.isEmpty()) {
return licenses;
}
getResolveDirector().resolveAutoFeatures(autoFeatures, installAssets);
Map<String, InstallLicenseImpl> licenseIds = new HashMap<String, InstallLicenseImpl>();
for (InstallAsset installAsset : installAssets) {
if (installAsset.isFeature()) {
ESAAsset esa = (ESAAsset) installAsset;
if (esa.isPublic()) {
ExeInstallAction.incrementNumOfLocalFeatures();
}
LicenseProvider lp = esa.getLicenseProvider(locale);
String licenseId = esa.getLicenseId();
if (licenseId != null && !licenseId.isEmpty()) {
InstallLicenseImpl ili = licenseIds.get(licenseId);
if (ili == null) {
ili = new InstallLicenseImpl(licenseId, null, lp);
licenseIds.put(licenseId, ili);
}
ili.addFeature(esa.getProvideFeature());
}
}
}
licenses.addAll(licenseIds.values());
return licenses;
} } | public class class_name {
public Set<InstallLicense> getFeatureLicense(Collection<String> featureIds, File fromDir, String toExtension, boolean offlineOnly, Locale locale) throws InstallException {
Set<InstallLicense> licenses = new HashSet<InstallLicense>();
ArrayList<InstallAsset> installAssets = new ArrayList<InstallAsset>();
ArrayList<String> unresolvedFeatures = new ArrayList<String>();
Collection<ESAAsset> autoFeatures = getResolveDirector().getAutoFeature(fromDir, toExtension);
getResolveDirector().resolve(featureIds, fromDir, toExtension, offlineOnly, installAssets, unresolvedFeatures);
if (!offlineOnly && !unresolvedFeatures.isEmpty()) {
log(Level.FINEST, "getFeatureLicense() determined unresolved features: " + unresolvedFeatures.toString() + " from " + fromDir.getAbsolutePath());
licenses = getFeatureLicense(unresolvedFeatures, locale, null, null);
}
if (installAssets.isEmpty()) {
return licenses;
}
getResolveDirector().resolveAutoFeatures(autoFeatures, installAssets);
Map<String, InstallLicenseImpl> licenseIds = new HashMap<String, InstallLicenseImpl>();
for (InstallAsset installAsset : installAssets) {
if (installAsset.isFeature()) {
ESAAsset esa = (ESAAsset) installAsset;
if (esa.isPublic()) {
ExeInstallAction.incrementNumOfLocalFeatures(); // depends on control dependency: [if], data = [none]
}
LicenseProvider lp = esa.getLicenseProvider(locale);
String licenseId = esa.getLicenseId();
if (licenseId != null && !licenseId.isEmpty()) {
InstallLicenseImpl ili = licenseIds.get(licenseId);
if (ili == null) {
ili = new InstallLicenseImpl(licenseId, null, lp); // depends on control dependency: [if], data = [none]
licenseIds.put(licenseId, ili); // depends on control dependency: [if], data = [none]
}
ili.addFeature(esa.getProvideFeature()); // depends on control dependency: [if], data = [none]
}
}
}
licenses.addAll(licenseIds.values());
return licenses;
} } |
public class class_name {
public static synchronized Apptentive.DateTime getTimeAtInstall(Selector selector) {
ensureLoaded();
for (VersionHistoryEntry entry : versionHistoryEntries) {
switch (selector) {
case total:
// Since the list is ordered, this will be the first and oldest entry.
return new Apptentive.DateTime(entry.getTimestamp());
case version_code:
if (entry.getVersionCode() == RuntimeUtils.getAppVersionCode(ApptentiveInternal.getInstance().getApplicationContext())) {
return new Apptentive.DateTime(entry.getTimestamp());
}
break;
case version_name:
Apptentive.Version entryVersionName = new Apptentive.Version();
Apptentive.Version currentVersionName = new Apptentive.Version();
entryVersionName.setVersion(entry.getVersionName());
currentVersionName.setVersion(RuntimeUtils.getAppVersionName(ApptentiveInternal.getInstance().getApplicationContext()));
if (entryVersionName.equals(currentVersionName)) {
return new Apptentive.DateTime(entry.getTimestamp());
}
break;
}
}
return new Apptentive.DateTime(Util.currentTimeSeconds());
} } | public class class_name {
public static synchronized Apptentive.DateTime getTimeAtInstall(Selector selector) {
ensureLoaded();
for (VersionHistoryEntry entry : versionHistoryEntries) {
switch (selector) {
case total:
// Since the list is ordered, this will be the first and oldest entry.
return new Apptentive.DateTime(entry.getTimestamp());
case version_code:
if (entry.getVersionCode() == RuntimeUtils.getAppVersionCode(ApptentiveInternal.getInstance().getApplicationContext())) {
return new Apptentive.DateTime(entry.getTimestamp()); // depends on control dependency: [if], data = [none]
}
break;
case version_name:
Apptentive.Version entryVersionName = new Apptentive.Version();
Apptentive.Version currentVersionName = new Apptentive.Version();
entryVersionName.setVersion(entry.getVersionName());
currentVersionName.setVersion(RuntimeUtils.getAppVersionName(ApptentiveInternal.getInstance().getApplicationContext()));
if (entryVersionName.equals(currentVersionName)) {
return new Apptentive.DateTime(entry.getTimestamp()); // depends on control dependency: [if], data = [none]
}
break;
}
}
return new Apptentive.DateTime(Util.currentTimeSeconds());
} } |
public class class_name {
protected String getRequiredMessage(final String[] messageKeys) {
MessageSourceResolvable resolvable = new MessageSourceResolvable() {
public String[] getCodes() {
return messageKeys;
}
public Object[] getArguments() {
return null;
}
public String getDefaultMessage() {
if (messageKeys.length > 0) {
return messageKeys[0];
}
return "";
}
};
return getMessages().getMessage(resolvable);
} } | public class class_name {
protected String getRequiredMessage(final String[] messageKeys) {
MessageSourceResolvable resolvable = new MessageSourceResolvable() {
public String[] getCodes() {
return messageKeys;
}
public Object[] getArguments() {
return null;
}
public String getDefaultMessage() {
if (messageKeys.length > 0) {
return messageKeys[0]; // depends on control dependency: [if], data = [none]
}
return "";
}
};
return getMessages().getMessage(resolvable);
} } |
public class class_name {
public static <T extends ImageGray<T>, Desc extends TupleDesc>
StereoVisualOdometry<T> stereoDualTrackerPnP(int thresholdAdd, int thresholdRetire,
double inlierPixelTol,
double epipolarPixelTol,
int ransacIterations,
int refineIterations,
PointTracker<T> trackerLeft, PointTracker<T> trackerRight,
DescribeRegionPoint<T,Desc> descriptor,
Class<T> imageType)
{
EstimateNofPnP pnp = FactoryMultiView.pnp_N(EnumPNP.P3P_FINSTERWALDER, -1);
DistanceFromModelMultiView<Se3_F64,Point2D3D> distanceMono = new PnPDistanceReprojectionSq();
PnPStereoDistanceReprojectionSq distanceStereo = new PnPStereoDistanceReprojectionSq();
PnPStereoEstimator pnpStereo = new PnPStereoEstimator(pnp,distanceMono,0);
ModelManagerSe3_F64 manager = new ModelManagerSe3_F64();
EstimatorToGenerator<Se3_F64,Stereo2D3D> generator = new EstimatorToGenerator<>(pnpStereo);
// Pixel tolerance for RANSAC inliers - euclidean error squared from left + right images
double ransacTOL = 2*inlierPixelTol * inlierPixelTol;
ModelMatcher<Se3_F64, Stereo2D3D> motion =
new Ransac<>(2323, manager, generator, distanceStereo, ransacIterations, ransacTOL);
RefinePnPStereo refinePnP = null;
Class<Desc> descType = descriptor.getDescriptionType();
ScoreAssociation<Desc> scorer = FactoryAssociation.defaultScore(descType);
AssociateStereo2D<Desc> associateStereo = new AssociateStereo2D<>(scorer, epipolarPixelTol, descType);
// need to make sure associations are unique
AssociateDescription2D<Desc> associateUnique = associateStereo;
if( !associateStereo.uniqueDestination() || !associateStereo.uniqueSource() ) {
associateUnique = new EnforceUniqueByScore.Describe2D<>(associateStereo, true, true);
}
if( refineIterations > 0 ) {
refinePnP = new PnPStereoRefineRodrigues(1e-12,refineIterations);
}
Triangulate2ViewsMetric triangulate = FactoryMultiView.triangulate2ViewMetric(
new ConfigTriangulation(ConfigTriangulation.Type.GEOMETRIC));
VisOdomDualTrackPnP<T,Desc> alg = new VisOdomDualTrackPnP<>(thresholdAdd, thresholdRetire, epipolarPixelTol,
trackerLeft, trackerRight, descriptor, associateUnique, triangulate, motion, refinePnP);
return new WrapVisOdomDualTrackPnP<>(pnpStereo, distanceMono, distanceStereo, associateStereo, alg, refinePnP, imageType);
} } | public class class_name {
public static <T extends ImageGray<T>, Desc extends TupleDesc>
StereoVisualOdometry<T> stereoDualTrackerPnP(int thresholdAdd, int thresholdRetire,
double inlierPixelTol,
double epipolarPixelTol,
int ransacIterations,
int refineIterations,
PointTracker<T> trackerLeft, PointTracker<T> trackerRight,
DescribeRegionPoint<T,Desc> descriptor,
Class<T> imageType)
{
EstimateNofPnP pnp = FactoryMultiView.pnp_N(EnumPNP.P3P_FINSTERWALDER, -1);
DistanceFromModelMultiView<Se3_F64,Point2D3D> distanceMono = new PnPDistanceReprojectionSq();
PnPStereoDistanceReprojectionSq distanceStereo = new PnPStereoDistanceReprojectionSq();
PnPStereoEstimator pnpStereo = new PnPStereoEstimator(pnp,distanceMono,0);
ModelManagerSe3_F64 manager = new ModelManagerSe3_F64();
EstimatorToGenerator<Se3_F64,Stereo2D3D> generator = new EstimatorToGenerator<>(pnpStereo);
// Pixel tolerance for RANSAC inliers - euclidean error squared from left + right images
double ransacTOL = 2*inlierPixelTol * inlierPixelTol;
ModelMatcher<Se3_F64, Stereo2D3D> motion =
new Ransac<>(2323, manager, generator, distanceStereo, ransacIterations, ransacTOL);
RefinePnPStereo refinePnP = null;
Class<Desc> descType = descriptor.getDescriptionType();
ScoreAssociation<Desc> scorer = FactoryAssociation.defaultScore(descType);
AssociateStereo2D<Desc> associateStereo = new AssociateStereo2D<>(scorer, epipolarPixelTol, descType);
// need to make sure associations are unique
AssociateDescription2D<Desc> associateUnique = associateStereo;
if( !associateStereo.uniqueDestination() || !associateStereo.uniqueSource() ) {
associateUnique = new EnforceUniqueByScore.Describe2D<>(associateStereo, true, true);
}
if( refineIterations > 0 ) {
refinePnP = new PnPStereoRefineRodrigues(1e-12,refineIterations); // depends on control dependency: [if], data = [none]
}
Triangulate2ViewsMetric triangulate = FactoryMultiView.triangulate2ViewMetric(
new ConfigTriangulation(ConfigTriangulation.Type.GEOMETRIC));
VisOdomDualTrackPnP<T,Desc> alg = new VisOdomDualTrackPnP<>(thresholdAdd, thresholdRetire, epipolarPixelTol,
trackerLeft, trackerRight, descriptor, associateUnique, triangulate, motion, refinePnP);
return new WrapVisOdomDualTrackPnP<>(pnpStereo, distanceMono, distanceStereo, associateStereo, alg, refinePnP, imageType);
} } |
public class class_name {
public static MultipleVersionRange parseMultipleVersionRange(String intersection) throws VersionException
{
Assert.notNull(intersection, "Version range must not be null.");
List<VersionRange> ranges = new ArrayList<VersionRange>();
String process = intersection;
Version upperBound = null;
Version lowerBound = null;
while (process.startsWith("[") || process.startsWith("("))
{
int index1 = process.indexOf(")");
int index2 = process.indexOf("]");
int index = index2;
if (index2 < 0 || index1 < index2)
{
if (index1 >= 0)
{
index = index1;
}
}
if (index < 0)
{
throw new VersionException("Unbounded range: " + intersection);
}
VersionRange range = parseVersionRange(process.substring(0, index + 1));
if (lowerBound == null)
{
lowerBound = range.getMin();
}
if (upperBound != null)
{
if (range.getMin() == null || range.getMin().compareTo(upperBound) < 0)
{
throw new VersionException("Ranges overlap: " + intersection);
}
}
ranges.add(range);
upperBound = range.getMax();
process = process.substring(index + 1).trim();
if (process.length() > 0 && process.startsWith(","))
{
process = process.substring(1).trim();
}
}
if (process.length() > 0)
{
if (ranges.size() > 0)
{
throw new VersionException("Only fully-qualified sets allowed in multiple version range scenario: "
+ intersection);
}
if (process.contains(","))
{
String[] split = process.split(",");
for (String version : split)
{
if (version.startsWith("[") || version.startsWith("("))
ranges.add(parseVersionRange(version));
else
ranges.add(new SingleVersionRange(SingleVersion.valueOf(version)));
}
}
else
{
ranges.add(new SingleVersionRange(SingleVersion.valueOf(process)));
}
}
return new MultipleVersionRange(ranges);
} } | public class class_name {
public static MultipleVersionRange parseMultipleVersionRange(String intersection) throws VersionException
{
Assert.notNull(intersection, "Version range must not be null.");
List<VersionRange> ranges = new ArrayList<VersionRange>();
String process = intersection;
Version upperBound = null;
Version lowerBound = null;
while (process.startsWith("[") || process.startsWith("("))
{
int index1 = process.indexOf(")");
int index2 = process.indexOf("]");
int index = index2;
if (index2 < 0 || index1 < index2)
{
if (index1 >= 0)
{
index = index1; // depends on control dependency: [if], data = [none]
}
}
if (index < 0)
{
throw new VersionException("Unbounded range: " + intersection);
}
VersionRange range = parseVersionRange(process.substring(0, index + 1));
if (lowerBound == null)
{
lowerBound = range.getMin(); // depends on control dependency: [if], data = [none]
}
if (upperBound != null)
{
if (range.getMin() == null || range.getMin().compareTo(upperBound) < 0)
{
throw new VersionException("Ranges overlap: " + intersection);
}
}
ranges.add(range);
upperBound = range.getMax();
process = process.substring(index + 1).trim();
if (process.length() > 0 && process.startsWith(","))
{
process = process.substring(1).trim(); // depends on control dependency: [if], data = [none]
}
}
if (process.length() > 0)
{
if (ranges.size() > 0)
{
throw new VersionException("Only fully-qualified sets allowed in multiple version range scenario: "
+ intersection);
}
if (process.contains(","))
{
String[] split = process.split(",");
for (String version : split)
{
if (version.startsWith("[") || version.startsWith("("))
ranges.add(parseVersionRange(version));
else
ranges.add(new SingleVersionRange(SingleVersion.valueOf(version)));
}
}
else
{
ranges.add(new SingleVersionRange(SingleVersion.valueOf(process))); // depends on control dependency: [if], data = [none]
}
}
return new MultipleVersionRange(ranges);
} } |
public class class_name {
private String checkPort(String uriAuthority)
throws URIException {
// Matcher m = PORTREGEX.matcher(uriAuthority);
Matcher m = TextUtils.getMatcher(PORTREGEX.pattern(), uriAuthority);
if (m.matches()) {
String no = m.group(2);
if (no != null && no.length() > 0) {
// First check if the port has leading zeros
// as in '0080'. Strip them if it has and
// then reconstitute the uriAuthority. Be careful
// of cases where port is '0' or '000'.
while (no.charAt(0) == '0' && no.length() > 1) {
no = no.substring(1);
}
uriAuthority = m.group(1) + no;
// Now makesure the number is legit.
int portNo = 0;
try {
portNo = Integer.parseInt(no);
} catch (NumberFormatException nfe) {
// just catch and leave portNo at illegal 0
}
if (portNo <= 0 || portNo > 65535) {
throw new URIException("Port out of bounds: " +
uriAuthority);
}
}
}
TextUtils.recycleMatcher(m);
return uriAuthority;
} } | public class class_name {
private String checkPort(String uriAuthority)
throws URIException {
// Matcher m = PORTREGEX.matcher(uriAuthority);
Matcher m = TextUtils.getMatcher(PORTREGEX.pattern(), uriAuthority);
if (m.matches()) {
String no = m.group(2);
if (no != null && no.length() > 0) {
// First check if the port has leading zeros
// as in '0080'. Strip them if it has and
// then reconstitute the uriAuthority. Be careful
// of cases where port is '0' or '000'.
while (no.charAt(0) == '0' && no.length() > 1) {
no = no.substring(1); // depends on control dependency: [while], data = [none]
}
uriAuthority = m.group(1) + no;
// Now makesure the number is legit.
int portNo = 0;
try {
portNo = Integer.parseInt(no); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException nfe) {
// just catch and leave portNo at illegal 0
} // depends on control dependency: [catch], data = [none]
if (portNo <= 0 || portNo > 65535) {
throw new URIException("Port out of bounds: " +
uriAuthority);
}
}
}
TextUtils.recycleMatcher(m);
return uriAuthority;
} } |
public class class_name {
private static boolean exemptedByAnnotation(
List<? extends AnnotationTree> annotations,
VisitorState state) {
for (AnnotationTree annotation : annotations) {
if (((JCAnnotation) annotation).type != null) {
TypeSymbol tsym = ((JCAnnotation) annotation).type.tsym;
if (EXEMPTING_METHOD_ANNOTATIONS.contains(tsym.getQualifiedName().toString())) {
return true;
}
}
}
return false;
} } | public class class_name {
private static boolean exemptedByAnnotation(
List<? extends AnnotationTree> annotations,
VisitorState state) {
for (AnnotationTree annotation : annotations) {
if (((JCAnnotation) annotation).type != null) {
TypeSymbol tsym = ((JCAnnotation) annotation).type.tsym;
if (EXEMPTING_METHOD_ANNOTATIONS.contains(tsym.getQualifiedName().toString())) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
public List<String> getUserGroups(final int userID)
throws WikiApiException
{
List<String> groups = new LinkedList<String>();
try {
if (userID < 1) {
throw new IllegalArgumentException();
}
if (!tableExists("user_groups")) {
throw new WikiInitializationException(
"User group assignment data is missing. Please download user_groups.sql for this Wikipedia from http://dumps.wikimedia.org and import the data into this database.");
}
PreparedStatement statement = null;
ResultSet result = null;
try {
statement = connection.prepareStatement("SELECT ug_group "
+ "FROM user_groups WHERE ug_user=?");
statement.setInt(1, userID);
result = statement.executeQuery();
// Make the query
if (result == null) {
throw new WikiPageNotFoundException("The user with the ID " + userID
+ " was not found.");
}
while (result.next()) {
groups.add(result.getString(1));
}
}
finally {
if (statement != null) {
statement.close();
}
if (result != null) {
result.close();
}
}
return groups;
}
catch (WikiApiException e) {
throw e;
}
catch (Exception e) {
throw new WikiApiException(e);
}
} } | public class class_name {
public List<String> getUserGroups(final int userID)
throws WikiApiException
{
List<String> groups = new LinkedList<String>();
try {
if (userID < 1) {
throw new IllegalArgumentException();
}
if (!tableExists("user_groups")) {
throw new WikiInitializationException(
"User group assignment data is missing. Please download user_groups.sql for this Wikipedia from http://dumps.wikimedia.org and import the data into this database.");
}
PreparedStatement statement = null;
ResultSet result = null;
try {
statement = connection.prepareStatement("SELECT ug_group "
+ "FROM user_groups WHERE ug_user=?"); // depends on control dependency: [try], data = [none]
statement.setInt(1, userID); // depends on control dependency: [try], data = [none]
result = statement.executeQuery(); // depends on control dependency: [try], data = [none]
// Make the query
if (result == null) {
throw new WikiPageNotFoundException("The user with the ID " + userID
+ " was not found.");
}
while (result.next()) {
groups.add(result.getString(1)); // depends on control dependency: [while], data = [none]
}
}
finally {
if (statement != null) {
statement.close(); // depends on control dependency: [if], data = [none]
}
if (result != null) {
result.close(); // depends on control dependency: [if], data = [none]
}
}
return groups; // depends on control dependency: [if], data = [none]
}
catch (WikiApiException e) {
throw e;
}
catch (Exception e) {
throw new WikiApiException(e);
}
} } |
public class class_name {
public JSType build() {
if (result == null) {
result = reduceAlternatesWithoutUnion();
if (result == null) {
result = new UnionType(registry, ImmutableList.copyOf(getAlternates()));
}
}
return result;
} } | public class class_name {
public JSType build() {
if (result == null) {
result = reduceAlternatesWithoutUnion(); // depends on control dependency: [if], data = [none]
if (result == null) {
result = new UnionType(registry, ImmutableList.copyOf(getAlternates())); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public static JMFType parse(String filename) {
try {
return parse(new FileReader(filename));
} catch(IOException e) {
// No FFDC needed
IllegalArgumentException ee = new IllegalArgumentException(e.getMessage());
ee.initCause(e);
throw ee;
}
} } | public class class_name {
public static JMFType parse(String filename) {
try {
return parse(new FileReader(filename)); // depends on control dependency: [try], data = [none]
} catch(IOException e) {
// No FFDC needed
IllegalArgumentException ee = new IllegalArgumentException(e.getMessage());
ee.initCause(e);
throw ee;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@SuppressWarnings("unchecked")
@Nonnull
public static <T> Optional<T> optionalInMessage(PMessage message, PField... fields) {
if (fields == null || fields.length == 0) {
throw new IllegalArgumentException("No fields arguments.");
}
PField field = fields[0];
if (!message.has(field.getId())) {
return Optional.empty();
}
if (fields.length > 1) {
if (field.getType() != PType.MESSAGE) {
throw new IllegalArgumentException("Field " + field.getName() + " is not a message.");
}
return optionalInMessage((PMessage) message.get(field), Arrays.copyOfRange(fields, 1, fields.length));
} else {
return Optional.of((T) message.get(field.getId()));
}
} } | public class class_name {
@SuppressWarnings("unchecked")
@Nonnull
public static <T> Optional<T> optionalInMessage(PMessage message, PField... fields) {
if (fields == null || fields.length == 0) {
throw new IllegalArgumentException("No fields arguments.");
}
PField field = fields[0];
if (!message.has(field.getId())) {
return Optional.empty(); // depends on control dependency: [if], data = [none]
}
if (fields.length > 1) {
if (field.getType() != PType.MESSAGE) {
throw new IllegalArgumentException("Field " + field.getName() + " is not a message.");
}
return optionalInMessage((PMessage) message.get(field), Arrays.copyOfRange(fields, 1, fields.length)); // depends on control dependency: [if], data = [none]
} else {
return Optional.of((T) message.get(field.getId())); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static void rcvReadSet(CommsByteBuffer request, Conversation conversation, int requestNumber,
boolean allocatedFromBufferPool, boolean partOfExchange)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "rcvReadSet",
new Object[]
{
request,
conversation,
"" + requestNumber,
"" + allocatedFromBufferPool
});
short connectionObjectId = request.getShort(); // BIT16 ConnectionObjectId
short consumerObjectId = request.getShort(); // BIT16 ConsumerSessionId
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "connectionObjectId", connectionObjectId);
SibTr.debug(tc, "consumerObjectId", consumerObjectId);
}
SIMessageHandle[] msgHandles = request.getSIMessageHandles();
CATMainConsumer mainConsumer =
(CATMainConsumer) ((ConversationState) conversation.getAttachment()).getObject(consumerObjectId);
mainConsumer.readSet(requestNumber, msgHandles);
request.release(allocatedFromBufferPool);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "rcvReadSet");
} } | public class class_name {
static void rcvReadSet(CommsByteBuffer request, Conversation conversation, int requestNumber,
boolean allocatedFromBufferPool, boolean partOfExchange)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "rcvReadSet",
new Object[]
{
request,
conversation,
"" + requestNumber,
"" + allocatedFromBufferPool
});
short connectionObjectId = request.getShort(); // BIT16 ConnectionObjectId
short consumerObjectId = request.getShort(); // BIT16 ConsumerSessionId
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "connectionObjectId", connectionObjectId); // depends on control dependency: [if], data = [none]
SibTr.debug(tc, "consumerObjectId", consumerObjectId); // depends on control dependency: [if], data = [none]
}
SIMessageHandle[] msgHandles = request.getSIMessageHandles();
CATMainConsumer mainConsumer =
(CATMainConsumer) ((ConversationState) conversation.getAttachment()).getObject(consumerObjectId);
mainConsumer.readSet(requestNumber, msgHandles);
request.release(allocatedFromBufferPool);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "rcvReadSet");
} } |
public class class_name {
private static void locateForMemcacheBucket(final BinaryRequest request, final List<Node> nodes,
final MemcachedBucketConfig config, CoreEnvironment env, RingBuffer<ResponseEvent> responseBuffer) {
if (!keyIsValid(request)) {
return;
}
NetworkAddress hostname = config.nodeForId(request.keyBytes());
request.partition((short) 0);
for (Node node : nodes) {
if (node.hostname().equals(hostname)) {
node.send(request);
return;
}
}
if(handleNotEqualNodeSizes(config.nodes().size(), nodes.size())) {
RetryHelper.retryOrCancel(env, request, responseBuffer);
return;
}
throw new IllegalStateException("Node not found for request" + request);
} } | public class class_name {
private static void locateForMemcacheBucket(final BinaryRequest request, final List<Node> nodes,
final MemcachedBucketConfig config, CoreEnvironment env, RingBuffer<ResponseEvent> responseBuffer) {
if (!keyIsValid(request)) {
return; // depends on control dependency: [if], data = [none]
}
NetworkAddress hostname = config.nodeForId(request.keyBytes());
request.partition((short) 0);
for (Node node : nodes) {
if (node.hostname().equals(hostname)) {
node.send(request); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
if(handleNotEqualNodeSizes(config.nodes().size(), nodes.size())) {
RetryHelper.retryOrCancel(env, request, responseBuffer); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
throw new IllegalStateException("Node not found for request" + request);
} } |
public class class_name {
private String getServerId() {
UUID fullServerId = null;
WsLocationAdmin locationService = this.wsLocationAdmin;
if (locationService != null) {
fullServerId = locationService.getServerId();
}
if (fullServerId == null) {
fullServerId = UUID.randomUUID(); // shouldn't get here, but be careful just in case
}
return fullServerId.toString().toLowerCase(); // clone IDs need to be in lower case for consistency with tWAS
} } | public class class_name {
private String getServerId() {
UUID fullServerId = null;
WsLocationAdmin locationService = this.wsLocationAdmin;
if (locationService != null) {
fullServerId = locationService.getServerId(); // depends on control dependency: [if], data = [none]
}
if (fullServerId == null) {
fullServerId = UUID.randomUUID(); // shouldn't get here, but be careful just in case // depends on control dependency: [if], data = [none]
}
return fullServerId.toString().toLowerCase(); // clone IDs need to be in lower case for consistency with tWAS
} } |
public class class_name {
@Override
public void go() {
logger.info("Waiting {} seconds for {}...", timeout, element);
WebDriverWait waiting = new WebDriverWait(getWebDriver(), timeout);
try {
waiting.until(ExpectedConditions.presenceOfElementLocated(element));
} catch (NullPointerException e) {
fail(String.format("Element %s did not appear within %d seconds.", element, timeout), e);
}
} } | public class class_name {
@Override
public void go() {
logger.info("Waiting {} seconds for {}...", timeout, element);
WebDriverWait waiting = new WebDriverWait(getWebDriver(), timeout);
try {
waiting.until(ExpectedConditions.presenceOfElementLocated(element)); // depends on control dependency: [try], data = [none]
} catch (NullPointerException e) {
fail(String.format("Element %s did not appear within %d seconds.", element, timeout), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public String getSingleValue(final String propertyName) {
Preconditions.checkNotNull(propertyName);
List<String> values = getValues(propertyName);
if (values == null || values.size() < 1) {
return null;
}
return values.get(0);
} } | public class class_name {
public String getSingleValue(final String propertyName) {
Preconditions.checkNotNull(propertyName);
List<String> values = getValues(propertyName);
if (values == null || values.size() < 1) {
return null; // depends on control dependency: [if], data = [none]
}
return values.get(0);
} } |
public class class_name {
private void disposeTasks(Collection<Runnable>... tasks) {
for (Collection<Runnable> task : tasks) {
for (Runnable runnable : task) {
if (runnable instanceof Disposable) {
((Disposable) runnable).dispose();
}
}
}
} } | public class class_name {
private void disposeTasks(Collection<Runnable>... tasks) {
for (Collection<Runnable> task : tasks) {
for (Runnable runnable : task) {
if (runnable instanceof Disposable) {
((Disposable) runnable).dispose(); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public List<MetadataDatabase> getMetadadaDatabasesSharedFolders(ResponseListNetworkSharedFolder responseNetworkSharedFolders){
//Init the list
List<MetadataDatabase> databases = new ArrayList<MetadataDatabase>();
if (null != responseNetworkSharedFolders){
for(ObjectNetworkShare networkShare : responseNetworkSharedFolders.getNetworkShares()){
try {
MetadataDatabase database = getDatabase(networkShare.getUrl());
databases.add(database);
logger.debug(database.toString());
} catch (TheDavidBoxClientException e) {
logger.warn("Not found metadata database for network share url: " + networkShare.getUrl());
}
}
}
return databases;
} } | public class class_name {
public List<MetadataDatabase> getMetadadaDatabasesSharedFolders(ResponseListNetworkSharedFolder responseNetworkSharedFolders){
//Init the list
List<MetadataDatabase> databases = new ArrayList<MetadataDatabase>();
if (null != responseNetworkSharedFolders){
for(ObjectNetworkShare networkShare : responseNetworkSharedFolders.getNetworkShares()){
try {
MetadataDatabase database = getDatabase(networkShare.getUrl());
databases.add(database);
// depends on control dependency: [try], data = [none]
logger.debug(database.toString());
// depends on control dependency: [try], data = [none]
} catch (TheDavidBoxClientException e) {
logger.warn("Not found metadata database for network share url: " + networkShare.getUrl());
}
// depends on control dependency: [catch], data = [none]
}
}
return databases;
} } |
public class class_name {
public static Element getAncestor(Element element, String className) {
if (hasClass(className, element)) {
return element;
}
if (element.getTagName().equalsIgnoreCase(Tag.body.name())) {
return null;
}
return getAncestor(element.getParentElement(), className);
} } | public class class_name {
public static Element getAncestor(Element element, String className) {
if (hasClass(className, element)) {
return element; // depends on control dependency: [if], data = [none]
}
if (element.getTagName().equalsIgnoreCase(Tag.body.name())) {
return null; // depends on control dependency: [if], data = [none]
}
return getAncestor(element.getParentElement(), className);
} } |
public class class_name {
public static double ioa(double[] obs, double[] sim, double pow) {
sameArrayLen(obs, sim);
int steps = sim.length;
double sum_obs = 0;
/**summing up both data sets */
for (int i = 0; i < steps; i++) {
sum_obs += obs[i];
}
/** calculating mean values for both data sets */
double mean_obs = sum_obs / steps;
/** calculating mean cubic deviations */
/** calculating absolute squared sum of deviations from verification mean */
double td_vd = 0;
double abs_sqDevi = 0;
for (int i = 0; i < steps; i++) {
td_vd += (Math.pow((Math.abs(obs[i] - sim[i])), pow));
abs_sqDevi += Math.pow(Math.abs(sim[i] - mean_obs) + Math.abs(obs[i] - mean_obs), pow);
}
return 1.0 - (td_vd / abs_sqDevi);
} } | public class class_name {
public static double ioa(double[] obs, double[] sim, double pow) {
sameArrayLen(obs, sim);
int steps = sim.length;
double sum_obs = 0;
/**summing up both data sets */
for (int i = 0; i < steps; i++) {
sum_obs += obs[i]; // depends on control dependency: [for], data = [i]
}
/** calculating mean values for both data sets */
double mean_obs = sum_obs / steps;
/** calculating mean cubic deviations */
/** calculating absolute squared sum of deviations from verification mean */
double td_vd = 0;
double abs_sqDevi = 0;
for (int i = 0; i < steps; i++) {
td_vd += (Math.pow((Math.abs(obs[i] - sim[i])), pow)); // depends on control dependency: [for], data = [i]
abs_sqDevi += Math.pow(Math.abs(sim[i] - mean_obs) + Math.abs(obs[i] - mean_obs), pow); // depends on control dependency: [for], data = [i]
}
return 1.0 - (td_vd / abs_sqDevi);
} } |
public class class_name {
public Node getNode(final int i) {
if (i < 0 || i >= nodeList.size()) {
return null;
}
return nodeList.get(i);
} } | public class class_name {
public Node getNode(final int i) {
if (i < 0 || i >= nodeList.size()) {
return null; // depends on control dependency: [if], data = [none]
}
return nodeList.get(i);
} } |
public class class_name {
public Stream<HString> findAllPatterns(@NonNull Pattern regex) {
return Streams.asStream(new Iterator<HString>() {
Matcher m = regex.matcher(HString.this);
int start = -1;
int end = -1;
private boolean advance() {
if (start == -1) {
if (m.find()) {
start = m.start();
end = m.end();
}
}
return start != -1;
}
@Override
public boolean hasNext() {
return advance();
}
@Override
public HString next() {
if (!advance()) {
throw new NoSuchElementException();
}
HString sub = substring(start, end);
start = -1;
end = -1;
//If we have tokens expand the match to the overlaping tokens.
if (document() != null && document().isCompleted(Types.TOKEN)) {
return union(sub.tokens());
}
return sub;
}
});
} } | public class class_name {
public Stream<HString> findAllPatterns(@NonNull Pattern regex) {
return Streams.asStream(new Iterator<HString>() {
Matcher m = regex.matcher(HString.this);
int start = -1;
int end = -1;
private boolean advance() {
if (start == -1) {
if (m.find()) {
start = m.start(); // depends on control dependency: [if], data = [none]
end = m.end(); // depends on control dependency: [if], data = [none]
}
}
return start != -1;
}
@Override
public boolean hasNext() {
return advance();
}
@Override
public HString next() {
if (!advance()) {
throw new NoSuchElementException();
}
HString sub = substring(start, end);
start = -1;
end = -1;
//If we have tokens expand the match to the overlaping tokens.
if (document() != null && document().isCompleted(Types.TOKEN)) {
return union(sub.tokens()); // depends on control dependency: [if], data = [none]
}
return sub;
}
});
} } |
public class class_name {
public static int recursiveDelete(File file) {
int answer = 0;
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
answer += recursiveDelete(child);
}
}
}
if (file.delete()) {
answer += 1;
}
return answer;
} } | public class class_name {
public static int recursiveDelete(File file) {
int answer = 0;
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
answer += recursiveDelete(child); // depends on control dependency: [for], data = [child]
}
}
}
if (file.delete()) {
answer += 1; // depends on control dependency: [if], data = [none]
}
return answer;
} } |
public class class_name {
public static base_responses update(nitro_service client, snmpalarm resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
snmpalarm updateresources[] = new snmpalarm[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new snmpalarm();
updateresources[i].trapname = resources[i].trapname;
updateresources[i].thresholdvalue = resources[i].thresholdvalue;
updateresources[i].normalvalue = resources[i].normalvalue;
updateresources[i].time = resources[i].time;
updateresources[i].state = resources[i].state;
updateresources[i].severity = resources[i].severity;
updateresources[i].logging = resources[i].logging;
}
result = update_bulk_request(client, updateresources);
}
return result;
} } | public class class_name {
public static base_responses update(nitro_service client, snmpalarm resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
snmpalarm updateresources[] = new snmpalarm[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new snmpalarm(); // depends on control dependency: [for], data = [i]
updateresources[i].trapname = resources[i].trapname; // depends on control dependency: [for], data = [i]
updateresources[i].thresholdvalue = resources[i].thresholdvalue; // depends on control dependency: [for], data = [i]
updateresources[i].normalvalue = resources[i].normalvalue; // depends on control dependency: [for], data = [i]
updateresources[i].time = resources[i].time; // depends on control dependency: [for], data = [i]
updateresources[i].state = resources[i].state; // depends on control dependency: [for], data = [i]
updateresources[i].severity = resources[i].severity; // depends on control dependency: [for], data = [i]
updateresources[i].logging = resources[i].logging; // depends on control dependency: [for], data = [i]
}
result = update_bulk_request(client, updateresources);
}
return result;
} } |
public class class_name {
WrappedByteBuffer expandAt(int i, int expectedRemaining) {
if ((i + expectedRemaining) <= _buf.limit()) {
return this;
} else {
if ((i + expectedRemaining) <= _buf.capacity()) {
_buf.limit(i + expectedRemaining);
} else {
// reallocate the underlying byte buffer and keep the original buffer
// intact. The resetting of the position is required because, one
// could be in the middle of a read of an existing buffer, when they
// decide to over write only few bytes but still keep the remaining
// part of the buffer unchanged.
int newCapacity = _buf.capacity()
+ ((expectedRemaining > INITIAL_CAPACITY) ? expectedRemaining : INITIAL_CAPACITY);
java.nio.ByteBuffer newBuffer = java.nio.ByteBuffer.allocate(newCapacity);
_buf.flip();
newBuffer.put(_buf);
_buf = newBuffer;
}
}
return this;
} } | public class class_name {
WrappedByteBuffer expandAt(int i, int expectedRemaining) {
if ((i + expectedRemaining) <= _buf.limit()) {
return this; // depends on control dependency: [if], data = [none]
} else {
if ((i + expectedRemaining) <= _buf.capacity()) {
_buf.limit(i + expectedRemaining); // depends on control dependency: [if], data = [none]
} else {
// reallocate the underlying byte buffer and keep the original buffer
// intact. The resetting of the position is required because, one
// could be in the middle of a read of an existing buffer, when they
// decide to over write only few bytes but still keep the remaining
// part of the buffer unchanged.
int newCapacity = _buf.capacity()
+ ((expectedRemaining > INITIAL_CAPACITY) ? expectedRemaining : INITIAL_CAPACITY);
java.nio.ByteBuffer newBuffer = java.nio.ByteBuffer.allocate(newCapacity);
_buf.flip(); // depends on control dependency: [if], data = [none]
newBuffer.put(_buf); // depends on control dependency: [if], data = [none]
_buf = newBuffer; // depends on control dependency: [if], data = [none]
}
}
return this;
} } |
public class class_name {
public void severe(String format, Object... args)
{
if (isLoggable(SEVERE))
{
logIt(SEVERE, String.format(format, args));
}
} } | public class class_name {
public void severe(String format, Object... args)
{
if (isLoggable(SEVERE))
{
logIt(SEVERE, String.format(format, args));
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void processDocument(BufferedReader document, Wordsi wordsi) {
try {
// Handle the context header, if one exists. Context headers are
// assumed to be the first line in a document and to contain an
// integer specifying which line the focus word is on..
String contextHeader = handleContextHeader(document);
String[] contextTokens = contextHeader.split("\\s+");
int focusIndex = Integer.parseInt(contextTokens[3]);
// Extract the dependency trees and skip any that are empty.
DependencyTreeNode[] nodes = extractor.readNextTree(document);
if (nodes.length == 0)
return;
DependencyTreeNode focusNode = nodes[focusIndex];
// Get the focus word, i.e., the primary key, and the secondary key.
String focusWord = getPrimaryKey(focusNode);
String secondarykey = pseudoWordMap.get(focusWord);
// Ignore any focus words that have no mapping.
if (secondarykey == null)
return;
// Ignore any focus words that are unaccepted by Wordsi.
if (!acceptWord(focusNode, contextTokens[1], wordsi))
return;
// Create a new context vector and send it to the Wordsi model.
SparseDoubleVector focusMeaning = generator.generateContext(
nodes, focusIndex);
wordsi.handleContextVector(secondarykey, focusWord, focusMeaning);
// Close up the document.
document.close();
} catch (IOException ioe) {
throw new IOError(ioe);
}
} } | public class class_name {
public void processDocument(BufferedReader document, Wordsi wordsi) {
try {
// Handle the context header, if one exists. Context headers are
// assumed to be the first line in a document and to contain an
// integer specifying which line the focus word is on..
String contextHeader = handleContextHeader(document);
String[] contextTokens = contextHeader.split("\\s+");
int focusIndex = Integer.parseInt(contextTokens[3]);
// Extract the dependency trees and skip any that are empty.
DependencyTreeNode[] nodes = extractor.readNextTree(document);
if (nodes.length == 0)
return;
DependencyTreeNode focusNode = nodes[focusIndex];
// Get the focus word, i.e., the primary key, and the secondary key.
String focusWord = getPrimaryKey(focusNode);
String secondarykey = pseudoWordMap.get(focusWord);
// Ignore any focus words that have no mapping.
if (secondarykey == null)
return;
// Ignore any focus words that are unaccepted by Wordsi.
if (!acceptWord(focusNode, contextTokens[1], wordsi))
return;
// Create a new context vector and send it to the Wordsi model.
SparseDoubleVector focusMeaning = generator.generateContext(
nodes, focusIndex);
wordsi.handleContextVector(secondarykey, focusWord, focusMeaning); // depends on control dependency: [try], data = [none]
// Close up the document.
document.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
throw new IOError(ioe);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public boolean deleteExisting(final File file) {
if (!file.exists()) {
return true;
}
boolean deleted = false;
if (file.canWrite()) {
deleted = file.delete();
} else {
LogLog.debug(file + " is not writeable for delete (retrying)");
}
if (!deleted) {
if (!file.exists()) {
deleted = true;
} else {
file.delete();
deleted = (!file.exists());
}
}
return deleted;
} } | public class class_name {
public boolean deleteExisting(final File file) {
if (!file.exists()) {
return true; // depends on control dependency: [if], data = [none]
}
boolean deleted = false;
if (file.canWrite()) {
deleted = file.delete(); // depends on control dependency: [if], data = [none]
} else {
LogLog.debug(file + " is not writeable for delete (retrying)");
}
if (!deleted) {
if (!file.exists()) {
deleted = true; // depends on control dependency: [if], data = [none]
} else {
file.delete();
deleted = (!file.exists());
}
}
return deleted;
} } |
public class class_name {
public void close() throws IOException
{
if (!this.closed)
{
this.closed = true;
this.is.close();
this.dataIn.close();
this.is = null;
this.dataIn = null;
int typeCount = 0;
if (this.resourceTypeTable != null)
{ // fix for bug 32320
for (int i = 0; i < this.resourceTypeTable.length; i++)
{
if (this.resourceTypeTable[i] != null)
{
if (this.resourceTypeTable[i].close())
{
this.resourceTypeTable[i] = null;
}
else
{
typeCount++;
}
}
}
ResourceType[] newTypeTable = new ResourceType[typeCount];
typeCount = 0;
for (ResourceType aResourceTypeTable : this.resourceTypeTable)
{
if (aResourceTypeTable != null)
{
newTypeTable[typeCount] = aResourceTypeTable;
typeCount++;
}
}
this.resourceTypeTable = newTypeTable;
}
if (this.resourceInstTable != null)
{ // fix for bug 32320
int instCount = 0;
for (int i = 0; i < this.resourceInstTable.length; i++)
{
if (this.resourceInstTable[i] != null)
{
if (this.resourceInstTable[i].close())
{
this.resourceInstTable[i] = null;
}
else
{
instCount++;
}
}
}
ResourceInst[] newInstTable = new ResourceInst[instCount];
instCount = 0;
for (ResourceInst aResourceInstTable : this.resourceInstTable)
{
if (aResourceInstTable != null)
{
newInstTable[instCount] = aResourceInstTable;
instCount++;
}
}
this.resourceInstTable = newInstTable;
this.resourceInstSize = instCount;
}
// optimize memory usage of timeSeries now that no more samples
this.timeSeries.shrink();
// filters are no longer needed since file will not be read from
this.filters = null;
}
} } | public class class_name {
public void close() throws IOException
{
if (!this.closed)
{
this.closed = true;
this.is.close();
this.dataIn.close();
this.is = null;
this.dataIn = null;
int typeCount = 0;
if (this.resourceTypeTable != null)
{ // fix for bug 32320
for (int i = 0; i < this.resourceTypeTable.length; i++)
{
if (this.resourceTypeTable[i] != null)
{
if (this.resourceTypeTable[i].close())
{
this.resourceTypeTable[i] = null; // depends on control dependency: [if], data = [none]
}
else
{
typeCount++; // depends on control dependency: [if], data = [none]
}
}
}
ResourceType[] newTypeTable = new ResourceType[typeCount];
typeCount = 0;
for (ResourceType aResourceTypeTable : this.resourceTypeTable)
{
if (aResourceTypeTable != null)
{
newTypeTable[typeCount] = aResourceTypeTable; // depends on control dependency: [if], data = [none]
typeCount++; // depends on control dependency: [if], data = [none]
}
}
this.resourceTypeTable = newTypeTable;
}
if (this.resourceInstTable != null)
{ // fix for bug 32320
int instCount = 0;
for (int i = 0; i < this.resourceInstTable.length; i++)
{
if (this.resourceInstTable[i] != null)
{
if (this.resourceInstTable[i].close())
{
this.resourceInstTable[i] = null;
}
else
{
instCount++;
}
}
}
ResourceInst[] newInstTable = new ResourceInst[instCount];
instCount = 0;
for (ResourceInst aResourceInstTable : this.resourceInstTable)
{
if (aResourceInstTable != null)
{
newInstTable[instCount] = aResourceInstTable;
instCount++;
}
}
this.resourceInstTable = newInstTable;
this.resourceInstSize = instCount;
}
// optimize memory usage of timeSeries now that no more samples
this.timeSeries.shrink();
// filters are no longer needed since file will not be read from
this.filters = null;
}
} } |
public class class_name {
public void marshall(DeleteDataSourceRequest deleteDataSourceRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteDataSourceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteDataSourceRequest.getApiId(), APIID_BINDING);
protocolMarshaller.marshall(deleteDataSourceRequest.getName(), NAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeleteDataSourceRequest deleteDataSourceRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteDataSourceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteDataSourceRequest.getApiId(), APIID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deleteDataSourceRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public double[] projectDataToScaledSpace(NumberVector data) {
final int dim = data.getDimensionality();
double[] vec = new double[dim];
for(int d = 0; d < dim; d++) {
vec[d] = scales[d].getScaled(data.doubleValue(d));
}
return vec;
} } | public class class_name {
@Override
public double[] projectDataToScaledSpace(NumberVector data) {
final int dim = data.getDimensionality();
double[] vec = new double[dim];
for(int d = 0; d < dim; d++) {
vec[d] = scales[d].getScaled(data.doubleValue(d)); // depends on control dependency: [for], data = [d]
}
return vec;
} } |
public class class_name {
public void setSigmaSquared(double sigmaSq) {
if (type == LogPriorType.ADAPT) { otherPrior.setSigmaSquared(sigmaSq); }
else {
// this.sigma = Math.sqrt(sigmaSq);
this.sigmaSq = sigmaSq;
this.sigmaQu = sigmaSq * sigmaSq;
}
} } | public class class_name {
public void setSigmaSquared(double sigmaSq) {
if (type == LogPriorType.ADAPT) { otherPrior.setSigmaSquared(sigmaSq); }
// depends on control dependency: [if], data = [none]
else {
// this.sigma = Math.sqrt(sigmaSq);
this.sigmaSq = sigmaSq;
// depends on control dependency: [if], data = [none]
this.sigmaQu = sigmaSq * sigmaSq;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void read(InputStream is) throws IOException {
// Buffered input stream for reading manifest data
FastInputStream fis = new FastInputStream(is);
// Line buffer
byte[] lbuf = new byte[512];
// Read the main attributes for the manifest
attr.read(fis, lbuf);
// Total number of entries, attributes read
int ecount = 0, acount = 0;
// Average size of entry attributes
int asize = 2;
// Now parse the manifest entries
int len;
String name = null;
boolean skipEmptyLines = true;
byte[] lastline = null;
while ((len = fis.readLine(lbuf)) != -1) {
if (lbuf[--len] != '\n') {
throw new IOException("manifest line too long");
}
if (len > 0 && lbuf[len-1] == '\r') {
--len;
}
if (len == 0 && skipEmptyLines) {
continue;
}
skipEmptyLines = false;
if (name == null) {
name = parseName(lbuf, len);
if (name == null) {
throw new IOException("invalid manifest format");
}
if (fis.peek() == ' ') {
// name is wrapped
lastline = new byte[len - 6];
System.arraycopy(lbuf, 6, lastline, 0, len - 6);
continue;
}
} else {
// continuation line
byte[] buf = new byte[lastline.length + len - 1];
System.arraycopy(lastline, 0, buf, 0, lastline.length);
System.arraycopy(lbuf, 1, buf, lastline.length, len - 1);
if (fis.peek() == ' ') {
// name is wrapped
lastline = buf;
continue;
}
name = new String(buf, 0, buf.length, "UTF8");
lastline = null;
}
Attributes attr = getAttributes(name);
if (attr == null) {
attr = new Attributes(asize);
entries.put(name, attr);
}
attr.read(fis, lbuf);
ecount++;
acount += attr.size();
//XXX: Fix for when the average is 0. When it is 0,
// you get an Attributes object with an initial
// capacity of 0, which tickles a bug in HashMap.
asize = Math.max(2, acount / ecount);
name = null;
skipEmptyLines = true;
}
} } | public class class_name {
public void read(InputStream is) throws IOException {
// Buffered input stream for reading manifest data
FastInputStream fis = new FastInputStream(is);
// Line buffer
byte[] lbuf = new byte[512];
// Read the main attributes for the manifest
attr.read(fis, lbuf);
// Total number of entries, attributes read
int ecount = 0, acount = 0;
// Average size of entry attributes
int asize = 2;
// Now parse the manifest entries
int len;
String name = null;
boolean skipEmptyLines = true;
byte[] lastline = null;
while ((len = fis.readLine(lbuf)) != -1) {
if (lbuf[--len] != '\n') {
throw new IOException("manifest line too long");
}
if (len > 0 && lbuf[len-1] == '\r') {
--len; // depends on control dependency: [if], data = [none]
}
if (len == 0 && skipEmptyLines) {
continue;
}
skipEmptyLines = false;
if (name == null) {
name = parseName(lbuf, len); // depends on control dependency: [if], data = [none]
if (name == null) {
throw new IOException("invalid manifest format");
}
if (fis.peek() == ' ') {
// name is wrapped
lastline = new byte[len - 6]; // depends on control dependency: [if], data = [none]
System.arraycopy(lbuf, 6, lastline, 0, len - 6); // depends on control dependency: [if], data = [none]
continue;
}
} else {
// continuation line
byte[] buf = new byte[lastline.length + len - 1];
System.arraycopy(lastline, 0, buf, 0, lastline.length); // depends on control dependency: [if], data = [none]
System.arraycopy(lbuf, 1, buf, lastline.length, len - 1); // depends on control dependency: [if], data = [none]
if (fis.peek() == ' ') {
// name is wrapped
lastline = buf; // depends on control dependency: [if], data = [none]
continue;
}
name = new String(buf, 0, buf.length, "UTF8"); // depends on control dependency: [if], data = [none]
lastline = null; // depends on control dependency: [if], data = [none]
}
Attributes attr = getAttributes(name);
if (attr == null) {
attr = new Attributes(asize); // depends on control dependency: [if], data = [none]
entries.put(name, attr); // depends on control dependency: [if], data = [none]
}
attr.read(fis, lbuf);
ecount++;
acount += attr.size();
//XXX: Fix for when the average is 0. When it is 0,
// you get an Attributes object with an initial
// capacity of 0, which tickles a bug in HashMap.
asize = Math.max(2, acount / ecount);
name = null;
skipEmptyLines = true;
}
} } |
public class class_name {
@Override
public boolean modelBuilderClassGenerated(TopLevelClass topLevelClass, InnerClass builderClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
if (this.support()) {
if (this.incEnum == null) {
this.incEnum = this.generatedIncEnum(introspectedTable);
this.incEnumBuilder = builderClass;
// 增加枚举
builderClass.addInnerEnum(this.incEnum);
// topLevel class 添加必要的操作方法
this.addIncMethodToTopLevelClass(topLevelClass, builderClass, introspectedTable, false);
}
// Builder 中 添加字段支持
for (IntrospectedColumn column : columns) {
if (this.supportColumn(column)) {
Field field = JavaBeansUtil.getJavaBeansField(column, context, introspectedTable);
// 增加方法
Method mIncrements = JavaElementGeneratorTools.generateMethod(
field.getName(),
JavaVisibility.PUBLIC,
builderClass.getType(),
new Parameter(field.getType(), field.getName()),
new Parameter(this.getIncEnum(builderClass, introspectedTable), "inc")
);
commentGenerator.addSetterComment(mIncrements, introspectedTable, column);
Method setterMethod = JavaBeansUtil.getJavaBeansSetter(column, context, introspectedTable);
mIncrements.addBodyLine("obj." + IncrementsPlugin.FIELD_INC_MAP + ".put(\"" + column.getActualColumnName() + "\", inc);");
mIncrements.addBodyLine("obj." + setterMethod.getName() + "(" + field.getName() + ");");
mIncrements.addBodyLine("return this;");
FormatTools.addMethodWithBestPosition(builderClass, mIncrements);
}
}
}
return true;
} } | public class class_name {
@Override
public boolean modelBuilderClassGenerated(TopLevelClass topLevelClass, InnerClass builderClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
if (this.support()) {
if (this.incEnum == null) {
this.incEnum = this.generatedIncEnum(introspectedTable); // depends on control dependency: [if], data = [none]
this.incEnumBuilder = builderClass; // depends on control dependency: [if], data = [none]
// 增加枚举
builderClass.addInnerEnum(this.incEnum); // depends on control dependency: [if], data = [(this.incEnum]
// topLevel class 添加必要的操作方法
this.addIncMethodToTopLevelClass(topLevelClass, builderClass, introspectedTable, false); // depends on control dependency: [if], data = [none]
}
// Builder 中 添加字段支持
for (IntrospectedColumn column : columns) {
if (this.supportColumn(column)) {
Field field = JavaBeansUtil.getJavaBeansField(column, context, introspectedTable);
// 增加方法
Method mIncrements = JavaElementGeneratorTools.generateMethod(
field.getName(),
JavaVisibility.PUBLIC,
builderClass.getType(),
new Parameter(field.getType(), field.getName()),
new Parameter(this.getIncEnum(builderClass, introspectedTable), "inc")
);
commentGenerator.addSetterComment(mIncrements, introspectedTable, column); // depends on control dependency: [if], data = [none]
Method setterMethod = JavaBeansUtil.getJavaBeansSetter(column, context, introspectedTable);
mIncrements.addBodyLine("obj." + IncrementsPlugin.FIELD_INC_MAP + ".put(\"" + column.getActualColumnName() + "\", inc);"); // depends on control dependency: [if], data = [none]
mIncrements.addBodyLine("obj." + setterMethod.getName() + "(" + field.getName() + ");");
mIncrements.addBodyLine("return this;");
FormatTools.addMethodWithBestPosition(builderClass, mIncrements); // depends on control dependency: [if], data = [none]
}
}
}
return true;
} } |
public class class_name {
public boolean smoothPath (PathSmootherRequest<N, V> request, long timeToRun) {
long lastTime = TimeUtils.nanoTime();
SmoothableGraphPath<N, V> path = request.path;
int inputPathLength = path.getCount();
// If the path is two nodes long or less, then we can't smooth it
if (inputPathLength <= 2) return true;
if (request.isNew) {
request.isNew = false;
// Make sure the ray is instantiated
if (this.ray == null) {
V vec = request.path.getNodePosition(0);
this.ray = new Ray<V>(vec.cpy(), vec.cpy());
}
// Keep track of where we are in the smoothed path.
// We start at 1, because we must always include the start node in the smoothed path.
request.outputIndex = 1;
// Keep track of where we are in the input path
// We start at 2, because we assume two adjacent
// nodes will pass the ray cast
request.inputIndex = 2;
}
// Loop until we find the last item in the input
while (request.inputIndex < inputPathLength) {
// Check the available time
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
if (timeToRun <= PathFinderQueue.TIME_TOLERANCE) return false;
// Set the ray
ray.start.set(path.getNodePosition(request.outputIndex - 1));
ray.end.set(path.getNodePosition(request.inputIndex));
// Do the ray cast
boolean collided = raycastCollisionDetector.collides(ray);
if (collided) {
// The ray test failed, swap nodes and consider the next output node
path.swapNodes(request.outputIndex, request.inputIndex - 1);
request.outputIndex++;
}
// Consider the next input node
request.inputIndex++;
// Store the current time
lastTime = currentTime;
}
// Reached the last input node, always add it to the smoothed path
path.swapNodes(request.outputIndex, request.inputIndex - 1);
path.truncatePath(request.outputIndex + 1);
// Smooth completed
return true;
} } | public class class_name {
public boolean smoothPath (PathSmootherRequest<N, V> request, long timeToRun) {
long lastTime = TimeUtils.nanoTime();
SmoothableGraphPath<N, V> path = request.path;
int inputPathLength = path.getCount();
// If the path is two nodes long or less, then we can't smooth it
if (inputPathLength <= 2) return true;
if (request.isNew) {
request.isNew = false; // depends on control dependency: [if], data = [none]
// Make sure the ray is instantiated
if (this.ray == null) {
V vec = request.path.getNodePosition(0);
this.ray = new Ray<V>(vec.cpy(), vec.cpy()); // depends on control dependency: [if], data = [none]
}
// Keep track of where we are in the smoothed path.
// We start at 1, because we must always include the start node in the smoothed path.
request.outputIndex = 1; // depends on control dependency: [if], data = [none]
// Keep track of where we are in the input path
// We start at 2, because we assume two adjacent
// nodes will pass the ray cast
request.inputIndex = 2; // depends on control dependency: [if], data = [none]
}
// Loop until we find the last item in the input
while (request.inputIndex < inputPathLength) {
// Check the available time
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime; // depends on control dependency: [while], data = [none]
if (timeToRun <= PathFinderQueue.TIME_TOLERANCE) return false;
// Set the ray
ray.start.set(path.getNodePosition(request.outputIndex - 1)); // depends on control dependency: [while], data = [none]
ray.end.set(path.getNodePosition(request.inputIndex)); // depends on control dependency: [while], data = [(request.inputIndex]
// Do the ray cast
boolean collided = raycastCollisionDetector.collides(ray);
if (collided) {
// The ray test failed, swap nodes and consider the next output node
path.swapNodes(request.outputIndex, request.inputIndex - 1); // depends on control dependency: [if], data = [none]
request.outputIndex++; // depends on control dependency: [if], data = [none]
}
// Consider the next input node
request.inputIndex++; // depends on control dependency: [while], data = [none]
// Store the current time
lastTime = currentTime; // depends on control dependency: [while], data = [none]
}
// Reached the last input node, always add it to the smoothed path
path.swapNodes(request.outputIndex, request.inputIndex - 1);
path.truncatePath(request.outputIndex + 1);
// Smooth completed
return true;
} } |
public class class_name {
@Deprecated
public static String encodeHex(byte[] data, char delimiter) {
// the result
StringBuilder result = new StringBuilder();
short val = 0;
// encode each byte into a hex dump
for (int i = 0; i < data.length; i++) {
val = decodeUnsigned(data[i]);
result.append(padLeading(Integer.toHexString((int) val), 2));
result.append(delimiter);
}
// return encoded text
return result.toString();
} } | public class class_name {
@Deprecated
public static String encodeHex(byte[] data, char delimiter) {
// the result
StringBuilder result = new StringBuilder();
short val = 0;
// encode each byte into a hex dump
for (int i = 0; i < data.length; i++) {
val = decodeUnsigned(data[i]); // depends on control dependency: [for], data = [i]
result.append(padLeading(Integer.toHexString((int) val), 2)); // depends on control dependency: [for], data = [none]
result.append(delimiter); // depends on control dependency: [for], data = [none]
}
// return encoded text
return result.toString();
} } |
public class class_name {
private WroManagerFactory createWroManagerFactory() {
if (wroManagerFactory == null) {
final WroManagerFactory managerFactoryAttribute = ServletContextAttributeHelper.create(filterConfig)
.getManagerFactory();
LOG.debug("managerFactory attribute: {}", managerFactoryAttribute);
wroManagerFactory = managerFactoryAttribute != null ? managerFactoryAttribute : newWroManagerFactory();
}
LOG.debug("created managerFactory: {}", wroManagerFactory);
return wroManagerFactory;
} } | public class class_name {
private WroManagerFactory createWroManagerFactory() {
if (wroManagerFactory == null) {
final WroManagerFactory managerFactoryAttribute = ServletContextAttributeHelper.create(filterConfig)
.getManagerFactory();
LOG.debug("managerFactory attribute: {}", managerFactoryAttribute); // depends on control dependency: [if], data = [none]
wroManagerFactory = managerFactoryAttribute != null ? managerFactoryAttribute : newWroManagerFactory(); // depends on control dependency: [if], data = [none]
}
LOG.debug("created managerFactory: {}", wroManagerFactory);
return wroManagerFactory;
} } |
public class class_name {
public void setZoomManager(ZoomManager manager) {
if ( zoomManager != null ) {
zoomManager.removeZoomListener( this );
}
zoomManager = manager;
if ( zoomManager != null ) {
zoomManager.addZoomListener( this );
}
} } | public class class_name {
public void setZoomManager(ZoomManager manager) {
if ( zoomManager != null ) {
zoomManager.removeZoomListener( this ); // depends on control dependency: [if], data = [none]
}
zoomManager = manager;
if ( zoomManager != null ) {
zoomManager.addZoomListener( this ); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setChainEventListeners(Set<ChainEventListener> newListeners) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(this, tc, "removeAllChainEventListeners", newListeners);
}
chainEventListeners.clear();
chainEventListeners.addAll(newListeners);
} } | public class class_name {
public void setChainEventListeners(Set<ChainEventListener> newListeners) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(this, tc, "removeAllChainEventListeners", newListeners); // depends on control dependency: [if], data = [none]
}
chainEventListeners.clear();
chainEventListeners.addAll(newListeners);
} } |
public class class_name {
public VariantAvroFilters addFilter(boolean mustPassAll, boolean acceptNull, String... filters) {
List<Predicate<Variant>> filtersList = new ArrayList<>(filters.length);
for (String filter : filters) {
String[] keyOpValue = splitOperator(filter);
String[] typeKey = keyOpValue[0].split(":");
String type;
String key;
if (typeKey.length == 1) {
if (typeKey[0].equals(FILTER) || typeKey[0].equals(QUAL)) {
type = "FILE";
key = typeKey[0];
} else {
throw new IllegalArgumentException("");
}
} else {
type = typeKey[0];
key = typeKey[1];
}
String op = keyOpValue[1];
String value = keyOpValue[2];
Predicate<String> predicate;
switch (type) {
case "FORMAT":
predicate = buildPredicate(op, value, acceptNull);
filtersList.add(v -> filterSampleFormat(v, key, true, predicate));
break;
case "INFO":
case "FILE":
if (key.equals(FILTER)) {
if (op.equals("=") || op.equals("!=") || op.equals("==")) {
boolean containsFilter;
if (value.startsWith("!") || op.equals("!=")) {
value = value.replace("!", "");
containsFilter = false;
} else {
containsFilter = true;
}
Set<String> values;
if (value.contains(",") || acceptNull) {
values = new HashSet<>(Arrays.asList(value.split(",")));
if (acceptNull) {
values.add(null);
}
} else {
values = Collections.singleton(value);
}
predicate = filterValue -> {
for (String v : filterValue.split(VCFConstants.FILTER_CODE_SEPARATOR)) {
if (values.contains(v)) {
return containsFilter;
}
}
return !containsFilter;
};
} else {
throw new IllegalArgumentException("Invalid operator " + op + " for FILE:FILTER");
}
} else {
predicate = buildPredicate(op, value, acceptNull);
}
filtersList.add(v -> filterFileAttribute(v, key, predicate));
break;
default:
throw new IllegalArgumentException("unknown " + type);
}
}
addFilterList(filtersList, !mustPassAll);
return this;
} } | public class class_name {
public VariantAvroFilters addFilter(boolean mustPassAll, boolean acceptNull, String... filters) {
List<Predicate<Variant>> filtersList = new ArrayList<>(filters.length);
for (String filter : filters) {
String[] keyOpValue = splitOperator(filter);
String[] typeKey = keyOpValue[0].split(":");
String type;
String key;
if (typeKey.length == 1) {
if (typeKey[0].equals(FILTER) || typeKey[0].equals(QUAL)) {
type = "FILE"; // depends on control dependency: [if], data = [none]
key = typeKey[0]; // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("");
}
} else {
type = typeKey[0]; // depends on control dependency: [if], data = [none]
key = typeKey[1]; // depends on control dependency: [if], data = [none]
}
String op = keyOpValue[1];
String value = keyOpValue[2];
Predicate<String> predicate;
switch (type) {
case "FORMAT":
predicate = buildPredicate(op, value, acceptNull);
filtersList.add(v -> filterSampleFormat(v, key, true, predicate));
break;
case "INFO":
case "FILE":
if (key.equals(FILTER)) {
if (op.equals("=") || op.equals("!=") || op.equals("==")) {
boolean containsFilter;
if (value.startsWith("!") || op.equals("!=")) {
value = value.replace("!", ""); // depends on control dependency: [if], data = [")]
containsFilter = false; // depends on control dependency: [if], data = [none]
} else {
containsFilter = true; // depends on control dependency: [if], data = [none]
}
Set<String> values;
if (value.contains(",") || acceptNull) {
values = new HashSet<>(Arrays.asList(value.split(","))); // depends on control dependency: [if], data = [none]
if (acceptNull) {
values.add(null); // depends on control dependency: [if], data = [none]
}
} else {
values = Collections.singleton(value); // depends on control dependency: [if], data = [none]
}
predicate = filterValue -> {
for (String v : filterValue.split(VCFConstants.FILTER_CODE_SEPARATOR)) { // depends on control dependency: [if], data = [none]
if (values.contains(v)) {
return containsFilter; // depends on control dependency: [if], data = [none]
}
}
return !containsFilter; // depends on control dependency: [if], data = [none]
};
} else {
throw new IllegalArgumentException("Invalid operator " + op + " for FILE:FILTER");
}
} else {
predicate = buildPredicate(op, value, acceptNull);
}
filtersList.add(v -> filterFileAttribute(v, key, predicate));
break;
default:
throw new IllegalArgumentException("unknown " + type);
}
}
addFilterList(filtersList, !mustPassAll);
return this;
} } |
public class class_name {
public ContactResources contactResources() {
if (contacts.get() == null) {
contacts.compareAndSet(null, new ContactResourcesImpl(this));
}
return contacts.get();
} } | public class class_name {
public ContactResources contactResources() {
if (contacts.get() == null) {
contacts.compareAndSet(null, new ContactResourcesImpl(this)); // depends on control dependency: [if], data = [none]
}
return contacts.get();
} } |
public class class_name {
@Override
public boolean containsKey(Object key)
{
if (key == null) {
return false;
}
K []keys = _keys;
for (int i = _size - 1 ; i >= 0; i--) {
K testKey = keys[i];
if (key.equals(testKey)) {
return true;
}
}
return false;
} } | public class class_name {
@Override
public boolean containsKey(Object key)
{
if (key == null) {
return false; // depends on control dependency: [if], data = [none]
}
K []keys = _keys;
for (int i = _size - 1 ; i >= 0; i--) {
K testKey = keys[i];
if (key.equals(testKey)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public boolean isSimple() {
if (isEmpty()) {
return true;
}
if (getNumGeometries() > 1) {
for (int n = 0; n < getNumGeometries(); n++) {
if (!getGeometryN(n).isSimple()) {
return false;
}
}
} else {
final Coordinate[] coords1 = getCoordinates();
final Coordinate[] coords2 = getCoordinates();
if (coords1.length > 1 && coords2.length > 1) {
for (int i = 0; i < coords2.length - 1; i++) {
for (int j = 0; j < coords1.length - 1; j++) {
if (Mathlib.lineIntersects(coords2[i], coords2[i + 1], coords1[j], coords1[j + 1])) {
return false;
}
}
}
} else {
// TODO implement me
}
}
return true;
} } | public class class_name {
public boolean isSimple() {
if (isEmpty()) {
return true; // depends on control dependency: [if], data = [none]
}
if (getNumGeometries() > 1) {
for (int n = 0; n < getNumGeometries(); n++) {
if (!getGeometryN(n).isSimple()) {
return false; // depends on control dependency: [if], data = [none]
}
}
} else {
final Coordinate[] coords1 = getCoordinates();
final Coordinate[] coords2 = getCoordinates();
if (coords1.length > 1 && coords2.length > 1) {
for (int i = 0; i < coords2.length - 1; i++) {
for (int j = 0; j < coords1.length - 1; j++) {
if (Mathlib.lineIntersects(coords2[i], coords2[i + 1], coords1[j], coords1[j + 1])) {
return false; // depends on control dependency: [if], data = [none]
}
}
}
} else {
// TODO implement me
}
}
return true;
} } |
public class class_name {
protected void setGalleriesVisible(boolean visible) {
if (visible) {
m_noGalleriesLabel.getElement().getStyle().clearDisplay();
m_galleryTree.getElement().getStyle().clearDisplay();
} else {
m_galleryTree.getElement().getStyle().setDisplay(Display.NONE);
m_noGalleriesLabel.getElement().getStyle().setDisplay(Display.NONE);
}
} } | public class class_name {
protected void setGalleriesVisible(boolean visible) {
if (visible) {
m_noGalleriesLabel.getElement().getStyle().clearDisplay(); // depends on control dependency: [if], data = [none]
m_galleryTree.getElement().getStyle().clearDisplay(); // depends on control dependency: [if], data = [none]
} else {
m_galleryTree.getElement().getStyle().setDisplay(Display.NONE); // depends on control dependency: [if], data = [none]
m_noGalleriesLabel.getElement().getStyle().setDisplay(Display.NONE); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final void setStepSize(final int stepSize) {
if (stepSize != -1) {
Condition.INSTANCE.ensureAtLeast(stepSize, 1, "The step size must be at least 1");
Condition.INSTANCE.ensureAtMaximum(stepSize, getRange(),
"The step size must be at maximum the range");
}
this.stepSize = stepSize;
setValue(adaptToStepSize(getValue()));
} } | public class class_name {
public final void setStepSize(final int stepSize) {
if (stepSize != -1) {
Condition.INSTANCE.ensureAtLeast(stepSize, 1, "The step size must be at least 1"); // depends on control dependency: [if], data = [(stepSize]
Condition.INSTANCE.ensureAtMaximum(stepSize, getRange(),
"The step size must be at maximum the range"); // depends on control dependency: [if], data = [(stepSize]
}
this.stepSize = stepSize;
setValue(adaptToStepSize(getValue()));
} } |
public class class_name {
public SqlInfo buildLikeSql(String fieldText, String valueText, String patternText) {
if (StringHelper.isNotBlank(valueText) && StringHelper.isBlank(patternText)) {
return super.buildLikeSql(fieldText, ParseHelper.parseExpressWithException(valueText, context));
} else if (StringHelper.isBlank(valueText) && StringHelper.isNotBlank(patternText)) {
return super.buildLikePatternSql(fieldText, patternText);
} else {
throw new ValidFailException("<like /> 标签中的'value'属性和'pattern'属性不能同时为空或者同时不为空!");
}
} } | public class class_name {
public SqlInfo buildLikeSql(String fieldText, String valueText, String patternText) {
if (StringHelper.isNotBlank(valueText) && StringHelper.isBlank(patternText)) {
return super.buildLikeSql(fieldText, ParseHelper.parseExpressWithException(valueText, context)); // depends on control dependency: [if], data = [none]
} else if (StringHelper.isBlank(valueText) && StringHelper.isNotBlank(patternText)) {
return super.buildLikePatternSql(fieldText, patternText); // depends on control dependency: [if], data = [none]
} else {
throw new ValidFailException("<like /> 标签中的'value'属性和'pattern'属性不能同时为空或者同时不为空!");
}
} } |
public class class_name {
private void pingNotifiableEventListenerInternal(Object object, String topic, Registration registration, boolean register) {
if (!(object instanceof NotifiableEventListener)) {
return;
}
NotifiableEventListener listener = ((NotifiableEventListener) object);
if (register) {
listener.onRegister(service, serviceName, topic, registration);
} else {
listener.onDeregister(service, serviceName, topic, registration);
}
} } | public class class_name {
private void pingNotifiableEventListenerInternal(Object object, String topic, Registration registration, boolean register) {
if (!(object instanceof NotifiableEventListener)) {
return; // depends on control dependency: [if], data = [none]
}
NotifiableEventListener listener = ((NotifiableEventListener) object);
if (register) {
listener.onRegister(service, serviceName, topic, registration); // depends on control dependency: [if], data = [none]
} else {
listener.onDeregister(service, serviceName, topic, registration); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@NotNull
public DoubleStream doubles(long streamSize) {
if (streamSize < 0L) throw new IllegalArgumentException();
if (streamSize == 0L) {
return DoubleStream.empty();
}
return doubles().limit(streamSize);
} } | public class class_name {
@NotNull
public DoubleStream doubles(long streamSize) {
if (streamSize < 0L) throw new IllegalArgumentException();
if (streamSize == 0L) {
return DoubleStream.empty(); // depends on control dependency: [if], data = [none]
}
return doubles().limit(streamSize);
} } |
public class class_name {
public EClass getIfcDocumentSelect() {
if (ifcDocumentSelectEClass == null) {
ifcDocumentSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(952);
}
return ifcDocumentSelectEClass;
} } | public class class_name {
public EClass getIfcDocumentSelect() {
if (ifcDocumentSelectEClass == null) {
ifcDocumentSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(952);
// depends on control dependency: [if], data = [none]
}
return ifcDocumentSelectEClass;
} } |
public class class_name {
public static void profileRulesOnText(String contents,
JLanguageTool lt) throws IOException {
long[] workTime = new long[10];
List<Rule> rules = lt.getAllActiveRules();
int ruleCount = rules.size();
System.out.printf("Testing %d rules%n", ruleCount);
System.out.println("Rule ID\tTime\tSentences\tMatches\tSentences per sec.");
List<String> sentences = lt.sentenceTokenize(contents);
for (Rule rule : rules) {
if (rule instanceof TextLevelRule) {
continue; // profile rules for sentences only
}
int matchCount = 0;
for (int k = 0; k < 10; k++) {
long startTime = System.currentTimeMillis();
for (String sentence : sentences) {
matchCount += rule.match
(lt.getAnalyzedSentence(sentence)).length;
}
long endTime = System.currentTimeMillis();
workTime[k] = endTime - startTime;
}
long time = median(workTime);
float timeInSeconds = time / 1000.0f;
float sentencesPerSecond = sentences.size() / timeInSeconds;
System.out.printf(Locale.ENGLISH,
"%s\t%d\t%d\t%d\t%.1f", rule.getId(),
time, sentences.size(), matchCount, sentencesPerSecond);
System.out.println();
}
} } | public class class_name {
public static void profileRulesOnText(String contents,
JLanguageTool lt) throws IOException {
long[] workTime = new long[10];
List<Rule> rules = lt.getAllActiveRules();
int ruleCount = rules.size();
System.out.printf("Testing %d rules%n", ruleCount);
System.out.println("Rule ID\tTime\tSentences\tMatches\tSentences per sec.");
List<String> sentences = lt.sentenceTokenize(contents);
for (Rule rule : rules) {
if (rule instanceof TextLevelRule) {
continue; // profile rules for sentences only
}
int matchCount = 0;
for (int k = 0; k < 10; k++) {
long startTime = System.currentTimeMillis();
for (String sentence : sentences) {
matchCount += rule.match
(lt.getAnalyzedSentence(sentence)).length; // depends on control dependency: [for], data = [none]
}
long endTime = System.currentTimeMillis();
workTime[k] = endTime - startTime; // depends on control dependency: [for], data = [k]
}
long time = median(workTime);
float timeInSeconds = time / 1000.0f;
float sentencesPerSecond = sentences.size() / timeInSeconds;
System.out.printf(Locale.ENGLISH,
"%s\t%d\t%d\t%d\t%.1f", rule.getId(),
time, sentences.size(), matchCount, sentencesPerSecond);
System.out.println();
}
} } |
public class class_name {
private void handleJobMasterError(final Throwable cause) {
if (ExceptionUtils.isJvmFatalError(cause)) {
log.error("Fatal error occurred on JobManager.", cause);
// The fatal error handler implementation should make sure that this call is non-blocking
fatalErrorHandler.onFatalError(cause);
} else {
jobCompletionActions.jobMasterFailed(cause);
}
} } | public class class_name {
private void handleJobMasterError(final Throwable cause) {
if (ExceptionUtils.isJvmFatalError(cause)) {
log.error("Fatal error occurred on JobManager.", cause); // depends on control dependency: [if], data = [none]
// The fatal error handler implementation should make sure that this call is non-blocking
fatalErrorHandler.onFatalError(cause); // depends on control dependency: [if], data = [none]
} else {
jobCompletionActions.jobMasterFailed(cause); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Iterator<Operator<Tree<E>>> validOperators(boolean reverse)
{
/*log.fine("public Iterator<Operator> validOperators(): called");*/
// Check if the tree is a leaf and return an empty iterator if so.
if (tree.isLeaf())
{
/*log.fine("is leaf");*/
return new ArrayList<Operator<Tree<E>>>().iterator();
}
// Generate an iterator over the child trees of the current node, encapsulating them as operators.
else
{
/*log.fine("is node");*/
Tree.Node<E> node = tree.getAsNode();
return new TreeSearchOperatorIterator<E>(node.getChildIterator());
}
} } | public class class_name {
public Iterator<Operator<Tree<E>>> validOperators(boolean reverse)
{
/*log.fine("public Iterator<Operator> validOperators(): called");*/
// Check if the tree is a leaf and return an empty iterator if so.
if (tree.isLeaf())
{
/*log.fine("is leaf");*/
return new ArrayList<Operator<Tree<E>>>().iterator(); // depends on control dependency: [if], data = [none]
}
// Generate an iterator over the child trees of the current node, encapsulating them as operators.
else
{
/*log.fine("is node");*/
Tree.Node<E> node = tree.getAsNode();
return new TreeSearchOperatorIterator<E>(node.getChildIterator()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public List<ContainerDef> getContainers() {
List<ContainerDef> containers = new ArrayList<ContainerDef>();
for (Node container : model.get("container")) {
containers.add(new ContainerDefImpl(getDescriptorName(), model, container));
}
return containers;
} } | public class class_name {
@Override
public List<ContainerDef> getContainers() {
List<ContainerDef> containers = new ArrayList<ContainerDef>();
for (Node container : model.get("container")) {
containers.add(new ContainerDefImpl(getDescriptorName(), model, container)); // depends on control dependency: [for], data = [container]
}
return containers;
} } |
public class class_name {
int insert(Row row,
byte []sourceBuffer,
int sourceOffset,
BlobOutputStream []blobs)
{
int rowHead = _rowHead;
int blobTail = _blobTail;
int rowLength = row.length();
rowHead -= rowLength;
// return false if the block is full
if (rowHead < blobTail) {
return -1;
}
byte []buffer = _buffer;
System.arraycopy(sourceBuffer, sourceOffset,
buffer, rowHead,
rowLength);
// XXX: timestamp
buffer[rowHead] = (byte) ((buffer[rowHead] & ~CODE_MASK) | INSERT);
blobTail = row.insertBlobs(buffer, rowHead, blobTail, blobs);
// System.out.println("HEXL: " + Hex.toHex(buffer, rowFirst, rowLength));
// if inline blobs can't fit, return false
if (blobTail < 0) {
return -1;
}
setBlobTail(blobTail);
rowHead(rowHead);
validateBlock(row);
return rowHead;
} } | public class class_name {
int insert(Row row,
byte []sourceBuffer,
int sourceOffset,
BlobOutputStream []blobs)
{
int rowHead = _rowHead;
int blobTail = _blobTail;
int rowLength = row.length();
rowHead -= rowLength;
// return false if the block is full
if (rowHead < blobTail) {
return -1; // depends on control dependency: [if], data = [none]
}
byte []buffer = _buffer;
System.arraycopy(sourceBuffer, sourceOffset,
buffer, rowHead,
rowLength);
// XXX: timestamp
buffer[rowHead] = (byte) ((buffer[rowHead] & ~CODE_MASK) | INSERT);
blobTail = row.insertBlobs(buffer, rowHead, blobTail, blobs);
// System.out.println("HEXL: " + Hex.toHex(buffer, rowFirst, rowLength));
// if inline blobs can't fit, return false
if (blobTail < 0) {
return -1; // depends on control dependency: [if], data = [none]
}
setBlobTail(blobTail);
rowHead(rowHead);
validateBlock(row);
return rowHead;
} } |
public class class_name {
private double calcSD(double[] arr, double mean) {
double sd = 0;
for (double resid : arr) {
sd += Math.pow(resid - mean, 2);
}
sd = Math.sqrt(sd/arr.length);
return sd;
} } | public class class_name {
private double calcSD(double[] arr, double mean) {
double sd = 0;
for (double resid : arr) {
sd += Math.pow(resid - mean, 2); // depends on control dependency: [for], data = [resid]
}
sd = Math.sqrt(sd/arr.length);
return sd;
} } |
public class class_name {
public static List<String> getSelectOptionValues(CmsObject cms, String rootPath, boolean allRemoved) {
try {
cms = OpenCms.initCmsObject(cms);
cms.getRequestContext().setSiteRoot("");
CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(cms, rootPath);
if (adeConfig.parent() != null) {
adeConfig = adeConfig.parent();
}
List<CmsSelectWidgetOption> options = getFormatterOptionsStatic(cms, adeConfig, rootPath, allRemoved);
List<CmsSelectWidgetOption> typeOptions = getTypeOptionsStatic(cms, adeConfig, allRemoved);
options.addAll(typeOptions);
List<String> result = new ArrayList<String>(options.size());
for (CmsSelectWidgetOption o : options) {
result.add(o.getValue());
}
return result;
} catch (CmsException e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
return null;
}
} } | public class class_name {
public static List<String> getSelectOptionValues(CmsObject cms, String rootPath, boolean allRemoved) {
try {
cms = OpenCms.initCmsObject(cms); // depends on control dependency: [try], data = [none]
cms.getRequestContext().setSiteRoot(""); // depends on control dependency: [try], data = [none]
CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(cms, rootPath);
if (adeConfig.parent() != null) {
adeConfig = adeConfig.parent(); // depends on control dependency: [if], data = [none]
}
List<CmsSelectWidgetOption> options = getFormatterOptionsStatic(cms, adeConfig, rootPath, allRemoved);
List<CmsSelectWidgetOption> typeOptions = getTypeOptionsStatic(cms, adeConfig, allRemoved);
options.addAll(typeOptions); // depends on control dependency: [try], data = [none]
List<String> result = new ArrayList<String>(options.size());
for (CmsSelectWidgetOption o : options) {
result.add(o.getValue()); // depends on control dependency: [for], data = [o]
}
return result; // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T extends ViewTraverse<T>> String expandVariable(
final MultiDataContext<T, DataContext> data,
final T currentContext,
final BiFunction<Integer, String, T> viewMap,
final String step,
final String group,
final String key,
final String node
)
{
Integer t = null;
if (null != step) {
try {
t = Integer.parseInt(step);
} catch (NumberFormatException e) {
return null;
}
}
T view = viewMap.apply(t, node);
T mergedview = view.merge(currentContext).getView();
return data.resolve(mergedview, view, group, key, null);
} } | public class class_name {
public static <T extends ViewTraverse<T>> String expandVariable(
final MultiDataContext<T, DataContext> data,
final T currentContext,
final BiFunction<Integer, String, T> viewMap,
final String step,
final String group,
final String key,
final String node
)
{
Integer t = null;
if (null != step) {
try {
t = Integer.parseInt(step); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
return null;
} // depends on control dependency: [catch], data = [none]
}
T view = viewMap.apply(t, node);
T mergedview = view.merge(currentContext).getView();
return data.resolve(mergedview, view, group, key, null);
} } |
public class class_name {
public static Result toResult(ResultSet rs, int maxRows) {
try {
return new ResultImpl(rs, -1, maxRows);
} catch (SQLException ex) {
return null;
}
} } | public class class_name {
public static Result toResult(ResultSet rs, int maxRows) {
try {
return new ResultImpl(rs, -1, maxRows); // depends on control dependency: [try], data = [none]
} catch (SQLException ex) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void validateElementProperty(String propertyName, String controlValue, String resultValue, TestContext context) {
if (StringUtils.hasText(controlValue)) {
String control = context.replaceDynamicContentInString(controlValue);
if (ValidationMatcherUtils.isValidationMatcherExpression(control)) {
ValidationMatcherUtils.resolveValidationMatcher("payload", resultValue, control, context);
} else {
Assert.isTrue(control.equals(resultValue), String.format("Selenium web element validation failed, %s expected '%s', but was '%s'", propertyName, control, resultValue));
}
}
} } | public class class_name {
private void validateElementProperty(String propertyName, String controlValue, String resultValue, TestContext context) {
if (StringUtils.hasText(controlValue)) {
String control = context.replaceDynamicContentInString(controlValue);
if (ValidationMatcherUtils.isValidationMatcherExpression(control)) {
ValidationMatcherUtils.resolveValidationMatcher("payload", resultValue, control, context); // depends on control dependency: [if], data = [none]
} else {
Assert.isTrue(control.equals(resultValue), String.format("Selenium web element validation failed, %s expected '%s', but was '%s'", propertyName, control, resultValue)); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void marshall(Filters filters, ProtocolMarshaller protocolMarshaller) {
if (filters == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(filters.getQueues(), QUEUES_BINDING);
protocolMarshaller.marshall(filters.getChannels(), CHANNELS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Filters filters, ProtocolMarshaller protocolMarshaller) {
if (filters == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(filters.getQueues(), QUEUES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(filters.getChannels(), CHANNELS_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 Object prepareNativeValue(VirtualForm virtualForm, Object bean, String name, Object exp, PropertyDesc pd,
StringBuilder pathSb, FormMappingOption option) {
final Class<?> propertyType = pd.getPropertyType();
try {
final Object filtered = filterIfSimpleText(exp, option, name, propertyType);
return convertToNativeIfPossible(bean, name, filtered, propertyType, option);
} catch (RuntimeException e) {
if (isTypeFailureException(e)) {
virtualForm.acceptTypeFailure(pathSb.toString(), exp); // to render failure value
handleTypeFailure(virtualForm, bean, name, exp, pd, propertyType, pathSb, e);
return null;
} else {
throw e;
}
}
} } | public class class_name {
protected Object prepareNativeValue(VirtualForm virtualForm, Object bean, String name, Object exp, PropertyDesc pd,
StringBuilder pathSb, FormMappingOption option) {
final Class<?> propertyType = pd.getPropertyType();
try {
final Object filtered = filterIfSimpleText(exp, option, name, propertyType);
return convertToNativeIfPossible(bean, name, filtered, propertyType, option);
} catch (RuntimeException e) {
if (isTypeFailureException(e)) {
virtualForm.acceptTypeFailure(pathSb.toString(), exp); // to render failure value // depends on control dependency: [if], data = [none]
handleTypeFailure(virtualForm, bean, name, exp, pd, propertyType, pathSb, e); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
} else {
throw e;
}
}
} } |
public class class_name {
@FFDCIgnore(value = { NoSuchMethodException.class, NumberFormatException.class, Exception.class })
// Liberty Change for CXF End
@SuppressWarnings("unchecked")
public static <T> T handleParameter(String value,
boolean decoded,
Class<T> pClass,
Type genericType,
Annotation[] paramAnns,
ParameterType pType,
Message message) {
if (value == null) {
return null;
}
//fix new Date("") throw exception defect
if (value.isEmpty() && genericType == Date.class) {
return null;
}
if (pType == ParameterType.PATH) {
if (PathSegment.class.isAssignableFrom(pClass)) {
return pClass.cast(new PathSegmentImpl(value, decoded));
} else if (!MessageUtils.isTrue(
message.getContextualProperty(IGNORE_MATRIX_PARAMETERS))) {
value = new PathSegmentImpl(value, false).getPath();
}
}
value = decodeValue(value, decoded, pType);
Object result = null;
try {
result = createFromParameterHandler(value, pClass, genericType, paramAnns, message);
} catch (IllegalArgumentException nfe) {
throw createParamConversionException(pType, nfe);
}
if (result != null) {
T theResult = null;
if (pClass.isPrimitive()) {
theResult = (T) result;
} else {
theResult = pClass.cast(result);
}
return theResult;
}
if (Number.class.isAssignableFrom(pClass) && "".equals(value)) {
//pass empty string to boxed number type will result in 404
return null;
}
if (Boolean.class == pClass) {
// allow == checks for Boolean object
pClass = (Class<T>) Boolean.TYPE;
}
if (pClass.isPrimitive()) {
try {
@SuppressWarnings("unchecked")
T ret = (T) PrimitiveUtils.read(value, pClass);
// cannot us pClass.cast as the pClass is something like
// Boolean.TYPE (representing the boolean primitive) and
// the object is a Boolean object
return ret;
} catch (NumberFormatException nfe) {
throw createParamConversionException(pType, nfe);
}
}
boolean adapterHasToBeUsed = false;
Class<?> cls = pClass;
Class<?> valueType = JAXBUtils.getValueTypeFromAdapter(pClass, pClass, paramAnns);
if (valueType != cls) {
cls = valueType;
adapterHasToBeUsed = true;
}
if (pClass == String.class && !adapterHasToBeUsed) {
return pClass.cast(value);
}
// check constructors accepting a single String value
try {
Constructor<?> c = cls.getConstructor(new Class<?>[] { String.class });
result = c.newInstance(new Object[] { value });
} catch (NoSuchMethodException ex) {
// try valueOf
} catch (WebApplicationException ex) {
throw ex;
} catch (Exception ex) {
Throwable t = getOrThrowActualException(ex);
Tr.warning(tc, new org.apache.cxf.common.i18n.Message("CLASS_CONSTRUCTOR_FAILURE",
BUNDLE,
pClass.getName()).toString());
Response r = JAXRSUtils.toResponse(HttpUtils.getParameterFailureStatus(pType));
throw ExceptionUtils.toHttpException(t, r);
}
if (result == null) {
// check for valueOf(String) static methods
String[] methodNames = cls.isEnum()
? new String[] { "fromString", "fromValue", "valueOf" }
: new String[] { "valueOf", "fromString" };
result = evaluateFactoryMethods(value, pType, result, cls, methodNames);
}
if (adapterHasToBeUsed) {
// as the last resort, try XmlJavaTypeAdapters
Object valueToReplace = result != null ? result : value;
try {
result = JAXBUtils.convertWithAdapter(valueToReplace, pClass, paramAnns);
} catch (Throwable ex) {
result = null;
}
}
if (result == null) {
reportServerError("WRONG_PARAMETER_TYPE", pClass.getName());
}
return pClass.cast(result);
} } | public class class_name {
@FFDCIgnore(value = { NoSuchMethodException.class, NumberFormatException.class, Exception.class })
// Liberty Change for CXF End
@SuppressWarnings("unchecked")
public static <T> T handleParameter(String value,
boolean decoded,
Class<T> pClass,
Type genericType,
Annotation[] paramAnns,
ParameterType pType,
Message message) {
if (value == null) {
return null; // depends on control dependency: [if], data = [none]
}
//fix new Date("") throw exception defect
if (value.isEmpty() && genericType == Date.class) {
return null; // depends on control dependency: [if], data = [none]
}
if (pType == ParameterType.PATH) {
if (PathSegment.class.isAssignableFrom(pClass)) {
return pClass.cast(new PathSegmentImpl(value, decoded)); // depends on control dependency: [if], data = [none]
} else if (!MessageUtils.isTrue(
message.getContextualProperty(IGNORE_MATRIX_PARAMETERS))) {
value = new PathSegmentImpl(value, false).getPath(); // depends on control dependency: [if], data = [none]
}
}
value = decodeValue(value, decoded, pType);
Object result = null;
try {
result = createFromParameterHandler(value, pClass, genericType, paramAnns, message); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException nfe) {
throw createParamConversionException(pType, nfe);
} // depends on control dependency: [catch], data = [none]
if (result != null) {
T theResult = null;
if (pClass.isPrimitive()) {
theResult = (T) result; // depends on control dependency: [if], data = [none]
} else {
theResult = pClass.cast(result); // depends on control dependency: [if], data = [none]
}
return theResult; // depends on control dependency: [if], data = [none]
}
if (Number.class.isAssignableFrom(pClass) && "".equals(value)) {
//pass empty string to boxed number type will result in 404
return null; // depends on control dependency: [if], data = [none]
}
if (Boolean.class == pClass) {
// allow == checks for Boolean object
pClass = (Class<T>) Boolean.TYPE; // depends on control dependency: [if], data = [none]
}
if (pClass.isPrimitive()) {
try {
@SuppressWarnings("unchecked")
T ret = (T) PrimitiveUtils.read(value, pClass);
// cannot us pClass.cast as the pClass is something like
// Boolean.TYPE (representing the boolean primitive) and
// the object is a Boolean object
return ret; // depends on control dependency: [try], data = [none]
} catch (NumberFormatException nfe) {
throw createParamConversionException(pType, nfe);
} // depends on control dependency: [catch], data = [none]
}
boolean adapterHasToBeUsed = false;
Class<?> cls = pClass;
Class<?> valueType = JAXBUtils.getValueTypeFromAdapter(pClass, pClass, paramAnns);
if (valueType != cls) {
cls = valueType; // depends on control dependency: [if], data = [none]
adapterHasToBeUsed = true; // depends on control dependency: [if], data = [none]
}
if (pClass == String.class && !adapterHasToBeUsed) {
return pClass.cast(value); // depends on control dependency: [if], data = [none]
}
// check constructors accepting a single String value
try {
Constructor<?> c = cls.getConstructor(new Class<?>[] { String.class });
result = c.newInstance(new Object[] { value }); // depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException ex) {
// try valueOf
} catch (WebApplicationException ex) { // depends on control dependency: [catch], data = [none]
throw ex;
} catch (Exception ex) { // depends on control dependency: [catch], data = [none]
Throwable t = getOrThrowActualException(ex);
Tr.warning(tc, new org.apache.cxf.common.i18n.Message("CLASS_CONSTRUCTOR_FAILURE",
BUNDLE,
pClass.getName()).toString());
Response r = JAXRSUtils.toResponse(HttpUtils.getParameterFailureStatus(pType));
throw ExceptionUtils.toHttpException(t, r);
} // depends on control dependency: [catch], data = [none]
if (result == null) {
// check for valueOf(String) static methods
String[] methodNames = cls.isEnum()
? new String[] { "fromString", "fromValue", "valueOf" }
: new String[] { "valueOf", "fromString" };
result = evaluateFactoryMethods(value, pType, result, cls, methodNames); // depends on control dependency: [if], data = [none]
}
if (adapterHasToBeUsed) {
// as the last resort, try XmlJavaTypeAdapters
Object valueToReplace = result != null ? result : value;
try {
result = JAXBUtils.convertWithAdapter(valueToReplace, pClass, paramAnns); // depends on control dependency: [try], data = [none]
} catch (Throwable ex) {
result = null;
} // depends on control dependency: [catch], data = [none]
}
if (result == null) {
reportServerError("WRONG_PARAMETER_TYPE", pClass.getName()); // depends on control dependency: [if], data = [none]
}
return pClass.cast(result);
} } |
public class class_name {
public PageFlowController getPageFlowForPath( RequestContext context, String path )
throws InstantiationException, IllegalAccessException
{
HttpServletRequest request = context.getHttpRequest();
HttpServletResponse response = context.getHttpResponse();
PageFlowController cur = PageFlowUtils.getCurrentPageFlow( request, getServletContext() );
String parentDir = PageFlowUtils.getModulePathForRelativeURI( path );
//
// Reinitialize transient data that may have been lost on session failover.
//
if ( cur != null )
cur.reinitialize( request, response, getServletContext() );
//
// If there's no current PageFlow, or if the current PageFlowController has a module path that
// is incompatible with the current request URI, then create the appropriate PageFlowController.
//
if ( cur == null || ! PageFlowUtils.getModulePathForRelativeURI( cur.getURI() ).equals( parentDir ) )
{
String className = null;
try
{
className = InternalUtils.getFlowControllerClassName( parentDir, request, getServletContext() );
return className != null ? createPageFlow( context, className ) : null;
}
catch ( ClassNotFoundException e )
{
if ( LOG.isInfoEnabled() )
LOG.info("No page flow exists for path " + path +
". Unable to load class \"" + className + "\". Cause: " + e, e);
return null;
}
}
return cur;
} } | public class class_name {
public PageFlowController getPageFlowForPath( RequestContext context, String path )
throws InstantiationException, IllegalAccessException
{
HttpServletRequest request = context.getHttpRequest();
HttpServletResponse response = context.getHttpResponse();
PageFlowController cur = PageFlowUtils.getCurrentPageFlow( request, getServletContext() );
String parentDir = PageFlowUtils.getModulePathForRelativeURI( path );
//
// Reinitialize transient data that may have been lost on session failover.
//
if ( cur != null )
cur.reinitialize( request, response, getServletContext() );
//
// If there's no current PageFlow, or if the current PageFlowController has a module path that
// is incompatible with the current request URI, then create the appropriate PageFlowController.
//
if ( cur == null || ! PageFlowUtils.getModulePathForRelativeURI( cur.getURI() ).equals( parentDir ) )
{
String className = null;
try
{
className = InternalUtils.getFlowControllerClassName( parentDir, request, getServletContext() ); // depends on control dependency: [try], data = [none]
return className != null ? createPageFlow( context, className ) : null; // depends on control dependency: [try], data = [none]
}
catch ( ClassNotFoundException e )
{
if ( LOG.isInfoEnabled() )
LOG.info("No page flow exists for path " + path +
". Unable to load class \"" + className + "\". Cause: " + e, e);
return null;
} // depends on control dependency: [catch], data = [none]
}
return cur;
} } |
public class class_name {
public DeployableUnitID install(String url) throws NullPointerException,
MalformedURLException, AlreadyDeployedException,
DeploymentException, ManagementException {
try {
final SleeContainer sleeContainer = getSleeContainer();
final DeployableUnitBuilder deployableUnitBuilder = sleeContainer.getDeployableUnitManagement().getDeployableUnitBuilder();
final SleeTransactionManager sleeTransactionManager = sleeContainer
.getTransactionManager();
final ComponentRepository componentRepositoryImpl = sleeContainer
.getComponentRepository();
final DeployableUnitManagement deployableUnitManagement = sleeContainer
.getDeployableUnitManagement();
synchronized (sleeContainer.getManagementMonitor()) {
DeployableUnitID deployableUnitID = new DeployableUnitID(url);
logger.info("Installing " +deployableUnitID);
if (deployableUnitManagement
.getDeployableUnit(deployableUnitID) != null) {
throw new AlreadyDeployedException(
"there is already a DU deployed for url " + url);
}
DeployableUnit deployableUnit = null;
Thread currentThread = Thread.currentThread();
ClassLoader currentClassLoader = currentThread
.getContextClassLoader();
Set<SleeComponent> componentsInstalled = new HashSet<SleeComponent>();
boolean rollback = true;
try {
// start transaction
sleeTransactionManager.begin();
// build du
deployableUnit = deployableUnitBuilder.build(url,
tempDUJarsDeploymentRoot, componentRepositoryImpl);
// install each component built
for (LibraryComponent component : deployableUnit
.getLibraryComponents().values()) {
componentRepositoryImpl.putComponent(component);
updateSecurityPermissions(component, false);
logger.info("Installed " + component);
}
for (EventTypeComponent component : deployableUnit
.getEventTypeComponents().values()) {
componentRepositoryImpl.putComponent(component);
logger.info("Installed " + component);
}
for (ResourceAdaptorTypeComponent component : deployableUnit
.getResourceAdaptorTypeComponents().values()) {
componentRepositoryImpl.putComponent(component);
currentThread.setContextClassLoader(component
.getClassLoader());
sleeContainer.getResourceManagement()
.installResourceAdaptorType(component);
componentsInstalled.add(component);
logger.info("Installed " + component);
}
// before executing the logic to install an profile spec, ra
// or sbb insert the components in the repo, a component can
// require that another is already in repo
for (ProfileSpecificationComponent component : deployableUnit
.getProfileSpecificationComponents().values()) {
componentRepositoryImpl.putComponent(component);
}
for (ResourceAdaptorComponent component : deployableUnit
.getResourceAdaptorComponents().values()) {
componentRepositoryImpl.putComponent(component);
}
for (SbbComponent component : deployableUnit
.getSbbComponents().values()) {
componentRepositoryImpl.putComponent(component);
}
// run the install logic to install an profile spec, ra or
// sbb
for (ProfileSpecificationComponent component : deployableUnit
.getProfileSpecificationComponents().values()) {
currentThread.setContextClassLoader(component
.getClassLoader());
sleeContainer.getSleeProfileTableManager()
.installProfileSpecification(component);
componentsInstalled.add(component);
updateSecurityPermissions(component, false);
logger.info("Installed " + component);
}
for (ResourceAdaptorComponent component : deployableUnit
.getResourceAdaptorComponents().values()) {
currentThread.setContextClassLoader(component
.getClassLoader());
sleeContainer.getResourceManagement()
.installResourceAdaptor(component);
componentsInstalled.add(component);
updateSecurityPermissions(component, false);
logger.info("Installed " + component);
}
for (SbbComponent component : deployableUnit
.getSbbComponents().values()) {
currentThread.setContextClassLoader(component
.getClassLoader());
sleeContainer.getSbbManagement().installSbb(component);
componentsInstalled.add(component);
updateSecurityPermissions(component, false);
logger.info("Installed " + component);
}
// finally install the services
currentThread.setContextClassLoader(currentClassLoader);
for (ServiceComponent component : deployableUnit
.getServiceComponents().values()) {
componentRepositoryImpl.putComponent(component);
sleeContainer.getServiceManagement().installService(
component);
componentsInstalled.add(component);
logger.info("Installed " + component+". Root sbb is "+component.getRootSbbComponent());
}
deployableUnitManagement.addDeployableUnit(deployableUnit);
logger.info("Installed " +deployableUnitID);
updateSecurityPermissions(null, true);
rollback = false;
return deployableUnitID;
} finally {
currentThread.setContextClassLoader(currentClassLoader);
try {
if (rollback) {
if (deployableUnit != null) {
// remove all components added to repo
// put all components in the repo again
for (LibraryComponent component : deployableUnit
.getLibraryComponents().values()) {
removeSecurityPermissions(component, false);
componentRepositoryImpl.removeComponent(component.getLibraryID());
logger.info("Uninstalled " + component
+ " due to tx rollback");
}
for (EventTypeComponent component : deployableUnit
.getEventTypeComponents().values()) {
componentRepositoryImpl.removeComponent(component.getEventTypeID());
logger.info("Uninstalled " + component
+ " due to tx rollback");
}
for (ResourceAdaptorTypeComponent component : deployableUnit
.getResourceAdaptorTypeComponents()
.values()) {
removeSecurityPermissions(component, false);
if(componentsInstalled.contains(component)) {
sleeContainer.getResourceManagement().uninstallResourceAdaptorType(component);
}
componentRepositoryImpl.removeComponent(component.getResourceAdaptorTypeID());
logger.info("Uninstalled " + component
+ " due to tx rollback");
}
for (ProfileSpecificationComponent component : deployableUnit
.getProfileSpecificationComponents()
.values()) {
if(componentsInstalled.contains(component)) {
sleeContainer.getSleeProfileTableManager().uninstallProfileSpecification(component);
}
componentRepositoryImpl.removeComponent(component.getProfileSpecificationID());
logger.info("Uninstalled " + component
+ " due to tx rollback");
}
for (ResourceAdaptorComponent component : deployableUnit
.getResourceAdaptorComponents().values()) {
removeSecurityPermissions(component, false);
if(componentsInstalled.contains(component)) {
sleeContainer.getResourceManagement().uninstallResourceAdaptor(component);
}
componentRepositoryImpl.removeComponent(component.getResourceAdaptorID());
logger.info("Uninstalled " + component
+ " due to tx rollback");
}
for (SbbComponent component : deployableUnit
.getSbbComponents().values()) {
removeSecurityPermissions(component, false);
if(componentsInstalled.contains(component)) {
sleeContainer.getSbbManagement().uninstallSbb(component);
}
componentRepositoryImpl.removeComponent(component.getSbbID());
logger.info("Uninstalled " + component
+ " due to tx rollback");
}
for (ServiceComponent component : deployableUnit
.getServiceComponents().values()) {
if(componentsInstalled.contains(component)) {
sleeContainer.getServiceManagement().uninstallService(component);
}
componentRepositoryImpl.removeComponent(component.getServiceID());
logger.info("Uninstalled " + component
+ " due to tx rollback");
}
removeSecurityPermissions(null, true);
// undeploy the unit
deployableUnit.undeploy();
}
sleeTransactionManager.rollback();
} else {
sleeTransactionManager.commit();
}
} catch (Exception ex) {
throw new ManagementException(
"Exception while completing transaction", ex);
}
}
}
} catch (AlreadyDeployedException e) {
throw e;
} catch (DeploymentException e) {
// This will remove stack trace;
// throw e;
throw new DeploymentException(
"Failure encountered during deploy process.", e);
} catch (Throwable e) {
if (logger.isDebugEnabled()) {
logger.debug(e.getMessage(),e);
}
throw new ManagementException(e.getMessage(), e);
}
} } | public class class_name {
public DeployableUnitID install(String url) throws NullPointerException,
MalformedURLException, AlreadyDeployedException,
DeploymentException, ManagementException {
try {
final SleeContainer sleeContainer = getSleeContainer();
final DeployableUnitBuilder deployableUnitBuilder = sleeContainer.getDeployableUnitManagement().getDeployableUnitBuilder();
final SleeTransactionManager sleeTransactionManager = sleeContainer
.getTransactionManager();
final ComponentRepository componentRepositoryImpl = sleeContainer
.getComponentRepository();
final DeployableUnitManagement deployableUnitManagement = sleeContainer
.getDeployableUnitManagement();
synchronized (sleeContainer.getManagementMonitor()) {
DeployableUnitID deployableUnitID = new DeployableUnitID(url);
logger.info("Installing " +deployableUnitID);
if (deployableUnitManagement
.getDeployableUnit(deployableUnitID) != null) {
throw new AlreadyDeployedException(
"there is already a DU deployed for url " + url);
}
DeployableUnit deployableUnit = null;
Thread currentThread = Thread.currentThread();
ClassLoader currentClassLoader = currentThread
.getContextClassLoader();
Set<SleeComponent> componentsInstalled = new HashSet<SleeComponent>();
boolean rollback = true;
try {
// start transaction
sleeTransactionManager.begin();
// build du
deployableUnit = deployableUnitBuilder.build(url,
tempDUJarsDeploymentRoot, componentRepositoryImpl);
// install each component built
for (LibraryComponent component : deployableUnit
.getLibraryComponents().values()) {
componentRepositoryImpl.putComponent(component); // depends on control dependency: [for], data = [component]
updateSecurityPermissions(component, false); // depends on control dependency: [for], data = [component]
logger.info("Installed " + component); // depends on control dependency: [for], data = [component]
}
for (EventTypeComponent component : deployableUnit
.getEventTypeComponents().values()) {
componentRepositoryImpl.putComponent(component); // depends on control dependency: [for], data = [component]
logger.info("Installed " + component); // depends on control dependency: [for], data = [component]
}
for (ResourceAdaptorTypeComponent component : deployableUnit
.getResourceAdaptorTypeComponents().values()) {
componentRepositoryImpl.putComponent(component); // depends on control dependency: [for], data = [component]
currentThread.setContextClassLoader(component
.getClassLoader()); // depends on control dependency: [for], data = [none]
sleeContainer.getResourceManagement()
.installResourceAdaptorType(component); // depends on control dependency: [for], data = [none]
componentsInstalled.add(component); // depends on control dependency: [for], data = [component]
logger.info("Installed " + component); // depends on control dependency: [for], data = [component]
}
// before executing the logic to install an profile spec, ra
// or sbb insert the components in the repo, a component can
// require that another is already in repo
for (ProfileSpecificationComponent component : deployableUnit
.getProfileSpecificationComponents().values()) {
componentRepositoryImpl.putComponent(component); // depends on control dependency: [for], data = [component]
}
for (ResourceAdaptorComponent component : deployableUnit
.getResourceAdaptorComponents().values()) {
componentRepositoryImpl.putComponent(component); // depends on control dependency: [for], data = [component]
}
for (SbbComponent component : deployableUnit
.getSbbComponents().values()) {
componentRepositoryImpl.putComponent(component); // depends on control dependency: [for], data = [component]
}
// run the install logic to install an profile spec, ra or
// sbb
for (ProfileSpecificationComponent component : deployableUnit
.getProfileSpecificationComponents().values()) {
currentThread.setContextClassLoader(component
.getClassLoader()); // depends on control dependency: [for], data = [none]
sleeContainer.getSleeProfileTableManager()
.installProfileSpecification(component); // depends on control dependency: [for], data = [none]
componentsInstalled.add(component); // depends on control dependency: [for], data = [component]
updateSecurityPermissions(component, false); // depends on control dependency: [for], data = [component]
logger.info("Installed " + component); // depends on control dependency: [for], data = [component]
}
for (ResourceAdaptorComponent component : deployableUnit
.getResourceAdaptorComponents().values()) {
currentThread.setContextClassLoader(component
.getClassLoader()); // depends on control dependency: [for], data = [none]
sleeContainer.getResourceManagement()
.installResourceAdaptor(component); // depends on control dependency: [for], data = [none]
componentsInstalled.add(component); // depends on control dependency: [for], data = [component]
updateSecurityPermissions(component, false); // depends on control dependency: [for], data = [component]
logger.info("Installed " + component); // depends on control dependency: [for], data = [component]
}
for (SbbComponent component : deployableUnit
.getSbbComponents().values()) {
currentThread.setContextClassLoader(component
.getClassLoader()); // depends on control dependency: [for], data = [none]
sleeContainer.getSbbManagement().installSbb(component); // depends on control dependency: [for], data = [component]
componentsInstalled.add(component); // depends on control dependency: [for], data = [component]
updateSecurityPermissions(component, false); // depends on control dependency: [for], data = [component]
logger.info("Installed " + component); // depends on control dependency: [for], data = [component]
}
// finally install the services
currentThread.setContextClassLoader(currentClassLoader);
for (ServiceComponent component : deployableUnit
.getServiceComponents().values()) {
componentRepositoryImpl.putComponent(component); // depends on control dependency: [for], data = [component]
sleeContainer.getServiceManagement().installService(
component); // depends on control dependency: [for], data = [none]
componentsInstalled.add(component); // depends on control dependency: [for], data = [component]
logger.info("Installed " + component+". Root sbb is "+component.getRootSbbComponent()); // depends on control dependency: [for], data = [component]
}
deployableUnitManagement.addDeployableUnit(deployableUnit);
logger.info("Installed " +deployableUnitID);
updateSecurityPermissions(null, true);
rollback = false;
return deployableUnitID;
} finally {
currentThread.setContextClassLoader(currentClassLoader);
try {
if (rollback) {
if (deployableUnit != null) {
// remove all components added to repo
// put all components in the repo again
for (LibraryComponent component : deployableUnit
.getLibraryComponents().values()) {
removeSecurityPermissions(component, false); // depends on control dependency: [for], data = [component]
componentRepositoryImpl.removeComponent(component.getLibraryID()); // depends on control dependency: [for], data = [component]
logger.info("Uninstalled " + component
+ " due to tx rollback"); // depends on control dependency: [for], data = [none]
}
for (EventTypeComponent component : deployableUnit
.getEventTypeComponents().values()) {
componentRepositoryImpl.removeComponent(component.getEventTypeID()); // depends on control dependency: [for], data = [component]
logger.info("Uninstalled " + component
+ " due to tx rollback"); // depends on control dependency: [for], data = [none]
}
for (ResourceAdaptorTypeComponent component : deployableUnit
.getResourceAdaptorTypeComponents()
.values()) {
removeSecurityPermissions(component, false); // depends on control dependency: [for], data = [component]
if(componentsInstalled.contains(component)) {
sleeContainer.getResourceManagement().uninstallResourceAdaptorType(component); // depends on control dependency: [if], data = [none]
}
componentRepositoryImpl.removeComponent(component.getResourceAdaptorTypeID()); // depends on control dependency: [for], data = [component]
logger.info("Uninstalled " + component
+ " due to tx rollback"); // depends on control dependency: [for], data = [none]
}
for (ProfileSpecificationComponent component : deployableUnit
.getProfileSpecificationComponents()
.values()) {
if(componentsInstalled.contains(component)) {
sleeContainer.getSleeProfileTableManager().uninstallProfileSpecification(component); // depends on control dependency: [if], data = [none]
}
componentRepositoryImpl.removeComponent(component.getProfileSpecificationID()); // depends on control dependency: [for], data = [component]
logger.info("Uninstalled " + component
+ " due to tx rollback"); // depends on control dependency: [for], data = [none]
}
for (ResourceAdaptorComponent component : deployableUnit
.getResourceAdaptorComponents().values()) {
removeSecurityPermissions(component, false); // depends on control dependency: [for], data = [component]
if(componentsInstalled.contains(component)) {
sleeContainer.getResourceManagement().uninstallResourceAdaptor(component); // depends on control dependency: [if], data = [none]
}
componentRepositoryImpl.removeComponent(component.getResourceAdaptorID()); // depends on control dependency: [for], data = [component]
logger.info("Uninstalled " + component
+ " due to tx rollback"); // depends on control dependency: [for], data = [none]
}
for (SbbComponent component : deployableUnit
.getSbbComponents().values()) {
removeSecurityPermissions(component, false); // depends on control dependency: [for], data = [component]
if(componentsInstalled.contains(component)) {
sleeContainer.getSbbManagement().uninstallSbb(component); // depends on control dependency: [if], data = [none]
}
componentRepositoryImpl.removeComponent(component.getSbbID()); // depends on control dependency: [for], data = [component]
logger.info("Uninstalled " + component
+ " due to tx rollback"); // depends on control dependency: [for], data = [none]
}
for (ServiceComponent component : deployableUnit
.getServiceComponents().values()) {
if(componentsInstalled.contains(component)) {
sleeContainer.getServiceManagement().uninstallService(component); // depends on control dependency: [if], data = [none]
}
componentRepositoryImpl.removeComponent(component.getServiceID()); // depends on control dependency: [for], data = [component]
logger.info("Uninstalled " + component
+ " due to tx rollback"); // depends on control dependency: [for], data = [none]
}
removeSecurityPermissions(null, true); // depends on control dependency: [if], data = [none]
// undeploy the unit
deployableUnit.undeploy(); // depends on control dependency: [if], data = [none]
}
sleeTransactionManager.rollback(); // depends on control dependency: [if], data = [none]
} else {
sleeTransactionManager.commit(); // depends on control dependency: [if], data = [none]
}
} catch (Exception ex) {
throw new ManagementException(
"Exception while completing transaction", ex);
} // depends on control dependency: [catch], data = [none]
}
}
} catch (AlreadyDeployedException e) {
throw e;
} catch (DeploymentException e) {
// This will remove stack trace;
// throw e;
throw new DeploymentException(
"Failure encountered during deploy process.", e);
} catch (Throwable e) {
if (logger.isDebugEnabled()) {
logger.debug(e.getMessage(),e);
}
throw new ManagementException(e.getMessage(), e);
}
} } |
public class class_name {
protected double[][] generateConditional(double P[], boolean M[][]) {
int L = P.length;
double Q[][] = new double[L][L];
// set priors
for (int j = 0; j < L; j++) {
Q[j][j] = P[j];
}
// create conditionals
for (int j = 0; j < Q.length; j++) {
for (int k = j + 1; k < Q[j].length; k++) {
// dependence
if (M[j][k]) {
// min = tending toward mutual exclusivity
// max = tending toward total co-occurence
// @NOTE it would also be an option to select in [min,max], but since
// we are approximating the joint distribution, we can take
// a stronger approach, and just take either min or max.
Q[j][k] = (m_MetaRandom.nextBoolean() ? min(P[j], P[k]) : max(P[j], P[k]));
Q[k][j] = (Q[j][k] * Q[j][j]) / Q[k][k]; // Bayes Rule
} // independence
else {
Q[j][k] = P[j];
Q[k][j] = (Q[j][k] * P[k]) / P[j]; // Bayes Rule
}
}
}
return Q;
} } | public class class_name {
protected double[][] generateConditional(double P[], boolean M[][]) {
int L = P.length;
double Q[][] = new double[L][L];
// set priors
for (int j = 0; j < L; j++) {
Q[j][j] = P[j]; // depends on control dependency: [for], data = [j]
}
// create conditionals
for (int j = 0; j < Q.length; j++) {
for (int k = j + 1; k < Q[j].length; k++) {
// dependence
if (M[j][k]) {
// min = tending toward mutual exclusivity
// max = tending toward total co-occurence
// @NOTE it would also be an option to select in [min,max], but since
// we are approximating the joint distribution, we can take
// a stronger approach, and just take either min or max.
Q[j][k] = (m_MetaRandom.nextBoolean() ? min(P[j], P[k]) : max(P[j], P[k])); // depends on control dependency: [if], data = [none]
Q[k][j] = (Q[j][k] * Q[j][j]) / Q[k][k]; // Bayes Rule // depends on control dependency: [if], data = [none]
} // independence
else {
Q[j][k] = P[j]; // depends on control dependency: [if], data = [none]
Q[k][j] = (Q[j][k] * P[k]) / P[j]; // Bayes Rule // depends on control dependency: [if], data = [none]
}
}
}
return Q;
} } |
public class class_name {
static MeasuredNode pickBest(MeasuredNode a, MeasuredNode b) {
if (a.length == b.length) {
return (b.isChanged()) ? a : b;
}
return (a.length < b.length) ? a : b;
} } | public class class_name {
static MeasuredNode pickBest(MeasuredNode a, MeasuredNode b) {
if (a.length == b.length) {
return (b.isChanged()) ? a : b; // depends on control dependency: [if], data = [none]
}
return (a.length < b.length) ? a : b;
} } |
public class class_name {
public boolean contains(String encoding) {
if (encoding.equalsIgnoreCase("sendrecv") ||
encoding.equalsIgnoreCase("fmtp") ||
encoding.equalsIgnoreCase("audio") ||
encoding.equalsIgnoreCase("AS") ||
encoding.equalsIgnoreCase("IP4")) {
return true;
}
for (int i = 0; i < count; i++) {
if (md[i].contains(encoding)) {
return true;
}
}
return false;
} } | public class class_name {
public boolean contains(String encoding) {
if (encoding.equalsIgnoreCase("sendrecv") ||
encoding.equalsIgnoreCase("fmtp") ||
encoding.equalsIgnoreCase("audio") ||
encoding.equalsIgnoreCase("AS") ||
encoding.equalsIgnoreCase("IP4")) {
return true; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < count; i++) {
if (md[i].contains(encoding)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Sensitive
private String getStoredReq(HttpServletRequest req, ReferrerURLCookieHandler referrerURLHandler) {
String storedReq = referrerURLHandler.getReferrerURLFromCookies(req, ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME);
if (storedReq != null) {
if (storedReq.equals("/"))
storedReq = "";
else if (storedReq.startsWith("/"))
storedReq = storedReq.substring(1);
} else {
storedReq = "";
}
return storedReq;
} } | public class class_name {
@Sensitive
private String getStoredReq(HttpServletRequest req, ReferrerURLCookieHandler referrerURLHandler) {
String storedReq = referrerURLHandler.getReferrerURLFromCookies(req, ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME);
if (storedReq != null) {
if (storedReq.equals("/"))
storedReq = "";
else if (storedReq.startsWith("/"))
storedReq = storedReq.substring(1);
} else {
storedReq = ""; // depends on control dependency: [if], data = [none]
}
return storedReq;
} } |
public class class_name {
private Node renameProperty(Node propertyName) {
checkArgument(propertyName.isString());
if (!renameProperties) {
return propertyName;
}
Node call = IR.call(
IR.name(NodeUtil.JSC_PROPERTY_NAME_FN).srcref(propertyName),
propertyName);
call.srcref(propertyName);
call.putBooleanProp(Node.FREE_CALL, true);
call.putBooleanProp(Node.IS_CONSTANT_NAME, true);
return call;
} } | public class class_name {
private Node renameProperty(Node propertyName) {
checkArgument(propertyName.isString());
if (!renameProperties) {
return propertyName; // depends on control dependency: [if], data = [none]
}
Node call = IR.call(
IR.name(NodeUtil.JSC_PROPERTY_NAME_FN).srcref(propertyName),
propertyName);
call.srcref(propertyName);
call.putBooleanProp(Node.FREE_CALL, true);
call.putBooleanProp(Node.IS_CONSTANT_NAME, true);
return call;
} } |
public class class_name {
public void layoutContainer (Container parent)
{
Insets insets = parent.getInsets();
int pcount = parent.getComponentCount();
for (int ii = 0; ii < pcount; ii++) {
Component comp = parent.getComponent(ii);
if (!comp.isVisible()) {
continue;
}
Object constr = _constraints.get(comp);
if (constr == null) {
log.warning("No constraints for child!?", "cont", parent, "comp", comp);
continue;
}
if (constr instanceof Rectangle) {
Rectangle r = (Rectangle)constr;
comp.setBounds(insets.left + r.x, insets.top + r.y,
r.width, r.height);
} else {
Point p = (Point)constr;
Dimension d = comp.getPreferredSize();
comp.setBounds(insets.left + p.x, insets.top + p.y,
d.width, d.height);
}
}
} } | public class class_name {
public void layoutContainer (Container parent)
{
Insets insets = parent.getInsets();
int pcount = parent.getComponentCount();
for (int ii = 0; ii < pcount; ii++) {
Component comp = parent.getComponent(ii);
if (!comp.isVisible()) {
continue;
}
Object constr = _constraints.get(comp);
if (constr == null) {
log.warning("No constraints for child!?", "cont", parent, "comp", comp); // depends on control dependency: [if], data = [none]
continue;
}
if (constr instanceof Rectangle) {
Rectangle r = (Rectangle)constr;
comp.setBounds(insets.left + r.x, insets.top + r.y,
r.width, r.height); // depends on control dependency: [if], data = [none]
} else {
Point p = (Point)constr;
Dimension d = comp.getPreferredSize();
comp.setBounds(insets.left + p.x, insets.top + p.y,
d.width, d.height); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public EditableResourceBundle getResourceBundle(Locale locale) {
EditableResourceBundle localeBundle = bundles.get(locale);
if(localeBundle==null) {
ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, locale);
if(!resourceBundle.getLocale().equals(locale)) throw new AssertionError("ResourceBundle not for this locale: "+locale);
if(!(resourceBundle instanceof EditableResourceBundle)) throw new AssertionError("ResourceBundle is not a EditableResourceBundle: "+resourceBundle);
localeBundle = (EditableResourceBundle)resourceBundle;
if(localeBundle.getBundleSet()!=this) throw new AssertionError("EditableResourceBundle not for this EditableResourceBundleSet: "+localeBundle);
if(!localeBundle.getBundleLocale().equals(locale)) throw new AssertionError("EditableResourceBundle not for this locale: "+locale);
// EditableResourceBundle will have added the bundle to the bundles map.
}
return localeBundle;
} } | public class class_name {
public EditableResourceBundle getResourceBundle(Locale locale) {
EditableResourceBundle localeBundle = bundles.get(locale);
if(localeBundle==null) {
ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, locale);
if(!resourceBundle.getLocale().equals(locale)) throw new AssertionError("ResourceBundle not for this locale: "+locale);
if(!(resourceBundle instanceof EditableResourceBundle)) throw new AssertionError("ResourceBundle is not a EditableResourceBundle: "+resourceBundle);
localeBundle = (EditableResourceBundle)resourceBundle; // depends on control dependency: [if], data = [none]
if(localeBundle.getBundleSet()!=this) throw new AssertionError("EditableResourceBundle not for this EditableResourceBundleSet: "+localeBundle);
if(!localeBundle.getBundleLocale().equals(locale)) throw new AssertionError("EditableResourceBundle not for this locale: "+locale);
// EditableResourceBundle will have added the bundle to the bundles map.
}
return localeBundle;
} } |
public class class_name {
public boolean tick (Pathable pable, long tickStamp)
{
// see if we need to stop
if (_stopTime <= tickStamp) {
boolean updated = updatePositionTo(pable, _sx, _sy);
pable.pathCompleted(tickStamp);
return updated;
}
// see if it's time to move..
if (_nextMove > tickStamp) {
return false;
}
// when bobbling, it's bad form to bobble into the same position
int newx, newy;
do {
newx = _sx + RandomUtil.getInt(_dx * 2 + 1) - _dx;
newy = _sy + RandomUtil.getInt(_dy * 2 + 1) - _dy;
} while (! updatePositionTo(pable, newx, newy));
// and update the next time to move
_nextMove = tickStamp + _updateFreq;
return true;
} } | public class class_name {
public boolean tick (Pathable pable, long tickStamp)
{
// see if we need to stop
if (_stopTime <= tickStamp) {
boolean updated = updatePositionTo(pable, _sx, _sy);
pable.pathCompleted(tickStamp); // depends on control dependency: [if], data = [none]
return updated; // depends on control dependency: [if], data = [none]
}
// see if it's time to move..
if (_nextMove > tickStamp) {
return false; // depends on control dependency: [if], data = [none]
}
// when bobbling, it's bad form to bobble into the same position
int newx, newy;
do {
newx = _sx + RandomUtil.getInt(_dx * 2 + 1) - _dx;
newy = _sy + RandomUtil.getInt(_dy * 2 + 1) - _dy;
} while (! updatePositionTo(pable, newx, newy));
// and update the next time to move
_nextMove = tickStamp + _updateFreq;
return true;
} } |
public class class_name {
public static StatsTraceContext newServerContext(
List<? extends ServerStreamTracer.Factory> factories,
String fullMethodName,
Metadata headers) {
if (factories.isEmpty()) {
return NOOP;
}
StreamTracer[] tracers = new StreamTracer[factories.size()];
for (int i = 0; i < tracers.length; i++) {
tracers[i] = factories.get(i).newServerStreamTracer(fullMethodName, headers);
}
return new StatsTraceContext(tracers);
} } | public class class_name {
public static StatsTraceContext newServerContext(
List<? extends ServerStreamTracer.Factory> factories,
String fullMethodName,
Metadata headers) {
if (factories.isEmpty()) {
return NOOP; // depends on control dependency: [if], data = [none]
}
StreamTracer[] tracers = new StreamTracer[factories.size()];
for (int i = 0; i < tracers.length; i++) {
tracers[i] = factories.get(i).newServerStreamTracer(fullMethodName, headers); // depends on control dependency: [for], data = [i]
}
return new StatsTraceContext(tracers);
} } |
public class class_name {
public static Window windowForWordInPosition(int windowSize, int wordPos, List<String> sentence) {
List<String> window = new ArrayList<>();
List<String> onlyTokens = new ArrayList<>();
int contextSize = (int) Math.floor((windowSize - 1) / 2);
for (int i = wordPos - contextSize; i <= wordPos + contextSize; i++) {
if (i < 0)
window.add("<s>");
else if (i >= sentence.size())
window.add("</s>");
else {
onlyTokens.add(sentence.get(i));
window.add(sentence.get(i));
}
}
String wholeSentence = StringUtils.join(sentence);
String window2 = StringUtils.join(onlyTokens);
int begin = wholeSentence.indexOf(window2);
int end = begin + window2.length();
return new Window(window, begin, end);
} } | public class class_name {
public static Window windowForWordInPosition(int windowSize, int wordPos, List<String> sentence) {
List<String> window = new ArrayList<>();
List<String> onlyTokens = new ArrayList<>();
int contextSize = (int) Math.floor((windowSize - 1) / 2);
for (int i = wordPos - contextSize; i <= wordPos + contextSize; i++) {
if (i < 0)
window.add("<s>");
else if (i >= sentence.size())
window.add("</s>");
else {
onlyTokens.add(sentence.get(i)); // depends on control dependency: [if], data = [(i]
window.add(sentence.get(i)); // depends on control dependency: [if], data = [(i]
}
}
String wholeSentence = StringUtils.join(sentence);
String window2 = StringUtils.join(onlyTokens);
int begin = wholeSentence.indexOf(window2);
int end = begin + window2.length();
return new Window(window, begin, end);
} } |
public class class_name {
private boolean isContainedIn(BitSet sourceBitSet, BitSet targetBitSet) {
boolean result = false;
if (sourceBitSet.isEmpty()) {
return true;
}
BitSet setA = (BitSet) sourceBitSet.clone();
setA.and(targetBitSet);
if (setA.equals(sourceBitSet)) {
result = true;
}
return result;
} } | public class class_name {
private boolean isContainedIn(BitSet sourceBitSet, BitSet targetBitSet) {
boolean result = false;
if (sourceBitSet.isEmpty()) {
return true; // depends on control dependency: [if], data = [none]
}
BitSet setA = (BitSet) sourceBitSet.clone();
setA.and(targetBitSet);
if (setA.equals(sourceBitSet)) {
result = true; // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
private static void debug(String header, GatekeeperReply reply) {
if (logger.isTraceEnabled()) {
logger.trace(header);
logger.trace(reply.toString());
}
} } | public class class_name {
private static void debug(String header, GatekeeperReply reply) {
if (logger.isTraceEnabled()) {
logger.trace(header); // depends on control dependency: [if], data = [none]
logger.trace(reply.toString()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static final <T extends Appendable> void appendEncodedByte(T buffer, byte value,
byte[] state) {
try {
if (state[0] != 0) {
char c = (char) ((state[1] << 8) | ((value) & 0xFF));
buffer.append(c);
state[0] = 0;
}
else {
state[0] = 1;
state[1] = value;
}
} catch (IOException e) {
throw new IllegalIcuArgumentException(e);
}
} } | public class class_name {
private static final <T extends Appendable> void appendEncodedByte(T buffer, byte value,
byte[] state) {
try {
if (state[0] != 0) {
char c = (char) ((state[1] << 8) | ((value) & 0xFF));
buffer.append(c); // depends on control dependency: [if], data = [none]
state[0] = 0; // depends on control dependency: [if], data = [none]
}
else {
state[0] = 1; // depends on control dependency: [if], data = [none]
state[1] = value; // depends on control dependency: [if], data = [none]
}
} catch (IOException e) {
throw new IllegalIcuArgumentException(e);
} // depends on control dependency: [catch], data = [none]
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.