signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def finish_oauth ( self , code ) : """Given an OAuth Exchange Code , completes the OAuth exchange with the authentication server . This should be called once the user has already been directed to the login _ uri , and has been sent back after successfully authenticating . For example , in ` Flask ` _ , this m...
r = requests . post ( self . _login_uri ( "/oauth/token" ) , data = { "code" : code , "client_id" : self . client_id , "client_secret" : self . client_secret } ) if r . status_code != 200 : raise ApiError ( "OAuth token exchange failed" , status = r . status_code , json = r . json ( ) ) token = r . json ( ) [ "acce...
def register ( self , target ) : """Registers a new virtual target . Checks if there ' s already registered target , with the same name , type , project and subvariant properties , and also with the same sources and equal action . If such target is found it is retured and ' target ' is not registered . Otherw...
assert isinstance ( target , VirtualTarget ) if target . path ( ) : signature = target . path ( ) + "-" + target . name ( ) else : signature = "-" + target . name ( ) result = None if signature not in self . cache_ : self . cache_ [ signature ] = [ ] for t in self . cache_ [ signature ] : a1 = t . actio...
def loadDict ( self , theDict ) : """Load the parameter settings from a given dict into the GUI ."""
# We are going to have to merge this info into ourselves so let ' s # first make sure all of our models are up to date with the values in # the GUI right now . badList = self . checkSetSaveEntries ( doSave = False ) if badList : if not self . processBadEntries ( badList , self . taskName ) : return # now , ...
def parse ( msg ) : """Helper method for parsing a Mongrel2 request string and returning a new ` MongrelRequest ` instance ."""
sender , conn_id , path , rest = msg . split ( ' ' , 3 ) headers , rest = tnetstring . pop ( rest ) body , _ = tnetstring . pop ( rest ) if type ( headers ) is str : headers = json . loads ( headers ) return MongrelRequest ( sender , conn_id , path , headers , body )
def plot_species ( statistics , view = False , filename = 'speciation.svg' ) : """Visualizes speciation throughout evolution ."""
if plt is None : warnings . warn ( "This display is not available due to a missing optional dependency (matplotlib)" ) return species_sizes = statistics . get_species_sizes ( ) num_generations = len ( species_sizes ) curves = np . array ( species_sizes ) . T fig , ax = plt . subplots ( ) ax . stackplot ( range ...
def _set_fe_access_check ( self , v , load = False ) : """Setter method for fe _ access _ check , mapped from YANG variable / sysmon / fe _ access _ check ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ fe _ access _ check is considered as a private meth...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = fe_access_check . fe_access_check , is_container = 'container' , presence = False , yang_name = "fe-access-check" , rest_name = "fe-access-check" , parent = self , path_helper = self . _path_helper , extmethods = self . _extm...
def _get_date ( data , position , dummy , opts ) : """Decode a BSON datetime to python datetime . datetime ."""
end = position + 8 millis = _UNPACK_LONG ( data [ position : end ] ) [ 0 ] diff = ( ( millis % 1000 ) + 1000 ) % 1000 seconds = ( millis - diff ) / 1000 micros = diff * 1000 if opts . tz_aware : return EPOCH_AWARE + datetime . timedelta ( seconds = seconds , microseconds = micros ) , end else : return EPOCH_NAI...
def _RunSingleHook ( self , hook_cls , executed_set , required = None ) : """Run the single hook specified by resolving all its prerequisites ."""
# If we already ran do nothing . if hook_cls in executed_set : return # Ensure all the pre execution hooks are run . for pre_hook in hook_cls . pre : self . _RunSingleHook ( pre_hook , executed_set , required = hook_cls . __name__ ) # Now run this hook . cls_instance = hook_cls ( ) if required : logging . d...
def parse_uri ( uri , default_port = DEFAULT_PORT , validate = True , warn = False ) : """Parse and validate a MongoDB URI . Returns a dict of the form : : ' nodelist ' : < list of ( host , port ) tuples > , ' username ' : < username > or None , ' password ' : < password > or None , ' database ' : < datab...
if not uri . startswith ( SCHEME ) : raise InvalidURI ( "Invalid URI scheme: URI " "must begin with '%s'" % ( SCHEME , ) ) scheme_free = uri [ SCHEME_LEN : ] if not scheme_free : raise InvalidURI ( "Must provide at least one hostname or IP." ) user = None passwd = None dbase = None collection = None options = {...
def segment_snrs ( filters , stilde , psd , low_frequency_cutoff ) : """This functions calculates the snr of each bank veto template against the segment Parameters filters : list of FrequencySeries The list of bank veto templates filters . stilde : FrequencySeries The current segment of data . psd : F...
snrs = [ ] norms = [ ] for bank_template in filters : # For every template compute the snr against the stilde segment snr , _ , norm = matched_filter_core ( bank_template , stilde , h_norm = bank_template . sigmasq ( psd ) , psd = None , low_frequency_cutoff = low_frequency_cutoff ) # SNR time series stored her...
def display_db_info ( self ) : """Displays some basic info about the GnuCash book"""
with self . open_book ( ) as book : default_currency = book . default_currency print ( "Default currency is " , default_currency . mnemonic )
def _real_key ( self , key ) : """Return the normalized key to be used for the internal dictionary , from the input key ."""
if key is not None : try : return key . lower ( ) except AttributeError : raise TypeError ( _format ( "NocaseDict key {0!A} must be a string, " "but is {1}" , key , type ( key ) ) ) if self . allow_unnamed_keys : return None raise TypeError ( _format ( "NocaseDict key None (unnamed key) is n...
def pprint_cell ( self , row , col ) : """Formatted contents of table cell . Args : row ( int ) : Integer index of table row col ( int ) : Integer index of table column Returns : Formatted table cell contents"""
ndims = self . ndims if col >= self . cols : raise Exception ( "Maximum column index is %d" % self . cols - 1 ) elif row >= self . rows : raise Exception ( "Maximum row index is %d" % self . rows - 1 ) elif row == 0 : if col >= ndims : if self . vdims : return self . vdims [ col - ndims ...
def validate ( self ) : """Validates whether a configuration is valid . : rtype : bool : raises ConfigurationError : if no ` ` access _ token ` ` provided . : raises ConfigurationError : if provided ` ` access _ token ` ` is invalid - contains disallowed characters . : raises ConfigurationError : if provide...
if self . access_token is None : raise ConfigurationError ( 'No access token provided. ' 'Set your access token during client initialization using: ' '"basecrm.Client(access_token= <YOUR_PERSONAL_ACCESS_TOKEN>)"' ) if re . search ( r'\s' , self . access_token ) : raise ConfigurationError ( 'Provided access toke...
def line_plot ( self , x = 'year' , y = 'value' , ** kwargs ) : """Plot timeseries lines of existing data see pyam . plotting . line _ plot ( ) for all available options"""
df = self . as_pandas ( with_metadata = kwargs ) # pivot data if asked for explicit variable name variables = df [ 'variable' ] . unique ( ) if x in variables or y in variables : keep_vars = set ( [ x , y ] ) & set ( variables ) df = df [ df [ 'variable' ] . isin ( keep_vars ) ] idx = list ( set ( df . colu...
def _send ( self ) : """Send data to statsd . Fire and forget . Cross fingers and it ' ll arrive ."""
if not statsd : return for metric in self . metrics : # Split the path into a prefix and a name # to work with the statsd module ' s view of the world . # It will get re - joined by the python - statsd module . # For the statsd module , you specify prefix in the constructor # so we just use the full metric path . ...
def get_unique_node_by_name ( manager , node_name , node_type ) : """Returns the node if the node is unique for name and type or None . : param manager : Neo4jDBSessionManager : param node _ name : string : param node _ type : str | unicode : return : norduniclient node model or None"""
q = """ MATCH (n:Node { name: {name} }) WHERE {label} IN labels(n) RETURN n.handle_id as handle_id """ with manager . session as s : result = list ( s . run ( q , { 'name' : node_name , 'label' : node_type } ) ) if result : if len ( result ) == 1 : return get_node_model (...
def _resolve_and_add ( nodes1 , s_val , final_s , nodes2 , t_val , final_t ) : """Resolve a computed intersection and add to lists . We perform one Newton step to deal with any residual issues of high - degree polynomial solves ( one of which depends on the already approximate ` ` x _ val , y _ val ` ` ) . ...
s_val , t_val = _intersection_helpers . newton_refine ( s_val , nodes1 , t_val , nodes2 ) s_val , success_s = _helpers . wiggle_interval ( s_val ) t_val , success_t = _helpers . wiggle_interval ( t_val ) if not ( success_s and success_t ) : return final_s . append ( s_val ) final_t . append ( t_val )
def replace_directory ( out_files , dest_dir ) : """change the output directory to dest _ dir can take a string ( single file ) or a list of files"""
if is_sequence ( out_files ) : filenames = map ( os . path . basename , out_files ) return [ os . path . join ( dest_dir , x ) for x in filenames ] elif is_string ( out_files ) : return os . path . join ( dest_dir , os . path . basename ( out_files ) ) else : raise ValueError ( "in_files must either be ...
def _format_multicolumn ( self , row , ilevels ) : r"""Combine columns belonging to a group to a single multicolumn entry according to self . multicolumn _ format e . g . : a & & & b & c & will become \ multicolumn { 3 } { l } { a } & b & \ multicolumn { 2 } { l } { c }"""
row2 = list ( row [ : ilevels ] ) ncol = 1 coltext = '' def append_col ( ) : # write multicolumn if needed if ncol > 1 : row2 . append ( '\\multicolumn{{{ncol:d}}}{{{fmt:s}}}{{{txt:s}}}' . format ( ncol = ncol , fmt = self . multicolumn_format , txt = coltext . strip ( ) ) ) # don ' t modify where not n...
def getPage ( self , path , return_content = True , return_html = True ) : """Use this method to get a Telegraph page . : param path : Required . Path to the Telegraph page ( in the format Title - 12-31 , i . e . everything that comes after http : / / telegra . ph / ) . : type path : str : param return _ co...
if path is None : raise TelegraphAPIException ( "Error while executing getPage: " "PAGE_NOT_FOUND" ) r = requests . post ( BASE_URL + "getPage/" + path , data = { "return_content" : return_content } ) if r . json ( ) [ 'ok' ] is not True : raise TelegraphAPIException ( "Error while executing getPage: " + r . js...
def follow_tail ( self ) : """Read ( tail and follow ) the log file , parse entries and send messages to Sentry using Raven ."""
try : follower = tailhead . follow_path ( self . filepath ) except ( FileNotFoundError , PermissionError ) as err : raise SystemExit ( "Error: Can't read logfile %s (%s)" % ( self . filepath , err ) ) for line in follower : self . message = None self . params = None self . site = None if line is...
def get_includes ( self ) : """Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit . The first object in this sequence is always the input file . Note that this method will not recursively iterate over header files included through precompiled ...
def visitor ( fobj , lptr , depth , includes ) : if depth > 0 : loc = lptr . contents includes . append ( FileInclusion ( loc . file , File ( fobj ) , loc , depth ) ) # Automatically adapt CIndex / ctype pointers to python objects includes = [ ] conf . lib . clang_getInclusions ( self , callbacks [ ...
def get_user ( name , profile = 'github' , user_details = False ) : '''Get a GitHub user by name . name The user for which to obtain information . profile The name of the profile configuration to use . Defaults to ` ` github ` ` . user _ details Prints user information details . Defaults to ` ` False ` ...
if not user_details and name in list_users ( profile ) : # User is in the org , no need for additional Data return True response = { } client = _get_client ( profile ) organization = client . get_organization ( _get_config_value ( profile , 'org_name' ) ) try : user = client . get_user ( name ) except UnknownOb...
def _split_indices ( self , concat_inds ) : """Take indices in ' concatenated space ' and return as pairs of ( traj _ i , frame _ i )"""
clengths = np . append ( [ 0 ] , np . cumsum ( self . __lengths ) ) mapping = np . zeros ( ( clengths [ - 1 ] , 2 ) , dtype = int ) for traj_i , ( start , end ) in enumerate ( zip ( clengths [ : - 1 ] , clengths [ 1 : ] ) ) : mapping [ start : end , 0 ] = traj_i mapping [ start : end , 1 ] = np . arange ( end -...
def register_integration ( package_folder ) : """Register a honeycomb integration . : param package _ folder : Path to folder with integration to load : returns : Validated integration object : rtype : : func : ` honeycomb . utils . defs . Integration `"""
logger . debug ( "registering integration %s" , package_folder ) package_folder = os . path . realpath ( package_folder ) if not os . path . exists ( package_folder ) : raise IntegrationNotFound ( os . path . basename ( package_folder ) ) json_config_path = os . path . join ( package_folder , CONFIG_FILE_NAME ) if ...
def get_identities ( self , item ) : """Return the identities from an item"""
category = item [ 'category' ] item = item [ 'data' ] if category == "issue" : identity_types = [ 'user' , 'assignee' ] elif category == "pull_request" : identity_types = [ 'user' , 'merged_by' ] else : identity_types = [ ] for identity in identity_types : if item [ identity ] : # In user _ data we have...
def parse_content ( self , content ) : """Called automatically to process the directory listing ( s ) contained in the content ."""
self . listings = ls_parser . parse ( content , self . first_path ) # No longer need the first path found , if any . delattr ( self , 'first_path' )
async def _drain_writer ( self , timeout : NumType = None ) -> None : """Wraps writer . drain ( ) with error handling ."""
if self . _stream_writer is None : raise SMTPServerDisconnected ( "Client not connected" ) # Wrapping drain in a task makes mypy happy drain_task = asyncio . Task ( self . _stream_writer . drain ( ) , loop = self . _loop ) try : await asyncio . wait_for ( drain_task , timeout , loop = self . _loop ) except Conn...
def _int2farray ( ftype , num , length = None ) : """Convert a signed integer to an farray ."""
if num < 0 : req_length = clog2 ( abs ( num ) ) + 1 objs = _uint2objs ( ftype , 2 ** req_length + num ) else : req_length = clog2 ( num + 1 ) + 1 objs = _uint2objs ( ftype , num , req_length ) if length : if length < req_length : fstr = "overflow: num = {} requires length >= {}, got length =...
def on_touch_down ( self , touch ) : """If I ' m the first card to collide this touch , grab it , store my metadata in its userdict , and store the relative coords upon me where the collision happened ."""
if not self . collide_point ( * touch . pos ) : return if 'card' in touch . ud : return touch . grab ( self ) self . dragging = True touch . ud [ 'card' ] = self touch . ud [ 'idx' ] = self . idx touch . ud [ 'deck' ] = self . deck touch . ud [ 'layout' ] = self . parent self . collide_x = touch . x - self . x ...
def map ( self , mapper ) : """Map categories using input correspondence ( dict , Series , or function ) . Maps the categories to new categories . If the mapping correspondence is one - to - one the result is a : class : ` ~ pandas . Categorical ` which has the same order property as the original , otherwise ...
new_categories = self . categories . map ( mapper ) try : return self . from_codes ( self . _codes . copy ( ) , categories = new_categories , ordered = self . ordered ) except ValueError : # NA values are represented in self . _ codes with - 1 # np . take causes NA values to take final element in new _ categories ...
def read_packet ( self , size = MTU ) : """Read blocks until it reaches either EOF or a packet , and returns None or ( packet , ( linktype , sec , usec , wirelen ) ) , where packet is a string ."""
while True : try : blocktype , blocklen = struct . unpack ( self . endian + "2I" , self . f . read ( 8 ) ) except struct . error : return None block = self . f . read ( blocklen - 12 ) if blocklen % 4 : pad = self . f . read ( 4 - ( blocklen % 4 ) ) warning ( "PcapNg: bad...
def _private_notes_595 ( self , key , value ) : """Populate the ` ` _ private _ notes ` ` key ."""
return [ { 'source' : value . get ( '9' ) , 'value' : _private_note , } for _private_note in force_list ( value . get ( 'a' ) ) ]
def level_names ( self ) : """Return MultiIndex level names or None if this IndexVariable has no MultiIndex ."""
index = self . to_index ( ) if isinstance ( index , pd . MultiIndex ) : return index . names else : return None
def place_instruction ( order_type , selection_id , side , handicap = None , limit_order = None , limit_on_close_order = None , market_on_close_order = None , customer_order_ref = None ) : """Create order instructions to place an order at exchange . : param str order _ type : define type of order to place . : p...
args = locals ( ) return { to_camel_case ( k ) : v for k , v in args . items ( ) if v is not None }
def sphinx_class ( self ) : """Redefine sphinx class so documentation links to instance _ class"""
classdoc = ':class:`{cls} <{pref}.{cls}>`' . format ( cls = self . instance_class . __name__ , pref = self . instance_class . __module__ , ) return classdoc
def max_num_reads ( self , ** params ) : """Returns the maximum number of reads for the given solver parameters . Args : * * params : Parameters for the sampling method . Relevant to num _ reads : - annealing _ time - readout _ thermalization - num _ reads - programming _ thermalization Returns : ...
# dev note : in the future it would be good to have a way of doing this # server - side , as we are duplicating logic here . properties = self . properties if self . software or not params : # software solvers don ' t use any of the above parameters return properties [ 'num_reads_range' ] [ 1 ] # qpu _ , duration =...
def get_versions ( verbose = False ) : """Get the project version from whatever source is available . Returns dict with two keys : ' version ' and ' full ' ."""
if "versioneer" in sys . modules : # see the discussion in cmdclass . py : get _ cmdclass ( ) del sys . modules [ "versioneer" ] root = get_root ( ) cfg = get_config_from_root ( root ) assert cfg . VCS is not None , "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS . get ( cfg . VCS ) assert handlers ,...
def get_parallel_bucket ( buckets : List [ Tuple [ int , int ] ] , length_source : int , length_target : int ) -> Tuple [ Optional [ int ] , Optional [ Tuple [ int , int ] ] ] : """Returns bucket index and bucket from a list of buckets , given source and target length . Algorithm assumes buckets are sorted from s...
for j , ( source_bkt , target_bkt ) in enumerate ( buckets ) : if source_bkt >= length_source and target_bkt >= length_target : return j , ( source_bkt , target_bkt ) return None , None
def matrix_representation ( op ) : """Return a matrix representation of a linear operator . Parameters op : ` Operator ` The linear operator of which one wants a matrix representation . If the domain or range is a ` ProductSpace ` , it must be a power - space . Returns matrix : ` numpy . ndarray ` The...
if not op . is_linear : raise ValueError ( 'the operator is not linear' ) if not ( isinstance ( op . domain , TensorSpace ) or ( isinstance ( op . domain , ProductSpace ) and op . domain . is_power_space and all ( isinstance ( spc , TensorSpace ) for spc in op . domain ) ) ) : raise TypeError ( 'operator domain...
def stop ( self ) : '''Stop server'''
self . app = None if self . run_thread : self . run_thread = None if self . server : self . server . shutdown ( ) self . server = None
def check_cell_methods ( self , ds ) : """7.3 To describe the characteristic of a field that is represented by cell values , we define the cell _ methods attribute of the variable . This is a string attribute comprising a list of blank - separated words of the form " name : method " . Each " name : method " pai...
methods = { "point" , "sum" , "mean" , "maximum" , "minimum" , "mid_range" , "standard_deviation" , "variance" , "mode" , "median" } ret_val = [ ] psep = regex . compile ( r'(?P<vars>\w+: )+(?P<method>\w+) ?(?P<where>where (?P<wtypevar>\w+) ' r'?(?P<over>over (?P<otypevar>\w+))?| ?)(?:\((?P<paren_contents>[^)]*)\))?' )...
def parse ( self , limit = None ) : """MPD data is delivered in four separate csv files and one xml file , which we process iteratively and write out as one large graph . : param limit : : return :"""
if limit is not None : LOG . info ( "Only parsing first %s rows fo each file" , str ( limit ) ) LOG . info ( "Parsing files..." ) self . _process_straininfo ( limit ) # the following will provide us the hash - lookups # These must be processed in a specific order # mapping between assays and ontology terms self . _...
def _collapse_addresses_internal ( addresses ) : """Loops through the addresses , collapsing concurrent netblocks . Example : ip1 = IPv4Network ( ' 192.0.2.0/26 ' ) ip2 = IPv4Network ( ' 192.0.2.64/26 ' ) ip3 = IPv4Network ( ' 192.0.2.128/26 ' ) ip4 = IPv4Network ( ' 192.0.2.192/26 ' ) _ collapse _ addr...
# First merge to_merge = list ( addresses ) subnets = { } while to_merge : net = to_merge . pop ( ) supernet = net . supernet ( ) existing = subnets . get ( supernet ) if existing is None : subnets [ supernet ] = net elif existing != net : # Merge consecutive subnets del subnets [ su...
def copy ( self ) : """Copies the current Map into a new one and returns it ."""
m = Map ( features = self . _features , width = self . _width , height = self . _height , ** self . _attrs ) m . _folium_map = self . _folium_map return m
def bad_signatures ( self ) : # pragma : no cover """A generator yielding namedtuples of all signatures that were not verified in the operation that returned this instance . The namedtuple has the following attributes : ` ` sigsubj . verified ` ` - ` ` bool ` ` of whether the signature verified successfully or ...
for s in [ i for i in self . _subjects if not i . verified ] : yield s
def humanize_size ( size ) : """Create a nice human readable representation of the given number ( understood as bytes ) using the " KiB " and " MiB " suffixes to indicate kibibytes and mebibytes . A kibibyte is defined as 1024 bytes ( as opposed to a kilobyte which is 1000 bytes ) and a mibibyte is 1024 * * 2...
for factor , format_string in ( ( 1 , '%i' ) , ( 1024 , '%iKiB' ) , ( 1024 * 1024 , '%.1fMiB' ) ) : if size / factor < 1024 : return format_string % ( size / factor ) return format_string % ( size / factor )
def install ( self , pip_args = None ) : """Install the program and put links in place ."""
if path . isdir ( self . env ) : print_pretty ( "<FG_RED>This seems to already be installed.<END>" ) else : print_pretty ( "<FG_BLUE>Creating environment {}...<END>\n" . format ( self . env ) ) self . create_env ( ) self . install_program ( pip_args ) self . create_links ( )
def do_notebook ( self , name ) : """Run a notebook file after optionally converting it to a python file ."""
CONVERT_NOTEBOOKS = int ( os . getenv ( 'CONVERT_NOTEBOOKS' , True ) ) s = StringIO ( ) if mock : out = unittest . mock . patch ( 'sys.stdout' , new = MockDevice ( s ) ) err = unittest . mock . patch ( 'sys.stderr' , new = MockDevice ( s ) ) self . _do_notebook ( name , CONVERT_NOTEBOOKS ) out . close (...
def get_context_data ( self , ** kwargs ) : """Include the name of the sub menu template in the context . This is purely for backwards compatibility . Any sub menus rendered as part of this menu will call ` sub _ menu _ template ` on the original menu instance to get an actual ` Template `"""
data = { } if self . _contextual_vals . current_level == 1 and self . max_levels > 1 : data [ 'sub_menu_template' ] = self . sub_menu_template . template . name data . update ( kwargs ) return super ( ) . get_context_data ( ** data )
def get_question_text ( constant ) : """Find a constant by name and return its value . : param constant : The name of the constant to look for . : type constant : string : returns : The value of the constant or red error message . : rtype : string"""
if constant in dir ( safe . gui . tools . wizard . wizard_strings ) : return getattr ( safe . gui . tools . wizard . wizard_strings , constant ) else : return '<b>MISSING CONSTANT: %s</b>' % constant
def inq ( pt , page = None , alloc = 74 ) : """Create an Inquiry command , send it , and parse the results . Input : pt : ScsiPT object page : vital product page number or None alloc : size to allocate for result TODO : implement page"""
cmd = Cmd ( "inq" , { "evpd" : 0 , "alloc" : alloc } ) cdb = CDB ( cmd . cdb ) cdb . set_data_in ( alloc ) pt . sendcdb ( cdb ) inq = Cmd . extract ( cdb . buf , Cmd . data_inquiry ) return inq
def get_map ( name , map_type , number , reverse = False ) : """Return a ` BrewerMap ` representation of the specified color map . Parameters name : str Name of color map . Use ` print _ maps ` to see available color maps . map _ type : { ' Sequential ' , ' Diverging ' , ' Qualitative ' } Select color map...
number = str ( number ) map_type = map_type . lower ( ) . capitalize ( ) # check for valid type if map_type not in MAP_TYPES : s = 'Invalid map type, must be one of {0}' . format ( MAP_TYPES ) raise ValueError ( s ) # make a dict of lower case map name to map name so this can be # insensitive to case . # this w...
def organize_dir ( orig_dir ) : '''scans through the given directory and organizes DICOMs that look similar into subdirectories output directory is the ` ` orig _ dir ` ` with ` ` - sorted ` ` appended to the end'''
tags = [ ( 0x10 , 0x20 ) , # Subj ID ( 0x8 , 0x21 ) , # Date ( 0x8 , 0x31 ) , # Time ( 0x8 , 0x103e ) # Descr ] orig_dir = orig_dir . rstrip ( '/' ) files = scan_dir ( orig_dir , tags = tags , md5_hash = True ) dups = find_dups ( files ) for dup in dups : nl . notify ( 'Found duplicates of %s...' % dup [ 0 ] ) ...
def send_dict ( * args , ** kwargs ) : """Make sure that we have an instance of the GraphiteClient . Then send the metrics to the graphite server . User consumable method ."""
if not _module_instance : raise GraphiteSendException ( "Must call graphitesend.init() before sending" ) _module_instance . send_dict ( * args , ** kwargs ) return _module_instance
def _handle_tag_close_close ( self ) : """Handle the ending of a closing tag ( ` ` < / foo > ` ` ) ."""
strip = lambda tok : tok . text . rstrip ( ) . lower ( ) closing = self . _pop ( ) if len ( closing ) != 1 or ( not isinstance ( closing [ 0 ] , tokens . Text ) or strip ( closing [ 0 ] ) != strip ( self . _stack [ 1 ] ) ) : self . _fail_route ( ) self . _emit_all ( closing ) self . _emit ( tokens . TagCloseClose (...
def remove_file_ident_desc_by_name ( self , name , logical_block_size ) : # type : ( bytes , int ) - > int '''A method to remove a UDF File Identifier Descriptor from this UDF File Entry . Parameters : name - The name of the UDF File Identifier Descriptor to remove . logical _ block _ size - The logical blo...
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'UDF File Entry not initialized' ) tmp_fi_desc = UDFFileIdentifierDescriptor ( ) tmp_fi_desc . isparent = False tmp_fi_desc . fi = name # If flags bit 3 is set , the entries are sorted . desc_index = len ( self . fi_descs ) for index , fi_...
def parse ( cls , command , argv ) : """Splits an argument list into an options dictionary and a fieldname list . The argument list , ` argv ` , must be of the form : : * [ option ] . . . * [ < field - name > ] Options are validated and assigned to items in ` command . options ` . Field names are validated ...
debug = environment . splunklib_logger . debug command_class = type ( command ) . __name__ # Prepare debug ( 'Parsing %s command line: %r' , command_class , argv ) command . fieldnames = None command . options . reset ( ) argv = ' ' . join ( argv ) command_args = cls . _arguments_re . match ( argv ) if command_args is ...
def from_httplib ( cls , message ) : # Python 2 """Read headers from a Python 2 httplib message object ."""
# python2.7 does not expose a proper API for exporting multiheaders # efficiently . This function re - reads raw lines from the message # object and extracts the multiheaders properly . obs_fold_continued_leaders = ( ' ' , '\t' ) headers = [ ] for line in message . headers : if line . startswith ( obs_fold_continue...
def walkfiles ( self , pattern = None , errors = 'strict' ) : """D . walkfiles ( ) - > iterator over files in D , recursively . The optional argument ` pattern ` limits the results to files with names that match the pattern . For example , ` ` mydir . walkfiles ( ' * . tmp ' ) ` ` yields only files with the `...
if errors not in ( 'strict' , 'warn' , 'ignore' ) : raise ValueError ( "invalid errors parameter" ) try : childList = self . listdir ( ) except Exception : if errors == 'ignore' : return elif errors == 'warn' : warnings . warn ( "Unable to list directory '%s': %s" % ( self , sys . exc_in...
def _get_parsing_plan_for_multifile_children ( self , obj_on_fs : PersistedObject , desired_type : Type [ Any ] , logger : Logger ) -> Dict [ str , Any ] : """Simply inspects the required type to find the names and types of its constructor arguments . Then relies on the inner ParserFinder to parse each of them . ...
if is_collection ( desired_type , strict = True ) : # if the destination type is ' strictly a collection ' ( not a subclass of a collection ) we know that we can ' t # handle it here , the constructor is not pep484 - typed raise TypeError ( 'Desired object type \'' + get_pretty_type_str ( desired_type ) + '\' is a ...
def delete_model ( client , model_id ) : """Sample ID : go / samples - tracker / 1534"""
# [ START bigquery _ delete _ model ] from google . cloud import bigquery # TODO ( developer ) : Construct a BigQuery client object . # client = bigquery . Client ( ) # TODO ( developer ) : Set model _ id to the ID of the model to fetch . # model _ id = ' your - project . your _ dataset . your _ model ' client . delete...
def add_portal ( self , origin , destination , symmetrical = False , ** kwargs ) : """Connect the origin to the destination with a : class : ` Portal ` . Keyword arguments are the : class : ` Portal ` ' s attributes . Exception : if keyword ` ` symmetrical ` ` = = ` ` True ` ` , a mirror - : class : ` Portal ...
if isinstance ( origin , Node ) : origin = origin . name if isinstance ( destination , Node ) : destination = destination . name super ( ) . add_edge ( origin , destination , ** kwargs ) if symmetrical : self . add_portal ( destination , origin , is_mirror = True )
def _list_fonts ( ) : """List system fonts"""
stdout_ , stderr = run_subprocess ( [ 'fc-list' , ':scalable=true' , 'family' ] ) vals = [ v . split ( ',' ) [ 0 ] for v in stdout_ . strip ( ) . splitlines ( False ) ] return vals
def __find_prime_in_row ( self , row ) : """Find the first prime element in the specified row . Returns the column index , or - 1 if no starred element was found ."""
col = - 1 for j in range ( self . n ) : if self . marked [ row ] [ j ] == 2 : col = j break return col
def build_frontend ( self , frontend_node ) : """parse ` frontend ` sections , and return a config . Frontend Args : frontend _ node ( TreeNode ) : Description Raises : Exception : Description Returns : config . Frontend : an object"""
proxy_name = frontend_node . frontend_header . proxy_name . text service_address_node = frontend_node . frontend_header . service_address # parse the config block config_block_lines = self . __build_config_block ( frontend_node . config_block ) # parse host and port host , port = '' , '' if isinstance ( service_address...
def rank_environment_and_phenotypes ( environment , phenotypes , k = 15 ) : """Clusters sets of resources / tasks using a weighted hamming distance such that you can have few enough values to give each group of similar things a different color . This function is designed for cases when you want to color both ...
environment = convert_world_to_phenotype ( environment ) ranks = get_ranks_for_environment_and_phenotypes ( environment , phenotypes ) environment , n = assign_ranks_by_cluster ( environment , k , ranks ) phenotypes , n = assign_ranks_by_cluster ( phenotypes , k , ranks ) return environment , phenotypes , n
def diff_identifiers ( a , b ) : """Return list of tuples where identifiers in datasets differ . Tuple structure : ( identifier , present in a , present in b ) : param a : first : class : ` dtoolcore . DataSet ` : param b : second : class : ` dtoolcore . DataSet ` : returns : list of tuples where identifi...
a_ids = set ( a . identifiers ) b_ids = set ( b . identifiers ) difference = [ ] for i in a_ids . difference ( b_ids ) : difference . append ( ( i , True , False ) ) for i in b_ids . difference ( a_ids ) : difference . append ( ( i , False , True ) ) return difference
def load_healthchecks ( self ) : """Loads healthchecks ."""
self . load_default_healthchecks ( ) if getattr ( settings , 'AUTODISCOVER_HEALTHCHECKS' , True ) : self . autodiscover_healthchecks ( ) self . _registry_loaded = True
def get_class ( class_string ) : """Get a class from a dotted string"""
split_string = class_string . encode ( 'ascii' ) . split ( '.' ) import_path = '.' . join ( split_string [ : - 1 ] ) class_name = split_string [ - 1 ] if class_name : try : if import_path : mod = __import__ ( import_path , globals ( ) , { } , [ class_name ] ) cls = getattr ( mod , cl...
def _clear ( self ) -> None : """Resets the internal state of the simulator , and sets the simulated clock back to 0.0 . This discards all outstanding events and tears down hanging process instances ."""
for _ , event , _ , _ in self . events ( ) : if hasattr ( event , "__self__" ) and isinstance ( event . __self__ , Process ) : # type : ignore event . __self__ . throw ( ) # type : ignore self . _events . clear ( ) self . _ts_now = 0.0
def validate_minimal_contract_factory_data ( contract_data : Dict [ str , str ] ) -> None : """Validate that contract data in a package contains at least an " abi " and " deployment _ bytecode " necessary to generate a deployable contract factory ."""
if not all ( key in contract_data . keys ( ) for key in ( "abi" , "deployment_bytecode" ) ) : raise InsufficientAssetsError ( "Minimum required contract data to generate a deployable " "contract factory (abi & deployment_bytecode) not found." )
def write_PIA0_A_data ( self , cpu_cycles , op_address , address , value ) : """write to 0xff00 - > PIA 0 A side Data reg ."""
log . error ( "%04x| write $%02x (%s) to $%04x -> PIA 0 A side Data reg.\t|%s" , op_address , value , byte2bit_string ( value ) , address , self . cfg . mem_info . get_shortest ( op_address ) ) self . pia_0_A_register . set ( value )
def remove ( self , path , dir_fd = None ) : """Remove the FakeFile object at the specified file path . Args : path : Path to file to be removed . dir _ fd : If not ` None ` , the file descriptor of a directory , with ` path ` being relative to this directory . New in Python 3.3. Raises : OSError : if...
path = self . _path_with_dir_fd ( path , self . remove , dir_fd ) self . filesystem . remove ( path )
def createBinaryRelation ( self , m ) : """Initialize a two - dimensional array of size m by m . : ivar int m : A value for m ."""
binaryRelation = [ ] for i in range ( m ) : binaryRelation . append ( range ( m ) ) binaryRelation [ i ] [ i ] = 0 return binaryRelation
def run ( files , temp_folder ) : "Check frosted errors in the code base ."
try : import frosted # NOQA except ImportError : return NO_FROSTED_MSG py_files = filter_python_files ( files ) cmd = 'frosted {0}' . format ( ' ' . join ( py_files ) ) return bash ( cmd ) . value ( )
def set_interval ( self , start , end , value , compact = False ) : """Set the value for the time series on an interval . If compact is True , only set the value if it ' s different from what it would be anyway ."""
# for each interval to render for i , ( s , e , v ) in enumerate ( self . iterperiods ( start , end ) ) : # look at all intervals included in the current interval # ( always at least 1) if i == 0 : # if the first , set initial value to new value of range self . set ( s , value , compact ) else : # other...
def parse_function_names ( sourcecode , top_level = True , ignore_condition = 1 ) : """Finds all function names in a file without importing it Args : sourcecode ( str ) : Returns : list : func _ names CommandLine : python - m utool . util _ inspect parse _ function _ names Example : > > > # ENABLE _...
import ast import utool as ut func_names = [ ] if six . PY2 : sourcecode = ut . ensure_unicode ( sourcecode ) encoded = sourcecode . encode ( 'utf8' ) pt = ast . parse ( encoded ) else : pt = ast . parse ( sourcecode ) class FuncVisitor ( ast . NodeVisitor ) : def __init__ ( self ) : super (...
def reduce_l1 ( attrs , inputs , proto_obj ) : """Reduce input tensor by l1 normalization ."""
new_attrs = translation_utils . _fix_attribute_names ( attrs , { 'axes' : 'axis' } ) new_attrs = translation_utils . _add_extra_attributes ( new_attrs , { 'ord' : 1 } ) return 'norm' , new_attrs , inputs
def get_and_check_tasks_for ( context , task , msg_prefix = '' ) : """Given a parent task , return the reason the parent task was spawned . ` ` . taskcluster . yml ` ` uses this to know whether to spawn an action , cron , or decision task definition . ` ` tasks _ for ` ` must be a valid one defined in the conte...
tasks_for = task [ 'extra' ] [ 'tasks_for' ] if tasks_for not in context . config [ 'valid_tasks_for' ] : raise ValueError ( '{}Unknown tasks_for: {}' . format ( msg_prefix , tasks_for ) ) return tasks_for
def make_eps ( asset_array , num_samples , seed , correlation ) : """: param asset _ array : an array of assets : param int num _ samples : the number of ruptures : param int seed : a random seed : param float correlation : the correlation coefficient : returns : epsilons matrix of shape ( num _ assets , nu...
assets_by_taxo = group_array ( asset_array , 'taxonomy' ) eps = numpy . zeros ( ( len ( asset_array ) , num_samples ) , numpy . float32 ) for taxonomy , assets in assets_by_taxo . items ( ) : shape = ( len ( assets ) , num_samples ) logging . info ( 'Building %s epsilons for taxonomy %s' , shape , taxonomy ) ...
def completed_count ( self ) : """Returns the total number of jobs that have been completed . Actors that don ' t store results are not counted , meaning this may be inaccurate if all or some of your actors don ' t store results . Raises : RuntimeError : If your broker doesn ' t have a result backend se...
for count , message in enumerate ( self . messages , start = 1 ) : try : message . get_result ( ) except ResultMissing : return count - 1 return count
def user_is_superadmin ( self , username = None ) : """: param username : the username . If None , the username of the currently logged in user is taken : return : True if the user is superadmin , False else"""
if username is None : username = self . session_username ( ) return username in self . _superadmins
def clip_grad ( learn : Learner , clip : float = 0.1 ) -> Learner : "Add gradient clipping of ` clip ` during training ."
learn . callback_fns . append ( partial ( GradientClipping , clip = clip ) ) return learn
def obstory_metadata_generator ( self , sql , sql_args ) : """Generator for : class : ` meteorpi _ model . CameraStatus ` : param sql : A SQL statement which must return rows describing obstory metadata : param sql _ args : Any arguments required to populate the query provided in ' sql ' : return : A ge...
self . con . execute ( sql , sql_args ) results = self . con . fetchall ( ) output = [ ] for result in results : value = "" if ( 'floatValue' in result ) and ( result [ 'floatValue' ] is not None ) : value = result [ 'floatValue' ] if ( 'stringValue' in result ) and ( result [ 'stringValue' ] is not...
def get_image_name ( self , repo_path : Path , requirements_option : RequirementsOptions , dependencies : Optional [ List [ str ] ] ) -> str : """Returns the name for images with installed requirements and dependencies ."""
if self . inherit_image is None : return self . get_arca_base_name ( ) else : name , tag = str ( self . inherit_image ) . split ( ":" ) return f"arca_{name}_{tag}"
def CheckEmail ( self , email , checkTypo = False ) : '''Checks a Single email if it is correct'''
contents = email . split ( '@' ) if len ( contents ) == 2 : if contents [ 1 ] in self . valid : return True return False
def autocov ( x ) : """Compute autocovariance estimates for every lag for the input array . Args : x ( array - like ) : An array containing MCMC samples . Returns : np . ndarray : An array of the same size as the input array ."""
acorr = autocorr ( x ) varx = np . var ( x , ddof = 1 ) * ( len ( x ) - 1 ) / len ( x ) acov = acorr * varx return acov
def run_mapper ( self , stdin = sys . stdin , stdout = sys . stdout ) : """Run the mapper on the hadoop node ."""
self . init_hadoop ( ) self . init_mapper ( ) outputs = self . _map_input ( ( line [ : - 1 ] for line in stdin ) ) if self . reducer == NotImplemented : self . writer ( outputs , stdout ) else : self . internal_writer ( outputs , stdout )
def reset ( self ) : """Reset the internal buffers for the abstract canvas ."""
# Reset our screen buffer self . _start_line = 0 self . _x = self . _y = None self . _buffer = _DoubleBuffer ( self . _buffer_height , self . width ) self . _reset ( )
def _ods2code ( self ) : """Updates code in code _ array"""
ods = ODSReader ( self . ods_file , clonespannedcolumns = True ) tables = ods . sheets for tab_id , table in enumerate ( tables ) : for row_id in xrange ( len ( table ) ) : for col_id in xrange ( len ( table [ row_id ] ) ) : key = row_id , col_id , tab_id text = unicode ( table [ row...
def _ReadCsvDict ( self , file_name , cols , required , deprecated ) : """Reads lines from file _ name , yielding a dict of unicode values ."""
assert file_name . endswith ( ".txt" ) table_name = file_name [ 0 : - 4 ] contents = self . _GetUtf8Contents ( file_name ) if not contents : return eol_checker = util . EndOfLineChecker ( StringIO . StringIO ( contents ) , file_name , self . _problems ) # The csv module doesn ' t provide a way to skip trailing spac...
def print_saveframe ( self , sf , f = sys . stdout , file_format = "nmrstar" , tw = 3 ) : """Print saveframe into a file or stdout . We need to keep track of how far over everything is tabbed . The " tab width " variable tw does this for us . : param str sf : Saveframe name . : param io . StringIO f : writa...
if file_format == "nmrstar" : for sftag in self [ sf ] . keys ( ) : # handle loops if sftag [ : 5 ] == "loop_" : print ( u"\n{}loop_" . format ( tw * u" " ) , file = f ) self . print_loop ( sf , sftag , f , file_format , tw * 2 ) print ( u"\n{}stop_" . format ( tw * u" " ...
def smooth_hue_palette ( scale ) : """Takes an array of ints and returns a corresponding colored rgb array ."""
# http : / / en . wikipedia . org / wiki / HSL _ and _ HSV # From _ HSL # Based on http : / / stackoverflow . com / a / 17382854 , with simplifications and # optimizations . Assumes S = 1 , L = 0.5 , meaning C = 1 and m = 0. # 0 stays black , everything else moves into a hue . # Some initial values and scaling . Check ...
def query_region ( self , chrom = None , start = None , stop = None ) : """Query the table , returning row or rows within the given genomic region . Parameters chrom : string , optional Chromosome / contig . start : int , optional Region start position ( 1 - based ) . stop : int , optional Region st...
if self . index is None : raise ValueError ( 'no index has been set' ) if isinstance ( self . index , SortedIndex ) : # ignore chrom loc = self . index . locate_range ( start , stop ) else : loc = self . index . locate_range ( chrom , start , stop ) return self [ loc ]
def get ( self , id ) : """根据 id 获取数据 。 : param id : 要获取的数据的 id : return : 返回取到的数据 , 如果是空则返回一个空的 ` ` dict ` ` 对象"""
document = self . _get_document ( id ) if document : session_json = document [ "session" ] return json_loads ( session_json ) return { }
def count ( self , axis = 'major' ) : """Return number of observations over requested axis . Parameters axis : { ' items ' , ' major ' , ' minor ' } or { 0 , 1 , 2} Returns count : DataFrame"""
i = self . _get_axis_number ( axis ) values = self . values mask = np . isfinite ( values ) result = mask . sum ( axis = i , dtype = 'int64' ) return self . _wrap_result ( result , axis )
def find_company ( cmp_id = None , cmp_name = None ) : """find the company according company id ( prioritary ) or company name : param cmp _ id : the company id : param cmp _ name : the company name : return : found company or None if not found"""
LOGGER . debug ( "CompanyService.find_company" ) if ( cmp_id is None or not cmp_id ) and ( cmp_name is None or not cmp_name ) : raise exceptions . ArianeCallParametersError ( 'id and name' ) if ( cmp_id is not None and cmp_id ) and ( cmp_name is not None and cmp_name ) : LOGGER . warn ( 'CompanyService.find_com...
def check_addresses ( address_list , is_remote = False ) : """Check if the format of the addresses is correct Arguments : address _ list ( list [ tuple ] ) : Sequence of ( ` ` str ` ` , ` ` int ` ` ) pairs , each representing an IP address and port respectively . . note : : when supported by the platfor...
assert all ( isinstance ( x , ( tuple , string_types ) ) for x in address_list ) if ( is_remote and any ( isinstance ( x , string_types ) for x in address_list ) ) : raise AssertionError ( 'UNIX domain sockets not allowed for remote' 'addresses' ) for address in address_list : check_address ( address )