idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
32,100
def all_node_style ( self , ** kwargs ) : for node in self . nodes : self . node_style ( node , ** kwargs )
Modifies all node styles
32,101
def edge_style ( self , head , tail , ** kwargs ) : if tail not in self . nodes : raise GraphError ( "invalid node %s" % ( tail , ) ) try : if tail not in self . edges [ head ] : self . edges [ head ] [ tail ] = { } self . edges [ head ] [ tail ] = kwargs except KeyError : raise GraphError ( "invalid edge %s -> %s " %...
Modifies an edge style to the dot representation .
32,102
def save_dot ( self , file_name = None ) : if not file_name : warnings . warn ( DeprecationWarning , "always pass a file_name" ) file_name = self . temp_dot fp = open ( file_name , "w" ) try : for chunk in self . iterdot ( ) : fp . write ( chunk ) finally : fp . close ( )
Saves the current graph representation into a file
32,103
def save_img ( self , file_name = None , file_type = "gif" , mode = 'dot' ) : if not file_name : warnings . warn ( DeprecationWarning , "always pass a file_name" ) file_name = "out" if mode == 'neato' : self . save_dot ( self . temp_neo ) neato_cmd = "%s -o %s %s" % ( self . neato , self . temp_dot , self . temp_neo ) ...
Saves the dot file as an image file
32,104
def get_repo_revision ( ) : repopath = _findrepo ( ) if not repopath : return '' try : import mercurial . hg , mercurial . ui , mercurial . scmutil from mercurial . node import short as hexfunc except ImportError : pass else : ui = mercurial . ui . ui ( ) repo = mercurial . hg . repository ( ui , repopath ) parents = r...
Returns mercurial revision string somelike hg identify does .
32,105
def reduce ( self , key , values ) : dist , key , value = min ( values , key = lambda x : x [ 0 ] ) print ( 'MinDist[%f]' % dist ) yield key , value
Select the image with the minimum distance
32,106
def checkmagic ( self ) : self . lib . seek ( self . start ) if self . lib . read ( len ( self . MAGIC ) ) != self . MAGIC : raise ArchiveReadError ( "%s is not a valid %s archive file" % ( self . path , self . __class__ . __name__ ) ) if self . lib . read ( len ( self . pymagic ) ) != self . pymagic : raise ArchiveRea...
Overridable . Check to see if the file object self . lib actually has a file we understand .
32,107
def update_headers ( self , tocpos ) : self . lib . seek ( self . start ) self . lib . write ( self . MAGIC ) self . lib . write ( self . pymagic ) self . lib . write ( struct . pack ( '!i' , tocpos ) )
Default - MAGIC + Python s magic + tocpos
32,108
def flipwritable ( fn , mode = None ) : if os . access ( fn , os . W_OK ) : return None old_mode = os . stat ( fn ) . st_mode os . chmod ( fn , stat . S_IWRITE | old_mode ) return old_mode
Flip the writability of a file and return the old mode . Returns None if the file is already writable .
32,109
def mergecopy ( src , dest ) : if os . path . exists ( dest ) and os . stat ( dest ) . st_mtime >= os . stat ( src ) . st_mtime : return copy2 ( src , dest )
copy2 but only if the destination isn t up to date
32,110
def sdk_normalize ( filename ) : if filename . startswith ( '/Developer/SDKs/' ) : pathcomp = filename . split ( '/' ) del pathcomp [ 1 : 4 ] filename = '/' . join ( pathcomp ) return filename
Normalize a path to strip out the SDK portion normally so that it can be decided whether it is in a system path or not .
32,111
def in_system_path ( filename ) : fn = sdk_normalize ( os . path . realpath ( filename ) ) if fn . startswith ( '/usr/local/' ) : return False elif fn . startswith ( '/System/' ) or fn . startswith ( '/usr/' ) : return True else : return False
Return True if the file is in a system path
32,112
def is_platform_file ( path ) : if not os . path . exists ( path ) or os . path . islink ( path ) : return False fileobj = open ( path , 'rb' ) bytes = fileobj . read ( MAGIC_LEN ) if bytes == FAT_MAGIC_BYTES : fileobj . seek ( 0 ) header = mach_o . fat_header . from_fileobj ( fileobj , _endian_ = '>' ) if header . nfa...
Return True if the file is Mach - O
32,113
def iter_platform_files ( dst ) : for root , dirs , files in os . walk ( dst ) : for fn in files : fn = os . path . join ( root , fn ) if is_platform_file ( fn ) : yield fn
Walk a directory and yield each full path that is a Mach - O file
32,114
def strip_files ( files , argv_max = ( 256 * 1024 ) ) : tostrip = [ ( fn , flipwritable ( fn ) ) for fn in files ] while tostrip : cmd = list ( STRIPCMD ) flips = [ ] pathlen = reduce ( operator . add , [ len ( s ) + 1 for s in cmd ] ) while pathlen < argv_max : if not tostrip : break added , flip = tostrip . pop ( ) p...
Strip a list of files
32,115
def check_call ( * popenargs , ** kwargs ) : retcode = call ( * popenargs , ** kwargs ) cmd = kwargs . get ( "args" ) if cmd is None : cmd = popenargs [ 0 ] if retcode : raise CalledProcessError ( retcode , cmd ) return retcode
Run command with arguments . Wait for command to complete . If the exit code was zero then return otherwise raise CalledProcessError . The CalledProcessError object will have the return code in the returncode attribute .
32,116
def __exec_python_cmd ( cmd ) : pp = os . pathsep . join ( PyInstaller . __pathex__ ) old_pp = compat . getenv ( 'PYTHONPATH' ) if old_pp : pp = os . pathsep . join ( [ pp , old_pp ] ) compat . setenv ( "PYTHONPATH" , pp ) try : try : txt = compat . exec_python ( * cmd ) except OSError , e : raise SystemExit ( "Executi...
Executes an externally spawned Python interpreter and returns anything that was emitted in the standard output as a single string .
32,117
def exec_script ( scriptfilename , * args ) : if scriptfilename != os . path . basename ( scriptfilename ) : raise SystemError ( "To prevent missuse, the script passed to " "hookutils.exec-script must be located in " "the `hooks` directory." ) cmd = [ os . path . join ( os . path . dirname ( __file__ ) , scriptfilename...
Executes a Python script in an externally spawned interpreter and returns anything that was emitted in the standard output as a single string .
32,118
def qt4_plugins_binaries ( plugin_type ) : binaries = [ ] pdir = qt4_plugins_dir ( ) files = misc . dlls_in_dir ( os . path . join ( pdir , plugin_type ) ) for f in files : binaries . append ( ( os . path . join ( 'qt4_plugins' , plugin_type , os . path . basename ( f ) ) , f , 'BINARY' ) ) return binaries
Return list of dynamic libraries formated for mod . binaries .
32,119
def qt4_menu_nib_dir ( ) : menu_dir = '' macports_prefix = sys . executable . split ( '/Library' ) [ 0 ] dirs = [ os . path . join ( macports_prefix , 'lib' , 'Resources' ) , os . path . join ( macports_prefix , 'libexec' , 'qt4-mac' , 'lib' , 'QtGui.framework' , 'Versions' , '4' , 'Resources' ) , '/Library/Frameworks/...
Return path to Qt resource dir qt_menu . nib .
32,120
def dyld_find ( name , executable_path = None , env = None ) : name = _ensure_utf8 ( name ) executable_path = _ensure_utf8 ( executable_path ) for path in dyld_image_suffix_search ( chain ( dyld_override_search ( name , env ) , dyld_executable_path_search ( name , executable_path ) , dyld_default_search ( name , env ) ...
Find a library or framework using dyld semantics
32,121
def framework_find ( fn , executable_path = None , env = None ) : try : return dyld_find ( fn , executable_path = executable_path , env = env ) except ValueError : pass fmwk_index = fn . rfind ( '.framework' ) if fmwk_index == - 1 : fmwk_index = len ( fn ) fn += '.framework' fn = os . path . join ( fn , os . path . bas...
Find a framework using dyld semantics in a very loose manner .
32,122
def get_repo_revision ( ) : rev = 0 path = os . path . abspath ( os . path . dirname ( os . path . dirname ( __file__ ) ) ) entries_path = os . path . join ( path , '.svn' , 'entries' ) try : entries = open ( entries_path , 'rU' ) . read ( ) except IOError : pass else : if re . match ( '(\d+)' , entries ) : rev_match =...
Returns SVN revision number .
32,123
def get_system_path ( ) : _bpath = [ ] if is_win : try : import win32api except ImportError : logger . warn ( "Cannot determine your Windows or System directories" ) logger . warn ( "Please add them to your PATH if .dlls are not found" ) logger . warn ( "or install http://sourceforge.net/projects/pywin32/" ) else : sys...
Return the path that Windows will search for dlls .
32,124
def getFirstChildElementByTagName ( self , tagName ) : for child in self . childNodes : if isinstance ( child , Element ) : if child . tagName == tagName : return child return None
Return the first element of type tagName if found else None
32,125
def GetManifestResources ( filename , names = None , languages = None ) : return winresource . GetResources ( filename , [ RT_MANIFEST ] , names , languages )
Get manifest resources from file
32,126
def UpdateManifestResourcesFromXML ( dstpath , xmlstr , names = None , languages = None ) : logger . info ( "Updating manifest in %s" , dstpath ) if dstpath . lower ( ) . endswith ( ".exe" ) : name = 1 else : name = 2 winresource . UpdateResources ( dstpath , xmlstr , RT_MANIFEST , names or [ name ] , languages or [ 0 ...
Update or add manifest XML as resource in dstpath
32,127
def UpdateManifestResourcesFromXMLFile ( dstpath , srcpath , names = None , languages = None ) : logger . info ( "Updating manifest from %s in %s" , srcpath , dstpath ) if dstpath . lower ( ) . endswith ( ".exe" ) : name = 1 else : name = 2 winresource . UpdateResourcesFromDataFile ( dstpath , srcpath , RT_MANIFEST , n...
Update or add manifest XML from srcpath as resource in dstpath
32,128
def create_manifest ( filename , manifest , console ) : if not manifest : manifest = ManifestFromXMLFile ( filename ) name = os . path . basename ( filename ) manifest . name = os . path . splitext ( os . path . splitext ( name ) [ 0 ] ) [ 0 ] elif isinstance ( manifest , basestring ) and "<" in manifest : manifest = M...
Create assembly manifest .
32,129
def add_file ( self , name = "" , hashalg = "" , hash = "" , comClasses = None , typelibs = None , comInterfaceProxyStubs = None , windowClasses = None ) : self . files . append ( File ( name , hashalg , hash , comClasses , typelibs , comInterfaceProxyStubs , windowClasses ) )
Shortcut for manifest . files . append
32,130
def getid ( self , language = None , version = None ) : if not self . name : logger . warn ( "Assembly metadata incomplete" ) return "" id = [ ] if self . processorArchitecture : id . append ( self . processorArchitecture ) id . append ( self . name ) if self . publicKeyToken : id . append ( self . publicKeyToken ) if ...
Return an identification string which uniquely names a manifest .
32,131
def getpolicyid ( self , fuzzy = True , language = None , windowsversion = None ) : if not self . name : logger . warn ( "Assembly metadata incomplete" ) return "" id = [ ] if self . processorArchitecture : id . append ( self . processorArchitecture ) name = [ ] name . append ( "policy" ) if self . version : name . app...
Return an identification string which can be used to find a policy .
32,132
def parse ( self , filename_or_file , initialize = True ) : if isinstance ( filename_or_file , ( str , unicode ) ) : filename = filename_or_file else : filename = filename_or_file . name try : domtree = minidom . parse ( filename_or_file ) except xml . parsers . expat . ExpatError , e : args = [ e . args [ 0 ] ] if isi...
Load manifest from file or file object
32,133
def parse_string ( self , xmlstr , initialize = True ) : try : domtree = minidom . parseString ( xmlstr ) except xml . parsers . expat . ExpatError , e : raise ManifestXMLParseError ( e ) self . load_dom ( domtree , initialize )
Load manifest from XML string
32,134
def same_id ( self , manifest , skip_version_check = False ) : if skip_version_check : version_check = True else : version_check = self . version == manifest . version return ( self . language == manifest . language and self . name == manifest . name and self . processorArchitecture == manifest . processorArchitecture ...
Return a bool indicating if another manifest has the same identitiy . This is done by comparing language name processorArchitecture publicKeyToken type and version .
32,135
def toprettyxml ( self , indent = " " , newl = os . linesep , encoding = "UTF-8" ) : domtree = self . todom ( ) if sys . version_info >= ( 2 , 3 ) : xmlstr = domtree . toprettyxml ( indent , newl , encoding ) else : xmlstr = domtree . toprettyxml ( indent , newl ) xmlstr = xmlstr . strip ( os . linesep ) . replace ( '...
Return the manifest as pretty - printed XML
32,136
def toxml ( self , encoding = "UTF-8" ) : domtree = self . todom ( ) xmlstr = domtree . toxml ( encoding ) . replace ( '<?xml version="1.0" encoding="%s"?>' % encoding , '<?xml version="1.0" encoding="%s" standalone="yes"?>' % encoding ) domtree . unlink ( ) return xmlstr
Return the manifest as XML
32,137
def launch_local ( in_name , out_name , script_path , poll = None , max_input = None , files = ( ) , cmdenvs = ( ) , pipe = True , python_cmd = 'python' , remove_tempdir = True , identity_mapper = False , num_reducers = None , ** kw ) : if isinstance ( files , ( str , unicode ) ) or isinstance ( cmdenvs , ( str , unico...
A simple local emulation of hadoop
32,138
def getfullnameof ( mod , xtrapath = None ) : epath = sys . path + winutils . get_system_path ( ) if xtrapath is not None : if type ( xtrapath ) == type ( '' ) : epath . insert ( 0 , xtrapath ) else : epath = xtrapath + epath for p in epath : npth = os . path . join ( p , mod ) if os . path . exists ( npth ) : return n...
Return the full path name of MOD .
32,139
def Dependencies ( lTOC , xtrapath = None , manifest = None ) : for nm , pth , typ in lTOC : if seen . get ( nm . upper ( ) , 0 ) : continue logger . info ( "Analyzing %s" , pth ) seen [ nm . upper ( ) ] = 1 if is_win : for ftocnm , fn in selectAssemblies ( pth , manifest ) : lTOC . append ( ( ftocnm , fn , 'BINARY' ) ...
Expand LTOC to include all the closure of binary dependencies .
32,140
def pkg_resouces_get_default_cache ( ) : egg_cache = compat . getenv ( 'PYTHON_EGG_CACHE' ) if egg_cache is not None : return egg_cache if os . name != 'nt' : return os . path . expanduser ( '~/.python-eggs' ) app_data = 'Application Data' app_homes = [ ( ( 'APPDATA' , ) , None ) , ( ( 'USERPROFILE' , ) , app_data ) , ...
Determine the default cache location
32,141
def getAssemblies ( pth ) : if not os . path . isfile ( pth ) : pth = check_extract_from_egg ( pth ) [ 0 ] [ 0 ] if pth . lower ( ) . endswith ( ".manifest" ) : return [ ] manifestnm = pth + ".manifest" if os . path . isfile ( manifestnm ) : fd = open ( manifestnm , "rb" ) res = { RT_MANIFEST : { 1 : { 0 : fd . read ( ...
Return the dependent assemblies of a binary .
32,142
def selectAssemblies ( pth , manifest = None ) : rv = [ ] if not os . path . isfile ( pth ) : pth = check_extract_from_egg ( pth ) [ 0 ] [ 0 ] if manifest : _depNames = set ( [ dep . name for dep in manifest . dependentAssemblies ] ) for assembly in getAssemblies ( pth ) : if seen . get ( assembly . getid ( ) . upper (...
Return a binary s dependent assemblies files that should be included .
32,143
def selectImports ( pth , xtrapath = None ) : rv = [ ] if xtrapath is None : xtrapath = [ os . path . dirname ( pth ) ] else : assert isinstance ( xtrapath , list ) xtrapath = [ os . path . dirname ( pth ) ] + xtrapath dlls = getImports ( pth ) for lib in dlls : if seen . get ( lib . upper ( ) , 0 ) : continue if not i...
Return the dependencies of a binary that should be included .
32,144
def getImports ( pth ) : if not os . path . isfile ( pth ) : pth = check_extract_from_egg ( pth ) [ 0 ] [ 0 ] if is_win or is_cygwin : if pth . lower ( ) . endswith ( ".manifest" ) : return [ ] try : return _getImports_pe ( pth ) except Exception , exception : if logger . isEnabledFor ( logging . WARN ) : logger . warn...
Forwards to the correct getImports implementation for the platform .
32,145
def findLibrary ( name ) : assert is_unix , "Current implementation for Unix only (Linux, Solaris, AIX)" lib = None lp = compat . getenv ( 'LD_LIBRARY_PATH' , '' ) for path in lp . split ( os . pathsep ) : libs = glob ( os . path . join ( path , name + '*' ) ) if libs : lib = libs [ 0 ] break if lib is None : expr = r'...
Look for a library in the system .
32,146
def getSoname ( filename ) : cmd = [ "objdump" , "-p" , "-j" , ".dynamic" , filename ] m = re . search ( r'\s+SONAME\s+([^\s]+)' , compat . exec_command ( * cmd ) ) if m : return m . group ( 1 )
Return the soname of a library .
32,147
def _os_bootstrap ( ) : global _os_stat , _os_getcwd , _os_environ , _os_listdir global _os_path_join , _os_path_dirname , _os_path_basename global _os_sep names = sys . builtin_module_names join = dirname = environ = listdir = basename = None mindirlen = 0 if 'posix' in names : from posix import stat , getcwd , enviro...
Set up os module replacement functions for use during import bootstrap .
32,148
def scan_code_for_ctypes ( co , instrs , i ) : def _libFromConst ( i ) : op , oparg , conditional , curline = instrs [ i ] if op == LOAD_CONST : soname = co . co_consts [ oparg ] b . append ( soname ) b = [ ] op , oparg , conditional , curline = instrs [ i ] if op in ( LOAD_GLOBAL , LOAD_NAME ) : name = co . co_names [...
Detects ctypes dependencies using reasonable heuristics that should cover most common ctypes usages ; returns a tuple of two lists one containing names of binaries detected as dependencies the other containing warnings .
32,149
def _resolveCtypesImports ( cbinaries ) : if is_unix : envvar = "LD_LIBRARY_PATH" elif is_darwin : envvar = "DYLD_LIBRARY_PATH" else : envvar = "PATH" def _setPaths ( ) : path = os . pathsep . join ( PyInstaller . __pathex__ ) old = compat . getenv ( envvar ) if old is not None : path = os . pathsep . join ( ( path , o...
Completes ctypes BINARY entries for modules with their full path .
32,150
def degree_dist ( graph , limits = ( 0 , 0 ) , bin_num = 10 , mode = 'out' ) : deg = [ ] if mode == 'inc' : get_deg = graph . inc_degree else : get_deg = graph . out_degree for node in graph : deg . append ( get_deg ( node ) ) if not deg : return [ ] results = _binning ( values = deg , limits = limits , bin_num = bin_n...
Computes the degree distribution for a graph .
32,151
def flatten ( self , condition = None , start = None ) : if start is None : start = self start = self . getRawIdent ( start ) return self . graph . iterdata ( start = start , condition = condition )
Iterate over the subgraph that is entirely reachable by condition starting from the given start node or the ObjectGraph root
32,152
def filterStack ( self , filters ) : visited , removes , orphans = filter_stack ( self . graph , self , filters ) for last_good , tail in orphans : self . graph . add_edge ( last_good , tail , edge_data = 'orphan' ) for node in removes : self . graph . hide_node ( node ) return len ( visited ) - 1 , len ( removes ) , l...
Filter the ObjectGraph in - place by removing all edges to nodes that do not match every filter in the given filter list
32,153
def removeNode ( self , node ) : ident = self . getIdent ( node ) if ident is not None : self . graph . hide_node ( ident )
Remove the given node from the graph if it exists
32,154
def removeReference ( self , fromnode , tonode ) : if fromnode is None : fromnode = self fromident = self . getIdent ( fromnode ) toident = self . getIdent ( tonode ) if fromident is not None and toident is not None : while True : edge = self . graph . edge_by_node ( fromident , toident ) if edge is None : break self ....
Remove all edges from fromnode to tonode
32,155
def getIdent ( self , node ) : ident = self . getRawIdent ( node ) if ident is not None : return ident node = self . findNode ( node ) if node is None : return None return node . graphident
Get the graph identifier for a node
32,156
def getRawIdent ( self , node ) : if node is self : return node ident = getattr ( node , 'graphident' , None ) return ident
Get the identifier for a node object
32,157
def findNode ( self , node ) : ident = self . getRawIdent ( node ) if ident is None : ident = node try : return self . graph . node_data ( ident ) except KeyError : return None
Find the node on the graph
32,158
def addNode ( self , node ) : self . msg ( 4 , "addNode" , node ) try : self . graph . restore_node ( node . graphident ) except GraphError : self . graph . add_node ( node . graphident , node )
Add a node to the graph referenced by the root
32,159
def createReference ( self , fromnode , tonode , edge_data = None ) : if fromnode is None : fromnode = self fromident , toident = self . getIdent ( fromnode ) , self . getIdent ( tonode ) if fromident is None or toident is None : return self . msg ( 4 , "createReference" , fromnode , tonode , edge_data ) self . graph ....
Create a reference from fromnode to tonode
32,160
def createNode ( self , cls , name , * args , ** kw ) : m = self . findNode ( name ) if m is None : m = cls ( name , * args , ** kw ) self . addNode ( m ) return m
Add a node of type cls to the graph if it does not already exist by the given name
32,161
def msg ( self , level , s , * args ) : if s and level <= self . debug : print "%s%s %s" % ( " " * self . indent , s , ' ' . join ( map ( repr , args ) ) )
Print a debug message with the given level
32,162
def dijkstra ( graph , start , end = None ) : D = { } P = { } Q = _priorityDictionary ( ) Q [ start ] = 0 for v in Q : D [ v ] = Q [ v ] if v == end : break for w in graph . out_nbrs ( v ) : edge_id = graph . edge_by_node ( v , w ) vwLength = D [ v ] + graph . edge_data ( edge_id ) if w in D : if vwLength < D [ w ] : r...
Dijkstra s algorithm for shortest paths
32,163
def smallest ( self ) : if len ( self ) == 0 : raise IndexError , "smallest of empty priorityDictionary" heap = self . __heap while heap [ 0 ] [ 1 ] not in self or self [ heap [ 0 ] [ 1 ] ] != heap [ 0 ] [ 0 ] : lastItem = heap . pop ( ) insertionPoint = 0 while 1 : smallChild = 2 * insertionPoint + 1 if smallChild + 1...
Find smallest item after removing deleted items from front of heap .
32,164
def _write_textfile ( filename , text ) : dirname = os . path . dirname ( filename ) if not os . path . exists ( dirname ) : os . makedirs ( dirname ) outf = open ( filename , 'w' ) outf . write ( text ) outf . close ( )
Write text into file filename . If the target directory does not exist create it .
32,165
def __add_options ( parser ) : parser . add_option ( '--upx-dir' , default = None , help = 'Directory containing UPX.' ) parser . add_option ( '-C' , '--configfile' , default = DEFAULT_CONFIGFILE , dest = 'configfilename' , help = 'Name of generated configfile (default: %default)' )
Add the Configure options to a option - parser instance or a option group .
32,166
def abspath ( path ) : global _USER_HOME_DIR if path [ 0 ] == '/' : return os . path . abspath ( path ) if _USER_HOME_DIR is None : try : _USER_HOME_DIR = _get_home_dir ( ) except IOError , e : if not exists ( '.' ) : raise IOError ( "Home directory doesn't exist" ) raise e return os . path . abspath ( os . path . join...
Return the absolute path to a file and canonicalize it
32,167
def cp ( hdfs_src , hdfs_dst ) : cmd = "hadoop fs -cp %s %s" % ( hdfs_src , hdfs_dst ) rcode , stdout , stderr = _checked_hadoop_fs_command ( cmd )
Copy a file
32,168
def stat ( path , format ) : cmd = "hadoop fs -stat %s %s" % ( format , path ) rcode , stdout , stderr = _checked_hadoop_fs_command ( cmd ) return stdout . rstrip ( )
Call stat on file
32,169
def mv ( hdfs_src , hdfs_dst ) : cmd = "hadoop fs -mv %s %s" % ( hdfs_src , hdfs_dst ) rcode , stdout , stderr = _checked_hadoop_fs_command ( cmd )
Move a file on hdfs
32,170
def put ( local_path , hdfs_path ) : cmd = "hadoop fs -put %s %s" % ( local_path , hdfs_path ) rcode , stdout , stderr = _checked_hadoop_fs_command ( cmd )
Put a file on hdfs
32,171
def get ( hdfs_path , local_path ) : cmd = "hadoop fs -get %s %s" % ( hdfs_path , local_path ) rcode , stdout , stderr = _checked_hadoop_fs_command ( cmd )
Get a file from hdfs
32,172
def ls ( path ) : rcode , stdout , stderr = _checked_hadoop_fs_command ( 'hadoop fs -ls %s' % path ) found_line = lambda x : re . search ( 'Found [0-9]+ items$' , x ) out = [ x . split ( ' ' ) [ - 1 ] for x in stdout . split ( '\n' ) if x and not found_line ( x ) ] return out
List files on HDFS .
32,173
def writetb ( path , kvs , java_mem_mb = 256 ) : read_fd , write_fd = os . pipe ( ) read_fp = os . fdopen ( read_fd , 'r' ) hstreaming = _find_hstreaming ( ) cmd = 'hadoop jar %s loadtb %s' % ( hstreaming , path ) p = _hadoop_fs_command ( cmd , stdin = read_fp , java_mem_mb = java_mem_mb ) read_fp . close ( ) with hado...
Write typedbytes sequence file to HDFS given an iterator of KeyValue pairs
32,174
def writetb_parts ( path , kvs , num_per_file , ** kw ) : out = [ ] part_num = 0 def _flush ( out , part_num ) : hadoopy . writetb ( '%s/part-%.5d' % ( path , part_num ) , out , ** kw ) return [ ] , part_num + 1 for kv in kvs : out . append ( kv ) if len ( out ) >= num_per_file : out , part_num = _flush ( out , part_nu...
Write typedbytes sequence files to HDFS given an iterator of KeyValue pairs
32,175
def add_node ( self , node , node_data = None ) : if node in self . hidden_nodes : return if node not in self . nodes : self . nodes [ node ] = ( [ ] , [ ] , node_data )
Adds a new node to the graph . Arbitrary data can be attached to the node via the node_data parameter . Adding the same node twice will be silently ignored .
32,176
def add_edge ( self , head_id , tail_id , edge_data = 1 , create_nodes = True ) : edge = self . next_edge if create_nodes : self . add_node ( head_id ) self . add_node ( tail_id ) try : self . nodes [ tail_id ] [ 0 ] . append ( edge ) self . nodes [ head_id ] [ 1 ] . append ( edge ) except KeyError : raise GraphError (...
Adds a directed edge going from head_id to tail_id . Arbitrary data can be attached to the edge via edge_data . It may create the nodes if adding edges between nonexisting ones .
32,177
def hide_edge ( self , edge ) : try : head_id , tail_id , edge_data = self . hidden_edges [ edge ] = self . edges [ edge ] self . nodes [ tail_id ] [ 0 ] . remove ( edge ) self . nodes [ head_id ] [ 1 ] . remove ( edge ) del self . edges [ edge ] except KeyError : raise GraphError ( 'Invalid edge %s' % edge )
Hides an edge from the graph . The edge may be unhidden at some later time .
32,178
def hide_node ( self , node ) : try : all_edges = self . all_edges ( node ) self . hidden_nodes [ node ] = ( self . nodes [ node ] , all_edges ) for edge in all_edges : self . hide_edge ( edge ) del self . nodes [ node ] except KeyError : raise GraphError ( 'Invalid node %s' % node )
Hides a node from the graph . The incoming and outgoing edges of the node will also be hidden . The node may be unhidden at some later time .
32,179
def restore_node ( self , node ) : try : self . nodes [ node ] , all_edges = self . hidden_nodes [ node ] for edge in all_edges : self . restore_edge ( edge ) del self . hidden_nodes [ node ] except KeyError : raise GraphError ( 'Invalid node %s' % node )
Restores a previously hidden node back into the graph and restores all of its incoming and outgoing edges .
32,180
def restore_edge ( self , edge ) : try : head_id , tail_id , data = self . hidden_edges [ edge ] self . nodes [ tail_id ] [ 0 ] . append ( edge ) self . nodes [ head_id ] [ 1 ] . append ( edge ) self . edges [ edge ] = head_id , tail_id , data del self . hidden_edges [ edge ] except KeyError : raise GraphError ( 'Inval...
Restores a previously hidden edge back into the graph .
32,181
def restore_all_edges ( self ) : for edge in self . hidden_edges . keys ( ) : try : self . restore_edge ( edge ) except GraphError : pass
Restores all hidden edges .
32,182
def describe_node ( self , node ) : incoming , outgoing , data = self . nodes [ node ] return node , data , outgoing , incoming
return node node data outgoing edges incoming edges for node
32,183
def describe_edge ( self , edge ) : head , tail , data = self . edges [ edge ] return edge , data , head , tail
return edge edge data head tail for edge
32,184
def out_nbrs ( self , node ) : l = map ( self . tail , self . out_edges ( node ) ) return l
List of nodes connected by outgoing edges
32,185
def inc_nbrs ( self , node ) : l = map ( self . head , self . inc_edges ( node ) ) return l
List of nodes connected by incoming edges
32,186
def all_nbrs ( self , node ) : l = dict . fromkeys ( self . inc_nbrs ( node ) + self . out_nbrs ( node ) ) return list ( l )
List of nodes connected by incoming and outgoing edges
32,187
def out_edges ( self , node ) : try : return list ( self . nodes [ node ] [ 1 ] ) except KeyError : raise GraphError ( 'Invalid node %s' % node ) return None
Returns a list of the outgoing edges
32,188
def inc_edges ( self , node ) : try : return list ( self . nodes [ node ] [ 0 ] ) except KeyError : raise GraphError ( 'Invalid node %s' % node ) return None
Returns a list of the incoming edges
32,189
def all_edges ( self , node ) : return set ( self . inc_edges ( node ) + self . out_edges ( node ) )
Returns a list of incoming and outging edges .
32,190
def _topo_sort ( self , forward = True ) : topo_list = [ ] queue = deque ( ) indeg = { } if forward : get_edges = self . out_edges get_degree = self . inc_degree get_next = self . tail else : get_edges = self . inc_edges get_degree = self . out_degree get_next = self . head for node in self . node_list ( ) : degree = g...
Topological sort .
32,191
def _bfs_subgraph ( self , start_id , forward = True ) : if forward : get_bfs = self . forw_bfs get_nbrs = self . out_nbrs else : get_bfs = self . back_bfs get_nbrs = self . inc_nbrs g = Graph ( ) bfs_list = get_bfs ( start_id ) for node in bfs_list : g . add_node ( node ) for node in bfs_list : for nbr_id in get_nbrs ...
Private method creates a subgraph in a bfs order .
32,192
def iterdfs ( self , start , end = None , forward = True ) : visited , stack = set ( [ start ] ) , deque ( [ start ] ) if forward : get_edges = self . out_edges get_next = self . tail else : get_edges = self . inc_edges get_next = self . head while stack : curr_node = stack . pop ( ) yield curr_node if curr_node == end...
Collecting nodes in some depth first traversal .
32,193
def _iterbfs ( self , start , end = None , forward = True ) : queue , visited = deque ( [ ( start , 0 ) ] ) , set ( [ start ] ) if forward : get_edges = self . out_edges get_next = self . tail else : get_edges = self . inc_edges get_next = self . head while queue : curr_node , curr_step = queue . popleft ( ) yield ( cu...
The forward parameter specifies whether it is a forward or backward traversal . Returns a list of tuples where the first value is the hop value the second value is the node id .
32,194
def forw_bfs ( self , start , end = None ) : return [ node for node , step in self . _iterbfs ( start , end , forward = True ) ]
Returns a list of nodes in some forward BFS order .
32,195
def back_bfs ( self , start , end = None ) : return [ node for node , step in self . _iterbfs ( start , end , forward = False ) ]
Returns a list of nodes in some backward BFS order .
32,196
def forw_dfs ( self , start , end = None ) : return list ( self . iterdfs ( start , end , forward = True ) )
Returns a list of nodes in some forward DFS order .
32,197
def back_dfs ( self , start , end = None ) : return list ( self . iterdfs ( start , end , forward = False ) )
Returns a list of nodes in some backward DFS order .
32,198
def clust_coef ( self , node ) : num = 0 nbr_set = set ( self . out_nbrs ( node ) ) if node in nbr_set : nbr_set . remove ( node ) for nbr in nbr_set : sec_set = set ( self . out_nbrs ( nbr ) ) if nbr in sec_set : sec_set . remove ( nbr ) num += len ( nbr_set & sec_set ) nbr_num = len ( nbr_set ) if nbr_num : clust_coe...
Computes and returns the local clustering coefficient of node . The local cluster coefficient is proportion of the actual number of edges between neighbours of node and the maximum number of edges between those neighbours .
32,199
def get_hops ( self , start , end = None , forward = True ) : if forward : return list ( self . _iterbfs ( start = start , end = end , forward = True ) ) else : return list ( self . _iterbfs ( start = start , end = end , forward = False ) )
Computes the hop distance to all nodes centered around a specified node .