signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def items_with_price ( raw_df ) : """Dataframe with price as number ."""
df = ( raw_df [ [ 'PRONAC' , 'idPlanilhaAprovacao' , 'Item' , 'idPlanilhaItens' , 'VlUnitarioAprovado' , 'idSegmento' , 'DataProjeto' , 'idPronac' , 'UfItem' , 'idProduto' , 'cdCidade' , 'cdEtapa' ] ] ) . copy ( ) df [ 'VlUnitarioAprovado' ] = df [ 'VlUnitarioAprovado' ] . apply ( pd . to_numeric ) return df
def handle_execution_mode ( self , container_state , next_child_state_to_execute = None ) : """Checks the current execution status and returns it . Depending on the execution state , the calling thread ( currently only hierarchy states ) waits for the execution to continue . If the execution mode is any of th...
self . state_counter_lock . acquire ( ) self . state_counter += 1 # logger . verbose ( " Increase state _ counter ! " + str ( self . state _ counter ) ) self . state_counter_lock . release ( ) woke_up_from_pause_or_step_mode = False if ( self . _status . execution_mode is StateMachineExecutionStatus . PAUSED ) or ( sel...
def get_toc ( text ) : """Extract Table of Content of MD : param text : : return :"""
mkd . convert ( text ) toc = mkd . toc mkd . reset ( ) return toc
def colors ( self , color_code ) : """Change the foreground and background colors for subsequently printed characters . None resets colors to their original values ( when class was instantiated ) . Since setting a color requires including both foreground and background codes ( merged ) , setting just the fore...
if color_code is None : color_code = WINDOWS_CODES [ '/all' ] # Get current color code . current_fg , current_bg = self . colors # Handle special negative codes . Also determine the final color code . if color_code == WINDOWS_CODES [ '/fg' ] : final_color_code = self . default_fg | current_bg # Reset the fo...
def add_command ( self , command , function , description = None ) : """Register a new function for command"""
super ( Program , self ) . add_command ( command , function , description ) self . service . register ( command , function )
def get_stp_brief_info_input_request_type_getnext_request_last_rcvd_instance_instance_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_stp_brief_info = ET . Element ( "get_stp_brief_info" ) config = get_stp_brief_info input = ET . SubElement ( get_stp_brief_info , "input" ) request_type = ET . SubElement ( input , "request-type" ) getnext_request = ET . SubElement ( request_type , "getnext-request" ) last_rcvd_in...
def _on_apply_button_clicked ( self , * args ) : """Apply button clicked : Apply the configuration"""
refresh_required = self . core_config_model . apply_preliminary_config ( ) refresh_required |= self . gui_config_model . apply_preliminary_config ( ) if not self . gui_config_model . config . get_config_value ( "SESSION_RESTORE_ENABLED" ) : import rafcon . gui . backup . session as backup_session logger . info ...
def refresh ( self ) : """Return a deferred ."""
d = self . request ( 'get' , self . instance_url ( ) ) return d . addCallback ( self . refresh_from ) . addCallback ( lambda _ : self )
def ec ( ns = None , cn = None , di = None , lo = None , iq = None , ico = None ) : # pylint : disable = redefined - outer - name """This function is a wrapper for : meth : ` ~ pywbem . WBEMConnection . EnumerateClasses ` . Enumerate the subclasses of a class , or the top - level classes in a namespace . Pa...
return CONN . EnumerateClasses ( ns , ClassName = cn , DeepInheritance = di , LocalOnly = lo , IncludeQualifiers = iq , IncludeClassOrigin = ico )
def confd_state_snmp_listen_udp_port ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" ) snmp = ET . SubElement ( confd_state , "snmp" ) listen = ET . SubElement ( snmp , "listen" ) udp = ET . SubElement ( listen , "udp" ) port = ET . SubElement ( udp , "port" ) po...
def _from_dict ( cls , _dict ) : """Initialize a IndexCapacity object from a json dictionary ."""
args = { } if 'documents' in _dict : args [ 'documents' ] = EnvironmentDocuments . _from_dict ( _dict . get ( 'documents' ) ) if 'disk_usage' in _dict : args [ 'disk_usage' ] = DiskUsage . _from_dict ( _dict . get ( 'disk_usage' ) ) if 'collections' in _dict : args [ 'collections' ] = CollectionUsage . _fro...
def _depend_on_lambda_permissions_using_tag ( self , bucket , permission ) : """Since conditional DependsOn is not supported this undocumented way of implicitely making dependency through tags is used . See https : / / stackoverflow . com / questions / 34607476 / cloudformation - apply - condition - on - depend...
properties = bucket . get ( 'Properties' , None ) if properties is None : properties = { } bucket [ 'Properties' ] = properties tags = properties . get ( 'Tags' , None ) if tags is None : tags = [ ] properties [ 'Tags' ] = tags dep_tag = { 'sam:ConditionalDependsOn:' + permission . logical_id : { 'Fn::I...
def convert_youtube_url ( youtube_url , no_controls , autoplay ) : """Use this function to convert the youtube URL . This function is used for converting the youtube URL so that it can be used correctly with Helium . It means that Helium will know the next video in the playlist . : param youtube _ url : the...
for section in youtube_url . split ( '&' ) : if 'list' in section : playlist_id = section . split ( 'list=' ) [ 1 ] break return ( 'https://www.youtube.com/embed/videoseries?{0}&{1}&' 'loop=1&html5=1&showinfo=0&listType=playlist&list={2}' . format ( '' if autoplay else 'autoplay=1' , 'controls=0' if...
def _intersperse_insertion_rows_and_columns ( self , pairwise_pvals ) : """Return pvals matrix with inserted NaN rows and columns , as numpy . ndarray . Each insertion ( a header or a subtotal ) creates an offset in the calculated pvals . These need to be taken into account when converting each pval to a corr...
for i in self . _insertion_indices : pairwise_pvals = np . insert ( pairwise_pvals , i , np . nan , axis = 0 ) pairwise_pvals = np . insert ( pairwise_pvals , i , np . nan , axis = 1 ) return pairwise_pvals
def rsync_roots ( self , gateway ) : """Rsync the set of roots to the node ' s gateway cwd ."""
if self . roots : for root in self . roots : self . rsync ( gateway , root , ** self . rsyncoptions )
def create_tasks_dict ( self , ast ) : '''Parse each " Task " in the AST . This will create self . tasks _ dictionary , where each task name is a key . : return : Creates the self . tasks _ dictionary necessary for much of the parser . Returning it is only necessary for unittests .'''
tasks = self . find_asts ( ast , 'Task' ) for task in tasks : self . parse_task ( task ) return self . tasks_dictionary
def remove_species ( self , species ) : """Remove all occurrences of a species from a molecule . Args : species : Species to remove ."""
new_sites = [ ] species = [ get_el_sp ( sp ) for sp in species ] for site in self . _sites : new_sp_occu = { sp : amt for sp , amt in site . species . items ( ) if sp not in species } if len ( new_sp_occu ) > 0 : new_sites . append ( Site ( new_sp_occu , site . coords , properties = site . properties ) ...
def encodeDNA ( seq_vec , maxlen = None , seq_align = "start" ) : """Convert the DNA sequence into 1 - hot - encoding numpy array # Arguments seq _ vec : list of chars List of sequences that can have different lengths maxlen : int or None , Should we trim ( subset ) the resulting sequence . If None don ' ...
return encodeSequence ( seq_vec , vocab = DNA , neutral_vocab = "N" , maxlen = maxlen , seq_align = seq_align , pad_value = "N" , encode_type = "one_hot" )
def inception_v3 ( pretrained = False , ctx = cpu ( ) , root = os . path . join ( base . data_dir ( ) , 'models' ) , ** kwargs ) : r"""Inception v3 model from ` " Rethinking the Inception Architecture for Computer Vision " < http : / / arxiv . org / abs / 1512.00567 > ` _ paper . Parameters pretrained : boo...
net = Inception3 ( ** kwargs ) if pretrained : from . . model_store import get_model_file net . load_parameters ( get_model_file ( 'inceptionv3' , root = root ) , ctx = ctx ) return net
def get_cache ( self , namespace , query_hash , length , start , end ) : """Get a cached value for the specified date range and query"""
query = 'SELECT start, value FROM gauged_cache WHERE namespace = ? ' 'AND hash = ? AND length = ? AND start BETWEEN ? AND ?' cursor = self . cursor cursor . execute ( query , ( namespace , query_hash , length , start , end ) ) return tuple ( cursor . fetchall ( ) )
def _upgrade_broker ( broker ) : """Extract the poller state from Broker and replace it with the industrial strength poller for this OS . Must run on the Broker thread ."""
# This function is deadly ! The act of calling start _ receive ( ) generates log # messages which must be silenced as the upgrade progresses , otherwise the # poller state will change as it is copied , resulting in write fds that are # lost . ( Due to LogHandler - > Router - > Stream - > Broker - > Poller , where Strea...
def _reset_connection_attributes ( self ) : """Reset connection attributes ."""
self . connection = None self . encoding = None self . _autojoin_channels = [ ] self . _reconnect_attempts = 0
def _load_id_or_insert ( self , session ) : """Load the id of the temporary context if it exists or return insert args . As a side effect , this also inserts the Context object for the stableid . : return : The record of the temporary context to insert . : rtype : dict"""
if self . id is None : stable_id = self . get_stable_id ( ) # Check if exists id = session . execute ( select ( [ Context . id ] ) . where ( Context . stable_id == stable_id ) ) . first ( ) # If not , insert if id is None : self . id = session . execute ( Context . __table__ . insert ( ) , {...
def convert_binary_to_int ( bin_tuple ) : """This function converts a binary represented as a tuple into its integer equivalent . > > > convert _ binary _ to _ int ( ( 1 , 1 , 0 , 1 , 0 , 0 , 1 ) ) '105' > > > convert _ binary _ to _ int ( ( 0 , 1 , 1 , 0 , 0 , 1 , 0 , 1 ) ) '101' > > > convert _ binary _...
result = int ( '' . join ( str ( bit ) for bit in bin_tuple ) , 2 ) return str ( result )
def is_all_field_none ( self ) : """: rtype : bool"""
if self . _monetary_account_id is not None : return False if self . _alias is not None : return False if self . _counterparty_alias is not None : return False if self . _amount_guaranteed is not None : return False if self . _amount_requested is not None : return False if self . _issuer is not None ...
def create ( self , from_ = values . unset , attributes = values . unset , date_created = values . unset , date_updated = values . unset , last_updated_by = values . unset , body = values . unset , media_sid = values . unset ) : """Create a new MessageInstance : param unicode from _ : The identity of the new mess...
data = values . of ( { 'From' : from_ , 'Attributes' : attributes , 'DateCreated' : serialize . iso8601_datetime ( date_created ) , 'DateUpdated' : serialize . iso8601_datetime ( date_updated ) , 'LastUpdatedBy' : last_updated_by , 'Body' : body , 'MediaSid' : media_sid , } ) payload = self . _version . create ( 'POST'...
def _has_valid_tuple ( self , key ) : """check the key for valid keys across my indexer"""
for i , k in enumerate ( key ) : if i >= self . obj . ndim : raise IndexingError ( 'Too many indexers' ) try : self . _validate_key ( k , i ) except ValueError : raise ValueError ( "Location based indexing can only have " "[{types}] types" . format ( types = self . _valid_types ) )
def main ( arguments , toxinidir = None ) : "ctox : tox with conda ."
try : # pragma : no cover # Exit on broken pipe . import signal signal . signal ( signal . SIGPIPE , signal . SIG_DFL ) except AttributeError : # pragma : no cover # SIGPIPE is not available on Windows . pass try : import sys sys . exit ( ctox ( arguments , toxinidir ) ) except CalledProcessError as...
def list_engines_by_priority ( engines = None ) : """Return a list of engines supported sorted by each priority ."""
if engines is None : engines = ENGINES return sorted ( engines , key = operator . methodcaller ( "priority" ) )
def get_default_config ( self ) : """Returns the default collector settings"""
config = super ( HBaseCollector , self ) . get_default_config ( ) config . update ( { 'path' : 'hbase' , 'metrics' : [ '/var/log/hbase/*.metrics' ] , } ) return config
def fix_decimals ( obj ) : """Removes the stupid Decimals See : https : / / github . com / boto / boto3 / issues / 369 # issuecomment - 302137290"""
if isinstance ( obj , list ) : for i in range ( len ( obj ) ) : obj [ i ] = fix_decimals ( obj [ i ] ) return obj elif isinstance ( obj , dict ) : for key , value in obj . items ( ) : obj [ key ] = fix_decimals ( value ) return obj elif isinstance ( obj , decimal . Decimal ) : if obj...
def visit_versions ( self , func ) : """Visit each version in the range , and apply a function to each . This is for advanced usage only . If ` func ` returns a ` Version ` , this call will change the versions in place . It is possible to change versions in a way that is nonsensical - for example setting ...
for bound in self . bounds : if bound . lower is not _LowerBound . min : result = func ( bound . lower . version ) if isinstance ( result , Version ) : bound . lower . version = result if bound . upper is not _UpperBound . inf : result = func ( bound . upper . version ) ...
def plot ( graph , show_x_axis = True , head = None , tail = None , label_length = 4 , padding = 0 , height = 2 , show_min_max = True , show_data_range = True , show_title = True ) : """show _ x _ axis : Display X axis head : Show first [ head : ] elements tail : Show last [ - tail : ] elements padding : Padd...
def __plot ( graph ) : def get_padding_str ( label , value ) : padding_str = '' if len ( label ) < label_length : diff = label_length - len ( label ) padding_str = ' ' * diff padding_str2 = '' if len ( str ( value ) ) < m : diff = m - len ( str ( v...
def flatter ( x , k = 1 ) : '''flatter ( x ) yields a numpy array equivalent to x but whose first dimension has been flattened . flatter ( x , k ) yields a numpy array whose first k dimensions have been flattened ; if k is negative , the last k dimensions are flattened . If np . inf or - np . inf is passed , th...
if k == 0 : return x x = x . toarray ( ) if sps . issparse ( x ) else np . asarray ( x ) if len ( x . shape ) - abs ( k ) < 2 : return x . flatten ( ) k += np . sign ( k ) if k > 0 : return np . reshape ( x , ( - 1 , ) + x . shape [ k : ] ) else : return np . reshape ( x , x . shape [ : k ] + ( - 1 , ) ...
def _J ( self , theta ) : """Implements the order dependent family of functions defined in equations 4 to 7 in the reference paper ."""
if self . order == 0 : return np . pi - theta elif self . order == 1 : return tf . sin ( theta ) + ( np . pi - theta ) * tf . cos ( theta ) elif self . order == 2 : return 3. * tf . sin ( theta ) * tf . cos ( theta ) + ( np . pi - theta ) * ( 1. + 2. * tf . cos ( theta ) ** 2 )
def angle ( v1 , v2 ) : """Return the angle in radians between vectors ' v1 ' and ' v2 ' ."""
v1_u = unit_vector ( v1 ) v2_u = unit_vector ( v2 ) return np . arccos ( np . clip ( np . dot ( v1_u , v2_u ) , - 1.0 , 1.0 ) )
def cmd_ip_geolocation ( ip_address , verbose ) : """Get the geolocation of an IP adddress from https : / / ipapi . co / . Example : $ habu . ip . geolocation 8.8.8.8 " ip " : " 8.8.8.8 " , " city " : " Mountain View " , " asn " : " AS15169 " , " org " : " Google LLC " """
if verbose : logging . basicConfig ( level = logging . INFO , format = '%(message)s' ) print ( "Looking up %s..." % ip_address , file = sys . stderr ) results = geo_location ( ip_address ) if results : print ( json . dumps ( results , indent = 4 ) ) else : print ( "[X] %s is not valid IPv4 address" % ip...
def decode_entities ( html ) : """Remove HTML entities from a string . Adapted from http : / / effbot . org / zone / re - sub . htm # unescape - html"""
def decode ( m ) : html = m . group ( 0 ) if html [ : 2 ] == "&#" : try : if html [ : 3 ] == "&#x" : return chr ( int ( html [ 3 : - 1 ] , 16 ) ) else : return chr ( int ( html [ 2 : - 1 ] ) ) except ValueError : pass else :...
def branch ( self , node , ** kwargs ) : """create a new Identifiers for a new Node , with this Identifiers as the parent ."""
return _Identifiers ( self . compiler , node , self , ** kwargs )
def trace ( args ) : """% prog trace unitig { version } . { partID } . { unitigID } Call ` grep ` to get the erroneous fragment placement ."""
p = OptionParser ( trace . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) s , = args version , partID , unitigID = get_ID ( s ) flist = glob ( "../5-consensus/*_{0:03d}.err" . format ( int ( partID ) ) ) assert len ( flist ) == 1 fp = open ( flist [ 0 ] ) in...
def get_subgraph_by_second_neighbors ( graph , nodes : Iterable [ BaseEntity ] , filter_pathologies : bool = False ) : """Get a graph around the neighborhoods of the given nodes and expand to the neighborhood of those nodes . Returns none if none of the nodes are in the graph . : param pybel . BELGraph graph : ...
result = get_subgraph_by_neighborhood ( graph , nodes ) if result is None : return expand_all_node_neighborhoods ( graph , result , filter_pathologies = filter_pathologies ) return result
def can_user_update_settings ( request , view , obj = None ) : """Only staff can update shared settings , otherwise user has to be an owner of the settings ."""
if obj is None : return # TODO [ TM : 3/21/17 ] clean it up after WAL - 634 . Clean up service settings update tests as well . if obj . customer and not obj . shared : return permissions . is_owner ( request , view , obj ) else : return permissions . is_staff ( request , view , obj )
def _afterpass ( self ) : """Assign a function - local index to each child object and register write operations to variables . This should only be called after the object is fully built ."""
if hasattr ( self , '_fi' ) : return fi = 0 for codeobj in self . walk_preorder ( ) : codeobj . _fi = fi fi += 1 if isinstance ( codeobj , CodeOperator ) and codeobj . is_assignment : if codeobj . arguments and isinstance ( codeobj . arguments [ 0 ] , CodeReference ) : var = codeobj ...
def _format_table ( fmt , headers , rows , colwidths , colaligns , is_multiline ) : """Produce a plain - text representation of the table ."""
lines = [ ] hidden = fmt . with_header_hide if ( headers and fmt . with_header_hide ) else [ ] pad = fmt . padding headerrow = fmt . headerrow padded_widths = [ ( w + 2 * pad ) for w in colwidths ] if is_multiline : pad_row = lambda row , _ : row # do it later , in _ append _ multiline _ row append_row = pa...
def seek ( self , loc ) : """Called if upload fails and must be retried ."""
assert loc == 0 # rewind progress bar if self . progressbar : self . progressbar . update ( - self . _tell ) self . _fp_left . seek ( loc ) self . _fp_right . seek ( loc ) self . _tell = loc self . _buf = Buffer ( )
def _feature_country_mentions ( self , doc ) : """Given a document , count how many times different country names and adjectives are mentioned . These are features used in the country picking phase . Parameters doc : a spaCy nlp ' ed piece of text Returns countries : dict the top two countries ( ISO cod...
c_list = [ ] for i in doc . ents : try : country = self . _both_codes [ i . text ] c_list . append ( country ) except KeyError : pass count = Counter ( c_list ) . most_common ( ) try : top , top_count = count [ 0 ] except : top = "" top_count = 0 try : two , two_count = c...
def _get_trusted_comma ( self , trusted , value ) : """Get the real value from a comma - separated header based on the configured number of trusted proxies . : param trusted : Number of values to trust in the header . : param value : Header value to parse . : return : The real value , or ` ` None ` ` if the...
if not ( trusted and value ) : return values = [ x . strip ( ) for x in value . split ( "," ) ] if len ( values ) >= trusted : return values [ - trusted ]
def create ( self , impersonation_level , desired_access , file_attributes , share_access , create_disposition , create_options , create_contexts = None , send = True ) : """This will open the file based on the input parameters supplied . Any file open should also be called with Open . close ( ) when it is finish...
create = SMB2CreateRequest ( ) create [ 'impersonation_level' ] = impersonation_level create [ 'desired_access' ] = desired_access create [ 'file_attributes' ] = file_attributes create [ 'share_access' ] = share_access create [ 'create_disposition' ] = create_disposition create [ 'create_options' ] = create_options if ...
def delete_expired_locks ( self ) : """Deletes all expired mutex locks if a ttl is provided ."""
ttl_seconds = self . get_mutex_ttl_seconds ( ) if ttl_seconds is not None : DBMutex . objects . filter ( creation_time__lte = timezone . now ( ) - timedelta ( seconds = ttl_seconds ) ) . delete ( )
def quirks_from_any_parent ( loc : Union [ Labware , Well , str , ModuleGeometry , None ] ) -> List [ str ] : """Walk the tree of wells and labwares and extract quirks"""
def recursive_get_quirks ( obj , found ) : if isinstance ( obj , Labware ) : return found + obj . quirks elif isinstance ( obj , Well ) : return recursive_get_quirks ( obj . parent , found ) else : return found return recursive_get_quirks ( loc , [ ] )
def _init_metadata ( self ) : """stub"""
QuestionTextAndFilesMixin . _init_metadata ( self ) BaseMultiChoiceTextQuestionFormRecord . _init_metadata ( self ) super ( MultiChoiceTextAndFilesQuestionFormRecord , self ) . _init_metadata ( )
def remove_all ( self ) : '''Remove all : attr : ` children ` .'''
if self . _children : for child in self . _children : if isinstance ( child , String ) : child . _parent = None self . _children = [ ]
def request ( self , method , url , parameters = dict ( ) ) : """Requests wrapper function"""
# The requests library uses urllib , which serializes to " True " / " False " while Pingdom requires lowercase parameters = self . _serializeBooleans ( parameters ) headers = { 'App-Key' : self . apikey } if self . accountemail : headers . update ( { 'Account-Email' : self . accountemail } ) # Method selection hand...
def poisson_cluster ( data , k , init = None , max_iters = 100 ) : """Performs Poisson hard EM on the given data . Args : data ( array ) : A 2d array - genes x cells . Can be dense or sparse ; for best performance , sparse matrices should be in CSC format . k ( int ) : Number of clusters init ( array , opti...
# TODO : be able to use a combination of fixed and unknown starting points # e . g . , have init values only for certain genes , have a row of all # zeros indicating that kmeans + + should be used for that row . genes , cells = data . shape # print ' starting : ' , centers if sparse . issparse ( data ) and not sparse ....
def solveConsMedShock ( solution_next , IncomeDstn , MedShkDstn , LivPrb , DiscFac , CRRA , CRRAmed , Rfree , MedPrice , pLvlNextFunc , BoroCnstArt , aXtraGrid , pLvlGrid , vFuncBool , CubicBool ) : '''Solve the one period problem for a consumer with shocks to permanent and transitory income as well as medical ne...
solver = ConsMedShockSolver ( solution_next , IncomeDstn , MedShkDstn , LivPrb , DiscFac , CRRA , CRRAmed , Rfree , MedPrice , pLvlNextFunc , BoroCnstArt , aXtraGrid , pLvlGrid , vFuncBool , CubicBool ) solver . prepareToSolve ( ) # Do some preparatory work solution_now = solver . solve ( ) # Solve the period return so...
def list_versions ( self , app_id ) : """List the versions of an app . : param str app _ id : application ID : returns : list of versions : rtype : list [ str ]"""
response = self . _do_request ( 'GET' , '/v2/apps/{app_id}/versions' . format ( app_id = app_id ) ) return [ version for version in response . json ( ) [ 'versions' ] ]
def _casual_timedelta_string ( meeting ) : """Return a casual timedelta string . If a meeting starts in 2 hours , 15 minutes , and 32 seconds from now , then return just " in 2 hours " . If a meeting starts in 7 minutes and 40 seconds from now , return just " in 7 minutes " . If a meeting starts 56 second...
now = datetime . datetime . utcnow ( ) mdate = meeting [ 'meeting_date' ] mtime = meeting [ 'meeting_time_start' ] dt_string = "%s %s" % ( mdate , mtime ) meeting_dt = datetime . datetime . strptime ( dt_string , "%Y-%m-%d %H:%M:%S" ) relative_td = dateutil . relativedelta . relativedelta ( meeting_dt , now ) denominat...
def delete ( self , resource , resource_id ) : '''A base function that performs a default delete DELETE request for a given object'''
service_def , resource_def , path = self . _get_service_information ( resource ) delete_path = "{0}{1}/" . format ( path , resource_id ) return self . call ( path = delete_path , method = "delete" )
def contains ( bank , key ) : '''Checks if the specified bank contains the specified key .'''
_init_client ( ) etcd_key = '{0}/{1}/{2}' . format ( path_prefix , bank , key ) try : r = client . read ( etcd_key ) # return True for keys , not dirs return r . dir is False except etcd . EtcdKeyNotFound : return False except Exception as exc : raise SaltCacheError ( 'There was an error getting the...
def advertisement ( ) : """This is the url we give for the ad for our ' external question ' . The ad has to display two different things : This page will be called from within mechanical turk , with url arguments hitId , assignmentId , and workerId . If the worker has not yet accepted the hit : These argume...
user_agent_string = request . user_agent . string user_agent_obj = user_agents . parse ( user_agent_string ) browser_ok = True for rule in string . split ( CONFIG . get ( 'HIT Configuration' , 'browser_exclude_rule' ) , ',' ) : myrule = rule . strip ( ) if myrule in [ "mobile" , "tablet" , "touchcapable" , "pc"...
def convolve ( data , h , res_g = None , sub_blocks = None ) : """convolves 1d - 3d data with kernel h data and h can either be numpy arrays or gpu buffer objects ( OCLArray , which must be float32 then ) boundary conditions are clamping to zero at edge ."""
if not len ( data . shape ) in [ 1 , 2 , 3 ] : raise ValueError ( "dim = %s not supported" % ( len ( data . shape ) ) ) if len ( data . shape ) != len ( h . shape ) : raise ValueError ( "dimemnsion of data (%s) and h (%s) are different" % ( len ( data . shape ) , len ( h . shape ) ) ) if isinstance ( data , OCL...
def _str_replace ( txt ) : """Makes a small text amenable to being used in a filename ."""
txt = txt . replace ( "," , "" ) txt = txt . replace ( " " , "_" ) txt = txt . replace ( ":" , "" ) txt = txt . replace ( "." , "" ) txt = txt . replace ( "/" , "" ) txt = txt . replace ( "" , "" ) return txt
def analyze ( self , analysis_set = '' , analysis_directory = None ) : '''This function runs the analysis and creates the plots and summary file .'''
self . calculate_metrics ( analysis_set , analysis_directory = analysis_directory ) if self . generate_plots : self . plot ( analysis_set , analysis_directory = analysis_directory )
def setDefaults ( self , instance ) : """Only call during object initialization , this function sets fields to schema defaults . It ' s adapted from the original to support IAcquireFieldDefaults adapters . If IAcquireFieldDefaults adapter does not find a suitable field , or that field ' s value is Falseish , ...
for field in self . values ( ) : # # # bika addition : we fire adapters for IAcquireFieldDefaults . # If IAcquireFieldDefaults returns None , this signifies " ignore " return . # First adapter found with non - None result , wins . value = None if shasattr ( field , 'acquire' ) : adapters = { } f...
def create_socket ( ) : """Creates a raw CAN socket . The socket will be returned unbound to any interface ."""
sock = socket . socket ( PF_CAN , socket . SOCK_RAW , CAN_RAW ) log . info ( 'Created a socket' ) return sock
def safequote_restbase ( title ) : """Safequote restbase title possibly having slash in title"""
try : return quote ( title . encode ( 'utf-8' ) , safe = '' ) except UnicodeDecodeError : return quote ( title , safe = '' )
def get_file_extension ( filename ) : """Return the extension if the filename has it . None if not . : param filename : The filename . : return : Extension or None ."""
filename_x = filename . split ( '.' ) if len ( filename_x ) > 1 : if filename_x [ - 1 ] . strip ( ) is not '' : return filename_x [ - 1 ] return None
def course_unregister_user ( self , course , username = None ) : """Unregister a user to the course : param course : a Course object : param username : The username of the user that we want to unregister . If None , uses self . session _ username ( )"""
if username is None : username = self . session_username ( ) # Needed if user belongs to a group self . _database . aggregations . find_one_and_update ( { "courseid" : course . get_id ( ) , "groups.students" : username } , { "$pull" : { "groups.$.students" : username , "students" : username } } ) # If user doesn ' ...
def non_position_scales ( self ) : """Return a list of the non - position scales that are present"""
l = [ s for s in self if not ( 'x' in s . aesthetics ) and not ( 'y' in s . aesthetics ) ] return Scales ( l )
def mprotect ( self , lpAddress , dwSize , flNewProtect ) : """Set memory protection in the address space of the process . @ see : U { http : / / msdn . microsoft . com / en - us / library / aa366899 . aspx } @ type lpAddress : int @ param lpAddress : Address of memory to protect . @ type dwSize : int @ p...
hProcess = self . get_handle ( win32 . PROCESS_VM_OPERATION ) return win32 . VirtualProtectEx ( hProcess , lpAddress , dwSize , flNewProtect )
def escape ( s , quote = True ) : """Replace special characters " & " , " < " and " > " to HTML - safe sequences . If the optional flag quote is true ( the default ) , the quotation mark characters , both double quote ( " ) and single quote ( ' ) characters are also translated ."""
assert not isinstance ( s , bytes ) , 'Pass a unicode string' if quote : return s . translate ( _escape_map_full ) return s . translate ( _escape_map )
def prune_builds ( self ) : """Delete the builder cache Returns : ( dict ) : A dictionary containing information about the operation ' s result . The ` ` SpaceReclaimed ` ` key indicates the amount of bytes of disk space reclaimed . Raises : : py : class : ` docker . errors . APIError ` If the server ...
url = self . _url ( "/build/prune" ) return self . _result ( self . _post ( url ) , True )
def get_templates ( self , context , template_name = None ) : "Extract parameters for ` get _ templates ` from the context ."
if not template_name : template_name = self . template_name kw = { } if 'object' in context : o = context [ 'object' ] kw [ 'slug' ] = o . slug if context . get ( 'content_type' , False ) : ct = context [ 'content_type' ] kw [ 'app_label' ] = ct . app_label kw [ 'model_label' ] = ct . model retu...
def _cp_embeds_into ( cp1 , cp2 ) : """Check that any state in ComplexPattern2 is matched in ComplexPattern1."""
# Check that any state in cp2 is matched in cp1 # If the thing we ' re matching to is just a monomer pattern , that makes # things easier - - we just need to find the corresponding monomer pattern # in cp1 if cp1 is None or cp2 is None : return False cp1 = as_complex_pattern ( cp1 ) cp2 = as_complex_pattern ( cp2 )...
def get_open ( self , appid ) : """获取公众号 / 小程序所绑定的开放平台账号 详情请参考 https : / / open . weixin . qq . com / cgi - bin / showdocument ? action = dir _ list & id = open1498704199_1bcax : param appid : 授权公众号或小程序的 appid : return : 开放平台的 appid"""
return self . _post ( 'cgi-bin/open/get' , data = { 'appid' : appid , } , result_processor = lambda x : x [ 'open_appid' ] , )
def dannotsagg2dannots2dalignbedannot ( cfg ) : """Map aggregated annotations to queries step # 9 : param cfg : configuration dict"""
datatmpd = cfg [ 'datatmpd' ] dannotsagg = del_Unnamed ( pd . read_csv ( cfg [ 'dannotsaggp' ] , sep = '\t' ) ) dalignbedstats = del_Unnamed ( pd . read_csv ( cfg [ 'dalignbedstatsp' ] , sep = '\t' ) ) dalignbedannotp = cfg [ 'dalignbedannotp' ] logging . info ( basename ( dalignbedannotp ) ) if not exists ( dalignbeda...
def does_keychain_exist ( dict_ , list_ ) : """Check if a sequence of keys exist in a nested dictionary . Parameters dict _ : Dict [ str / int / tuple , Any ] list _ : List [ str / int / tuple ] Returns keychain _ exists : bool Examples > > > d = { ' a ' : { ' b ' : { ' c ' : ' d ' } } } > > > l _ e...
for key in list_ : if key not in dict_ : return False dict_ = dict_ [ key ] return True
def attempt_advance ( self , blocksize , timeout = 10 ) : """Attempt to advance the frame buffer . Retry upon failure , except if the frame file is beyond the timeout limit . Parameters blocksize : int The number of seconds to attempt to read from the channel timeout : { int , 10 } , Optional Number of ...
if self . force_update_cache : self . update_cache ( ) try : if self . increment_update_cache : self . update_cache_by_increment ( blocksize ) return DataBuffer . advance ( self , blocksize ) except RuntimeError : if lal . GPSTimeNow ( ) > timeout + self . raw_buffer . end_time : # The frame is ...
def monkeypatch_i18n ( ) : """Alleviates problems with extraction for trans blocks Jinja2 has a ` ` babel _ extract ` ` function which sets up a Jinja2 environment to parse Jinja2 templates to extract strings for translation . That ' s awesome ! Yay ! However , when it goes to set up the environment , it ch...
import jinja2 . ext from puente . ext import PuenteI18nExtension jinja2 . ext . InternationalizationExtension = PuenteI18nExtension jinja2 . ext . i18n = PuenteI18nExtension
def value_attr ( attr_name ) : """Creates a getter that will retrieve value ' s attribute with specified name . @ param attr _ name : the name of an attribute belonging to the value . @ type attr _ name : str"""
def value_attr ( value , context , ** _params ) : value = getattr ( value , attr_name ) return _attr ( value ) return value_attr
def set_xattr ( self , path , xattr_name , xattr_value , flag , ** kwargs ) : """Set an xattr of a file or directory . : param xattr _ name : The name must be prefixed with the namespace followed by ` ` . ` ` . For example , ` ` user . attr ` ` . : param flag : ` ` CREATE ` ` or ` ` REPLACE ` `"""
kwargs [ 'xattr.name' ] = xattr_name kwargs [ 'xattr.value' ] = xattr_value response = self . _put ( path , 'SETXATTR' , flag = flag , ** kwargs ) assert not response . content
def _on_timeout ( self , key : object , info : str = None ) -> None : """Timeout callback of request . Construct a timeout HTTPResponse when a timeout occurs . : arg object key : A simple object to mark the request . : info string key : More detailed timeout information ."""
request , callback , timeout_handle = self . waiting [ key ] self . queue . remove ( ( key , request , callback ) ) error_message = "Timeout {0}" . format ( info ) if info else "Timeout" timeout_response = HTTPResponse ( request , 599 , error = HTTPTimeoutError ( error_message ) , request_time = self . io_loop . time (...
def taylor ( fun , z0 = 0 , n = 1 , r = 0.0061 , num_extrap = 3 , step_ratio = 1.6 , ** kwds ) : """Return Taylor coefficients of complex analytic function using FFT Parameters fun : callable function to differentiate z0 : real or complex scalar at which to evaluate the derivatives n : scalar integer , de...
return Taylor ( fun , n = n , r = r , num_extrap = num_extrap , step_ratio = step_ratio , ** kwds ) ( z0 )
def schedule_next_request ( self ) : """Schedules a request , if exists . : return :"""
req = self . next_request ( ) if req : self . crawler . engine . crawl ( req , spider = self )
def complex_fault_node ( edges ) : """: param edges : a list of lists of points : returns : a Node of kind complexFaultGeometry"""
node = Node ( 'complexFaultGeometry' ) node . append ( edge_node ( 'faultTopEdge' , edges [ 0 ] ) ) for edge in edges [ 1 : - 1 ] : node . append ( edge_node ( 'intermediateEdge' , edge ) ) node . append ( edge_node ( 'faultBottomEdge' , edges [ - 1 ] ) ) return node
def select ( self , selector ) : '''Query this document for objects that match the given selector . Args : selector ( JSON - like query dictionary ) : you can query by type or by name , e . g . ` ` { " type " : HoverTool } ` ` , ` ` { " name " : " mycircle " } ` ` Returns : seq [ Model ]'''
if self . _is_single_string_selector ( selector , 'name' ) : # special - case optimization for by - name query return self . _all_models_by_name . get_all ( selector [ 'name' ] ) else : return find ( self . _all_models . values ( ) , selector )
def _check_instance_relationships_for_delete ( self , instance ) : """Ensure we are authorized to delete this and all cascaded resources . : param instance : The instance to check the relationships of ."""
check_permission ( instance , None , Permissions . DELETE ) for rel_key , rel in instance . __mapper__ . relationships . items ( ) : check_permission ( instance , rel_key , Permissions . EDIT ) if rel . cascade . delete : if rel . direction == MANYTOONE : related = getattr ( instance , rel_k...
def blk_nd ( blk , shape ) : """Iterate through the blocks that cover an array . This function first iterates trough the blocks that recover the part of the array given by max _ blk _ coverage and then iterates with smaller blocks for the rest of the array . : param blk : the N - dimensional shape of the ...
internals = ( blk_1d ( b , s ) for b , s in zip ( blk , shape ) ) return product ( * internals )
def configure ( self , viewport = None , fbo_size = None , fbo_rect = None , canvas = None ) : """Automatically configure the TransformSystem : * canvas _ transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system , taking into account the logical / physical pixel scal...
# TODO : check that d2f and f2r transforms still contain a single # STTransform ( if the user has modified these , then auto - config should # either fail or replace the transforms ) if canvas is not None : self . canvas = canvas canvas = self . _canvas if canvas is None : raise RuntimeError ( "No canvas assign...
def get_default_remote_name ( ) : """Return the default name appearing in argv [ 0 ] of remote machines ."""
s = u'%s@%s:%d' s %= ( getpass . getuser ( ) , socket . gethostname ( ) , os . getpid ( ) ) # In mixed UNIX / Windows environments , the username may contain slashes . return s . translate ( { ord ( u'\\' ) : ord ( u'_' ) , ord ( u'/' ) : ord ( u'_' ) } )
def linear_trend_timewise ( x , param ) : """Calculate a linear least - squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one . This feature uses the index of the time series to fit the model , which must be of a datetime dtype . The parameter...
ix = x . index # Get differences between each timestamp and the first timestamp in seconds . # Then convert to hours and reshape for linear regression times_seconds = ( ix - ix [ 0 ] ) . total_seconds ( ) times_hours = np . asarray ( times_seconds / float ( 3600 ) ) linReg = linregress ( times_hours , x . values ) retu...
def notification_rules ( self , ** kwargs ) : """Get all notification rules for this user ."""
endpoint = '{0}/{1}/notification_rules' . format ( self . endpoint , self [ 'id' ] , ) result = self . request ( 'GET' , endpoint = endpoint , query_params = kwargs ) return result [ 'notification_rules' ]
def _get_var_names ( posterior ) : """Extract latent and observed variable names from pyro . MCMC . Parameters posterior : pyro . MCMC Fitted MCMC object from Pyro Returns list [ str ] , list [ str ] observed and latent variable names from the MCMC trace ."""
sample_point = posterior . exec_traces [ 0 ] nodes = [ node for node in sample_point . nodes . values ( ) if node [ "type" ] == "sample" ] observed = [ node [ "name" ] for node in nodes if node [ "is_observed" ] ] latent = [ node [ "name" ] for node in nodes if not node [ "is_observed" ] ] return observed , latent
def apply_transform ( sample , transform_matrix , channel_axis = 0 , fill_mode = 'nearest' , cval = 0. ) : """Apply the image transformation specified by a matrix . # Arguments sample : 2D numpy array , single sample . transform _ matrix : Numpy array specifying the geometric transformation . channel _ axis...
if sample . ndim == 4 : channel_axis = channel_axis - 1 transformed_frames = [ transform ( frame , transform_matrix , channel_axis , fill_mode , cval ) for frame in sample ] return np . stack ( transformed_frames , axis = 0 ) if sample . ndim == 3 : return transform ( sample , transform_matrix , channel...
def auth_from_hass_config ( path = None , ** kwargs ) : """Initialize auth from HASS config ."""
if path is None : path = config . find_hass_config ( ) return Auth ( os . path . join ( path , ".storage/auth" ) , ** kwargs )
def slugify ( text , sep = '-' ) : """A simple slug generator ."""
text = stringify ( text ) if text is None : return None text = text . replace ( sep , WS ) text = normalize ( text , ascii = True ) if text is None : return None return text . replace ( WS , sep )
def _env ( self , lines ) : '''env will parse a list of environment lines and simply remove any blank lines , or those with export . Dockerfiles don ' t usually have exports . Parameters lines : A list of environment pair lines .'''
environ = [ x for x in lines if not x . startswith ( 'export' ) ] self . environ += environ
async def jsk_sudo ( self , ctx : commands . Context , * , command_string : str ) : """Run a command bypassing all checks and cooldowns . This also bypasses permission checks so this has a high possibility of making a command raise ."""
alt_ctx = await copy_context_with ( ctx , content = ctx . prefix + command_string ) if alt_ctx . command is None : return await ctx . send ( f'Command "{alt_ctx.invoked_with}" is not found' ) return await alt_ctx . command . reinvoke ( alt_ctx )
def get_peer_id ( peer , add_mark = True ) : """Finds the ID of the given peer , and converts it to the " bot api " format so it the peer can be identified back . User ID is left unmodified , chat ID is negated , and channel ID is prefixed with - 100. The original ID and the peer type class can be returned wi...
# First we assert it ' s a Peer TLObject , or early return for integers if isinstance ( peer , int ) : return peer if add_mark else resolve_id ( peer ) [ 0 ] # Tell the user to use their client to resolve InputPeerSelf if we got one if isinstance ( peer , types . InputPeerSelf ) : _raise_cast_fail ( peer , 'int...
def get_fw_dict ( self ) : """This API creates a FW dictionary from the local attributes ."""
fw_dict = { } if self . fw_id is None : return fw_dict fw_dict = { 'rules' : { } , 'tenant_name' : self . tenant_name , 'tenant_id' : self . tenant_id , 'fw_id' : self . fw_id , 'fw_name' : self . fw_name , 'firewall_policy_id' : self . active_pol_id , 'fw_type' : self . fw_type , 'router_id' : self . router_id } #...