w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
python networkx: do networkx's centrality algorithms use a weighted adjacency matrix?
Both of those algorithms as implemented in NetworkX will use edge weights if specified with the edge attribute 'weight' (for each edge). If you do not specify a weight on the edge the numeric value 1 will be used. This is very unclear from the documentation. I've opened an issue at https://github.com/networkx/networkx/issues/920 so the developers fix this.

Categories : Python

Creating adjacency matrix
based on the comments, suitable formats are either a three-dimensional array or a list of data.frames / data.tables. library(data.table) DT <- data.table ### create a template matrix # find all unique ID's and unique Club's ids <- unique(DT$id) clubs <- unique(DT$club) # matrix template based on the number of ids & clubs mat.template <- matrix(0L, nrow=length(ids), ncol=length(clubs), dimnames=list(ids, clubs)) # iterate over the unique values of year DT <- data.table(dat, key="id,club") res <- lapply(unique(DT$year), function(y) { # index the matrix by the DT where y == year. Set those values to 1 mat <- copy(mat.template) mat[as.matrix(DT[y==year, list(id, club)])] <- 1 mat }) setattr(res, "names", unique(DT$year)) R

Categories : R

How to pad adjacency matrix cells in D3.js style?
One possible solution is to use the pcolor method of pyplot, as it accepts a kwarg edgecolor. import matplotlib.pyplot as plt import numpy as np x = np.arange(6) y = np.arange(6) X, Y = np.meshgrid(x, y) Z = np.random.rand(5, 5) ax = plt.subplot(111, aspect='equal') # To make the cells square ax.pcolor(X, Y, Z, edgecolor='white', # Color of "padding" between cells linewidth=2) # Width of "padding" between cells plt.show()

Categories : Python

k-array tree to produce adjacency matrix
I have an implementation of a k-ary tree (it is very similar to my n-ary tree implementation that you linked to). It is not complete, but it should give you enough to start on. To generate an adjacency matrix, you would need a two-dimensional array with dimensions n x k. You would then have to traverse the tree and populate the adjacency matrix. A row i would correspond to node i and matrix[i][0] to matrix[i][k - 1] would contain references to the k children of node i. Of course, the order of the nodes in the adjacency matrix would depend on your method of traversal.

Categories : Java

Adjacency Matrix not populating correctly python
The lists are all shallow copies of each other, so when you edit one you're actually editing each row. Try this for initializing the matrix: adj_matrix = [[0] * size for i in range(size)]

Categories : Python

BFS graph traversal - Append new node to adjacency matrix
By blanking the adjacency matrix and replacing it with a new one with the updated size, all cells except (from, to) and (to, from) will be zero. You need to make a new adjacency matrix with the new size, copy the data from the old one, and only then overwrite the old one.

Categories : Java

(OpenCV) Fast adjacency matrix computation from watershed
The following is simple but very fast: Mat getAdjacencyMatrix(const int* klabels, int width, int height, int K) /////* Input: //// - int* klabels: the labeled watershed image (the intensity of the watershed lines is -1) //// - int K: the number of superpixels (= kmax + 1) //// * Output: //// - Mat M: the adjacency matrix (M[i][j] = M[i][j] = 1 if the superpixels i and j are adjacent, and = 0 otherwise) ////*/ { /// Create a KxK matrix and initialize to 0 Mat M(K, K, CV_32S, Scalar(0)); /// Scan the labeled image for(int y=1; y < height-1; y++) { for(int x=1; x < width-1; x++) { // Get the label of the current pixel and the ones of its neighbors int k = klabels[y*width + x]; int kleft = kla

Categories : Opencv

Find all the missing directed edges in an adjacency matrix
An adjacency matrix like this should be symmetric. What about taking the lower triangular portion, transposing it and comparing it to the upper triangular portion? Something like this: low = tril(m).transpose() upp = triu(m) missing = mod(low + upp, 2) missing should be 1 where there are missing locations in the upper triangular portion. If all you care about it making sure the upper portion is right, you could just do something like: m = tril(m).transpose() + tril(m)

Categories : Python

Given an nxn Adjacency matrix, how can one compute the number of triangles in the graph (Matlab)?
The (i, j) element in the n'th power of an adjacency matrix A counts the number of paths of length n starting at i and ending at j. A triangle is a path of length 3 that starts and ends at the same node. Therefore the i'th diagonal element of the 3rd power of A counts the number of triangles that contain i as one of the nodes. Each distinct triangle will be counted twice for each of the three nodes in the graph (once in each direction, clockwise and anticlockwise). Therefore the number of distinct triangles is trace(A^3) / 6.

Categories : Matlab

