signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def template_for_action ( self , action ) : """Returns the template to use for the passed in action"""
return "%s/%s_%s.html" % ( self . module_name . lower ( ) , self . model_name . lower ( ) , action )
def nextLunarEclipse ( date ) : """Returns the Datetime of the maximum phase of the next global lunar eclipse ."""
eclipse = swe . lunarEclipseGlobal ( date . jd , backward = False ) return Datetime . fromJD ( eclipse [ 'maximum' ] , date . utcoffset )
def run_bcl2fastq ( run_folder , ss_csv , config ) : """Run bcl2fastq for de - multiplexing and fastq generation . run _ folder - - directory of Illumina outputs ss _ csv - - Samplesheet CSV file describing samples ."""
bc_dir = os . path . join ( run_folder , "Data" , "Intensities" , "BaseCalls" ) output_dir = os . path . join ( run_folder , "fastq" ) if not os . path . exists ( os . path . join ( output_dir , "Makefile" ) ) : subprocess . check_call ( [ "configureBclToFastq.pl" , "--no-eamss" , "--input-dir" , bc_dir , "--output...
def prepare ( self , data_batch , sparse_row_id_fn = None ) : """Prepares two modules for processing a data batch . Usually involves switching bucket and reshaping . For modules that contain ` row _ sparse ` parameters in KVStore , it prepares the ` row _ sparse ` parameters based on the sparse _ row _ id _ f...
super ( SVRGModule , self ) . prepare ( data_batch , sparse_row_id_fn = sparse_row_id_fn ) self . _mod_aux . prepare ( data_batch , sparse_row_id_fn = sparse_row_id_fn )
def get_groups_by_name ( self , name , parent = None ) : """Retrieve all groups matching the given name and optionally filtered by the given parent node . : param name : The name of the group that has to be returned : param parent : A PBXGroup object where the object has to be retrieved from . If None all match...
groups = self . objects . get_objects_in_section ( u'PBXGroup' ) groups = [ group for group in groups if group . get_name ( ) == name ] if parent : return [ group for group in groups if parent . has_child ( group ) ] return groups
def _print_layers ( targets , components , tasks ) : """Print dependency information , grouping components based on their position in the dependency graph . Components with no dependnecies will be in layer 0 , components that only depend on layer 0 will be in layer 1 , and so on . If there ' s a circular depe...
layer = 0 expected_count = len ( tasks ) counts = { } def _add_layer ( resolved , dep_fn ) : nonlocal layer nonlocal counts nonlocal expected_count really_resolved = [ ] for resolved_task in resolved : resolved_component_tasks = counts . get ( resolved_task [ 0 ] , [ ] ) resolved_com...
def create ( obj : PersistedObject , obj_type : Type [ T ] , errors : Dict [ Type , Exception ] ) : """Helper method provided because we actually can ' t put that in the constructor , it creates a bug in Nose tests https : / / github . com / nose - devs / nose / issues / 725 : param obj : : param errors : a d...
e = NoParserFoundForUnionType ( '{obj} cannot be parsed as a {typ} because no parser could be found for any of ' 'the alternate types. Caught exceptions: {errs}' '' . format ( obj = obj , typ = get_pretty_type_str ( obj_type ) , errs = errors ) ) # save the errors e . errors = errors return e
def get_stdlib_path ( ) : """Returns the path to the standard lib for the current path installation . This function can be dropped and " sysconfig . get _ paths ( ) " used directly once Python 2.6 support is dropped ."""
if sys . version_info >= ( 2 , 7 ) : import sysconfig return sysconfig . get_paths ( ) [ 'stdlib' ] else : return os . path . join ( sys . prefix , 'lib' )
def linkify ( self , commands , notificationways ) : """Create link between objects : : * contacts - > notificationways : param notificationways : notificationways to link : type notificationways : alignak . objects . notificationway . Notificationways : return : None TODO : Clean this function"""
self . linkify_with_notificationways ( notificationways ) self . linkify_command_list_with_commands ( commands , 'service_notification_commands' ) self . linkify_command_list_with_commands ( commands , 'host_notification_commands' )
def get_portchannel_info_by_intf_output_lacp_actor_priority ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_portchannel_info_by_intf = ET . Element ( "get_portchannel_info_by_intf" ) config = get_portchannel_info_by_intf output = ET . SubElement ( get_portchannel_info_by_intf , "output" ) lacp = ET . SubElement ( output , "lacp" ) actor_priority = ET . SubElement ( lacp , "actor-priorit...
def _parse_world_info ( self , world_info_table ) : """Parses the World Information table from Tibia . com and adds the found values to the object . Parameters world _ info _ table : : class : ` list ` [ : class : ` bs4 . Tag ` ]"""
world_info = { } for row in world_info_table : cols_raw = row . find_all ( 'td' ) cols = [ ele . text . strip ( ) for ele in cols_raw ] field , value = cols field = field . replace ( "\xa0" , "_" ) . replace ( " " , "_" ) . replace ( ":" , "" ) . lower ( ) value = value . replace ( "\xa0" , " " ) ...
def list_resources ( self , lang ) : """Return a sequence of resources for a given lang . Each Resource is a dict containing the slug , name , i18n _ type , source _ language _ code and the category ."""
return registry . registry . http_handler . get ( '/api/2/project/%s/resources/' % ( self . get_project_slug ( lang ) , ) )
def customer_webhook_handler ( event ) : """Handle updates to customer objects . First determines the crud _ type and then handles the event if a customer exists locally . As customers are tied to local users , djstripe will not create customers that do not already exist locally . Docs and an example custom...
if event . customer : # As customers are tied to local users , djstripe will not create # customers that do not already exist locally . _handle_crud_like_event ( target_cls = models . Customer , event = event , crud_exact = True , crud_valid = True )
def is_excluded ( root , excludes ) : """Check if the directory is in the exclude list . Note : by having trailing slashes , we avoid common prefix issues , like e . g . an exlude " foo " also accidentally excluding " foobar " ."""
sep = os . path . sep if not root . endswith ( sep ) : root += sep for exclude in excludes : if root . startswith ( exclude ) : return True return False
def use_comparative_gradebook_view ( self ) : """Pass through to provider GradeSystemGradebookSession . use _ comparative _ gradebook _ view"""
self . _gradebook_view = COMPARATIVE # self . _ get _ provider _ session ( ' grade _ system _ gradebook _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_comparative_gradebook_view ( ) except AttributeError : pass
def _get_range_from_filters ( cls , filters , model_class ) : """Get property range from filters user provided . This method also validates there is one and only one closed range on a single property . Args : filters : user supplied filters . Each filter should be a list or tuple of format ( < property _ ...
if not filters : return None , None , None range_property = None start_val = None end_val = None start_filter = None end_filter = None for f in filters : prop , op , val = f if op in [ ">" , ">=" , "<" , "<=" ] : if range_property and range_property != prop : raise errors . BadReaderPara...
def _dot1q_headers_size ( layer ) : """calculate size of lower dot1q layers ( if present ) : param layer : the layer to start at : return : size of vlan headers , layer below lowest vlan header"""
vlan_headers_size = 0 under_layer = layer while under_layer and isinstance ( under_layer , Dot1Q ) : vlan_headers_size += LLDPDU . DOT1Q_HEADER_LEN under_layer = under_layer . underlayer return vlan_headers_size , under_layer
def _set_local_as ( self , v , load = False ) : """Setter method for local _ as , mapped from YANG variable / routing _ system / router / router _ bgp / address _ family / ipv4 / ipv4 _ unicast / af _ vrf / neighbor / af _ ipv4 _ vrf _ neighbor _ address _ holder / af _ ipv4 _ neighbor _ addr / local _ as ( contain...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = local_as . local_as , is_container = 'container' , presence = False , yang_name = "local-as" , rest_name = "local-as" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr...
def get_commands ( self ) : """Returns commands stored in the registry ( sorted by name ) ."""
commands = OrderedDict ( ) for cmd in sorted ( self . registry . keys ( ) ) : commands [ cmd ] = self . registry [ cmd ] return commands
def make_converters ( data_types ) -> dict : """Return a mapping between data type names , and casting functions , or class definitions to convert text into its Python object . Parameters data _ types : dict - like data field name str : python primitive type or class . Example > > make _ converters ( { ...
return { k : TYPE_CASTERS . get ( v , v ) for k , v in data_types . items ( ) }
def stop_playback ( self ) : """Stop playback from the audio sink ."""
self . _sink . flush ( ) self . _sink . stop ( ) self . _playing = False
def _ParseFileEntry ( self , knowledge_base , file_entry ) : """Parses a file entry for a preprocessing attribute . Args : knowledge _ base ( KnowledgeBase ) : to fill with preprocessing information . file _ entry ( dfvfs . FileEntry ) : file entry that contains the artifact value data . Raises : PrePro...
file_object = file_entry . GetFileObject ( ) try : self . _ParseFileData ( knowledge_base , file_object ) finally : file_object . close ( )
def list_courses ( self ) : """List enrolled courses . @ return : List of enrolled courses . @ rtype : [ str ]"""
course = CourseraOnDemand ( session = self . _session , course_id = None , course_name = None ) return course . list_courses ( )
def scope_in ( ctx ) : """- build new scope on the top of stack - and current scope will wait for it result : param ctx : : return :"""
logger . debug ( '# scope_in' ) logger . debug ( ctx ) ctx = ctx . clone ( ) compiled_story = None if not ctx . is_empty_stack ( ) : compiled_story = ctx . get_child_story ( ) logger . debug ( '# child' ) logger . debug ( compiled_story ) # we match child story loop once by message # what should pre...
def get_printer ( name , color = None , ansi_code = None , force_color = False ) : """Return a function which prints a message with a coloured name prefix"""
if force_color or supports_color ( ) : if color is None and ansi_code is None : cpre_1 , csuf_1 = hash_coloured_escapes ( name ) cpre_2 , csuf_2 = hash_coloured_escapes ( name + 'salt' ) name = cpre_1 + '+' + cpre_2 + '+' + csuf_1 + ' ' + name else : name = colored ( name , color...
async def remove_participant ( self , p : Participant ) : """remove a participant from the tournament | methcoro | Args : p : the participant to remove Raises : APIException"""
await self . connection ( 'DELETE' , 'tournaments/{}/participants/{}' . format ( self . _id , p . _id ) ) if p in self . participants : self . participants . remove ( p )
def register ( cls ) : """Register a class ."""
definition_name = make_definition_name ( cls . __name__ ) REGISTRY [ definition_name ] = cls return cls
def _convert_angle_limit ( angle , joint , ** kwargs ) : """Converts the limit angle of the PyPot JSON file to the internal format"""
angle_pypot = angle # No need to take care of orientation if joint [ "orientation" ] == "indirect" : angle_pypot = 1 * angle_pypot # angle _ pypot = angle _ pypot + offset return angle_pypot * np . pi / 180
def create ( self , friendly_name , api_version = values . unset , voice_url = values . unset , voice_method = values . unset , voice_fallback_url = values . unset , voice_fallback_method = values . unset , status_callback = values . unset , status_callback_method = values . unset , voice_caller_id_lookup = values . un...
data = values . of ( { 'FriendlyName' : friendly_name , 'ApiVersion' : api_version , 'VoiceUrl' : voice_url , 'VoiceMethod' : voice_method , 'VoiceFallbackUrl' : voice_fallback_url , 'VoiceFallbackMethod' : voice_fallback_method , 'StatusCallback' : status_callback , 'StatusCallbackMethod' : status_callback_method , 'V...
async def get ( self , key , * , dc = None , watch = None , consistency = None ) : """Returns the specified key Parameters : key ( str ) : Key to fetch watch ( Blocking ) : Do a blocking query consistency ( Consistency ) : Force consistency Returns : ObjectMeta : where value is the queried kv value Ob...
response = await self . _read ( key , dc = dc , watch = watch , consistency = consistency ) result = response . body [ 0 ] result [ "Value" ] = decode_value ( result [ "Value" ] , result [ "Flags" ] ) return consul ( result , meta = extract_meta ( response . headers ) )
def soldOutForRole ( event , role ) : '''This tag allows one to determine whether any event is sold out for any particular role .'''
if not isinstance ( event , Event ) or not isinstance ( role , DanceRole ) : return None return event . soldOutForRole ( role )
def _main ( ) : "ctox : tox with conda"
from sys import argv arguments = argv [ 1 : ] toxinidir = os . getcwd ( ) return main ( arguments , toxinidir )
def _import ( self , document , element , base_location = None ) : '''Algo take < import > element ' s children , clone them , and add them to the main document . Support for relative locations is a bit complicated . The orig document context is lost , so we need to store base location in DOM elements repre...
namespace = DOM . getAttr ( element , 'namespace' , default = None ) location = DOM . getAttr ( element , 'location' , default = None ) if namespace is None or location is None : raise WSDLError ( 'Invalid import element (missing namespace or location).' ) if base_location : location = basejoin ( base_location ...
def longest_path_weighted_nodes ( G , source , target , weights = None ) : """The longest path problem is the problem of finding a simple path of maximum length in a given graph . While for general graph , this problem is NP - hard , but if G is a directed acyclic graph ( DAG ) , longest paths in G can be found...
assert nx . is_directed_acyclic_graph ( G ) tree = nx . topological_sort ( G ) node_to_index = dict ( ( t , i ) for i , t in enumerate ( tree ) ) nnodes = len ( tree ) weights = [ weights . get ( x , 1 ) for x in tree ] if weights else [ 1 ] * nnodes score , fromc = weights [ : ] , [ - 1 ] * nnodes si = node_to_index [...
def namespace ( self , name = None , function = None , recursive = None ) : """Returns reference to namespace declaration that matches a defined criteria ."""
return ( self . _find_single ( scopedef . scopedef_t . _impl_matchers [ namespace_t . namespace ] , name = name , function = function , recursive = recursive ) )
def circ_corrcc ( x , y , tail = 'two-sided' ) : """Correlation coefficient between two circular variables . Parameters x : np . array First circular variable ( expressed in radians ) y : np . array Second circular variable ( expressed in radians ) tail : string Specify whether to return ' one - sided...
from scipy . stats import norm x = np . asarray ( x ) y = np . asarray ( y ) # Check size if x . size != y . size : raise ValueError ( 'x and y must have the same length.' ) # Remove NA x , y = remove_na ( x , y , paired = True ) n = x . size # Compute correlation coefficient x_sin = np . sin ( x - circmean ( x ) )...
def editable_loader ( context ) : """Set up the required JS / CSS for the in - line editing toolbar and controls ."""
user = context [ "request" ] . user template_vars = { "has_site_permission" : has_site_permission ( user ) , "request" : context [ "request" ] , } if ( settings . INLINE_EDITING_ENABLED and template_vars [ "has_site_permission" ] ) : t = get_template ( "includes/editable_toolbar.html" ) template_vars [ "REDIREC...
def _get_value ( self , scalar_data_blob , dtype_enum ) : """Obtains value for scalar event given blob and dtype enum . Args : scalar _ data _ blob : The blob obtained from the database . dtype _ enum : The enum representing the dtype . Returns : The scalar value ."""
tensorflow_dtype = tf . DType ( dtype_enum ) buf = np . frombuffer ( scalar_data_blob , dtype = tensorflow_dtype . as_numpy_dtype ) return np . asscalar ( buf )
def computeNumberOfMarkers ( inputFileName ) : """Count the number of marker ( line ) in a BIM file . : param inputFileName : the name of the ` ` bim ` ` file . : type inputFileName : str : returns : the number of marker in the ` ` bim ` ` file ."""
nbLine = 0 with open ( inputFileName , "r" ) as inputFile : nbLine = len ( inputFile . readlines ( ) ) return nbLine
def _set_option_by_index ( self , index ) : """Sets a single option in the Combo by its index , returning True if it was able too ."""
if index < len ( self . _options ) : self . _selected . set ( self . _options [ index ] ) return True else : return False
def delete_ikepolicy ( self , ikepolicy ) : '''Deletes the specified IKEPolicy'''
ikepolicy_id = self . _find_ikepolicy_id ( ikepolicy ) ret = self . network_conn . delete_ikepolicy ( ikepolicy_id ) return ret if ret else True
def cmd_slow_requests ( self ) : """List all requests that took a certain amount of time to be processed . . . warning : : By now hardcoded to 1 second ( 1000 milliseconds ) , improve the command line interface to allow to send parameters to each command or globally ."""
slow_requests = [ line . time_wait_response for line in self . _valid_lines if line . time_wait_response > 1000 ] return slow_requests
def from_terms_dict ( terms_dict ) : """For internal use ."""
return Expr ( tuple ( Term ( k , v ) for k , v in terms_dict . items ( ) if v ) )
def to_instants_dataframe ( self , sql_ctx ) : """Returns a DataFrame of instants , each a horizontal slice of this TimeSeriesRDD at a time . This essentially transposes the TimeSeriesRDD , producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD ."""
ssql_ctx = sql_ctx . _ssql_ctx jdf = self . _jtsrdd . toInstantsDataFrame ( ssql_ctx , - 1 ) return DataFrame ( jdf , sql_ctx )
def rebase ( self , yaml_dict ) : '''Use yaml _ dict as self ' s new base and update with existing reverse of update .'''
base = yaml_dict . clone ( ) base . update ( self ) self . clear ( ) self . update ( base )
def save ( fname , d , link_copy = True , raiseError = False ) : """link _ copy is used by hdf5 saving only , it allows to creat link of identical arrays ( saving space )"""
# make sure the object is dict ( recursively ) this allows reading it # without the DataStorage module fname = pathlib . Path ( fname ) d = toDict ( d , recursive = True ) d [ 'filename' ] = str ( fname ) extension = fname . suffix log . info ( "Saving storage file %s" % fname ) try : if extension == ".npz" : ...
def get_networkid ( vm_ ) : '''Return the networkid to use , only valid for Advanced Zone'''
networkid = config . get_cloud_config_value ( 'networkid' , vm_ , __opts__ ) if networkid is not None : return networkid else : return False
def _drop_remaining_rules ( self , * rules ) : """Drops rules from the queue of the rules that still need to be evaluated for the currently processed field . If no arguments are given , the whole queue is emptied ."""
if rules : for rule in rules : try : self . _remaining_rules . remove ( rule ) except ValueError : pass else : self . _remaining_rules = [ ]
def find ( self , flags = 0 ) : """Looks throught the text document based on the current criteria . The \ inputed flags will be merged with the generated search flags . : param flags | < QTextDocument . FindFlag > : return < bool > | success"""
# check against the web and text views if ( not ( self . _textEdit or self . _webView ) ) : fg = QColor ( 'darkRed' ) bg = QColor ( 'red' ) . lighter ( 180 ) palette = self . palette ( ) palette . setColor ( palette . Text , fg ) palette . setColor ( palette . Base , bg ) self . _searchEdit . se...
def shutdown ( self ) : """Shutdown the accept loop and stop running payloads"""
self . _must_shutdown = True self . _is_shutdown . wait ( ) self . _meta_runner . stop ( )
def run_length_decode ( in_array ) : """A function to run length decode an int array . : param in _ array : the input array of integers : return the decoded array"""
switch = False out_array = [ ] in_array = in_array . tolist ( ) for item in in_array : if switch == False : this_item = item switch = True else : switch = False out_array . extend ( [ this_item ] * int ( item ) ) return numpy . asarray ( out_array , dtype = numpy . int32 )
async def reload_modules ( self , pathlist ) : """Reload modules with a full path in the pathlist"""
loadedModules = [ ] failures = [ ] for path in pathlist : p , module = findModule ( path , False ) if module is not None and hasattr ( module , '_instance' ) and module . _instance . state != ModuleLoadStateChanged . UNLOADED : loadedModules . append ( module ) # Unload all modules ums = [ ModuleLoadSta...
def _extract_progress ( self , text ) : '''Finds progress information in the text using the user - supplied regex and calculation instructions'''
# monad - ish dispatch to avoid the if / else soup find = partial ( re . search , string = text . strip ( ) . decode ( self . encoding ) ) regex = unit ( self . progress_regex ) match = bind ( regex , find ) result = bind ( match , self . _calculate_progress ) return result
def MakeRequest ( http , http_request , retries = 7 , max_retry_wait = 60 , redirections = 5 , retry_func = HandleExceptionsAndRebuildHttpConnections , check_response_func = CheckResponse ) : """Send http _ request via the given http , performing error / retry handling . Args : http : An httplib2 . Http instanc...
retry = 0 first_req_time = time . time ( ) while True : try : return _MakeRequestNoRetry ( http , http_request , redirections = redirections , check_response_func = check_response_func ) # retry _ func will consume the exception types it handles and raise . # pylint : disable = broad - except ex...
def fetch_zip ( url , output_path , feature_type , progress_dialog = None ) : """Download zip containing shp file and write to output _ path . . . versionadded : : 3.2 : param url : URL of the zip bundle . : type url : str : param output _ path : Path of output file , : type output _ path : str : param ...
LOGGER . debug ( 'Downloading file from URL: %s' % url ) LOGGER . debug ( 'Downloading to: %s' % output_path ) if progress_dialog : progress_dialog . show ( ) # Infinite progress bar when the server is fetching data . # The progress bar will be updated with the file size later . progress_dialog . setMax...
def _find_spellcheckable_chunks ( contents , comment_system ) : """Given some contents for a file , find chunks that can be spellchecked . This applies the following rules : 1 . If the comment system comments individual lines , that whole line can be spellchecked from the point of the comment 2 . If a comme...
state = InTextParser ( ) comment_system_transitions = CommentSystemTransitions ( comment_system ) chunks = [ ] for line_index , line in enumerate ( contents ) : column = 0 line_len = len ( line ) escape_next = False # We hit a new line . If we were waiting until the end of the line # then add a new ...
def output_detailed ( paragraphs , fp = sys . stdout ) : """Same as output _ default , but only < p > tags are used and the following attributes are added : class , cfclass and heading ."""
for paragraph in paragraphs : output = '<p class="%s" cfclass="%s" heading="%i" xpath="%s"> %s' % ( paragraph . class_type , paragraph . cf_class , int ( paragraph . heading ) , paragraph . xpath , cgi . escape ( paragraph . text ) ) print ( output , file = fp )
def get_nameserver_detail_output_show_nameserver_nameserver_portid ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_nameserver_detail = ET . Element ( "get_nameserver_detail" ) config = get_nameserver_detail output = ET . SubElement ( get_nameserver_detail , "output" ) show_nameserver = ET . SubElement ( output , "show-nameserver" ) nameserver_portid = ET . SubElement ( show_nameserver , "names...
def dbmin10years ( self , value = None ) : """Corresponds to IDD Field ` dbmin10years ` 10 - year return period values for minimum extreme dry - bulb temperature Args : value ( float ) : value for IDD Field ` dbmin10years ` Unit : C if ` value ` is None it will not be checked against the specification a...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `dbmin10years`' . format ( value ) ) self . _dbmin10years = value
def apply_T1 ( word ) : '''There is a syllable boundary in front of every CV - sequence .'''
WORD = _split_consonants_and_vowels ( word ) for k , v in WORD . iteritems ( ) : if k == 1 and is_consonantal_onset ( v ) : WORD [ k ] = '.' + v elif is_consonant ( v [ 0 ] ) and WORD . get ( k + 1 , 0 ) : WORD [ k ] = v [ : - 1 ] + '.' + v [ - 1 ] word = _compile_dict_into_word ( WORD ) return ...
def main ( ) : """Provide the program ' s entry point when directly executed ."""
if len ( sys . argv ) != 2 : print ( "Usage: {} USERNAME" . format ( sys . argv [ 0 ] ) ) return 1 authenticator = prawcore . TrustedAuthenticator ( prawcore . Requestor ( "prawcore_read_only_example" ) , os . environ [ "PRAWCORE_CLIENT_ID" ] , os . environ [ "PRAWCORE_CLIENT_SECRET" ] , ) authorizer = prawcore...
def flush ( self ) : """Send messages by e - mail . The sending of messages is suppressed if a trigger severity level has been set and none of the received messages was at that level or above . In that case the messages are discarded . Empty e - mails are discarded ."""
if self . triggered and len ( self . buffer ) > 0 : # Do not send empty e - mails text = [ ] for record in self . buffer : terminator = getattr ( record , 'terminator' , '\n' ) s = self . format ( record ) if terminator is not None : text . append ( s + terminator ) e...
def write_to_file ( self , f ) : """Write configuration to a file - like object ."""
for section , values in self . _values . iteritems ( ) : try : section_name , subsection_name = section except ValueError : ( section_name , ) = section subsection_name = None if subsection_name is None : f . write ( "[%s]\n" % section_name ) else : f . write ( "[...
def _inject_format_spec ( self , value , format_spec ) : """value : ' { x } ' , format _ spec : ' f ' - > ' { x : f } '"""
t = type ( value ) return value [ : - 1 ] + t ( u':' ) + format_spec + t ( u'}' )
def create_index ( self , table_name , attr_name ) : """: param str table _ name : Table name that contains the attribute to be indexed . : param str attr _ name : Attribute name to create index . : raises IOError : | raises _ write _ permission | : raises simplesqlite . NullDatabaseConnectionError : | ra...
self . verify_table_existence ( table_name ) self . validate_access_permission ( [ "w" , "a" ] ) query_format = "CREATE INDEX IF NOT EXISTS {index:s} ON {table}({attr})" query = query_format . format ( index = make_index_name ( table_name , attr_name ) , table = Table ( table_name ) , attr = Attr ( attr_name ) , ) logg...
def get_to_run_checks ( self , do_checks = False , do_actions = False , poller_tags = None , reactionner_tags = None , worker_name = 'none' , module_types = None ) : # pylint : disable = too - many - branches """Get actions / checks for reactionner / poller Called by the poller to get checks ( do _ checks = True ...
res = [ ] now = time . time ( ) if poller_tags is None : poller_tags = [ 'None' ] if reactionner_tags is None : reactionner_tags = [ 'None' ] if module_types is None : module_types = [ 'fork' ] if not isinstance ( module_types , list ) : module_types = [ module_types ] # If a poller wants its checks if ...
def metalarchives ( song ) : """Returns the lyrics found in MetalArchives for the specified mp3 file or an empty string if not found ."""
artist = normalize ( song . artist ) title = normalize ( song . title ) url = 'https://www.metal-archives.com/search/ajax-advanced/searching/songs' url += f'/?songTitle={title}&bandName={artist}&ExactBandMatch=1' soup = get_url ( url , parser = 'json' ) if not soup : return '' song_id_re = re . compile ( r'lyricsLi...
def _write_instance_repr ( out , visited , name , pyop_attrdict , address ) : '''Shared code for use by old - style and new - style classes : write a representation to file - like object " out "'''
out . write ( '<' ) out . write ( name ) # Write dictionary of instance attributes : if isinstance ( pyop_attrdict , PyDictObjectPtr ) : out . write ( '(' ) first = True for pyop_arg , pyop_val in pyop_attrdict . iteritems ( ) : if not first : out . write ( ', ' ) first = False ...
def add_minutes ( self , datetimestr , n ) : """Returns a time that n minutes after a time . : param datetimestr : a datetime object or a datetime str : param n : number of minutes , value can be negative * * 中文文档 * * 返回给定日期N分钟之后的时间 。"""
a_datetime = self . parse_datetime ( datetimestr ) return a_datetime + timedelta ( seconds = 60 * n )
def parse_command_line ( self , args : List [ str ] = None , final : bool = True ) -> List [ str ] : """Parses all options given on the command line ( defaults to ` sys . argv ` ) . Options look like ` ` - - option = value ` ` and are parsed according to their ` ` type ` ` . For boolean options , ` ` - - opti...
if args is None : args = sys . argv remaining = [ ] # type : List [ str ] for i in range ( 1 , len ( args ) ) : # All things after the last option are command line arguments if not args [ i ] . startswith ( "-" ) : remaining = args [ i : ] break if args [ i ] == "--" : remaining = ar...
def command ( state , args ) : """Delete priority rule ."""
args = parser . parse_args ( args [ 1 : ] ) query . files . delete_priority_rule ( state . db , args . id ) del state . file_picker
def user_cache_dir ( appname = None , appauthor = None , version = None , opinion = True , as_path = False ) : r"""Return full path to the user - specific cache dir for this application . " appname " is the name of application . If None , just the system directory is returned . " appauthor " ( only used on Wi...
if system == "win32" : if appauthor is None : appauthor = appname path = os . path . normpath ( _get_win_folder ( "CSIDL_LOCAL_APPDATA" ) ) if appname : if appauthor is not False : path = os . path . join ( path , appauthor , appname ) else : path = os . path ...
def feature_info ( self ) : """Returns information about the features available for the CPC of this partition . Authorization requirements : * Object - access permission to this partition . Returns : : term : ` iterable ` : An iterable where each item represents one feature that is available for the C...
feature_list = self . prop ( 'available-features-list' , None ) if feature_list is None : raise ValueError ( "Firmware features are not supported on CPC %s" % self . manager . cpc . name ) return feature_list
def make_confidence_report_spsa ( filepath , train_start = TRAIN_START , train_end = TRAIN_END , test_start = TEST_START , test_end = TEST_END , batch_size = BATCH_SIZE , which_set = WHICH_SET , report_path = REPORT_PATH , nb_iter = NB_ITER_SPSA , spsa_samples = SPSA_SAMPLES , spsa_iters = SPSA . DEFAULT_SPSA_ITERS ) :...
# Set TF random seed to improve reproducibility tf . set_random_seed ( 1234 ) # Set logging level to see debug information set_log_level ( logging . INFO ) # Create TF session sess = tf . Session ( ) if report_path is None : assert filepath . endswith ( '.joblib' ) report_path = filepath [ : - len ( '.joblib' )...
def add_edges_from ( self , ebunch , ** kwargs ) : """Add all the edges in ebunch . If nodes referred in the ebunch are not already present , they will be automatically added . Node names can be any hashable python object . Parameters ebunch : list , array - like List of edges to add . Each edge must be o...
for edge in ebunch : self . add_edge ( edge [ 0 ] , edge [ 1 ] )
def truncate ( self , branch , turn , tick ) : """Delete all data after ( not on ) a specific tick"""
parents , branches , keys , settings , presettings , keycache , send = self . _truncate_stuff def truncate_branhc ( branhc ) : if turn in branhc : trn = branhc [ turn ] trn . truncate ( tick ) branhc . truncate ( turn ) if not trn : del branhc [ turn ] else : ...
def _setup_edge ( self , capabilities ) : """Setup Edge webdriver : param capabilities : capabilities object : returns : a new local Edge driver"""
edge_driver = self . config . get ( 'Driver' , 'edge_driver_path' ) self . logger . debug ( "Edge driver path given in properties: %s" , edge_driver ) return webdriver . Edge ( edge_driver , capabilities = capabilities )
def set_path ( self , path ) : '''Sets the listitem ' s path'''
self . _path = path return self . _listitem . setPath ( path )
def lv_load_areas ( self ) : """Returns a generator for iterating over load _ areas Yields int generator for iterating over load _ areas"""
for load_area in sorted ( self . _lv_load_areas , key = lambda _ : repr ( _ ) ) : yield load_area
def to_ufo_family_user_data ( self , ufo ) : """Set family - wide user data as Glyphs does ."""
if not self . use_designspace : ufo . lib [ FONT_USER_DATA_KEY ] = dict ( self . font . userData )
def compare_cells ( self , cell1 , cell2 ) : '''return true if exactly equal or if equal but modified , otherwise return false return type : BooleanPlus'''
eqlanguage = cell1 [ "language" ] == cell2 [ "language" ] eqinput = cell1 [ "input" ] == cell2 [ "input" ] eqoutputs = self . equaloutputs ( cell1 [ "outputs" ] , cell2 [ "outputs" ] ) if eqlanguage and eqinput and eqoutputs : return BooleanPlus ( True , False ) elif not self . check_modified : return BooleanPl...
def validate_account_id ( sts_client , account_id ) : """Exit if get _ caller _ identity doesn ' t match account _ id ."""
resp = sts_client . get_caller_identity ( ) if 'Account' in resp : if resp [ 'Account' ] == account_id : LOGGER . info ( 'Verified current AWS account matches required ' 'account id %s.' , account_id ) else : LOGGER . error ( 'Current AWS account %s does not match ' 'required account %s in Runwa...
def _check_input ( self , X ) : """Check the input for validity . Ensures that the input data , X , is a 2 - dimensional matrix , and that the second dimension of this matrix has the same dimensionality as the weight matrix ."""
if np . ndim ( X ) == 1 : X = np . reshape ( X , ( 1 , - 1 ) ) if X . ndim != 2 : raise ValueError ( "Your data is not a 2D matrix. " "Actual size: {0}" . format ( X . shape ) ) if X . shape [ 1 ] != self . data_dimensionality : raise ValueError ( "Your data size != weight dim: {0}, " "expected {1}" . forma...
def summary ( self , indicator_data ) : """Return a summary value for any given indicator type ."""
summary = [ ] for v in self . _value_fields : summary . append ( indicator_data . get ( v , '' ) ) return indicator_data . get ( 'summary' , ' : ' . join ( summary ) )
def equals ( self , junc ) : """test equality with another junction"""
if self . left . equals ( junc . left ) : return False if self . right . equals ( junc . right ) : return False return True
def delete ( self ) : '''method to remove version from resource ' s history'''
# send patch response = self . resource . repo . api . http_request ( 'DELETE' , self . uri ) # if response 204 if response . status_code == 204 : logger . debug ( 'deleting previous version of resource, %s' % self . uri ) # remove from resource versions delattr ( self . _current_resource . versions , self ...
def is_excluded ( root , excludes ) : # type : ( unicode , List [ unicode ] ) - > bool """Check if the directory is in the exclude list . Note : by having trailing slashes , we avoid common prefix issues , like e . g . an exlude " foo " also accidentally excluding " foobar " ."""
for exclude in excludes : if fnmatch ( root , exclude ) : return True return False
def encrypt_file ( self , path , output_path = None , overwrite = False , enable_verbose = True ) : """Encrypt a file using rsa . RSA for big file encryption is very slow . For big file , I recommend to use symmetric encryption and use RSA to encrypt the password ."""
path , output_path = files . process_dst_overwrite_args ( src = path , dst = output_path , overwrite = overwrite , src_to_dst_func = files . get_encrpyted_path , ) with open ( path , "rb" ) as infile , open ( output_path , "wb" ) as outfile : encrypt_bigfile ( infile , outfile , self . his_pubkey )
def generate_model_cls ( config , schema , model_name , raml_resource , es_based = True ) : """Generate model class . Engine DB field types are determined using ` type _ fields ` and only those types may be used . : param schema : Model schema dict parsed from RAML . : param model _ name : String that is us...
from nefertari . authentication . models import AuthModelMethodsMixin base_cls = engine . ESBaseDocument if es_based else engine . BaseDocument model_name = str ( model_name ) metaclass = type ( base_cls ) auth_model = schema . get ( '_auth_model' , False ) bases = [ ] if config . registry . database_acls : from ne...
def _linux_disks ( ) : '''Return list of disk devices and work out if they are SSD or HDD .'''
ret = { 'disks' : [ ] , 'SSDs' : [ ] } for entry in glob . glob ( '/sys/block/*/queue/rotational' ) : try : with salt . utils . files . fopen ( entry ) as entry_fp : device = entry . split ( '/' ) [ 3 ] flag = entry_fp . read ( 1 ) if flag == '0' : ret [ '...
def _ParseProcessingOptions ( self , options ) : """Parses the processing options . Args : options ( argparse . Namespace ) : command line arguments . Raises : BadConfigOption : if the options are invalid ."""
self . _single_process_mode = getattr ( options , 'single_process' , False ) argument_helper_names = [ 'process_resources' , 'temporary_directory' , 'workers' , 'zeromq' ] helpers_manager . ArgumentHelperManager . ParseOptions ( options , self , names = argument_helper_names )
def get_help_html ( message = None ) : """Create the HTML content for the help dialog or for external browser : param message : An optional message object to display in the dialog . : type message : Message . Message : return : the help HTML content : rtype : str"""
html = html_help_header ( ) if message is None : message = dock_help ( ) html += message . to_html ( ) html += html_footer ( ) return html
def external_editor ( self , filename , goto = - 1 ) : """Edit in an external editor Recommended : SciTE ( e . g . to go to line where an error did occur )"""
editor_path = CONF . get ( 'internal_console' , 'external_editor/path' ) goto_option = CONF . get ( 'internal_console' , 'external_editor/gotoline' ) try : args = [ filename ] if goto > 0 and goto_option : args . append ( '%s%d' . format ( goto_option , goto ) ) programs . run_program ( editor_path ...
def _get_client_address ( self , req ) : """Get address from ` ` X - Forwarded - For ` ` header or use remote address . Remote address is used if the ` ` X - Forwarded - For ` ` header is not available . Note that this may not be safe to depend on both without proper authorization backend . Args : req ( f...
try : forwarded_for = req . get_header ( 'X-Forwarded-For' , True ) return forwarded_for . split ( ',' ) [ 0 ] . strip ( ) except ( KeyError , HTTPMissingHeader ) : return ( req . env . get ( 'REMOTE_ADDR' ) if self . remote_address_fallback else None )
def unhold ( name = None , pkgs = None , ** kwargs ) : '''Remove specified package lock . root operate on a different root directory . CLI Example : . . code - block : : bash salt ' * ' pkg . remove _ lock < package name > salt ' * ' pkg . remove _ lock < package1 > , < package2 > , < package3 > salt ...
ret = { } root = kwargs . get ( 'root' ) if ( not name and not pkgs ) or ( name and pkgs ) : raise CommandExecutionError ( 'Name or packages must be specified.' ) elif name : pkgs = [ name ] locks = list_locks ( root ) try : pkgs = list ( __salt__ [ 'pkg_resource.parse_targets' ] ( pkgs ) [ 0 ] . keys ( ) )...
def write_dataframe ( self , df , path , format = 'csv' ) : """Write a pandas DataFrame to indicated file path ( default : HDFS ) in the indicated format Parameters df : DataFrame path : string Absolute output path format : { ' csv ' } , default ' csv ' Returns None ( for now )"""
from ibis . impala . pandas_interop import DataFrameWriter writer = DataFrameWriter ( self , df ) return writer . write_csv ( path )
def sync_local_to_set ( org , syncer , remote_set ) : """Syncs an org ' s set of local instances of a model to match the set of remote objects . Local objects not in the remote set are deleted . : param org : the org : param * syncer : the local model syncer : param remote _ set : the set of remote objects ...
outcome_counts = defaultdict ( int ) remote_identities = set ( ) for remote in remote_set : outcome = sync_from_remote ( org , syncer , remote ) outcome_counts [ outcome ] += 1 remote_identities . add ( syncer . identify_remote ( remote ) ) # active local objects which weren ' t in the remote set need to be...
def get_annotation_entries_by_names ( self , url : str , names : Iterable [ str ] ) -> List [ NamespaceEntry ] : """Get annotation entries by URL and names . : param url : The url of the annotation source : param names : The names of the annotation entries from the given url ' s document"""
annotation_filter = and_ ( Namespace . url == url , NamespaceEntry . name . in_ ( names ) ) return self . session . query ( NamespaceEntry ) . join ( Namespace ) . filter ( annotation_filter ) . all ( )
def _wrap_measure ( individual_group_measure_process , group_measure , loaded_processes ) : """Creates a function on a state _ collection , which creates analysis _ collections for each group in the collection ."""
def wrapped_measure ( state_collection , overriding_parameters = None , loggers = None ) : if loggers == None : loggers = funtool . logger . set_default_loggers ( ) if loaded_processes != None : if group_measure . grouping_selectors != None : for grouping_selector_name in group_measu...
def parse_stack_pointer ( sp ) : """Convert multiple supported forms of stack pointer representations into stack offsets . : param sp : A stack pointer representation . : return : A stack pointer offset . : rtype : int"""
if isinstance ( sp , int ) : return sp if isinstance ( sp , StackBaseOffset ) : return sp . offset if isinstance ( sp , BinaryOp ) : op0 , op1 = sp . operands off0 = parse_stack_pointer ( op0 ) off1 = parse_stack_pointer ( op1 ) if sp . op == "Sub" : return off0 - off1 elif sp . op =...