code
stringlengths
73
34.1k
label
stringclasses
1 value
private DependencyTreeNode getNextNode(DependencyRelation prev, DependencyRelation cur) { return (prev.headNode() == cur.headNode() || prev.dependentNode() == cur.headNode()) ? cur.dependentNode() : cur.headNode(); }
java
private static double[] toArray(DoubleVector v, int length) { double[] arr = new double[length]; for (int i = 0; i < arr.length; ++i) { arr[i] = v.get(i); } return arr; }
java
private Collection<WordSimilarity> parse(File word353file) { Collection<WordSimilarity> pairs = new LinkedList<WordSimilarity>(); try { BufferedReader br = new BufferedReader(new FileReader(word353file)); // skip the first line br.readLine(); ...
java
public Iterator<MatrixEntry> iterator() { try { return MatrixIO.getMatrixFileIterator(matrixFile, format); } catch (IOException ioe) { throw new IOError(ioe); } }
java
private void loadFromFormat(InputStream is, SSpaceFormat format) throws IOException { // NOTE: Use a LinkedHashMap here because this will ensure that the // words are returned in the same row-order as the matrix. This // generates better disk I/O behavior for accessing the matrix si...
java
public Graph<T> next() { if (nextSubgraphs.isEmpty()) throw new NoSuchElementException(); Graph<T> next = nextSubgraphs.poll(); // If we've exhausted the current set of subgraphs, queue up more of // them, generated from the remaining vertices if (nextSubgra...
java
private static void add(IntegerVector semantics, TernaryVector index) { // Lock on the semantic vector to avoid a race condition with another // thread updating its semantics. Use the vector to avoid a class-level // lock, which would limit the concurrency. synchronized(semantics) { ...
java
public SimpleDependencyPath copy() { SimpleDependencyPath copy = new SimpleDependencyPath(); copy.path.addAll(path); copy.nodes.addAll(nodes); return copy; }
java
public SimpleDependencyPath extend(DependencyRelation relation) { SimpleDependencyPath copy = copy(); // Figure out which node is at the end of our path, and then add the new // node to the end of our nodes DependencyTreeNode last = last(); copy.nodes.add((relation.headNode().eq...
java
public static Matrix create(int rows, int cols, boolean isDense) { // Estimate the number of bytes that the matrix will take up based on // its maximum dimensions and its sparsity. long size = (isDense) ? (long)rows * (long)cols * BYTES_PER_DOUBLE : (long)(rows * (long)co...
java
public static Matrix copy(Matrix matrix) { Matrix copiedMatrix = null; if (matrix instanceof SparseMatrix) copiedMatrix = Matrices.create( matrix.rows(), matrix.columns(), Type.SPARSE_IN_MEMORY); else copiedMatrix = Matrices.create( ...
java
public String next() { if (next == null) throw new NoSuchElementException(); String replacement = replacementMap.get(next); replacement = (replacement == null) ? next : replacement; advance(); return replacement; }
java
public Color next() { int r = rand.nextInt(256); int g = rand.nextInt(256); int b = rand.nextInt(256); return (seed == null) ? new Color(r, g, b) : new Color((r + seed.getRed()) / 2, (g + seed.getGreen()) / 2, (b + s...
java
public static synchronized void setProperties(Properties props) { wordLimit = Integer.parseInt( props.getProperty(TOKEN_COUNT_LIMIT_PROPERTY, "0")); String filterProp = props.getProperty(TOKEN_FILTER_PROPERTY); filter = (filterProp != null) ? TokenFilter...
java
private static Iterator<String> getBaseIterator(BufferedReader reader, boolean keepOrdering) { // The final iterator is how the stream will be tokenized after all the // tokenizing options have been applied. This value is iteratively set // a...
java
@SuppressWarnings("unchecked") private void updateSemantics(SemanticVector toUpdate, String cooccurringWord, TernaryVector iv) { SemanticVector prevWordSemantics = getSemanticVector(cooccurringWord); Integer occurrences = wor...
java
private static void add(DoubleVector semantics, TernaryVector index, double percentage) { for (int p : index.positiveDimensions()) semantics.add(p, percentage); for (int n : index.negativeDimensions()) semantics.add(n, -perc...
java
private static DoubleVector generateInitialVector(int length, double mean, double std) { DoubleVector vector = new DenseVector(length); for (int i = 0; i < length; ++i) { double v = RA...
java
private static double dotProduct(DoubleVector u, DoubleVector v) { double dot = 0; for (int i = 0; i < u.length(); ++i) { double a = u.get(i); double b = v.get(i); dot += u.get(i) * v.get(i); } return dot; }
java
private void updateTypeCounts(T type, int delta) { if (!typeCounts.containsKey(type)) { assert delta > 0 : "removing edge type that was not originally present"; typeCounts.put(type, delta); } else { int curCount = typeCounts.get(type); ...
java
private static File getTempMatrixFile() { File tmp = null; try { tmp = File.createTempFile("matlab-sparse-matrix", ".dat"); } catch (IOException ioe) { throw new IOError(ioe); } tmp.deleteOnExit(); return tmp; }
java
private IntegerVector getSemanticVector(String word) { IntegerVector v = wordSpace.get(word); if (v == null) { // lock on the word in case multiple threads attempt to add it at // once synchronized(this) { // recheck in case another thread added it whi...
java
public static void shuffle(int[] arr, Random rand) { int size = arr.length; for (int i = size; i > 1; i--) { int tmp = arr[i-1]; int r = rand.nextInt(i); arr[i-1] = arr[r]; arr[r] = tmp; } }
java
private void addInitial(G g) { Set<T> typeCounts = g.edgeTypes(); LinkedList<Map.Entry<G,Integer>> graphs = typesToGraphs.get(typeCounts); if (graphs == null) { graphs = new LinkedList<Map.Entry<G,Integer>>(); typesToGraphs.put(new HashSet<T>(typeCounts), graphs); ...
java
private static void usage(ArgOptions options) { System.out.println( "Fanmod 1.0, " + "usage: java -jar fanmod.jar [options] input.graph output.serialized \n\n" + options.prettyPrint() + "\nThe edge file format is:\n" + " vertex1 vertex2 [edge_label]...
java
private static double entropy(double count, double sum) { double p = count / sum; return Math.log(p) * p; }
java
public int getCount(T obj) { int objIndex = (allowNewIndices) ? objectIndices.index(obj) : objectIndices.find(obj); return (objIndex < 0) ? 0 : indexToCount.get(objIndex); }
java
public static int log2 (int n){ int log = 0; for(int k=1; k < n; k *= 2, log++); if (n != (1 << log)) return -1 ; /* n is not a power of 2 */ return log; }
java
public static double sum(DoubleVector v) { double sum = 0; if (v instanceof SparseVector) { for (int nz : ((SparseVector)v).getNonZeroIndices()) sum += v.get(nz); } else { int len = v.length(); for (int i = 0; i < len; ++i) ...
java
private static void execute(File dataMatrixFile, File affMatrixFile, int dims, File outputMatrix) throws IOException { // Decide whether to use Matlab or Octave if (isMatlabAvailable()) invokeMatlab(dataMatrixFile,...
java
private static void invokeMatlab(File dataMatrixFile, File affMatrixFile, int dimensions, File outputFile) throws IOException { String commandLine = "matlab -nodisplay -nosplash -nojvm"; LOGGER.fine(commandLine); Process matlab = Runtime.getRun...
java
private static void invokeOctave(File dataMatrixFile, File affMatrixFile, int dimensions, File outputFile) throws IOException { // Create the octave file for executing File octaveFile = File.createTempFile("octave-LPP",".m"); // Create the Matl...
java
public static void setLevel(Level outputLevel) { Logger appRooLogger = Logger.getLogger("edu.ucla.sspace"); Handler verboseHandler = new ConsoleHandler(); verboseHandler.setLevel(outputLevel); appRooLogger.addHandler(verboseHandler); appRooLogger.setLevel(outputLevel); ap...
java
private void advance() { try { // loop until we find a word in the reader, or there are no more // words while (true) { // if we haven't looked at any lines yet, or if the index into // the current line is already at the end if...
java
private void checkIndices(int row, int col, boolean expand) { if (row < 0 || col < 0) { throw new ArrayIndexOutOfBoundsException(); } if (expand) { int r = row + 1; int cur = 0; while (r > (cur = rows.get()) && !rows.compareAndSet(cur, r)) ...
java
private static int index(Object o) { Integer i = TYPE_INDICES.get(o); if (i == null) { synchronized (TYPE_INDICES) { // check that another thread did not already update the index i = TYPE_INDICES.get(o); if (i != null) retur...
java
private void addThread() { Thread t = new WorkerThread(workQueue); threads.add(t); t.start(); }
java
public long getRemainingTasks(Object taskGroupId) { CountDownLatch latch = taskKeyToLatch.get(taskGroupId); return (latch == null) ? 0 : latch.getCount(); }
java
public Object registerTaskGroup(int numTasks) { Object key = new Object(); taskKeyToLatch.putIfAbsent(key, new CountDownLatch(numTasks)); return key; }
java
public void run(Collection<Runnable> tasks) { // Create a semphore that the wrapped runnables will execute int numTasks = tasks.size(); CountDownLatch latch = new CountDownLatch(numTasks); for (Runnable r : tasks) { if (r == null) throw new NullPointerExceptio...
java
@SuppressWarnings("unchecked") public static <T> T getObjectInstance(String className) { try { Class clazz = Class.forName(className); return (T) clazz.newInstance(); } catch (Exception e) { throw new Error(e); } }
java
public static <T extends Vector> double getSimilarity( SimType similarityType, T a, T b) { switch (similarityType) { case COSINE: return cosineSimilarity(a, b); case PEARSON_CORRELATION: return correlation(a, b); case EUCLIDEAN: ...
java
public static double cosineSimilarity(double[] a, double[] b) { check(a,b); double dotProduct = 0.0; double aMagnitude = 0.0; double bMagnitude = 0.0; for (int i = 0; i < b.length ; i++) { double aValue = a[i]; double bValue = b[i]; aMagnitude ...
java
public static double spearmanRankCorrelationCoefficient(double[] a, double[] b) { check(a, b); int N = a.length; int NcubedMinusN = (N * N * N) - N; // Convert a and b into rankings. The last value of this array is the ...
java
public Set<T> types() { // NOTE: purely unoptimized! Set<T> types = new HashSet<T>(); for (Object o : edges.values()) { Set<T> s = (Set<T>)o; types.addAll(s); } return types; }
java
public static double mean(Collection<? extends Number> values) { double sum = 0d; for (Number n : values) sum += n.doubleValue(); return sum / values.size(); }
java
public static double mean(int[] values) { double sum = 0d; for (int i : values) sum += i; return sum / values.length; }
java
@SuppressWarnings("unchecked") public static <T extends Number & Comparable> T median(Collection<T> values) { if (values.isEmpty()) throw new IllegalArgumentException( "No median in an empty collection"); List<T> sorted = new ArrayList<T>(values); Collect...
java
public static double median(int[] values) { if (values.length == 0) throw new IllegalArgumentException("No median in an empty array"); int[] sorted = Arrays.copyOf(values, values.length); Arrays.sort(sorted); return sorted[sorted.length/2]; }
java
public static <T extends Number> T mode(Collection<T> values) { if (values.isEmpty()) throw new IllegalArgumentException( "No mode in an empty collection"); Counter<T> c = new ObjectCounter<T>(); for (T n : values) c.count(n); return c.max(); }
java
public static int mode(int[] values) { if (values.length == 0) throw new IllegalArgumentException("No mode in an empty array"); Counter<Integer> c = new ObjectCounter<Integer>(); for (int i : values) c.count(i); return c.max(); }
java
public static double mode(double[] values) { if (values.length == 0) throw new IllegalArgumentException("No mode in an empty array"); Counter<Double> c = new ObjectCounter<Double>(); for (double d : values) c.count(d); return c.max(); }
java
public static double stddev(Collection<? extends Number> values) { double mean = mean(values); double sum = 0d; for (Number n : values) { double d = n.doubleValue() - mean; sum += d*d; } return Math.sqrt(sum / values.size()); }
java
public static double stddev(int[] values) { double mean = mean(values); double sum = 0d; for (int i : values) { double d = i - mean; sum += d*d; } return Math.sqrt(sum / values.length); }
java
public static double sum(Collection<? extends Number> values) { double sum = 0d; for (Number n : values) sum += n.doubleValue(); return sum; }
java
private <E extends Edge> double getConnectionSimilarity( Graph<E> graph, Edge e1, Edge e2) { int e1to = e1.to(); int e1from = e1.from(); int e2to = e2.to(); int e2from = e2.from(); if (e1to == e2to) return getConnectionSimilarity(graph, e1to, e1from, e2fro...
java
private void addIntermediateNode(Node<V> original, int numOverlappingCharacters, String key, int indexOfStartOfOverlap, V value) { // get the current prefix for the node char[] originalPrefix = original.prefix; // create the new prefix for the original node, which will ...
java
public <E extends Edge> double[] compute(Graph<E> g) { // Perform a quick test for whether the vertices of g are a contiguous // sequence starting at 0, which makes the vertex mapping trivial if (!hasContiguousVertices(g)) throw new IllegalArgumentException( "Vertices...
java
private Matrix getEdgeSimMatrix(List<Edge> edgeList, SparseMatrix sm, boolean keepSimilarityMatrixInMemory) { return (keepSimilarityMatrixInMemory) ? calculateEdgeSimMatrix(edgeList, sm) : new LazySimilarityMatrix(edgeList, sm); }
java
private Matrix calculateEdgeSimMatrix( final List<Edge> edgeList, final SparseMatrix sm) { final int numEdges = edgeList.size(); final Matrix edgeSimMatrix = new SparseSymmetricMatrix( new SparseHashMatrix(numEdges, numEdges)); Object key = workQueue.re...
java
private static MultiMap<Integer,Integer> convertMergesToAssignments( List<Merge> merges, int numOriginalClusters) { MultiMap<Integer,Integer> clusterToElements = new HashMultiMap<Integer,Integer>(); for (int i = 0; i < numOriginalClusters; ++i) clusterToElements.put...
java
private static int[] getImpostNeighbors(SparseMatrix sm, int rowIndex) { int[] impost1edges = sm.getRowVector(rowIndex).getNonZeroIndices(); int[] neighbors = Arrays.copyOf(impost1edges, impost1edges.length + 1); neighbors[neighbors.length - 1] = rowIndex; return neighbors; }
java
public double getSolutionDensity(int solutionNum) { if (solutionNum < 0 || solutionNum >= mergeOrder.size()) { throw new IllegalArgumentException( "not a valid solution: " + solutionNum); } if (mergeOrder == null || edgeList == null) { throw new Ille...
java
public Assignments getSolution(int solutionNum) { if (solutionNum < 0 || solutionNum >= mergeOrder.size()) { throw new IllegalArgumentException( "not a valid solution: " + solutionNum); } if (mergeOrder == null || edgeList == null) { throw new Illega...
java
public static Matrix average(Matrix m, Dimension dim) { Matrix averageMatrix = null; if (dim == Dimension.ALL) { // Compute the average of all values in the matrix. double average = 0; for (int i = 0; i < m.rows(); ++i) { for (int j = 0; j < m.columns...
java
public void processFile(File blogFile) throws IOException { BufferedReader br = new BufferedReader(new FileReader(blogFile)); String line = null; String date = null; String id = null; StringBuilder content = new StringBuilder(); boolean needMoreContent = false; while ((line = br.readLine()) ...
java
private Collection<Multigraph<T,E>> enumerateSimpleGraphs( Multigraph<T,E> input, List<IntPair> connected, int curPair, Multigraph<T,E> toCopy) { List<Multigraph<T,E>> simpleGraphs = new LinkedList<Multigraph<T,E>>(); IntPair p = connected.get(curPair); // Get th...
java
public Multigraph<T,E> next() { if (!hasNext()) throw new NoSuchElementException(); Multigraph<T,E> cur = next.poll(); if (next.isEmpty()) advance(); return cur; }
java
private void addRelation(String object, String attribute) { double val; int row, col; object = object.toLowerCase(); attribute = attribute.toLowerCase(); // get row in matrix if( objectTable.containsKey(object) ) { // if the object already exists in matrix, ...
java
private boolean inStartSet(String tag) { return // noun tag.startsWith("NN") || // adjective tag.startsWith("JJ") || // adverb tag.startsWith("RB") || // cardinal number tag.startsWith("CD"); }
java
private boolean isPhraseOrClause(String tag) { // find out why adding more reduced the number of relations return (!tag.equals("SYM") && tag.startsWith("S")) || tag.equals("ADJP") || tag.equals("ADVP") || tag.equals("CONJP") || tag...
java
private String getNextTag(String str) { String tag; int endIndex; int tagIndex = str.indexOf("("); if( tagIndex < 0 ) { return null; } // in case there's nothing in the sentence endIndex = str.indexOf(" ", tagIndex); if( endIndex < 0 ) { ...
java
public double[] vectorize(List<String> phonemes) { int nextConsonantIndex = 0; int nextVowelIndex = 0; double[] result = new double[(vowelIndices.length + consonantIndices.length) * 3]; for (String phoneme : phonemes) { int offset = 3; ...
java
public void process(Iterator<String> text) { String nextToken = null, curToken = null; // Base case for the next token buffer to ensure we always have two // valid tokens present if (text.hasNext()) nextToken = text.next(); while (text.hasNext()) { curToke...
java
private void processBigram(String left, String right) { TokenStats leftStats = getStatsFor(left); TokenStats rightStats = getStatsFor(right); // mark that both appeared leftStats.count++; rightStats.count++; // Mark the respective positions of each leftS...
java
public void printBigrams(PrintWriter output, SignificanceTest test, int minOccurrencePerToken) { String[] indexToToken = new String[tokenCounts.size()]; for (Map.Entry<String,TokenStats> e : tokenCounts.entrySet()) indexToToken[e.getValue().index] = e....
java
private double getScore(int[] contingencyTable, SignificanceTest test) { switch (test) { case PMI: return pmi(contingencyTable); case CHI_SQUARED: return chiSq(contingencyTable); case LOG_LIKELIHOOD: return logLikelihood(contingencyTable); defa...
java
private double logLikelihood(int[] contingencyTable) { // Rename for short-hand convenience int[] t = contingencyTable; int col1sum = t[0] + t[2]; int col2sum = t[1] + t[3]; int row1sum = t[0] + t[1]; int row2sum = t[2] + t[3]; double sum = row1sum + row2sum; ...
java
public int getDimension(DependencyPath path) { String endToken = path.last().word(); // Extract out how the current word is related to the last word in the // path. String relation = path.getRelation(path.length() - 1); return getDimensionInternal(endToken + "+" + relation); ...
java
public synchronized DoubleVector generate() { DoubleVector termVector = new DenseVector(indexVectorLength); for (int i = 0; i < indexVectorLength; i++) termVector.set(i, mean + (randomGenerator.nextGaussian() * stdev)); return termVector; }
java
protected void addContextTerms(SparseDoubleVector meaning, Queue<String> words, int distance) { // Iterate through each of the context words. for (String term : words) { if (!term.equals(IteratorFactory.EMPTY_TOKEN)) { ...
java
@SuppressWarnings("unchecked") private void processSpace() throws IOException { compressedDocumentsWriter.close(); // Generate the reverse index-to-term mapping. We will need this for // assigning specific senses to each term String[] indexToTerm = new String[termToIndex.si...
java
private void senseInduce(String term, Matrix contexts) throws IOException { LOGGER.fine("Clustering " + contexts.rows() + " contexts for " + term); // For terms with fewer than seven contexts, set the number of potential // clusters lower int numClusters = Math.min(7, contexts.rows()); ...
java
private int processIntDocument(int termIndex, int[] document, Matrix contextMatrix, int rowStart, BitSet featuresForTerm) { int contexts = 0; for (int i = 0; i < document.length; ++i) { ...
java
private static double logLikelihood(double a, double b, double c, double d) { // Table set up as: // a b // c d double col1sum = a + c; double col2sum = b + d; double row1sum = a + b; double row2sum = c + d; d...
java
private void checkIndices(int row, int col) { if (row < 0 || row >= rows) throw new ArrayIndexOutOfBoundsException("row: " + row); else if (col < 0 || col >= cols) throw new ArrayIndexOutOfBoundsException("column: " + col); }
java
public boolean add(WeightedEdge e) { int toAdd = -1; if (e.from() == rootVertex) toAdd = e.to(); else if (e.to() == rootVertex) toAdd = e.from(); else { return false; } double w = e.weight(); if (edges.contains...
java
public DoubleVector centerOfMass() { // Handle lazy initialization if (centroid == null) { if (indices.size() == 1) centroid = sumVector; else { // Update the centroid by normalizing by the number of elements. // We expect that the ...
java
public void add(int index, DoubleVector v) { boolean added = indices.add(index); assert added : "Adding duplicate indices to candidate facility"; if (sumVector == null) { sumVector = (v instanceof SparseVector) ? new SparseHashDoubleVector(v) : new Den...
java
public void merge(CandidateCluster other) { indices.addAll(other.indices); VectorMath.add(sumVector, other.sumVector); centroid = null; }
java
private void printSpace(SemanticSpace sspace, String tag) { try { String EXT = ".sspace"; File output = (overwrite) ? new File(outputDir, sspace.getSpaceName() + tag + EXT) : File.createTempFile(sspace.getSpaceName() + tag, EXT, ...
java
private void updateTemporalSemantics(long currentSemanticPartitionStartTime, SemanticSpace semanticPartition) { // Pre-allocate the zero vector so that if multiple interesting words // are not present in the space, they all point to the same zero ...
java
private void printShiftRankings(String dateString, long startOfMostRecentPartition, TimeSpan partitionDuration) throws IOException { SortedMultiMap<Double,String> shiftToWord = new TreeMultiMap<Double,String>(); ...
java
protected void usage() { System.out.println( "usage: java FixedDurationTemporalRandomIndexingMain [options] " + "<output-dir>\n\n" + argOptions.prettyPrint() + "\nFixed-Duration TRI provides four main output options:\n\n" + " 1) Outputting each s...
java
public Iterator<T> iterator() { List<Iterator<T>> iters = new ArrayList<Iterator<T>>(sets.size()); for (Set<T> s : sets) iters.add(s.iterator()); return new CombinedIterator<T>(iters); }
java
public int size() { // Since the sets are disjoint, we can simple sum their sizes int size = 0; for (Set<T> s : sets) size += s.size(); return size; }
java
public void readFields(DataInput in) throws IOException { t.readFields(in); position = in.readInt(); }
java
public void write(DataOutput out) throws IOException { t.write(out); out.writeInt(position); }
java
private void normalize(DoubleVector v) { double magnitude = 0; for (int i = 0; i < v.length(); ++i) magnitude += Math.pow(v.get(i), 2); if (magnitude == 0) return; magnitude = Math.sqrt(magnitude); for (int i = 0; i < v.length(); ++i) v.set(i,...
java
private DoubleVector groupConvolution(Queue<String> prevWords, Queue<String> nextWords) { // Generate an empty DoubleVector to hold the convolution. DoubleVector result = new DenseVector(indexVectorSize); // Do the convolutions starting at index 0. ...
java