signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _parse_game_date_and_location ( self , boxscore ) : """Retrieve the game ' s date and location . The date and location of the game follow a more complicated parsing scheme and should be handled differently from other tags . Both fields are separated by a newline character ( ' \n ' ) with the first line be...
scheme = BOXSCORE_SCHEME [ 'time' ] items = [ i . text ( ) for i in boxscore ( scheme ) . items ( ) ] game_info = items [ 0 ] . split ( '\n' ) time = '' date = '' stadium = '' for line in game_info : time_match = re . findall ( r'(\d:\d\d|\d\d:\d\d)' , line . lower ( ) ) if len ( time_match ) > 0 : time...
def write_bits ( self , bits ) : """Write the bits to the stream . Add the bits to the existing unflushed bits and write complete bytes to the stream ."""
for bit in bits : self . _bits . append ( bit ) while len ( self . _bits ) >= 8 : byte_bits = [ self . _bits . popleft ( ) for x in six . moves . range ( 8 ) ] byte = bits_to_bytes ( byte_bits ) self . _stream . write ( byte )
def stmt2enum ( enum_type , declare = True , assign = True , wrap = True ) : """Returns a dzn enum declaration from an enum type . Parameters enum _ type : Enum The enum to serialize . declare : bool Whether to include the ` ` enum ` ` declatation keyword in the statement or just the assignment . assi...
if not ( declare or assign ) : raise ValueError ( 'The statement must be a declaration or an assignment.' ) stmt = [ ] if declare : stmt . append ( 'enum ' ) stmt . append ( enum_type . __name__ ) if assign : val_str = [ ] for v in list ( enum_type ) : val_str . append ( v . name ) val_str =...
def end_of_history ( self , e ) : u'''Move to the end of the input history , i . e . , the line currently being entered .'''
self . _history . end_of_history ( self . l_buffer ) self . finalize ( )
def _build ( self , src , path , dest , mtime ) : """Calls ` build ` after testing that at least one output file ( as returned by ` _ outputs ( ) ` does not exist or is older than ` mtime ` . If the build fails , the build time is recorded and no other builds will be attempted on ` input ` until this method i...
input_path = os . path . join ( src , path ) output_paths = [ os . path . join ( dest , output ) for output in self . _outputs ( src , path ) ] if path in self . failures and mtime <= self . failures [ path ] : # the input file was not modified since the last recorded failure # as such , assume that the task will fail ...
def invalidate_m2m_cache ( sender , instance , model , ** kwargs ) : """Signal receiver for models to invalidate model cache for many - to - many relationship . Parameters sender The model class instance The instance whose many - to - many relation is updated . model The class of the objects that are ...
logger . debug ( 'Received m2m_changed signals from sender {0}' . format ( sender ) ) update_model_cache ( instance . _meta . db_table ) update_model_cache ( model . _meta . db_table )
def set_or_edit_conditional_breakpoint ( self ) : """Set / Edit conditional breakpoint"""
editorstack = self . get_current_editorstack ( ) if editorstack is not None : self . switch_to_plugin ( ) editorstack . set_or_edit_conditional_breakpoint ( )
def is_link_local ( link_target ) : """: param link _ target : The target of a symbolic link , as given by os . readlink ( ) : type link _ target : string : returns : A boolean indicating the link is local to the current directory . This is defined to mean that os . path . isabs ( link _ target ) = = False ...
is_local = ( not os . path . isabs ( link_target ) ) if is_local : # make sure that the path NEVER extends outside the resources directory ! d , l = os . path . split ( link_target ) link_parts = [ ] while l : link_parts . append ( l ) d , l = os . path . split ( d ) curr_path = os . sep...
def packages_dict ( self ) : """All packages in this RPM spec as a dictionary . You can access the individual packages by their package name , e . g . , git _ spec . packages _ dict [ ' git - doc ' ]"""
assert self . packages return dict ( zip ( [ package . name for package in self . packages ] , self . packages ) )
def connect_direct ( self , device , calibration = True ) : """Establish a connection to a single SK8. Args : device : either a : class : ` ScanResult ` or a plain hardware address string in xx : xx : xx : xx : xx : xx format . calibration ( bool ) : True to attempt to load calibration data for this devic...
# convert string address into a ScanResult if needed if not isinstance ( device , ScanResult ) : if isinstance ( device , str ) : device = ScanResult ( device , fmt_addr_raw ( device ) ) elif isinstance ( device , unicode ) : device = device . encode ( 'ascii' ) device = ScanResult ( dev...
def to_javascript_ ( self , table_name : str = "data" ) -> str : """Convert the main dataframe to javascript code : param table _ name : javascript variable name , defaults to " data " : param table _ name : str , optional : return : a javascript constant with the data : rtype : str : example : ` ` ds . t...
try : renderer = pytablewriter . JavaScriptTableWriter data = self . _build_export ( renderer , table_name ) return data except Exception as e : self . err ( e , "Can not convert data to javascript code" )
def _format_variants ( self , variant , index , case_obj , add_all_info = False ) : """Return a Variant object Format variant make a variant that includes enough information for the variant view . If add _ all _ info then all transcripts will be parsed Args : variant ( cython2 . Variant ) : A variant obje...
header_line = self . head . header # Get the individual ids for individuals in vcf file vcf_individuals = set ( [ ind_id for ind_id in self . head . individuals ] ) # Create a info dict : info_dict = dict ( variant . INFO ) chrom = variant . CHROM if chrom . startswith ( 'chr' ) or chrom . startswith ( 'CHR' ) : ch...
def patch_mutating_webhook_configuration ( self , name , body , ** kwargs ) : """partially update the specified MutatingWebhookConfiguration This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . patch _ mutating _ w...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . patch_mutating_webhook_configuration_with_http_info ( name , body , ** kwargs ) else : ( data ) = self . patch_mutating_webhook_configuration_with_http_info ( name , body , ** kwargs ) return data
def extend ( self ) : """Extend the OAuth token ."""
graph = GraphAPI ( ) response = graph . get ( 'oauth/access_token' , client_id = FACEBOOK_APPLICATION_ID , client_secret = FACEBOOK_APPLICATION_SECRET_KEY , grant_type = 'fb_exchange_token' , fb_exchange_token = self . token ) components = parse_qs ( response ) self . token = components [ 'access_token' ] [ 0 ] self . ...
def candle_lighting ( self ) : """Return the time for candle lighting , or None if not applicable ."""
today = HDate ( gdate = self . date , diaspora = self . location . diaspora ) tomorrow = HDate ( gdate = self . date + dt . timedelta ( days = 1 ) , diaspora = self . location . diaspora ) # If today is a Yom Tov or Shabbat , and tomorrow is a Yom Tov or # Shabbat return the havdalah time as the candle lighting time . ...
def generate_message ( contract : Contract , condition_kwargs : Mapping [ str , Any ] ) -> str : """Generate the message upon contract violation ."""
# pylint : disable = protected - access parts = [ ] # type : List [ str ] if contract . location is not None : parts . append ( "{}:\n" . format ( contract . location ) ) if contract . description is not None : parts . append ( "{}: " . format ( contract . description ) ) lambda_inspection = None # type : Optio...
def rest_get_stream ( self , url , session = None , verify = True , cert = None ) : """Perform a chunked GET request to url with requests . session This is specifically to download files ."""
res = session . get ( url , stream = True , verify = verify , cert = cert ) return res . raw , res . status_code
def __update_existing ( self , msg , req ) : """Propagate changes based on type of message . MUST be called within self . _ _ requests lock . Performs additional actions when solicited messages arrive ."""
req . _messages . append ( msg ) payload = msg [ M_PAYLOAD ] if msg [ M_TYPE ] in _RSP_TYPE_CREATION : if payload [ P_RESOURCE ] == R_SUB : # Add callback for feeddata with self . __pending_subs : if msg [ M_CLIENTREF ] in self . __pending_subs : callback = self . __pending_subs ...
def all_status ( self ) : """Return names , hall numbers , and the washers / dryers available for all rooms in the system > > > all _ laundry = l . all _ status ( )"""
laundry_rooms = { } for room in self . hall_to_link : laundry_rooms [ room ] = self . parse_a_hall ( room ) return laundry_rooms
def to_planar ( self , to_2D = None , normal = None , check = True ) : """Check to see if current vectors are all coplanar . If they are , return a Path2D and a transform which will transform the 2D representation back into 3 dimensions Parameters to _ 2D : ( 4,4 ) float Homogenous transformation matrix t...
# which vertices are actually referenced referenced = self . referenced_vertices # if nothing is referenced return an empty path if len ( referenced ) == 0 : return Path2D ( ) , np . eye ( 4 ) # no explicit transform passed if to_2D is None : # fit a plane to our vertices C , N = plane_fit ( self . vertices [ r...
def split_by_idx ( idxs , * a ) : """Split each array passed as * a , to a pair of arrays like this ( elements selected by idxs , the remaining elements ) This can be used to split multiple arrays containing training data to validation and training set . : param idxs [ int ] : list of indexes selected : param...
mask = np . zeros ( len ( a [ 0 ] ) , dtype = bool ) mask [ np . array ( idxs ) ] = True return [ ( o [ mask ] , o [ ~ mask ] ) for o in a ]
def get_states ( self , config_ids ) : """Generates state information for the selected container and its dependencies / dependents . : param config _ ids : MapConfigId tuples . : type config _ ids : list [ dockermap . map . input . MapConfigId ] : return : Iterable of configuration states . : rtype : collec...
input_paths = [ ( config_id , list ( self . get_dependency_path ( config_id ) ) ) for config_id in config_ids ] log . debug ( "Dependency paths from input: %s" , input_paths ) dependency_paths = merge_dependency_paths ( input_paths ) log . debug ( "Merged dependency paths: %s" , dependency_paths ) return itertools . ch...
def _validate_required ( self , attributes ) : """Ensure required attributes are present ."""
required_fulfilled = set ( self . _required ) . issubset ( set ( attributes ) ) if not required_fulfilled : raise ValueError ( "Not all required attributes fulfilled. Required: {required}" . format ( required = set ( self . _required ) ) )
def start_instance ( self , key_name , public_key_path , private_key_path , security_group , flavor , image_id , image_userdata , username = None , node_name = None , network_ids = None , price = None , timeout = None , ** kwargs ) : """Starts a new instance on the cloud using the given properties . The following...
connection = self . _connect ( ) log . debug ( "Checking keypair `%s`." , key_name ) # the ` _ check _ keypair ` method has to be called within a lock , # since it will upload the key if it does not exist and if this # happens for every node at the same time ec2 will throw an error # message ( see issue # 79) with Boto...
def update ( self ) : """Calulate the auxilary term . > > > from hydpy . models . llake import * > > > parameterstep ( ' 1d ' ) > > > simulationstep ( ' 12h ' ) > > > n ( 3) > > > v ( 0 . , 1e5 , 1e6) > > > q ( _ 1 = [ 0 . , 1 . , 2 . ] , _ 7 = [ 0 . , 2 . , 5 . ] ) > > > maxdt ( ' 12h ' ) > > > der...
con = self . subpars . pars . control der = self . subpars for ( toy , qs ) in con . q : setattr ( self , str ( toy ) , 2. * con . v + der . seconds / der . nmbsubsteps * qs ) self . refresh ( )
def is_fasta ( filename ) : """Check if filename is FASTA based on extension Return : Boolean"""
if re . search ( "\.fa*s[ta]*$" , filename , flags = re . I ) : return True elif re . search ( "\.fa$" , filename , flags = re . I ) : return True else : return False
def _detect_content_type ( self , filename ) : '''Determine the mimetype for a file . : param filename : Filename of file to detect .'''
name , ext = os . path . splitext ( filename ) if not ext : raise MessageError ( 'File requires an extension.' ) ext = ext . lower ( ) if ext . lstrip ( '.' ) in self . _banned_extensions : err = 'Extension "{0}" is not allowed.' raise MessageError ( err . format ( ext ) ) if not mimetypes . inited : mi...
def _learn ( connections , rng , learningSegments , activeInput , potentialOverlaps , initialPermanence , sampleSize , permanenceIncrement , permanenceDecrement , maxSynapsesPerSegment ) : """Adjust synapse permanences , grow new synapses , and grow new segments . @ param learningActiveSegments ( numpy array ) ...
# Learn on existing segments connections . adjustSynapses ( learningSegments , activeInput , permanenceIncrement , - permanenceDecrement ) # Grow new synapses . Calculate " maxNew " , the maximum number of synapses to # grow per segment . " maxNew " might be a number or it might be a list of # numbers . if sampleSize =...
def busy ( self ) : """Return if the connection is currently executing a query or is locked by a session that still exists . : rtype : bool"""
if self . handle . isexecuting ( ) : return True elif self . used_by is None : return False return not self . used_by ( ) is None
def join ( self , timeout = None ) : """Blocks until all items in the Queue have been gotten and processed . The count of unfinished tasks goes up whenever an item is added to the queue . The count goes down whenever a consumer thread calls task _ done ( ) to indicate the item was retrieved and all work on it...
self . all_tasks_done . acquire ( ) try : while self . unfinished_tasks : self . all_tasks_done . wait ( timeout ) finally : self . all_tasks_done . release ( )
def display_popup ( self , message , size_x = None , size_y = None , duration = 3 , is_input = False , input_size = 30 , input_value = None ) : """Display a centered popup . If is _ input is False : Display a centered popup with the given message during duration seconds If size _ x and size _ y : set the popu...
# Center the popup sentence_list = message . split ( '\n' ) if size_x is None : size_x = len ( max ( sentence_list , key = len ) ) + 4 # Add space for the input field if is_input : size_x += input_size if size_y is None : size_y = len ( sentence_list ) + 4 screen_x = self . screen . getmaxyx ( )...
def envify ( app = None , add_repo_to_path = True ) : """This will simply activate virtualenv on openshift ans returs the app in a wsgi . py or app . py in your openshift python web app - wsgi . py from shiftpy . wsgi _ utils import envify from myproject import app # wsgi expects an object named ' applica...
if getvar ( 'HOMEDIR' ) : if add_repo_to_path : sys . path . append ( os . path . join ( getvar ( 'REPO_DIR' ) ) ) sys . path . insert ( 0 , os . path . dirname ( __file__ ) or '.' ) virtenv = getvar ( 'PYTHON_DIR' ) + '/virtenv/' virtualenv = os . path . join ( virtenv , 'bin/activate_this.py' ...
def get_session ( * , env_vars = None , loop = None ) : """Return a new session object ."""
loop = loop or asyncio . get_event_loop ( ) return AioSession ( session_vars = env_vars , loop = loop )
def async_ ( fn ) : """Wrap the given function into a coroutine function ."""
@ functools . wraps ( fn ) async def wrapper ( * args , ** kwargs ) : return await fn ( * args , ** kwargs ) return wrapper
def drawBackground ( self , painter , rect ) : """When an area of the window is exposed , we just copy out of the server - side , off - screen pixmap to that area ."""
if not self . pixmap : return x1 , y1 , x2 , y2 = rect . getCoords ( ) width = x2 - x1 + 1 height = y2 - y1 + 1 # redraw the screen from backing pixmap rect = QtCore . QRect ( x1 , y1 , width , height ) painter . drawPixmap ( rect , self . pixmap , rect )
def skip_row ( self , instance , original ) : """Returns ` ` True ` ` if ` ` row ` ` importing should be skipped . Default implementation returns ` ` False ` ` unless skip _ unchanged = = True . Override this method to handle skipping rows meeting certain conditions . Use ` ` super ` ` if you want to preser...
if not self . _meta . skip_unchanged : return False for field in self . get_import_fields ( ) : try : # For fields that are models . fields . related . ManyRelatedManager # we need to compare the results if list ( field . get_value ( instance ) . all ( ) ) != list ( field . get_value ( original ) . ...
def sendPREMISEvent ( webRoot , eventType , agentIdentifier , eventDetail , eventOutcome , eventOutcomeDetail = None , linkObjectList = [ ] , eventDate = None , debug = False , eventIdentifier = None ) : """A function to format an event to be uploaded and send it to a particular CODA server in order to register i...
atomID = uuid . uuid1 ( ) . hex eventXML = createPREMISEventXML ( eventType = eventType , agentIdentifier = agentIdentifier , eventDetail = eventDetail , eventOutcome = eventOutcome , outcomeDetail = eventOutcomeDetail , eventIdentifier = eventIdentifier , eventDate = eventDate , linkObjectList = linkObjectList ) atomX...
def set_field_at ( self , index , * , name , value , inline = True ) : """Modifies a field to the embed object . The index must point to a valid pre - existing field . This function returns the class instance to allow for fluent - style chaining . Parameters index : : class : ` int ` The index of the fi...
try : field = self . _fields [ index ] except ( TypeError , IndexError , AttributeError ) : raise IndexError ( 'field index out of range' ) field [ 'name' ] = str ( name ) field [ 'value' ] = str ( value ) field [ 'inline' ] = inline return self
def itemize ( data ) : """The xmltodict . unparse requires we modify the shape of the input dictionary slightly . Instead of a dict of the form : { ' key ' : [ ' value1 ' , ' value2 ' ] } We must provide : { ' key ' : { ' item ' : [ ' value1 ' , ' value2 ' ] } }"""
if isinstance ( data , dict ) : ret = { } for key in data : ret [ key ] = itemize ( data [ key ] ) return ret elif isinstance ( data , list ) : return { 'item' : [ itemize ( value ) for value in data ] } else : return data
def clusterflow_pipelines_printout ( self ) : """Print the steps used in each Cluster Flow pipeline"""
data = dict ( ) html = '' for f , d in self . clusterflow_runfiles . items ( ) : pid = d . get ( 'pipeline_id' , 'unknown' ) data [ pid ] = [ d . get ( 'pipeline_name' ) , "\n" . join ( d . get ( 'pipeline_steps' , [ ] ) ) ] for pid , d in data . items ( ) : html += ''' <div class="panel pan...
def classes ( self , set_uri_or_id = None , nestedhierarchy = False ) : """Returns a dictionary of classes for the specified ( sub ) set ( if None , default , the main set is selected )"""
if set_uri_or_id and set_uri_or_id . startswith ( ( 'http://' , 'https://' ) ) : set_uri = set_uri_or_id else : set_uri = self . get_set_uri ( set_uri_or_id ) assert set_uri is not None classes = { } uri2idmap = { } for row in self . graph . query ( "SELECT ?classuri ?classid ?classlabel ?parentclass ?seqnr WH...
def onWith ( self , evnt , func ) : '''A context manager which can be used to add a callback and remove it when using a ` ` with ` ` statement . Args : evnt ( str ) : An event name func ( function ) : A callback function to receive event tufo'''
self . on ( evnt , func ) # Allow exceptions to propagate during the context manager # but ensure we cleanup our temporary callback try : yield self finally : self . off ( evnt , func )
def t_binaryValue ( t ) : r'[ + - ] ? [ 0-9 ] + [ bB ]'
# We must match [ 0-9 ] , and then check the validity of the binary number . # If we match [ 0-1 ] , the invalid binary number " 2b " would match # ' decimalValue ' 2 and ' IDENTIFIER ' b ' . if re . search ( r'[2-9]' , t . value ) is not None : msg = _format ( "Invalid binary number {0!A}" , t . value ) t . le...
def prepare_destruction ( self ) : """Prepares the model for destruction Un - registers itself as observer from the state machine and the root state"""
try : self . relieve_model ( self . state_machine_model ) assert self . __buffered_root_state_model is self . state_machine_model . root_state self . relieve_model ( self . __buffered_root_state_model ) self . state_machine_model = None self . __buffered_root_state_model = None self . modificati...
def list_fonts ( self , pattern , max_names ) : """Return a list of font names matching pattern . No more than max _ names will be returned ."""
r = request . ListFonts ( display = self . display , max_names = max_names , pattern = pattern ) return r . fonts
def match1 ( pattern , data , ** parse_kwargs ) : """Returns first matched value of pattern in data or None if no matches"""
matches = match ( pattern , data , ** parse_kwargs ) return matches [ 0 ] if matches else None
def _plot_MLmodel ( ax , sampler , modelidx , e_range , e_npoints , e_unit , sed ) : """compute and plot ML model"""
ML , MLp , MLerr , ML_model = _calc_ML ( sampler , modelidx , e_range = e_range , e_npoints = e_npoints ) f_unit , sedf = sed_conversion ( ML_model [ 0 ] , ML_model [ 1 ] . unit , sed ) ax . loglog ( ML_model [ 0 ] . to ( e_unit ) . value , ( ML_model [ 1 ] * sedf ) . to ( f_unit ) . value , color = "k" , lw = 2 , alph...
def convert_tuple_to_string ( incoming_tuple ) : """Function to convert a tuple to a string . Examples : convert _ tuple _ to _ string ( ( ' e ' , ' x ' , ' e ' , ' r ' , ' c ' , ' i ' , ' s ' , ' e ' , ' s ' ) ) - > ' exercises ' convert _ tuple _ to _ string ( ( ' p ' , ' y ' , ' t ' , ' h ' , ' o ' , ' n '...
return '' . join ( incoming_tuple )
def getStates ( self ) : '''Gets simulated consumers pLvl and mNrm for this period , but with the alteration that these represent perceived rather than actual values . Also calculates mLvlTrue , the true level of market resources that the individual has on hand . Parameters None Returns None'''
# Update consumers ' perception of their permanent income level pLvlPrev = self . pLvlNow self . pLvlNow = pLvlPrev * self . PermShkNow # Perceived permanent income level ( only correct if macro state is observed this period ) self . PlvlAggNow *= self . PermShkAggNow # Updated aggregate permanent productivity level se...
def robust_int ( v ) : """Parse an int robustly , ignoring commas and other cruft ."""
if isinstance ( v , int ) : return v if isinstance ( v , float ) : return int ( v ) v = str ( v ) . replace ( ',' , '' ) if not v : return None return int ( v )
def _strongly_connected_subgraph ( counts , weight = 1 , verbose = True ) : """Trim a transition count matrix down to its maximal strongly ergodic subgraph . From the counts matrix , we define a graph where there exists a directed edge between two nodes , ` i ` and ` j ` if ` counts [ i ] [ j ] > weight ` ....
n_states_input = counts . shape [ 0 ] n_components , component_assignments = csgraph . connected_components ( csr_matrix ( counts >= weight ) , connection = "strong" ) populations = np . array ( counts . sum ( 0 ) ) . flatten ( ) component_pops = np . array ( [ populations [ component_assignments == i ] . sum ( ) for i...
def load ( self , ladderName ) : """retrieve the ladder settings from saved disk file"""
self . name = ladderName # preset value to load self . filename with open ( self . filename , "rb" ) as f : data = f . read ( ) self . __dict__ . update ( json . loads ( data ) )
def compute_fov ( self , x : int , y : int , radius : int = 0 , light_walls : bool = True , algorithm : int = tcod . constants . FOV_RESTRICTIVE , ) -> None : """Compute a field - of - view on the current instance . Args : x ( int ) : Point of view , x - coordinate . y ( int ) : Point of view , y - coordinate...
lib . TCOD_map_compute_fov ( self . map_c , x , y , radius , light_walls , algorithm )
def list_images ( self ) : """list all available nspawn images : return : collection of instances of : class : ` conu . backend . nspawn . image . NspawnImage `"""
# Fedora - Cloud - Base - 27-1.6 . x86_64 raw no 601.7M Sun 2017-11-05 08:30:10 CET \ # Sun 2017-11-05 08:30:10 CET data = os . listdir ( CONU_IMAGES_STORE ) output = [ ] for name in data : output . append ( self . ImageClass ( name , pull_policy = ImagePullPolicy . NEVER ) ) return output
def bind ( self , attribute , cls , buffer , fmt , * , offset = 0 , stride = 0 , divisor = 0 , normalize = False ) -> None : '''Bind individual attributes to buffers . Args : location ( int ) : The attribute location . cls ( str ) : The attribute class . Valid values are ` ` f ` ` , ` ` i ` ` or ` ` d ` ` . ...
self . mglo . bind ( attribute , cls , buffer . mglo , fmt , offset , stride , divisor , normalize )
def to_match ( self ) : """Return a unicode object with the MATCH representation of this GlobalContextField ."""
self . validate ( ) mark_name , field_name = self . location . get_location_name ( ) validate_safe_string ( mark_name ) validate_safe_string ( field_name ) return u'%s.%s' % ( mark_name , field_name )
def perform_command ( self ) : """Perform command and return the appropriate exit code . : rtype : int"""
if len ( self . actual_arguments ) < 2 : return self . print_help ( ) input_file_path = self . actual_arguments [ 0 ] output_file_path = self . actual_arguments [ 1 ] output_html = self . has_option ( u"--output-html" ) if not self . check_input_file ( input_file_path ) : return self . ERROR_EXIT_CODE input_sm_...
def render_compressed ( self , package , package_name , package_type ) : """Render HTML for the package . If ` ` PIPELINE _ ENABLED ` ` is ` ` True ` ` , this will render the package ' s output file ( using : py : meth : ` render _ compressed _ output ` ) . Otherwise , this will render the package ' s source ...
if settings . PIPELINE_ENABLED : return self . render_compressed_output ( package , package_name , package_type ) else : return self . render_compressed_sources ( package , package_name , package_type )
def list_kubernetes_roles ( self , mount_point = 'kubernetes' ) : """GET / auth / < mount _ point > / role ? list = true : param mount _ point : The " path " the k8s auth backend was mounted on . Vault currently defaults to " kubernetes " . : type mount _ point : str . : return : Parsed JSON response from the...
url = 'v1/auth/{0}/role?list=true' . format ( mount_point ) return self . _adapter . get ( url ) . json ( )
def split_pkt ( pkt , assoclen , icvlen = 0 ) : """split the packet into associated data , plaintext or ciphertext , and optional ICV"""
data = raw ( pkt ) assoc = data [ : assoclen ] if icvlen : icv = data [ - icvlen : ] enc = data [ assoclen : - icvlen ] else : icv = b'' enc = data [ assoclen : ] return assoc , enc , icv
def dewpoint_from_specific_humidity ( specific_humidity , temperature , pressure ) : r"""Calculate the dewpoint from specific humidity , temperature , and pressure . Parameters specific _ humidity : ` pint . Quantity ` Specific humidity of air temperature : ` pint . Quantity ` Air temperature pressure :...
return dewpoint_rh ( temperature , relative_humidity_from_specific_humidity ( specific_humidity , temperature , pressure ) )
def encode ( self , sequence ) : """Encodes a ` ` sequence ` ` . Args : sequence ( str ) : String ` ` sequence ` ` to encode . Returns : torch . Tensor : Encoding of the ` ` sequence ` ` ."""
sequence = super ( ) . encode ( sequence ) sequence = self . tokenize ( sequence ) vector = [ self . stoi . get ( token , self . unknown_index ) for token in sequence ] if self . append_eos : vector . append ( self . eos_index ) return torch . tensor ( vector )
def matches ( self , string , fuzzy = 90 , fname_match = True , fuzzy_fragment = None , guess = False ) : '''Returns whether this : class : ` Concept ` matches ` ` string ` `'''
matches = [ ] for item in self . examples : m = best_match_from_list ( string , self . examples [ item ] , fuzzy , fname_match , fuzzy_fragment , guess ) if m : match = ConceptMatch ( self ) match . concept = self match . string = string match . item = item match . exampl...
def start ( component , exact ) : # type : ( str ) - > None """Create a new release . It will bump the current version number and create a release branch called ` release / < version > ` with one new commit ( the version bump ) . * * Example Config * * : : version _ file : ' src / mypkg / _ _ init _ _ . py ...
from peltak . extra . gitflow import logic logic . release . start ( component , exact )
def _deduplicate ( lst ) : """Auxiliary function to deduplicate lst ."""
out = [ ] for i in lst : if i not in out : out . append ( i ) return out
def ready ( self ) : """Read - only property indicating status of " value " property ."""
if self . __timeout < time . time ( ) : self . cancel ( ) return self . __queue . full ( ) and not self . __queue . empty ( )
def _resolve_paths ( self , * paths ) : """Resolve paths into a set of filenames ( no directories ) to check . External tools will handle directories as arguments differently , so for consistency we just want to pass them filenames . This method will recursively walk all directories and filter out any paths...
result = set ( ) for path in paths : if os . path . isdir ( path ) : for dirpath , _ , filenames in os . walk ( path ) : for filename in filenames : path = os . path . join ( dirpath , filename ) if path . startswith ( '.' ) : path = path [ 1 :...
def do_man ( self , args , arguments ) : """Usage : man COMMAND man [ - - noheader ] Options : - - norule no rst header Arguments : COMMAND the command to be printed Description : man Prints out the help pages man COMMAND Prints out the help page for a specific command"""
if arguments [ 'COMMAND' ] is None : print print "Commands" print 70 * "=" commands = [ k for k in dir ( self ) if k . startswith ( "do_" ) ] commands . sort ( ) else : print arguments commands = [ arguments [ 'COMMAND' ] ] for command in commands : what = command . replace ( "do_" , "" ...
def _update_column_info ( self ) : """Used for validation during parsing , and additional book - keeping . For internal use only ."""
del self . columnnames [ : ] del self . columntypes [ : ] del self . columnpytypes [ : ] for child in self . getElementsByTagName ( ligolw . Column . tagName ) : if self . validcolumns is not None : try : if self . validcolumns [ child . Name ] != child . Type : raise ligolw . El...
def cwd ( self , newdir ) : """Send the FTP CWD command : param newdir : Directory to change to"""
logger . debug ( 'Sending FTP cwd command. New Workding Directory: {}' . format ( newdir ) ) self . client . cwd ( newdir ) self . state [ 'current_dir' ] = self . client . pwd ( )
def main ( args = sys . argv ) : """Main command - line invocation ."""
try : opts , args = getopt . gnu_getopt ( args [ 1 : ] , 'p:o:jdt' , [ 'jspath=' , 'output=' , 'private' , 'json' , 'dependencies' , 'test' , 'help' ] ) opts = dict ( opts ) except getopt . GetoptError : usage ( ) sys . exit ( 2 ) run_and_exit_if ( opts , run_doctests , '--test' ) run_and_exit_if ( opts...
def enable_snmp ( self , address , community_string ) : """Enables SNMP . uWSGI server embeds a tiny SNMP server that you can use to integrate your web apps with your monitoring infrastructure . * http : / / uwsgi . readthedocs . io / en / latest / SNMP . html . . note : : SNMP server is started in the mast...
self . _set ( 'snmp' , address ) self . _set ( 'snmp-community' , community_string ) return self . _section
def log_to_console ( status = True , level = None ) : """Log events to the console . Args : status ( bool , Optional , Default = True ) whether logging to console should be turned on ( True ) or off ( False ) level ( string , Optional , Default = None ) : level of logging ; whichever level is chosen all h...
if status : if level is not None : LOGGER . setLevel ( level ) console_handler = logging . StreamHandler ( ) # create formatter formatter = logging . Formatter ( '%(levelname)s-%(name)s: %(message)s' ) # add formatter to handler console_handler . setFormatter ( formatter ) LOGGER . a...
async def send_game ( self , chat_id : base . Integer , game_short_name : base . String , disable_notification : typing . Union [ base . Boolean , None ] = None , reply_to_message_id : typing . Union [ base . Integer , None ] = None , reply_markup : typing . Union [ types . InlineKeyboardMarkup , None ] = None ) -> typ...
reply_markup = prepare_arg ( reply_markup ) payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . SEND_GAME , payload ) return types . Message ( ** result )
def getTextBlocks ( page , images = False ) : """Return the text blocks on a page . Notes : Lines in a block are concatenated with line breaks . Args : images : ( bool ) also return meta data of any images . Image data are never returned with this method . Returns : A list of the blocks . Each item co...
CheckParent ( page ) dl = page . getDisplayList ( ) flags = TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE if images : flags |= TEXT_PRESERVE_IMAGES tp = dl . getTextPage ( flags ) l = tp . _extractTextBlocks_AsList ( ) del tp del dl return l
def get ( key , default = - 1 ) : """Backport support for original codes ."""
if isinstance ( key , int ) : return TOS_ECN ( key ) if key not in TOS_ECN . _member_map_ : extend_enum ( TOS_ECN , key , default ) return TOS_ECN [ key ]
def slice_to_numerical_args ( slice_ , num_examples ) : """Translate a slice ' s attributes into numerical attributes . Parameters slice _ : : class : ` slice ` Slice for which numerical attributes are wanted . num _ examples : int Number of examples in the indexable that is to be sliced through . This ...
start = slice_ . start if slice_ . start is not None else 0 stop = slice_ . stop if slice_ . stop is not None else num_examples step = slice_ . step if slice_ . step is not None else 1 return start , stop , step
def spill ( directory , src ) : """Spill / unpack OCRD - ZIP bag at SRC to DEST SRC must exist an be an OCRD - ZIP DEST must not exist and be a directory"""
resolver = Resolver ( ) workspace_bagger = WorkspaceBagger ( resolver ) workspace = workspace_bagger . spill ( src , directory ) print ( workspace )
def extract_lrzip ( archive , compression , cmd , verbosity , interactive , outdir ) : """Extract a LRZIP archive ."""
cmdlist = [ cmd , '-d' ] if verbosity > 1 : cmdlist . append ( '-v' ) outfile = util . get_single_outfile ( outdir , archive ) cmdlist . extend ( [ "-o" , outfile , os . path . abspath ( archive ) ] ) return cmdlist
def enclosure_shell ( self ) : """A dictionary of path indexes which are ' shell ' paths , and values of ' hole ' paths . Returns corresponding : dict , { index of self . paths of shell : [ indexes of holes ] }"""
pairs = [ ( r , self . connected_paths ( r , include_self = False ) ) for r in self . root ] # OrderedDict to maintain corresponding order corresponding = collections . OrderedDict ( pairs ) return corresponding
def get_go2obj_unique ( go2obj ) : """If GO keys point to the same GOTerm , return new go2obj w / no duplicates ."""
# Find the unique GO Terms that are represented for each GO in go2obj goid2gokeys = cx . defaultdict ( set ) for goid , goobj in go2obj . items ( ) : goid2gokeys [ goobj . id ] . add ( goid ) go_unique = set ( ) for goid , gos_seen in goid2gokeys . items ( ) : # Return main GO ID , if it is present in the go2obj ke...
def clear ( self , chunk_size = 1000 , aggressive = False ) : """Will deindex all the value for the current field Parameters chunk _ size : int Default to 1000 , it ' s the number of instances to load at once if not in aggressive mode . aggressive : bool Default to ` ` False ` ` . When ` ` False ` ` , the...
assert self . attached_to_model , '`clear` can only be called on an index attached to the model field' if aggressive : keys = self . get_all_storage_keys ( ) with self . model . database . pipeline ( transaction = False ) as pipe : for key in keys : pipe . delete ( key ) pipe . execu...
def get_next_iteration ( self , iteration , iteration_kwargs = { } ) : """BO - HB uses ( just like Hyperband ) SuccessiveHalving for each iteration . See Li et al . ( 2016 ) for reference . Parameters iteration : int the index of the iteration to be instantiated Returns SuccessiveHalving : the Successiv...
# number of ' SH rungs ' s = self . max_SH_iter - 1 - ( iteration % self . max_SH_iter ) # number of configurations in that bracket n0 = int ( np . floor ( ( self . max_SH_iter ) / ( s + 1 ) ) * self . eta ** s ) ns = [ max ( int ( n0 * ( self . eta ** ( - i ) ) ) , 1 ) for i in range ( s + 1 ) ] return ( SuccessiveHal...
def extra_reading_spec ( self ) : """Additional data fields to store on disk and their decoders ."""
field_names = ( "frame_number" , "action" , "reward" , "done" ) data_fields = { name : tf . FixedLenFeature ( [ 1 ] , tf . int64 ) for name in field_names } decoders = { name : tf . contrib . slim . tfexample_decoder . Tensor ( tensor_key = name ) for name in field_names } return ( data_fields , decoders )
def get_led_mode ( self , led_id ) : """Return the led mode for led : led _ id : . @ led _ id Character in range A - F"""
if not self . _connected : return return self . _protocol . status . get ( "OTGW_LED_{}" . format ( led_id ) )
def sample ( polygon , count , factor = 1.5 , max_iter = 10 ) : """Use rejection sampling to generate random points inside a polygon . Parameters polygon : shapely . geometry . Polygon Polygon that will contain points count : int Number of points to return factor : float How many points to test per ...
bounds = np . reshape ( polygon . bounds , ( 2 , 2 ) ) extents = bounds . ptp ( axis = 0 ) hit = [ ] hit_count = 0 per_loop = int ( count * factor ) for i in range ( max_iter ) : # generate points inside polygons AABB points = np . random . random ( ( per_loop , 2 ) ) points = ( points * extents ) + bounds [ 0 ...
def calc_across_paths_textnodes ( paths_nodes , dbg = False ) : """Given a list of parent paths tupled with children textnodes , plus initialized feature values , we calculate the total and average string length of the parent ' s children textnodes ."""
# for ( path , [ textnodes ] , # num . of tnodes , # ttl strlen across tnodes , # avg strlen across tnodes . ] ) for path_nodes in paths_nodes : cnt = len ( path_nodes [ 1 ] [ 0 ] ) ttl = sum ( [ len ( s ) for s in paths_nodes [ 1 ] [ 0 ] ] ) # calculate total path_nodes [ 1 ] [ 1 ] = cnt # cardinal...
def gamma_automatic ( kpts = ( 1 , 1 , 1 ) , shift = ( 0 , 0 , 0 ) ) : """Convenient static constructor for an automatic Gamma centered Kpoint grid . Args : kpts : Subdivisions N _ 1 , N _ 2 and N _ 3 along reciprocal lattice vectors . Defaults to ( 1,1,1) shift : Shift to be applied to the kpoints . Defa...
return Kpoints ( "Automatic kpoint scheme" , 0 , Kpoints . supported_modes . Gamma , kpts = [ kpts ] , kpts_shift = shift )
def project_job_trigger_path ( cls , project , job_trigger ) : """Return a fully - qualified project _ job _ trigger string ."""
return google . api_core . path_template . expand ( "projects/{project}/jobTriggers/{job_trigger}" , project = project , job_trigger = job_trigger , )
def main ( ) : """NAME odp _ dcs _ magic . py DESCRIPTION converts ODP discrete sample format files to magic _ measurements format files SYNTAX odp _ dsc _ magic . py [ command line options ] OPTIONS - h : prints the help message and quits . - F FILE : specify output measurements file , default is m...
version_num = pmag . get_version ( ) meas_file = 'magic_measurements.txt' spec_file = 'er_specimens.txt' samp_file = 'er_samples.txt' site_file = 'er_sites.txt' ErSpecs , ErSamps , ErSites , ErLocs , ErCits = [ ] , [ ] , [ ] , [ ] , [ ] MagRecs = [ ] citation = "This study" dir_path , demag = '.' , 'NRM' args = sys . a...
def parse_tag ( self , dtype , count , offset_buf ) : """Interpret an Exif image tag data payload ."""
try : fmt = self . datatype2fmt [ dtype ] [ 0 ] * count payload_size = self . datatype2fmt [ dtype ] [ 1 ] * count except KeyError : msg = 'Invalid TIFF tag datatype ({0}).' . format ( dtype ) raise IOError ( msg ) if payload_size <= 4 : # Interpret the payload from the 4 bytes in the tag entry . ta...
def transformation_post ( node_id , info_in_id , info_out_id ) : """Transform an info . The ids of the node , info in and info out must all be in the url . You can also pass transformation _ type ."""
exp = experiment ( session ) # Get the parameters . transformation_type = request_parameter ( parameter = "transformation_type" , parameter_type = "known_class" , default = models . Transformation ) if type ( transformation_type ) == Response : return transformation_type # Check that the node etc . exists . node = ...
def payload_register ( ptype , klass , pid ) : """is used while a hook is running to let Juju know that a payload has been started ."""
cmd = [ 'payload-register' ] for x in [ ptype , klass , pid ] : cmd . append ( x ) subprocess . check_call ( cmd )
def _get_indent ( self , node ) : """Get node indentation level ."""
lineno = node . lineno if lineno > len ( self . _lines ) : return - 1 wsindent = self . _wsregexp . match ( self . _lines [ lineno - 1 ] ) return len ( wsindent . group ( 1 ) )
def set_channel_property ( self , channel_id , property_name , value ) : '''This function adds a property dataset to the given channel under the property name . Parameters channel _ id : int The channel id for which the property will be added property _ name : str A property stored by the RecordingExtra...
if isinstance ( channel_id , ( int , np . integer ) ) : if channel_id in self . get_channel_ids ( ) : if channel_id not in self . _channel_properties : self . _channel_properties [ channel_id ] = { } if isinstance ( property_name , str ) : self . _channel_properties [ channel...
def _instance_from_process ( self , process ) : """Default converter from psutil . Process to process instance classes for subclassing ."""
return ProcessManager ( name = process . name ( ) , pid = process . pid , process_name = process . name ( ) , metadata_base_dir = self . _metadata_base_dir )
def listener ( cls , name = None ) : """A decorator that marks a function as a listener . This is the cog equivalent of : meth : ` . Bot . listen ` . Parameters name : : class : ` str ` The name of the event being listened to . If not provided , it defaults to the function ' s name . Raises TypeError ...
if name is not None and not isinstance ( name , str ) : raise TypeError ( 'Cog.listener expected str but received {0.__class__.__name__!r} instead.' . format ( name ) ) def decorator ( func ) : actual = func if isinstance ( actual , staticmethod ) : actual = actual . __func__ if not inspect . is...
def startup ( name ) : '''Start Traffic Server on the local node . . . code - block : : yaml startup _ ats : trafficserver . startup'''
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } if __opts__ [ 'test' ] : ret [ 'comment' ] = 'Starting up local node' return ret __salt__ [ 'trafficserver.startup' ] ( ) ret [ 'result' ] = True ret [ 'comment' ] = 'Starting up local node' return ret
def lookup_comment_by_wordpress_id ( self , comment_id , comments ) : """Returns Django comment object with this wordpress id"""
for comment in comments : if comment . wordpress_id == comment_id : return comment
def find_rt_jar ( javahome = None ) : """Find the path to the Java standard library jar . The jar is expected to exist at the path ' jre / lib / rt . jar ' inside a standard Java installation directory . The directory is found using the following procedure : 1 . If the javehome argument is provided , use th...
if not javahome : if 'JAVA_HOME' in os . environ : javahome = os . environ [ 'JAVA_HOME' ] elif sys . platform == 'darwin' : # The default java binary on OS X is not part of a standard Oracle # install , so building paths relative to it does not work like it # does on other platforms . j...