Generate Weighted Random Boolean Matrix in Matlab
I've wrote a very clear and simple code to understand: mat5x5 = rand(5); chanse_of_1s=.90% probability for 1s, just change it. chanse_of_0s=.10% probability for 0s, just change it. mat5x5 = arrayfun(@(x)sum(x >= cumsum([0, chanse_of_0s, chanse_of_1s])), mat5x5)-1 just chage the chanses!

Categories : Matlab

create an adjacency list type structure from a list of pairs
You can do this with LINQ's GroupBy method, like this: var adj = sList .GroupBy(p => p.val1) .ToDictionary(g => g.Key, g => g.Select(p => p.val2).ToList()); Note that this would not compute a transitive closure of your graph, i.e. only the direct links will be present. In .NET 4 and up you can also use Tuple<int,int> instead of making your own Pair class.

Categories : C#

Graphs using Adjacency List in c++
Couple of things. Because you are using malloc no constructor is ever called, and as such the non primitive member adj is never constructed and is NULL. You are leaking memory since you never free/delete any of your dynamically allocated memory. If you are using C++ why are you using malloc instead of new and delete? You don't have to say struct vertex in the sizeof for C++. To fix it you could do: vPtr node = new struct vertex(); // also change to delete instead of free or // use current malloc line, change adj to be a pointer to a list and new it // but this will cause additional problems for you since you really need to use a constructor for STL::list node->adj = new list<int>; Bottom line you really shouldn't be using malloc here.

Categories : C++

inserting a new entry into adjacency list
Why can't you do it in a simple way? dict1[x3] = [y2, y4] for yi in dict1[x3]: if yi in dict2.keys(): dict2[yi].append(x3) else: dict2[yi] = [x3]

Categories : Python

sql adjacency list children for node
Try with CTE(About CTE): DECLARE @SelectedNode INT = 103; ;WITH nodes AS ( SELECT Node , ParentNode , GroupID , Depth FROM TableNodes WHERE Node = @SelectedNode UNION ALL SELECT tn.Node , tn.ParentNode , tn.GroupID , tn.Depth FROM TableNode tn INNER JOIN nodes n ON n.Node = tn.ParentNode ) SELECT * FROM nodes;

Categories : SQL

Adjacency list representation of graphs
I guess that the author of the article would call that structure an incidence list, since nodes link to other nodes via edges rather than directly. The incidence list/adjacency list distinction is nonstandard and IMHO not terribly useful because both structures have similar performance characteristics and because it's not clear that the distinction is well-founded if one strips away the list ADT.

Categories : Algorithm

adjacency-list representation of a directed graph
Both are O(m + n) where m is the number of edges and n is the number of vertices. Start a set of counters, one for each vertex, one for in-degree and out for out-degree. Scan the edges. For the out vertex of each edge, add one to the out-degree counter for that vertex. For the in vertex of each edge, add one to the in-degree counter for that vertex. This is O(m) operation. Output the out-degree and in-degree counters for each vertex, which is O(n). That's how you get O(m + n).

Categories : Algorithm

Mysql Adjacency List Model, My query result is not what I want
Mike has no children so just add such persons with UNION to your query. Also you should use INNER JOIN instead of LEFT JOIN select * from ( SELECT t1.name as level1, t2.name as level2 FROM People as t1 JOIN People as t2 ON t2.parent_id = t1.id UNION select t1.Name as level1, '' as level2 from People t1 where Parent_id=0 and not exists(select 1 from People where Parent_id=t1.Id) ) People ORDER BY level1, level2 SQLFiddle demo

Categories : Mysql

Trouble with List or Pointers, Adjacency Representaiton of Graph
In createEdge() you have this: e.start=v1; e.start=v2; Should it instead be e.start=v1; e.end=v2; EDIT: Your problem is in createEdge, e1 and e2 are just copies, so changes don't affect the actual vertex objects. Here's my solution, seems to be working: Add a function to vertex like so: void addEdge(edge &e){edges.push_back(e);} Then in createEdge(): edge e; e.start=v1; e.end=v2; v1->addEdge(e); v2->addEdge(e);

Categories : C++

How to make formatted file read for Adjacency list?
Use getline() to read each line into a string, and then construct istringstream from the string and read numbers from there. Something like this, but with better error checking. std::ifstream file; // open file etc. std::string line; AdjacencyList al; while (!file.eof()) { getline(file, line); std::istringstream buffer(line); int num; buffer >> num; auto it = al.insert(std::make_pair(num, AdjacencyList::mapped_type()).first; while (!buffer.eof()) { buffer >> num; it->push_back(num); } }

Categories : C++

Problems with C++ Pointers, Iterator, Adjacency List Representation of Graph
When calling addVertex(vertex * v), you add a copy of the vertex argument to the list with graph.push_back(*v). Thus the vertex objects have different addresses. You probably want to store a std::list<vertex*> graph and use graph.push_back(v), then.

Categories : C++

