signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def rpn_losses ( anchor_labels , anchor_boxes , label_logits , box_logits ) : """Args : anchor _ labels : fHxfWxNA anchor _ boxes : fHxfWxNAx4 , encoded label _ logits : fHxfWxNA box _ logits : fHxfWxNAx4 Returns : label _ loss , box _ loss"""
with tf . device ( '/cpu:0' ) : valid_mask = tf . stop_gradient ( tf . not_equal ( anchor_labels , - 1 ) ) pos_mask = tf . stop_gradient ( tf . equal ( anchor_labels , 1 ) ) nr_valid = tf . stop_gradient ( tf . count_nonzero ( valid_mask , dtype = tf . int32 ) , name = 'num_valid_anchor' ) nr_pos = tf ....
def rolling_window ( array , length , mutable = False ) : """Restride an array of shape ( X _ 0 , . . . X _ N ) into an array of shape ( length , X _ 0 - length + 1 , . . . X _ N ) where each slice at index i along the first axis is equivalent to result [ i ] = array [ length * i : length * ( i + 1 ) ] ...
if not length : raise ValueError ( "Can't have 0-length window" ) orig_shape = array . shape if not orig_shape : raise IndexError ( "Can't restride a scalar." ) elif orig_shape [ 0 ] < length : raise IndexError ( "Can't restride array of shape {shape} with" " a window length of {len}" . format ( shape = ori...
def load_stack ( stack ) : """Loads the saved state of a CallStack and returns a whole instance given an instance with incomplete state . : param caliendo . hooks . CallStack stack : The stack to load : returns : A CallStack previously built in the context of a patch call . : rtype : caliendo . hooks . CallSt...
global CACHE_ load_cache ( True ) key = "{0}.{1}" . format ( stack . module , stack . caller ) if key in CACHE_ [ 'stacks' ] : return pickle . loads ( CACHE_ [ 'stacks' ] [ key ] )
def get_dependency_metadata ( ) : '''Returns list of strings with dependency metadata from Dapi'''
link = os . path . join ( _api_url ( ) , 'meta.txt' ) return _process_req_txt ( requests . get ( link ) ) . split ( '\n' )
def _elapsed_time ( begin_time , end_time ) : """Assuming format YYYY - MM - DD hh : mm : ss Returns the elapsed time in seconds"""
bt = _str2datetime ( begin_time ) et = _str2datetime ( end_time ) return float ( ( et - bt ) . seconds )
def wait_stop ( self ) : """Stop the stream and wait for it to stop . See : meth : ` stop ` for the general stopping conditions . You can assume that : meth : ` stop ` is the first thing this coroutine calls ."""
if not self . running : return self . stop ( ) try : yield from self . _task except asyncio . CancelledError : pass
def unique ( input_list ) : """Return a list of unique items ( similar to set functionality ) . Parameters input _ list : list A list containg some items that can occur more than once . Returns list A list with only unique occurances of an item ."""
output = [ ] for item in input_list : if item not in output : output . append ( item ) return output
def on_before_transform_resource ( self , logical_id , resource_type , resource_properties ) : """Hook method that gets called before " each " SAM resource gets processed : param string logical _ id : Logical ID of the resource being processed : param string resource _ type : Type of the resource being processe...
if not self . _is_supported ( resource_type ) : return function_policies = FunctionPolicies ( resource_properties , self . _policy_template_processor ) if len ( function_policies ) == 0 : # No policies to process return result = [ ] for policy_entry in function_policies . get ( ) : if policy_entry . type is...
def generate_overlay_urls ( self ) : """Return dict with overlay / URL pairs for the dataset overlays ."""
overlays = { } for o in self . dataset . list_overlay_names ( ) : url = self . generate_url ( ".dtool/overlays/{}.json" . format ( o ) ) overlays [ o ] = url return overlays
def parse_log_line ( line ) : """Parses a log line and returns it with more information : param line : str - A line from a bcbio - nextgen log : returns dict : A dictionary containing the line , if its a new step if its a Traceback or if the analysis is finished"""
matches = re . search ( r'^\[([^\]]+)\] ([^:]+: .*)' , line ) error = re . search ( r'Traceback' , line ) if error : return { 'line' : line , 'step' : 'error' } if not matches : return { 'line' : line , 'step' : None } tstamp = matches . group ( 1 ) msg = matches . group ( 2 ) if not msg . find ( 'Timing: ' ) >...
def get_config_filename ( metadata ) : """Derive a configuration file name from the FOO _ SETTINGS environment variable ."""
envvar = "{}__SETTINGS" . format ( underscore ( metadata . name ) . upper ( ) ) try : return environ [ envvar ] except KeyError : return None
def init_with_context ( self , context ) : """Initializes the icon list ."""
super ( AppIconList , self ) . init_with_context ( context ) apps = self . children # Standard model only has a title , change _ url and add _ url . # Restore the app _ name and name , so icons can be matched . for app in apps : app_name = self . _get_app_name ( app ) app [ 'name' ] = app_name for model in ...
def write_table ( self , d ) : """Write out a Python dictionary made of up string keys , and values that are strings , signed integers , Decimal , datetime . datetime , or sub - dictionaries following the same constraints ."""
# HACK : encoding of AMQP tables is broken because it requires the # length of the / encoded / data instead of the number of items . To # support streaming , fiddle with cursor position , rewinding to write # the real length of the data . Generally speaking , I ' m not a fan of # the AMQP encoding scheme , it could be ...
def project_set_properties ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / project - xxxx / setProperties API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Projects # API - method % 3A - % 2Fproject - xxxx % 2FsetPropertie...
return DXHTTPRequest ( '/%s/setProperties' % object_id , input_params , always_retry = always_retry , ** kwargs )
def safe_translation_getter ( self , field , default = None , language_code = None , any_language = False ) : """Fetch a translated property , and return a default value when both the translation and fallback language are missing . When ` ` any _ language = True ` ` is used , the function also looks into othe...
meta = self . _parler_meta . _get_extension_by_field ( field ) # Extra feature : query a single field from a other translation . if language_code and language_code != self . _current_language : try : tr_model = self . _get_translated_model ( language_code , meta = meta , use_fallback = True ) return...
def split_text ( text : str , length : int = MAX_MESSAGE_LENGTH ) -> typing . List [ str ] : """Split long text : param text : : param length : : return : list of parts : rtype : : obj : ` typing . List [ str ] `"""
return [ text [ i : i + length ] for i in range ( 0 , len ( text ) , length ) ]
def complist ( self ) : """Return a list of all components and sub - components . This is for use with : py : meth : ` ~ object . _ _ iter _ _ ` ."""
ans = [ ] for comp in ( self . component1 , self . component2 ) : try : ans . extend ( comp . complist ( ) ) except AttributeError : ans . append ( comp ) return ans
def create_keypair ( self , keypair_name ) : """Create a new 2048 bit RSA key pair and return a unique ID that can be used to reference the created key pair when launching new instances ."""
query = self . query_factory ( action = "CreateKeyPair" , creds = self . creds , endpoint = self . endpoint , other_params = { "KeyName" : keypair_name } ) d = query . submit ( ) return d . addCallback ( self . parser . create_keypair )
def show ( self , xlim = None , ylim = None , units = "thz" ) : """Show the plot using matplotlib . Args : xlim : Specifies the x - axis limits . Set to None for automatic determination . ylim : Specifies the y - axis limits . units : units for the frequencies . Accepted values thz , ev , mev , ha , cm - ...
plt = self . get_plot ( xlim , ylim , units = units ) plt . show ( )
def set_attr ( self , attr , value , selection = None ) : """Sets attr of current selection to value"""
if selection is None : selection = self . grid . selection if not selection : # Add current cell to selection so that it gets changed selection . cells . append ( self . grid . actions . cursor [ : 2 ] ) attrs = { attr : value } table = self . grid . current_table # Change model self . _set_cell_attr ( selectio...
async def SetStatusMessage ( self , message ) : '''message : str Returns - > None'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'MigrationMaster' , request = 'SetStatusMessage' , version = 1 , params = _params ) _params [ 'message' ] = message reply = await self . rpc ( msg ) return reply
def RemoveForwardedIp ( self , address , interface ) : """Delete an IP address on the network interface . Args : address : string , the IP address to configure . interface : string , the output device to use ."""
ip = netaddr . IPNetwork ( address ) self . _RunIfconfig ( args = [ interface , '-alias' , str ( ip . ip ) ] )
def get_or_add ( self , reltype , target_part ) : """Return relationship of * reltype * to * target _ part * , newly added if not already present in collection ."""
rel = self . _get_matching ( reltype , target_part ) if rel is None : rId = self . _next_rId rel = self . add_relationship ( reltype , target_part , rId ) return rel
def clone ( self , name = None ) : """Returns a cloned ` _ ConvND ` module . Args : name : Optional string assigning name of cloned module . The default name is constructed by appending " _ clone " to ` self . module _ name ` . Returns : A copy of the current class ."""
if name is None : name = self . module_name + "_clone" return type ( self ) ( output_channels = self . output_channels , kernel_shape = self . _kernel_shape , stride = self . _stride , rate = self . _rate , padding = self . _padding , use_bias = self . _use_bias , initializers = self . _initializers , partitioners ...
def rot_points ( pnts , pb , alfa ) : """Rotate a list of points by an angle alfa ( radians ) around pivotal point pb . Intended for modifying the control points of trigonometric functions ."""
points = [ ] # rotated points calfa = math . cos ( alfa ) salfa = math . sin ( alfa ) for p in pnts : s = p - pb r = abs ( s ) if r > 0 : s /= r np = ( s . x * calfa - s . y * salfa , s . y * calfa + s . x * salfa ) points . append ( pb + fitz . Point ( np ) * r ) return points
import math def calculate_cone_surface_area ( radius , height ) : """This function calculates the surface area of a cone given the radius and height . Example : calculate _ cone _ surface _ area ( 5 , 12 ) - > 282.7433388230814 calculate _ cone _ surface _ area ( 10 , 15 ) - > 880.5179353159282 calculate _ ...
slant_height = math . sqrt ( ( radius ** 2 ) + ( height ** 2 ) ) surface_area = ( math . pi * radius * ( radius + slant_height ) ) return surface_area
def extract_status ( self , status_headers ) : """Extract status code only from status line"""
self [ 'status' ] = status_headers . get_statuscode ( ) if not self [ 'status' ] : self [ 'status' ] = '-' elif self [ 'status' ] == '204' and 'Error' in status_headers . statusline : self [ 'status' ] = '-'
def create ( context , name , country , active , parent_id ) : """create ( context , name , country , active , parent _ id ) Create a team . > > > dcictl team - create [ OPTIONS ] : param string name : Name of the team [ required ] : param string country : Country code where the team is based : param bool...
state = utils . active_string ( active ) result = team . create ( context , name = name , country = country , state = state , parent_id = parent_id ) utils . format_output ( result , context . format )
def AddFrequencyObject ( self , frequency , problem_reporter ) : """Add a Frequency object to this trip ' s list of Frequencies ."""
if frequency is not None : self . AddFrequency ( frequency . StartTime ( ) , frequency . EndTime ( ) , frequency . HeadwaySecs ( ) , frequency . ExactTimes ( ) , problem_reporter )
def detect_intent_with_model_selection ( project_id , session_id , audio_file_path , language_code ) : """Returns the result of detect intent with model selection on an audio file as input Using the same ` session _ id ` between requests allows continuation of the conversaion ."""
import dialogflow_v2beta1 as dialogflow session_client = dialogflow . SessionsClient ( ) # Note : hard coding audio _ encoding and sample _ rate _ hertz for simplicity . audio_encoding = dialogflow . enums . AudioEncoding . AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 16000 session_path = session_client . session_path ...
def parse_yaml_config ( yaml_config , repo_home ) : """Converts a dictionary ( parsed Yaml ) to the internal representation ."""
config = collections . defaultdict ( list ) variables = { 'DEFAULT_CONFIGS' : os . path . join ( os . path . dirname ( __file__ ) , 'configs' ) , 'REPO_HOME' : repo_home , } for name , data in yaml_config . items ( ) : command = _replace_variables ( [ data [ 'command' ] ] , variables ) [ 0 ] requirements = _rep...
def as_text ( self ) : """Return a textual representation of this key ."""
if self . secret_exponent ( ) : return self . wif ( ) sec_hex = self . sec_as_hex ( ) if sec_hex : return sec_hex return self . address ( )
def strftime ( self , fmt ) : """Format using strftime ( ) . The date part of the timestamp passed to underlying strftime should not be used ."""
# The year must be > = 1000 else Python ' s strftime implementation # can raise a bogus exception . timetuple = ( 1900 , 1 , 1 , self . _hour , self . _minute , self . _second , 0 , 1 , - 1 ) return _wrap_strftime ( self , fmt , timetuple )
def inspect_node ( nlinks , unariesalt , msinds , node_msindex ) : """Get information about one node in graph : param nlinks : neighboorhood edges : param unariesalt : weights : param msinds : indexes in 3d image : param node _ msindex : msindex of selected node . See get _ node _ msindex ( ) : return : n...
node_unariesalt = unariesalt [ node_msindex ] neigh_edges , neigh_seeds = inspect_node_neighborhood ( nlinks , msinds , node_msindex ) return node_unariesalt , neigh_edges , neigh_seeds
def find_atoms_near_atom ( self , source_atom , search_radius , atom_hit_cache = set ( ) , atom_names_to_include = set ( ) , atom_names_to_exclude = set ( ) , restrict_to_CA = False ) : '''It is advisable to set up and use an atom hit cache object . This reduces the number of distance calculations and gives better ...
if len ( atom_names_to_include ) > 0 and len ( atom_names_to_exclude ) > 0 : raise Exception ( 'Error: either one of the set of atoms types to include or the set of atom types to exclude can be set but not both.' ) atom_names_to_exclude = set ( atom_names_to_exclude ) if atom_names_to_include : atom_names_to_ex...
def get ( self , url , params = None , cache_cb = None , ** kwargs ) : """Make http get request . : param url : : param params : : param cache _ cb : ( optional ) a function that taking requests . Response as input , and returns a bool flag , indicate whether should update the cache . : param cache _ expi...
if self . use_random_user_agent : headers = kwargs . get ( "headers" , dict ( ) ) headers . update ( { Headers . UserAgent . KEY : Headers . UserAgent . random ( ) } ) kwargs [ "headers" ] = headers url = add_params ( url , params ) cache_consumed , value = self . try_read_cache ( url ) if cache_consumed : ...
def get_db_state ( working_dir ) : """Callback to the virtual chain state engine . Get a * read - only * handle to our state engine implementation ( i . e . our name database ) . Note that in this implementation , the database handle returned will only support read - only operations by default . Attempts ...
impl = sys . modules [ __name__ ] db_inst = BlockstackDB . get_readonly_instance ( working_dir ) assert db_inst , 'Failed to instantiate database handle' return db_inst
def sum_biomass_weight ( reaction ) : """Compute the sum of all reaction compounds . This function expects all metabolites of the biomass reaction to have formula information assigned . Parameters reaction : cobra . core . reaction . Reaction The biomass reaction of the model under investigation . Retur...
return sum ( - coef * met . formula_weight for ( met , coef ) in iteritems ( reaction . metabolites ) ) / 1000.0
def datagram_received ( self , data , addr ) : """Method run when data is received from the devices This method will unpack the data according to the LIFX protocol . If a new device is found , the Light device will be created and started aa a DatagramProtocol and will be registered with the parent . : param...
response = unpack_lifx_message ( data ) response . ip_addr = addr [ 0 ] mac_addr = response . target_addr if mac_addr == BROADCAST_MAC : return if type ( response ) == StateService and response . service == 1 : # only look for UDP services # discovered remote_port = response . port elif type ( response ) == Lig...
def _determine_hpp_url ( self , platform , action ) : """This returns the Adyen HPP endpoint based on the provided platform , and action . Args : platform ( str ) : Adyen platform , ie ' live ' or ' test ' . action ( str ) : the HPP action to perform . possible actions : select , pay , skipDetails , direc...
base_uri = settings . BASE_HPP_URL . format ( platform ) service = action + '.shtml' result = '/' . join ( [ base_uri , service ] ) return result
def to_rfi ( data , channels = None , amplification_type = None , amplifier_gain = None , resolution = None ) : """Transform flow cytometry data to Relative Fluorescence Units ( RFI ) . If ` ` amplification _ type [ 0 ] ` ` is different from zero , data has been taken using a log amplifier . Therefore , to tran...
# Default : all channels if channels is None : channels = range ( data . shape [ 1 ] ) if not ( hasattr ( channels , '__iter__' ) and not isinstance ( channels , six . string_types ) ) : # If channels is not an iterable , convert it , along with resolution , # amplification _ type , and amplifier _ gain . chann...
def html_output_graph ( self , node ) : """Output the graph for HTML . This will insert a PNG with clickable image map ."""
graph = node [ 'graph' ] parts = node [ 'parts' ] graph_hash = get_graph_hash ( node ) name = "inheritance%s" % graph_hash path = '_images' dest_path = os . path . join ( setup . app . builder . outdir , path ) if not os . path . exists ( dest_path ) : os . makedirs ( dest_path ) png_path = os . path . join ( dest_...
def get_acl ( self , request ) : """Get ACL . Initialize the _ _ acl _ _ from the sql database once , then use the cached version . : param request : pyramid request : type login : : class : ` pyramid . request . Request ` : return : ACLs in pyramid format . ( Allow , group name , permission name ) : rt...
if RootFactory . _acl is None : acl = [ ] session = DBSession ( ) groups = Group . all ( session ) for g in groups : acl . extend ( [ ( Allow , g . name , p . name ) for p in g . permissions ] ) RootFactory . _acl = acl return RootFactory . _acl
def delete ( self , value , key ) : """Delete a value from a tree ."""
# Base case : The empty tree cannot possibly have the desired value . if self is NULL : raise KeyError ( value ) direction = cmp ( key ( value ) , key ( self . value ) ) # Because we lean to the left , the left case stands alone . if direction < 0 : if ( not self . left . red and self . left is not NULL and not...
async def two ( s : Sublemon ) : """Spin up some subprocesses , sleep , and echo a message for this coro ."""
subprocess_1 , subprocess_2 = s . spawn ( 'sleep 1 && echo subprocess 1 in coroutine two' , 'sleep 1 && echo subprocess 2 in coroutine two' ) async for line in amerge ( subprocess_1 . stdout , subprocess_2 . stdout ) : print ( line . decode ( 'utf-8' ) , end = '' )
def master_srcmdl_xml ( self , ** kwargs ) : """return the name of a source model file"""
kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) localpath = NameFactory . master_srcmdl_xml_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpath ) return localpath
def intent_path ( cls , project , intent ) : """Return a fully - qualified intent string ."""
return google . api_core . path_template . expand ( 'projects/{project}/agent/intents/{intent}' , project = project , intent = intent , )
def username_encryption_level ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) username = ET . SubElement ( config , "username" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" ) name_key = ET . SubElement ( username , "name" ) name_key . text = kwargs . pop ( 'name' ) encryption_level = ET . SubElement ( username , "encryption-level" ) encryption_level . text = kwa...
def temporal_closeness_centrality ( tnet = None , paths = None ) : '''Returns temporal closeness centrality per node . Parameters Input should be * either * tnet or paths . data : array or dict Temporal network input ( graphlet or contact ) . nettype : ' bu ' , ' bd ' . paths : pandas dataframe Output o...
if tnet is not None and paths is not None : raise ValueError ( 'Only network or path input allowed.' ) if tnet is None and paths is None : raise ValueError ( 'No input.' ) # if shortest paths are not calculated , calculate them if tnet is not None : paths = shortest_temporal_path ( tnet ) pathmat = np . zer...
def dotcall ( name , * args , ** kwargs ) : """Creates a function that accepts an object and invokes a member function ( a " method " ) on it . The object can be a class instance , a class , a type , or even a module . : param name : Name of member function to invoke The rest of positional and keyword argum...
ensure_string ( name ) get_member_func = attr_func ( name ) def call ( obj ) : member_func = ensure_callable ( get_member_func ( obj ) ) return member_func ( * args , ** kwargs ) # through : func : ` attr _ func ` , we may support ` ` name ` ` containing dots , # but we need to turn it into valid Python identif...
def get_meta ( filepath ) : """Get meta - information of an image . Parameters filepath : str Returns meta : dict"""
meta = { } try : from PIL import Image with Image . open ( filepath ) as img : width , height = img . size meta [ 'width' ] = width meta [ 'height' ] = height meta [ 'channels' ] = len ( img . mode ) # RGB , RGBA - does this always work ? except ImportError : pass # Get times - creat...
def put ( self , url , html , cache_info = None ) : """Put response into cache : param url : Url to cache : type url : str | unicode : param html : HTML content of url : type html : str | unicode : param cache _ info : Cache Info ( default : None ) : type cache _ info : floscraper . models . CacheInfo ...
key = hashlib . md5 ( url ) . hexdigest ( ) try : self . _cache_set ( key , html ) except : self . exception ( "Failed to write cache" ) return self . update ( url , cache_info )
def bulkWrite ( self , endpoint , buffer , timeout = 100 ) : r"""Perform a bulk write request to the endpoint specified . Arguments : endpoint : endpoint number . buffer : sequence data buffer to write . This parameter can be any sequence type . timeout : operation timeout in milliseconds . ( default : 10...
return self . dev . write ( endpoint , buffer , timeout )
def compiler_info ( compiler ) : """Determine the name + version of the compiler"""
( out , err ) = subprocess . Popen ( [ '/bin/sh' , '-c' , '{0} -v' . format ( compiler ) ] , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( '' ) gcc_clang = re . compile ( '(gcc|clang) version ([0-9]+(\\.[0-9]+)*)' ) for line in ( out + err ) . split ( '\n' ) : ...
def clean ( self ) : """* clean up and run some maintance tasks on the crossmatch catalogue helper tables * . . todo : : - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exi...
self . log . debug ( 'starting the ``get`` method' ) self . _update_tcs_helper_catalogue_tables_info_with_new_tables ( ) self . _updated_row_counts_in_tcs_helper_catalogue_tables_info ( ) self . _clean_up_columns ( ) self . _update_tcs_helper_catalogue_views_info_with_new_views ( ) self . _clean_up_columns ( ) self . _...
def apply_config_changes ( before_editing , data , kvpairs ) : """Applies config changes specified as a list of key - value pairs . Keys are interpreted as dotted paths into the configuration data structure . Except for paths beginning with ` postgresql . parameters ` where rest of the path is used directly to ...
changed_data = copy . deepcopy ( data ) def set_path_value ( config , path , value , prefix = ( ) ) : # Postgresql GUCs can ' t be nested , but can contain dots so we re - flatten the structure for this case if prefix == ( 'postgresql' , 'parameters' ) : path = [ '.' . join ( path ) ] key = path [ 0 ] ...
def add_students ( self , student_emails , nid = None ) : """Enroll students in a network ` nid ` . Piazza will email these students with instructions to activate their account . : type student _ emails : list of str : param student _ emails : A listing of email addresses to enroll in the network ( or cla...
r = self . request ( method = "network.update" , data = { "from" : "ClassSettingsPage" , "add_students" : student_emails } , nid = nid , nid_key = "id" ) return self . _handle_error ( r , "Could not add users." )
def _get_final_none_policy_for_validator ( is_nonable , # type : bool none_policy # type : NoneArgPolicy ) : """Depending on none _ policy and of the fact that the target parameter is nonable or not , returns a corresponding NonePolicy : param is _ nonable : : param none _ policy : : return :"""
if none_policy in { NonePolicy . VALIDATE , NonePolicy . SKIP , NonePolicy . FAIL } : none_policy_to_use = none_policy elif none_policy is NoneArgPolicy . SKIP_IF_NONABLE_ELSE_VALIDATE : none_policy_to_use = NonePolicy . SKIP if is_nonable else NonePolicy . VALIDATE elif none_policy is NoneArgPolicy . SKIP_IF_N...
def add_time_features ( self , year = False , month = False , week = True , tod = True , dow = True ) : """Add time features to dataframe . Parameters year : bool Year . month : bool Month . week : bool Week . tod : bool Time of Day . dow : bool Day of Week ."""
var_to_expand = [ ] if self . preprocessed_data . empty : data = self . original_data else : data = self . preprocessed_data if year : data [ "year" ] = data . index . year var_to_expand . append ( "year" ) if month : data [ "month" ] = data . index . month var_to_expand . append ( "month" ) if ...
def app_data ( self , org_name , prod_name ) : '''a method to retrieve the os appropriate path to user app data # https : / / www . chromium . org / user - experience / user - data - directory : param org _ name : string with name of product / service creator : param prod _ name : string with name of product ...
__name__ = '%s.app_data' % self . __class__ . __name__ # validate inputs org_name = self . fields . validate ( org_name , '.org_name' ) prod_name = self . fields . validate ( prod_name , '.prod_name' ) # construct empty fields data_path = '' # construct path from os if self . os . sysname == 'Windows' : from re imp...
def list_actions ( name , location = '\\' ) : r'''List all actions that pertain to a task in the specified location . : param str name : The name of the task for which list actions . : param str location : A string value representing the location of the task from which to list actions . Default is ' \ \ ' whi...
# Create the task service object with salt . utils . winapi . Com ( ) : task_service = win32com . client . Dispatch ( "Schedule.Service" ) task_service . Connect ( ) # Get the folder to list folders from task_folder = task_service . GetFolder ( location ) task_definition = task_folder . GetTask ( name ) . Definitio...
def _check_encoding ( name , encoding_to_check , alternative_encoding , source = None ) : """Check that ` ` encoding ` ` is a valid Python encoding : param name : name under which the encoding is known to the user , e . g . ' default encoding ' : param encoding _ to _ check : name of the encoding to check , e ....
assert name is not None if encoding_to_check not in ( alternative_encoding , 'chardet' , None ) : try : '' . encode ( encoding_to_check ) except LookupError : raise pygount . common . OptionError ( '{0} is "{1}" but must be "{2}" or a known Python encoding' . format ( name , encoding_to_check , ...
def getClassInModuleFromName ( className , module ) : """get a class from name within a module"""
n = getAvClassNamesInModule ( module ) i = n . index ( className ) c = getAvailableClassesInModule ( module ) return c [ i ]
def random_cohort ( size , cache_dir , data_dir = None , min_random_variants = None , max_random_variants = None , seed_val = 1234 ) : """Parameters min _ random _ variants : optional , int Minimum number of random variants to be generated per patient . max _ random _ variants : optional , int Maximum numbe...
seed ( seed_val ) d = { } d [ "id" ] = [ str ( id ) for id in range ( size ) ] d [ "age" ] = choice ( [ 10 , 15 , 28 , 32 , 59 , 62 , 64 , 66 , 68 ] , size ) d [ "smoker" ] = choice ( [ False , True ] , size ) d [ "OS" ] = [ randint ( 10 , 1000 ) for i in range ( size ) ] d [ "PFS" ] = [ int ( os * 0.6 ) for os in d [ ...
def vsenqueue ( trg_queue , item_s , args , ** kwargs ) : '''Enqueue a string , or string - like object to queue with arbitrary arguments , vsenqueue is to venqueue what vsprintf is to vprintf , vsenqueue is to senqueue what vsprintf is to sprintf .'''
charset = kwargs . get ( 'charset' , _c . FSQ_CHARSET ) if kwargs . has_key ( 'charset' ) : del kwargs [ 'charset' ] # we coerce here because StringIO . StringIO will coerce on file - write , # and cStringIO . StringIO has a bug which injects NULs for unicode if isinstance ( item_s , unicode ) : try : i...
def filter ( self , track = None , follow = None , locations = None , event = None , record_keepalive = False ) : """Returns an iterator for tweets that match a given filter track from the livestream of tweets happening right now . If a threading . Event is provided for event and the event is set , the filter...
if locations is not None : if type ( locations ) == list : locations = ',' . join ( locations ) locations = locations . replace ( '\\' , '' ) url = 'https://stream.twitter.com/1.1/statuses/filter.json' params = { "stall_warning" : True , "include_ext_alt_text" : True } if track : params [ "track" ] ...
def _button_autosave_clicked ( self , checked ) : """Called whenever the button is clicked ."""
if checked : # get the path from the user path = _spinmob . dialogs . save ( filters = self . file_type ) # abort if necessary if not path : self . button_autosave . set_checked ( False ) return # otherwise , save the info ! self . _autosave_directory , filename = _os . path . split ...
def tempDir ( self ) : """Shortcut to calling : func : ` job . fileStore . getLocalTempDir ` . Temp dir is created on first call and will be returned for first and future calls : return : Path to tempDir . See ` job . fileStore . getLocalTempDir ` : rtype : str"""
if self . _tempDir is None : self . _tempDir = self . _fileStore . getLocalTempDir ( ) return self . _tempDir
def adhan ( day , location , parameters , timezone_offset = 0 ) : """Calculate adhan times given the parameters . This function will compute the adhan times for a certain location on certain day . The method for calculating the prayers as well as the time for Asr can also be specified . The timezone offset na...
latitude , longitude = location # To reduce a little repetitiveness , using a partial function that has the # day and latitude already set time_at_sun_angle = partial ( compute_time_at_sun_angle , day = day , latitude = latitude ) zuhr_time = compute_zuhr_utc ( day , longitude ) shuruq_time = zuhr_time - time_at_sun_an...
def ignore_sphinx ( ) : """Register Sphinx directives and roles to ignore ."""
( directives , roles ) = _get_directives_and_roles_from_sphinx ( ) directives += [ 'centered' , 'include' , 'deprecated' , 'index' , 'no-code-block' , 'literalinclude' , 'hlist' , 'seealso' , 'toctree' , 'todo' , 'versionadded' , 'versionchanged' ] ext_autosummary = [ 'autosummary' , 'currentmodule' , ] ignore_directiv...
def highestMax ( requestContext , seriesList , n = 1 ) : """Takes one metric or a wildcard seriesList followed by an integer N . Out of all metrics passed , draws only the N metrics with the highest maximum value in the time period specified . Example : : & target = highestMax ( server * . instance * . thre...
result_list = sorted ( seriesList , key = lambda s : safeMax ( s ) ) [ - n : ] return sorted ( result_list , key = lambda s : max ( s ) , reverse = True )
def pretty_format_table ( labels , data , num_format = "{:.3f}" , line_separator = "\n" ) : """Parses and creates pretty table : param labels : List of labels of data : param data : Matrix of any type : param num _ format : Format numbers with this format : param line _ separator : Separate each new line wi...
table = SqlTable ( labels , data , num_format , line_separator ) return table . build ( )
def _convert_to_floats ( self , data ) : """Convert all values in a dict to floats"""
for key , value in data . items ( ) : data [ key ] = float ( value ) return data
def get_next_invalid_day ( self , timestamp ) : # pylint : disable = no - else - return """Get next day where timerange is not active : param timestamp : time we compute from : type timestamp : int : return : timestamp of the next invalid day ( midnight ) in LOCAL time . : rtype : int | None"""
if self . is_time_day_invalid ( timestamp ) : return timestamp next_future_timerange_invalid = self . get_next_future_timerange_invalid ( timestamp ) # If today there is no more unavailable timerange , search the next day if next_future_timerange_invalid is None : # this day is finish , we check for next period ...
def get_index ( lis , argument ) : """Find the index of an item , given either the item or index as an argument . Particularly useful as a wrapper for arguments like channel or axis . Parameters lis : list List to parse . argument : int or object Argument . Returns int Index of chosen object ."""
# get channel if isinstance ( argument , int ) : if - len ( lis ) <= argument < len ( lis ) : return argument else : raise IndexError ( "index {0} incompatible with length {1}" . format ( argument , len ( lis ) ) ) else : return lis . index ( argument )
def get_subset_in_chemsys ( self , chemsys : List [ str ] ) : """Returns an EntrySet containing only the set of entries belonging to a particular chemical system ( in this definition , it includes all sub systems ) . For example , if the entries are from the Li - Fe - P - O system , and chemsys = [ " Li " , "...
chemsys = set ( chemsys ) if not chemsys . issubset ( self . chemsys ) : raise ValueError ( "%s is not a subset of %s" % ( chemsys , self . chemsys ) ) subset = set ( ) for e in self . entries : elements = [ sp . symbol for sp in e . composition . keys ( ) ] if chemsys . issuperset ( elements ) : su...
def put_directory ( self , target_path , local_directory , ** kwargs ) : """Upload a directory with all its contents : param target _ path : path of the directory to upload into : param local _ directory : path to the local directory to upload : param \ * \ * kwargs : optional arguments that ` ` put _ file ` ...
target_path = self . _normalize_path ( target_path ) if not target_path . endswith ( '/' ) : target_path += '/' gathered_files = [ ] if not local_directory . endswith ( '/' ) : local_directory += '/' basedir = os . path . basename ( local_directory [ 0 : - 1 ] ) + '/' # gather files to upload for path , _ , fil...
def cfg_intf ( self , protocol_interface , phy_interface = None ) : """Called by application to add an interface to the list ."""
self . intf_list . append ( protocol_interface ) self . cfg_lldp_interface ( protocol_interface , phy_interface )
def get_key ( keyid = None , fingerprint = None , user = None , gnupghome = None ) : '''Get a key from the GPG keychain keyid The key ID ( short or long ) of the key to be retrieved . fingerprint The fingerprint of the key to be retrieved . user Which user ' s keychain to access , defaults to user Salt ...
tmp = { } for _key in _list_keys ( user , gnupghome ) : if ( _key [ 'fingerprint' ] == fingerprint or _key [ 'keyid' ] == keyid or _key [ 'keyid' ] [ 8 : ] == keyid ) : tmp [ 'keyid' ] = _key [ 'keyid' ] tmp [ 'fingerprint' ] = _key [ 'fingerprint' ] tmp [ 'uids' ] = _key [ 'uids' ] ...
def broadcast ( cast , onto , cast_on = None , onto_on = None , cast_index = False , onto_index = False ) : """Register a rule for merging two tables by broadcasting one onto the other . Parameters cast , onto : str Names of registered tables . cast _ on , onto _ on : str , optional Column names used fo...
logger . debug ( 'registering broadcast of table {!r} onto {!r}' . format ( cast , onto ) ) _BROADCASTS [ ( cast , onto ) ] = Broadcast ( cast , onto , cast_on , onto_on , cast_index , onto_index )
def write_fieldtrip ( data , filename ) : """Export data to FieldTrip . Parameters data : instance of ChanTime data with only one trial filename : path to file file to export to ( include ' . mat ' ) Notes It saves mat file using Version 6 ( ' - v7 ' ) because it relies on scipy . io functions . The...
n_trl = data . number_of ( 'trial' ) trial = empty ( n_trl , dtype = 'O' ) time = empty ( n_trl , dtype = 'O' ) for trl in range ( n_trl ) : trial [ trl ] = data . data [ trl ] time [ trl ] = data . axis [ 'time' ] [ trl ] ft_data = { 'fsample' : float ( data . s_freq ) , 'label' : data . axis [ 'chan' ] [ 0 ] ...
def setBaseLocale ( self , locale ) : """Sets the base locale that is used with in this widget . All displayed information will be translated to this locale . : param locale | < str >"""
locale = str ( locale ) if self . _baseLocale == locale : return try : babel . Locale . parse ( locale ) except ( babel . UnknownLocaleError , StandardError ) : return False self . _baseLocale = locale self . setCurrentLocale ( locale ) self . setDirty ( ) return True
def get_parameters ( self , prior_type = 'BDeu' , equivalent_sample_size = 5 , pseudo_counts = None ) : """Method to estimate the model parameters ( CPDs ) . Parameters prior _ type : ' dirichlet ' , ' BDeu ' , or ' K2' string indicting which type of prior to use for the model parameters . - If ' prior _ ty...
parameters = [ ] for node in self . model . nodes ( ) : _equivalent_sample_size = equivalent_sample_size [ node ] if isinstance ( equivalent_sample_size , dict ) else equivalent_sample_size _pseudo_counts = pseudo_counts [ node ] if pseudo_counts else None cpd = self . estimate_cpd ( node , prior_type = pri...
def list_source_code ( self , context : int = 5 ) -> None : """Show source code around the current trace frame location . Parameters : context : int number of lines to show above and below trace location ( default : 5)"""
self . _verify_entrypoint_selected ( ) current_trace_frame = self . trace_tuples [ self . current_trace_frame_index ] . trace_frame filename = os . path . join ( self . repository_directory , current_trace_frame . filename ) file_lines : List [ str ] = [ ] try : # Use readlines instead of enumerate ( file ) because moc...
async def end ( self ) : """Coroutine to end stream from the client - side . It should be used to finally end stream from the client - side when we ' re finished sending messages to the server and stream wasn ' t closed with last DATA frame . See : py : meth : ` send _ message ` for more details . HTTP / 2 ...
if self . _end_done : raise ProtocolError ( 'Stream was already ended' ) if ( not self . _cardinality . client_streaming and not self . _send_message_count ) : raise ProtocolError ( 'Unary request requires a single message ' 'to be sent' ) await self . _stream . end ( ) self . _end_done = True
def _interval_sum ( interval , start = None , end = None , context = None ) : """Return sum of intervals between " R " esume and " P " aused events in C { interval } , optionally limited by a time window defined by C { start } and C { end } . Return ` ` None ` ` if there ' s no sensible information . C { in...
end = float ( end ) if end else time . time ( ) events = _interval_split ( interval , context = context ) result = [ ] # # import sys ; print > > sys . stderr , " ! ! ! ! ! isum " , interval . fetch ( " custom _ activations " ) , events , start , end while events : event , resumed = events . pop ( ) # # print "...
def reinstall ( self ) : """Reinstalls the manhole . Checks if the thread is running . If not , it starts it again ."""
with _LOCK : if not ( self . thread . is_alive ( ) and self . thread in _ORIGINAL__ACTIVE ) : self . thread = self . thread . clone ( bind_delay = self . reinstall_delay ) if self . should_restart : self . thread . start ( )
def from_yaml ( cls , path ) : """Return an instance from a YAML file ."""
import yaml with path . open ( mode = 'r' ) as fp : source = yaml . safe_load ( fp ) or { } self = cls . from_jsonld ( source , __reference__ = path , __source__ = deepcopy ( source ) , ) return self
def from_dict ( data , ctx ) : """Instantiate a new OpenTradeFinancing from a dict ( generally from loading a JSON response ) . The data used to instantiate the OpenTradeFinancing is a shallow copy of the dict passed in , with any complex child types instantiated appropriately ."""
data = data . copy ( ) if data . get ( 'financing' ) is not None : data [ 'financing' ] = ctx . convert_decimal_number ( data . get ( 'financing' ) ) return OpenTradeFinancing ( ** data )
def GetViewCollection ( self ) : """Get Views for Current List This is run in _ _ init _ _ so you don ' t have to run it again . Access from self . views"""
# Build Request soap_request = soap ( 'GetViewCollection' ) soap_request . add_parameter ( 'listName' , self . listName ) self . last_request = str ( soap_request ) # Send Request response = self . _session . post ( url = self . _url ( 'Views' ) , headers = self . _headers ( 'GetViewCollection' ) , data = str ( soap_re...
def buildResourceFile ( rscpath , outpath = '' ) : """Generates a Qt resource module based on the given source path . This will take all the files and folders within the source and generate a new XML representation of that path . An optional outpath can be provided as the generated resource path , by default ...
import xqt wrapper = QT_WRAPPER . lower ( ) if not outpath : name = os . path . basename ( rscpath ) . split ( '.' ) [ 0 ] filename = '{0}_{1}_rc.py' . format ( wrapper , name ) outpath = os . path . join ( os . path . dirname ( rscpath ) , filename ) elif os . path . isdir ( outpath ) : name = os . pat...
def create_folder ( self , dir_name ) : """创建目录 ( https : / / www . qcloud . com / document / product / 436/6061) : param dir _ name : 要创建的目录的目录的名称 : return 返回True创建成功 , 返回False创建失败"""
if dir_name [ 0 ] == '/' : dir_name = dir_name [ 1 : len ( dir_name ) ] self . url = "http://<Region>.file.myqcloud.com" + "/files/v2/<appid>/<bucket_name>/<dir_name>/" self . url = self . url . replace ( "<Region>" , self . config . region ) . replace ( "<appid>" , str ( self . config . app_id ) ) self . url = str...
def pomodoro ( self ) : """Pomodoro response handling and countdown"""
if not self . _initialized : self . _init ( ) cached_until = self . py3 . time_in ( 0 ) if self . _running : self . _time_left = ceil ( self . _end_time - time ( ) ) time_left = ceil ( self . _time_left ) else : time_left = ceil ( self . _time_left ) vals = { "ss" : int ( time_left ) , "mm" : int ( ceil...
def split_query ( query : str ) -> List [ str ] : """Split a query into different expressions . Example : name : bla , foo : < = 1"""
try : _query = query . strip ( ) except ( ValueError , AttributeError ) : raise QueryParserException ( 'query is not valid, received instead {}' . format ( query ) ) expressions = _query . split ( ',' ) expressions = [ exp . strip ( ) for exp in expressions if exp . strip ( ) ] if not expressions : raise Qu...
def help_version ( self ) : """Help and version info"""
if ( len ( self . args ) == 1 and self . args [ 0 ] in [ "-h" , "--help" ] and self . args [ 1 : ] == [ ] ) : options ( ) elif ( len ( self . args ) == 1 and self . args [ 0 ] in [ "-v" , "--version" ] and self . args [ 1 : ] == [ ] ) : prog_version ( ) else : usage ( "" )
def analyze ( self , A ) : """Analyzes structure of A . Parameters A : matrix For symmetric systems , should contain only lower diagonal part ."""
A = coo_matrix ( A ) self . mumps . set_shape ( A . shape [ 0 ] ) self . mumps . set_centralized_assembled_rows_cols ( A . row + 1 , A . col + 1 ) self . mumps . run ( job = 1 ) self . analyzed = True
def p_do_loop_while ( p ) : """statement : do _ start program _ co label _ loop WHILE expr | do _ start label _ loop WHILE expr | DO label _ loop WHILE expr"""
if len ( p ) == 6 : q = make_block ( p [ 2 ] , p [ 3 ] ) r = p [ 5 ] else : q = p [ 2 ] r = p [ 4 ] if p [ 1 ] == 'DO' : gl . LOOPS . append ( ( 'DO' , ) ) p [ 0 ] = make_sentence ( 'DO_WHILE' , r , q ) gl . LOOPS . pop ( ) if is_number ( r ) : api . errmsg . warning_condition_is_always ( p . li...
def get_jvm_path ( self ) : """Retrieves the path to the default or first found JVM library : return : The path to the JVM shared library file : raise ValueError : No JVM library found"""
for method in self . _methods : try : jvm = method ( ) # If found check the architecture if jvm : self . check ( jvm ) except NotImplementedError : # Ignore missing implementations pass except JVMNotFoundException : # Ignore not successful methods pass ...
def as_curve ( self , start = None , stop = None ) : """Get the synthetic as a Curve , in depth . Facilitates plotting along - side other curve data ."""
params = { 'start' : start or getattr ( self , 'z start' , None ) , 'mnemonic' : 'SYN' , 'step' : 0.1524 } return Curve ( data , params = params )
def get_trailerLinks ( self ) : """Returns dictionary with trailer names as keys and list of trailer urls as values . Each trailer can have more links due to different qualities . Example : { ' Trailer ' : [ ' url1 ' , ' url2 ' ] , ' Featurette ' : [ ' url1 ' , ' url2 ' ] }"""
if self . _trailerLinks : return self . _trailerLinks wip = WebIncParser ( "http://trailers.apple.com" + self . baseURL , "includes/playlists/web.inc" ) self . _trailerLinks = wip . getTrailers ( ) return self . _trailerLinks