signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def save_method_args ( method ) : """Wrap a method such that when it is called , the args and kwargs are saved on the method . > > > class MyClass : . . . @ save _ method _ args . . . def method ( self , a , b ) : . . . print ( a , b ) > > > my _ ob = MyClass ( ) > > > my _ ob . method ( 1 , 2) 1 2 ...
args_and_kwargs = collections . namedtuple ( 'args_and_kwargs' , 'args kwargs' ) @ functools . wraps ( method ) def wrapper ( self , * args , ** kwargs ) : attr_name = '_saved_' + method . __name__ attr = args_and_kwargs ( args , kwargs ) setattr ( self , attr_name , attr ) return method ( self , * args...
def add_task_group ( self , task_group , project ) : """AddTaskGroup . [ Preview API ] Create a task group . : param : class : ` < TaskGroupCreateParameter > < azure . devops . v5_0 . task _ agent . models . TaskGroupCreateParameter > ` task _ group : Task group object to create . : param str project : Projec...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) content = self . _serialize . body ( task_group , 'TaskGroupCreateParameter' ) response = self . _send ( http_method = 'POST' , location_id = '6c08ffbf-dbf1-4f9a-94e5-a1cbd47005e7' , vers...
def debug_reduce ( self , rule , tokens , parent , i ) : """Customized format and print for our kind of tokens which gets called in debugging grammar reduce rules"""
prefix = ' ' if parent and tokens : p_token = tokens [ parent ] if hasattr ( p_token , 'line' ) : prefix = 'L.%3d.%03d: ' % ( p_token . line , p_token . column ) pass pass print ( "%s%s ::= %s" % ( prefix , rule [ 0 ] , ' ' . join ( rule [ 1 ] ) ) )
def write ( self , source = None , ** kwargs ) : '''Wrappe r to call the writer ' s write method if present . Args : source ( pandasdmx . model . Message , iterable ) : stuff to be written . If a : class : ` pandasdmx . model . Message ` is given , the writer itself must determine what to write unless speci...
if not source : source = self . msg return self . _writer . write ( source = source , ** kwargs )
def start ( config , args ) : """Start Glances ."""
# Load mode global mode if core . is_standalone ( ) : from glances . standalone import GlancesStandalone as GlancesMode elif core . is_client ( ) : if core . is_client_browser ( ) : from glances . client_browser import GlancesClientBrowser as GlancesMode else : from glances . client import G...
def _set_config_keystone ( self , username , password ) : """Set config to Keystone"""
self . _keystone_auth = KeystoneAuth ( settings . KEYSTONE_AUTH_URL , settings . KEYSTONE_PROJECT_NAME , username , password , settings . KEYSTONE_USER_DOMAIN_NAME , settings . KEYSTONE_PROJECT_DOMAIN_NAME , settings . KEYSTONE_TIMEOUT )
def get ( self , ldap_dn ) : '''Return an LDAP entry by DN Args : ldap _ dn ( str ) : LDAP DN'''
self . base_dn = ldap_dn self . sub_tree = BASE return self . first ( )
def update_routing_table_from ( self , * routers ) : """Try to update routing tables with the given routers . : return : True if the routing table is successfully updated , otherwise False"""
for router in routers : new_routing_table = self . fetch_routing_table ( router ) if new_routing_table is not None : self . routing_table . update ( new_routing_table ) return True return False
def run ( self , b , compute , times = [ ] , ** kwargs ) : """if within mpirun , workers should call _ run _ worker instead of run"""
self . run_checks ( b , compute , times , ** kwargs ) logger . debug ( "rank:{}/{} calling get_packet_and_syns" . format ( mpi . myrank , mpi . nprocs ) ) packet , new_syns = self . get_packet_and_syns ( b , compute , times , ** kwargs ) if mpi . enabled : # broadcast the packet to ALL workers mpi . comm . bcast ( ...
def round_down ( x , decimal_places ) : """Round a float down to decimal _ places . Parameters x : float decimal _ places : int Returns rounded _ float : float Examples > > > round _ down ( 1.23456 , 3) 1.234 > > > round _ down ( 1.23456 , 2) 1.23"""
from math import floor d = int ( '1' + ( '0' * decimal_places ) ) return floor ( x * d ) / d
def _marshaled_dispatch ( self , data , dispatch_method = None ) : """Dispatches an XML - RPC method from marshalled ( XML ) data . XML - RPC methods are dispatched from the marshalled ( XML ) data using the _ dispatch method and the result is returned as marshalled data . For backwards compatibility , a disp...
try : params , method = xmlrpclib . loads ( data ) # generate response if dispatch_method is not None : response = dispatch_method ( method , params ) else : response = self . _dispatch ( method , params ) # wrap response in a singleton tuple response = ( response , ) respons...
def format_subpages ( self , page , subpages ) : """Banana banana"""
if not subpages : return None try : template = self . get_template ( 'subpages.html' ) except IOError : return None ret = etree . XML ( template . render ( { 'page' : page , 'subpages' : subpages } ) ) assets = ret . xpath ( './/*[@src]' ) for asset in assets : self . __lookup_asset ( asset , self . ext...
def _remove_broken_links ( ) : '''Remove broken links in ` < conda prefix > / etc / microdrop / plugins / enabled / ` . Returns list List of links removed ( if any ) .'''
enabled_dir = MICRODROP_CONDA_PLUGINS . joinpath ( 'enabled' ) if not enabled_dir . isdir ( ) : return [ ] broken_links = [ ] for dir_i in enabled_dir . walkdirs ( errors = 'ignore' ) : if platform . system ( ) == 'Windows' : if dir_i . isjunction ( ) and not dir_i . readlink ( ) . isdir ( ) : # Junctio...
def density ( self , R , z , nsigma = None , mc = False , nmc = 10000 , gl = True , ngl = _DEFAULTNGL , ** kwargs ) : """NAME : density PURPOSE : calculate the density at R , z by marginalizing over velocity INPUT : R - radius at which to calculate the density ( can be Quantity ) z - height at which to ...
return self . _vmomentdensity ( R , z , 0. , 0. , 0. , nsigma = nsigma , mc = mc , nmc = nmc , gl = gl , ngl = ngl , ** kwargs )
def _read_signer ( key_filename ) : """Reads the given file as a hex key . Args : key _ filename : The filename where the key is stored . If None , defaults to the default key for the current user . Returns : Signer : the signer Raises : CliException : If unable to read the file ."""
filename = key_filename if filename is None : filename = os . path . join ( os . path . expanduser ( '~' ) , '.sawtooth' , 'keys' , getpass . getuser ( ) + '.priv' ) try : with open ( filename , 'r' ) as key_file : signing_key = key_file . read ( ) . strip ( ) except IOError as e : raise CliExceptio...
def _run_vardict_caller ( align_bams , items , ref_file , assoc_files , region = None , out_file = None ) : """Detect SNPs and indels with VarDict . var2vcf _ valid uses - A flag which reports all alleles and improves sensitivity : https : / / github . com / AstraZeneca - NGS / VarDict / issues / 35 # issuecomm...
config = items [ 0 ] [ "config" ] if out_file is None : out_file = "%s-variants.vcf.gz" % os . path . splitext ( align_bams [ 0 ] ) [ 0 ] if not utils . file_exists ( out_file ) : with file_transaction ( items [ 0 ] , out_file ) as tx_out_file : vrs = bedutils . population_variant_regions ( items ) ...
def _FormatSocketUnixToken ( self , token_data ) : """Formats an Unix socket token as a dictionary of values . Args : token _ data ( bsm _ token _ data _ sockunix ) : AUT _ SOCKUNIX token data . Returns : dict [ str , str ] : token values ."""
protocol = bsmtoken . BSM_PROTOCOLS . get ( token_data . socket_family , 'UNKNOWN' ) return { 'protocols' : protocol , 'family' : token_data . socket_family , 'path' : token_data . socket_path }
def comp_listing ( request , directory_slug = None ) : """Output the list of HTML templates and subdirectories in the COMPS _ DIR"""
context = { } working_dir = settings . COMPS_DIR if directory_slug : working_dir = os . path . join ( working_dir , directory_slug ) dirnames = [ ] templates = [ ] items = os . listdir ( working_dir ) templates = [ x for x in items if os . path . splitext ( x ) [ 1 ] == '.html' ] dirnames = [ x for x in items if no...
def display_movements_stats ( ct , base_assignment ) : """Display how the amount of movement between two assignments . : param ct : The cluster ' s ClusterTopology . : param base _ assignment : The cluster assignment to compare against ."""
movement_count , movement_size , leader_changes = stats . get_partition_movement_stats ( ct , base_assignment ) print ( 'Total partition movements: {movement_count}\n' 'Total partition movement size: {movement_size}\n' 'Total leader changes: {leader_changes}' . format ( movement_count = movement_count , movement_size =...
def check_image_state ( self , image_id , wait = True ) : '''method for checking the state of an image on AWS EC2 : param image _ id : string with AWS id of image : param wait : [ optional ] boolean to wait for image while pending : return : string reporting state of image'''
title = '%s.check_image_state' % self . __class__ . __name__ # validate inputs input_fields = { 'image_id' : image_id } for key , value in input_fields . items ( ) : object_title = '%s(%s=%s)' % ( title , key , str ( value ) ) self . fields . validate ( value , '.%s' % key , object_title ) # notify state check ...
def mediatype_delete ( mediatypeids , ** kwargs ) : '''Delete mediatype : param interfaceids : IDs of the mediatypes to delete : param _ connection _ user : Optional - zabbix user ( can also be set in opts or pillar , see module ' s docstring ) : param _ connection _ password : Optional - zabbix password ( ca...
conn_args = _login ( ** kwargs ) ret = { } try : if conn_args : method = 'mediatype.delete' if isinstance ( mediatypeids , list ) : params = mediatypeids else : params = [ mediatypeids ] ret = _query ( method , params , conn_args [ 'url' ] , conn_args [ 'auth'...
def plot_mds ( self , rank = "auto" , metric = "braycurtis" , method = "pcoa" , title = None , xlabel = None , ylabel = None , color = None , size = None , tooltip = None , return_chart = False , label = None , ) : """Plot beta diversity distance matrix using multidimensional scaling ( MDS ) . Parameters rank :...
if len ( self . _results ) < 2 : raise OneCodexException ( "`plot_mds` requires 2 or more valid classification results." ) dists = self . _compute_distance ( rank , metric ) . to_data_frame ( ) # here we figure out what to put in the tooltips and get the appropriate data if tooltip : if not isinstance ( tooltip...
def exclude ( prop ) : '''Don ' t replicate property that is normally replicated : ordering column , many - to - one relation that is marked for replication from other side .'''
if isinstance ( prop , QueryableAttribute ) : prop = prop . property assert isinstance ( prop , ( Column , ColumnProperty , RelationshipProperty ) ) _excluded . add ( prop ) if isinstance ( prop , RelationshipProperty ) : # Also exclude columns that participate in this relationship for local in prop . local_col...
def get_next_id ( self ) : """Gets the next Id in this list . return : ( osid . id . Id ) - the next Id in this list . The has _ next ( ) method should be used to test that a next Id is available before calling this method . raise : IllegalState - no more elements available in this list raise : OperationF...
try : next_item = next ( self ) except StopIteration : raise IllegalState ( 'no more elements available in this list' ) except Exception : # Need to specify exceptions here ! raise OperationFailed ( ) else : return next_item
def decompose_nfkd ( text ) : """Perform unicode compatibility decomposition . This will replace some non - standard value representations in unicode and normalise them , while also separating characters and their diacritics into two separate codepoints ."""
if text is None : return None if not hasattr ( decompose_nfkd , '_tr' ) : decompose_nfkd . _tr = Transliterator . createInstance ( 'Any-NFKD' ) return decompose_nfkd . _tr . transliterate ( text )
def _serialize ( self , include_run_logs = False , strict_json = False ) : """Serialize a representation of this Job to a Python dict object ."""
# return tasks in sorted order if graph is in a valid state try : topo_sorted = self . topological_sort ( ) t = [ self . tasks [ task ] . _serialize ( include_run_logs = include_run_logs , strict_json = strict_json ) for task in topo_sorted ] except : t = [ task . _serialize ( include_run_logs = include_run...
def _wrap_section ( source , width ) : # type : ( str , int ) - > str """Wrap the given section string to the current terminal size . Intelligently wraps the section string to the given width . When wrapping section lines , it auto - adjusts the spacing between terms and definitions . It also adjusts commands...
if _get_section ( 'usage' , source ) : return _wrap_usage_section ( source , width ) if _is_definition_section ( source ) : return _wrap_definition_section ( source , width ) lines = inspect . cleandoc ( source ) . splitlines ( ) paragraphs = ( textwrap . wrap ( line , width , replace_whitespace = False ) for l...
def digital_channel_air ( self , opt1 = '?' , opt2 = '?' ) : """Description : Change Channel ( Digital ) Pass Channels " XX . YY " as TV . digital _ channel _ air ( XX , YY ) Arguments : opt1 : integer 1-99 : Major Channel opt2 : integer ( optional ) 1-99 : Minor Channel"""
if opt1 == '?' : parameter = '?' elif opt2 == '?' : parameter = str ( opt1 ) . rjust ( 4 , "0" ) else : parameter = '{:02d}{:02d}' . format ( opt1 , opt2 ) return self . _send_command ( 'digital_channel_air' , parameter )
def course_register_user ( self , course , username = None , password = None , force = False ) : """Register a user to the course : param course : a Course object : param username : The username of the user that we want to register . If None , uses self . session _ username ( ) : param password : Password for...
if username is None : username = self . session_username ( ) user_info = self . _database . users . find_one ( { "username" : username } ) # Do not continue registering the user in the course if username is empty . if not username : return False if not force : if not course . is_registration_possible ( user...
def __field_callback ( self , field , event , * args , ** kwargs ) : # type : ( str , str , * Any , * * Any ) - > Any """Calls the registered method in the component for the given field event : param field : A field name : param event : An event ( IPOPO _ CALLBACK _ VALIDATE , . . . ) : return : The callback ...
# Get the field callback info cb_info = self . context . get_field_callback ( field , event ) if not cb_info : # No registered callback return True # Extract information callback , if_valid = cb_info if if_valid and self . state != StoredInstance . VALID : # Don ' t call the method if the component state isn ' t sa...
def call_api_fetch ( self , params , get_latest_only = True ) : """GET https : / / myserver / piwebapi / assetdatabases / D0NxzXSxtlKkGzAhZfHOB - KAQLhZ5wrU - UyRDQnzB _ zGVAUEhMQUZTMDRcTlVHUkVFTg HTTP / 1.1 Host : myserver Accept : application / json"""
output_format = 'application/json' url_string = self . request_info . url_string ( ) # passing the username and required output format headers_list = { "Accept" : output_format , "Host" : self . request_info . host } try : hub_result = requests . get ( url_string , headers = headers_list , timeout = 10.000 , verify...
def jupytext ( args = None ) : """Internal implementation of Jupytext command line"""
args = parse_jupytext_args ( args ) def log ( text ) : if not args . quiet : sys . stdout . write ( text + '\n' ) if args . version : log ( __version__ ) return 0 if args . pre_commit : if args . notebooks : raise ValueError ( '--pre-commit takes notebooks from the git index. Do not pass...
def plot_reaction_scheme ( df , temperature , pressure , potential , pH , e_lim = None ) : """Returns a matplotlib object with the plotted reaction path . Parameters df : Pandas DataFrame generated by reaction _ network temperature : numeric temperature in K pressure : numeric pressure in mbar pH : PH...
ncols = int ( ( df . shape [ 0 ] / 20 ) ) + 1 fig_width = ncols + 1.5 * len ( df [ 'intermediate_labels' ] [ 0 ] ) figsize = ( fig_width , 6 ) fig , ax = plt . subplots ( figsize = figsize ) if pressure == None : pressure_label = '0' else : pressure_label = str ( pressure ) lines = [ ] for j , energy_list in en...
def get ( self , object_name ) : """Return an object or None if it doesn ' t exist : param object _ name : : return : Object"""
if object_name in self : return Object ( obj = self . container . get_object ( object_name ) ) return None
def gpu_iuwt_decomposition ( in1 , scale_count , scale_adjust , store_smoothed , store_on_gpu ) : """This function calls the a trous algorithm code to decompose the input into its wavelet coefficients . This is the isotropic undecimated wavelet transform implemented for a GPU . INPUTS : in1 ( no default ) : A...
# The following simple kernel just allows for the construction of a 3D decomposition on the GPU . ker = SourceModule ( """ __global__ void gpu_store_detail_coeffs(float *in1, float *in2, float* out1, int *scale, int *adjust) { const int len = g...
def ConsultarDepositosAcopio ( self , sep = "||" ) : "Retorna los depósitos de acopio pertenencientes al contribuyente"
ret = self . client . consultarDepositosAcopio ( auth = { 'token' : self . Token , 'sign' : self . Sign , 'cuit' : self . Cuit , } , ) [ 'respuesta' ] self . __analizar_errores ( ret ) array = ret . get ( 'acopio' , [ ] ) if sep is None : return array else : return [ ( "%s %%s %s %%s %s %%s %s %%s %s" % ( sep ,...
def reinforce_lv_branches_overloading ( grid , crit_branches ) : """Choose appropriate cable type for branches with line overloading Parameters grid : LVGridDing0 Ding0 LV grid object crit _ branches : : any : ` list ` List of critical branches incl . its line loading Notes If maximum size cable is no...
unsolved_branches = [ ] cable_lf = cfg_ding0 . get ( 'assumptions' , 'load_factor_lv_cable_lc_normal' ) cables = grid . network . static_data [ 'LV_cables' ] # resolve overloading issues for each branch segment for branch in crit_branches : I_max_branch_load = branch [ 's_max' ] [ 0 ] I_max_branch_gen = branch ...
def clear ( self ) : """Clears the information for this edit ."""
self . uiQueryTXT . setText ( '' ) self . uiQueryTREE . clear ( ) self . uiGroupingTXT . setText ( '' ) self . uiSortingTXT . setText ( '' )
def parallel_map ( func , iterable , args = None , kwargs = None , workers = None ) : """Map func on a list using gevent greenlets . : param func : function applied on iterable elements : type func : function : param iterable : elements to map the function over : type iterable : iterable : param args : ar...
if args is None : args = ( ) if kwargs is None : kwargs = { } if workers is not None : pool = Pool ( workers ) else : pool = Group ( ) iterable = [ pool . spawn ( func , i , * args , ** kwargs ) for i in iterable ] pool . join ( raise_error = True ) for idx , i in enumerate ( iterable ) : i_type = t...
def set ( self , value , pos = None ) : """Set one or many bits to 1 or 0. value - - If True bits are set to 1 , otherwise they are set to 0. pos - - Either a single bit position or an iterable of bit positions . Negative numbers are treated in the same way as slice indices . Defaults to the entire bitstrin...
f = self . _set if value else self . _unset if pos is None : pos = xrange ( self . len ) try : length = self . len for p in pos : if p < 0 : p += length if not 0 <= p < length : raise IndexError ( "Bit position {0} out of range." . format ( p ) ) f ( p ) excep...
def pre_run_hook ( self , func , prefix = None ) : """Decorator to add a pre - run hook to this ingredient . Pre - run hooks are captured functions that are run , just before the main function is executed ."""
cf = self . capture ( func , prefix = prefix ) self . pre_run_hooks . append ( cf ) return cf
def weight_field ( self , f ) : """Select one field as the weight field . Note that this field will be exclude from feature fields . : param f : Selected weight field : type f : str : rtype : DataFrame"""
if f is None : raise ValueError ( "Field name cannot be None." ) self . _assert_ml_fields_valid ( f ) return _change_singleton_roles ( self , { f : FieldRole . WEIGHT } , clear_feature = True )
def total_supply ( self , block_identifier = 'latest' ) : """Return the total supply of the token at the given block identifier ."""
return self . proxy . contract . functions . totalSupply ( ) . call ( block_identifier = block_identifier )
def record ( session_file , shell , prompt , alias , envvar ) : """Record a session file . If no argument is passed , commands are written to . / session . sh . When you are finished recording , run the " stop " command ."""
if os . path . exists ( session_file ) : click . confirm ( 'File "{0}" already exists. Overwrite?' . format ( session_file ) , abort = True , default = False , ) secho ( "We'll do it live!" , fg = "red" , bold = True ) filename = click . format_filename ( session_file ) secho ( "RECORDING SESSION: {}" . format ( fi...
def write_newick_ott ( out , ott , ott_id2children , root_ott_id , label_style , prune_flags , create_log_dict = False ) : """` out ` is an output stream ` ott ` is an OTT instance used for translating labels ` ott _ id2children ` is a dict mapping an OTT ID to the IDs of its children ` root _ ott _ id ` is t...
# create to _ prune _ fsi _ set a set of flag set indices to prune . . . if prune_flags : flags_to_prune_list = list ( prune_flags ) to_prune_fsi_set = ott . convert_flag_string_set_to_union ( flags_to_prune_list ) else : flags_to_prune_list = [ ] to_prune_fsi_set = None flags_to_prune_set = frozenset (...
def _init_ui ( self ) -> VBox : "Initialize the widget UI and return the UI ."
self . _search_input = Text ( placeholder = "What images to search for?" ) self . _count_input = BoundedIntText ( placeholder = "How many pics?" , value = 10 , min = 1 , max = 5000 , step = 1 , layout = Layout ( width = '60px' ) ) self . _size_input = Dropdown ( options = _img_sizes . keys ( ) , value = '>400*300' , la...
def setup_asset_page ( self , ) : """Create and set the model on the asset page : returns : None : rtype : None : raises : None"""
self . asset_asset_treev . header ( ) . setResizeMode ( QtGui . QHeaderView . ResizeToContents ) self . asset_task_tablev . horizontalHeader ( ) . setResizeMode ( QtGui . QHeaderView . ResizeToContents )
def delete ( self , client = None ) : """Delete this notification . See : https : / / cloud . google . com / storage / docs / json _ api / v1 / notifications / delete If : attr : ` user _ project ` is set on the bucket , bills the API request to that project . : type client : : class : ` ~ google . cloud ...
if self . notification_id is None : raise ValueError ( "Notification not intialized by server" ) client = self . _require_client ( client ) query_params = { } if self . bucket . user_project is not None : query_params [ "userProject" ] = self . bucket . user_project client . _connection . api_request ( method =...
def vms ( message , level = 1 ) : """Writes the specified message * only * if verbose output is enabled ."""
if verbose is not None and verbose != False : if isinstance ( verbose , bool ) or ( isinstance ( verbose , int ) and level <= verbose ) : std ( message )
def _plot ( self , xticks = [ ] , yticks = [ ] , minor_xticks = [ ] , minor_yticks = [ ] , xlabel = 'Longitude' , ylabel = 'Latitude' , ax = None , ax2 = None , colorbar = None , cb_orientation = None , cb_label = None , grid = False , axes_labelsize = None , tick_labelsize = None , ** kwargs ) : """Plot the raw da...
if ax is None : if colorbar is True : if cb_orientation == 'horizontal' : scale = 0.67 else : scale = 0.5 else : scale = 0.55 figsize = ( _mpl . rcParams [ 'figure.figsize' ] [ 0 ] , _mpl . rcParams [ 'figure.figsize' ] [ 0 ] * scale ) fig , axes = _plt . ...
def sub ( self , num ) : """Subtracts num from the current value"""
try : val = self . value ( ) - num except : val = - num self . set ( max ( 0 , val ) )
def _compute_soil_linear_factor ( cls , pga_rock , imt ) : """Compute soil linear factor as explained in paragraph ' Functional Form ' , page 1706."""
if imt . period >= 1 : return np . ones_like ( pga_rock ) else : sl = np . zeros_like ( pga_rock ) pga_between_100_500 = ( pga_rock > 100 ) & ( pga_rock < 500 ) pga_greater_equal_500 = pga_rock >= 500 is_SA_between_05_1 = 0.5 < imt . period < 1 is_SA_less_equal_05 = imt . period <= 0.5 if is...
def add_tags ( self , archive_name , tags ) : '''Add tags to an archive Parameters archive _ name : s tr Name of archive tags : list or tuple of strings tags to add to the archive'''
updated_tag_list = list ( self . _get_tags ( archive_name ) ) for tag in tags : if tag not in updated_tag_list : updated_tag_list . append ( tag ) self . _set_tags ( archive_name , updated_tag_list )
def _get_mechanism ( self , rup , C ) : """Compute the fourth term of the equation described on p . 199: ` ` f1 * Fn + f2 * Fr ` `"""
Fn , Fr = self . _get_fault_type_dummy_variables ( rup ) return ( C [ 'f1' ] * Fn ) + ( C [ 'f2' ] * Fr )
def _hz_to_semitones ( self , hz ) : """Convert hertz into a number of semitones above or below some reference value , in this case , A440"""
return np . log ( hz / self . _a440 ) / np . log ( self . _a )
def publishing_set_update_time ( sender , instance , ** kwargs ) : """Update the time modified before saving a publishable object ."""
if hasattr ( instance , 'publishing_linked' ) : # Hack to avoid updating ` publishing _ modified _ at ` field when a draft # publishable item is saved as part of a ` publish ` operation . This # ensures that the ` publishing _ published _ at ` timestamp is later than # the ` publishing _ modified _ at ` timestamp when ...
def load_configuration ( ) : """Load the configuration"""
( belbio_conf_fp , belbio_secrets_fp ) = get_belbio_conf_files ( ) log . info ( f"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} " ) config = { } if belbio_conf_fp : with open ( belbio_conf_fp , "r" ) as f : config = yaml . load ( f , Loader = yaml . SafeLoader ) config [ "sourc...
def get_all_rrsets ( self , hosted_zone_id , type = None , name = None , identifier = None , maxitems = None ) : """Retrieve the Resource Record Sets defined for this Hosted Zone . Returns the raw XML data returned by the Route53 call . : type hosted _ zone _ id : str : param hosted _ zone _ id : The unique i...
from boto . route53 . record import ResourceRecordSets params = { 'type' : type , 'name' : name , 'Identifier' : identifier , 'maxitems' : maxitems } uri = '/%s/hostedzone/%s/rrset' % ( self . Version , hosted_zone_id ) response = self . make_request ( 'GET' , uri , params = params ) body = response . read ( ) boto . l...
def addQuery ( self ) : """Sets the query for this widget from the quick query text builder ."""
insert_item = self . uiQueryTREE . currentItem ( ) if ( insert_item and not insert_item . isSelected ( ) ) : insert_item = None # create the query if ( self . uiQueryTXT . text ( ) ) : query = Q . fromString ( nativestring ( self . uiQueryTXT . text ( ) ) ) self . uiQueryTXT . setText ( '' ) else : quer...
def key_type ( self , type_ ) : """returns reference to the class key type declaration"""
if not self . is_mapping ( type_ ) : raise TypeError ( 'Type "%s" is not "mapping" container' % str ( type_ ) ) return self . __find_xxx_type ( type_ , self . key_type_index , self . key_type_typedef , 'container_key_type' )
def columns_formatter ( cls , colname ) : """Decorator to mark a function as columns formatter ."""
def wrapper ( func ) : cls . columns_formatters [ colname ] = func return func return wrapper
def cli ( ctx , user , organism , administrate = False , write = False , export = False , read = False ) : """Update the permissions of a user on a specified organism Output : a dictionary containing user ' s organism permissions"""
return ctx . gi . users . update_organism_permissions ( user , organism , administrate = administrate , write = write , export = export , read = read )
def makeImages ( self ) : """Make spiral images in sectors and steps . Plain , reversed , sectorialized , negative sectorialized outline , outline reversed , lonely only nodes , only edges , both"""
# make layout self . makeLayout ( ) self . setAgraph ( ) # make function that accepts a mode , a sector # and nodes and edges True and False self . plotGraph ( ) self . plotGraph ( "reversed" , filename = "tgraphR.png" ) agents = n . concatenate ( self . np . sectorialized_agents__ ) for i , sector in enumerate ( self ...
def subset ( self , used_indices , params = None ) : """Get subset of current Dataset . Parameters used _ indices : list of int Indices used to create the subset . params : dict or None , optional ( default = None ) These parameters will be passed to Dataset constructor . Returns subset : Dataset Su...
if params is None : params = self . params ret = Dataset ( None , reference = self , feature_name = self . feature_name , categorical_feature = self . categorical_feature , params = params , free_raw_data = self . free_raw_data ) ret . _predictor = self . _predictor ret . pandas_categorical = self . pandas_categori...
def pieces ( self , piece_type : PieceType , color : Color ) -> "SquareSet" : """Gets pieces of the given type and color . Returns a : class : ` set of squares < chess . SquareSet > ` ."""
return SquareSet ( self . pieces_mask ( piece_type , color ) )
def create_SMS ( self , files , recipients , body , params = { } ) : """Create a new certified sms @ files Files to send ex : [ ' / documents / internet _ contract . pdf ' , . . . ] @ recipients A dictionary with the phone and name of the person you want to sign . Phone must be always with prefix If you...
parameters = { } parser = Parser ( ) documents = { } parser . fill_array ( documents , files , 'files' ) recipients = recipients if isinstance ( recipients , list ) else [ recipients ] index = 0 for recipient in recipients : parser . fill_array ( parameters , recipient , 'recipients[%i]' % index ) index += 1 pa...
def set_windows_env_var ( key , value ) : """Set an env var . Raises : WindowsError"""
if not isinstance ( key , text_type ) : raise TypeError ( "%r not of type %r" % ( key , text_type ) ) if not isinstance ( value , text_type ) : raise TypeError ( "%r not of type %r" % ( value , text_type ) ) status = winapi . SetEnvironmentVariableW ( key , value ) if status == 0 : raise ctypes . WinError (...
def color_print ( * args , ** kwargs ) : """Prints colors and styles to the terminal uses ANSI escape sequences . color _ print ( ' This is the color ' , ' default ' , ' GREEN ' , ' green ' ) Parameters positional args : str The positional arguments come in pairs ( * msg * , * color * ) , where * msg * ...
file = kwargs . get ( 'file' , _get_stdout ( ) ) end = kwargs . get ( 'end' , '\n' ) write = file . write if isatty ( file ) and options . console . use_color : for i in range ( 0 , len ( args ) , 2 ) : msg = args [ i ] if i + 1 == len ( args ) : color = '' else : col...
def dump_yaml ( testcase , yaml_file ) : """dump HAR entries to yaml testcase"""
logging . info ( "dump testcase to YAML format." ) with io . open ( yaml_file , 'w' , encoding = "utf-8" ) as outfile : yaml . dump ( testcase , outfile , allow_unicode = True , default_flow_style = False , indent = 4 ) logging . info ( "Generate YAML testcase successfully: {}" . format ( yaml_file ) )
def packet_in_handler ( self , evt ) : """PacketIn event handler . when the received packet was IGMP , proceed it . otherwise , send a event ."""
msg = evt . msg dpid = msg . datapath . id req_pkt = packet . Packet ( msg . data ) req_igmp = req_pkt . get_protocol ( igmp . igmp ) if req_igmp : if self . _querier . dpid == dpid : self . _querier . packet_in_handler ( req_igmp , msg ) else : self . _snooper . packet_in_handler ( req_pkt , re...
def as_sql ( self , qn , connection ) : """Create the proper SQL fragment . This inserts something like " ( T0 . flags & value ) ! = 0 " . This will be called by Where . as _ sql ( )"""
engine = connection . settings_dict [ 'ENGINE' ] . rsplit ( '.' , - 1 ) [ - 1 ] if engine . startswith ( 'postgres' ) : XOR_OPERATOR = '#' elif engine . startswith ( 'sqlite' ) : raise NotImplementedError else : XOR_OPERATOR = '^' if self . bit : return ( "%s.%s | %d" % ( qn ( self . table_alias ) , qn ...
def fetch_package_version ( dist_name ) : """> > > fetch _ package _ version ( ' sentry ' )"""
try : # Importing pkg _ resources can be slow , so only import it # if we need it . import pkg_resources except ImportError : # pkg _ resource is not available on Google App Engine raise NotImplementedError ( 'pkg_resources is not available ' 'on this Python install' ) dist = pkg_resources . get_distribution ( ...
def tablecopy ( tablename , newtablename , deep = False , valuecopy = False , dminfo = { } , endian = 'aipsrc' , memorytable = False , copynorows = False ) : """Copy a table . It is the same as : func : ` table . copy ` , but without the need to open the table first ."""
t = table ( tablename , ack = False ) return t . copy ( newtablename , deep = deep , valuecopy = valuecopy , dminfo = dminfo , endian = endian , memorytable = memorytable , copynorows = copynorows )
def setup_seasonal ( self ) : """Check if there ' s some seasonal holiday going on , setup appropriate Shibe picture and load holiday words . Note : if there are two or more holidays defined for a certain date , the first one takes precedence ."""
# If we ' ve specified a season , just run that one if self . ns . season : return self . load_season ( self . ns . season ) # If we ' ve specified another doge or no doge at all , it does not make # sense to use seasons . if self . ns . doge_path is not None and not self . ns . no_shibe : return now = datetime...
def one_instance ( function = None , key = '' , timeout = DEFAULT_ONE_INSTANCE_TIMEOUT ) : """Decorator to enforce only one Celery task execution at a time when multiple workers are available . See http : / / loose - bits . com / 2010/10 / distributed - task - locking - in - celery . html"""
def _dec ( run_func ) : def _caller ( * args , ** kwargs ) : ret_value = None have_lock = False # Use Redis AOF for persistent lock . if REDIS_CLIENT . config_get ( 'appendonly' ) . values ( ) [ 0 ] == 'no' : REDIS_CLIENT . config_set ( 'appendonly' , 'yes' ) lock...
def _onsuccess ( self , result ) : """To execute on execution success : param cdumay _ result . Result result : Execution result : return : Execution result : rtype : cdumay _ result . Result"""
self . _set_status ( "SUCCESS" , result ) logger . info ( "{}.Success: {}[{}]: {}" . format ( self . __class__ . __name__ , self . __class__ . path , self . uuid , result ) , extra = dict ( kmsg = Message ( self . uuid , entrypoint = self . __class__ . path , params = self . params ) . dump ( ) , kresult = ResultSchema...
def set_qos ( self , prefetch_size = 0 , prefetch_count = 0 , apply_globally = False ) : """Specify quality of service by requesting that messages be pre - fetched from the server . Pre - fetching means that the server will deliver messages to the client while the client is still processing unacknowledged messa...
self . sender . send_BasicQos ( prefetch_size , prefetch_count , apply_globally ) yield from self . synchroniser . wait ( spec . BasicQosOK ) self . reader . ready ( )
def _bb_intensity ( self , Teff , photon_weighted = False ) : """Computes mean passband intensity using blackbody atmosphere : I _ pb ^ E = \ int _ \ lambda I ( \ lambda ) P ( \ lambda ) d \ lambda / \ int _ \ lambda P ( \ lambda ) d \ lambda I _ pb ^ P = \ int _ \ lambda \ lambda I ( \ lambda ) P ( \ lambda ) ...
if photon_weighted : pb = lambda w : w * self . _planck ( w , Teff ) * self . ptf ( w ) return integrate . quad ( pb , self . wl [ 0 ] , self . wl [ - 1 ] ) [ 0 ] / self . ptf_photon_area else : pb = lambda w : self . _planck ( w , Teff ) * self . ptf ( w ) return integrate . quad ( pb , self . wl [ 0 ]...
async def send_photo ( self , path , entity ) : """Sends the file located at path to the desired entity as a photo"""
await self . send_file ( entity , path , progress_callback = self . upload_progress_callback ) print ( 'Photo sent!' )
def set_agent_settings ( contact = None , location = None , services = None ) : '''Manage the SNMP sysContact , sysLocation , and sysServices settings . Args : contact ( str , optional ) : The SNMP contact . location ( str , optional ) : The SNMP location . services ( list , optional ) : A list of selected ...
if services is not None : # Filter services for unique items , and sort them for comparison # purposes . services = sorted ( set ( services ) ) # Validate the services . for service in services : if service not in _SERVICE_TYPES : message = ( "Invalid service '{0}' specified. Valid servi...
def save_dir ( key , dir_path , * refs ) : """Convert the given parameters to a special JSON object . JSON object is of the form : { key : { " dir " : dir _ path } } , or { key : { " dir " : dir _ path , " refs " : [ refs [ 0 ] , refs [ 1 ] , . . . ] } }"""
if not os . path . isdir ( dir_path ) : return error ( "Output '{}' set to a missing directory: '{}'." . format ( key , dir_path ) ) result = { key : { "dir" : dir_path } } if refs : missing_refs = [ ref for ref in refs if not ( os . path . isfile ( ref ) or os . path . isdir ( ref ) ) ] if len ( missing_re...
def get_network ( self ) : """Get the network that this resource attribute is in ."""
ref_key = self . ref_key if ref_key == 'NETWORK' : return self . network elif ref_key == 'NODE' : return self . node . network elif ref_key == 'LINK' : return self . link . network elif ref_key == 'GROUP' : return self . group . network elif ref_key == 'PROJECT' : return None
def draw_arc ( self , color , world_loc , world_radius , start_angle , stop_angle , thickness = 1 ) : """Draw an arc using world coordinates , radius , start and stop angles ."""
center = self . world_to_surf . fwd_pt ( world_loc ) . round ( ) radius = max ( 1 , int ( self . world_to_surf . fwd_dist ( world_radius ) ) ) rect = pygame . Rect ( center - radius , ( radius * 2 , radius * 2 ) ) pygame . draw . arc ( self . surf , color , rect , start_angle , stop_angle , thickness if thickness < rad...
def find_path ( dirs , path_to_find ) : """Go through a bunch of dirs and see if dir + path _ to _ find exists there . Returns the first dir that matches . Otherwise , return None ."""
for dir in dirs : if os . path . exists ( os . path . join ( dir , path_to_find ) ) : return dir return None
def _lemmatise_desassims ( self , f , * args , ** kwargs ) : """Lemmatise un mot f avec sa désassimilation : param f : Mot à lemmatiser : yield : Match formated like in _ lemmatise ( )"""
forme_assimilee = self . desassims ( f ) if forme_assimilee != f : for proposal in self . _lemmatise ( forme_assimilee , * args , ** kwargs ) : yield proposal
def filepaths ( self ) : """Yield absolute paths to existing files in : attr : ` path ` Any files that match patterns in : attr : ` exclude ` as well as hidden and empty files are not included ."""
if self . path is not None : yield from utils . filepaths ( self . path , exclude = self . exclude , hidden = False , empty = False )
def upload_slice_file ( self , real_file_path , slice_size , file_name , offset = 0 , dir_name = None ) : """此分片上传代码由GitHub用户a270443177 ( https : / / github . com / a270443177 ) 友情提供 : param real _ file _ path : : param slice _ size : : param file _ name : : param offset : : param dir _ name : : return ...
if dir_name is not None and dir_name [ 0 ] == '/' : dir_name = dir_name [ 1 : len ( dir_name ) ] if dir_name is None : dir_name = "" self . url = 'http://' + self . config . region + '.file.myqcloud.com/files/v2/' + str ( self . config . app_id ) + '/' + self . config . bucket if dir_name is not None : self...
def from_jd ( jd ) : '''Calculate Islamic date from Julian day'''
jd = trunc ( jd ) + 0.5 year = trunc ( ( ( 30 * ( jd - EPOCH ) ) + 10646 ) / 10631 ) month = min ( 12 , ceil ( ( jd - ( 29 + to_jd ( year , 1 , 1 ) ) ) / 29.5 ) + 1 ) day = int ( jd - to_jd ( year , month , 1 ) ) + 1 return ( year , month , day )
def _DecodeUnknownMessages ( message , encoded_message , pair_type ) : """Process unknown fields in encoded _ message of a message type ."""
field_type = pair_type . value . type new_values = [ ] all_field_names = [ x . name for x in message . all_fields ( ) ] for name , value_dict in six . iteritems ( encoded_message ) : if name in all_field_names : continue value = PyValueToMessage ( field_type , value_dict ) if pair_type . value . rep...
def reload ( name = DEFAULT , all_names = False ) : """Reload one or all : class : ` ConfigNamespace ` . Reload clears the cache of : mod : ` staticconf . schema ` and : mod : ` staticconf . getters ` , allowing them to pickup the latest values in the namespace . Defaults to reloading just the DEFAULT namespa...
for namespace in get_namespaces_from_names ( name , all_names ) : for value_proxy in namespace . get_value_proxies ( ) : value_proxy . reset ( )
def create_review ( self , commit = github . GithubObject . NotSet , body = None , event = github . GithubObject . NotSet , comments = github . GithubObject . NotSet ) : """: calls : ` POST / repos / : owner / : repo / pulls / : number / reviews < https : / / developer . github . com / v3 / pulls / reviews / > ` _ ...
assert commit is github . GithubObject . NotSet or isinstance ( commit , github . Commit . Commit ) , commit assert isinstance ( body , str ) , body assert event is github . GithubObject . NotSet or isinstance ( event , str ) , event assert comments is github . GithubObject . NotSet or isinstance ( comments , list ) , ...
def delete_contacts ( self , ids ) : """Delete selected contacts for the current user : param ids : list of ids"""
str_ids = self . _return_comma_list ( ids ) self . request ( 'ContactAction' , { 'action' : { 'op' : 'delete' , 'id' : str_ids } } )
def decode ( self , encoded_payload ) : """Decode a transmitted payload ."""
self . packets = [ ] while encoded_payload : if six . byte2int ( encoded_payload [ 0 : 1 ] ) <= 1 : packet_len = 0 i = 1 while six . byte2int ( encoded_payload [ i : i + 1 ] ) != 255 : packet_len = packet_len * 10 + six . byte2int ( encoded_payload [ i : i + 1 ] ) i +...
def filter_words ( tokenized_obj , valid_pos , stopwords , check_field_name = 'stem' ) : # type : ( TokenizedSenetence , List [ Tuple [ text _ type , . . . ] ] , List [ text _ type ] , text _ type ) - > FilteredObject """This function filter token that user don ' t want to take . Condition is stopword and pos . ...
assert isinstance ( tokenized_obj , TokenizedSenetence ) assert isinstance ( valid_pos , list ) assert isinstance ( stopwords , list ) filtered_tokens = [ ] for token_obj in tokenized_obj . tokenized_objects : assert isinstance ( token_obj , TokenizedResult ) if check_field_name == 'stem' : res_stopword...
def build_model ( self , n_features , n_classes ) : """Create the computational graph of the model . : param n _ features : Number of features . : param n _ classes : number of classes . : return : self"""
self . _create_placeholders ( n_features , n_classes ) self . _create_layers ( n_classes ) self . cost = self . loss . compile ( self . mod_y , self . input_labels ) self . train_step = self . trainer . compile ( self . cost ) self . accuracy = Evaluation . accuracy ( self . mod_y , self . input_labels )
def metrics ( self ) -> list : """List of metrics to track for this learning process"""
my_metrics = [ FramesMetric ( "frames" ) , FPSMetric ( "fps" ) , EpisodeRewardMetric ( 'PMM:episode_rewards' ) , EpisodeRewardMetricQuantile ( 'P09:episode_rewards' , quantile = 0.9 ) , EpisodeRewardMetricQuantile ( 'P01:episode_rewards' , quantile = 0.1 ) , EpisodeLengthMetric ( "episode_length" ) ] return my_metrics ...
def model_select ( self , score_function , alleles = None , min_models = 1 , max_models = 10000 ) : """Perform model selection using a user - specified scoring function . Model selection is done using a " step up " variable selection procedure , in which models are repeatedly added to an ensemble until the scor...
if alleles is None : alleles = self . supported_alleles dfs = [ ] allele_to_allele_specific_models = { } for allele in alleles : df = pandas . DataFrame ( { 'model' : self . allele_to_allele_specific_models [ allele ] } ) df [ "model_num" ] = df . index df [ "allele" ] = allele df [ "selected" ] = F...
def notify ( self , method_name_or_object , params = None ) : """Sends a notification to the service by calling the ` ` method _ name ` ` method with the ` ` params ` ` parameters . Does not wait for a response , even if the response triggers an error . : param method _ name _ or _ object : the name of the me...
if isinstance ( method_name_or_object , Notification ) : req_obj = method_name_or_object else : req_obj = Notification ( method_name_or_object , params ) self . handle_single_request ( req_obj )
def _at_for ( self , calculator , rule , scope , block ) : """Implements @ for"""
var , _ , name = block . argument . partition ( ' from ' ) frm , _ , through = name . partition ( ' through ' ) if through : inclusive = True else : inclusive = False frm , _ , through = frm . partition ( ' to ' ) frm = calculator . calculate ( frm ) through = calculator . calculate ( through ) try : fr...
def set_quality_index ( self ) : """Set the current signal quality in combobox ."""
window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) qual = self . annot . get_stage_for_epoch ( window_start , window_length , attr = 'quality' ) # lg . info ( ' winstart : ' + str ( window _ start ) + ' , quality : ' + str ( qual ) ) if qual is None : s...