idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
226,600 | def get_relative_to_remote ( self ) : s = self . git ( "status" , "--short" , "-b" ) [ 0 ] r = re . compile ( "\[([^\]]+)\]" ) toks = r . findall ( s ) if toks : try : s2 = toks [ - 1 ] adj , n = s2 . split ( ) assert ( adj in ( "ahead" , "behind" ) ) n = int ( n ) return - n if adj == "behind" else n except Exception as e : raise ReleaseVCSError ( ( "Problem parsing first line of result of 'git status " "--short -b' (%s):\n%s" ) % ( s , str ( e ) ) ) else : return 0 | Return the number of commits we are relative to the remote . Negative is behind positive in front zero means we are matched to remote . | 170 | 26 |
226,601 | def links ( self , obj ) : if obj in self . edge_links : return self . edge_links [ obj ] else : return self . node_links [ obj ] | Return all nodes connected by the given hyperedge or all hyperedges connected to the given hypernode . | 37 | 22 |
226,602 | def neighbors ( self , obj ) : neighbors = set ( [ ] ) for e in self . node_links [ obj ] : neighbors . update ( set ( self . edge_links [ e ] ) ) return list ( neighbors - set ( [ obj ] ) ) | Return all neighbors adjacent to the given node . | 55 | 9 |
226,603 | def del_node ( self , node ) : if self . has_node ( node ) : for e in self . node_links [ node ] : self . edge_links [ e ] . remove ( node ) self . node_links . pop ( node ) self . graph . del_node ( ( node , 'n' ) ) | Delete a given node from the hypergraph . | 71 | 9 |
226,604 | def add_hyperedge ( self , hyperedge ) : if ( not hyperedge in self . edge_links ) : self . edge_links [ hyperedge ] = [ ] self . graph . add_node ( ( hyperedge , 'h' ) ) | Add given hyperedge to the hypergraph . | 60 | 10 |
226,605 | def del_hyperedge ( self , hyperedge ) : if ( hyperedge in self . hyperedges ( ) ) : for n in self . edge_links [ hyperedge ] : self . node_links [ n ] . remove ( hyperedge ) del ( self . edge_links [ hyperedge ] ) self . del_edge_labeling ( hyperedge ) self . graph . del_node ( ( hyperedge , 'h' ) ) | Delete the given hyperedge . | 103 | 7 |
226,606 | def link ( self , node , hyperedge ) : if ( hyperedge not in self . node_links [ node ] ) : self . edge_links [ hyperedge ] . append ( node ) self . node_links [ node ] . append ( hyperedge ) self . graph . add_edge ( ( ( node , 'n' ) , ( hyperedge , 'h' ) ) ) else : raise AdditionError ( "Link (%s, %s) already in graph" % ( node , hyperedge ) ) | Link given node and hyperedge . | 115 | 8 |
226,607 | def unlink ( self , node , hyperedge ) : self . node_links [ node ] . remove ( hyperedge ) self . edge_links [ hyperedge ] . remove ( node ) self . graph . del_edge ( ( ( node , 'n' ) , ( hyperedge , 'h' ) ) ) | Unlink given node and hyperedge . | 71 | 9 |
226,608 | def rank ( self ) : max_rank = 0 for each in self . hyperedges ( ) : if len ( self . edge_links [ each ] ) > max_rank : max_rank = len ( self . edge_links [ each ] ) return max_rank | Return the rank of the given hypergraph . | 58 | 9 |
226,609 | def get_next_base26 ( prev = None ) : if not prev : return 'a' r = re . compile ( "^[a-z]*$" ) if not r . match ( prev ) : raise ValueError ( "Invalid base26" ) if not prev . endswith ( 'z' ) : return prev [ : - 1 ] + chr ( ord ( prev [ - 1 ] ) + 1 ) return get_next_base26 ( prev [ : - 1 ] ) + 'a' | Increment letter - based IDs . | 111 | 7 |
226,610 | def create_unique_base26_symlink ( path , source ) : retries = 0 while True : # if a link already exists that points at `source`, return it name = find_matching_symlink ( path , source ) if name : return os . path . join ( path , name ) # get highest current symlink in path names = [ x for x in os . listdir ( path ) if os . path . islink ( os . path . join ( path , x ) ) ] if names : prev = max ( names ) else : prev = None linkname = get_next_base26 ( prev ) linkpath = os . path . join ( path , linkname ) # attempt to create the symlink try : os . symlink ( source , linkpath ) return linkpath except OSError as e : if e . errno != errno . EEXIST : raise # if we're here, the same named symlink was created in parallel # somewhere. Try again up to N times. # if retries > 10 : raise RuntimeError ( "Variant shortlink not created - there was too much contention." ) retries += 1 | Create a base - 26 symlink in path pointing to source . | 252 | 14 |
226,611 | def find_wheels ( projects , search_dirs ) : wheels = [ ] # Look through SEARCH_DIRS for the first suitable wheel. Don't bother # about version checking here, as this is simply to get something we can # then use to install the correct version. for project in projects : for dirname in search_dirs : # This relies on only having "universal" wheels available. # The pattern could be tightened to require -py2.py3-none-any.whl. files = glob . glob ( os . path . join ( dirname , project + '-*.whl' ) ) if files : wheels . append ( os . path . abspath ( files [ 0 ] ) ) break else : # We're out of luck, so quit with a suitable error logger . fatal ( 'Cannot find a wheel for %s' % ( project , ) ) return wheels | Find wheels from which we can import PROJECTS . | 190 | 12 |
226,612 | def relative_script ( lines ) : activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this" # Find the last future statement in the script. If we insert the activation # line before a future statement, Python will raise a SyntaxError. activate_at = None for idx , line in reversed ( list ( enumerate ( lines ) ) ) : if line . split ( ) [ : 3 ] == [ 'from' , '__future__' , 'import' ] : activate_at = idx + 1 break if activate_at is None : # Activate after the shebang. activate_at = 1 return lines [ : activate_at ] + [ '' , activate , '' ] + lines [ activate_at : ] | Return a script that ll work in a relocatable environment . | 218 | 13 |
226,613 | def fixup_pth_and_egg_link ( home_dir , sys_path = None ) : home_dir = os . path . normcase ( os . path . abspath ( home_dir ) ) if sys_path is None : sys_path = sys . path for path in sys_path : if not path : path = '.' if not os . path . isdir ( path ) : continue path = os . path . normcase ( os . path . abspath ( path ) ) if not path . startswith ( home_dir ) : logger . debug ( 'Skipping system (non-environment) directory %s' % path ) continue for filename in os . listdir ( path ) : filename = os . path . join ( path , filename ) if filename . endswith ( '.pth' ) : if not os . access ( filename , os . W_OK ) : logger . warn ( 'Cannot write .pth file %s, skipping' % filename ) else : fixup_pth_file ( filename ) if filename . endswith ( '.egg-link' ) : if not os . access ( filename , os . W_OK ) : logger . warn ( 'Cannot write .egg-link file %s, skipping' % filename ) else : fixup_egg_link ( filename ) | Makes . pth and . egg - link files use relative paths | 287 | 14 |
226,614 | def make_relative_path ( source , dest , dest_is_directory = True ) : source = os . path . dirname ( source ) if not dest_is_directory : dest_filename = os . path . basename ( dest ) dest = os . path . dirname ( dest ) dest = os . path . normpath ( os . path . abspath ( dest ) ) source = os . path . normpath ( os . path . abspath ( source ) ) dest_parts = dest . strip ( os . path . sep ) . split ( os . path . sep ) source_parts = source . strip ( os . path . sep ) . split ( os . path . sep ) while dest_parts and source_parts and dest_parts [ 0 ] == source_parts [ 0 ] : dest_parts . pop ( 0 ) source_parts . pop ( 0 ) full_parts = [ '..' ] * len ( source_parts ) + dest_parts if not dest_is_directory : full_parts . append ( dest_filename ) if not full_parts : # Special case for the current directory (otherwise it'd be '') return './' return os . path . sep . join ( full_parts ) | Make a filename relative where the filename is dest and it is being referred to from the filename source . | 262 | 20 |
226,615 | def create_bootstrap_script ( extra_text , python_version = '' ) : filename = __file__ if filename . endswith ( '.pyc' ) : filename = filename [ : - 1 ] f = codecs . open ( filename , 'r' , encoding = 'utf-8' ) content = f . read ( ) f . close ( ) py_exe = 'python%s' % python_version content = ( ( '#!/usr/bin/env %s\n' % py_exe ) + '## WARNING: This file is generated\n' + content ) return content . replace ( '##EXT' 'END##' , extra_text ) | Creates a bootstrap script which is like this script but with extend_parser adjust_options and after_install hooks . | 146 | 25 |
226,616 | def read_data ( file , endian , num = 1 ) : res = struct . unpack ( endian + 'L' * num , file . read ( num * 4 ) ) if len ( res ) == 1 : return res [ 0 ] return res | Read a given number of 32 - bits unsigned integers from the given file with the given endianness . | 55 | 21 |
226,617 | def _stdout_level ( self ) : for level , consumer in self . consumers : if consumer is sys . stdout : return level return self . FATAL | Returns the level that stdout runs at | 34 | 8 |
226,618 | def get_config_section ( self , name ) : if self . config . has_section ( name ) : return self . config . items ( name ) return [ ] | Get a section of a configuration | 36 | 6 |
226,619 | def get_environ_vars ( self , prefix = 'VIRTUALENV_' ) : for key , val in os . environ . items ( ) : if key . startswith ( prefix ) : yield ( key . replace ( prefix , '' ) . lower ( ) , val ) | Returns a generator with all environmental vars with prefix VIRTUALENV | 64 | 15 |
226,620 | def copy ( self , overrides = None , locked = False ) : other = copy . copy ( self ) if overrides is not None : other . overrides = overrides other . locked = locked other . _uncache ( ) return other | Create a separate copy of this config . | 51 | 8 |
226,621 | def override ( self , key , value ) : keys = key . split ( '.' ) if len ( keys ) > 1 : if keys [ 0 ] != "plugins" : raise AttributeError ( "no such setting: %r" % key ) self . plugins . override ( keys [ 1 : ] , value ) else : self . overrides [ key ] = value self . _uncache ( key ) | Set a setting to the given value . | 86 | 8 |
226,622 | def remove_override ( self , key ) : keys = key . split ( '.' ) if len ( keys ) > 1 : raise NotImplementedError elif key in self . overrides : del self . overrides [ key ] self . _uncache ( key ) | Remove a setting override if one exists . | 59 | 8 |
226,623 | def warn ( self , key ) : return ( not self . quiet and not self . warn_none and ( self . warn_all or getattr ( self , "warn_%s" % key ) ) ) | Returns True if the warning setting is enabled . | 45 | 9 |
226,624 | def debug ( self , key ) : return ( not self . quiet and not self . debug_none and ( self . debug_all or getattr ( self , "debug_%s" % key ) ) ) | Returns True if the debug setting is enabled . | 45 | 9 |
226,625 | def data ( self ) : d = { } for key in self . _data : if key == "plugins" : d [ key ] = self . plugins . data ( ) else : try : d [ key ] = getattr ( self , key ) except AttributeError : pass # unknown key, just leave it unchanged return d | Returns the entire configuration as a dict . | 69 | 8 |
226,626 | def nonlocal_packages_path ( self ) : paths = self . packages_path [ : ] if self . local_packages_path in paths : paths . remove ( self . local_packages_path ) return paths | Returns package search paths with local path removed . | 46 | 9 |
226,627 | def _swap ( self , other ) : self . __dict__ , other . __dict__ = other . __dict__ , self . __dict__ | Swap this config with another . | 33 | 7 |
226,628 | def _create_main_config ( cls , overrides = None ) : filepaths = [ ] filepaths . append ( get_module_root_config ( ) ) filepath = os . getenv ( "REZ_CONFIG_FILE" ) if filepath : filepaths . extend ( filepath . split ( os . pathsep ) ) filepath = os . path . expanduser ( "~/.rezconfig" ) filepaths . append ( filepath ) return Config ( filepaths , overrides ) | See comment block at top of rezconfig describing how the main config is assembled . | 115 | 17 |
226,629 | def platform_mapped ( func ) : def inner ( * args , * * kwargs ) : # Since platform is being used within config lazy import config to prevent # circular dependencies from rez . config import config # Original result result = func ( * args , * * kwargs ) # The function name is used as primary key entry = config . platform_map . get ( func . __name__ ) if entry : for key , value in entry . iteritems ( ) : result , changes = re . subn ( key , value , result ) if changes > 0 : break return result return inner | Decorates functions for lookups within a config . platform_map dictionary . | 126 | 16 |
226,630 | def pagerank ( graph , damping_factor = 0.85 , max_iterations = 100 , min_delta = 0.00001 ) : nodes = graph . nodes ( ) graph_size = len ( nodes ) if graph_size == 0 : return { } min_value = ( 1.0 - damping_factor ) / graph_size #value for nodes without inbound links # itialize the page rank dict with 1/N for all nodes pagerank = dict . fromkeys ( nodes , 1.0 / graph_size ) for i in range ( max_iterations ) : diff = 0 #total difference compared to last iteraction # computes each node PageRank based on inbound links for node in nodes : rank = min_value for referring_page in graph . incidents ( node ) : rank += damping_factor * pagerank [ referring_page ] / len ( graph . neighbors ( referring_page ) ) diff += abs ( pagerank [ node ] - rank ) pagerank [ node ] = rank #stop if PageRank has converged if diff < min_delta : break return pagerank | Compute and return the PageRank in an directed graph . | 244 | 12 |
226,631 | def exec_command ( attr , cmd ) : import subprocess p = popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) out , err = p . communicate ( ) if p . returncode : from rez . exceptions import InvalidPackageError raise InvalidPackageError ( "Error determining package attribute '%s':\n%s" % ( attr , err ) ) return out . strip ( ) , err . strip ( ) | Runs a subproc to calculate a package attribute . | 105 | 11 |
226,632 | def exec_python ( attr , src , executable = "python" ) : import subprocess if isinstance ( src , basestring ) : src = [ src ] p = popen ( [ executable , "-c" , "; " . join ( src ) ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) out , err = p . communicate ( ) if p . returncode : from rez . exceptions import InvalidPackageError raise InvalidPackageError ( "Error determining package attribute '%s':\n%s" % ( attr , err ) ) return out . strip ( ) | Runs a python subproc to calculate a package attribute . | 136 | 12 |
226,633 | def find_site_python ( module_name , paths = None ) : from rez . packages_ import iter_packages import subprocess import ast import os py_cmd = 'import {x}; print {x}.__path__' . format ( x = module_name ) p = popen ( [ "python" , "-c" , py_cmd ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) out , err = p . communicate ( ) if p . returncode : raise InvalidPackageError ( "Failed to find installed python module '%s':\n%s" % ( module_name , err ) ) module_paths = ast . literal_eval ( out . strip ( ) ) def issubdir ( path , parent_path ) : return path . startswith ( parent_path + os . sep ) for package in iter_packages ( "python" , paths = paths ) : if not hasattr ( package , "_site_paths" ) : continue contained = True for module_path in module_paths : if not any ( issubdir ( module_path , x ) for x in package . _site_paths ) : contained = False if contained : return package raise InvalidPackageError ( "Failed to find python installation containing the module '%s'. Has " "python been installed as a rez package?" % module_name ) | Find the rez native python package that contains the given module . | 304 | 13 |
226,634 | def _intersection ( A , B ) : intersection = [ ] for i in A : if i in B : intersection . append ( i ) return intersection | A simple function to find an intersection between two arrays . | 32 | 11 |
226,635 | def critical_path ( graph ) : #if the graph contains a cycle we return an empty array if not len ( find_cycle ( graph ) ) == 0 : return [ ] #this empty dictionary will contain a tuple for every single node #the tuple contains the information about the most costly predecessor #of the given node and the cost of the path to this node #(predecessor, cost) node_tuples = { } topological_nodes = topological_sorting ( graph ) #all the tuples must be set to a default value for every node in the graph for node in topological_nodes : node_tuples . update ( { node : ( None , 0 ) } ) #run trough all the nodes in a topological order for node in topological_nodes : predecessors = [ ] #we must check all the predecessors for pre in graph . incidents ( node ) : max_pre = node_tuples [ pre ] [ 1 ] predecessors . append ( ( pre , graph . edge_weight ( ( pre , node ) ) + max_pre ) ) max = 0 max_tuple = ( None , 0 ) for i in predecessors : #look for the most costly predecessor if i [ 1 ] >= max : max = i [ 1 ] max_tuple = i #assign the maximum value to the given node in the node_tuples dictionary node_tuples [ node ] = max_tuple #find the critical node max = 0 critical_node = None for k , v in list ( node_tuples . items ( ) ) : if v [ 1 ] >= max : max = v [ 1 ] critical_node = k path = [ ] #find the critical path with backtracking trought the dictionary def mid_critical_path ( end ) : if node_tuples [ end ] [ 0 ] != None : path . append ( end ) mid_critical_path ( node_tuples [ end ] [ 0 ] ) else : path . append ( end ) #call the recursive function mid_critical_path ( critical_node ) path . reverse ( ) return path | Compute and return the critical path in an acyclic directed weighted graph . | 443 | 17 |
226,636 | def build ( self , context , variant , build_path , install_path , install = False , build_type = BuildType . local ) : ret = { } if self . write_build_scripts : # write out the script that places the user in a build env, where # they can run bez directly themselves. build_env_script = os . path . join ( build_path , "build-env" ) create_forwarding_script ( build_env_script , module = ( "build_system" , "custom" ) , func_name = "_FWD__spawn_build_shell" , working_dir = self . working_dir , build_path = build_path , variant_index = variant . index , install = install , install_path = install_path ) ret [ "success" ] = True ret [ "build_env_script" ] = build_env_script return ret # get build command command = self . package . build_command # False just means no build command if command is False : ret [ "success" ] = True return ret def expand ( txt ) : root = self . package . root install_ = "install" if install else '' return txt . format ( root = root , install = install_ ) . strip ( ) if isinstance ( command , basestring ) : if self . build_args : command = command + ' ' + ' ' . join ( map ( quote , self . build_args ) ) command = expand ( command ) cmd_str = command else : # list command = command + self . build_args command = map ( expand , command ) cmd_str = ' ' . join ( map ( quote , command ) ) if self . verbose : pr = Printer ( sys . stdout ) pr ( "Running build command: %s" % cmd_str , heading ) # run the build command def _callback ( executor ) : self . _add_build_actions ( executor , context = context , package = self . package , variant = variant , build_type = build_type , install = install , build_path = build_path , install_path = install_path ) if self . opts : # write args defined in ./parse_build_args.py out as env vars extra_args = getattr ( self . opts . parser , "_rezbuild_extra_args" , [ ] ) for key , value in vars ( self . opts ) . iteritems ( ) : if key in extra_args : varname = "__PARSE_ARG_%s" % key . upper ( ) # do some value conversions if isinstance ( value , bool ) : value = 1 if value else 0 elif isinstance ( value , ( list , tuple ) ) : value = map ( str , value ) value = map ( quote , value ) value = ' ' . join ( value ) executor . env [ varname ] = value retcode , _ , _ = context . execute_shell ( command = command , block = True , cwd = build_path , actions_callback = _callback ) ret [ "success" ] = ( not retcode ) return ret | Perform the build . | 678 | 5 |
226,637 | def _create_tag_highlevel ( self , tag_name , message = None ) : results = [ ] if self . patch_path : # make a tag on the patch queue tagged = self . _create_tag_lowlevel ( tag_name , message = message , patch = True ) if tagged : results . append ( { 'type' : 'tag' , 'patch' : True } ) # use a bookmark on the main repo since we can't change it self . hg ( 'bookmark' , '-f' , tag_name ) results . append ( { 'type' : 'bookmark' , 'patch' : False } ) else : tagged = self . _create_tag_lowlevel ( tag_name , message = message , patch = False ) if tagged : results . append ( { 'type' : 'tag' , 'patch' : False } ) return results | Create a tag on the toplevel repo if there is no patch repo or a tag on the patch repo and bookmark on the top repo if there is a patch repo | 191 | 34 |
226,638 | def _create_tag_lowlevel ( self , tag_name , message = None , force = True , patch = False ) : # check if tag already exists, and if it does, if it is a direct # ancestor, and there is NO difference in the files between the tagged # state and current state # # This check is mainly to avoid re-creating the same tag over and over # on what is essentially the same commit, since tagging will # technically create a new commit, and update the working copy to it. # # Without this check, say you were releasing to three different # locations, one right after another; the first would create the tag, # and a new tag commit. The second would then recreate the exact same # tag, but now pointing at the commit that made the first tag. # The third would create the tag a THIRD time, but now pointing at the # commit that created the 2nd tag. tags = self . get_tags ( patch = patch ) old_commit = tags . get ( tag_name ) if old_commit is not None : if not force : return False old_rev = old_commit [ 'rev' ] # ok, now check to see if direct ancestor... if self . is_ancestor ( old_rev , '.' , patch = patch ) : # ...and if filestates are same altered = self . hg ( 'status' , '--rev' , old_rev , '--rev' , '.' , '--no-status' ) if not altered or altered == [ '.hgtags' ] : force = False if not force : return False tag_args = [ 'tag' , tag_name ] if message : tag_args += [ '--message' , message ] # we should be ok with ALWAYS having force flag on now, since we should # have already checked if the commit exists.. but be paranoid, in case # we've missed some edge case... if force : tag_args += [ '--force' ] self . hg ( patch = patch , * tag_args ) return True | Create a tag on the toplevel or patch repo | 438 | 11 |
226,639 | def is_ancestor ( self , commit1 , commit2 , patch = False ) : result = self . hg ( "log" , "-r" , "first(%s::%s)" % ( commit1 , commit2 ) , "--template" , "exists" , patch = patch ) return "exists" in result | Returns True if commit1 is a direct ancestor of commit2 or False otherwise . | 74 | 16 |
226,640 | def get_patched_request ( requires , patchlist ) : # rules from table in docstring above rules = { '' : ( True , True , True ) , '!' : ( False , False , False ) , '~' : ( False , False , True ) , '^' : ( True , True , True ) } requires = [ Requirement ( x ) if not isinstance ( x , Requirement ) else x for x in requires ] appended = [ ] for patch in patchlist : if patch and patch [ 0 ] in ( '!' , '~' , '^' ) : ch = patch [ 0 ] name = Requirement ( patch [ 1 : ] ) . name else : ch = '' name = Requirement ( patch ) . name rule = rules [ ch ] replaced = ( ch == '^' ) for i , req in enumerate ( requires ) : if req is None or req . name != name : continue if not req . conflict : replace = rule [ 0 ] # foo elif not req . weak : replace = rule [ 1 ] # !foo else : replace = rule [ 2 ] # ~foo if replace : if replaced : requires [ i ] = None else : requires [ i ] = Requirement ( patch ) replaced = True if not replaced : appended . append ( Requirement ( patch ) ) result = [ x for x in requires if x is not None ] + appended return result | Apply patch args to a request . | 300 | 7 |
226,641 | def execute ( self , app_path , app_args , version , * * kwargs ) : multi_launchapp = self . parent extra = multi_launchapp . get_setting ( "extra" ) use_rez = False if self . check_rez ( ) : from rez . resolved_context import ResolvedContext from rez . config import config # Define variables used to bootstrap tank from overwrite on first reference # PYTHONPATH is used by tk-maya # NUKE_PATH is used by tk-nuke # HIERO_PLUGIN_PATH is used by tk-nuke (nukestudio) # KATANA_RESOURCES is used by tk-katana config . parent_variables = [ "PYTHONPATH" , "HOUDINI_PATH" , "NUKE_PATH" , "HIERO_PLUGIN_PATH" , "KATANA_RESOURCES" ] rez_packages = extra [ "rez_packages" ] context = ResolvedContext ( rez_packages ) use_rez = True system = sys . platform shell_type = 'bash' if system == "linux2" : # on linux, we just run the executable directly cmd = "%s %s &" % ( app_path , app_args ) elif self . parent . get_setting ( "engine" ) in [ "tk-flame" , "tk-flare" ] : # flame and flare works in a different way from other DCCs # on both linux and mac, they run unix-style command line # and on the mac the more standardized "open" command cannot # be utilized. cmd = "%s %s &" % ( app_path , app_args ) elif system == "darwin" : # on the mac, the executable paths are normally pointing # to the application bundle and not to the binary file # embedded in the bundle, meaning that we should use the # built-in mac open command to execute it cmd = "open -n \"%s\"" % ( app_path ) if app_args : cmd += " --args \"%s\"" % app_args . replace ( "\"" , "\\\"" ) elif system == "win32" : # on windows, we run the start command in order to avoid # any command shells popping up as part of the application launch. cmd = "start /B \"App\" \"%s\" %s" % ( app_path , app_args ) shell_type = 'cmd' # Execute App in a Rez context if use_rez : n_env = os . environ . copy ( ) proc = context . execute_shell ( command = cmd , parent_environ = n_env , shell = shell_type , stdin = False , block = False ) exit_code = proc . wait ( ) context . print_info ( verbosity = True ) else : # run the command to launch the app exit_code = os . system ( cmd ) return { "command" : cmd , "return_code" : exit_code } | The execute functon of the hook will be called to start the required application | 674 | 16 |
226,642 | def check_rez ( self , strict = True ) : system = sys . platform if system == "win32" : rez_cmd = 'rez-env rez -- echo %REZ_REZ_ROOT%' else : rez_cmd = 'rez-env rez -- printenv REZ_REZ_ROOT' process = subprocess . Popen ( rez_cmd , stdout = subprocess . PIPE , shell = True ) rez_path , err = process . communicate ( ) if err or not rez_path : if strict : raise ImportError ( "Failed to find Rez as a package in the current " "environment! Try 'rez-bind rez'!" ) else : print >> sys . stderr , ( "WARNING: Failed to find a Rez package in the current " "environment. Unable to request Rez packages." ) rez_path = "" else : rez_path = rez_path . strip ( ) print "Found Rez:" , rez_path print "Adding Rez to system path..." sys . path . append ( rez_path ) return rez_path | Checks to see if a Rez package is available in the current environment . If it is available add it to the system path exposing the Rez Python API | 244 | 30 |
226,643 | def get_last_changed_revision ( client , url ) : try : svn_entries = client . info2 ( url , pysvn . Revision ( pysvn . opt_revision_kind . head ) , recurse = False ) if not svn_entries : raise ReleaseVCSError ( "svn.info2() returned no results on url %s" % url ) return svn_entries [ 0 ] [ 1 ] . last_changed_rev except pysvn . ClientError , ce : raise ReleaseVCSError ( "svn.info2() raised ClientError: %s" % ce ) | util func get last revision of url | 143 | 7 |
226,644 | def get_svn_login ( realm , username , may_save ) : import getpass print "svn requires a password for the user %s:" % username pwd = '' while not pwd . strip ( ) : pwd = getpass . getpass ( "--> " ) return True , username , pwd , False | provide svn with permissions . | 70 | 7 |
226,645 | def read ( string ) : dom = parseString ( string ) if dom . getElementsByTagName ( "graph" ) : G = graph ( ) elif dom . getElementsByTagName ( "digraph" ) : G = digraph ( ) elif dom . getElementsByTagName ( "hypergraph" ) : return read_hypergraph ( string ) else : raise InvalidGraphType # Read nodes... for each_node in dom . getElementsByTagName ( "node" ) : G . add_node ( each_node . getAttribute ( 'id' ) ) for each_attr in each_node . getElementsByTagName ( "attribute" ) : G . add_node_attribute ( each_node . getAttribute ( 'id' ) , ( each_attr . getAttribute ( 'attr' ) , each_attr . getAttribute ( 'value' ) ) ) # Read edges... for each_edge in dom . getElementsByTagName ( "edge" ) : if ( not G . has_edge ( ( each_edge . getAttribute ( 'from' ) , each_edge . getAttribute ( 'to' ) ) ) ) : G . add_edge ( ( each_edge . getAttribute ( 'from' ) , each_edge . getAttribute ( 'to' ) ) , wt = float ( each_edge . getAttribute ( 'wt' ) ) , label = each_edge . getAttribute ( 'label' ) ) for each_attr in each_edge . getElementsByTagName ( "attribute" ) : attr_tuple = ( each_attr . getAttribute ( 'attr' ) , each_attr . getAttribute ( 'value' ) ) if ( attr_tuple not in G . edge_attributes ( ( each_edge . getAttribute ( 'from' ) , each_edge . getAttribute ( 'to' ) ) ) ) : G . add_edge_attribute ( ( each_edge . getAttribute ( 'from' ) , each_edge . getAttribute ( 'to' ) ) , attr_tuple ) return G | Read a graph from a XML document and return it . Nodes and edges specified in the input will be added to the current graph . | 457 | 27 |
226,646 | def read_hypergraph ( string ) : hgr = hypergraph ( ) dom = parseString ( string ) for each_node in dom . getElementsByTagName ( "node" ) : hgr . add_node ( each_node . getAttribute ( 'id' ) ) for each_node in dom . getElementsByTagName ( "hyperedge" ) : hgr . add_hyperedge ( each_node . getAttribute ( 'id' ) ) dom = parseString ( string ) for each_node in dom . getElementsByTagName ( "node" ) : for each_edge in each_node . getElementsByTagName ( "link" ) : hgr . link ( str ( each_node . getAttribute ( 'id' ) ) , str ( each_edge . getAttribute ( 'to' ) ) ) return hgr | Read a graph from a XML document . Nodes and hyperedges specified in the input will be added to the current graph . | 190 | 26 |
226,647 | def diff_packages ( pkg1 , pkg2 = None ) : if pkg2 is None : it = iter_packages ( pkg1 . name ) pkgs = [ x for x in it if x . version < pkg1 . version ] if not pkgs : raise RezError ( "No package to diff with - %s is the earliest " "package version" % pkg1 . qualified_name ) pkgs = sorted ( pkgs , key = lambda x : x . version ) pkg2 = pkgs [ - 1 ] def _check_pkg ( pkg ) : if not ( pkg . vcs and pkg . revision ) : raise RezError ( "Cannot diff package %s: it is a legacy format " "package that does not contain enough information" % pkg . qualified_name ) _check_pkg ( pkg1 ) _check_pkg ( pkg2 ) path = mkdtemp ( prefix = "rez-pkg-diff" ) paths = [ ] for pkg in ( pkg1 , pkg2 ) : print "Exporting %s..." % pkg . qualified_name path_ = os . path . join ( path , pkg . qualified_name ) vcs_cls_1 = plugin_manager . get_plugin_class ( "release_vcs" , pkg1 . vcs ) vcs_cls_1 . export ( revision = pkg . revision , path = path_ ) paths . append ( path_ ) difftool = config . difftool print "Opening diff viewer %s..." % difftool proc = Popen ( [ difftool ] + paths ) proc . wait ( ) | Invoke a diff editor to show the difference between the source of two packages . | 370 | 16 |
226,648 | def sigint_handler ( signum , frame ) : global _handled_int if not _handled_int : _handled_int = True if not _env_var_true ( "_REZ_QUIET_ON_SIG" ) : print >> sys . stderr , "Interrupted by user" sigbase_handler ( signum , frame ) | Exit gracefully on ctrl - C . | 77 | 9 |
226,649 | def sigterm_handler ( signum , frame ) : global _handled_term if not _handled_term : _handled_term = True if not _env_var_true ( "_REZ_QUIET_ON_SIG" ) : print >> sys . stderr , "Terminated by user" sigbase_handler ( signum , frame ) | Exit gracefully on terminate . | 77 | 6 |
226,650 | def format_help ( self ) : if self . _subparsers : for action in self . _subparsers . _actions : if isinstance ( action , LazySubParsersAction ) : for parser_name , parser in action . _name_parser_map . iteritems ( ) : action . _setup_subparser ( parser_name , parser ) return super ( LazyArgumentParser , self ) . format_help ( ) | Sets up all sub - parsers when help is requested . | 98 | 13 |
226,651 | def is_valid_package_name ( name , raise_error = False ) : is_valid = PACKAGE_NAME_REGEX . match ( name ) if raise_error and not is_valid : raise PackageRequestError ( "Not a valid package name: %r" % name ) return is_valid | Test the validity of a package name string . | 66 | 9 |
226,652 | def expand_abbreviations ( txt , fields ) : def _expand ( matchobj ) : s = matchobj . group ( "var" ) if s not in fields : matches = [ x for x in fields if x . startswith ( s ) ] if len ( matches ) == 1 : s = matches [ 0 ] return "{%s}" % s return re . sub ( FORMAT_VAR_REGEX , _expand , txt ) | Expand abbreviations in a format string . | 100 | 9 |
226,653 | def dict_to_attributes_code ( dict_ ) : lines = [ ] for key , value in dict_ . iteritems ( ) : if isinstance ( value , dict ) : txt = dict_to_attributes_code ( value ) lines_ = txt . split ( '\n' ) for line in lines_ : if not line . startswith ( ' ' ) : line = "%s.%s" % ( key , line ) lines . append ( line ) else : value_txt = pformat ( value ) if '\n' in value_txt : lines . append ( "%s = \\" % key ) value_txt = indent ( value_txt ) lines . extend ( value_txt . split ( '\n' ) ) else : line = "%s = %s" % ( key , value_txt ) lines . append ( line ) return '\n' . join ( lines ) | Given a nested dict generate a python code equivalent . | 198 | 10 |
226,654 | def columnise ( rows , padding = 2 ) : strs = [ ] maxwidths = { } for row in rows : for i , e in enumerate ( row ) : se = str ( e ) nse = len ( se ) w = maxwidths . get ( i , - 1 ) if nse > w : maxwidths [ i ] = nse for row in rows : s = '' for i , e in enumerate ( row ) : se = str ( e ) if i < len ( row ) - 1 : n = maxwidths [ i ] + padding - len ( se ) se += ' ' * n s += se strs . append ( s ) return strs | Print rows of entries in aligned columns . | 148 | 8 |
226,655 | def print_colored_columns ( printer , rows , padding = 2 ) : rows_ = [ x [ : - 1 ] for x in rows ] colors = [ x [ - 1 ] for x in rows ] for col , line in zip ( colors , columnise ( rows_ , padding = padding ) ) : printer ( line , col ) | Like columnise but with colored rows . | 72 | 8 |
226,656 | def expanduser ( path ) : if '~' not in path : return path if os . name == "nt" : if 'HOME' in os . environ : userhome = os . environ [ 'HOME' ] elif 'USERPROFILE' in os . environ : userhome = os . environ [ 'USERPROFILE' ] elif 'HOMEPATH' in os . environ : drive = os . environ . get ( 'HOMEDRIVE' , '' ) userhome = os . path . join ( drive , os . environ [ 'HOMEPATH' ] ) else : return path else : userhome = os . path . expanduser ( '~' ) def _expanduser ( path ) : return EXPANDUSER_RE . sub ( lambda m : m . groups ( ) [ 0 ] + userhome + m . groups ( ) [ 1 ] , path ) # only replace '~' if it's at start of string or is preceeded by pathsep or # ';' or whitespace; AND, is followed either by sep, pathsep, ';', ' ' or # end-of-string. # return os . path . normpath ( _expanduser ( path ) ) | Expand ~ to home directory in the given string . | 269 | 11 |
226,657 | def as_block_string ( txt ) : import json lines = [ ] for line in txt . split ( '\n' ) : line_ = json . dumps ( line ) line_ = line_ [ 1 : - 1 ] . rstrip ( ) # drop double quotes lines . append ( line_ ) return '"""\n%s\n"""' % '\n' . join ( lines ) | Return a string formatted as a python block comment string like the one you re currently reading . Special characters are escaped if necessary . | 88 | 25 |
226,658 | def format ( self , s , pretty = None , expand = None ) : if pretty is None : pretty = self . format_pretty if expand is None : expand = self . format_expand formatter = ObjectStringFormatter ( self , pretty = pretty , expand = expand ) return formatter . format ( s ) | Format a string . | 67 | 4 |
226,659 | def copy ( self ) : other = Version ( None ) other . tokens = self . tokens [ : ] other . seps = self . seps [ : ] return other | Returns a copy of the version . | 36 | 7 |
226,660 | def trim ( self , len_ ) : other = Version ( None ) other . tokens = self . tokens [ : len_ ] other . seps = self . seps [ : len_ - 1 ] return other | Return a copy of the version possibly with less tokens . | 45 | 11 |
226,661 | def union ( self , other ) : if not hasattr ( other , "__iter__" ) : other = [ other ] bounds = self . bounds [ : ] for range in other : bounds += range . bounds bounds = self . _union ( bounds ) range = VersionRange ( None ) range . bounds = bounds return range | OR together version ranges . | 68 | 5 |
226,662 | def intersection ( self , other ) : if not hasattr ( other , "__iter__" ) : other = [ other ] bounds = self . bounds for range in other : bounds = self . _intersection ( bounds , range . bounds ) if not bounds : return None range = VersionRange ( None ) range . bounds = bounds return range | AND together version ranges . | 71 | 5 |
226,663 | def inverse ( self ) : if self . is_any ( ) : return None else : bounds = self . _inverse ( self . bounds ) range = VersionRange ( None ) range . bounds = bounds return range | Calculate the inverse of the range . | 45 | 9 |
226,664 | def split ( self ) : ranges = [ ] for bound in self . bounds : range = VersionRange ( None ) range . bounds = [ bound ] ranges . append ( range ) return ranges | Split into separate contiguous ranges . | 39 | 6 |
226,665 | def as_span ( cls , lower_version = None , upper_version = None , lower_inclusive = True , upper_inclusive = True ) : lower = ( None if lower_version is None else _LowerBound ( lower_version , lower_inclusive ) ) upper = ( None if upper_version is None else _UpperBound ( upper_version , upper_inclusive ) ) bound = _Bound ( lower , upper ) range = cls ( None ) range . bounds = [ bound ] return range | Create a range from lower_version .. upper_version . | 111 | 12 |
226,666 | def from_version ( cls , version , op = None ) : lower = None upper = None if op is None : lower = _LowerBound ( version , True ) upper = _UpperBound ( version . next ( ) , False ) elif op in ( "eq" , "==" ) : lower = _LowerBound ( version , True ) upper = _UpperBound ( version , True ) elif op in ( "gt" , ">" ) : lower = _LowerBound ( version , False ) elif op in ( "gte" , ">=" ) : lower = _LowerBound ( version , True ) elif op in ( "lt" , "<" ) : upper = _UpperBound ( version , False ) elif op in ( "lte" , "<=" ) : upper = _UpperBound ( version , True ) else : raise VersionError ( "Unknown bound operation '%s'" % op ) bound = _Bound ( lower , upper ) range = cls ( None ) range . bounds = [ bound ] return range | Create a range from a version . | 225 | 7 |
226,667 | def from_versions ( cls , versions ) : range = cls ( None ) range . bounds = [ ] for version in dedup ( sorted ( versions ) ) : lower = _LowerBound ( version , True ) upper = _UpperBound ( version , True ) bound = _Bound ( lower , upper ) range . bounds . append ( bound ) return range | Create a range from a list of versions . | 76 | 9 |
226,668 | def to_versions ( self ) : versions = [ ] for bound in self . bounds : if bound . lower . inclusive and bound . upper . inclusive and ( bound . lower . version == bound . upper . version ) : versions . append ( bound . lower . version ) return versions or None | Returns exact version ranges as Version objects or None if there are no exact version ranges present . | 60 | 18 |
226,669 | def contains_version ( self , version ) : if len ( self . bounds ) < 5 : # not worth overhead of binary search for bound in self . bounds : i = bound . version_containment ( version ) if i == 0 : return True if i == - 1 : return False else : _ , contains = self . _contains_version ( version ) return contains return False | Returns True if version is contained in this range . | 80 | 10 |
226,670 | def iter_intersecting ( self , iterable , key = None , descending = False ) : return _ContainsVersionIterator ( self , iterable , key , descending , mode = _ContainsVersionIterator . MODE_INTERSECTING ) | Like iter_intersect_test but returns intersections only . | 53 | 12 |
226,671 | def iter_non_intersecting ( self , iterable , key = None , descending = False ) : return _ContainsVersionIterator ( self , iterable , key , descending , mode = _ContainsVersionIterator . MODE_NON_INTERSECTING ) | Like iter_intersect_test but returns non - intersections only . | 58 | 14 |
226,672 | def span ( self ) : other = VersionRange ( None ) bound = _Bound ( self . bounds [ 0 ] . lower , self . bounds [ - 1 ] . upper ) other . bounds = [ bound ] return other | Return a contiguous range that is a superset of this range . | 46 | 13 |
226,673 | def visit_versions ( self , func ) : for bound in self . bounds : if bound . lower is not _LowerBound . min : result = func ( bound . lower . version ) if isinstance ( result , Version ) : bound . lower . version = result if bound . upper is not _UpperBound . inf : result = func ( bound . upper . version ) if isinstance ( result , Version ) : bound . upper . version = result | Visit each version in the range and apply a function to each . | 94 | 13 |
226,674 | def send ( self , url , data , headers ) : req = urllib2 . Request ( url , headers = headers ) try : response = urlopen ( url = req , data = data , timeout = self . timeout , verify_ssl = self . verify_ssl , ca_certs = self . ca_certs , ) except urllib2 . HTTPError as exc : msg = exc . headers . get ( 'x-sentry-error' ) code = exc . getcode ( ) if code == 429 : try : retry_after = int ( exc . headers . get ( 'retry-after' ) ) except ( ValueError , TypeError ) : retry_after = 0 raise RateLimited ( msg , retry_after ) elif msg : raise APIError ( msg , code ) else : raise return response | Sends a request to a remote webserver using HTTP POST . | 178 | 13 |
226,675 | def extract_auth_vars ( request ) : if request . META . get ( 'HTTP_X_SENTRY_AUTH' , '' ) . startswith ( 'Sentry' ) : return request . META [ 'HTTP_X_SENTRY_AUTH' ] elif request . META . get ( 'HTTP_AUTHORIZATION' , '' ) . startswith ( 'Sentry' ) : return request . META [ 'HTTP_AUTHORIZATION' ] else : # Try to construct from GET request args = [ '%s=%s' % i for i in request . GET . items ( ) if i [ 0 ] . startswith ( 'sentry_' ) and i [ 0 ] != 'sentry_data' ] if args : return 'Sentry %s' % ', ' . join ( args ) return None | raven - js will pass both Authorization and X - Sentry - Auth depending on the browser and server configurations . | 192 | 23 |
226,676 | def _get_value ( self , exc_type , exc_value , exc_traceback ) : stack_info = get_stack_info ( iter_traceback_frames ( exc_traceback ) , transformer = self . transform , capture_locals = self . client . capture_locals , ) exc_module = getattr ( exc_type , '__module__' , None ) if exc_module : exc_module = str ( exc_module ) exc_type = getattr ( exc_type , '__name__' , '<unknown>' ) return { 'value' : to_unicode ( exc_value ) , 'type' : str ( exc_type ) , 'module' : to_unicode ( exc_module ) , 'stacktrace' : stack_info , } | Convert exception info to a value for the values list . | 174 | 12 |
226,677 | def record ( message = None , timestamp = None , level = None , category = None , data = None , type = None , processor = None ) : if timestamp is None : timestamp = time ( ) for ctx in raven . context . get_active_contexts ( ) : ctx . breadcrumbs . record ( timestamp , level , message , category , data , type , processor ) | Records a breadcrumb for all active clients . This is what integration code should use rather than invoking the captureBreadcrumb method on a specific client . | 82 | 33 |
226,678 | def ignore_logger ( name_or_logger , allow_level = None ) : def handler ( logger , level , msg , args , kwargs ) : if allow_level is not None and level >= allow_level : return False return True register_special_log_handler ( name_or_logger , handler ) | Ignores a logger during breadcrumb recording . | 71 | 10 |
226,679 | def transform ( self , value , * * kwargs ) : if value is None : return None objid = id ( value ) if objid in self . context : return '<...>' self . context . add ( objid ) try : for serializer in self . serializers : try : if serializer . can ( value ) : return serializer . serialize ( value , * * kwargs ) except Exception as e : logger . exception ( e ) return text_type ( type ( value ) ) # if all else fails, lets use the repr of the object try : return repr ( value ) except Exception as e : logger . exception ( e ) # It's common case that a model's __unicode__ definition # may try to query the database which if it was not # cleaned up correctly, would hit a transaction aborted # exception return text_type ( type ( value ) ) finally : self . context . remove ( objid ) | Primary function which handles recursively transforming values via their serializers | 199 | 13 |
226,680 | def send ( self , auth_header = None , callback = None , * * data ) : message = self . encode ( data ) return self . send_encoded ( message , auth_header = auth_header , callback = callback ) | Serializes the message and passes the payload onto send_encoded . | 50 | 14 |
226,681 | def _send_remote ( self , url , data , headers = None , callback = None ) : if headers is None : headers = { } return AsyncHTTPClient ( ) . fetch ( url , callback , method = "POST" , body = data , headers = headers , validate_cert = self . validate_cert ) | Initialise a Tornado AsyncClient and send the request to the sentry server . If the callback is a callable it will be called with the response . | 68 | 32 |
226,682 | def get_sentry_data_from_request ( self ) : return { 'request' : { 'url' : self . request . full_url ( ) , 'method' : self . request . method , 'data' : self . request . body , 'query_string' : self . request . query , 'cookies' : self . request . headers . get ( 'Cookie' , None ) , 'headers' : dict ( self . request . headers ) , } } | Extracts the data required for sentry . interfaces . Http from the current request being handled by the request handler | 104 | 24 |
226,683 | def get_public_dsn ( self , scheme = None ) : if self . is_enabled ( ) : url = self . remote . get_public_dsn ( ) if scheme : return '%s:%s' % ( scheme , url ) return url | Returns a public DSN which is consumable by raven - js | 57 | 13 |
226,684 | def capture ( self , event_type , data = None , date = None , time_spent = None , extra = None , stack = None , tags = None , sample_rate = None , * * kwargs ) : if not self . is_enabled ( ) : return exc_info = kwargs . get ( 'exc_info' ) if exc_info is not None : if self . skip_error_for_logging ( exc_info ) : return elif not self . should_capture ( exc_info ) : self . logger . info ( 'Not capturing exception due to filters: %s' , exc_info [ 0 ] , exc_info = sys . exc_info ( ) ) return self . record_exception_seen ( exc_info ) data = self . build_msg ( event_type , data , date , time_spent , extra , stack , tags = tags , * * kwargs ) # should this event be sampled? if sample_rate is None : sample_rate = self . sample_rate if self . _random . random ( ) < sample_rate : self . send ( * * data ) self . _local_state . last_event_id = data [ 'event_id' ] return data [ 'event_id' ] | Captures and processes an event and pipes it off to SentryClient . send . | 278 | 17 |
226,685 | def _log_failed_submission ( self , data ) : message = data . pop ( 'message' , '<no message value>' ) output = [ message ] if 'exception' in data and 'stacktrace' in data [ 'exception' ] [ 'values' ] [ - 1 ] : # try to reconstruct a reasonable version of the exception for frame in data [ 'exception' ] [ 'values' ] [ - 1 ] [ 'stacktrace' ] . get ( 'frames' , [ ] ) : output . append ( ' File "%(fn)s", line %(lineno)s, in %(func)s' % { 'fn' : frame . get ( 'filename' , 'unknown_filename' ) , 'lineno' : frame . get ( 'lineno' , - 1 ) , 'func' : frame . get ( 'function' , 'unknown_function' ) , } ) self . uncaught_logger . error ( output ) | Log a reasonable representation of an event that should have been sent to Sentry | 212 | 15 |
226,686 | def send_encoded ( self , message , auth_header = None , * * kwargs ) : client_string = 'raven-python/%s' % ( raven . VERSION , ) if not auth_header : timestamp = time . time ( ) auth_header = get_auth_header ( protocol = self . protocol_version , timestamp = timestamp , client = client_string , api_key = self . remote . public_key , api_secret = self . remote . secret_key , ) headers = { 'User-Agent' : client_string , 'X-Sentry-Auth' : auth_header , 'Content-Encoding' : self . get_content_encoding ( ) , 'Content-Type' : 'application/octet-stream' , } return self . send_remote ( url = self . remote . store_endpoint , data = message , headers = headers , * * kwargs ) | Given an already serialized message signs the message and passes the payload off to send_remote . | 202 | 19 |
226,687 | def captureQuery ( self , query , params = ( ) , engine = None , * * kwargs ) : return self . capture ( 'raven.events.Query' , query = query , params = params , engine = engine , * * kwargs ) | Creates an event for a SQL query . | 56 | 9 |
226,688 | def captureBreadcrumb ( self , * args , * * kwargs ) : # Note: framework integration should not call this method but # instead use the raven.breadcrumbs.record_breadcrumb function # which will record to the correct client automatically. self . context . breadcrumbs . record ( * args , * * kwargs ) | Records a breadcrumb with the current context . They will be sent with the next event . | 75 | 20 |
226,689 | def register_scheme ( self , scheme , cls ) : if scheme in self . _schemes : raise DuplicateScheme ( ) urlparse . register_scheme ( scheme ) # TODO (vng): verify the interface of the new class self . _schemes [ scheme ] = cls | It is possible to inject new schemes at runtime | 67 | 9 |
226,690 | def get_http_info ( self , request ) : if self . is_json_type ( request . mimetype ) : retriever = self . get_json_data else : retriever = self . get_form_data return self . get_http_info_with_retriever ( request , retriever ) | Determine how to retrieve actual data by using request . mimetype . | 70 | 16 |
226,691 | def setup_logging ( handler , exclude = EXCLUDE_LOGGER_DEFAULTS ) : logger = logging . getLogger ( ) if handler . __class__ in map ( type , logger . handlers ) : return False logger . addHandler ( handler ) # Add StreamHandler to sentry's default so you can catch missed exceptions for logger_name in exclude : logger = logging . getLogger ( logger_name ) logger . propagate = False logger . addHandler ( logging . StreamHandler ( ) ) return True | Configures logging to pipe to Sentry . | 110 | 9 |
226,692 | def to_dict ( dictish ) : if hasattr ( dictish , 'iterkeys' ) : m = dictish . iterkeys elif hasattr ( dictish , 'keys' ) : m = dictish . keys else : raise ValueError ( dictish ) return dict ( ( k , dictish [ k ] ) for k in m ( ) ) | Given something that closely resembles a dictionary we attempt to coerce it into a propery dictionary . | 76 | 19 |
226,693 | def slim_frame_data ( frames , frame_allowance = 25 ) : frames_len = 0 app_frames = [ ] system_frames = [ ] for frame in frames : frames_len += 1 if frame . get ( 'in_app' ) : app_frames . append ( frame ) else : system_frames . append ( frame ) if frames_len <= frame_allowance : return frames remaining = frames_len - frame_allowance app_count = len ( app_frames ) system_allowance = max ( frame_allowance - app_count , 0 ) if system_allowance : half_max = int ( system_allowance / 2 ) # prioritize trimming system frames for frame in system_frames [ half_max : - half_max ] : frame . pop ( 'vars' , None ) frame . pop ( 'pre_context' , None ) frame . pop ( 'post_context' , None ) remaining -= 1 else : for frame in system_frames : frame . pop ( 'vars' , None ) frame . pop ( 'pre_context' , None ) frame . pop ( 'post_context' , None ) remaining -= 1 if remaining : app_allowance = app_count - remaining half_max = int ( app_allowance / 2 ) for frame in app_frames [ half_max : - half_max ] : frame . pop ( 'vars' , None ) frame . pop ( 'pre_context' , None ) frame . pop ( 'post_context' , None ) return frames | Removes various excess metadata from middle frames which go beyond frame_allowance . | 331 | 16 |
226,694 | def get_data_from_request ( ) : return { 'request' : { 'url' : '%s://%s%s' % ( web . ctx [ 'protocol' ] , web . ctx [ 'host' ] , web . ctx [ 'path' ] ) , 'query_string' : web . ctx . query , 'method' : web . ctx . method , 'data' : web . data ( ) , 'headers' : dict ( get_headers ( web . ctx . environ ) ) , 'env' : dict ( get_environ ( web . ctx . environ ) ) , } } | Returns request data extracted from web . ctx . | 142 | 10 |
226,695 | def get_regex ( resolver_or_pattern ) : try : regex = resolver_or_pattern . regex except AttributeError : regex = resolver_or_pattern . pattern . regex return regex | Utility method for django s deprecated resolver . regex | 45 | 12 |
226,696 | def once ( func ) : lock = threading . Lock ( ) def new_func ( * args , * * kwargs ) : if new_func . called : return with lock : if new_func . called : return rv = func ( * args , * * kwargs ) new_func . called = True return rv new_func = update_wrapper ( new_func , func ) new_func . called = False return new_func | Runs a thing once and once only . | 97 | 9 |
226,697 | def get_host ( request ) : # We try three options, in order of decreasing preference. if settings . USE_X_FORWARDED_HOST and ( 'HTTP_X_FORWARDED_HOST' in request . META ) : host = request . META [ 'HTTP_X_FORWARDED_HOST' ] elif 'HTTP_HOST' in request . META : host = request . META [ 'HTTP_HOST' ] else : # Reconstruct the host using the algorithm from PEP 333. host = request . META [ 'SERVER_NAME' ] server_port = str ( request . META [ 'SERVER_PORT' ] ) if server_port != ( request . is_secure ( ) and '443' or '80' ) : host = '%s:%s' % ( host , server_port ) return host | A reimplementation of Django s get_host without the SuspiciousOperation check . | 192 | 16 |
226,698 | def install_middleware ( middleware_name , lookup_names = None ) : if lookup_names is None : lookup_names = ( middleware_name , ) # default settings.MIDDLEWARE is None middleware_attr = 'MIDDLEWARE' if getattr ( settings , 'MIDDLEWARE' , None ) is not None else 'MIDDLEWARE_CLASSES' # make sure to get an empty tuple when attr is None middleware = getattr ( settings , middleware_attr , ( ) ) or ( ) if set ( lookup_names ) . isdisjoint ( set ( middleware ) ) : setattr ( settings , middleware_attr , type ( middleware ) ( ( middleware_name , ) ) + middleware ) | Install specified middleware | 169 | 4 |
226,699 | def _fit_and_score ( est , x , y , scorer , train_index , test_index , parameters , fit_params , predict_params ) : X_train , y_train = _safe_split ( est , x , y , train_index ) train_params = fit_params . copy ( ) # Training est . set_params ( * * parameters ) est . fit ( X_train , y_train , * * train_params ) # Testing test_predict_params = predict_params . copy ( ) X_test , y_test = _safe_split ( est , x , y , test_index , train_index ) score = scorer ( est , X_test , y_test , * * test_predict_params ) if not isinstance ( score , numbers . Number ) : raise ValueError ( "scoring must return a number, got %s (%s) instead." % ( str ( score ) , type ( score ) ) ) return score | Train survival model on given data and return its score on test data | 211 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.