_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q180600
BaseUnaryCondition.await
test
public void await(T t) throws InterruptedException { synchronized (monitor) { long waitNanos = evaluateWithWaitTimeNanos(t); // Loop forever until all conditions pass or the thread is interrupted. while (waitNanos > 0) { // If some conditions failed, then wait for the shortest wait time, or until the thread is woken up by // a signal, before re-evaluating conditions. long milliPause = waitNanos / 1000000; int nanoPause = (int) (waitNanos % 1000000); monitor.wait(milliPause, nanoPause); waitNanos = evaluateWithWaitTimeNanos(t); } } }
java
{ "resource": "" }
q180601
BaseUnaryCondition.await
test
public boolean await(T t, long timeout, TimeUnit unit) throws InterruptedException { synchronized (monitor) { // Holds the absolute time when the timeout expires. long expiryTimeNanos = System.nanoTime() + unit.toNanos(timeout); // Used to hold the estimated wait time until the condition may pass. long waitNanos = evaluateWithWaitTimeNanos(t); // Loop forever until all conditions pass, the timeout expires, or the thread is interrupted. while (waitNanos > 0) { // Check how much time remains until the timeout expires. long remainingTimeNanos = expiryTimeNanos - System.nanoTime(); // Check if the timeout has expired. if (remainingTimeNanos <= 0) { return false; } // If some conditions failed, then wait for the shortest of the wait time or the remaining time until the // timout expires, or until the thread is woken up by a signal, before re-evaluating conditions. long timeToPauseNanos = (waitNanos < remainingTimeNanos) ? waitNanos : remainingTimeNanos; long milliPause = timeToPauseNanos / 1000000; int nanoPause = (int) (timeToPauseNanos % 1000000); monitor.wait(milliPause, nanoPause); // Re-evelaute the condition and obtain a new estimate of how long until it may pass. waitNanos = evaluateWithWaitTimeNanos(t); } } // All conditions have passed when the above loop terminates. return true; }
java
{ "resource": "" }
q180602
ScriptGenMojo.execute
test
public void execute() throws MojoExecutionException, MojoFailureException { //log.debug("public void execute() throws MojoExecutionException: called"); // Turn each of the test runner command lines into a script. for (String commandName : commands.keySet()) { if (scriptOutDirectory != null) { writeUnixScript(commandName, scriptOutDirectory); writeWindowsScript(commandName, scriptOutDirectory); } } }
java
{ "resource": "" }
q180603
ScriptGenMojo.appendClasspath
test
protected String appendClasspath(String commandLine, boolean unix) { String pathSeperator; String seperator; if (unix) { pathSeperator = "/"; seperator = ":"; } else { pathSeperator = "\\"; seperator = ";"; } for (Iterator i = classpathElements.iterator(); i.hasNext();) { String cpPath = (String) i.next(); cpPath = cpPath.replace("/", pathSeperator); commandLine += cpPath + (i.hasNext() ? seperator : ""); } return commandLine; }
java
{ "resource": "" }
q180604
DateRangeType.createInstance
test
public static Type createInstance(String name, DateOnly from, DateOnly to) { // Ensure that min is less than or equal to max. if ((from != null) && (to != null) && (from.compareTo(to) > 0)) { throw new IllegalArgumentException("'min' must be less than or equal to 'max'."); } synchronized (DATE_RANGE_TYPES) { // Add the newly created type to the map of all types. DateRangeType newType = new DateRangeType(name, from, to); // 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. DateRangeType oldType = DATE_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 { DATE_RANGE_TYPES.put(name, newType); return newType; } } }
java
{ "resource": "" }
q180605
ResolutionInterpreter.printIntroduction
test
private void printIntroduction() { System.out.println("| LoJiX Prolog."); System.out.println("| Copyright The Sett Ltd."); System.out.println("| Licensed under the Apache License, Version 2.0."); System.out.println("| //www.apache.org/licenses/LICENSE-2.0"); System.out.println(); }
java
{ "resource": "" }
q180606
ResolutionInterpreter.initializeCommandLineReader
test
private ConsoleReader initializeCommandLineReader() throws IOException { ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false); return reader; }
java
{ "resource": "" }
q180607
ResolutionInterpreter.evaluate
test
private void evaluate(Sentence<Clause> sentence) throws SourceCodeException { Clause clause = sentence.getT(); if (clause.isQuery()) { engine.endScope(); engine.compile(sentence); evaluateQuery(); } else { // Check if the program clause is new, or a continuation of the current predicate. int name = clause.getHead().getName(); if ((currentPredicateName == null) || (currentPredicateName != name)) { engine.endScope(); currentPredicateName = name; } addProgramClause(sentence); } }
java
{ "resource": "" }
q180608
ResolutionInterpreter.evaluateQuery
test
private void evaluateQuery() { /*log.fine("Read query from input.");*/ // Create an iterator to generate all solutions on demand with. Iteration will stop if the request to // the parser for the more ';' token fails. Iterator<Set<Variable>> i = engine.iterator(); if (!i.hasNext()) { System.out.println("false. "); return; } for (; i.hasNext();) { Set<Variable> solution = i.next(); if (solution.isEmpty()) { System.out.print("true"); } else { for (Iterator<Variable> j = solution.iterator(); j.hasNext();) { Variable nextVar = j.next(); String varName = engine.getVariableName(nextVar.getName()); System.out.print(varName + " = " + nextVar.getValue().toString(engine, true, false)); if (j.hasNext()) { System.out.println(); } } } // Finish automatically if there are no more solutions. if (!i.hasNext()) { System.out.println("."); break; } // Check if the user wants more solutions. try { int key = consoleReader.readVirtualKey(); if (key == SEMICOLON) { System.out.println(" ;"); } else { System.out.println(); break; } } catch (IOException e) { throw new IllegalStateException(e); } } }
java
{ "resource": "" }
q180609
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(boolean b) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(Boolean.toString(b)); result.nativeType = BOOLEAN; return result; }
java
{ "resource": "" }
q180610
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(byte b) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(Byte.toString(b)); result.nativeType = BYTE; return result; }
java
{ "resource": "" }
q180611
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(char c) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(Character.toString(c)); result.nativeType = CHAR; return result; }
java
{ "resource": "" }
q180612
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(short s) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(Short.toString(s)); result.nativeType = SHORT; return result; }
java
{ "resource": "" }
q180613
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(int i) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(Integer.toString(i)); result.nativeType = INT; return result; }
java
{ "resource": "" }
q180614
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(long l) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(Long.toString(l)); result.nativeType = LONG; return result; }
java
{ "resource": "" }
q180615
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(float f) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(Float.toString(f)); result.nativeType = FLOAT; return result; }
java
{ "resource": "" }
q180616
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(double d) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(Double.toString(d)); result.nativeType = DOUBLE; return result; }
java
{ "resource": "" }
q180617
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(String s) { MultiTypeData result = new MultiTypeData(); // Start by assuming that the String can only be converted to a String. result.typeFlags = STRING; result.stringValue = s; // Assume that the native type is String. It is up to methods that call this one to override this if this is // not the case. result.nativeType = STRING; // Check if the string can be converted to a boolean. if ("true".equals(s)) { result.booleanValue = true; result.typeFlags |= BOOLEAN; } else if ("false".equals(s)) { result.booleanValue = false; result.typeFlags |= BOOLEAN; } // Check if the string can be converted to an int. try { result.intValue = Integer.parseInt(s); result.typeFlags |= INT; } catch (NumberFormatException e) { // Exception noted so can be ignored. e = null; result.typeFlags &= (Integer.MAX_VALUE - INT); } // Check if the string can be converted to a byte. try { result.byteValue = Byte.parseByte(s); result.typeFlags |= BYTE; } catch (NumberFormatException e) { // Exception noted so can be ignored. e = null; result.typeFlags = (Integer.MAX_VALUE - BYTE); } // Check if the string can be converted to a char. if (s.length() == 1) { result.charValue = s.charAt(0); result.typeFlags |= CHAR; } // Check if the string can be converted to a short. try { result.shortValue = Short.parseShort(s); result.typeFlags |= SHORT; } catch (NumberFormatException e) { // Exception noted so can be ignored. e = null; result.typeFlags = (Integer.MAX_VALUE - SHORT); } // Check if the string can be converted to a long. try { result.longValue = Long.parseLong(s); result.typeFlags |= LONG; } catch (NumberFormatException e) { // Exception noted so can be ignored. e = null; result.typeFlags = (Integer.MAX_VALUE - LONG); } // Check if the string can be converted to a float. try { result.floatValue = Float.parseFloat(s); result.typeFlags |= FLOAT; } catch (NumberFormatException e) { // Exception noted so can be ignored. e = null; result.typeFlags = (Integer.MAX_VALUE - FLOAT); } // Check if the string can be converted to a double. try { result.doubleValue = Double.parseDouble(s); result.typeFlags |= DOUBLE; } catch (NumberFormatException e) { // Exception noted so can be ignored. e = null; result.typeFlags = (Integer.MAX_VALUE - DOUBLE); } // Assume the string can never be converted to an object. return result; }
java
{ "resource": "" }
q180618
TypeConverter.getMultiTypeData
test
public static MultiTypeData getMultiTypeData(Object o) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData(o.toString()); result.nativeType = OBJECT; return result; }
java
{ "resource": "" }
q180619
TypeConverter.convert
test
public static Object convert(MultiTypeData d, Class c) { // Check if it is an boolean convertion. if (((d.typeFlags & BOOLEAN) != 0) && (Boolean.TYPE.equals(c) || Boolean.class.equals(c))) { return d.booleanValue; } // Check if it is an int convertion. else if (((d.typeFlags & INT) != 0) && (Integer.TYPE.equals(c) || Integer.class.equals(c))) { return d.intValue; } // Check if it is an char convertion. else if (((d.typeFlags & CHAR) != 0) && (Character.TYPE.equals(c) || Character.class.equals(c))) { return d.charValue; } // Check if it is an byte convertion. else if (((d.typeFlags & BYTE) != 0) && (Byte.TYPE.equals(c) || Byte.class.equals(c))) { return d.byteValue; } // Check if it is an short convertion. else if (((d.typeFlags & SHORT) != 0) && (Short.TYPE.equals(c) || Short.class.equals(c))) { return d.shortValue; } // Check if it is an long convertion. else if (((d.typeFlags & LONG) != 0) && (Long.TYPE.equals(c) || Long.class.equals(c))) { return d.longValue; } // Check if it is an float convertion. else if (((d.typeFlags & FLOAT) != 0) && (Float.TYPE.equals(c) || Float.class.equals(c))) { return d.floatValue; } // Check if it is an double convertion. else if (((d.typeFlags & DOUBLE) != 0) && (Double.TYPE.equals(c) || Double.class.equals(c))) { return d.doubleValue; } // Check if it is a string convertion. else if (((d.typeFlags & STRING) != 0) && String.class.equals(c)) { return d.stringValue; } // Check if it is an object convertion and th object types match. else if (((d.typeFlags & OBJECT) != 0) && d.objectValue.getClass().equals(c)) { return d.objectValue; } // Throw a class cast exception if the multi data type cannot be converted to the specified class. else { throw new ClassCastException("The multi data type, " + d + ", cannot be converted to the class, " + c + "."); } }
java
{ "resource": "" }
q180620
ScopeHelper.put
test
public void put(String name, Object value) { pageContext.setAttribute(name, value, scope); }
java
{ "resource": "" }
q180621
CircularArrayMap.clearUpTo
test
public void clearUpTo(int key) { if (((start <= key) && (key < (end - 1)))) { // Loop from the start of the data, up to the key to clear up to, clearing all data encountered in-between. int newStart; for (newStart = start; (newStart <= end) && (newStart <= key); newStart++) { int offset = offset(newStart); if (data[offset] != null) { data[offset] = null; count--; } } // Continue on after the clear up to point, until the first non-null entry or end of array is encountered, // and make that the new start. for (; newStart <= end; newStart++) { if (data[offset(newStart)] != null) { break; } } start = newStart; } else { // The key does not lie between the start and end markers, so clear the entire map up to the end int newStart; for (newStart = start; (newStart <= end); newStart++) { int offset = offset(newStart); if (data[offset] != null) { data[offset] = null; count--; } } start = newStart; offset = -start; } }
java
{ "resource": "" }
q180622
CircularArrayMap.expand
test
private void expand(int key) { // Set the new size to whichever is the larger of 1.5 times the old size, or an array large enough to hold // the proposed key that caused the expansion. int newFactorSize = ((length * 3) / 2) + 1; int newSpaceSize = spaceRequired(key); int newSize = (newSpaceSize > newFactorSize) ? newSpaceSize : newFactorSize; Object[] oldData = data; data = new Object[newSize]; // The valid data in the old array runs from offset(start) to offset(end) when offset(start) < offset(end), and // from offset(start) to length - 1 and 0 to offset(end) when offset(start) >= offset(end). int offsetStart = offset(start); int offsetEnd = offset(end); if (offsetStart < offsetEnd) { System.arraycopy(oldData, offsetStart, data, 0, end - start); } else { System.arraycopy(oldData, offsetStart, data, 0, length - offsetStart); System.arraycopy(oldData, 0, data, length - offsetStart, offsetEnd); } offset = -start; length = newSize; }
java
{ "resource": "" }
q180623
TextGridImpl.internalInsert
test
private void internalInsert(char character, int c, int r) { maxColumn = (c > maxColumn) ? c : maxColumn; maxRow = (r > maxRow) ? r : maxRow; data.put((long) c, (long) r, character); }
java
{ "resource": "" }
q180624
UniformCostComparator.compare
test
public int compare(SearchNode object1, SearchNode object2) { float cost1 = object1.getPathCost(); float cost2 = object2.getPathCost(); return (cost1 > cost2) ? 1 : ((cost1 < cost2) ? -1 : 0); }
java
{ "resource": "" }
q180625
DynamicOperatorParser.parseOperators
test
public Term parseOperators(Term[] terms) throws SourceCodeException { // Initialize the parsers state. stack.offer(0); state = 0; position = 0; nextTerm = null; // Consume the terms from left to right. for (position = 0; position <= terms.length;) { Symbol nextSymbol; // Decide what the next symbol to parse is; candidate op, term or final. if (position < terms.length) { nextTerm = terms[position]; if (nextTerm instanceof CandidateOpSymbol) { nextSymbol = Symbol.Op; } else { nextSymbol = Symbol.Term; } } else { nextSymbol = Symbol.Final; } // Look in the action table to find the action associated with the current symbol and state. Action action = actionTable[state][nextSymbol.ordinal()]; // Apply the action. action.apply(); } return (Functor) outputStack.poll(); }
java
{ "resource": "" }
q180626
DynamicOperatorParser.getOperatorsMatchingNameByFixity
test
public EnumMap<OpSymbol.Fixity, OpSymbol> getOperatorsMatchingNameByFixity(String name) { return operators.get(name); }
java
{ "resource": "" }
q180627
DynamicOperatorParser.checkAndResolveToFixity
test
protected static OpSymbol checkAndResolveToFixity(CandidateOpSymbol candidate, OpSymbol.Fixity... fixities) throws SourceCodeException { OpSymbol result = null; for (OpSymbol.Fixity fixity : fixities) { result = candidate.getPossibleOperators().get(fixity); if (result != null) { break; } } if (result == null) { throw new SourceCodeException("Operator " + candidate + " must be one of " + Arrays.toString(fixities) + ", but does not have the required form.", null, null, null, candidate.getSourceCodePosition()); } return result; }
java
{ "resource": "" }
q180628
SearchNode.makeNode
test
public SearchNode<O, T> makeNode(Successor successor) throws SearchNotExhaustiveException { SearchNode newNode; try { // Create a new instance of this class newNode = getClass().newInstance(); // Set the state, operation, parent, depth and cost for the new search node newNode.state = successor.getState(); newNode.parent = this; newNode.appliedOp = successor.getOperator(); newNode.depth = depth + 1; newNode.pathCost = pathCost + successor.getCost(); // Check if there is a repeated state filter and copy the reference to it into the new node if so if (repeatedStateFilter != null) { newNode.setRepeatedStateFilter(repeatedStateFilter); } return newNode; } catch (InstantiationException e) { // In practice this should never happen but may if the nodes if some class loader error were to occur whilst // using a custom node implementation. Rethrow this as a RuntimeException. throw new IllegalStateException("InstantiationException during creation of new search node.", e); } catch (IllegalAccessException e) { // In practice this should never happen but may if the nodes to use are not public whilst using a custom node // implementation. Rethrow this as a RuntimeException. throw new IllegalStateException("IllegalAccessException during creation of new search node.", e); } }
java
{ "resource": "" }
q180629
CommandLineParser.rightPad
test
public static String rightPad(String stringToPad, String padder, int size) { if (padder.length() == 0) { return stringToPad; } StringBuffer strb = new StringBuffer(stringToPad); CharacterIterator sci = new StringCharacterIterator(padder); while (strb.length() < size) { for (char ch = sci.first(); ch != CharacterIterator.DONE; ch = sci.next()) { if (strb.length() < size) { strb.append(String.valueOf(ch)); } } } return strb.toString(); }
java
{ "resource": "" }
q180630
CommandLineParser.getErrors
test
public String getErrors() { // Return the empty string if there are no errors. if (parsingErrors.isEmpty()) { return ""; } // Concatenate all the parsing errors together. String result = ""; for (String s : parsingErrors) { result += s; } return result; }
java
{ "resource": "" }
q180631
CommandLineParser.getOptionsInForce
test
public String getOptionsInForce() { // Check if there are no properties to report and return and empty string if so. if (parsedProperties == null) { return ""; } // List all the properties. String result = "Options in force:\n"; for (Map.Entry<Object, Object> property : parsedProperties.entrySet()) { result += property.getKey() + " = " + property.getValue() + "\n"; } return result; }
java
{ "resource": "" }
q180632
CommandLineParser.getUsage
test
public String getUsage() { String result = "Options:\n"; int optionWidth = 0; int argumentWidth = 0; // Calculate the column widths required for aligned layout. for (CommandLineOption optionInfo : optionMap.values()) { int oWidth = optionInfo.option.length(); int aWidth = (optionInfo.argument != null) ? (optionInfo.argument.length()) : 0; optionWidth = (oWidth > optionWidth) ? oWidth : optionWidth; argumentWidth = (aWidth > argumentWidth) ? aWidth : argumentWidth; } // Print usage on each of the command line options. for (CommandLineOption optionInfo : optionMap.values()) { String argString = ((optionInfo.argument != null) ? (optionInfo.argument) : ""); String optionString = optionInfo.option; argString = rightPad(argString, " ", argumentWidth); optionString = rightPad(optionString, " ", optionWidth); result += "-" + optionString + " " + argString + " " + optionInfo.comment + "\n"; } return result; }
java
{ "resource": "" }
q180633
CommandLineParser.addTrailingPairsToProperties
test
public void addTrailingPairsToProperties(Properties properties) { if (trailingProperties != null) { for (Object propKey : trailingProperties.keySet()) { String name = (String) propKey; String value = trailingProperties.getProperty(name); properties.setProperty(name, value); } } }
java
{ "resource": "" }
q180634
CommandLineParser.addOptionsToProperties
test
public void addOptionsToProperties(Properties properties) { if (parsedProperties != null) { for (Object propKey : parsedProperties.keySet()) { String name = (String) propKey; String value = parsedProperties.getProperty(name); // This filters out all trailing items. if (!name.matches("^[0-9]+$")) { properties.setProperty(name, value); } } } }
java
{ "resource": "" }
q180635
CommandLineParser.addOption
test
protected void addOption(String option, String comment, String argument, boolean mandatory, String formatRegexp) { // Check if usage text has been set in which case this option is expecting arguments. boolean expectsArgs = (!((argument == null) || "".equals(argument))); // Add the option to the map of command line options. CommandLineOption opt = new CommandLineOption(option, expectsArgs, comment, argument, mandatory, formatRegexp); optionMap.put(option, opt); }
java
{ "resource": "" }
q180636
CommandLineParser.takeFreeArgsAsProperties
test
private Properties takeFreeArgsAsProperties(Properties properties, int from) { Properties result = new Properties(); for (int i = from; true; i++) { String nextFreeArg = properties.getProperty(Integer.toString(i)); // Terminate the loop once all free arguments have been consumed. if (nextFreeArg == null) { break; } // Split it on the =, strip any whitespace and set it as a system property. String[] nameValuePair = nextFreeArg.split("="); if (nameValuePair.length == 2) { result.setProperty(nameValuePair[0], nameValuePair[1]); } } return result; }
java
{ "resource": "" }
q180637
CommandLineParser.checkArgumentFormat
test
private void checkArgumentFormat(CommandLineOption optionInfo, CharSequence matchedArg) { // Check if this option enforces a format for its argument. if (optionInfo.argumentFormatRegexp != null) { Pattern pattern = Pattern.compile(optionInfo.argumentFormatRegexp); Matcher argumentMatcher = pattern.matcher(matchedArg); // Check if the argument does not meet its required format. if (!argumentMatcher.matches()) { // Create an error for this badly formed argument. parsingErrors.add("The argument to option " + optionInfo.option + " does not meet its required format.\n"); } } }
java
{ "resource": "" }
q180638
Comparisons.compareIterators
test
public static <T, U> String compareIterators(Iterator<U> iterator, Iterator<T> expectedIterator, Function<U, T> mapping) { String errorMessage = ""; while (iterator.hasNext()) { U next = iterator.next(); T nextMapped = mapping.apply(next); T nextExpected = expectedIterator.next(); if (!nextMapped.equals(nextExpected)) { errorMessage += "Expecting " + nextExpected + " but got " + nextMapped; } } return errorMessage; }
java
{ "resource": "" }
q180639
PTStemmer.listOptions
test
public Enumeration listOptions() { Vector<Option> result; String desc; SelectedTag tag; int i; result = new Vector<Option>(); desc = ""; for (i = 0; i < TAGS_STEMMERS.length; i++) { tag = new SelectedTag(TAGS_STEMMERS[i].getID(), TAGS_STEMMERS); desc += "\t" + tag.getSelectedTag().getIDStr() + " = " + tag.getSelectedTag().getReadable() + "\n"; } result.addElement(new Option( "\tThe type of stemmer algorithm to use:\n" + desc + "\t(default: " + new SelectedTag(STEMMER_ORENGO, TAGS_STEMMERS) + ")", "S", 1, "-S " + Tag.toOptionList(TAGS_STEMMERS))); result.addElement(new Option( "\tThe file with the named entities to ignore (optional).\n" + "\tFile format: simple text file with one entity per line.\n" + "\t(default: none)\n", "N", 1, "-N <file>")); result.addElement(new Option( "\tThe file with the stopwords (optional).\n" + "\tFile format: simple text file with one stopword per line.\n" + "\t(default: none)\n", "W", 1, "-W <file>")); result.addElement(new Option( "\tThe size of the cache. Disable with 0.\n" + "\t(default: 1000)\n", "C", 1, "-C <int>")); return result.elements(); }
java
{ "resource": "" }
q180640
PTStemmer.getOptions
test
public String[] getOptions() { Vector<String> result; result = new Vector<String>(); result.add("-S"); result.add("" + getStemmer()); result.add("-N"); result.add("" + getNamedEntities()); result.add("-W"); result.add("" + getStopwords()); result.add("-C"); result.add("" + getCache()); return result.toArray(new String[result.size()]); }
java
{ "resource": "" }
q180641
PTStemmer.setStemmer
test
public void setStemmer(SelectedTag value) { if (value.getTags() == TAGS_STEMMERS) { m_Stemmer = value.getSelectedTag().getID(); invalidate(); } }
java
{ "resource": "" }
q180642
PTStemmer.getActualStemmer
test
protected synchronized ptstemmer.Stemmer getActualStemmer() throws PTStemmerException { if (m_ActualStemmer == null) { // stemmer algorithm if (m_Stemmer == STEMMER_ORENGO) m_ActualStemmer = new OrengoStemmer(); else if (m_Stemmer == STEMMER_PORTER) m_ActualStemmer = new PorterStemmer(); else if (m_Stemmer == STEMMER_SAVOY) m_ActualStemmer = new SavoyStemmer(); else throw new IllegalStateException("Unhandled stemmer type: " + m_Stemmer); // named entities if (!m_NamedEntities.isDirectory()) m_ActualStemmer.ignore(PTStemmerUtilities.fileToSet(m_NamedEntities.getAbsolutePath())); // stopwords if (!m_Stopwords.isDirectory()) m_ActualStemmer.ignore(PTStemmerUtilities.fileToSet(m_Stopwords.getAbsolutePath())); // cache if (m_Cache > 0) m_ActualStemmer.enableCaching(m_Cache); else m_ActualStemmer.disableCaching(); } return m_ActualStemmer; }
java
{ "resource": "" }
q180643
PTStemmer.stem
test
public String stem(String word) { String ret = null; try { ret = getActualStemmer().getWordStem(word); } catch (PTStemmerException e) { e.printStackTrace(); } return ret; }
java
{ "resource": "" }
q180644
PTStemmer.main
test
public static void main(String[] args) { try { Stemming.useStemmer(new PTStemmer(), args); } catch (Exception e) { e.printStackTrace(); } }
java
{ "resource": "" }
q180645
FloatRangeType.createInstance
test
public static Type createInstance(String name, float min, float max) { // Ensure that min is less than or equal to max. if (min > max) { throw new IllegalArgumentException("'min' must be less than or equal to 'max'."); } synchronized (FLOAT_RANGE_TYPES) { // Add the newly created type to the map of all types. FloatRangeType newType = new FloatRangeType(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. FloatRangeType oldType = FLOAT_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 { FLOAT_RANGE_TYPES.put(name, newType); return newType; } } }
java
{ "resource": "" }
q180646
WAMResolvingJavaMachine.reset
test
public void reset() { // Create fresh heaps, code areas and stacks. data = ByteBuffer.allocateDirect(TOP << 2).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); codeBuffer = ByteBuffer.allocateDirect(CODE_SIZE); codeBuffer.order(ByteOrder.LITTLE_ENDIAN); // Registers are on the top of the data area, the heap comes next. hp = HEAP_BASE; hbp = HEAP_BASE; sp = HEAP_BASE; // The stack comes after the heap. Pointers are zero initially, since no stack frames exist yet. ep = 0; bp = 0; b0 = 0; // The trail comes after the stack. trp = TRAIL_BASE; // The unification stack (PDL) is a push down stack at the end of the data area. up = TOP; // Turn off write mode. writeMode = false; // Reset the instruction pointer to that start of the code area, ready for fresh code to be loaded there. ip = 0; // Could probably not bother resetting these, but will do it anyway just to be sure. derefTag = 0; derefVal = 0; // The machine is initially not suspended. suspended = false; // Ensure that the overridden reset method of WAMBaseMachine is run too, to clear the call table. super.reset(); // Put the internal functions in the call table. setInternalCodeAddress(internFunctorName("call", 1), CALL_1_ID); setInternalCodeAddress(internFunctorName("execute", 1), EXECUTE_1_ID); // Notify any debug monitor that the machine has been reset. if (monitor != null) { monitor.onReset(this); } }
java
{ "resource": "" }
q180647
WAMResolvingJavaMachine.traceEnvFrame
test
protected String traceEnvFrame() { return "env: [ ep = " + data.get(ep) + ", cp = " + data.get(ep + 1) + ", n = " + data.get(ep + 2) + "]"; }
java
{ "resource": "" }
q180648
WAMResolvingJavaMachine.traceChoiceFrame
test
protected String traceChoiceFrame() { if (bp == 0) { return ""; } int n = data.get(bp); return "choice: [ n = " + data.get(bp) + ", ep = " + data.get(bp + n + 1) + ", cp = " + data.get(bp + n + 2) + ", bp = " + data.get(bp + n + 3) + ", l = " + data.get(bp + n + 4) + ", trp = " + data.get(bp + n + 5) + ", hp = " + data.get(bp + n + 6) + ", b0 = " + data.get(bp + n + 7); }
java
{ "resource": "" }
q180649
WAMResolvingJavaMachine.callInternal
test
private boolean callInternal(int function, int arity, int numPerms) { switch (function) { case CALL_1_ID: return internalCall_1(numPerms); case EXECUTE_1_ID: return internalExecute_1(); default: throw new IllegalStateException("Unknown internal function id: " + function); } }
java
{ "resource": "" }
q180650
WAMResolvingJavaMachine.nextStackFrame
test
private int nextStackFrame() { // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 if (ep == bp) { return STACK_BASE; } else if (ep > bp) { return ep + data.get(ep + 2) + 3; } else { return bp + data.get(bp) + 8; } }
java
{ "resource": "" }
q180651
WAMResolvingJavaMachine.backtrack
test
private boolean backtrack() { // if B = bottom_of_stack if (bp == 0) { // then fail_and_exit_program return true; } else { // B0 <- STACK[B + STACK[B} + 7] b0 = data.get(bp + data.get(bp) + 7); // P <- STACK[B + STACK[B] + 4] ip = data.get(bp + data.get(bp) + 4); return false; } }
java
{ "resource": "" }
q180652
WAMResolvingJavaMachine.trail
test
private void trail(int addr) { // if (a < HB) \/ ((H < a) /\ (a < B)) if ((addr < hbp) || ((hp < addr) && (addr < bp))) { // TRAIL[TR] <- a data.put(trp, addr); // TR <- TR + 1 trp++; } }
java
{ "resource": "" }
q180653
WAMResolvingJavaMachine.unwindTrail
test
private void unwindTrail(int a1, int a2) { // for i <- a1 to a2 - 1 do for (int addr = a1; addr < a2; addr++) { // STORE[TRAIL[i]] <- <REF, TRAIL[i]> int tmp = data.get(addr); data.put(tmp, refTo(tmp)); } }
java
{ "resource": "" }
q180654
WAMResolvingJavaMachine.tidyTrail
test
private void tidyTrail() { int i; // Check that there is a current choice point to tidy down to, otherwise tidy down to the root of the trail. if (bp == 0) { i = TRAIL_BASE; } else { i = data.get(bp + data.get(bp) + 5); } while (i < trp) { int addr = data.get(i); if ((addr < hbp) || ((hp < addr) && (addr < bp))) { i++; } else { data.put(i, data.get(trp - 1)); trp--; } } }
java
{ "resource": "" }
q180655
WAMResolvingJavaMachine.unify
test
private boolean unify(int a1, int a2) { // pdl.push(a1) // pdl.push(a2) uPush(a1); uPush(a2); // fail <- false boolean fail = false; // while !empty(PDL) and not failed while (!uEmpty() && !fail) { // d1 <- deref(pdl.pop()) // d2 <- deref(pdl.pop()) // t1, v1 <- STORE[d1] // t2, v2 <- STORE[d2] int d1 = deref(uPop()); int t1 = derefTag; int v1 = derefVal; int d2 = deref(uPop()); int t2 = derefTag; int v2 = derefVal; // if (d1 != d2) if (d1 != d2) { // if (t1 = REF or t2 = REF) // bind(d1, d2) if ((t1 == WAMInstruction.REF)) { bind(d1, d2); } else if (t2 == WAMInstruction.REF) { bind(d1, d2); } else if (t2 == WAMInstruction.STR) { // f1/n1 <- STORE[v1] // f2/n2 <- STORE[v2] int fn1 = data.get(v1); int fn2 = data.get(v2); byte n1 = (byte) (fn1 >>> 24); // if f1 = f2 and n1 = n2 if (fn1 == fn2) { // for i <- 1 to n1 for (int i = 1; i <= n1; i++) { // pdl.push(v1 + i) // pdl.push(v2 + i) uPush(v1 + i); uPush(v2 + i); } } else { // fail <- true fail = true; } } else if (t2 == WAMInstruction.CON) { if ((t1 != WAMInstruction.CON) || (v1 != v2)) { fail = true; } } else if (t2 == WAMInstruction.LIS) { if (t1 != WAMInstruction.LIS) { fail = true; } else { uPush(v1); uPush(v2); uPush(v1 + 1); uPush(v2 + 1); } } } } return !fail; }
java
{ "resource": "" }
q180656
WAMResolvingJavaMachine.unifyConst
test
private boolean unifyConst(int fn, int addr) { boolean success; int deref = deref(addr); int tag = derefTag; int val = derefVal; // case STORE[addr] of switch (tag) { case REF: { // <REF, _> : // STORE[addr] <- <CON, c> data.put(deref, constantCell(fn)); // trail(addr) trail(deref); success = true; break; } case CON: { // <CON, c'> : // fail <- (c != c'); success = val == fn; break; } default: { // other: fail <- true; success = false; } } return success; }
java
{ "resource": "" }
q180657
WAMResolvingJavaMachine.printSlot
test
private String printSlot(int xi, int mode) { return ((mode == STACK_ADDR) ? "Y" : "X") + ((mode == STACK_ADDR) ? (xi - ep - 3) : xi); }
java
{ "resource": "" }
q180658
EightPuzzleState.getRandomStartState
test
public static EightPuzzleState getRandomStartState() { EightPuzzleState newState; // Turn the goal string into a list of characters. List<Character> charList = stringToCharList(GOAL_STRING); // Generate random puzzles until a solvable one is found. do { // Shuffle the list. Collections.shuffle(charList); // Turn the shuffled list into a proper eight puzzle state object. newState = charListToState(charList); // Check that the puzzle is solvable and if not then repeat the shuffling process. } while (!isSolvable(newState)); return newState; }
java
{ "resource": "" }
q180659
EightPuzzleState.isSolvable
test
public static boolean isSolvable(EightPuzzleState state) { // Take a copy of the puzzle to check. This is done because this puzzle will be updated in-place and the // original is to be preserved. EightPuzzleState checkState; try { checkState = (EightPuzzleState) state.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Puzzle state could not be cloned.", e); } // Create the goal state to check against when swapping tiles into position. EightPuzzleState goalState = getGoalState(); // Count the number of illegal swaps needed to put the puzzle in order. int illegalSwaps = 0; // Loop over the whole board, left to right, to to bottom for (int j = 0; j < 3; j++) { for (int i = 0; i < 3; i++) { // Find out from the goal state what tile should be at this position. char t = goalState.getTileAt(i, j); // Swap the tile into its goal position keeping count of the total number of illegal swaps. illegalSwaps += checkState.swapTileToLocationCountingIllegal(t, i, j); } } // Check if the number of illegal swaps is even in which case the puzzle is solvable, or odd in which case it // is not solvable. return (illegalSwaps % 2) == 0; }
java
{ "resource": "" }
q180660
EightPuzzleState.getChildStateForOperator
test
public EightPuzzleState getChildStateForOperator(Operator op) { // Create a copy of the existing board state EightPuzzleState newState; try { newState = (EightPuzzleState) clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Puzzle state could not be cloned.", e); } // Update the new board state using the in-place operator application newState.updateWithOperator(op); return newState; }
java
{ "resource": "" }
q180661
EightPuzzleState.validOperators
test
public Iterator<Operator<String>> validOperators(boolean reverse) { // Used to hold a list of valid moves List<Operator<String>> moves = new ArrayList<Operator<String>>(4); // Check if the up move is valid if (emptyY != 0) { moves.add(new OperatorImpl<String>("U")); } // Check if the down move is valid if (emptyY != 2) { moves.add(new OperatorImpl<String>("D")); } // Check if the left move is valid if (emptyX != 0) { moves.add(new OperatorImpl<String>("L")); } // Check if the right move is valid if (emptyX != 2) { moves.add(new OperatorImpl<String>("R")); } return moves.iterator(); }
java
{ "resource": "" }
q180662
EightPuzzleState.prettyPrint
test
public String prettyPrint() { String result = ""; for (int j = 0; j < 3; j++) { result += new String(board[j]) + "\n"; } result = result.replace('E', ' '); return result; }
java
{ "resource": "" }
q180663
EightPuzzleState.swapTileToLocationCountingIllegal
test
protected int swapTileToLocationCountingIllegal(char t, int x, int y) { // Used to hold the count of illegal swaps int illegal = 0; // Find out where the tile to move is int tileX = getXForTile(t); int tileY = getYForTile(t); // Shift the tile into the correct column by repeatedly moving it left or right. while (tileX != x) { if ((tileX - x) > 0) { if (swapTiles(tileX, tileY, tileX - 1, tileY)) { illegal++; } tileX--; } else { if (swapTiles(tileX, tileY, tileX + 1, tileY)) { illegal++; } tileX++; } } // Shift the tile into the correct row by repeatedly moving it up or down. while (tileY != y) { // Commented out because tiles never swap down the board during the solvability test because tiles are // swapped into place left to right, top to bottom. The top row is always filled first so tiles cannot be // swapped down into it. Then the next row is filled but ones from the row above are never swapped down // into it because they are alrady in place and never move again and so on. /* if (tileY - y > 0) *{*/ if (swapTiles(tileX, tileY, tileX, tileY - 1)) { illegal++; } tileY--; /*} * else { if (swapTiles(tileX, tileY, tileX, tileY + 1)) illegal++; tileY++;}*/ } return illegal; }
java
{ "resource": "" }
q180664
EightPuzzleState.swapTiles
test
protected boolean swapTiles(int x1, int y1, int x2, int y2) { // Used to indicate that one of the swapped tiles was the empty tile boolean swappedEmpty = false; // Get the tile at the first position char tile1 = board[y1][x1]; // Store the tile from the second position at the first position char tile2 = board[y2][x2]; board[y1][x1] = tile2; // Store the first tile in the second position board[y2][x2] = tile1; // Check if the first tile was the empty tile and update the empty tile coordinates if so if (tile1 == 'E') { emptyX = x2; emptyY = y2; swappedEmpty = true; } // Else check if the second tile was the empty tile and update the empty tile coordinates if so else if (tile2 == 'E') { emptyX = x1; emptyY = y1; swappedEmpty = true; } return !swappedEmpty; }
java
{ "resource": "" }
q180665
EightPuzzleState.stringToCharList
test
private static List<Character> stringToCharList(String boardString) { // Turn the goal state into a list of characters char[] chars = new char[9]; boardString.getChars(0, 9, chars, 0); List<Character> charList = new ArrayList<Character>(); for (int l = 0; l < 9; l++) { charList.add(chars[l]); } return charList; }
java
{ "resource": "" }
q180666
EightPuzzleState.charListToState
test
private static EightPuzzleState charListToState(List<Character> charList) { // Create a new empty puzzle state EightPuzzleState newState = new EightPuzzleState(); // Loop over the board inserting the characters into it from the character list Iterator<Character> k = charList.iterator(); for (int j = 0; j < 3; j++) { for (int i = 0; i < 3; i++) { char nextChar = k.next(); // Check if this is the empty tile and if so then take note of its position if (nextChar == 'E') { newState.emptyX = i; newState.emptyY = j; } newState.board[j][i] = nextChar; } } return newState; }
java
{ "resource": "" }
q180667
LoggingToLog4JHandler.toLog4jMessage
test
private String toLog4jMessage(LogRecord record) { String message = record.getMessage(); // Format message Object[] parameters = record.getParameters(); if ((parameters != null) && (parameters.length != 0)) { // Check for the first few parameters ? if ((message.indexOf("{0}") >= 0) || (message.indexOf("{1}") >= 0) || (message.indexOf("{2}") >= 0) || (message.indexOf("{3}") >= 0)) { message = MessageFormat.format(message, parameters); } } return message; }
java
{ "resource": "" }
q180668
LoggingToLog4JHandler.toLog4j
test
private org.apache.log4j.Level toLog4j(Level level) { if (Level.SEVERE == level) { return org.apache.log4j.Level.ERROR; } else if (Level.WARNING == level) { return org.apache.log4j.Level.WARN; } else if (Level.INFO == level) { return org.apache.log4j.Level.INFO; } else if (Level.FINE == level) { return org.apache.log4j.Level.DEBUG; } else if (Level.FINER == level) { return org.apache.log4j.Level.TRACE; } else if (Level.OFF == level) { return org.apache.log4j.Level.OFF; } return org.apache.log4j.Level.OFF; }
java
{ "resource": "" }
q180669
WrapperQueue.requeue
test
private void requeue(E element) { RequeueElementWrapper<E> record = new RequeueElementWrapper<E>(element); requeue.add(record); requeuedElementMap.put(element, record); }
java
{ "resource": "" }
q180670
WrapperQueue.requeue
test
private RequeueElementWrapper<E> requeue(E element, Object owner, AcquireState acquired) { RequeueElementWrapper<E> record = new RequeueElementWrapper<E>(element); record.state = acquired; record.owner = owner; requeue.add(record); requeuedElementMap.put(element, record); return record; }
java
{ "resource": "" }
q180671
WrapperQueue.incrementSizeAndCount
test
private void incrementSizeAndCount(E record) { // Update the count for atomically counted queues. if (atomicallyCounted) { count.incrementAndGet(); } // Update the size for sizeable elements and sizeable queues. if (sizeable && (record instanceof Sizeable)) { dataSize.addAndGet(((Sizeable) record).sizeof()); } else if (sizeable) { dataSize.incrementAndGet(); } }
java
{ "resource": "" }
q180672
WrapperQueue.decrementSizeAndCount
test
private void decrementSizeAndCount(E record) { // Update the count for atomically counted queues. if (atomicallyCounted) { count.decrementAndGet(); } // Update the size for sizeable elements and sizeable queues. if (sizeable && (record instanceof Sizeable)) { long recordSize = -((Sizeable) record).sizeof(); long oldSize = dataSize.getAndAdd(recordSize); long newSize = oldSize + recordSize; signalOnSizeThresholdCrossing(oldSize, newSize); } else if (sizeable) { long oldSize = dataSize.getAndDecrement(); long newSize = oldSize - 1; signalOnSizeThresholdCrossing(oldSize, newSize); } }
java
{ "resource": "" }
q180673
WrapperQueue.signalOnSizeThresholdCrossing
test
private void signalOnSizeThresholdCrossing(long oldSize, long newSize) { if (signalable != null) { if ((oldSize >= lowWaterSizeThreshold) && (newSize < lowWaterSizeThreshold)) { signalable.signalAll(); } else if ((oldSize >= highWaterSizeThreshold) && (newSize < highWaterSizeThreshold)) { signalable.signal(); } } }
java
{ "resource": "" }
q180674
SimpleContext.list
test
public NamingEnumeration list(String name) throws NamingException { if ("".equals(name)) { // listing this context return new FlatNames(bindings.keys()); } // Perhaps `name' names a context Object target = lookup(name); if (target instanceof Context) { return ((Context) target).list(""); } throw new NotContextException(name + " cannot be listed"); }
java
{ "resource": "" }
q180675
SimpleContext.listBindings
test
public NamingEnumeration listBindings(String name) throws NamingException { if ("".equals(name)) { // listing this context return new FlatBindings(bindings.keys()); } // Perhaps `name' names a context Object target = lookup(name); if (target instanceof Context) { return ((Context) target).listBindings(""); } throw new NotContextException(name + " cannot be listed"); }
java
{ "resource": "" }
q180676
SimpleContext.addToEnvironment
test
public Object addToEnvironment(String propName, Object propVal) { if (myEnv == null) { myEnv = new Hashtable(5, 0.75f); } return myEnv.put(propName, propVal); }
java
{ "resource": "" }
q180677
SimpleContext.removeFromEnvironment
test
public Object removeFromEnvironment(String propName) { if (myEnv == null) { return null; } return myEnv.remove(propName); }
java
{ "resource": "" }
q180678
Sizeof.runGCTillStable
test
private static void runGCTillStable() { // Possibly add another iteration in here to run this whole method 3 or 4 times. long usedMem1 = usedMemory(); long usedMem2 = Long.MAX_VALUE; // Repeatedly garbage collection until the used memory count becomes stable, or 500 iterations occur. for (int i = 0; (usedMem1 < usedMem2) && (i < 500); i++) { // Force finalisation of all object pending finalisation. RUNTIME.runFinalization(); // Return unused memory to the heap. RUNTIME.gc(); // Allow other threads to run. Thread.currentThread().yield(); // Keep the old used memory count from the last iteration and get a fresh reading. usedMem2 = usedMem1; usedMem1 = usedMemory(); } }
java
{ "resource": "" }
q180679
Parser.Literal
test
Rule Literal() { return Sequence( FirstOf(Color(), MultiDimension(), Dimension(), String()), push(new SimpleNode(match())) ); }
java
{ "resource": "" }
q180680
Parser.resolveMixinReference
test
boolean resolveMixinReference(String name, ArgumentsNode arguments) { if (!isParserTranslationEnabled()) { return push(new PlaceholderNode(new SimpleNode(name))); } // Walk down the stack, looking for a scope node that knows about a given rule set for (Node node : getContext().getValueStack()) { if (!(node instanceof ScopeNode)) { continue; } ScopeNode scope = (ScopeNode) node; RuleSetNode ruleSet = scope.getRuleSet(name); if (ruleSet == null) { continue; } // Get the scope of the rule set we located and call it as a mixin ScopeNode ruleSetScope = NodeTreeUtils.getFirstChild(ruleSet, ScopeNode.class).callMixin(name, arguments); return push(ruleSetScope); } // Record error location throw new UndefinedMixinException(name); }
java
{ "resource": "" }
q180681
Parser.pushVariableReference
test
boolean pushVariableReference(String name) { if (!isParserTranslationEnabled()) { return push(new SimpleNode(name)); } // Walk down the stack, looking for a scope node that knows about a given variable for (Node node : getContext().getValueStack()) { if (!(node instanceof ScopeNode)) { continue; } // Ensure that the variable exists ScopeNode scope = (ScopeNode) node; if (!scope.isVariableDefined(name)) { continue; } return push(new VariableReferenceNode(name)); } // Record error location throw new UndefinedVariableException(name); }
java
{ "resource": "" }
q180682
TextTableImpl.setMaxRowHeight
test
public void setMaxRowHeight(int row, int height) { Integer previousValue = maxRowSizes.get(row); if (previousValue == null) { maxRowSizes.put(row, height); } else if (previousValue < height) { maxRowSizes.put(row, height); } }
java
{ "resource": "" }
q180683
TextTableImpl.updateMaxColumnWidth
test
private void updateMaxColumnWidth(int column, int width) { Integer previousValue = maxColumnSizes.get(column); if (previousValue == null) { maxColumnSizes.put(column, width); } else if (previousValue < width) { maxColumnSizes.put(column, width); } }
java
{ "resource": "" }
q180684
PageAction.executeWithErrorHandling
test
public ActionForward executeWithErrorHandling(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, ActionErrors errors) throws Exception { // Get a reference to the session. HttpSession session = request.getSession(false); // Extract the page form. DynaActionForm pageForm = (DynaActionForm) form; log.fine("pageForm = " + pageForm); // Get the paged list object from the session. String listingVarName = pageForm.getString(VAR_NAME_PARAM); log.fine("listingVarName = " + listingVarName); PagedList pagedList = (PagedList) session.getAttribute(listingVarName); // Set its current page. pagedList.setCurrentPage((Integer) pageForm.get(NUMBER_PARAM)); // Set its index offset if one is specified. Integer index = (Integer) pageForm.get(INDEX_PARAM); if (index != null) { pagedList.setCurrentIndex(index); } // Forward to the success location. return mapping.findForward(SUCCESS_FORWARD); }
java
{ "resource": "" }
q180685
HeuristicSearchNode.makeNode
test
public HeuristicSearchNode<O, T> makeNode(Successor successor) throws SearchNotExhaustiveException { HeuristicSearchNode<O, T> node = (HeuristicSearchNode<O, T>) super.makeNode(successor); // Make sure the new node has a reference to the heuristic evaluator node.heuristic = this.heuristic; // Compute h for the new node node.computeH(); return node; }
java
{ "resource": "" }
q180686
BaseAction.execute
test
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.fine("ActionForward perform(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse): called"); // Build an ActionErrors object to hold any errors that occurr ActionErrors errors = new ActionErrors(); // Create reference to the session HttpSession session = request.getSession(); // Use a try block to catch any errors that may occur try { return executeWithErrorHandling(mapping, form, request, response, errors); } // Catch all exceptions here. This will forward to the error page in the event of // any exception that falls through to this top level handler. // Don't catch Throwable here as Errors should fall through to the JVM top level and will result in // termination of the application. catch (Exception t) { log.log(Level.WARNING, "Caught a Throwable", t); // Don't Forward the error to the error handler to interpret it as a Struts error as the exception will // automatically be translated by the error page. // @todo Could add code here to check if there is a 'error' forward page defined. If there is then call // the error handler to translate the throwable into Struts errors and then forward to the 'error' page. // This would mean that the error page defined in web.xml would be the default unless an action explicitly // defined an alternative 'error' forward. // handleErrors(t, errors); // Save all the error messages in the request so that they will be displayed // request.setAttribute(Action.ERROR_KEY, errors); // Rethrow the error as a ServletException here to cause forwarding to error page defined in web.xml throw new WrappedStrutsServletException(t); } }
java
{ "resource": "" }
q180687
PreCompiler.substituteBuiltIns
test
private void substituteBuiltIns(Term clause) { TermWalker walk = TermWalkers.positionalWalker(new BuiltInTransformVisitor(interner, symbolTable, null, builtInTransform)); walk.walk(clause); }
java
{ "resource": "" }
q180688
PreCompiler.initialiseSymbolTable
test
private void initialiseSymbolTable(Term clause) { // Run the symbol key traverser over the clause, to ensure that all terms have their symbol keys correctly // set up. SymbolKeyTraverser symbolKeyTraverser = new SymbolKeyTraverser(interner, symbolTable, null); symbolKeyTraverser.setContextChangeVisitor(symbolKeyTraverser); TermWalker symWalker = new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), symbolKeyTraverser, symbolKeyTraverser); symWalker.walk(clause); }
java
{ "resource": "" }
q180689
PreCompiler.topLevelCheck
test
private void topLevelCheck(Term clause) { TermWalker walk = TermWalkers.positionalWalker(new TopLevelCheckVisitor(interner, symbolTable, null)); walk.walk(clause); }
java
{ "resource": "" }
q180690
Cons.listToString
test
private String listToString(VariableAndFunctorInterner interner, boolean isFirst, boolean printVarName, boolean printBindings) { String result = ""; if (isFirst) { result += "["; } result += arguments[0].toString(interner, printVarName, printBindings); Term consArgument = arguments[1].getValue(); if (consArgument instanceof Cons) { result += ", " + ((Cons) consArgument).listToString(interner, false, printVarName, printBindings); } if (isFirst) { result += "]"; } return result; }
java
{ "resource": "" }
q180691
LessThan.evaluate
test
protected boolean evaluate(NumericType firstNumber, NumericType secondNumber) { // If either of the arguments is a real number, then use real number arithmetic, otherwise use integer arithmetic. if (firstNumber.isInteger() && secondNumber.isInteger()) { return firstNumber.intValue() < secondNumber.intValue(); } else { return firstNumber.doubleValue() < secondNumber.doubleValue(); } }
java
{ "resource": "" }
q180692
StartStopLifecycleBase.running
test
public void running() { try { stateLock.writeLock().lock(); if (state == State.Initial) { state = State.Running; stateChange.signalAll(); } } finally { stateLock.writeLock().unlock(); } }
java
{ "resource": "" }
q180693
StartStopLifecycleBase.terminating
test
public void terminating() { try { stateLock.writeLock().lock(); if (state == State.Running) { state = State.Shutdown; stateChange.signalAll(); } } finally { stateLock.writeLock().unlock(); } }
java
{ "resource": "" }
q180694
StartStopLifecycleBase.terminated
test
public void terminated() { try { stateLock.writeLock().lock(); if ((state == State.Shutdown) || (state == State.Running)) { state = State.Terminated; stateChange.signalAll(); } } finally { stateLock.writeLock().unlock(); } }
java
{ "resource": "" }
q180695
FibonacciHeap.offer
test
public boolean offer(E o) { // Make a new node out of the new data element. Node newNode = new Node(o); // Check if there is already a minimum element. if (minNode != null) { // There is already a minimum element, so add this new element to its right. newNode.next = minNode.next; newNode.prev = minNode; minNode.next.prev = newNode; minNode.next = newNode; // Compare the new element with the minimum and update the minimum if neccessary. updateMinimum(newNode); } // There is not already a minimum element. else { // Update the new element previous and next references to refer to itself so that it forms a doubly linked // list with only one element. This leaves the data structure in a suitable condition for adding more // elements. newNode.next = newNode; newNode.prev = newNode; // Set the minimum element to be the new data element. minNode = newNode; } // Increment the count of data elements in this collection. size++; // Return true to indicate that the new data element was accepted into the heap. return true; }
java
{ "resource": "" }
q180696
FibonacciHeap.ceilingLog2
test
private static int ceilingLog2(int n) { int oa; int i; int b; oa = n; b = 32 / 2; i = 0; while (b != 0) { i = (i << 1); if (n >= (1 << b)) { n /= (1 << b); i = i | 1; } else { n &= (1 << b) - 1; } b /= 2; } if ((1 << i) == oa) { return i; } else { return i + 1; } }
java
{ "resource": "" }
q180697
FibonacciHeap.updateMinimum
test
private void updateMinimum(Node node) { // Check if a comparator was set. if (entryComparator != null) { // Use the comparator to compare the candidate new minimum with the current one and check if the new one // should be set. if (entryComparator.compare(node.element, minNode.element) < 0) { // Update the minimum node. minNode = node; } } // No comparator was set so use the natural ordering. else { // Cast the candidate new minimum element into a Comparable and compare it with the existing minimum // to check if the new one should be set. if (((Comparable) node.element).compareTo(minNode.element) < 0) { // Update the minimum node. minNode = node; } } }
java
{ "resource": "" }
q180698
FibonacciHeap.compare
test
private int compare(Node node1, Node node2) { // Check if a comparator was set. if (entryComparator != null) { // Use the comparator to compare. return entryComparator.compare(node1.element, node2.element); } // No comparator was set so use the natural ordering. else { // Cast one of the elements into a Comparable and compare it with the other. return ((Comparable) node1.element).compareTo(node2.element); } }
java
{ "resource": "" }
q180699
FibonacciHeap.insertNodes
test
private void insertNodes(Node node, Node newNode) { // Keep a reference to the next node in the node's chain as this will be overwritten when attaching the node // or chain into the root list. Node oldNodeNext = newNode.next; // Break open the node's chain and attach it into the root list. newNode.next.prev = node; newNode.next = node.next; // Break open the root list chain and attach it to the new node or chain. node.next.prev = newNode; node.next = oldNodeNext; }
java
{ "resource": "" }