Randomly choosing from a list with weighted probabilities
The idea: Iterate through all the elements and set the value of each element as the cumulative frequency thus far. Generate a random number between 1 and the sum of all frequencies Do a binary search on the values for this number (finding the first value greater than or equal to the number). Example: Element A B C D Frequency 1 4 3 2 Cumulative 1 5 8 10 Generate a random number in the range 1-10 (1+4+3+2 = 10, the same as the last value in the cumulative list), do a binary search, which will return values as follows: Number Element returned 1 A 2 B 3 B 4 B 5 B 6 C 7 C 8 C 9 D 10 D

Categories : Algorithm

Algorithm to convert adjacency list of a multigraph to an equivalent undirected graph
If you want to achieve O(V+E) time complexity, there is no better algorithm, because this is basically a variation of the element distinctness problem, which can be solved by sorting in O(nlogn), or by using O(n) extra space in O(n). So, to achieve O(V+E) time, your algorithm is optimal (in terms of big O notation)

Categories : Algorithm

Adjacency list of a undirected Graph is giving wrong ouptut in Java
An adjacency matrix has every node in the head position and then all the nodes connected to each head node in the secondaryList with edges relative to the head node. Vertex ver = findVertex(s); if (ver == null) { ver = new Vertex(s); this.vertices.add(ver); } ver.edgeLength = scan.nextInt(); from.connected.add(ver); Seems like a problem. Ideally every node in "vertices" (lets call it headList), should have 0 edgeLength (distance from itself). You cannot pull a vertex from headList and push it in the "connected"(secondaryList). The edgeLengths are realtive to the headVertex for each secondaryList.

Categories : Java

How to import a text file to a 3-d matrix in matlab
First, import your 2D matrix of coordinates/values into Matlab, possibly using dlmread. M = dlmread(filename, '/'); As noted by Shai you will want to convert the coordinates to 1-offset rather than 0-offset: M(:,1:3) = M(:,1:3) + 1; Next, create an appropriately sized matrix to insert your values into. foo = zeros(max(M(:,1)), max(M(:,2)), max(M(:,3))); Finally, convert your your coordinates to indeces using sub2ind, and insert the values. idx = sub2ind(size(foo), M(:,1), M(:,2), M(:,3)); foo(idx) = M(:,4);

Categories : Matlab

Pydev tags import as "unresolved import" but code using this import works fine.
So, what you're seeing here is their distribution model. Usually a module will have one root import that everything stems from, but that's not necessarily the case. They're providing a package with (what I assume) is many modules that don't interact with each other; or they can all stand alone. instead of importing each package individually, you could use the 'from' keyword: from ROOTFOL.PACKAGE import * which will grab everything inside that sub-module. You could e-mail the developer and ask why they deployed it this way...or you could add your own __init__.py to the root folder and, from ROOTFOL import * which will walk the tree. Good luck!

Categories : Python

Python strange import behavior: import x.y works, from x import y doesn't
Works for me: danielallan@MacBook:~$mkdir myproject danielallan@MacBook:~$cd myproject/ danielallan@MacBook:myproject$mkdir lib danielallan@MacBook:myproject$cd lib danielallan@MacBook:lib$touch __init__.py danielallan@MacBook:lib$touch view.py danielallan@MacBook:lib$touch common_lib.py danielallan@MacBook:lib$cd .. In [1]: from lib import view In [2]: view Out[2]: <module 'lib.view' from 'lib/view.pyc'> What happens when you try that on your machine? Are you sitting in the wrong directory, or is your path not configured to find these files?

Categories : Python

Import list into SQL
If you have access to mysql command line then you could use the following command: LOAD DATA LOCAL INFILE '/path/myfile.txt' INTO TABLE mytable; http://dev.mysql.com/doc/refman/5.0/en/loading-tables.html

Categories : SQL

How to convert a list into a matrix in R
You can use unlist to get the values in the list, then use sapply to get the number of values in each element of the list. # Generate the list a <- list(1:10, 20:30, 40:45) # Find the number of elements num.el <- sapply(a, length) # Generate the matrix res <- cbind(unlist(a), rep(1:length(a), num.el))

Categories : R

R - How to return a list of matrix
The error can be reproduced easily: test <- list(x=1, y=2) test[[0]] The problem is this: 1:2-1 #[1] 0 1 Maybe you want for(i in 1:(n-1)){?

Categories : R

python 2D matrix simple logic works but matrix print logic doesnt show correct matrix
You can use zip here: >>> lis = [['a','b','c'],['d','e','f']] >>> [ x[::-1] for x in zip(*lis) ] [('d', 'a'), ('e', 'b'), ('f', 'c')] #or >>> [ list(reversed(x)) for x in zip(*lis)] [['d', 'a'], ['e', 'b'], ['f', 'c']]

Categories : Python

