_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q180400
|
PrologParser.internOperator
|
test
|
public void internOperator(String operatorName, int priority, OpSymbol.Associativity associativity)
{
int arity;
if ((associativity == XFY) | (associativity == YFX) | (associativity == XFX))
{
arity = 2;
}
else
{
arity = 1;
}
int name = interner.internFunctorName(operatorName, arity);
operatorTable.setOperator(name, operatorName, priority, associativity);
}
|
java
|
{
"resource": ""
}
|
q180401
|
PrologParser.initializeBuiltIns
|
test
|
protected void initializeBuiltIns()
{
// Initializes the operator table with the standard ISO prolog built-in operators.
internOperator(":-", 1200, XFX);
internOperator(":-", 1200, FX);
internOperator("-->", 1200, XFX);
internOperator("?-", 1200, FX);
internOperator(";", 1100, XFY);
internOperator("->", 1050, XFY);
internOperator(",", 1000, XFY);
internOperator("\\+", 900, FY);
internOperator("=", 700, XFX);
internOperator("\\=", 700, XFX);
internOperator("==", 700, XFX);
internOperator("\\==", 700, XFX);
internOperator("@<", 700, XFX);
internOperator("@=<", 700, XFX);
internOperator("@>", 700, XFX);
internOperator("@>=", 700, XFX);
internOperator("=..", 700, XFX);
internOperator("is", 700, XFX);
internOperator("=:=", 700, XFX);
internOperator("=\\=", 700, XFX);
internOperator("<", 700, XFX);
internOperator("=<", 700, XFX);
internOperator(">", 700, XFX);
internOperator(">=", 700, XFX);
internOperator("+", 500, YFX);
internOperator("-", 500, YFX);
internOperator("\\/", 500, YFX);
internOperator("/\\", 500, YFX);
internOperator("/", 400, YFX);
internOperator("//", 400, YFX);
internOperator("*", 400, YFX);
internOperator(">>", 400, YFX);
internOperator("<<", 400, YFX);
internOperator("rem", 400, YFX);
internOperator("mod", 400, YFX);
internOperator("-", 200, FY);
internOperator("^", 200, YFX);
internOperator("**", 200, YFX);
internOperator("\\", 200, FY);
// Intern all built in functors.
interner.internFunctorName("nil", 0);
interner.internFunctorName("cons", 2);
interner.internFunctorName("true", 0);
interner.internFunctorName("fail", 0);
interner.internFunctorName("!", 0);
}
|
java
|
{
"resource": ""
}
|
q180402
|
PrologParser.consumeToken
|
test
|
protected Token consumeToken(int kind) throws SourceCodeException
{
Token nextToken = tokenSource.peek();
if (nextToken.kind != kind)
{
throw new SourceCodeException("Was expecting " + tokenImage[kind] + " but got " +
tokenImage[nextToken.kind] + ".", null, null, null,
new SourceCodePositionImpl(nextToken.beginLine, nextToken.beginColumn, nextToken.endLine,
nextToken.endColumn));
}
else
{
nextToken = tokenSource.poll();
return nextToken;
}
}
|
java
|
{
"resource": ""
}
|
q180403
|
PrologParser.peekAndConsume
|
test
|
private boolean peekAndConsume(int kind)
{
Token nextToken = tokenSource.peek();
if (nextToken.kind == kind)
{
try
{
consumeToken(kind);
}
catch (SourceCodeException e)
{
// If the peek ahead kind can not be consumed then something strange has gone wrong so report this
// as a bug rather than try to recover from it.
throw new IllegalStateException(e);
}
return true;
}
else
{
return false;
}
}
|
java
|
{
"resource": ""
}
|
q180404
|
TxSessionImpl.bind
|
test
|
public void bind()
{
// If necessary create a fresh transaction id.
if ((txId == null) || !txId.isValid())
{
txId = TxManager.createTxId();
}
// Bind the transaction to the current thread.
TxManager.assignTxIdToThread(txId);
// Bind this session to the current thread.
threadSession.set(this);
}
|
java
|
{
"resource": ""
}
|
q180405
|
TxSessionImpl.rollback
|
test
|
public void rollback()
{
// Rollback all soft resources.
for (Transactional enlist : enlists)
{
enlist.rollback();
}
// Clear all of the rolled back resources.
enlists.clear();
// Invalidate the transaction id, so that a fresh transaction is begun.
txId = TxManager.removeTxIdFromThread();
TxManager.invalidateTxId(txId);
bind();
}
|
java
|
{
"resource": ""
}
|
q180406
|
Filterators.collectIterator
|
test
|
public static <T> Collection<T> collectIterator(Iterator<T> iterator, Collection<T> targetCollection)
{
while (iterator.hasNext())
{
targetCollection.add(iterator.next());
}
return targetCollection;
}
|
java
|
{
"resource": ""
}
|
q180407
|
BaseCodeMachine.reserveCallPoint
|
test
|
public CallPoint reserveCallPoint(int name, int length)
{
// Work out where the code will go and advance the insertion point beyond its end, so that additional code
// will be added beyond the reserved space.
int address = getCodeInsertionPoint();
advanceCodeInsertionPoint(length);
// Create a call point for the reserved space.
CallPoint callPoint = new CallPoint(address, length, name);
// Add the call point to the symbol table under the interned name.
symbolTable.put(name, getCallPointSymbolField(), callPoint);
return callPoint;
}
|
java
|
{
"resource": ""
}
|
q180408
|
TimeUtils.timeOfDayToTicks
|
test
|
public static long timeOfDayToTicks(int hour, int minute, int second, int millisecond)
{
return millisecond + (MILLIS_PER_SECOND * second) + (MILLIS_PER_MINUTE * minute) + (MILLIS_PER_HOUR * hour);
}
|
java
|
{
"resource": ""
}
|
q180409
|
TimeUtils.ticksToYears
|
test
|
public static int ticksToYears(long ticks)
{
// The number of years is ticks floor divided by number of milliseconds in 365 1/4 days.
//return flooredDiv(ticks, MILLIS_PER_REAL_YEAR) + 1970;
//return flooredDiv(ticks + ((long)DAYS_TO_1970 * MILLIS_PER_DAY), MILLIS_PER_REAL_YEAR);
long unitMillis = MILLIS_PER_YEAR / 2;
long i2 = (ticks >> 1) + ((1970L * MILLIS_PER_YEAR) / 2);
if (i2 < 0)
{
i2 = i2 - unitMillis + 1;
}
int year = (int) (i2 / unitMillis);
long yearStart = millisToYearStart(year);
long diff = ticks - yearStart;
if (diff < 0)
{
year--;
}
else if (diff >= (MILLIS_PER_DAY * 365L))
{
// One year may need to be added to fix estimate.
long oneYear;
if (isLeapYear(year))
{
oneYear = MILLIS_PER_DAY * 366L;
}
else
{
oneYear = MILLIS_PER_DAY * 365L;
}
yearStart += oneYear;
if (yearStart <= ticks)
{
year++;
}
}
return year;
}
|
java
|
{
"resource": ""
}
|
q180410
|
TimeUtils.ticksWithHoursSetTo
|
test
|
public static long ticksWithHoursSetTo(long ticks, int hours)
{
long oldHours = ticksToHours(ticks);
return ticks - (oldHours * MILLIS_PER_HOUR) + (hours * MILLIS_PER_HOUR);
}
|
java
|
{
"resource": ""
}
|
q180411
|
TimeUtils.ticksWithMinutesSetTo
|
test
|
public static long ticksWithMinutesSetTo(long ticks, int minutes)
{
long oldMinutes = ticksToMinutes(ticks);
return ticks - (oldMinutes * MILLIS_PER_MINUTE) + (minutes * MILLIS_PER_MINUTE);
}
|
java
|
{
"resource": ""
}
|
q180412
|
TimeUtils.ticksWithSecondsSetTo
|
test
|
public static long ticksWithSecondsSetTo(long ticks, int seconds)
{
long oldSeconds = ticksToSeconds(ticks);
return ticks - (oldSeconds * MILLIS_PER_SECOND) + (seconds * MILLIS_PER_SECOND);
}
|
java
|
{
"resource": ""
}
|
q180413
|
TimeUtils.ticksWithYearSetTo
|
test
|
public static long ticksWithYearSetTo(long ticks, int year)
{
int oldYear = ticksToYears(ticks);
return ticks - millisToYearStart(oldYear) + millisToYearStart(year);
}
|
java
|
{
"resource": ""
}
|
q180414
|
TimeUtils.ticksWithMonthSetTo
|
test
|
public static long ticksWithMonthSetTo(long ticks, int month)
{
int year = ticksToYears(ticks);
boolean isLeapYear = isLeapYear(year);
int oldMonth = ticksToMonths(ticks);
return ticks - millisToStartOfMonth(oldMonth, isLeapYear) + millisToStartOfMonth(month, isLeapYear);
}
|
java
|
{
"resource": ""
}
|
q180415
|
TimeUtils.ticksWithDateSetTo
|
test
|
public static long ticksWithDateSetTo(long ticks, int date)
{
int oldDays = ticksToDate(ticks);
return ticks - (oldDays * MILLIS_PER_DAY) + (date * MILLIS_PER_DAY);
}
|
java
|
{
"resource": ""
}
|
q180416
|
TimeUtils.millisToYearStart
|
test
|
public static long millisToYearStart(int year)
{
// Calculate how many leap years elapsed prior to the year in question.
int leapYears = year / 100;
if (year < 0)
{
leapYears = ((year + 3) >> 2) - leapYears + ((leapYears + 3) >> 2) - 1;
}
else
{
leapYears = (year >> 2) - leapYears + (leapYears >> 2);
if (isLeapYear(year))
{
leapYears--;
}
}
return ((year * 365L) + leapYears - DAYS_TO_1970) * MILLIS_PER_DAY;
}
|
java
|
{
"resource": ""
}
|
q180417
|
TimeUtils.getMonthOfYear
|
test
|
private static int getMonthOfYear(long ticks, int year)
{
int i = (int) ((ticks - millisToYearStart(year)) >> 10);
return (isLeapYear(year))
? ((i < (182 * MILLIS_PER_DAY_OVER_1024))
? ((i < (91 * MILLIS_PER_DAY_OVER_1024))
? ((i < (31 * MILLIS_PER_DAY_OVER_1024)) ? 1 : ((i < (60 * MILLIS_PER_DAY_OVER_1024)) ? 2 : 3))
: ((i < (121 * MILLIS_PER_DAY_OVER_1024)) ? 4 : ((i < (152 * MILLIS_PER_DAY_OVER_1024)) ? 5 : 6)))
: ((i < (274 * MILLIS_PER_DAY_OVER_1024))
? ((i < (213 * MILLIS_PER_DAY_OVER_1024)) ? 7 : ((i < (244 * MILLIS_PER_DAY_OVER_1024)) ? 8 : 9))
: ((i < (305 * MILLIS_PER_DAY_OVER_1024)) ? 10
: ((i < (335 * MILLIS_PER_DAY_OVER_1024)) ? 11 : 12))))
: ((i < (181 * MILLIS_PER_DAY_OVER_1024))
? ((i < (90 * MILLIS_PER_DAY_OVER_1024))
? ((i < (31 * MILLIS_PER_DAY_OVER_1024)) ? 1 : ((i < (59 * MILLIS_PER_DAY_OVER_1024)) ? 2 : 3))
: ((i < (120 * MILLIS_PER_DAY_OVER_1024)) ? 4 : ((i < (151 * MILLIS_PER_DAY_OVER_1024)) ? 5 : 6)))
: ((i < (273 * MILLIS_PER_DAY_OVER_1024))
? ((i < (212 * MILLIS_PER_DAY_OVER_1024)) ? 7 : ((i < (243 * MILLIS_PER_DAY_OVER_1024)) ? 8 : 9))
: ((i < (304 * MILLIS_PER_DAY_OVER_1024)) ? 10
: ((i < (334 * MILLIS_PER_DAY_OVER_1024)) ? 11 : 12))));
}
|
java
|
{
"resource": ""
}
|
q180418
|
DistributedInputStreamImpl.read
|
test
|
public ByteBlock read(byte[] b) throws IOException
{
int count = source.read(b);
return new ByteBlock(b, count);
}
|
java
|
{
"resource": ""
}
|
q180419
|
SequentialCuckooFunction.applyWithEntry
|
test
|
private Integer applyWithEntry(K key, Entry<K> entry, boolean tryRehashing)
{
// Used to hold a new entry if one has to be created, or can re-use an entry passed in as a parameter.
Entry<K> uninsertedEntry = entry;
// Holds a flag to indicate that a new sequence number has been taken.
boolean createdNewEntry = false;
// Check if there is already an entry for the key, and return it if so.
Entry<K> existingEntry = entryForKey(key);
Integer result = null;
if (existingEntry != null)
{
result = existingEntry.seq;
}
else
{
// Create a new entry, if one has not already been created and cached.
if (uninsertedEntry == null)
{
uninsertedEntry = new Entry<K>();
uninsertedEntry.key = key;
uninsertedEntry.seq = nextSequenceNumber;
nextSequenceNumber++;
count++;
createdNewEntry = true;
result = uninsertedEntry.seq;
}
// Attempt to insert the new entry. The sequence number is only incremented when this succeeds for a new
// entry. Existing entries that are being re-hashed into a new table will not increment the sequence
// number.
while (true)
{
// Hash the entry for the current hash functions.
int keyHashCode = uninsertedEntry.key.hashCode();
uninsertedEntry.hash1 = hash1(keyHashCode);
uninsertedEntry.hash2 = hash2(uninsertedEntry.hash1, keyHashCode);
// Try and insert the entry, checking that no entry is left uninserted as a result.
uninsertedEntry = cuckoo(uninsertedEntry);
if (uninsertedEntry == null)
{
result = createdNewEntry ? result : -1;
break;
}
// If the cuckoo algorithm fails then change the hash function/table size and try again.
if (tryRehashing)
{
rehash();
}
else
{
result = null;
break;
}
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180420
|
SequentialCuckooFunction.entryForKey
|
test
|
private Entry<K> entryForKey(K key)
{
int keyHashCode = key.hashCode();
int hash1 = hash1(keyHashCode);
Entry<K> entry = hashTable[indexFor(hash1)];
if ((entry != null) && key.equals(entry.key))
{
return entry;
}
int hash2 = hash2(hash1, keyHashCode);
entry = hashTable[indexFor(hash2)];
if ((entry != null) && key.equals(entry.key))
{
return entry;
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180421
|
SequentialCuckooFunction.cuckoo
|
test
|
private Entry<K> cuckoo(Entry<K> entry)
{
// Holds the entry currently being placed in the hash table.
Entry<K> currentEntry = entry;
// Holds the index into the hash table where the current entry will be placed.
int hash = entry.hash1;
int index = indexFor(hash);
Entry<K> nextEntry = hashTable[index];
int previousFlag = 0;
int[] previousIndex = new int[2];
int[] previousSeq = new int[2];
for (int i = 0; i < hashTableSize; i++)
{
// Check the current index, to see if it is an empty slot. If it is an empty slot then the current
// entry is placed there and the algorithm completes.
if (nextEntry == null)
{
hashTable[index] = currentEntry;
return null;
}
// If the current index does not point to an empty slot, the current entry is placed there anyway, but the
// displaced entry (the egg displaced by the cuckoo) becomes the current entry for placing.
hashTable[index] = currentEntry;
currentEntry = nextEntry;
// A new index is selected depending on whether the entry is currently at its primary or secondary hashing.
int firstPosition = indexFor(currentEntry.hash1);
hash = (index == firstPosition) ? currentEntry.hash2 : currentEntry.hash1;
index = indexFor(hash);
// A check for infinite loops of size 2 is made here, to circumvent the simplest and most common infinite
// looping condition.
previousIndex[previousFlag] = index;
previousSeq[previousFlag] = nextEntry.seq;
previousFlag = (previousFlag == 1) ? 0 : 1;
nextEntry = hashTable[index];
if ((nextEntry != null) && (index == previousIndex[previousFlag]) &&
(nextEntry.seq == previousSeq[previousFlag]))
{
break;
}
}
return currentEntry;
}
|
java
|
{
"resource": ""
}
|
q180422
|
SequentialCuckooFunction.rehash
|
test
|
private void rehash()
{
// Increase the table size, to keep the load factory < 0.5.
int newSize = hashTableSize;
if (hashTableSize < (count * 2))
{
newSize = hashTableSize * 2;
if (newSize > maxSize)
{
throw new IllegalStateException("'newSize' of " + newSize +
" would put the table over the maximum size limit of " + maxSize);
}
}
// Keep hold of the old table, until a new one is succesfully buily.
Entry<K>[] oldTable = hashTable;
hashTableSize = newSize;
length = hashTable.length;
// Keep rehashing the table until it is succesfully rebuilt.
boolean rehashedOk;
do
{
// Start by assuming that this will work.
rehashedOk = true;
// Alter the hash functions.
changeHashFunctions();
// Create a new table from the old one, to rehash everything into.
hashTable = (Entry<K>[]) new Entry[hashTableSize];
for (Entry<K> entry : oldTable)
{
if (entry != null)
{
// Add the entry to the new table, dropping out if this fails.
if (applyWithEntry(entry.key, entry, false) == null)
{
rehashedOk = false;
break;
}
}
}
}
while (!rehashedOk);
}
|
java
|
{
"resource": ""
}
|
q180423
|
WorkPanel.actionPerformed
|
test
|
public void actionPerformed(ActionEvent event)
{
/*log.fine("void actionPerformed(ActionEvent): called");*/
/*log.fine("Action is " + event.getActionCommand());*/
// Check which action was performed
String action = event.getActionCommand();
if ("OK".equals(action))
{
// Check if the state is NOT_SAVED
if (state.getState().equals(WorkPanelState.NOT_SAVED))
{
// Save the work
saveWork();
}
}
else if ("Cancel".equals(action))
{
// Check if the state is NOT_SAVED
if (state.getState().equals(WorkPanelState.NOT_SAVED))
{
// Discard the work
discardWork();
}
}
else if ("Apply".equals(action))
{
// Check if the state is NOT_SAVED
if (state.getState().equals(WorkPanelState.NOT_SAVED))
{
// Save the work
saveWork();
}
}
}
|
java
|
{
"resource": ""
}
|
q180424
|
WorkFlowScreenState.setNextAvailable
|
test
|
public void setNextAvailable(boolean avail)
{
// Check if the state has changed
if (nextAvailable != avail)
{
// Keep the new state
nextAvailable = avail;
// Notify any listeners fo the change in state
firePropertyChange(new PropertyChangeEvent(this, "nextAvailable", !avail, avail));
}
}
|
java
|
{
"resource": ""
}
|
q180425
|
WorkFlowScreenState.setPrevAvailable
|
test
|
public void setPrevAvailable(boolean avail)
{
// Check if the state has changed
if (prevAvailable != avail)
{
// Keep the new state
prevAvailable = avail;
// Notify any listeners fo the change in state
firePropertyChange(new PropertyChangeEvent(this, "prevAvailable", !avail, avail));
}
}
|
java
|
{
"resource": ""
}
|
q180426
|
WorkFlowScreenState.setFinished
|
test
|
public void setFinished(boolean avail)
{
/*log.fine("void setFinished(boolean): called");*/
// Check if the state has changed
if (finished != avail)
{
// Keep the new state
finished = avail;
// Notify any listeners fo the change in state
firePropertyChange(new PropertyChangeEvent(this, "finished", !avail, avail));
/*log.fine("fired property change event");*/
}
}
|
java
|
{
"resource": ""
}
|
q180427
|
WAMResolvingNativeMachine.getInstance
|
test
|
public static WAMResolvingNativeMachine getInstance(SymbolTableImpl<Integer, String, Object> symbolTable)
throws ImplementationUnavailableException
{
try
{
if (!libraryLoadAttempted)
{
libraryLoadAttempted = true;
System.loadLibrary("aima_native");
libraryFound = true;
}
if (libraryFound)
{
return new WAMResolvingNativeMachine(symbolTable);
}
else
{
throw new ImplementationUnavailableException("The native library could not be found.", null, null,
null);
}
}
catch (UnsatisfiedLinkError e)
{
libraryFound = false;
throw new ImplementationUnavailableException("The native library could not be found.", e, null, null);
}
}
|
java
|
{
"resource": ""
}
|
q180428
|
WAMResolvingNativeMachine.iterator
|
test
|
public Iterator<Set<Variable>> iterator()
{
return new SequenceIterator<Set<Variable>>()
{
public Set<Variable> nextInSequence()
{
return resolve();
}
};
}
|
java
|
{
"resource": ""
}
|
q180429
|
InformationTheory.expectedI
|
test
|
public static double expectedI(double[] probabilities)
{
double result = 0.0d;
// Loop over the probabilities for all the symbols calculating the contribution of each to the expected value.
for (double p : probabilities)
{
// Calculate the information in each symbol. I(p) = - ln p and weight this by its probability of occurence
// to get that symbols contribution to the expected value over all symbols.
if (p > 0.0d)
{
result -= p * Math.log(p);
}
}
// Convert the result from nats to bits by dividing by ln 2.
return result / LN2;
}
|
java
|
{
"resource": ""
}
|
q180430
|
InformationTheory.pForDistribution
|
test
|
public static double[] pForDistribution(int[] counts)
{
double[] probabilities = new double[counts.length];
int total = 0;
// Loop over the counts for all symbols adding up the total number.
for (int c : counts)
{
total += c;
}
// Loop over the counts for all symbols dividing by the total number to provide a probability estimate.
for (int i = 0; i < probabilities.length; i++)
{
if (total > 0)
{
probabilities[i] = ((double) counts[i]) / total;
}
else
{
probabilities[i] = 0.0d;
}
}
return probabilities;
}
|
java
|
{
"resource": ""
}
|
q180431
|
DateOnly.setTicks
|
test
|
void setTicks(long ticks)
{
year = TimeUtils.ticksToYears(ticks);
month = TimeUtils.ticksToMonths(ticks);
day = TimeUtils.ticksToDate(ticks);
}
|
java
|
{
"resource": ""
}
|
q180432
|
SortAction.perform
|
test
|
public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
log.fine("perform: called");
// Reference the SortForm as a SortForm rather than the generic ActionForm
SortForm sortForm = (SortForm) form;
// Get a reference to the session scope
HttpSession session = request.getSession();
// Get a reference to the application scope
ServletContext application = session.getServletContext();
log.fine("variables in the servlet context: ");
for (Enumeration e = application.getAttributeNames(); e.hasMoreElements();)
{
log.fine(e.nextElement().toString());
}
// Get a reference to the list to be sorted
List list = (List) session.getAttribute(sortForm.getList());
// Get a reference to the comparator from the application scope to use to perform the sort
Comparator comparator = (Comparator) application.getAttribute(sortForm.getComparator());
log.fine("comparator = " + comparator);
// Get a reference to the current sort state (if there is one)
SortStateBean sortStateBean = (SortStateBean) session.getAttribute(sortForm.getSortState());
// Check if there is no sort state bean and create one if so
if (sortStateBean == null)
{
log.fine("There is no sort state bean");
sortStateBean = new SortStateBean();
}
// Determine whether a forward or reverse sort is to be done
// If its reverse sorted, unsorted or not sorted by the current sort property then forward sort it
if (!sortStateBean.getState().equals(SortStateBean.FORWARD) ||
!sortStateBean.getSortProperty().equals(sortForm.getSortStateProperty()))
{
// Sort the list
Collections.sort(list, comparator);
// Update the current sort state
sortStateBean.setState(SortStateBean.FORWARD);
}
// If its already forward sorted then reverse sort it
else
{
// Sort the list
Collections.sort(list, comparator);
// Reverse the list
Collections.reverse(list);
// Update the current sort state
sortStateBean.setState(SortStateBean.REVERSE);
}
// Store the sorted list in the variable from which the original list was taken
session.setAttribute(sortForm.getList(), list);
// Store the new sort state, setting the property that has been sorted by in the sort state
sortStateBean.setSortProperty(sortForm.getSortStateProperty());
session.setAttribute(sortForm.getSortState(), sortStateBean);
// Forward to the success page
return (mapping.findForward("success"));
}
|
java
|
{
"resource": ""
}
|
q180433
|
Urls.newUrl
|
test
|
public static URL newUrl(String spec)
{
try
{
return new URL(spec);
}
catch (MalformedURLException exception)
{
throw new IllegalArgumentException("Invalid URL: " + spec);
}
}
|
java
|
{
"resource": ""
}
|
q180434
|
DebugTag.getRequestInfo
|
test
|
public String getRequestInfo()
{
Map info = new TreeMap();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
info.put("authType", nullToString(req.getAuthType()));
info.put("characterEncoding", nullToString(req.getCharacterEncoding()));
info.put("contentLength", Integer.toString(req.getContentLength()));
info.put("contentType", nullToString(req.getContentType()));
info.put("contextPath", nullToString(req.getContextPath()));
info.put("pathInfo", nullToString(req.getPathInfo()));
info.put("protocol", nullToString(req.getProtocol()));
info.put("queryString", nullToString(req.getQueryString()));
info.put("remoteAddr", nullToString(req.getRemoteAddr()));
info.put("remoteHost", nullToString(req.getRemoteHost()));
info.put("remoteUser", nullToString(req.getRemoteUser()));
info.put("requestURI", nullToString(req.getRequestURI()));
info.put("scheme", nullToString(req.getScheme()));
info.put("serverName", nullToString(req.getServerName()));
info.put("serverPort", Integer.toString(req.getServerPort()));
info.put("servletPath", nullToString(req.getServletPath()));
return toHTMLTable("request properties", info);
}
|
java
|
{
"resource": ""
}
|
q180435
|
DebugTag.getHeaders
|
test
|
public String getHeaders()
{
Map info = new TreeMap();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
Enumeration names = req.getHeaderNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
Enumeration values = req.getHeaders(name);
StringBuffer sb = new StringBuffer();
boolean first = true;
while (values.hasMoreElements())
{
if (!first)
{
sb.append(" | ");
}
first = false;
sb.append(values.nextElement());
}
info.put(name, sb.toString());
}
return toHTMLTable("headers", info);
}
|
java
|
{
"resource": ""
}
|
q180436
|
DebugTag.getCookies
|
test
|
public String getCookies()
{
Map info = new TreeMap();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
Cookie[] cookies = req.getCookies();
// check that cookies is not null which it may be if there are no cookies
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
Cookie cooky = cookies[i];
info.put(cooky.getName(), cooky.getValue());
}
}
return toHTMLTable("cookies", info);
}
|
java
|
{
"resource": ""
}
|
q180437
|
DebugTag.getParameters
|
test
|
public String getParameters()
{
Map info = new TreeMap();
ServletRequest req = (HttpServletRequest) pageContext.getRequest();
Enumeration names = req.getParameterNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
String[] values = req.getParameterValues(name);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < values.length; i++)
{
if (i != 0)
{
sb.append(" | ");
}
sb.append(values[i]);
}
info.put(name, sb.toString());
}
return toHTMLTable("request parameters", info);
}
|
java
|
{
"resource": ""
}
|
q180438
|
DebugTag.getRequestScope
|
test
|
public String getRequestScope()
{
Map info = new TreeMap();
ServletRequest req = (HttpServletRequest) pageContext.getRequest();
Enumeration names = req.getAttributeNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
Object value = req.getAttribute(name);
info.put(name, toStringValue(value));
}
return toHTMLTable("request scope", info);
}
|
java
|
{
"resource": ""
}
|
q180439
|
DebugTag.getPageScope
|
test
|
public String getPageScope()
{
Map info = new TreeMap();
Enumeration names = pageContext.getAttributeNamesInScope(PageContext.PAGE_SCOPE);
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
Object value = pageContext.getAttribute(name);
info.put(name, toStringValue(value));
}
return toHTMLTable("page scope", info);
}
|
java
|
{
"resource": ""
}
|
q180440
|
DebugTag.getSessionScope
|
test
|
public String getSessionScope()
{
Map info = new TreeMap();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
HttpSession session = req.getSession();
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
Object value = session.getAttribute(name);
info.put(name, toStringValue(value));
}
return toHTMLTable("session scope", info);
}
|
java
|
{
"resource": ""
}
|
q180441
|
DebugTag.getApplicationScope
|
test
|
public String getApplicationScope()
{
Map info = new TreeMap();
ServletContext context = pageContext.getServletContext();
Enumeration names = context.getAttributeNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
Object value = context.getAttribute(name);
info.put(name, toStringValue(value));
}
return toHTMLTable("application scope", info);
}
|
java
|
{
"resource": ""
}
|
q180442
|
DebugTag.getUserPrincipal
|
test
|
public String getUserPrincipal()
{
// Create a hash table to hold the results in
Map info = new TreeMap();
// Extract the request from the page context
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
// Get the principal from the request
Principal principal = request.getUserPrincipal();
// Check if there is a principal
if (principal != null)
{
info.put("principal name", principal.getName());
}
else
{
info.put("principal name", "no principal");
}
// Convert the results to an HTML table
return toHTMLTable("container security", info);
}
|
java
|
{
"resource": ""
}
|
q180443
|
DebugTag.doStartTag
|
test
|
public int doStartTag() throws JspException
{
log.fine("doStartTag: called");
try
{
// Write out the beggining of the debug table
pageContext.getResponse().getWriter().write("<table class=\"debug\" width=\"100%\" border=\"1\">");
// Write out the debugging info for all categories
pageContext.getResponse().getWriter().write(getRequestInfo());
pageContext.getResponse().getWriter().write(getHeaders());
pageContext.getResponse().getWriter().write(getCookies());
pageContext.getResponse().getWriter().write(getParameters());
pageContext.getResponse().getWriter().write(getRequestScope());
pageContext.getResponse().getWriter().write(getPageScope());
pageContext.getResponse().getWriter().write(getSessionScope());
pageContext.getResponse().getWriter().write(getApplicationScope());
pageContext.getResponse().getWriter().write(getUserPrincipal());
// Write out the closing of the debug table
pageContext.getResponse().getWriter().write("</table>");
}
catch (IOException e)
{
throw new JspException("Got an IOException whilst writing the debug tag to the page.", e);
}
// Continue processing the page
return (EVAL_BODY_INCLUDE);
}
|
java
|
{
"resource": ""
}
|
q180444
|
DebugTag.toHTMLTable
|
test
|
private String toHTMLTable(String propName, Map values)
{
StringBuffer tableSB = new StringBuffer();
tableSB.append("<tr class=\"debug\"><th class=\"debug\">").append(propName).append("</th></tr>");
for (Iterator it = values.keySet().iterator(); it.hasNext();)
{
Object o = it.next();
String key = (String) o;
tableSB.append("<tr class=\"debug\"><td class=\"debug\">").append(key).append("</td><td>").append(
values.get(key)).append("</td></tr>");
}
return tableSB.toString();
}
|
java
|
{
"resource": ""
}
|
q180445
|
BoundedAlgorithm.search
|
test
|
public SearchNode search(QueueSearchState<O, T> initSearch, Collection<T> startStates, int maxSteps,
int searchSteps) throws SearchNotExhaustiveException
{
// Initialize the queue with the start states set up in search nodes.
Queue<SearchNode<O, T>> queue = initSearch.enqueueStartStates(startStates);
// Get the goal predicate configured as part of the enqueueing start states process.
UnaryPredicate<T> goalPredicate = initSearch.getGoalPredicate();
// Flag used to indicate whether there are unexplored successor states known to exist beyond the max depth
// fringe.
boolean beyondFringe = false;
// Reset the minimum beyond the fringe boundary value.
minBeyondBound = Float.POSITIVE_INFINITY;
// Keep running until the queue becomes empty or a goal state is found.
while (!queue.isEmpty())
{
// Extract the head element from the queue.
SearchNode<O, T> headNode = peekAtHead ? queue.peek() : queue.remove();
// Expand the successors into the queue whether the current node is a goal state or not.
// This prepares the queue for subsequent searches, ensuring that goal states do not block
// subsequent goal states that exist beyond them.
// Add the successors to the queue provided that they are below or at the maximum bounded property.
// Get all the successor states.
Queue<SearchNode<O, T>> successors = new LinkedList<SearchNode<O, T>>();
headNode.expandSuccessors(successors, reverseEnqueue);
// Loop over all the successor states checking how they stand with respect to the bounded property.
for (SearchNode<O, T> successor : successors)
{
// Get the value of the bound property for the successor node.
float boundProperty = boundPropertyExtractor.getBoundProperty(successor);
// Check if the successor is below or on the bound.
if (boundProperty <= maxBound)
{
// Add it to the queue to be searched.
queue.offer(successor);
}
// The successor state is above the bound.
else
{
// Set the flag to indicate that there is at least one search node known to exist beyond the
// bound.
beyondFringe = true;
// Compare to the best minimum beyond the bound property found so far to see if
// this is a new minimum and update the minimum to the new minimum if so.
minBeyondBound = (boundProperty < minBeyondBound) ? boundProperty : minBeyondBound;
}
}
// Get the node to be goal checked, either the head node or the new top of queue, depending on the
// peek at head flag.
SearchNode<O, T> currentNode = peekAtHead ? queue.remove() : headNode;
// Check if the current node is a goal state.
// Only goal check leaves, or nodes already expanded. (The expanded flag will be set on leaves anyway).
if (currentNode.isExpanded() && goalPredicate.evaluate(currentNode.getState()))
{
return currentNode;
}
// Check if there is a maximum number of steps limit and increase the step count and check the limit if so.
if (maxSteps > 0)
{
// Increase the search step count because a goal test was performed.
searchSteps++;
// Update the search state with the number of steps taken so far.
initSearch.setStepsTaken(searchSteps);
if (searchSteps >= maxSteps)
{
// The maximum number of steps has been reached, however if the queue is now empty then the search
// has just completed within the maximum. Check if the queue is empty and return null if so.
if (queue.isEmpty())
{
return null;
}
// Quit without a solution as the max number of steps has been reached but because there are still
// more states in the queue then raise a search failure exception.
else
{
throw new SearchNotExhaustiveException("Maximum number of steps reached.", null);
}
}
}
}
// No goal state was found. Check if there known successors beyond the max depth fringe and if so throw
// a SearchNotExhaustiveException to indicate that the search failed rather than exhausted the search space.
if (beyondFringe)
{
throw new MaxBoundException("Max bound reached.", null);
}
else
{
// The search space was exhausted so return null to indicate that no goal could be found.
return null;
}
}
|
java
|
{
"resource": ""
}
|
q180446
|
WorkFlowState.setCurrentScreenState
|
test
|
public void setCurrentScreenState(WorkFlowScreenState state)
{
/*log.fine("void setCurrentScreenState(WorkFlowScreenState): called");*/
WorkFlowScreenState oldState = currentScreenState;
// Keep the new state.
currentScreenState = state;
// Notify all listeners of the change of current screen.
firePropertyChange(new PropertyChangeEvent(this, "currentScreenState", oldState, state));
}
|
java
|
{
"resource": ""
}
|
q180447
|
TermWalker.walk
|
test
|
public void walk(Term term)
{
// Set up the traverser on the term to walk over.
term.setTermTraverser(traverser);
// Create a fresh search starting from the term.
search.reset();
if (goalPredicate != null)
{
search.setGoalPredicate(goalPredicate);
}
search.addStartState(term);
Iterator<Term> treeWalker = Searches.allSolutions(search);
// If the traverser is a term visitor, allow it to visit the top-level term in the walk to establish
// an initial context.
if (traverser instanceof TermVisitor)
{
term.accept((TermVisitor) traverser);
}
// Visit every goal node discovered in the walk over the term.
while (treeWalker.hasNext())
{
Term nextTerm = treeWalker.next();
nextTerm.accept(visitor);
}
// Remote the traverser on the term to walk over.
term.setTermTraverser(null);
}
|
java
|
{
"resource": ""
}
|
q180448
|
AStarComparator.compare
|
test
|
public int compare(SearchNode object1, SearchNode object2)
{
float f1 = ((HeuristicSearchNode) object1).getF();
float f2 = ((HeuristicSearchNode) object2).getF();
return (f1 > f2) ? 1 : ((f1 < f2) ? -1 : 0);
}
|
java
|
{
"resource": ""
}
|
q180449
|
InternalRegisterBean.updateRegisters
|
test
|
public void updateRegisters(WAMInternalRegisters registers)
{
List<PropertyChangeEvent> changes = delta(this, registers);
ip = registers.ip;
hp = registers.hp;
hbp = registers.hbp;
sp = registers.sp;
up = registers.up;
ep = registers.ep;
bp = registers.bp;
b0 = registers.b0;
trp = registers.trp;
writeMode = registers.writeMode;
notifyChanges(changes);
}
|
java
|
{
"resource": ""
}
|
q180450
|
InternalRegisterBean.notifyChanges
|
test
|
private void notifyChanges(Iterable<PropertyChangeEvent> changes)
{
List<PropertyChangeListener> activeListeners = listeners.getActiveListeners();
if (activeListeners != null)
{
for (PropertyChangeListener listener : activeListeners)
{
for (PropertyChangeEvent event : changes)
{
listener.propertyChange(event);
}
}
}
}
|
java
|
{
"resource": ""
}
|
q180451
|
PositionAndOccurrenceVisitor.leaveClause
|
test
|
protected void leaveClause(Clause clause)
{
// Remove the set of constants appearing in argument positions, from the set of all constants, to derive
// the set of constants that appear in non-argument positions only.
constants.keySet().removeAll(argumentConstants);
// Set the nonArgPosition flag on all symbol keys for all constants that only appear in non-arg positions.
for (List<SymbolKey> symbolKeys : constants.values())
{
for (SymbolKey symbolKey : symbolKeys)
{
symbolTable.put(symbolKey, SymbolTableKeys.SYMKEY_FUNCTOR_NON_ARG, true);
}
}
}
|
java
|
{
"resource": ""
}
|
q180452
|
PositionAndOccurrenceVisitor.inTopLevelFunctor
|
test
|
private boolean inTopLevelFunctor(PositionalContext context)
{
PositionalContext parentContext = context.getParentContext();
return parentContext.isTopLevel() || isTopLevel(parentContext);
}
|
java
|
{
"resource": ""
}
|
q180453
|
AbstractHeap.toArray
|
test
|
public <T> T[] toArray(T[] a)
{
int size = size();
if (a.length < size)
{
a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
}
Iterator<E> it = iterator();
Object[] result = a;
for (int i = 0; i < size; i++)
{
result[i] = it.next();
}
if (a.length > size)
{
a[size] = null;
}
return a;
}
|
java
|
{
"resource": ""
}
|
q180454
|
OpSymbol.setArguments
|
test
|
public void setArguments(Term[] arguments)
{
// Check that there is at least one and at most two arguments.
if ((arguments == null) || (arguments.length < 1) || (arguments.length > 2))
{
throw new IllegalArgumentException("An operator has minimum 1 and maximum 2 arguments.");
}
this.arguments = arguments;
this.arity = arguments.length;
}
|
java
|
{
"resource": ""
}
|
q180455
|
OpSymbol.getFixity
|
test
|
public Fixity getFixity()
{
switch (associativity)
{
case FX:
case FY:
return Fixity.Pre;
case XF:
case YF:
return Fixity.Post;
case XFX:
case XFY:
case YFX:
return Fixity.In;
default:
throw new IllegalStateException("Unknown associativity.");
}
}
|
java
|
{
"resource": ""
}
|
q180456
|
OpSymbol.isInfix
|
test
|
public boolean isInfix()
{
return ((associativity == Associativity.XFY) || (associativity == Associativity.YFX) ||
(associativity == Associativity.XFX));
}
|
java
|
{
"resource": ""
}
|
q180457
|
OpSymbol.compareTo
|
test
|
public int compareTo(Object o)
{
OpSymbol opSymbol = (OpSymbol) o;
return (priority < opSymbol.priority) ? -1 : ((priority > opSymbol.priority) ? 1 : 0);
}
|
java
|
{
"resource": ""
}
|
q180458
|
WorkFlowButtonsPanel.propertyChange
|
test
|
public void propertyChange(PropertyChangeEvent event)
{
/*log.fine("void propertyChange(PropertyChangeEvent): called");*/
/*log.fine("source class = " + event.getSource().getClass());*/
/*log.fine("source object = " + event.getSource());*/
/*log.fine("property name = " + event.getPropertyName());*/
/*log.fine("new value = " + event.getNewValue());*/
/*log.fine("old value = " + event.getOldValue());*/
Object source = event.getSource();
Object oldValue = event.getOldValue();
String propertyName = event.getPropertyName();
// Check if the event source is an individual screen state
if (source instanceof WorkFlowScreenState)
{
WorkFlowScreenState wfsState = (WorkFlowScreenState) source;
// Update the buttons to reflect the change in screen state
updateButtonsForScreen(wfsState);
}
// Check if the event source is the whole work flow
if (source instanceof WorkFlowState)
{
WorkFlowState wfState = (WorkFlowState) source;
// Check if the event cause is a change in current screen
if ("currentScreenState".equals(propertyName))
{
WorkFlowScreenState newScreenState = wfState.getCurrentScreenState();
WorkFlowScreenState oldScreenState = (WorkFlowScreenState) oldValue;
// De-register this as a listener for the old current screen state
if (oldScreenState != null)
{
oldScreenState.removePropertyChangeListener(this);
}
// Register this as a listener for the new current screen state
if (newScreenState != null)
{
newScreenState.addPropertyChangeListener(this);
}
// Update the buttons to reflect the current screen state
updateButtonsForScreen(newScreenState);
}
// Check if the event cause is a change in the work flow state
else if ("state".equals(propertyName))
{
// Update the buttons to reflect the change in state
updateButtonsForWorkFlow(wfState);
}
}
}
|
java
|
{
"resource": ""
}
|
q180459
|
WorkFlowButtonsPanel.registerWorkFlowController
|
test
|
public void registerWorkFlowController(WorkFlowController controller)
{
// Set the work flow controller to listen for button events
backButton.addActionListener(controller);
nextButton.addActionListener(controller);
finishButton.addActionListener(controller);
cancelButton.addActionListener(controller);
// Register this to listen for changes to the work flow state
controller.getWorkFlowState().addPropertyChangeListener(this);
// Register this to listen for changes to the state for the current screen if it is not null
WorkFlowScreenState currentScreenState = controller.getWorkFlowState().getCurrentScreenState();
if (currentScreenState != null)
{
currentScreenState.addPropertyChangeListener(this);
}
}
|
java
|
{
"resource": ""
}
|
q180460
|
EnumAttribute.getFactoryForClass
|
test
|
public static EnumAttributeFactory getFactoryForClass(Class cls)
{
// Check that the requested class is actually an enum.
if (!cls.isEnum())
{
throw new IllegalArgumentException("Can only create enum attribute factories for classes that are enums.");
}
return EnumClassImpl.getInstance(cls);
}
|
java
|
{
"resource": ""
}
|
q180461
|
ComponentFactoryBuilder.createComponentFactory
|
test
|
public static ComponentFactory createComponentFactory(String className)
{
return (ComponentFactory) ReflectionUtils.newInstance(ReflectionUtils.forName(className));
}
|
java
|
{
"resource": ""
}
|
q180462
|
StackVariable.getStorageCell
|
test
|
public Variable getStorageCell(Variable variable)
{
VariableBindingContext<Variable> context = getBindingContext();
if (context == null)
{
return null;
}
else
{
return context.getStorageCell(this);
}
}
|
java
|
{
"resource": ""
}
|
q180463
|
StackVariable.isBound
|
test
|
public boolean isBound()
{
VariableBindingContext<Variable> context = getBindingContext();
// The variable can only be bound if it has a binding context and is bound in that context.
return (context != null) && context.getStorageCell(this).isBound();
}
|
java
|
{
"resource": ""
}
|
q180464
|
AttributeGridImpl.setColumnAttribute
|
test
|
private void setColumnAttribute(AttributeSet attributes, int c)
{
if (c >= columnAttributes.size())
{
for (int i = columnAttributes.size(); i <= c; i++)
{
columnAttributes.add(null);
}
}
columnAttributes.set(c, attributes);
}
|
java
|
{
"resource": ""
}
|
q180465
|
AttributeGridImpl.setRowAttribute
|
test
|
private void setRowAttribute(AttributeSet attributes, int r)
{
if (r >= rowAttributes.size())
{
for (int i = rowAttributes.size(); i <= r; i++)
{
rowAttributes.add(null);
}
}
rowAttributes.set(r, attributes);
}
|
java
|
{
"resource": ""
}
|
q180466
|
AttributeGridImpl.getColumnAttributeOrNull
|
test
|
private AttributeSet getColumnAttributeOrNull(int c)
{
if ((c >= 0) && (c < columnAttributes.size()))
{
return columnAttributes.get(c);
}
else
{
return null;
}
}
|
java
|
{
"resource": ""
}
|
q180467
|
AttributeGridImpl.getRowAttributeOrNull
|
test
|
private AttributeSet getRowAttributeOrNull(int r)
{
if ((r >= 0) && (r < rowAttributes.size()))
{
return rowAttributes.get(r);
}
else
{
return null;
}
}
|
java
|
{
"resource": ""
}
|
q180468
|
AttributeGridImpl.internalInsert
|
test
|
private void internalInsert(AttributeSet attributes, int c, int r)
{
cellAttributes.put((long) c, (long) r, attributes);
}
|
java
|
{
"resource": ""
}
|
q180469
|
TimeRangeType.createInstance
|
test
|
public static Type createInstance(String name, TimeOnly min, TimeOnly max)
{
// Ensure that min is less than or equal to max.
if ((min != null) && (max != null) && (min.compareTo(max) > 0))
{
throw new IllegalArgumentException("'min' must be less than or equal to 'max'.");
}
synchronized (INT_RANGE_TYPES)
{
// Add the newly created type to the map of all types.
TimeRangeType newType = new TimeRangeType(name, min, max);
// Ensure that the named type does not already exist, unless it has an identical definition already, in which
// case the old definition can be re-used and the new one discarded.
TimeRangeType oldType = INT_RANGE_TYPES.get(name);
if ((oldType != null) && !oldType.equals(newType))
{
throw new IllegalArgumentException("The type '" + name + "' already exists and cannot be redefined.");
}
else if ((oldType != null) && oldType.equals(newType))
{
return oldType;
}
else
{
INT_RANGE_TYPES.put(name, newType);
return newType;
}
}
}
|
java
|
{
"resource": ""
}
|
q180470
|
StringPatternType.createInstance
|
test
|
public static Type createInstance(String name, int maxLength, String pattern)
{
synchronized (STRING_PATTERN_TYPES)
{
StringPatternType newType = new StringPatternType(name, maxLength, pattern);
// Ensure that the named type does not already exist.
StringPatternType oldType = STRING_PATTERN_TYPES.get(name);
if ((oldType != null) && !oldType.equals(newType))
{
throw new IllegalArgumentException("The type '" + name + "' already exists and cannot be redefined.");
}
else if ((oldType != null) && oldType.equals(newType))
{
return oldType;
}
else
{
// Add the newly created type to the map of all types.
STRING_PATTERN_TYPES.put(name, newType);
return newType;
}
}
}
|
java
|
{
"resource": ""
}
|
q180471
|
StringPatternType.isInstance
|
test
|
public boolean isInstance(CharSequence value)
{
// Check the value is under the maximum if one is set.
// Check the value matches the pattern if one is set.
return ((maxLength <= 0) || (value.length() <= maxLength)) && compiledPattern.matcher(value).matches();
}
|
java
|
{
"resource": ""
}
|
q180472
|
PositionalTermTraverserImpl.createInitialContext
|
test
|
private void createInitialContext(Term term)
{
if (!initialContextCreated)
{
PositionalContextOperator initialContext =
new PositionalContextOperator(term, -1, false, false, false, null, contextStack.peek());
contextStack.offer(initialContext);
term.setReversable(initialContext);
initialContextCreated = true;
}
}
|
java
|
{
"resource": ""
}
|
q180473
|
InternalMemoryLayoutBean.updateRegisters
|
test
|
public void updateRegisters(WAMMemoryLayout layout)
{
List<PropertyChangeEvent> changes = delta(this, layout);
regBase = layout.regBase;
regSize = layout.regSize;
heapBase = layout.heapBase;
heapSize = layout.heapSize;
stackBase = layout.stackBase;
stackSize = layout.stackSize;
trailBase = layout.trailBase;
trailSize = layout.trailSize;
pdlBase = layout.pdlBase;
pdlSize = layout.pdlSize;
notifyChanges(changes);
}
|
java
|
{
"resource": ""
}
|
q180474
|
VariableReferenceNode.getValue
|
test
|
public String getValue() {
for (ScopeNode scope = NodeTreeUtils.getParentScope(this); scope != null; scope = NodeTreeUtils.getParentScope(scope)) {
ExpressionGroupNode value = scope.getVariable(_name);
if (value == null) {
continue;
}
return value.toString();
}
return _name; // Unable to find the variable's value, return the name for now (helpful for debugging)
}
|
java
|
{
"resource": ""
}
|
q180475
|
BaseBiDirectionalQueueSearch.findGoalPath
|
test
|
public SearchNode<O, T> findGoalPath() throws SearchNotExhaustiveException
{
// Keep running until the queue becomes empty or a goal state is found
while (!forwardQueue.isEmpty() || !reverseQueue.isEmpty())
{
// Only run the forward step of the search if the forward queue is not empty
if (!forwardQueue.isEmpty())
{
// Extract the next node from the forward queue
SearchNode<O, T> currentForwardNode = forwardQueue.remove();
// Remove this node from the forward fringe map as it will soon be replaced by more fringe members
forwardFringe.remove(currentForwardNode.getState());
// Check the reverse fringe against the next forward node for a match.
if (reverseFringe.containsKey(currentForwardNode.getState()))
{
// A path from start to the goal has been found. Walk backwards along the reverse path adding all
// nodes encountered to the forward path until the goal is reached.
return joinBothPaths(currentForwardNode, reverseFringe.get(currentForwardNode.getState()));
}
// There was no match so a path to the goal has not been found
else
{
// Get all of the successor states to the current node
Queue<SearchNode<O, T>> newStates = new LinkedList<SearchNode<O, T>>();
currentForwardNode.expandSuccessors(newStates, false);
// Expand all the successors to the current forward node into the buffer to be searched.
forwardQueue.addAll(newStates);
// Also add all the successors to the current forward fringe map.
for (SearchNode<O, T> nextSearchNode : newStates)
{
forwardFringe.put(nextSearchNode.getState(), nextSearchNode);
}
}
}
// Only run the reverse step of the search if the reverse queue is not empty
if (!reverseQueue.isEmpty())
{
// Extract the next node from the reverse queue
SearchNode<O, T> currentReverseNode = reverseQueue.remove();
// Remove this node from the reverse fringe set as it will soon be replaced by more fringe members
reverseFringe.remove(currentReverseNode.getState());
// Check the forward fringe against the next reverse node for a match.
if (forwardFringe.containsKey(currentReverseNode.getState()))
{
// A path from start to goal has been found.
// Walk backwards along the reverse path adding all nodes encountered to the foward path until the
// goal is reached.
return joinBothPaths(forwardFringe.get(currentReverseNode.getState()), currentReverseNode);
}
// There was no match so a path to the goal has not been found
else
{
// Get all of the successor states to the current node (really predecessor state)
Queue<SearchNode<O, T>> newStates = new LinkedList<SearchNode<O, T>>();
currentReverseNode.expandSuccessors(newStates, false);
// Expand all the successors to the current reverse node into the reverse buffer to be searched.
reverseQueue.addAll(newStates);
// Add all the successors to the current reverse fringe set
for (SearchNode<O, T> nextSearchNode : newStates)
{
reverseFringe.put(nextSearchNode.getState(), nextSearchNode);
}
}
}
}
// No goal state was found so return null
return null;
}
|
java
|
{
"resource": ""
}
|
q180476
|
BaseBiDirectionalQueueSearch.joinBothPaths
|
test
|
private SearchNode<O, T> joinBothPaths(SearchNode<O, T> forwardPath, SearchNode<O, T> reversePath)
throws SearchNotExhaustiveException
{
// Check if an alternative path join algorithm has been set and delegate to it if so
if (pathJoiner != null)
{
return pathJoiner.joinBothPaths(forwardPath, reversePath);
}
// No alternative path join algorithm has been supplied so use this default one
else
{
// Used to hold the current position along the reverse path of search nodes
SearchNode<O, T> currentReverseNode = reversePath;
// Used to hold the current position along the forward path of search nodes
SearchNode<O, T> currentForwardNode = forwardPath;
// Loop over all nodes in the reverse path checking if the current reverse node is the
// goal state to terminate on.
while (!goalPredicate.evaluate(currentReverseNode.getState()))
{
// Create a new forward node from the parent state of the current reverse node, the current reverse
// nodes applied operation and cost, and an increment of one to the path depth
SearchNode<O, T> reverseParentNode = currentReverseNode.getParent();
T state = currentReverseNode.getParent().getState();
Operator<O> operation = currentReverseNode.getAppliedOp();
float cost = currentReverseNode.getPathCost() - reverseParentNode.getPathCost();
currentForwardNode = currentForwardNode.makeNode(new Successor<O>(state, operation, cost));
// Move one step up the reverse path
currentReverseNode = reverseParentNode;
}
// Return the last forward search node found
return currentForwardNode;
}
}
|
java
|
{
"resource": ""
}
|
q180477
|
LazyPagingList.cacheBlock
|
test
|
public List<T> cacheBlock(int block)
{
/*log.fine("public List<T> cacheBlock(int block): called");*/
// Get the new block.
List<T> blockList = getBlock(block * blockSize, blockSize);
// Cache it.
blockMap.put(block, blockList);
/*log.fine("Cached block " + block + " with list of size " + blockList.size());*/
return blockList;
}
|
java
|
{
"resource": ""
}
|
q180478
|
DefaultPropertyReader.getProperties
|
test
|
public static synchronized Properties getProperties(String resourceName)
{
/*log.fine("public static synchronized Properties getProperties(String resourceName): called");*/
/*log.fine("resourceName = " + resourceName);*/
// Try to find an already created singleton property reader for the resource
PropertyReaderBase propertyReader = (PropertyReaderBase) propertyReaders.get(resourceName);
if (propertyReader != null)
{
/*log.fine("found property reader in the cache for resource: " + resourceName);*/
return propertyReader.getProperties();
}
/*log.fine("did not find property reader in the cache for resource: " + resourceName);*/
// There is not already a singleton for the named resource so create a new one
propertyReader = new DefaultPropertyReader(resourceName);
// Keep the newly created singleton for next time
propertyReaders.put(resourceName, propertyReader);
return propertyReader.getProperties();
}
|
java
|
{
"resource": ""
}
|
q180479
|
BatchedThrottle.setRate
|
test
|
public void setRate(float hertz)
{
// Pass the rate unaltered down to the base implementation, for the check method.
super.setRate(hertz);
// Log base 10 over 2 is used here to get a feel for what power of 100 the total rate is.
// As the total rate goes up the powers of 100 the batch size goes up by powers of 100 to keep the
// throttle rate in the range 1 to 100.
int x = (int) (Math.log10(hertz) / 2);
batchSize = (int) Math.pow(100, x);
float throttleRate = hertz / batchSize;
// Reset the call count.
callCount = 0;
// Set the sleep throttle wrapped implementation at a rate within its abilities.
batchRateThrottle.setRate(throttleRate);
}
|
java
|
{
"resource": ""
}
|
q180480
|
ClientInputStream.read
|
test
|
public int read(byte[] b) throws IOException
{
try
{
ByteBlock block = source.read(b);
System.arraycopy(block.data, 0, b, 0, block.count);
return block.count;
}
catch (RemoteException e)
{
throw new IOException("There was a Remote Exception.", e);
}
}
|
java
|
{
"resource": ""
}
|
q180481
|
ClientInputStream.skip
|
test
|
public long skip(long n) throws IOException
{
try
{
return source.skip(n);
}
catch (RemoteException e)
{
throw new IOException("There was a Remote Exception.", e);
}
}
|
java
|
{
"resource": ""
}
|
q180482
|
Disjunction.gatherDisjunctions
|
test
|
private void gatherDisjunctions(Disjunction disjunction, List<Term> expressions)
{
// Left argument.
gatherDisjunctionsExploreArgument(disjunction.getArguments()[0], expressions);
// Right argument.
gatherDisjunctionsExploreArgument(disjunction.getArguments()[1], expressions);
}
|
java
|
{
"resource": ""
}
|
q180483
|
ByteBufferUtils.getIntFromBytes
|
test
|
public static int getIntFromBytes(byte[] buf, int offset)
{
int result = 0;
result += buf[offset++] & 0xFF;
result += ((buf[offset++] & 0xFF) << 8);
result += ((buf[offset++] & 0xFF) << 16);
result += ((buf[offset]) << 24);
return result;
}
|
java
|
{
"resource": ""
}
|
q180484
|
ByteBufferUtils.writeIntToByteArray
|
test
|
public static void writeIntToByteArray(byte[] buf, int offset, int value)
{
buf[offset++] = (byte) (value & 0x000000ff);
buf[offset++] = (byte) ((value & 0x0000ff00) >> 8);
buf[offset++] = (byte) ((value & 0x00ff0000) >> 16);
buf[offset] = (byte) ((value & 0xff000000) >> 24);
}
|
java
|
{
"resource": ""
}
|
q180485
|
ByteBufferUtils.write24BitIntToByteArray
|
test
|
public static void write24BitIntToByteArray(byte[] buf, int offset, int value)
{
buf[offset++] = (byte) (value & 0x000000ff);
buf[offset++] = (byte) ((value & 0x0000ff00) >> 8);
buf[offset] = (byte) ((value & 0x00ff0000) >> 16);
}
|
java
|
{
"resource": ""
}
|
q180486
|
ByteBufferUtils.get24BitIntFromBytes
|
test
|
public static int get24BitIntFromBytes(byte[] buf, int offset)
{
int i = 0;
offset++;
i += buf[offset++] & 0xFF;
i += ((buf[offset++] & 0xFF) << 8);
i += ((buf[offset] & 0xFF) << 16);
return i;
}
|
java
|
{
"resource": ""
}
|
q180487
|
ByteBufferUtils.getShortFromBytes
|
test
|
public static short getShortFromBytes(byte[] buf, int offset)
{
short result = 0;
result += buf[offset++] & 0xFF;
result += ((buf[offset]) << 8);
return result;
}
|
java
|
{
"resource": ""
}
|
q180488
|
ByteBufferUtils.writeShortToByteArray
|
test
|
public static void writeShortToByteArray(byte[] buf, int offset, short value)
{
buf[offset++] = (byte) (value & 0x000000ff);
buf[offset] = (byte) ((value & 0x0000ff00) >> 8);
}
|
java
|
{
"resource": ""
}
|
q180489
|
TreeSearchState.getChildStateForOperator
|
test
|
public TreeSearchState<E> getChildStateForOperator(Operator<Tree<E>> op)
{
/*log.fine("public Traversable getChildStateForOperator(Operator op): called");*/
// Extract the child tree from the operator and create a new tree search state from it.
return new TreeSearchState<E>(op.getOp());
}
|
java
|
{
"resource": ""
}
|
q180490
|
TreeSearchState.validOperators
|
test
|
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());
}
}
|
java
|
{
"resource": ""
}
|
q180491
|
IdAttribute.getId
|
test
|
public long getId()
{
// Check if the attribute class has been finalized yet.
if (attributeClass.finalized)
{
// Fetch the object value from the attribute class array of finalized values.
return attributeClass.lookupValue[value].id;
}
// The attribute class has not been finalized yet.
else
{
// Fetch the object value from the attribute class list of unfinalized values.
return attributeClass.lookupValueList.get(value).id;
}
}
|
java
|
{
"resource": ""
}
|
q180492
|
IdAttribute.getValue
|
test
|
public T getValue()
{
// Check if the attribute class has been finalized yet.
if (attributeClass.finalized)
{
// Fetch the object value from the attribute class.
return attributeClass.lookupValue[value].label;
}
else
{
return attributeClass.lookupValueList.get(value).label;
}
}
|
java
|
{
"resource": ""
}
|
q180493
|
IdAttribute.setValue
|
test
|
public void setValue(T value) throws IllegalArgumentException
{
Integer b = attributeClass.lookupInt.get(value);
// Check if the value is not already a memeber of the attribute class.
if (b == null)
{
// Check if the attribute class has been finalized yet.
if (attributeClass.finalized)
{
throw new IllegalArgumentException("The value to set, " + value +
", is not already a member of the finalized IdType, " + attributeClass.attributeClassName + ".");
}
else
{
// Add the new value to the attribute class. Delegate to the factory to do this so that strings are
// interned and so on.
IdAttribute newAttribute = attributeClass.createIdAttribute(value);
b = newAttribute.value;
}
}
// Set the new value as the value of this attribute.
this.value = b;
}
|
java
|
{
"resource": ""
}
|
q180494
|
StringUtils.listToArray
|
test
|
public static String[] listToArray(String value, String delim)
{
List<String> result = new ArrayList<String>();
StringTokenizer tokenizer = new StringTokenizer(value, delim);
while (tokenizer.hasMoreTokens())
{
result.add(tokenizer.nextToken());
}
return result.toArray(new String[result.size()]);
}
|
java
|
{
"resource": ""
}
|
q180495
|
StringUtils.arrayToList
|
test
|
public static String arrayToList(String[] array, String delim)
{
String result = "";
for (int i = 0; i < array.length; i++)
{
result += array[i] + ((i == (array.length - 1)) ? "" : delim);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180496
|
StringUtils.toCamelCase
|
test
|
public static String toCamelCase(String name)
{
String[] parts = name.split("_");
String result = parts[0];
for (int i = 1; i < parts.length; i++)
{
if (parts[i].length() > 0)
{
result += upperFirstChar(parts[i]);
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180497
|
StringUtils.convertCase
|
test
|
public static String convertCase(String value, String separator, boolean firstLetterUpper, boolean firstLetterOfWordUpper) {
final StringBuffer result = new StringBuffer();
boolean firstWord = true;
boolean firstLetter = true;
boolean upper = false;
WordMachineState state = WordMachineState.Initial;
Function2<Character, Boolean, StringBuffer> writeChar = new Function2<Character, Boolean, StringBuffer>() {
public StringBuffer apply(Character nextChar, Boolean upper) {
if (upper)
result.append(Character.toUpperCase(nextChar));
else
result.append(Character.toLowerCase(nextChar));
return result;
}
};
for (int i = 0; i < value.length(); i++) {
char nextChar = value.charAt(i);
if (Character.isUpperCase(nextChar)) {
switch (state) {
case Initial:
state = WordMachineState.StartWord;
upper = firstLetterOfWordUpper;
if (!firstWord) {
result.append(separator);
}
firstWord = false;
break;
case StartWord:
case ContinueWordCaps:
state = WordMachineState.ContinueWordCaps;
upper = false;
break;
case ContinueWordLower:
state = WordMachineState.StartWord;
upper = firstLetterOfWordUpper;
result.append(separator);
break;
}
writeChar.apply(nextChar, (!firstLetter && upper) || (firstLetter & firstLetterUpper));
firstLetter = false;
} else if (Character.isLetterOrDigit(nextChar)) {
switch (state) {
case Initial:
state = WordMachineState.StartWord;
upper = firstLetterOfWordUpper;
if (!firstWord) {
result.append(separator);
}
firstWord = false;
break;
case StartWord:
case ContinueWordLower:
case ContinueWordCaps:
state = WordMachineState.ContinueWordLower;
upper = false;
break;
}
writeChar.apply(nextChar, (!firstLetter && upper) || (firstLetter & firstLetterUpper));
firstLetter = false;
} else {
switch (state) {
case Initial:
state = WordMachineState.Initial;
break;
case StartWord:
case ContinueWordCaps:
case ContinueWordLower:
state = WordMachineState.Initial;
break;
}
upper = false;
}
}
return result.toString();
}
|
java
|
{
"resource": ""
}
|
q180498
|
LoggingDiagnostic.currentConfiguration
|
test
|
public static String currentConfiguration()
{
StringBuffer rtn = new StringBuffer(1024);
String loggingConfigClass = System.getProperty("java.util.logging.config.class");
String loggingConfigFile = System.getProperty("java.util.logging.config.file");
boolean configClassOK = false;
if (loggingConfigClass == null)
{
rtn.append("No java.util.logging.config.class class is set.\n");
}
else
{
rtn.append("java.util.logging.config.class is set to '").append(loggingConfigClass).append("'\n");
try
{
Class c = Class.forName(loggingConfigClass);
c.newInstance();
rtn.append("This class was loaded and a new instance was sucessfully created.\n");
configClassOK = true;
}
catch (ClassNotFoundException e)
{
e = null;
rtn.append(loggingConfigClass).append(" could not be found.");
}
catch (InstantiationException e)
{
e = null;
rtn.append(loggingConfigClass).append(" could not be instantiated.");
}
catch (IllegalAccessException e)
{
e = null;
rtn.append(loggingConfigClass).append(" could not be accessed.");
}
}
if (loggingConfigFile == null)
{
rtn.append("No java.util.logging.config.file file is set.\n");
}
else
{
rtn.append("java.util.logging.config.file is set to '").append(loggingConfigFile).append("'\n");
File loggingFile = new File(loggingConfigFile);
rtn.append(loggingFile.getAbsolutePath()).append("\n");
if (!loggingFile.exists() || !loggingFile.isFile())
{
rtn.append("This file does NOT EXIST.\n");
}
if (loggingConfigClass != null)
{
if (configClassOK)
{
rtn.append("This file is ignored because java.util.logging.config.class is set.\n");
}
}
}
Handler[] handlers = Logger.getLogger("").getHandlers();
listHandlers(handlers, rtn);
return rtn.toString();
}
|
java
|
{
"resource": ""
}
|
q180499
|
LoggingDiagnostic.listHandlers
|
test
|
private static StringBuffer listHandlers(Handler[] handlers, StringBuffer buffer)
{
for (Handler handler : handlers)
{
Class<? extends Handler> handlerClass = handler.getClass();
Formatter formatter = handler.getFormatter();
buffer.append("Handler:").append(handlerClass.getName()).append("\n");
buffer.append("Level:").append(handler.getLevel().toString()).append("\n");
if (formatter != null)
{
buffer.append("Formatter:").append(formatter.getClass().getName()).append("\n");
}
}
return buffer;
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.