_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q180300
SimpleTree.addChild
test
public void addChild(Tree<E> child) { initChildren(); // Add the new child to the collection of children. children.add(child); // Set the type of this point in the tree to a node as it now has children. nodeOrLeaf = Type.Node; // Set the new childs parent to this. child.setParent(this); }
java
{ "resource": "" }
q180301
SimpleTree.clearChildren
test
public void clearChildren() { // Check that their are children to clear. if (children != null) { // Loop over all the children setting their parent to null. for (Tree<E> child : children) { child.setParent(null); } // Clear out the children collection. children.clear(); // Mark this as a leaf node. nodeOrLeaf = Type.Leaf; } }
java
{ "resource": "" }
q180302
SequenceIterator.nextInternal
test
private E nextInternal() { // Check if the next soluation has already been cached, because of a call to hasNext. if (nextSolution != null) { return nextSolution; } // Otherwise, generate the next solution, if possible. nextSolution = nextInSequence(); // Check if the solution was null, which indicates that the search space is exhausted. if (nextSolution == null) { exhausted = true; } return nextSolution; }
java
{ "resource": "" }
q180303
WAMCompiledClause.addInstructions
test
public void addInstructions(Functor body, SizeableList<WAMInstruction> instructions) { int oldLength; if (this.body == null) { oldLength = 0; this.body = new Functor[1]; } else { oldLength = this.body.length; this.body = Arrays.copyOf(this.body, oldLength + 1); } this.body[oldLength] = body; addInstructionsAndThisToParent(instructions); }
java
{ "resource": "" }
q180304
WAMCompiledClause.addInstructionsAndThisToParent
test
private void addInstructionsAndThisToParent(SizeableList<WAMInstruction> instructions) { if (!addedToParent) { parent.addInstructions(this, instructions); addedToParent = true; } else { parent.addInstructions(instructions); } }
java
{ "resource": "" }
q180305
ButtonPanel.propertyChange
test
public void propertyChange(PropertyChangeEvent event) { /*log.fine("void propertyChange(PropertyChangeEvent): called");*/ // Check that the property change was sent by a WorkPanelState if (event.getSource() instanceof WorkPanelState) { // Get the state String state = ((WorkPanelState) event.getSource()).getState(); // Check what the state to set is if (state.equals(WorkPanelState.NOT_SAVED)) { // Set the Cancel and Apply buttons to enabled cancelButton.setEnabled(true); applyButton.setEnabled(true); } else if (state.equals(WorkPanelState.READY)) { // Set the Cancel and Apply buttons to disabled cancelButton.setEnabled(false); applyButton.setEnabled(false); } else if (state.equals(WorkPanelState.NOT_INITIALIZED)) { // Disable all the buttons okButton.setEnabled(false); cancelButton.setEnabled(false); applyButton.setEnabled(false); } } }
java
{ "resource": "" }
q180306
ButtonPanel.registerWorkPanel
test
public void registerWorkPanel(WorkPanel panel) { // Set the work panel to listen for actions generated by the buttons okButton.addActionListener(panel); cancelButton.addActionListener(panel); applyButton.addActionListener(panel); // Register this to listen for changes to the work panels state panel.getWorkPanelState().addPropertyChangeListener(this); }
java
{ "resource": "" }
q180307
DesktopAppLayout.updatePresentComponentFlags
test
private void updatePresentComponentFlags() { hasConsole = componentMap.containsKey(CONSOLE); hasStatusBar = componentMap.containsKey(STATUS_BAR); hasLeftBar = componentMap.containsKey(LEFT_VERTICAL_BAR); hasLeftPane = componentMap.containsKey(LEFT_PANE); hasRightBar = componentMap.containsKey(RIGHT_VERTICAL_BAR); hasRightPane = componentMap.containsKey(RIGHT_PANE); }
java
{ "resource": "" }
q180308
BigDecimalTypeImpl.createInstance
test
public static Type createInstance(String name, int precision, int scale, String min, String max) { synchronized (DECIMAL_TYPES) { // Add the newly created type to the map of all types. BigDecimalTypeImpl newType = new BigDecimalTypeImpl(name, precision, scale, 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. BigDecimalTypeImpl oldType = DECIMAL_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 { DECIMAL_TYPES.put(name, newType); return newType; } } }
java
{ "resource": "" }
q180309
FreeNonAnonymousVariablePredicate.evaluate
test
public boolean evaluate(Term term) { if (term.isVar() && (term instanceof Variable)) { Variable var = (Variable) term; return !var.isBound() && !var.isAnonymous(); } return false; }
java
{ "resource": "" }
q180310
WAMOptimizer.optimize
test
private SizeableList<WAMInstruction> optimize(List<WAMInstruction> instructions) { StateMachine optimizeConstants = new OptimizeInstructions(symbolTable, interner); Iterable<WAMInstruction> matcher = new Matcher<WAMInstruction, WAMInstruction>(instructions.iterator(), optimizeConstants); SizeableList<WAMInstruction> result = new SizeableLinkedList<WAMInstruction>(); for (WAMInstruction instruction : matcher) { result.add(instruction); } return result; }
java
{ "resource": "" }
q180311
LexicographicalCollectionComparator.compare
test
public int compare(Collection<T> c1, Collection<T> c2) { // Simultaneously iterator over both collections until one runs out. Iterator<T> i1 = c1.iterator(); Iterator<T> i2 = c2.iterator(); while (i1.hasNext() && i2.hasNext()) { T t1 = i1.next(); T t2 = i2.next(); // Compare t1 and t2. int comp = comparator.compare(t1, t2); // Check if t1 < t2 in which case c1 < c2. if (comp < 0) { return -1; } // Check if t2 < t1 in which case c2 < c1. else if (comp > 0) { return 1; } // Otherwise t1 = t2 in which case further elements must be examined in order to determine the ordering. } // If this point is reached then one of the collections ran out of elements before the ordering was determined. // Check if c1 ran out and c2 still has elements, in which case c1 < c2. if (!i1.hasNext() && i2.hasNext()) { return -1; } // Check if c2 ran out and c1 still has elements, in which case c2 < c1. if (i1.hasNext() && !i2.hasNext()) { return 1; } // Otherwise both ran out in which case c1 = c2. return 0; }
java
{ "resource": "" }
q180312
DataStreamServlet.service
test
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { log.fine("void service(HttpServletRequest, HttpServletResponse): called"); // Read the parameters and attributes from the request String contentType = (String) request.getAttribute("contentType"); String contentDisposition = (String) request.getAttribute("contentDisposition"); InputStream inputStream = (InputStream) request.getAttribute("inputStream"); // Build the response header // response.addHeader("Content-disposition", "attachment; filename=" + fileName); if (contentType != null) { response.setContentType(contentType); } if (contentDisposition != null) { response.addHeader("Content-disposition", contentDisposition); } // response.setContentLength((int)f.length()); // Create a stream to write the data out to BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); // Read the entire input stream until no more bytes can be read and write the results into the response // This is done in chunks of 8k at a time. int length = -1; byte[] chunk = new byte[8192]; while ((length = inputStream.read(chunk)) != -1) { outputStream.write(chunk, 0, length); } // Clear up any open stream and ensure that they are flushed outputStream.flush(); inputStream.close(); }
java
{ "resource": "" }
q180313
PageControlTag.doStartTag
test
public int doStartTag() throws JspException { log.fine("public int doStartTag(): called"); TagUtils tagUtils = TagUtils.getInstance(); // Get a reference to the PagedList. PagedList list = (PagedList) tagUtils.lookup(pageContext, name, property, scope); log.fine("list = " + list); // Work out what the URL of the action to handle the paging events is. String url; try { url = tagUtils.computeURL(pageContext, null, null, null, action, null, null, null, false); } catch (MalformedURLException e) { throw new JspException("Got malformed URL exception: ", e); } // Optionally render the first page button. renderButton(renderFirst, 0, 0, openDelimFirst, url, firstText, list.getCurrentPage() != 0); // Optionally render the back button. renderButton(renderBack, list.getCurrentPage() - 1, ((list.getCurrentPage() - 1) < list.getCurrentIndex()) ? (list.getCurrentIndex() - maxPages) : list.getCurrentIndex(), openDelimBack, url, backText, (list.getCurrentPage() - 1) >= 0); // Render links for pages from the current index to the current index plus the maximum number of pages. int from = list.getCurrentIndex(); int to = list.getCurrentIndex() + maxPages; for (int i = from; (i < list.size()) && (i < to); i++) { renderButton(true, i, list.getCurrentIndex(), (i == list.getCurrentPage()) ? openDelimCurrent : openDelimNumber, url, "" + (i + 1), i != list.getCurrentPage()); } // Optionally render a more button. The more button should only be rendered if the current index plus // the maximum number of pages is less than the total number of pages so there are pages beyond those that // have numeric link to them already. renderButton((list.getCurrentIndex() + maxPages) < list.size(), list.getCurrentPage() + maxPages, list.getCurrentPage() + maxPages, openDelimMore, url, moreText, true); // Optionally render a forward button. renderButton(renderForward, list.getCurrentPage() + 1, ((list.getCurrentPage() + 1) >= (list.getCurrentIndex() + maxPages)) ? (list.getCurrentIndex() + maxPages) : list.getCurrentIndex(), openDelimForward, url, forwardText, (list.getCurrentPage() + 1) < list.size()); // Optionally render a last page button. renderButton(renderLast, list.size() - 1, (list.size() / maxPages) * maxPages, openDelimLast, url, lastText, list.getCurrentPage() != (list.size() - 1)); return SKIP_BODY; }
java
{ "resource": "" }
q180314
PageControlTag.renderButton
test
private void renderButton(boolean render, int page, int index, String openDelim, String url, String text, boolean active) throws JspException { log.fine( "private void renderButton(boolean render, int page, int index, String openDelim, String url, String text, boolean active): called"); log.fine("render = " + render); log.fine("page = " + page); log.fine("index = " + index); log.fine("openDelim = " + openDelim); log.fine("url = " + url); log.fine("text = " + text); log.fine("active = " + active); TagUtils tagUtils = TagUtils.getInstance(); if (render) { tagUtils.write(pageContext, openDelim); // Only render the button as active if the active flag is set. if (active) { tagUtils.write(pageContext, "<a href=\"" + url + "?varName=" + name + "&number=" + page + "&index=" + index + "\">" + text + "</a>"); } // Render an inactive button. else { tagUtils.write(pageContext, text); } tagUtils.write(pageContext, closeDelim); } }
java
{ "resource": "" }
q180315
AbstractLearningMethod.reset
test
public void reset() { maxSteps = 0; machineToTrain = null; inputExamples = new ArrayList<State>(); inputProperties = new HashSet<String>(); outputProperties = new HashSet<String>(); inputPropertiesSet = false; outputPropertiesSet = false; }
java
{ "resource": "" }
q180316
AbstractLearningMethod.initialize
test
protected void initialize() throws LearningFailureException { // Check that at least one training example has been set. if (inputExamples.isEmpty()) { throw new LearningFailureException("No training examples to learn from.", null); } // Check if an output property set to override the default was not set. if (!outputPropertiesSet) { // Set the 'goal' property as the default. addGoalProperty("goal"); } // Check if an input property set to override the default was not set. if (!inputPropertiesSet) { // Extract all properties from the first example in the training data set as the input property set, // automatically excluding any properties which are in the output set. State example = inputExamples.iterator().next(); Set<String> allProperties = example.getComponentType().getAllPropertyNames(); inputProperties = new HashSet<String>(allProperties); inputProperties.removeAll(outputProperties); inputPropertiesSet = true; } // Check all the training examples have all the required input and output properties. for (State example : inputExamples) { Set<String> properties = example.getComponentType().getAllPropertyNames(); String errorMessage = ""; for (String inputProperty : inputProperties) { if (!properties.contains(inputProperty)) { errorMessage += "The training example, " + example + " does not contain the specified input property, " + inputProperty + "\n"; } } for (String outputProperty : outputProperties) { if (!properties.contains(outputProperty)) { errorMessage += "The training example, " + example + " does not contain the specified output property, " + outputProperty + "\n"; } } if (!"".equals(errorMessage)) { throw new LearningFailureException(errorMessage, null); } } }
java
{ "resource": "" }
q180317
HashArray.get
test
public V get(Object key) { // Get the index from the map Integer index = keyToIndex.get(key); // Check that the key is in the map if (index == null) { return null; } // Get the data from the array return data.get(index.intValue()); }
java
{ "resource": "" }
q180318
HashArray.getIndexOf
test
public int getIndexOf(Object key) { // Get the index from the map Integer index = keyToIndex.get(key); // Check that the key is in the map and return -1 if it is not. if (index == null) { return -1; } return index; }
java
{ "resource": "" }
q180319
HashArray.set
test
public V set(int index, V value) throws IndexOutOfBoundsException { // Check if the index does not already exist if (index >= data.size()) { throw new IndexOutOfBoundsException(); } return data.set(index, value); }
java
{ "resource": "" }
q180320
HashArray.remove
test
public V remove(Object key) { // Check if the key is in the map Integer index = keyToIndex.get(key); if (index == null) { return null; } // Leave the data in the array but remove its key keyToIndex.remove(key); keySet.remove(key); // Remove the data from the array V removedValue = data.remove(index.intValue()); // Go through the whole key to index map reducing by one the value of any indexes greater that the removed index for (K nextKey : keyToIndex.keySet()) { Integer nextIndex = keyToIndex.get(nextKey); if (nextIndex > index) { keyToIndex.put(nextKey, nextIndex - 1); } } // Return the removed object return removedValue; }
java
{ "resource": "" }
q180321
HashArray.remove
test
public V remove(int index) throws IndexOutOfBoundsException { // Check that the index is not too large if (index >= data.size()) { throw new IndexOutOfBoundsException(); } // Get the key for the index by scanning through the key to index mapping for (K nextKey : keyToIndex.keySet()) { int nextIndex = keyToIndex.get(nextKey); // Found the key for the index, now remove it if (index == nextIndex) { return remove(nextKey); } } // No matching index was found throw new IndexOutOfBoundsException(); }
java
{ "resource": "" }
q180322
PropertyIntrospectorBase.hasProperty
test
public boolean hasProperty(String property) { // Check if a getter method exists for the property. Method getterMethod = getters.get(property); return getterMethod != null; }
java
{ "resource": "" }
q180323
PropertyIntrospectorBase.setProperty
test
protected void setProperty(Object callee, String property, Object value) { // Initialize this meta bean if it has not already been initialized. if (!initialized) { initialize(callee); } // Check that at least one setter method exists for the property. Method[] setterMethods = setters.get(property); if ((setterMethods == null) || (setterMethods.length == 0)) { throw new IllegalArgumentException("No setter method for the property " + property + " exists."); } // Choose which setter method to call based on the type of the value argument. If the value argument is null // then call the first available one. Method setterMethod = null; Class valueType = (value == null) ? null : value.getClass(); // Check if the value is null and use the first available setter if so, as type cannot be extracted. if (value == null) { setterMethod = setterMethods[0]; } // Loop through the available setter methods for one that matches the arguments type. else { for (Method method : setterMethods) { Class argType = method.getParameterTypes()[0]; if (argType.isAssignableFrom(valueType)) { setterMethod = method; break; } // Check if the arg type is primitive but the value type is a wrapper type that matches it. else if (argType.isPrimitive() && !valueType.isPrimitive() && isAssignableFromPrimitive(valueType, argType)) { setterMethod = method; break; } // Check if the arg type is a wrapper but the value type is a primitive type that matches it. else if (valueType.isPrimitive() && !argType.isPrimitive() && isAssignableFromPrimitive(argType, valueType)) { setterMethod = method; break; } } // Check if this point has been reached but no matching setter method could be found, in which case raise // an exception. if (setterMethod == null) { Class calleeType = (callee == null) ? null : callee.getClass(); throw new IllegalArgumentException("No setter method for property " + property + ", of type, " + calleeType + " will accept the type of value specified, " + valueType + "."); } } // Call the setter method with the value. try { Object[] args = new Object[] { value }; setterMethod.invoke(callee, args); } catch (InvocationTargetException e) { throw new IllegalArgumentException("The setter method for the property " + property + " threw an invocation target exception.", e); } // This should never happen as the initiliazed method should already have checked this. catch (IllegalAccessException e) { throw new IllegalStateException("The setter method for the property " + property + " cannot be accessed.", e); } }
java
{ "resource": "" }
q180324
PropertyIntrospectorBase.getProperty
test
protected Object getProperty(Object callee, String property) { // Initialize this meta bean if it has not already been initialized. if (!initialized) { initialize(callee); } // Check if a getter method exists for the property being fetched. Method getterMethod = getters.get(property); if (getterMethod == null) { throw new IllegalArgumentException("No getter method for the property " + property + " exists."); } // Fetch the value by calling the getter method. Object result; try { result = getterMethod.invoke(callee); } // This should never happen as the initiliazation method should already have checked this. catch (InvocationTargetException e) { throw new IllegalStateException("The getter method for the property " + property + " threw an invocation target exception.", e); } // This should never happen as the initiliazation method should already have checked this. catch (IllegalAccessException e) { throw new IllegalStateException("The getter method for the property " + property + " cannot be accessed.", e); } return result; }
java
{ "resource": "" }
q180325
PropertyIntrospectorBase.isAssignableFromPrimitive
test
private boolean isAssignableFromPrimitive(Class wrapperType, Class primitiveType) { boolean result = false; if (primitiveType.equals(boolean.class) && wrapperType.equals(Boolean.class)) { result = true; } else if (primitiveType.equals(byte.class) && wrapperType.equals(Byte.class)) { result = true; } else if (primitiveType.equals(char.class) && wrapperType.equals(Character.class)) { result = true; } else if (primitiveType.equals(short.class) && wrapperType.equals(Short.class)) { result = true; } else if (primitiveType.equals(int.class) && wrapperType.equals(Integer.class)) { result = true; } else if (primitiveType.equals(long.class) && wrapperType.equals(Long.class)) { result = true; } else if (primitiveType.equals(float.class) && wrapperType.equals(Float.class)) { result = true; } else if (primitiveType.equals(double.class) && wrapperType.equals(Double.class)) { result = true; } else { result = false; } return result; }
java
{ "resource": "" }
q180326
PropertyIntrospectorBase.initialize
test
private void initialize(Object callee) { // This is used to build up all the setter methods in. Map<String, List<Method>> settersTemp = new HashMap<String, List<Method>>(); // Get all the property getters and setters on this class. Method[] methods = callee.getClass().getMethods(); for (Method nextMethod : methods) { String methodName = nextMethod.getName(); // Check if it is a getter method. if (methodName.startsWith("get") && (methodName.length() >= 4) && Character.isUpperCase(methodName.charAt(3)) && Modifier.isPublic(nextMethod.getModifiers()) && (nextMethod.getParameterTypes().length == 0)) { String propertyName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4); getters.put(propertyName, nextMethod); } // Check if it is a setter method. else if (methodName.startsWith("set") && Modifier.isPublic(nextMethod.getModifiers()) && (nextMethod.getParameterTypes().length == 1)) { /*log.fine("Found setter method.");*/ String propertyName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4); /*log.fine("propertyName = " + propertyName);*/ // Check the setter to see if any for this name already exist, and start a new list if not. List<Method> setterMethodsForName = settersTemp.get(propertyName); if (setterMethodsForName == null) { setterMethodsForName = new ArrayList<Method>(); settersTemp.put(propertyName, setterMethodsForName); } // Add the setter method to the list of setter methods for the named property. setterMethodsForName.add(nextMethod); } } // Convert all the lists of setter methods into arrays. for (Map.Entry<String, List<Method>> entries : settersTemp.entrySet()) { String nextPropertyName = entries.getKey(); List<Method> nextMethodList = entries.getValue(); Method[] methodArray = nextMethodList.toArray(new Method[nextMethodList.size()]); setters.put(nextPropertyName, methodArray); } // Initialization completed, set the initialized flag. initialized = true; }
java
{ "resource": "" }
q180327
Decision.decide
test
public DecisionTree decide(State state) { // Extract the value of the property being decided from state to be classified. OrdinalAttribute attributeValue = (OrdinalAttribute) state.getProperty(propertyName); // Extract the child decision tree that matches the property value, using the attributes ordinal for a quick // look up. return decisions[attributeValue.ordinal()]; }
java
{ "resource": "" }
q180328
Decision.initializeLookups
test
public void initializeLookups(DecisionTree thisNode) { // Scan over all the decision trees children at this point inserting them into the lookup table depending // on the ordinal of the attribute value that matches them. for (Iterator<Tree<DecisionTreeElement>> i = thisNode.getChildIterator(); i.hasNext();) { DecisionTree nextChildTree = (DecisionTree) i.next(); // Get the matching attribute value from the childs decision tree element. OrdinalAttribute matchingValue = nextChildTree.getElement().getAttributeValue(); // Insert the matching sub-tree into the lookup table. decisions[matchingValue.ordinal()] = nextChildTree; } }
java
{ "resource": "" }
q180329
PrologUnifier.unify
test
public List<Variable> unify(Term query, Term statement) { /*log.fine("unify(Term left = " + query + ", Term right = " + statement + "): called");*/ // Find all free variables in the query. Set<Variable> freeVars = TermUtils.findFreeNonAnonymousVariables(query); // Build up all the variable bindings in both sides of the unification in these bindings. List<Variable> queryBindings = new LinkedList<Variable>(); List<Variable> statementBindings = new LinkedList<Variable>(); // Fund the most general unifier, if possible. boolean unified = unifyInternal(query, statement, queryBindings, statementBindings); List<Variable> results = null; // If a unification was found, only retain the free variables in the query in the results returned. if (unified) { queryBindings.retainAll(freeVars); results = new ArrayList<Variable>(queryBindings); } return results; }
java
{ "resource": "" }
q180330
PrologUnifier.unifyInternal
test
public boolean unifyInternal(Term left, Term right, List<Variable> leftTrail, List<Variable> rightTrail) { /*log.fine("public boolean unifyInternal(Term left = " + left + ", Term right = " + right + ", List<Variable> trail = " + leftTrail + "): called");*/ if (left == right) { /*log.fine("Terms are identical objects.");*/ return true; } if (!left.isVar() && !right.isVar() && left.isConstant() && right.isConstant() && left.equals(right)) { /*log.fine("Terms are equal atoms or literals.");*/ return true; } else if (left.isVar()) { /*log.fine("Left is a variable.");*/ return unifyVar((Variable) left, right, leftTrail, rightTrail); } else if (right.isVar()) { /*log.fine("Right is a variable.");*/ return unifyVar((Variable) right, left, rightTrail, leftTrail); } else if (left.isFunctor() && right.isFunctor()) { /*log.fine("Terms are functors, at least one of which is not an atom.");*/ Functor leftFunctor = (Functor) left; Functor rightFunctor = (Functor) right; // Check if the functors may be not be equal (that is, they do not have the same name and arity), in // which case they cannot possibly be unified. if (!left.equals(right)) { return false; } /*log.fine("Terms are functors with same name and arity, both are compound.");*/ // Pairwise unify all of the arguments of the functor. int arity = leftFunctor.getArity(); for (int i = 0; i < arity; i++) { Term leftArgument = leftFunctor.getArgument(i); Term rightArgument = rightFunctor.getArgument(i); boolean result = unifyInternal(leftArgument, rightArgument, leftTrail, rightTrail); if (!result) { /*log.fine("Non unifying arguments in functors encountered, left = " + leftArgument + ", right = " + rightArgument);*/ return false; } } return true; } else { return false; } }
java
{ "resource": "" }
q180331
PrologUnifier.unifyVar
test
protected boolean unifyVar(Variable leftVar, Term rightTerm, List<Variable> leftTrail, List<Variable> rightTrail) { /*log.fine("protected boolean unifyVar(Variable var = " + leftVar + ", Term term = " + rightTerm + ", List<Variable> trail = " + leftTrail + "): called");*/ // Check if the variable is bound (in the trail, but no need to explicitly check the trail as the binding is // already held against the variable). if (leftVar.isBound()) { /*log.fine("Variable is bound.");*/ return unifyInternal(leftVar.getValue(), rightTerm, leftTrail, rightTrail); } else if (rightTerm.isVar() && ((Variable) rightTerm).isBound()) { // The variable is free, but the term itself is a bound variable, in which case unify againt the value // of the term. /*log.fine("Term is a bound variable.");*/ return unifyInternal(leftVar, rightTerm.getValue(), leftTrail, rightTrail); } else { // Otherwise, unify by binding the variable to the value of the term. /*log.fine("Variable is free, substituting in the term for it.");*/ leftVar.setSubstitution(rightTerm); leftTrail.add(leftVar.getStorageCell(leftVar)); //leftTrail.add(leftVar); return true; } // Occurs can go above if desired. /*else if (var occurs anywhere in x) { return false; }*/ }
java
{ "resource": "" }
q180332
InstructionCompiler.compileQuery
test
private void compileQuery(Clause clause) throws SourceCodeException { // Used to build up the compiled result in. WAMCompiledQuery result; // A mapping from top stack frame slots to interned variable names is built up in this. // This is used to track the stack positions that variables in a query are assigned to. Map<Byte, Integer> varNames = new TreeMap<Byte, Integer>(); // Used to keep track of registers as they are seen during compilation. The first time a variable is seen, // a variable is written onto the heap, subsequent times its value. The first time a functor is seen, // its structure is written onto the heap, subsequent times it is compared with. seenRegisters = new TreeSet<Integer>(); // This is used to keep track of the next temporary register available to allocate. lastAllocatedTempReg = findMaxArgumentsInClause(clause); // This is used to keep track of the number of permanent variables. numPermanentVars = 0; // This is used to keep track of the allocation slot for the cut level variable, when needed. -1 means it is // not needed, so it is initialized to this. cutLevelVarSlot = -1; // These are used to generate pre and post instructions for the clause, for example, for the creation and // clean-up of stack frames. SizeableList<WAMInstruction> preFixInstructions = new SizeableLinkedList<WAMInstruction>(); SizeableList<WAMInstruction> postFixInstructions = new SizeableLinkedList<WAMInstruction>(); // Find all the free non-anonymous variables in the clause. Set<Variable> freeVars = TermUtils.findFreeNonAnonymousVariables(clause); Set<Integer> freeVarNames = new TreeSet<Integer>(); for (Variable var : freeVars) { freeVarNames.add(var.getName()); } // Allocate permanent variables for a query. In queries all variables are permanent so that they are preserved // on the stack upon completion of the query. allocatePermanentQueryRegisters(clause, varNames); // Gather information about the counts and positions of occurrence of variables and constants within the clause. gatherPositionAndOccurrenceInfo(clause); result = new WAMCompiledQuery(varNames, freeVarNames); // Generate the prefix code for the clause. Queries require a stack frames to hold their environment. /*log.fine("ALLOCATE " + numPermanentVars);*/ preFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.AllocateN, REG_ADDR, (byte) (numPermanentVars & 0xff))); // Deep cuts require the current choice point to be kept in a permanent variable, so that it can be recovered // once deeper choice points or environments have been reached. if (cutLevelVarSlot >= 0) { /*log.fine("GET_LEVEL "+ cutLevelVarSlot);*/ preFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.GetLevel, STACK_ADDR, (byte) cutLevelVarSlot)); } result.addInstructions(preFixInstructions); // Compile all of the conjunctive parts of the body of the clause, if there are any. Functor[] expressions = clause.getBody(); // The current query does not have a name, so invent one for it. FunctorName fn = new FunctorName("tq", 0); for (int i = 0; i < expressions.length; i++) { Functor expression = expressions[i]; boolean isFirstBody = i == 0; // Select a non-default built-in implementation to compile the functor with, if it is a built-in. BuiltIn builtIn; if (expression instanceof BuiltIn) { builtIn = (BuiltIn) expression; } else { builtIn = this; } // The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule, which it // never is for a query. SizeableLinkedList<WAMInstruction> instructions = builtIn.compileBodyArguments(expression, false, fn, i); result.addInstructions(expression, instructions); // Queries are never chain rules, and as all permanent variables are preserved, bodies are never called // as last calls. instructions = builtIn.compileBodyCall(expression, isFirstBody, false, false, numPermanentVars); result.addInstructions(expression, instructions); } // Generate the postfix code for the clause. /*log.fine("DEALLOCATE");*/ postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Suspend)); postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Deallocate)); result.addInstructions(postFixInstructions); // Run the optimizer on the output. result = optimizer.apply(result); displayCompiledQuery(result); observer.onQueryCompilation(result); }
java
{ "resource": "" }
q180333
InstructionCompiler.findMaxArgumentsInClause
test
private int findMaxArgumentsInClause(Clause clause) { int result = 0; Functor head = clause.getHead(); if (head != null) { result = head.getArity(); } Functor[] body = clause.getBody(); if (body != null) { for (int i = 0; i < body.length; i++) { int arity = body[i].getArity(); result = (arity > result) ? arity : result; } } return result; }
java
{ "resource": "" }
q180334
InstructionCompiler.allocatePermanentQueryRegisters
test
private void allocatePermanentQueryRegisters(Term clause, Map<Byte, Integer> varNames) { // Allocate local variable slots for all variables in a query. QueryRegisterAllocatingVisitor allocatingVisitor = new QueryRegisterAllocatingVisitor(symbolTable, varNames, null); PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl(); positionalTraverser.setContextChangeVisitor(allocatingVisitor); TermWalker walker = new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, allocatingVisitor); walker.walk(clause); }
java
{ "resource": "" }
q180335
InstructionCompiler.gatherPositionAndOccurrenceInfo
test
private void gatherPositionAndOccurrenceInfo(Term clause) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl(); PositionAndOccurrenceVisitor positionAndOccurrenceVisitor = new PositionAndOccurrenceVisitor(interner, symbolTable, positionalTraverser); positionalTraverser.setContextChangeVisitor(positionAndOccurrenceVisitor); TermWalker walker = new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, positionAndOccurrenceVisitor); walker.walk(clause); }
java
{ "resource": "" }
q180336
InstructionCompiler.displayCompiledPredicate
test
private void displayCompiledPredicate(Term predicate) { // Pretty print the clause. StringBuffer result = new StringBuffer(); PositionalTermVisitor displayVisitor = new WAMCompiledPredicatePrintingVisitor(interner, symbolTable, result); TermWalkers.positionalWalker(displayVisitor).walk(predicate); /*log.fine(result.toString());*/ }
java
{ "resource": "" }
q180337
InstructionCompiler.displayCompiledQuery
test
private void displayCompiledQuery(Term query) { // Pretty print the clause. StringBuffer result = new StringBuffer(); PositionalTermVisitor displayVisitor = new WAMCompiledQueryPrintingVisitor(interner, symbolTable, result); TermWalkers.positionalWalker(displayVisitor).walk(query); /*log.fine(result.toString());*/ }
java
{ "resource": "" }
q180338
ByteBufferUtils.putPaddedInt32AsString
test
public static ByteBuffer putPaddedInt32AsString(ByteBuffer buffer, int value, int length) { // Ensure there is sufficient space in the buffer to hold the result. int charsRequired = BitHackUtils.getCharacterCountInt32(value); length = (charsRequired < length) ? length : charsRequired; // Take an explicit index into the buffer to start writing to, as the numbers will be written backwards. int index = buffer.position() + length - 1; // Record the start position, to remember if a minus sign was written or not, so that it does not get // overwritten by the zero padding. int start = buffer.position(); // Advance the buffer position manually, as the characters will be written to specific indexes backwards. buffer.position(buffer.position() + length); // Take care of the minus sign for negative numbers. if (value < 0) { buffer.put(MINUS_ASCII); start++; // Stop padding code overwriting minus sign. } else { value = -value; } // Write the digits least significant to most significant into the buffer. As the number was converted to be // negative the remainders will be negative too. do { int remainder = value % 10; value = value / 10; buffer.put(index--, ((byte) (ZERO_ASCII - remainder))); } while (value != 0); // Write out the padding zeros. while (index >= start) { buffer.put(index--, ZERO_ASCII); } return buffer; }
java
{ "resource": "" }
q180339
ByteBufferUtils.asString
test
public static String asString(ByteBuffer buffer, int length) { char[] chars = new char[length]; for (int i = 0; i < length; i++) { chars[i] = (char) buffer.get(i); } return String.valueOf(chars); }
java
{ "resource": "" }
q180340
EnumeratedStringAttribute.getStringValue
test
public String getStringValue() { // Check if the attribute class has been finalized yet. if (attributeClass.finalized) { // Fetch the string value from the attribute class. return attributeClass.lookupValue[value].label; } else { return attributeClass.lookupValueList.get(value).label; } }
java
{ "resource": "" }
q180341
EnumeratedStringAttribute.setStringValue
test
public void setStringValue(String value) throws IllegalArgumentException { Byte b = attributeClass.lookupByte.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 EnumeratedStringType, " + 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. EnumeratedStringAttribute newAttribute = attributeClass.createStringAttribute(value); b = newAttribute.value; } } // Set the new value as the value of this attribute. this.value = b; }
java
{ "resource": "" }
q180342
LojixTermReader.read
test
private void read(Term term) { if (term.isNumber()) { NumericType numericType = (NumericType) term; if (numericType.isInteger()) { IntLiteral jplInteger = (IntLiteral) term; getContentHandler().startIntegerTerm(jplInteger.longValue()); } else if (numericType.isFloat()) { FloatLiteral jplFloat = (FloatLiteral) term; getContentHandler().startFloatTerm(jplFloat.doubleValue()); } } else if (term.isVar()) { Variable var = (Variable) term; getContentHandler().startVariable(interner.getVariableName(var.getName())); } else if (term.isAtom()) { Functor atom = (Functor) term; getContentHandler().startAtom(interner.getFunctorName(atom.getName())); } else if (term.isCompound()) { Functor functor = (Functor) term; getContentHandler().startCompound(); getContentHandler().startAtom(interner.getFunctorName(functor.getName())); for (com.thesett.aima.logic.fol.Term child : functor.getArguments()) { read(child); } getContentHandler().endCompound(); } else { throw new IllegalStateException("Unrecognized Lojix term: " + term); } }
java
{ "resource": "" }
q180343
ReflectionUtils.classExistsAndIsLoadable
test
public static boolean classExistsAndIsLoadable(String className) { try { Class.forName(className); return true; } catch (ClassNotFoundException e) { // Exception noted and ignored. e = null; return false; } }
java
{ "resource": "" }
q180344
ReflectionUtils.isSubTypeOf
test
public static boolean isSubTypeOf(Class parent, String className) { try { Class cls = Class.forName(className); return parent.isAssignableFrom(cls); } catch (ClassNotFoundException e) { // Exception noted and ignored. e = null; return false; } }
java
{ "resource": "" }
q180345
ReflectionUtils.isSubTypeOf
test
public static boolean isSubTypeOf(String parent, String child) { try { return isSubTypeOf(Class.forName(parent), Class.forName(child)); } catch (ClassNotFoundException e) { // Exception noted so can be ignored. e = null; return false; } }
java
{ "resource": "" }
q180346
ReflectionUtils.isSubTypeOf
test
public static boolean isSubTypeOf(Class parentClass, Class childClass) { try { // Check that the child class can be cast as a sub-type of the parent. childClass.asSubclass(parentClass); return true; } catch (ClassCastException e) { // Exception noted so can be ignored. e = null; return false; } }
java
{ "resource": "" }
q180347
ReflectionUtils.forName
test
public static Class<?> forName(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new ReflectionUtilsException("ClassNotFoundException whilst finding class: " + className + ".", e); } }
java
{ "resource": "" }
q180348
ReflectionUtils.newInstance
test
public static <T> T newInstance(Class<T> cls) { try { return cls.newInstance(); } catch (InstantiationException e) { throw new ReflectionUtilsException("InstantiationException whilst instantiating class.", e); } catch (IllegalAccessException e) { throw new ReflectionUtilsException("IllegalAccessException whilst instantiating class.", e); } }
java
{ "resource": "" }
q180349
ReflectionUtils.newInstance
test
public static <T> T newInstance(Constructor<T> constructor, Object[] args) { try { return constructor.newInstance(args); } catch (InstantiationException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q180350
ReflectionUtils.callMethodOverridingIllegalAccess
test
public static Object callMethodOverridingIllegalAccess(Object o, String method, Object[] params, Class[] paramClasses) { // Get the objects class. Class cls = o.getClass(); // Get the classes of the parameters. /*Class[] paramClasses = new Class[params.length]; for (int i = 0; i < params.length; i++) { paramClasses[i] = params[i].getClass(); }*/ try { // Try to find the matching method on the class. Method m = cls.getDeclaredMethod(method, paramClasses); // Make it accessible. m.setAccessible(true); // Invoke it with the parameters. return m.invoke(o, params); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q180351
ReflectionUtils.callMethod
test
public static Object callMethod(Object o, String method, Object[] params) { // Get the objects class. Class cls = o.getClass(); // Get the classes of the parameters. Class[] paramClasses = new Class[params.length]; for (int i = 0; i < params.length; i++) { paramClasses[i] = params[i].getClass(); } try { // Try to find the matching method on the class. Method m = cls.getMethod(method, paramClasses); // Invoke it with the parameters. return m.invoke(o, params); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q180352
ReflectionUtils.callStaticMethod
test
public static Object callStaticMethod(Method method, Object[] params) { try { return method.invoke(null, params); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q180353
ReflectionUtils.getConstructor
test
public static <T> Constructor<T> getConstructor(Class<T> cls, Class[] args) { try { return cls.getConstructor(args); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q180354
ReflectionUtils.findMatchingSetters
test
public static Set<Class> findMatchingSetters(Class obClass, String propertyName) { /*log.fine("private Set<Class> findMatchingSetters(Object ob, String propertyName): called");*/ Set<Class> types = new HashSet<Class>(); // Convert the first letter of the property name to upper case to match against the upper case version of // it that will be in the setter method name. For example the property test will have a setter method called // setTest. String upperPropertyName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); // Scan through all the objects methods. Method[] methods = obClass.getMethods(); for (Method nextMethod : methods) { // Get the next method. /*log.fine("nextMethod = " + nextMethod.getName());*/ // Check if a method has the correct name, accessibility and the correct number of arguments to be a setter // method for the property. String methodName = nextMethod.getName(); if (methodName.equals("set" + upperPropertyName) && Modifier.isPublic(nextMethod.getModifiers()) && (nextMethod.getParameterTypes().length == 1)) { /*log.fine(methodName + " is a valid setter method for the property " + propertyName + " with argument of type " + nextMethod.getParameterTypes()[0]);*/ // Add its argument type to the array of setter types. types.add(nextMethod.getParameterTypes()[0]); } } return types; }
java
{ "resource": "" }
q180355
Queues.getTransactionalQueue
test
public static <E> Queue<E> getTransactionalQueue(java.util.Queue<E> queue) { return new WrapperQueue<E>(queue, new LinkedList<E>(), true, false, false); }
java
{ "resource": "" }
q180356
Queues.getTransactionalReQueue
test
public static <E> Queue<E> getTransactionalReQueue(java.util.Queue<E> queue, Collection<E> requeue) { return new WrapperQueue<E>(queue, requeue, true, false, false); }
java
{ "resource": "" }
q180357
TypeHelper.getTypeFromObject
test
public static Type getTypeFromObject(Object o) { // Check if the object is null, in which case its type cannot be derived. if (o == null) { return new UnknownType(); } // Check if the object is an attribute a and get its type that way if possible. if (o instanceof Attribute) { return ((Attribute) o).getType(); } // Return an approproate Type for the java primitive, wrapper or class type of the argument. return new JavaType(o); }
java
{ "resource": "" }
q180358
BaseQueueSearch.reset
test
public void reset() { // Clear out the start states. startStates.clear(); enqueuedOnce = false; // Reset the queue to a fresh empty queue. queue = createQueue(); // Clear the goal predicate. goalPredicate = null; // Reset the maximum steps limit maxSteps = 0; // Reset the number of steps taken searchSteps = 0; // Reset the repeated state filter if there is one. if (repeatedStateFilter != null) { repeatedStateFilter.reset(); } // Reset the search alogorithm if it requires resettting. searchAlgorithm.reset(); }
java
{ "resource": "" }
q180359
BaseQueueSearch.search
test
public T search() throws SearchNotExhaustiveException { SearchNode<O, T> path = findGoalPath(); if (path != null) { return path.getState(); } else { return null; } }
java
{ "resource": "" }
q180360
IntRangeType.createInstance
test
public static Type createInstance(String name, int min, int 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 (INT_RANGE_TYPES) { // Add the newly created type to the map of all types. IntRangeType newType = new IntRangeType(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. IntRangeType 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": "" }
q180361
SchemaDefinitionImpl.addSupportedTZ
test
public void addSupportedTZ(String tzName) { if (!StringUtils.isBlank(tzName) && !tzNamesAliases.containsKey(tzName.trim())) { tzNamesAliases.put(tzName.trim(), tzName.trim()); if (LOG.isInfoEnabled()) { LOG.info("Endpoint " + this.getEndPointName() + " - add support of TZ: " + tzName); } } }
java
{ "resource": "" }
q180362
SchemaDefinitionImpl.addTZAlternateDimension
test
public void addTZAlternateDimension(String orignalDimensionName, DimensionTable alternateDimension, String tzName) { addSupportedTZ(tzName); if (tzNamesAliases.containsValue(tzName)) { sqlTables.put(alternateDimension.getTableName(), alternateDimension); alternateDimensions.put(Pair.of(orignalDimensionName.toUpperCase(), tzName), alternateDimension); } else { LOG.error("Unsuported timezone: " + tzName); } }
java
{ "resource": "" }
q180363
SchemaDefinitionImpl.addDimension
test
public void addDimension(DimensionTable table, boolean mandatory) { sqlTables.put(table.getTableName(), table); dimensions.put(table.getDimensionName().toUpperCase(), table); if (mandatory) { mandatoryDimensionNames.add(table.getDimensionName().toUpperCase(Locale.ENGLISH)); } }
java
{ "resource": "" }
q180364
TermUtils.findFreeVariables
test
public static Set<Variable> findFreeVariables(Term query) { QueueBasedSearchMethod<Term, Term> freeVarSearch = new DepthFirstSearch<Term, Term>(); freeVarSearch.reset(); freeVarSearch.addStartState(query); freeVarSearch.setGoalPredicate(new FreeVariablePredicate()); return (Set<Variable>) (Set) Searches.setOf(freeVarSearch); }
java
{ "resource": "" }
q180365
TermUtils.findFreeNonAnonymousVariables
test
public static Set<Variable> findFreeNonAnonymousVariables(Term query) { QueueBasedSearchMethod<Term, Term> freeVarSearch = new DepthFirstSearch<Term, Term>(); freeVarSearch.reset(); freeVarSearch.addStartState(query); freeVarSearch.setGoalPredicate(new FreeNonAnonymousVariablePredicate()); return (Set<Variable>) (Set) Searches.setOf(freeVarSearch); }
java
{ "resource": "" }
q180366
GreedyComparator.compare
test
public int compare(SearchNode object1, SearchNode object2) { float h1 = ((HeuristicSearchNode) object1).getH(); float h2 = ((HeuristicSearchNode) object2).getH(); return (h1 > h2) ? 1 : ((h1 < h2) ? -1 : 0); }
java
{ "resource": "" }
q180367
FileUtils.writeObjectToFile
test
public static void writeObjectToFile(String outputFileName, Object toWrite, boolean append) { // Open the output file. Writer resultWriter; try { resultWriter = new FileWriter(outputFileName, append); } catch (IOException e) { throw new IllegalStateException("Unable to open the output file '" + outputFileName + "' for writing.", e); } // Write the object into the output file. try { resultWriter.write(toWrite.toString()); resultWriter.flush(); resultWriter.close(); } catch (IOException e) { throw new IllegalStateException("There was an error whilst writing to the output file '" + outputFileName + "'.", e); } }
java
{ "resource": "" }
q180368
FileUtils.readStreamAsString
test
private static String readStreamAsString(BufferedInputStream is) { try { byte[] data = new byte[4096]; StringBuffer inBuffer = new StringBuffer(); int read; while ((read = is.read(data)) != -1) { String s = new String(data, 0, read); inBuffer.append(s); } return inBuffer.toString(); } catch (IOException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q180369
BaseHeuristicSearch.createSearchNode
test
public SearchNode<O, T> createSearchNode(T state) { return new HeuristicSearchNode<O, T>(state, heuristic); }
java
{ "resource": "" }
q180370
TraceIndenter.generateTraceIndent
test
public String generateTraceIndent(int delta) { if (!useIndent) { return ""; } else { if (delta >= 1) { indentStack.push(delta); } else if (delta < 0) { indentStack.pop(); } StringBuffer result = new StringBuffer(); traceIndent += (delta < 0) ? delta : 0; for (int i = 0; i < traceIndent; i++) { result.append(" "); } traceIndent += (delta > 0) ? delta : 0; return result.toString(); } }
java
{ "resource": "" }
q180371
DefaultBuiltIn.allocateArgumentRegisters
test
protected void allocateArgumentRegisters(Functor expression) { // Assign argument registers to functors appearing directly in the argument of the outermost functor. // Variables are never assigned directly to argument registers. int reg = 0; for (; reg < expression.getArity(); reg++) { Term term = expression.getArgument(reg); if (term instanceof Functor) { /*log.fine("X" + lastAllocatedTempReg + " = " + interner.getFunctorFunctorName((Functor) term));*/ int allocation = (reg & 0xff) | (REG_ADDR << 8); symbolTable.put(term.getSymbolKey(), SymbolTableKeys.SYMKEY_ALLOCATION, allocation); } } }
java
{ "resource": "" }
q180372
DefaultBuiltIn.isLastBodyTermInArgPositionOnly
test
private boolean isLastBodyTermInArgPositionOnly(Term var, Functor body) { return body == symbolTable.get(var.getSymbolKey(), SymbolTableKeys.SYMKEY_VAR_LAST_ARG_FUNCTOR); }
java
{ "resource": "" }
q180373
ProtoDTLearningMethod.getMajorityClassification
test
private OrdinalAttribute getMajorityClassification(String property, Iterable<State> examples) throws LearningFailureException { /*log.fine("private OrdinalAttribute getMajorityClassification(String property, Collection<State> examples): called");*/ /*log.fine("property = " + property);*/ // Flag used to indicate that the map to hold the value counts in has been initialized. Map<OrdinalAttribute, Integer> countMap = null; // Used to hold the biggest count found so far. int biggestCount = 0; // Used to hold the value with the biggest count found so far. OrdinalAttribute biggestAttribute = null; // Loop over all the examples counting the number of occurences of each possible classification by the // named property. for (State example : examples) { OrdinalAttribute nextAttribute = (OrdinalAttribute) example.getProperty(property); /*log.fine("nextAttribute = " + nextAttribute);*/ // If this is the first attribute then find out how many possible values it can take on. if (countMap == null) { // A check has already been performed at the start of the learning method to ensure that the output // property only takes on a finite number of values. countMap = new HashMap<OrdinalAttribute, Integer>(); } int count; // Increment the count for the number of occurences of this classification. if (!countMap.containsKey(nextAttribute)) { count = 1; countMap.put(nextAttribute, count); } else { count = countMap.get(nextAttribute); countMap.put(nextAttribute, count++); } // Compare it to the biggest score found so far to see if it is bigger. if (count > biggestCount) { // Update the biggest score. biggestCount = count; // Update the value of the majority classification. biggestAttribute = nextAttribute; } } // Return the majority classification found. return biggestAttribute; }
java
{ "resource": "" }
q180374
ProtoDTLearningMethod.allHaveSameClassification
test
private boolean allHaveSameClassification(String property, Iterable<State> examples) { // Used to hold the value of the first attribute seen. OrdinalAttribute firstAttribute = null; // Flag used to indicate that the test passed successfully. boolean success = true; // Loop over all the examples. for (State example : examples) { OrdinalAttribute nextAttribute = (OrdinalAttribute) example.getProperty(property); // If this is the first example just store its attribute value. if (firstAttribute == null) { firstAttribute = nextAttribute; } // Otherwise check if the attribute value does not match the first one in which case the test fails. else if (!nextAttribute.equals(firstAttribute)) { success = false; break; } } // If the test passed then store the matching classification that all the examples have in a memeber variable // from where it can be accessed. if (success) { allClassification = firstAttribute; } return success; }
java
{ "resource": "" }
q180375
ProtoDTLearningMethod.chooseBestPropertyToDecideOn
test
private String chooseBestPropertyToDecideOn(String outputProperty, Iterable<State> examples, Iterable<String> inputProperties) { /*log.fine("private String chooseBestPropertyToDecideOn(String outputProperty, Collection<State> examples, " + "Collection<String> inputProperties): called");*/ // for (State e : examples) /*log.fine(e);*/ // Determine how many possible values (symbols) the output property can have. int numOutputValues = examples.iterator().next().getComponentType().getPropertyType(outputProperty).getNumPossibleValues(); // Used to hold the largest information gain found so far. double largestGain = 0.0d; // Used to hold the input property that gives the largest gain found so far. String largestGainProperty = null; // Loop over all the input properties. for (String inputProperty : inputProperties) { // let G = the set of goal property values. // let A = the set of property values that the input property can have. // Determine how many possible values (symbols) the input property can have. int numInputValues = examples.iterator().next().getComponentType().getPropertyType(inputProperty).getNumPossibleValues(); // Create an array to hold the counts of the output symbols. int[] outputCounts = new int[numOutputValues]; // Create arrays to hold the counts of the input symbols and the joint input/output counts. int[] inputCounts = new int[numInputValues]; int[][] jointCounts = new int[numInputValues][numOutputValues]; // Loop over all the examples. for (State example : examples) { // Extract the output property attribute value. OrdinalAttribute outputAttribute = (OrdinalAttribute) example.getProperty(outputProperty); // Extract the input property attribute value. OrdinalAttribute inputAttribute = (OrdinalAttribute) example.getProperty(inputProperty); // Increment the count for the occurence of this value of the output property. outputCounts[outputAttribute.ordinal()]++; // Increment the count for the occurence of this value of the input property. inputCounts[inputAttribute.ordinal()]++; // Increment the count for the joint occurrence of this input/output value pair. jointCounts[inputAttribute.ordinal()][outputAttribute.ordinal()]++; } // Calculate the estimated probability distribution of G from the occurrence counts over the examples. double[] pForG = InformationTheory.pForDistribution(outputCounts); // Calculate the estimated probability distribution of A from the occurrence counts over the examples. double[] pForA = InformationTheory.pForDistribution(inputCounts); // Calculate the estimated probability distribution p(g|a) from the joint occurrence counts over the // examples. double[][] pForGGivenA = InformationTheory.pForJointDistribution(jointCounts); // Calculate the information gain on G by knowing A. double gain = InformationTheory.gain(pForG, pForA, pForGGivenA); // Check if the gain is larger than the best found so far and update the best if so. if (gain > largestGain) { largestGain = gain; largestGainProperty = inputProperty; } } return largestGainProperty; }
java
{ "resource": "" }
q180376
TermBuilder.functor
test
public Functor functor(String name, Term... args) { int internedName = interner.internFunctorName(name, args.length); return new Functor(internedName, args); }
java
{ "resource": "" }
q180377
TermBuilder.var
test
public Variable var(String name) { boolean isAnonymous = name.startsWith("_"); int internedName = interner.internVariableName(name); return new Variable(internedName, null, isAnonymous); }
java
{ "resource": "" }
q180378
RedirectAction.executeWithErrorHandling
test
public ActionForward executeWithErrorHandling(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, ActionErrors errors) { log.fine("public ActionForward performWithErrorHandling(ActionMapping mapping, ActionForm form," + "HttpServletRequest request, HttpServletResponse response, " + "ActionErrors errors): called"); HttpSession session = request.getSession(); DynaBean dynaForm = (DynaActionForm) form; // Redirect to the specified location String redirect = (String) dynaForm.get(REDIRECT); log.fine("redirect = " + redirect); return new ActionForward(redirect, true); }
java
{ "resource": "" }
q180379
PagedList.get
test
public List<E> get(int index) { /*log.fine("public List<E> get(int index): called");*/ // Check that the index is not to large. int originalSize = original.size(); int size = (originalSize / pageSize) + (((originalSize % pageSize) == 0) ? 0 : 1); /*log.fine("originalSize = " + originalSize);*/ /*log.fine("size = " + size);*/ // Check if the size of the underlying list is zero, in which case return an empty list, so long as page zero // was requested. if ((index == 0) && (originalSize == 0)) { return new ArrayList<E>(); } // Check if the requested index exceeds the number of pages, or is an illegal negative value. if ((index >= size) || (index < 0)) { /*log.fine("(index >= size) || (index < 0), throwing out of bounds exception.");*/ throw new IndexOutOfBoundsException("Index " + index + " is less than zero or more than the number of pages: " + size); } // Extract the appropriate sub-list. // Note that if this is the last page it may not be a full page. Just up to the last page will be returned. /*log.fine("Requesting sublist from, " + (pageSize * index) + ", to ," + (((pageSize * (index + 1)) >= originalSize) ? originalSize : (pageSize * (index + 1))) + ".");*/ List<E> result = original.subList(pageSize * index, ((pageSize * (index + 1)) >= originalSize) ? originalSize : (pageSize * (index + 1))); return result; }
java
{ "resource": "" }
q180380
Surface.setTexture
test
public void setTexture(Paint obj) { if (obj instanceof GradientPaint) { texture = new GradientPaint(0, 0, Color.white, getSize().width * 2, 0, Color.green); } else { texture = obj; } }
java
{ "resource": "" }
q180381
Surface.paintImmediately
test
public void paintImmediately(int x, int y, int w, int h) { RepaintManager repaintManager = null; boolean save = true; if (!isDoubleBuffered()) { repaintManager = RepaintManager.currentManager(this); save = repaintManager.isDoubleBufferingEnabled(); repaintManager.setDoubleBufferingEnabled(false); } super.paintImmediately(x, y, w, h); if (repaintManager != null) { repaintManager.setDoubleBufferingEnabled(save); } }
java
{ "resource": "" }
q180382
Surface.createBufferedImage
test
protected BufferedImage createBufferedImage(int w, int h, int imgType) { BufferedImage bi = null; if (imgType == 0) { bi = (BufferedImage) createImage(w, h); } else if ((imgType > 0) && (imgType < 14)) { bi = new BufferedImage(w, h, imgType); } else if (imgType == 14) { bi = createBinaryImage(w, h, 2); } else if (imgType == 15) { bi = createBinaryImage(w, h, 4); } else if (imgType == 16) { bi = createSGISurface(w, h, 32); } else if (imgType == 17) { bi = createSGISurface(w, h, 16); } // Store the buffered image size biw = w; bih = h; return bi; }
java
{ "resource": "" }
q180383
Surface.createGraphics2D
test
protected Graphics2D createGraphics2D(int width, int height, BufferedImage bi, Graphics g) { Graphics2D g2 = null; // Check if the buffered image is null if (bi != null) { // Create Graphics2D context for the buffered image g2 = bi.createGraphics(); } else { // The buffered image is null so create Graphics2D context for the Graphics context g2 = (Graphics2D) g; } // @todo what is this for? g2.setBackground(getBackground()); // Set the rendering properties of the graphics context g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAlias); g2.setRenderingHint(RenderingHints.KEY_RENDERING, rendering); // Check the clear flags to see if the graphics context should be cleared if (clearSurface || clearOnce) { // Clear the image g2.clearRect(0, 0, width, height); // Reset the clear once flag to show that clearing has been done clearOnce = false; } // Check if a background fill texture is to be used if (texture != null) { // set composite to opaque for texture fills g2.setComposite(AlphaComposite.SrcOver); g2.setPaint(texture); g2.fillRect(0, 0, width, height); } // Check if alpha compositing is to be used if (composite != null) { // Set the alpha compositing algorithm g2.setComposite(composite); } return g2; }
java
{ "resource": "" }
q180384
Surface.createBinaryImage
test
private BufferedImage createBinaryImage(int w, int h, int pixelBits) { int bytesPerRow = w * pixelBits / 8; if ((w * pixelBits % 8) != 0) { bytesPerRow++; } byte[] imageData = new byte[h * bytesPerRow]; IndexColorModel cm = null; switch (pixelBits) { case 1: { cm = new IndexColorModel(pixelBits, lut1Arr.length, lut1Arr, lut1Arr, lut1Arr); break; } case 2: { cm = new IndexColorModel(pixelBits, lut2Arr.length, lut2Arr, lut2Arr, lut2Arr); break; } case 4: { cm = new IndexColorModel(pixelBits, lut4Arr.length, lut4Arr, lut4Arr, lut4Arr); break; } default: { new Exception("Invalid # of bit per pixel").printStackTrace(); } } DataBuffer db = new DataBufferByte(imageData, imageData.length); WritableRaster r = Raster.createPackedRaster(db, w, h, pixelBits, null); return new BufferedImage(cm, r, false, null); }
java
{ "resource": "" }
q180385
Surface.createSGISurface
test
private BufferedImage createSGISurface(int w, int h, int pixelBits) { int rMask32 = 0xFF000000; int rMask16 = 0xF800; int gMask32 = 0x00FF0000; int gMask16 = 0x07C0; int bMask32 = 0x0000FF00; int bMask16 = 0x003E; DirectColorModel dcm = null; DataBuffer db = null; WritableRaster wr = null; switch (pixelBits) { case 16: { short[] imageDataUShort = new short[w * h]; dcm = new DirectColorModel(16, rMask16, gMask16, bMask16); db = new DataBufferUShort(imageDataUShort, imageDataUShort.length); wr = Raster.createPackedRaster(db, w, h, w, new int[] { rMask16, gMask16, bMask16 }, null); break; } case 32: { int[] imageDataInt = new int[w * h]; dcm = new DirectColorModel(32, rMask32, gMask32, bMask32); db = new DataBufferInt(imageDataInt, imageDataInt.length); wr = Raster.createPackedRaster(db, w, h, w, new int[] { rMask32, gMask32, bMask32 }, null); break; } default: { new Exception("Invalid # of bit per pixel").printStackTrace(); } } return new BufferedImage(dcm, wr, false, null); }
java
{ "resource": "" }
q180386
PostFixSearch.setQueueSearchAlgorithm
test
protected void setQueueSearchAlgorithm(QueueSearchAlgorithm<O, T> algorithm) { algorithm.setPeekAtHead(true); algorithm.setReverseEnqueueOrder(true); super.setQueueSearchAlgorithm(algorithm); }
java
{ "resource": "" }
q180387
IterativeBoundAlgorithm.search
test
public SearchNode search(QueueSearchState<O, T> initSearch, Collection<T> startStates, int maxSteps, int searchSteps) throws SearchNotExhaustiveException { // Iteratively increase the bound until a search succeeds. for (float bound = startBound;;) { // Set up the maximum bound for this iteration. maxBound = bound; // Use a try block as the depth bounded search will throw a MaxBoundException if it fails but there // are successors states known to exist beyond the current max depth fringe. try { // Get the number of search steps taken so far and pass this into the underlying depth bounded search // so that the step count limit carries over between successive iterations. int numStepsSoFar = initSearch.getStepsTaken(); // Call the super class search method to perform a depth bounded search on this maximum bound starting // from the initial search state. initSearch.resetEnqueuedOnceFlag(); SearchNode node = super.search(initSearch, startStates, maxSteps, numStepsSoFar); // Check if the current depth found a goal node if (node != null) { return node; } // The depth bounded search returned null, so it has exhausted the search space. Return with null. else { return null; } } // The depth bounded search failed but it knows that there are more successor states at deeper levels. catch (MaxBoundException e) { // Do nothing, no node found at this depth so continue at the next depth level e = null; } // Check if the bound should be increased by epsilon or to the next smallest bound property value // beyond the fringe and update the bound for the next iteration. if (useEpsilon) { bound = bound + epsilon; } else { bound = getMinBeyondBound(); } } }
java
{ "resource": "" }
q180388
MaxStepsAlgorithm.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 if this has not already been done. // This will only be done on the first call to this method, as enqueueStartStates sets a flag when it is // done. Subsequent searches continue from where the previous search left off. Have to call reset on // the search method to really start the search again from the start states. 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(); // Keep running until the queue becomes empty or a goal state is found. while (!queue.isEmpty()) { // Extract or peek at 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. if (!headNode.isExpanded()) { headNode.expandSuccessors(queue, reverseEnqueue); } // Get the node to be goal checked, either the head node or the new top of queue, depending on the // peek at head flag. Again this is only a peek, the node is only to be removed if it is to be // goal checked. SearchNode<O, T> currentNode = peekAtHead ? queue.peek() : headNode; // Only goal check leaves, or nodes already expanded. (The expanded flag will be set on leaves anyway). if (currentNode.isExpanded()) { // If required, remove the node to goal check from the queue. currentNode = peekAtHead ? queue.remove() : headNode; // Check if the current node is a goal state. if (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) { 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 so return null return null; }
java
{ "resource": "" }
q180389
PrologParser.main
test
public static void main(String[] args) { try { SimpleCharStream inputStream = new SimpleCharStream(System.in, null, 1, 1); PrologParserTokenManager tokenManager = new PrologParserTokenManager(inputStream); Source<Token> tokenSource = new TokenSource(tokenManager); PrologParser parser = new PrologParser(tokenSource, new VariableAndFunctorInternerImpl("Prolog_Variable_Namespace", "Prolog_Functor_Namespace")); while (true) { // Parse the next sentence or directive. Object nextParsing = parser.clause(); console.info(nextParsing.toString()); } } catch (Exception e) { console.log(Level.SEVERE, e.getMessage(), e); System.exit(1); } }
java
{ "resource": "" }
q180390
PrologParser.clause
test
public Clause clause() throws SourceCodeException { // Each new sentence provides a new scope in which to make variables unique. variableContext.clear(); Term term = term(); Clause clause = TermUtils.convertToClause(term, interner); if (clause == null) { throw new SourceCodeException("Only queries and clauses are valid sentences in Prolog, not " + term + ".", null, null, null, term.getSourceCodePosition()); } return clause; }
java
{ "resource": "" }
q180391
PrologParser.terms
test
public List<Term> terms(List<Term> terms) throws SourceCodeException { Term term; Token nextToken = tokenSource.peek(); switch (nextToken.kind) { case FUNCTOR: term = functor(); break; case LSQPAREN: term = listFunctor(); break; case VAR: term = variable(); break; case INTEGER_LITERAL: term = intLiteral(); break; case FLOATING_POINT_LITERAL: term = doubleLiteral(); break; case STRING_LITERAL: term = stringLiteral(); break; case ATOM: term = atom(); break; case LPAREN: consumeToken(LPAREN); term = term(); // Mark the term as bracketed to ensure that this is its final parsed form. In particular the // #arglist method will not break it up if it contains commas. term.setBracketed(true); consumeToken(RPAREN); break; default: throw new SourceCodeException("Was expecting one of " + BEGIN_TERM_TOKENS + " but got " + tokenImage[nextToken.kind] + ".", null, null, null, new SourceCodePositionImpl(nextToken.beginLine, nextToken.beginColumn, nextToken.endLine, nextToken.endColumn)); } terms.add(term); switch (tokenSource.peek().kind) { case LPAREN: case LSQPAREN: case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case VAR: case FUNCTOR: case ATOM: terms(terms); break; default: } return terms; }
java
{ "resource": "" }
q180392
PrologParser.functor
test
public Term functor() throws SourceCodeException { Token name = consumeToken(FUNCTOR); Term[] args = arglist(); consumeToken(RPAREN); int nameId = interner.internFunctorName((args == null) ? name.image : name.image.substring(0, name.image.length() - 1), (args == null) ? 0 : args.length); Functor result = new Functor(nameId, args); SourceCodePosition position = new SourceCodePositionImpl(name.beginLine, name.beginColumn, name.endLine, name.endColumn); result.setSourceCodePosition(position); return result; }
java
{ "resource": "" }
q180393
PrologParser.listFunctor
test
public Term listFunctor() throws SourceCodeException { // Get the interned names of the nil and cons functors. int nilId = interner.internFunctorName("nil", 0); int consId = interner.internFunctorName("cons", 2); // A list always starts with a '['. Token leftDelim = consumeToken(LSQPAREN); // Check if the list contains any arguments and parse them if so. Term[] args = null; Token nextToken = tokenSource.peek(); switch (nextToken.kind) { case LPAREN: case LSQPAREN: case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case STRING_LITERAL: case VAR: case FUNCTOR: case ATOM: args = arglist(); break; default: } // Work out what the terminal element in the list is. It will be 'nil' unless an explicit cons '|' has // been used to specify a different terminal element. In the case where cons is used explciitly, the // list prior to the cons must not be empty. Term accumulator; if (tokenSource.peek().kind == CONS) { if (args == null) { throw new SourceCodeException("Was expecting one of " + BEGIN_TERM_TOKENS + " but got " + tokenImage[nextToken.kind] + ".", null, null, null, new SourceCodePositionImpl(nextToken.beginLine, nextToken.beginColumn, nextToken.endLine, nextToken.endColumn)); } consumeToken(CONS); accumulator = term(); } else { accumulator = new Nil(nilId, null); } // A list is always terminated with a ']'. Token rightDelim = consumeToken(RSQPAREN); // Walk down all of the lists arguments joining them together with cons/2 functors. if (args != null) // 'args' will contain one or more elements if not null. { for (int i = args.length - 1; i >= 0; i--) { Term previousAccumulator = accumulator; //accumulator = new Functor(consId.ordinal(), new Term[] { args[i], previousAccumulator }); accumulator = new Cons(consId, new Term[] { args[i], previousAccumulator }); } } // Set the position that the list was parsed from, as being the region between the '[' and ']' brackets. SourceCodePosition position = new SourceCodePositionImpl(leftDelim.beginLine, leftDelim.beginColumn, rightDelim.endLine, rightDelim.endColumn); accumulator.setSourceCodePosition(position); // The cast must succeed because arglist must return at least one argument, therefore the cons generating // loop must have been run at least once. If arglist is not called at all because an empty list was // encountered, then the accumulator will contain the 'nil' constant which is a functor of arity zero. return (Functor) accumulator; }
java
{ "resource": "" }
q180394
PrologParser.arglist
test
public Term[] arglist() throws SourceCodeException { Term term = term(); List<Term> result = TermUtils.flattenTerm(term, Term.class, ",", interner); return result.toArray(new Term[result.size()]); }
java
{ "resource": "" }
q180395
PrologParser.variable
test
public Term variable() throws SourceCodeException { Token name = consumeToken(VAR); // Intern the variables name. int nameId = interner.internVariableName(name.image); // Check if the variable already exists in this scope, or create a new one if it does not. // If the variable is the unidentified anonymous variable '_', a fresh one will always be created. Variable var = null; if (!"_".equals(name.image)) { var = variableContext.get(nameId); } if (var != null) { return var; } else { var = new Variable(nameId, null, name.image.equals("_")); variableContext.put(nameId, var); return var; } }
java
{ "resource": "" }
q180396
PrologParser.intLiteral
test
public Term intLiteral() throws SourceCodeException { Token valToken = consumeToken(INTEGER_LITERAL); NumericType result = new IntLiteral(Integer.parseInt(valToken.image)); // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl(valToken.beginLine, valToken.beginColumn, valToken.endLine, valToken.endColumn); result.setSourceCodePosition(position); return result; }
java
{ "resource": "" }
q180397
PrologParser.doubleLiteral
test
public Term doubleLiteral() throws SourceCodeException { Token valToken = consumeToken(FLOATING_POINT_LITERAL); NumericType result = new DoubleLiteral(Double.parseDouble(valToken.image)); // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl(valToken.beginLine, valToken.beginColumn, valToken.endLine, valToken.endColumn); result.setSourceCodePosition(position); return result; }
java
{ "resource": "" }
q180398
PrologParser.stringLiteral
test
public Term stringLiteral() throws SourceCodeException { Token valToken = consumeToken(STRING_LITERAL); String valWithQuotes = valToken.image; StringLiteral result = new StringLiteral(valWithQuotes.substring(1, valWithQuotes.length() - 1)); // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl(valToken.beginLine, valToken.beginColumn, valToken.endLine, valToken.endColumn); result.setSourceCodePosition(position); return result; }
java
{ "resource": "" }
q180399
PrologParser.peekAndConsumeDirective
test
public Directive peekAndConsumeDirective() throws SourceCodeException { if (peekAndConsumeTrace()) { return Directive.Trace; } if (peekAndConsumeInfo()) { return Directive.Info; } if (peekAndConsumeUser()) { return Directive.User; } return null; }
java
{ "resource": "" }