signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def artifactCreated ( self , * args , ** kwargs ) : """Artifact Creation Messages Whenever the ` createArtifact ` end - point is called , the queue will create a record of the artifact and post a message on this exchange . All of this happens before the queue returns a signed URL for the caller to upload th...
ref = { 'exchange' : 'artifact-created' , 'name' : 'artifactCreated' , 'routingKey' : [ { 'constant' : 'primary' , 'multipleWords' : False , 'name' : 'routingKeyKind' , } , { 'multipleWords' : False , 'name' : 'taskId' , } , { 'multipleWords' : False , 'name' : 'runId' , } , { 'multipleWords' : False , 'name' : 'worker...
def encodeEntitiesReentrant ( self , input ) : """Do a global encoding of a string , replacing the predefined entities and non ASCII values with their entities and CharRef counterparts . Contrary to xmlEncodeEntities , this routine is reentrant , and result must be deallocated ."""
ret = libxml2mod . xmlEncodeEntitiesReentrant ( self . _o , input ) return ret
def _load_mirteFile ( d , m ) : """Loads the dictionary from the mirteFile into < m >"""
defs = d [ 'definitions' ] if 'definitions' in d else { } insts = d [ 'instances' ] if 'instances' in d else { } # Filter out existing instances insts_to_skip = [ ] for k in insts : if k in m . insts : m . update_instance ( k , dict ( insts [ k ] ) ) insts_to_skip . append ( k ) for k in insts_to_sk...
def vcf_to_npz ( input , output , compressed = True , overwrite = False , fields = None , exclude_fields = None , rename_fields = None , types = None , numbers = None , alt_number = DEFAULT_ALT_NUMBER , fills = None , region = None , tabix = True , samples = None , transformers = None , buffer_size = DEFAULT_BUFFER_SIZ...
# guard condition if not overwrite and os . path . exists ( output ) : raise ValueError ( 'file exists at path %r; use overwrite=True to replace' % output ) # read all data into memory data = read_vcf ( input = input , fields = fields , exclude_fields = exclude_fields , rename_fields = rename_fields , types = types...
def build ( self , sources = None , headers = None ) : '''sources can be file name or code : sources = [ ' x . c ' , ' int main ( ) { } ' ] or sources = ' int main ( ) { } ' '''
tempdir = None strings , files = separate_sources ( sources ) if len ( strings ) or headers : # TODO : remove tempdir tempdir = tmpdir ( ) temp_list = [ tmpfile ( x , tempdir , '.c' ) for x in strings ] if headers : for n , s in headers . items ( ) : ( Path ( tempdir ) / n ) . write_text ( s ) cmd = sel...
def value ( self ) : """Returns a copy of the original map ' s value . Nested values are pure Python values as returned by : attr : ` Datatype . value ` from the nested types . : rtype : dict"""
pvalue = { } for key in self . _value : pvalue [ key ] = self . _value [ key ] . value return pvalue
def open ( self ) : """Implementation of Reporter callback ."""
safe_mkdir ( os . path . dirname ( self . _html_dir ) ) self . _report_file = open ( self . report_path ( ) , 'w' )
def _find_files ( metadata ) : '''Looks for all the files in the S3 bucket cache metadata'''
ret = [ ] found = { } for bucket_dict in metadata : for bucket_name , data in six . iteritems ( bucket_dict ) : filepaths = [ k [ 'Key' ] for k in data ] filepaths = [ k for k in filepaths if not k . endswith ( '/' ) ] if bucket_name not in found : found [ bucket_name ] = True ...
def step ( self ) -> Number : "Return next value along annealed schedule ."
self . n += 1 return self . func ( self . start , self . end , self . n / self . n_iter )
def destroy ( self ) : """Destroy all vagrant box involved in the deployment ."""
v = vagrant . Vagrant ( root = os . getcwd ( ) , quiet_stdout = False , quiet_stderr = True ) v . destroy ( )
def get_all_hits ( self ) : '''Get all HITs'''
if not self . connect_to_turk ( ) : return False try : hits = [ ] paginator = self . mtc . get_paginator ( 'list_hits' ) for page in paginator . paginate ( ) : hits . extend ( page [ 'HITs' ] ) except Exception as e : print e return False hits_data = self . _hit_xml_to_object ( hits ) re...
def _find_matching_expectation ( self , args , kwargs ) : """Return a matching expectation . Returns the first expectation that matches the ones declared . Tries one with specific arguments first , then falls back to an expectation that allows arbitrary arguments . : return : The matching ` ` Expectation ` ` ...
for expectation in self . _expectations : if expectation . satisfy_exact_match ( args , kwargs ) : return expectation for expectation in self . _expectations : if expectation . satisfy_custom_matcher ( args , kwargs ) : return expectation for expectation in self . _expectations : if expectat...
def _list_object_parts ( self , bucket_name , object_name , upload_id ) : """List all parts . : param bucket _ name : Bucket name to list parts for . : param object _ name : Object name to list parts for . : param upload _ id : Upload id of the previously uploaded object name ."""
is_valid_bucket_name ( bucket_name ) is_non_empty_string ( object_name ) is_non_empty_string ( upload_id ) query = { 'uploadId' : upload_id , 'max-parts' : '1000' } is_truncated = True part_number_marker = '' while is_truncated : if part_number_marker : query [ 'part-number-marker' ] = str ( part_number_mar...
def set_window_position ( self , x , y , windowHandle = 'current' ) : """Sets the x , y position of the current window . ( window . moveTo ) : Args : - x : the x - coordinate in pixels to set the window position - y : the y - coordinate in pixels to set the window position : Usage : driver . set _ window ...
if self . w3c : if windowHandle != 'current' : warnings . warn ( "Only 'current' window is supported for W3C compatibile browsers." ) return self . set_window_rect ( x = int ( x ) , y = int ( y ) ) else : self . execute ( Command . SET_WINDOW_POSITION , { 'x' : int ( x ) , 'y' : int ( y ) , 'windowH...
def getWifiState ( self ) : '''Gets the Wi - Fi enabled state . @ return : One of WIFI _ STATE _ DISABLED , WIFI _ STATE _ DISABLING , WIFI _ STATE _ ENABLED , WIFI _ STATE _ ENABLING , WIFI _ STATE _ UNKNOWN'''
result = self . device . shell ( 'dumpsys wifi' ) if result : state = result . splitlines ( ) [ 0 ] if self . WIFI_IS_ENABLED_RE . match ( state ) : return self . WIFI_STATE_ENABLED elif self . WIFI_IS_DISABLED_RE . match ( state ) : return self . WIFI_STATE_DISABLED print >> sys . stderr , ...
def get_job ( db , job_id , username = None ) : """If job _ id is negative , return the last calculation of the current user , otherwise returns the job _ id unchanged . : param db : a : class : ` openquake . server . dbapi . Db ` instance : param job _ id : a job ID ( can be negative and can be nonexisting )...
job_id = int ( job_id ) if job_id > 0 : dic = dict ( id = job_id ) if username : dic [ 'user_name' ] = username try : return db ( 'SELECT * FROM job WHERE ?A' , dic , one = True ) except NotFound : return # else negative job _ id if username : joblist = db ( 'SELECT * FROM jo...
def avail_images ( call = None ) : '''Return available Linode images . CLI Example : . . code - block : : bash salt - cloud - - list - images my - linode - config salt - cloud - f avail _ images my - linode - config'''
if call == 'action' : raise SaltCloudException ( 'The avail_images function must be called with -f or --function.' ) response = _query ( 'avail' , 'distributions' ) ret = { } for item in response [ 'DATA' ] : name = item [ 'LABEL' ] ret [ name ] = item return ret
def get_residual_norms ( H , self_adjoint = False ) : '''Compute relative residual norms from Hessenberg matrix . It is assumed that the initial guess is chosen as zero .'''
H = H . copy ( ) n_ , n = H . shape y = numpy . eye ( n_ , 1 , dtype = H . dtype ) resnorms = [ 1. ] for i in range ( n_ - 1 ) : G = Givens ( H [ i : i + 2 , [ i ] ] ) if self_adjoint : H [ i : i + 2 , i : i + 3 ] = G . apply ( H [ i : i + 2 , i : i + 3 ] ) else : H [ i : i + 2 , i : ] = G ....
def from_ranges ( ranges , name , data_key , start_key = 'offset' , length_key = 'length' ) : """Creates a list of commands from a list of ranges . Each range is converted to two commands : a start _ * and a stop _ * ."""
commands = [ ] for r in ranges : data = r [ data_key ] start = r [ start_key ] stop = start + r [ length_key ] commands . extend ( Command . start_stop ( name , start , stop , data ) ) return commands
def _warning ( self , msg , node_id , ex , * args , ** kwargs ) : """Handles the error messages . . . note : : If ` self . raises ` is True the dispatcher interrupt the dispatch when an error occur , otherwise it logs a warning ."""
raises = self . raises ( ex ) if callable ( self . raises ) else self . raises if raises and isinstance ( ex , DispatcherError ) : ex . update ( self ) raise ex self . _errors [ node_id ] = msg % ( ( node_id , ex ) + args ) node_id = '/' . join ( self . full_name + ( node_id , ) ) if raises : raise Dispatch...
def _cursor_down ( self , value ) : """Moves the cursor down by ` ` value ` ` ."""
self . _cursor . clearSelection ( ) if self . _cursor . atEnd ( ) : self . _cursor . insertText ( '\n' ) else : self . _cursor . movePosition ( self . _cursor . Down , self . _cursor . MoveAnchor , value ) self . _last_cursor_pos = self . _cursor . position ( )
def unmarkelect_comment ( self , msg_data_id , index , user_comment_id ) : """将评论取消精选"""
return self . _post ( 'comment/unmarkelect' , data = { 'msg_data_id' : msg_data_id , 'index' : index , 'user_comment_id' : user_comment_id , } )
def surface_trim_tessellate ( v1 , v2 , v3 , v4 , vidx , tidx , trims , tessellate_args ) : """Triangular tessellation algorithm for trimmed surfaces . This function can be directly used as an input to : func : ` . make _ triangle _ mesh ` using ` ` tessellate _ func ` ` keyword argument . : param v1 : vertex...
# Tolerance value tol = 10e-8 tols = tol ** 2 vtol = ( ( tols , tols ) , ( - tols , tols ) , ( - tols , - tols ) , ( tols , - tols ) ) # Start processing vertices vertices = [ v1 , v2 , v3 , v4 ] for idx in range ( len ( vertices ) ) : for trim in trims : cf = 1 if trim . opt [ 'reversed' ] else - 1 ...
def process_request ( self , request_info = None , ** kwargs ) : """The AuthorizationRequest endpoint : param request _ info : The authorization request as a dictionary : return : dictionary"""
if isinstance ( request_info , AuthorizationErrorResponse ) : return request_info _cid = request_info [ "client_id" ] cinfo = self . endpoint_context . cdb [ _cid ] try : cookie = kwargs [ 'cookie' ] except KeyError : cookie = '' else : del kwargs [ 'cookie' ] if proposed_user ( request_info ) : kwa...
def tag_lookup ( request ) : """JSON endpoint that returns a list of potential tags . Used for upload template autocomplete ."""
tag = request . GET [ 'tag' ] tagSlug = slugify ( tag . strip ( ) ) tagCandidates = Tag . objects . values ( 'word' ) . filter ( slug__startswith = tagSlug ) tags = json . dumps ( [ candidate [ 'word' ] for candidate in tagCandidates ] ) return HttpResponse ( tags , content_type = 'application/json' )
def ApplicationDatagram ( self , app , stream , text ) : """Called when a datagram is received over a stream ."""
# we should only proceed if we are in UDP mode if stype != socket . SOCK_DGRAM : return # decode the data data = base64 . decodestring ( text ) # open an UDP socket sock = socket . socket ( type = stype ) # send the data try : sock . sendto ( data , addr ) except socket . error , e : print 'error: %s' % e
def assertSignalNotFired ( self , signal , * args , ** kwargs ) : """Assert that a signal was fired with appropriate arguments . : param signal : The : class : ` Signal ` that should not have been fired . Typically this is ` ` SomeClass . on _ some _ signal ` ` reference : param args : List of positional ...
event = ( signal , args , kwargs ) self . assertNotIn ( event , self . _events_seen , "\nSignal unexpectedly fired: {}\n" . format ( event ) )
def set_media_params_after ( self , params ) : """If we ' re not doing a full run , limit to media uploaded to wordpress ' recently ' . ' Recently ' in this case means 90 days before the date we ' re processing content from . The wp . com REST API doesn ' t have a way to limit based on media modification date ,...
if not self . full : if self . modified_after : ninety_days_ago = self . modified_after - timedelta ( days = 90 ) else : ninety_days_ago = datetime . utcnow ( ) - timedelta ( days = 90 ) params [ "after" ] = ninety_days_ago . isoformat ( )
def force_lazy_import ( name ) : """Import any modules off of " name " by iterating a new list rather than a generator so that this library works with lazy imports ."""
obj = import_object ( name ) module_items = list ( getattr ( obj , '__dict__' , { } ) . items ( ) ) for key , value in module_items : if getattr ( value , '__module__' , None ) : import_object ( name + '.' + key )
def calcAFunc ( self , MaggNow , AaggNow ) : '''Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation . Calculates an aggregate saving rule for each macroeconomic Markov state . Parameters MaggNow : [ float ] List of the histo...
verbose = self . verbose discard_periods = self . T_discard # Throw out the first T periods to allow the simulation to approach the SS update_weight = 1. - self . DampingFac # Proportional weight to put on new function vs old function parameters total_periods = len ( MaggNow ) # Trim the histories of M _ t and A _ t an...
def p_struct ( self , p ) : '''struct : STRUCT IDENTIFIER ' { ' field _ seq ' } ' annotations'''
p [ 0 ] = ast . Struct ( name = p [ 2 ] , fields = p [ 4 ] , annotations = p [ 6 ] , lineno = p . lineno ( 2 ) )
def read_config_info ( ini_file ) : """Read the INI file Args : ini _ file - path to the file Returns : A dictionary of stuff from the INI file Exits : 1 - if problems are encountered"""
try : config = RawConfigParser ( ) config . optionxform = lambda option : option config . read ( ini_file ) the_stuff = { } for section in config . sections ( ) : the_stuff [ section ] = { } for option in config . options ( section ) : the_stuff [ section ] [ option ] = c...
def to_html ( self ) : """Render a Cell MessageElement as html : returns : The html representation of the Cell MessageElement : rtype : basestring"""
# Apply bootstrap alignment classes first if self . align is 'left' : if self . style_class is None : self . style_class = 'text-left' else : self . style_class += ' text-left' elif self . align is 'right' : if self . style_class is None : self . style_class = 'text-right' else :...
def skip_signatures_and_duplicates_concat_well_known_metadata ( cls , default_dup_action = None , additional_rules = None ) : """Produces a rule set useful in many deploy jar creation contexts . The rule set skips duplicate entries by default , retaining the 1st encountered . In addition it has the following sp...
default_dup_action = Duplicate . validate_action ( default_dup_action or Duplicate . SKIP ) additional_rules = assert_list ( additional_rules , expected_type = ( Duplicate , Skip ) ) rules = [ Skip ( r'^META-INF/[^/]+\.SF$' ) , # signature file Skip ( r'^META-INF/[^/]+\.DSA$' ) , # default signature alg . file Skip ( r...
def corr ( x , y = None , method = None ) : """Compute the correlation ( matrix ) for the input RDD ( s ) using the specified method . Methods currently supported : I { pearson ( default ) , spearman } . If a single RDD of Vectors is passed in , a correlation matrix comparing the columns in the input RDD is...
# Check inputs to determine whether a single value or a matrix is needed for output . # Since it ' s legal for users to use the method name as the second argument , we need to # check if y is used to specify the method name instead . if type ( y ) == str : raise TypeError ( "Use 'method=' to specify method name." )...
def convert_complex_output ( out_in ) : """Convert complex values in the output dictionary ` out _ in ` to pairs of real and imaginary parts ."""
out = { } for key , val in out_in . iteritems ( ) : if val . data . dtype in complex_types : rval = copy ( val ) rval . data = val . data . real out [ 'real(%s)' % key ] = rval ival = copy ( val ) ival . data = val . data . imag out [ 'imag(%s)' % key ] = ival els...
def dispatch ( self , * args , ** kwargs ) : """Decorate the view dispatcher with csrf _ exempt ."""
return super ( EntryTrackback , self ) . dispatch ( * args , ** kwargs )
def infer_type ( expr , scope ) : """Try to infer the type of x [ y ] if y is a known value ( literal ) ."""
# Do we know what the key even is ? if isinstance ( expr . key , ast . Literal ) : key = expr . key . value else : return protocol . AnyType container_type = infer_type ( expr . value , scope ) try : # Associative types are not subject to scoping rules so we can just # reflect using IAssociative . return as...
def _get_all_children ( self , ) : """return the list of children of a node"""
res = '' if self . child_nodes : for c in self . child_nodes : res += ' child = ' + str ( c ) + '\n' if c . child_nodes : for grandchild in c . child_nodes : res += ' child = ' + str ( grandchild ) + '\n' else : res += ' child = None\n' return res
def get_series ( self , series ) : """Returns a census series API handler ."""
if series == "acs1" : return self . census . acs1dp elif series == "acs5" : return self . census . acs5 elif series == "sf1" : return self . census . sf1 elif series == "sf3" : return self . census . sf3 else : return None
def addAttachment ( self , oid , file_path ) : """Adds an attachment to a feature service Input : oid - string - OBJECTID value to add attachment to file _ path - string - path to file Output : JSON Repsonse"""
if self . hasAttachments == True : attachURL = self . _url + "/%s/addAttachment" % oid params = { 'f' : 'json' } parsed = urlparse . urlparse ( attachURL ) files = { 'attachment' : file_path } res = self . _post ( url = attachURL , param_dict = params , files = files , securityHandler = self . _secu...
def set ( self , lang , instance ) : """Establece en la instancia actual los atributos de traducción y la almacena en un diccionario de claves _ create _ key y valores el objeto con los atributos dinámicos ."""
if self . _cache_is_too_big ( ) : self . cache = { } instance_key = TransCache . _create_key ( lang , instance ) instance . _translations_are_cached = True instance . load_translations ( lang = lang ) self . cache [ instance_key ] = instance
def _process_trait_mappings ( self , raw , limit = None ) : """This method mapps traits from / to . . . Triples created : : param limit : : return :"""
if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 model = Model ( graph ) with open ( raw , 'r' ) as csvfile : filereader = csv . reader ( csvfile , delimiter = ',' , quotechar = '\"' ) next ( filereader , None ) # skip header line for row in filereader ...
def delete_credit_card_payment_by_id ( cls , credit_card_payment_id , ** kwargs ) : """Delete CreditCardPayment Delete an instance of CreditCardPayment by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . d...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _delete_credit_card_payment_by_id_with_http_info ( credit_card_payment_id , ** kwargs ) else : ( data ) = cls . _delete_credit_card_payment_by_id_with_http_info ( credit_card_payment_id , ** kwargs ) return data
def import_doc ( self , file_uris , docsearch , current_doc = None ) : """Import the specified PDF files"""
doc = None docs = [ ] pages = [ ] file_uris = [ self . fs . safe ( uri ) for uri in file_uris ] imported = [ ] for file_uri in file_uris : logger . info ( "Importing PDF from '%s'" % ( file_uri ) ) idx = 0 for child in self . fs . recurse ( file_uri ) : gc . collect ( ) if not self . check_f...
def _get_request_obj ( csr ) : '''Returns a CSR object based on PEM text .'''
text = _text_or_file ( csr ) text = get_pem_entry ( text , pem_type = 'CERTIFICATE REQUEST' ) return M2Crypto . X509 . load_request_string ( text )
def delete_record ( self , identifier = None , rtype = None , name = None , content = None , ** kwargs ) : """Delete an existing record . If record does not exist , do nothing . If an identifier is specified , use it , otherwise do a lookup using type , name and content ."""
if not rtype and kwargs . get ( 'type' ) : warnings . warn ( 'Parameter "type" is deprecated, use "rtype" instead.' , DeprecationWarning ) rtype = kwargs . get ( 'type' ) return self . _delete_record ( identifier = identifier , rtype = rtype , name = name , content = content )
def __move ( self , current_pos ) : '''Move in the feature map . Args : current _ pos : The now position . Returns : The next position .'''
if self . __move_range is not None : next_pos = np . random . randint ( current_pos - self . __move_range , current_pos + self . __move_range ) if next_pos < 0 : next_pos = 0 elif next_pos >= self . var_arr . shape [ 0 ] - 1 : next_pos = self . var_arr . shape [ 0 ] - 1 return next_pos e...
def unsafe_execute ( self , result = None ) : """un - wrapped execution , can raise excepetion : return : Execution result : rtype : kser . result . Result"""
if result : self . result += result with opentracing . tracer . start_span ( obj = self , child_of = KserSpan . extract_span ( self ) , span_factory = KserSpan ) as span : self . result = self . _onsuccess ( self . _postrun ( self . _run ( ) ) ) span . obj = self return self . result
def _select_input ( self ) : """Select current line ( without selecting console prompt )"""
line , index = self . get_position ( 'eof' ) if self . current_prompt_pos is None : pline , pindex = line , index else : pline , pindex = self . current_prompt_pos self . setSelection ( pline , pindex , line , index )
def from_dict ( d ) : """Re - create the noise model from a dictionary representation . : param Dict [ str , Any ] d : The dictionary representation . : return : The restored noise model . : rtype : NoiseModel"""
return NoiseModel ( gates = [ KrausModel . from_dict ( t ) for t in d [ "gates" ] ] , assignment_probs = { int ( qid ) : np . array ( a ) for qid , a in d [ "assignment_probs" ] . items ( ) } , )
def find_button ( browser , value ) : """Find a button with the given value . Searches for the following different kinds of buttons : < input type = " submit " > < input type = " reset " > < input type = " button " > < input type = " image " > < button > < { a , p , div , span , . . . } role = " butto...
field_types = ( 'submit' , 'reset' , 'button-element' , 'button' , 'image' , 'button-role' , ) return reduce ( operator . add , ( find_field_with_value ( browser , field_type , value ) for field_type in field_types ) )
def list_all_defaults ( self ) : # type : ( ) - > Dict [ str , List [ SkillEntry ] ] """Returns { ' skill _ group ' : [ SkillEntry ( ' name ' ) ] }"""
skills = self . list ( ) name_to_skill = { skill . name : skill for skill in skills } defaults = { group : [ ] for group in self . SKILL_GROUPS } for section_name , skill_names in self . repo . get_default_skill_names ( ) : section_skills = [ ] for skill_name in skill_names : if skill_name in name_to_sk...
def StripTypeInfo ( rendered_data ) : """Strips type information from rendered data . Useful for debugging ."""
if isinstance ( rendered_data , ( list , tuple ) ) : return [ StripTypeInfo ( d ) for d in rendered_data ] elif isinstance ( rendered_data , dict ) : if "value" in rendered_data and "type" in rendered_data : return StripTypeInfo ( rendered_data [ "value" ] ) else : result = { } for k...
def send_news_message ( self , user_id , media_id , kf_account = None ) : """发送永久素材中的图文消息 。 : param user _ id : 用户 ID 。 就是你收到的 ` Message ` 的 source : param media _ id : 媒体文件 ID : param kf _ account : 发送消息的客服账户 , 默认值为 None , None 为不指定 : return : 返回的 JSON 数据包"""
data = { "touser" : user_id , "msgtype" : "mpnews" , "mpnews" : { "media_id" : media_id } } if kf_account is not None : data [ 'customservice' ] = { 'kf_account' : kf_account } return self . post ( url = "https://api.weixin.qq.com/cgi-bin/message/custom/send" , data = data )
def implode_multi_values ( self , name , data ) : """Due to the way Angular organizes it model , when Form data is sent via a POST request , then for this kind of widget , the posted data must to be converted into a format suitable for Django ' s Form validation ."""
mkeys = [ k for k in data . keys ( ) if k . startswith ( name + '.' ) ] mvls = [ data . pop ( k ) [ 0 ] for k in mkeys ] if mvls : data . setlist ( name , mvls )
def recursive_get ( obj , key ) : '''Get an attribute or a key recursively . : param obj : The object to fetch attribute or key on : type obj : object | dict : param key : Either a string in dotted - notation ar an array of string : type key : string | list | tuple'''
if not obj or not key : return parts = key . split ( '.' ) if isinstance ( key , basestring ) else key key = parts . pop ( 0 ) if isinstance ( obj , dict ) : value = obj . get ( key , None ) else : value = getattr ( obj , key , None ) return recursive_get ( value , parts ) if parts else value
def pdfextract_dois ( pdf_file ) : """Extract DOIs of references using ` pdfextract < https : / / github . com / CrossRef / pdfextract > ` _ . . . note : : See ` ` libbmc . citations . pdf . pdfextract ` ` function as this one is just a wrapper around it . See ` ` libbmc . citations . plaintext . get _ cited ...
# Call pdf - extract on the PDF file references = pdfextract ( pdf_file ) # Parse the resulting XML root = ET . fromstring ( references ) plaintext_references = [ e . text for e in root . iter ( "reference" ) ] # Call the plaintext methods to fetch DOIs return plaintext . get_cited_dois ( plaintext_references )
def get_logger ( ) : """Get or create logger ( if it does not exist ) @ rtype : RootLogger"""
name = Logr . get_logger_name ( ) if name not in Logr . loggers : Logr . configure_check ( ) Logr . loggers [ name ] = logging . Logger ( name ) Logr . loggers [ name ] . addHandler ( Logr . handler ) return Logr . loggers [ name ]
def _calculate_progress ( self , match ) : '''Calculates the final progress value found by the regex'''
if not self . progress_expr : return safe_float ( match . group ( 1 ) ) else : return self . _eval_progress ( match )
def _peek_unicode ( self , is_long ) : # type : ( bool ) - > Tuple [ Optional [ str ] , Optional [ str ] ] """Peeks ahead non - intrusively by cloning then restoring the initial state of the parser . Returns the unicode value is it ' s a valid one else None ."""
# we always want to restore after exiting this scope with self . _state ( save_marker = True , restore = True ) : if self . _current not in { "u" , "U" } : raise self . parse_error ( InternalParserError , "_peek_unicode() entered on non-unicode value" ) self . inc ( ) # Dropping prefix self . ma...
def _validate_entity_cls ( self , entity_cls ) : """Validate that Entity is a valid class"""
# Import here to avoid cyclic dependency from protean . core . entity import Entity if not issubclass ( entity_cls , Entity ) : raise AssertionError ( f'Entity {entity_cls.__name__} must be subclass of `Entity`' ) if entity_cls . meta_ . abstract is True : raise NotSupportedError ( f'{entity_cls.__name__} class...
def transpose_nested_dictionary ( nested_dict ) : """Given a nested dictionary from k1 - > k2 > value transpose its outer and inner keys so it maps k2 - > k1 - > value ."""
result = defaultdict ( dict ) for k1 , d in nested_dict . items ( ) : for k2 , v in d . items ( ) : result [ k2 ] [ k1 ] = v return result
def groups_invite ( self , * , channel : str , user : str , ** kwargs ) -> SlackResponse : """Invites a user to a private channel . Args : channel ( str ) : The group id . e . g . ' G1234567890' user ( str ) : The user id . e . g . ' U1234567890'"""
self . _validate_xoxp_token ( ) kwargs . update ( { "channel" : channel , "user" : user } ) return self . api_call ( "groups.invite" , json = kwargs )
def _infer_sig_len ( file_name , fmt , n_sig , dir_name , pb_dir = None ) : """Infer the length of a signal from a dat file . Parameters file _ name : str Name of the dat file fmt : str WFDB fmt of the dat file n _ sig : int Number of signals contained in the dat file Notes sig _ len * n _ sig * b...
if pb_dir is None : file_size = os . path . getsize ( os . path . join ( dir_name , file_name ) ) else : file_size = download . _remote_file_size ( file_name = file_name , pb_dir = pb_dir ) sig_len = int ( file_size / ( BYTES_PER_SAMPLE [ fmt ] * n_sig ) ) return sig_len
def exec_nb_cmd ( self , cmd ) : '''Yield None until cmd finished'''
r_out = [ ] r_err = [ ] rcode = None cmd = self . _cmd_str ( cmd ) logmsg = 'Executing non-blocking command: {0}' . format ( cmd ) if self . passwd : logmsg = logmsg . replace ( self . passwd , ( '*' * 6 ) ) log . debug ( logmsg ) for out , err , rcode in self . _run_nb_cmd ( cmd ) : if out is not None : ...
def get_short_annotations ( annotations ) : """Converts full GATK annotation name to the shortened version : param annotations : : return :"""
# Annotations need to match VCF header short_name = { 'QualByDepth' : 'QD' , 'FisherStrand' : 'FS' , 'StrandOddsRatio' : 'SOR' , 'ReadPosRankSumTest' : 'ReadPosRankSum' , 'MappingQualityRankSumTest' : 'MQRankSum' , 'RMSMappingQuality' : 'MQ' , 'InbreedingCoeff' : 'ID' } short_annotations = [ ] for annotation in annotat...
def mark_offer_as_win ( self , offer_id ) : """Mark offer as win : param offer _ id : the offer id : return Response"""
return self . _create_put_request ( resource = OFFERS , billomat_id = offer_id , command = WIN , )
def neg_loglik ( self , beta ) : """Creates the negative log - likelihood of the model Parameters beta : np . array Contains untransformed starting values for latent variables Returns The negative logliklihood of the model"""
lmda , Y , _ , theta = self . _model ( beta ) return - np . sum ( ss . t . logpdf ( x = Y , df = self . latent_variables . z_list [ - ( len ( self . X_names ) * 2 ) - 2 ] . prior . transform ( beta [ - ( len ( self . X_names ) * 2 ) - 2 ] ) , loc = theta , scale = np . exp ( lmda / 2.0 ) ) )
def assert_array ( A , shape = None , uniform = None , ndim = None , size = None , dtype = None , kind = None ) : r"""Asserts whether the given array or sparse matrix has the given properties Parameters A : ndarray , scipy . sparse matrix or array - like the array under investigation shape : shape , optiona...
try : if shape is not None : if not np . array_equal ( np . shape ( A ) , shape ) : raise AssertionError ( 'Expected shape ' + str ( shape ) + ' but given array has shape ' + str ( np . shape ( A ) ) ) if uniform is not None : shapearr = np . array ( np . shape ( A ) ) is_uni...
def deep_get ( d , * keys , default = None ) : """Recursive safe search in a dictionary of dictionaries . Args : d : the dictionary to work with * keys : the list of keys to work with default : the default value to return if the recursive search did not succeed Returns : The value wich was found recursi...
for key in keys : try : d = d [ key ] except ( KeyError , IndexError , TypeError ) : return default return d
def model_config ( instance_type , model , role = None , image = None ) : """Export Airflow model config from a SageMaker model Args : instance _ type ( str ) : The EC2 instance type to deploy this Model to . For example , ' ml . p2 . xlarge ' model ( sagemaker . model . FrameworkModel ) : The SageMaker model...
s3_operations = { } model . image = image or model . image if isinstance ( model , sagemaker . model . FrameworkModel ) : container_def = prepare_framework_container_def ( model , instance_type , s3_operations ) else : container_def = model . prepare_container_def ( instance_type ) base_name = utils . base_...
def matches ( self , object ) : """< Purpose > Return True if ' object ' matches this schema , False if it doesn ' t . If the caller wishes to signal an error on a failed match , check _ match ( ) should be called , which will raise a ' exceptions . FormatError ' exception ."""
try : self . check_match ( object ) except securesystemslib . exceptions . FormatError : return False else : return True
def notify_created ( room , event , user ) : """Notifies about the creation of a chatroom . : param room : the chatroom : param event : the event : param user : the user performing the action"""
tpl = get_plugin_template_module ( 'emails/created.txt' , chatroom = room , event = event , user = user ) _send ( event , tpl )
def complete_list_value ( self , return_type : GraphQLList [ GraphQLOutputType ] , field_nodes : List [ FieldNode ] , info : GraphQLResolveInfo , path : ResponsePath , result : Iterable [ Any ] , ) -> AwaitableOrValue [ Any ] : """Complete a list value . Complete a list value by completing each item in the list w...
if not isinstance ( result , Iterable ) or isinstance ( result , str ) : raise TypeError ( "Expected Iterable, but did not find one for field" f" {info.parent_type.name}.{info.field_name}." ) # This is specified as a simple map , however we ' re optimizing the path where # the list contains no coroutine objects by ...
def promote_alert_to_case ( self , alert_id ) : """This uses the TheHiveAPI to promote an alert to a case : param alert _ id : Alert identifier : return : TheHive Case : rtype : json"""
req = self . url + "/api/alert/{}/createCase" . format ( alert_id ) try : return requests . post ( req , headers = { 'Content-Type' : 'application/json' } , proxies = self . proxies , auth = self . auth , verify = self . cert , data = json . dumps ( { } ) ) except requests . exceptions . RequestException as the_exc...
def append_attribute ( self , name , value , content ) : """Append an attribute name / value into L { Content . data } . @ param name : The attribute name @ type name : basestring @ param value : The attribute ' s value @ type value : basestring @ param content : The current content being unmarshalled . ...
type = self . resolver . findattr ( name ) if type is None : log . warn ( 'attribute (%s) type, not-found' , name ) else : value = self . translated ( value , type ) Core . append_attribute ( self , name , value , content )
def render_obs ( self , obs ) : """Render a frame given an observation ."""
start_time = time . time ( ) self . _obs = obs self . check_valid_queued_action ( ) self . _update_camera ( point . Point . build ( self . _obs . observation . raw_data . player . camera ) ) for surf in self . _surfaces : # Render that surface . surf . draw ( surf ) mouse_pos = self . get_mouse_pos ( ) if mouse_pos...
def _cleanstarlog ( file_in ) : """cleaning history . data or star . log file , e . g . to take care of repetitive restarts . private , should not be called by user directly Parameters file _ in : string Typically the filename of the mesa output history . data or star . log file , creates a clean file c...
file_out = file_in + 'sa' f = open ( file_in ) lignes = f . readlines ( ) f . close ( ) nb = np . array ( [ ] , dtype = int ) # model number nb = np . concatenate ( ( nb , [ int ( lignes [ len ( lignes ) - 1 ] . split ( ) [ 0 ] ) ] ) ) nbremove = np . array ( [ ] , dtype = int ) # model number i = - 1 for i in np . ara...
async def get_user_data ( self ) : """Get Tautulli userdata ."""
userdata = { } sessions = self . session_data . get ( 'sessions' , { } ) try : async with async_timeout . timeout ( 8 , loop = self . _loop ) : for username in self . tautulli_users : userdata [ username ] = { } userdata [ username ] [ 'Activity' ] = None for session in s...
def _validate ( self , key , val , arg_types ) : """Ensures that the key and the value are valid arguments to be used with the feed ."""
if key in arg_types : arg_type = arg_types [ key ] else : if ANY_ARG not in arg_types : raise CloudantArgumentError ( 116 , key ) arg_type = arg_types [ ANY_ARG ] if arg_type == ANY_TYPE : return if ( not isinstance ( val , arg_type ) or ( isinstance ( val , bool ) and int in arg_type ) ) : ...
def slugify ( text , delim = u'-' ) : """Generate an ASCII - only slug ."""
result = [ ] for word in _punct_re . split ( text . lower ( ) ) : result . extend ( unidecode ( word ) . split ( ) ) return unicode ( delim . join ( result ) )
def warning ( * args ) : """Display warning message via stderr or GUI ."""
if sys . stdin . isatty ( ) : print ( 'WARNING:' , * args , file = sys . stderr ) else : notify_warning ( * args )
def start ( self , future ) : """Execute Future . Return the Future ' s result , or raise its exception . : param future : : return :"""
self . _check_frozen ( ) self . _freeze = True loop : asyncio . AbstractEventLoop = self . loop try : loop . run_until_complete ( self . _startup_polling ( ) ) result = loop . run_until_complete ( future ) except ( KeyboardInterrupt , SystemExit ) : result = None loop . stop ( ) finally : loop . run...
def main ( ) : """Main entrypoint for command - line webserver ."""
parser = argparse . ArgumentParser ( ) parser . add_argument ( "-H" , "--host" , help = "Web server Host address to bind to" , default = "0.0.0.0" , action = "store" , required = False ) parser . add_argument ( "-p" , "--port" , help = "Web server Port to bind to" , default = 8080 , action = "store" , required = False ...
def update_config ( self ) : """Update the configuration files according to the current in - memory SExtractor configuration ."""
# - - Write filter configuration file # First check the filter itself filter = self . config [ 'FILTER_MASK' ] rows = len ( filter ) cols = len ( filter [ 0 ] ) # May raise ValueError , OK filter_f = __builtin__ . open ( self . config [ 'FILTER_NAME' ] , 'w' ) filter_f . write ( "CONV NORM\n" ) filter_f . write ( "# %d...
def handle_device_json ( self , data ) : """Manage the device json list ."""
self . _device_json . insert ( 0 , data ) self . _device_json . pop ( )
def merge_two ( one , other , merge_strategy = MergeStrategy . UNION , silent = False , pixel_strategy = PixelStrategy . FIRST ) : # type : ( GeoRaster2 , GeoRaster2 , MergeStrategy , bool , PixelStrategy ) - > GeoRaster2 """Merge two rasters into one . Parameters one : GeoRaster2 Left raster to merge . oth...
other_res = _prepare_other_raster ( one , other ) if other_res is None : if silent : return one else : raise ValueError ( "rasters do not intersect" ) else : other = other . copy_with ( image = other_res . image , band_names = other_res . band_names ) # To make MyPy happy # Create a list of ...
def flowtable ( self ) : """get a flat flow table globally"""
ftable = dict ( ) for table in self . flow_table : for k , v in table . items ( ) : if k not in ftable : ftable [ k ] = set ( v ) else : [ ftable [ k ] . add ( i ) for i in v ] # convert set to list for k in ftable : ftable [ k ] = list ( ftable [ k ] ) return ftable
def cmd ( send , msg , args ) : """Changes the output filter . Syntax : { command } [ - - channel channel ] < filter | - - show | - - list | - - reset | - - chain filter , [ filter2 , . . . ] >"""
if args [ 'type' ] == 'privmsg' : send ( 'Filters must be set in channels, not via private message.' ) return isadmin = args [ 'is_admin' ] ( args [ 'nick' ] ) parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--channel' , nargs = '?' , default = args [ 'target' ] ) group = parser . ...
def round_linestring_coords ( ls , precision ) : """Round the coordinates of a shapely LineString to some decimal precision . Parameters ls : shapely LineString the LineString to round the coordinates of precision : int decimal precision to round coordinates to Returns LineString"""
return LineString ( [ [ round ( x , precision ) for x in c ] for c in ls . coords ] )
def _createAbsMagEstimationDict ( ) : """loads magnitude _ estimation . dat which is from http : / / xoomer . virgilio . it / hrtrace / Sk . htm on 24/01/2014 and based on Schmid - Kaler ( 1982) creates a dict in the form [ Classletter ] [ ClassNumber ] [ List of values for each L Class ]"""
magnitude_estimation_filepath = resource_filename ( __name__ , 'data/magnitude_estimation.dat' ) raw_table = np . loadtxt ( magnitude_estimation_filepath , '|S5' ) absMagDict = { 'O' : { } , 'B' : { } , 'A' : { } , 'F' : { } , 'G' : { } , 'K' : { } , 'M' : { } } for row in raw_table : if sys . hexversion >= 0x03000...
def ReadContainers ( self , database_link , options = None ) : """Reads all collections in a database . : param str database _ link : The link to the database . : param dict options : The request options for the request . : return : Query Iterable of Collections . : rtype : query _ iterable . QueryIte...
if options is None : options = { } return self . QueryContainers ( database_link , None , options )
def bin_kb_dense ( M , positions , length = 10 , contigs = None ) : """Perform binning with a fixed genomic length in kilobase pairs ( kb ) . Fragments will be binned such that their total length is closest to the specified input . If a contig list is specified , binning will be performed such that fragment...
unit = 10 ** 3 ul = unit * length unit = positions / ul n = len ( positions ) idx = [ i for i in range ( n - 1 ) if np . ceil ( unit [ i ] ) < np . ceil ( unit [ i + 1 ] ) ] binned_positions = positions [ idx ] m = len ( idx ) - 1 N = np . zeros ( ( m , m ) ) for i in range ( m ) : N [ i ] = np . array ( [ M [ idx ...
def get_default_jvm_path ( ) : """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"""
if sys . platform == "cygwin" : # Cygwin from . _cygwin import WindowsJVMFinder finder = WindowsJVMFinder ( ) elif sys . platform == "win32" : # Windows from . _windows import WindowsJVMFinder finder = WindowsJVMFinder ( ) elif sys . platform == "darwin" : # Mac OS X from . _darwin import DarwinJVMF...
def get_graph_by_most_recent ( self , name : str ) -> Optional [ BELGraph ] : """Get the most recently created network with the given name as a : class : ` pybel . BELGraph ` ."""
network = self . get_most_recent_network_by_name ( name ) if network is None : return return network . as_bel ( )
def _dockerKill ( containerName , action ) : """Deprecated . Kills the specified container . : param str containerName : The name of the container created by docker _ call : param int action : What action should be taken on the container ?"""
running = containerIsRunning ( containerName ) if running is None : # This means that the container doesn ' t exist . We will see this if the # container was run with - - rm and has already exited before this call . logger . debug ( 'The container with name "%s" appears to have already been ' 'removed. Nothing to ...
def setup_gui ( self ) : """Setup the main layout of the widget ."""
layout = QGridLayout ( self ) layout . setContentsMargins ( 0 , 0 , 0 , 0 ) layout . addWidget ( self . canvas , 0 , 1 ) layout . addLayout ( self . setup_toolbar ( ) , 0 , 3 , 2 , 1 ) layout . setColumnStretch ( 0 , 100 ) layout . setColumnStretch ( 2 , 100 ) layout . setRowStretch ( 1 , 100 )
def convert_pmod ( pmod ) : """Update BEL1 pmod ( ) protein modification term"""
if pmod . args [ 0 ] . value in spec [ "bel1_migration" ] [ "protein_modifications" ] : pmod . args [ 0 ] . value = spec [ "bel1_migration" ] [ "protein_modifications" ] [ pmod . args [ 0 ] . value ] return pmod
def lowpass ( ts , cutoff_hz , order = 3 ) : """forward - backward butterworth low - pass filter"""
orig_ndim = ts . ndim if ts . ndim is 1 : ts = ts [ : , np . newaxis ] channels = ts . shape [ 1 ] fs = ( len ( ts ) - 1.0 ) / ( ts . tspan [ - 1 ] - ts . tspan [ 0 ] ) nyq = 0.5 * fs cutoff = cutoff_hz / nyq b , a = signal . butter ( order , cutoff , btype = 'low' ) if not np . all ( np . abs ( np . roots ( a ) ) ...