Import a list from a different file
One option is to dump that list into a temp file, and read it from your other python script. Another option (if one python script calls the other), is to pass the list as an argument (e.g. using sys.argv[1] and *args, etc).

Categories : Python

Create a matrix from a list of key-value pairs
you probably have something like m_dict = {'A': ['aa', 'bb', 'cc'], 'B': ['bb'], 'C': ['aa']} i would go like this: res = {} for k, v in m_dict.items(): res[k] = defaultdict(int) for col in v: res[k][v] = 1 edit given your format, it would probably be more in the line of : m_array = [['A', 'aa'], ['A', 'bb'], ['A', 'cc'], ['B', 'bb'], ['C', 'aa']] res = defaultdict(lambda: defaultdict(int)) for k, v in m_array: res[k][v] = 1 which both give: >>> res['A']['aa'] 1 >>> res['B']['aa'] 0

Categories : Python

Matrix converting to a list in python
from ast import literal_eval with open('filename') as f: lis = [[[abs(literal_eval(item))] for item in line.rstrip('}, ').lstrip('{').split(', ')] for line in f] print lis ... [[[0.00036], [1], [0], [1], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0.0003], [1.00026], [2], [0], [1], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0.0002], [2], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]]

Categories : Python

to convert a list to a 2D matrix in python
Something like this: >>> data = ['1,2','3,4'] >>> arr2=[ map(float,x.split(',')) for x in data] >>> arr2 = np.asarray(arr2) >>> A = np.asmatrix(arr2) >>> A.I matrix([[-2. , 1. ], [ 1.5, -0.5]])

Categories : Python

Complex rearrangement of list into matrix
library(reshape2) table(melt(lst)) # L1 #value A B C D # one 1 0 0 1 # three 1 0 0 0 # two 1 1 0 0 # five 0 1 0 1 # four 0 1 0 0 # seven 0 0 1 0 # six 0 0 1 0 # eight 0 0 0 1

Categories : R

How to feed values from a list of 9 elements to 3 by 3 matrix
Use the grouper recipe to collect elements of L into groups of 3: L = iter(L) zip(*[L]*3) For example, In [11]: L = [11, 15, 18, 20, 22, 25, 30, 35, 40] In [12]: L = iter(L) In [13]: zip(*[L]*3) Out[13]: [(11, 15, 18), (20, 22, 25), (30, 35, 40)] I'm assuming by "matrix" you mean a list of tuples. It is easy to convert this to a true matrix object (such as numpy.matrix) if that is what you desire. There is an explanation of the grouper recipe here.

Categories : Python

Python- Import txt file and having each line as a list
Do not create separate lists; create a list of lists: results = [] with open('inputfile.txt') as inputfile: for line in inputfile: results.append(line.strip().split(',')) or better still, use the csv module: import csv results = [] with open('inputfile.txt', newline='') as inputfile: for row in csv.reader(inputfile): results.append(row) Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file. Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there. Just for completeness sake, here's the one-liner compact version to read in a CSV file into a li

Categories : Python

list files in the sqoop import directory
Without more details, I can't be sure, but maybe you're confused about where the destination of the sqoop import is. Sqoop imports to the hadoop filesystem, so to view the files, do the following: hadoop fs -ls Here's some reference documentation: http://hadoop.apache.org/docs/r0.18.3/hdfs_shell.html It might be old, depending on the version of hadoop you're using.

Categories : SQL

Import Excel into SQL Server with ASP.NET MVC in a list so it will easy
Have you considered using Linq to Excel? Pretty simple and straight forward way to query data in your excel sheets using linq statements. You could actually use nuget to add LinqToExcel to your MVC solution. Just simply search for "LinqToExcel" and install the package. After that's done your code would look something like this: var excel = new ExcelQueryFactory(); excel.FileName = "PutFileNameHere"; var details = from x in excel.Worksheet<ExcelDate>() select x; Then you could just loop through the contents of the collection "details" and save that into your database. foreach(var detail in details) { //add logic to save each line to your database } Here are some helpful links to get you started: https://code.google.com/p/linqtoexcel/wiki/UsingLinqToExcel https://code.g

Categories : C#

How to cross check a python list of dictionaries against a csr matrix
If X is your sparse matrix and D = [{11998: 0.27257158100079237, 12114: 0.27024630707640002}, {10085: 0.23909781233007368, 9105: 0.57533007741289421}, {6577: 0.45085059256989168, 6491: 0.5895717192325539}, {5286: 0.4482789582819417, 6178: 0.32295433881928487}] then for i, d in enumerate(D): for j in d: d[j] = X[i, j] gives the desired result: >>> D [{12114: 4.0, 11998: 2.0}, {9105: 8.0, 10085: 1.0}, {6577: 2.0, 6491: 4.0}, {6178: 8.0, 5286: 1.0}]

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.