signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _is_utf_8 ( txt ) : """Check a string is utf - 8 encoded : param bytes txt : utf - 8 string : return : Whether the string is utf - 8 encoded or not : rtype : bool"""
assert isinstance ( txt , six . binary_type ) try : _ = six . text_type ( txt , 'utf-8' ) except ( TypeError , UnicodeEncodeError ) : return False else : return True
def _stop_instance ( self ) : """Stop the instance ."""
instance = self . _get_instance ( ) instance . stop ( ) self . _wait_on_instance ( 'stopped' , self . timeout )
def get_payload ( self ) : """Return Payload ."""
ret = bytes ( [ self . node_id ] ) ret += string_to_bytes ( self . name , 64 ) return ret
def e2h ( string ) : """Convert english to hangul . ( ' gksdudxk ' - > ' 한영타 ' ) During processing , state interleaves INIT , LEAD _ GIVEN , MEDI _ GIVEN and TAIL _ GIVEN : param string : english that actually represent hangul string : return : converted hangul string"""
ctx = Context ( string ) for char in ctx . input : hchar = E2H_MAPPING . get ( char ) if not char . isalpha ( ) or not hchar : ctx . do_final ( ) ctx . output . append ( char ) ctx . state = State . INIT continue if ctx . state is State . INIT : if hchar not in JA_LEA...
def is_client_method_whitelisted ( request : AxesHttpRequest ) -> bool : """Check if the given request uses a whitelisted method ."""
if settings . AXES_NEVER_LOCKOUT_GET and request . method == 'GET' : return True return False
def start ( self ) : """Start the server and run forever ."""
Server ( ) . start ( self . options , self . handler_function , self . __class__ . component_type )
def error ( request , message , extra_tags = '' , fail_silently = False , async = False ) : """Adds a message with the ` ` ERROR ` ` level ."""
if ASYNC and async : messages . debug ( _get_user ( request ) , message ) else : add_message ( request , constants . ERROR , message , extra_tags = extra_tags , fail_silently = fail_silently )
def update_book ( self , id , body , doc_type = 'book' ) : '''Update a book The " body " is merged with the current one . Yes , it is NOT overwritten . In case of concurrency conflict this function could raise ` elasticsearch . ConflictError `'''
# note that we are NOT overwriting all the _ source , just merging book = self . get_book_by_id ( id ) book [ '_source' ] . update ( body ) validated = validate_book ( book [ '_source' ] ) ret = self . es . index ( index = self . index_name , id = id , doc_type = doc_type , body = validated , version = book [ '_version...
def restore_default_button_clicked ( self , classification ) : """Action for restore default button clicked . It will set the threshold with default value . : param classification : The classification that being edited . : type classification : dict"""
# Obtain default value class_dict = { } for the_class in classification . get ( 'classes' ) : class_dict [ the_class [ 'key' ] ] = { 'numeric_default_min' : the_class [ 'numeric_default_min' ] , 'numeric_default_max' : the_class [ 'numeric_default_max' ] , } # Set for all threshold for key , value in list ( self . ...
def _modify ( self , ** patch ) : """Wrapped with modify , override in a subclass to customize ."""
requests_params , patch_uri , session , read_only = self . _prepare_put_or_patch ( patch ) self . _check_for_boolean_pair_reduction ( patch ) read_only_mutations = [ ] for attr in read_only : if attr in patch : read_only_mutations . append ( attr ) if read_only_mutations : msg = 'Attempted to mutate rea...
def process_raw_data ( cls , raw_data ) : """Create a new model using raw API response ."""
properties = raw_data . get ( "properties" , { } ) frontend_ip_configurations = [ ] for raw_content in properties . get ( "frontendIPConfigurations" , [ ] ) : resource = Resource . from_raw_data ( raw_content ) frontend_ip_configurations . append ( resource ) properties [ "frontendIPConfigurations" ] = frontend...
def authentication ( self ) : '''Retrieve information on the current authentication token'''
url = '%s/authentication' % ( self . domain ) res = self . session . get ( url ) self . _check_response ( res ) return res . json ( )
def _parse_specific_options ( self , data ) : """Parse all specific setttings ."""
data [ 'common_flags' ] = [ ] data [ 'ld_flags' ] = [ ] data [ 'c_flags' ] = [ ] data [ 'cxx_flags' ] = [ ] data [ 'asm_flags' ] = [ ] for k , v in data [ 'misc' ] . items ( ) : if type ( v ) is list : if k not in data : data [ k ] = [ ] data [ k ] . extend ( v ) else : if k ...
def htmlize_paragraphs ( text ) : """Convert paragraphs delimited by blank lines into HTML text enclosed in < p > tags ."""
paragraphs = re . split ( '(\r?\n)\s*(\r?\n)' , text ) return '\n' . join ( '<p>%s</p>' % paragraph for paragraph in paragraphs )
def _export_prb_file ( recording , file_name , format = None , adjacency_distance = None , graph = False , geometry = True , radius = 100 , dimensions = 'all' ) : '''Exports . prb file Parameters recording : RecordingExtractor The recording extractor to save probe file from file _ name : str probe filenam...
if format == 'klusta' : graph = True geometry = False elif format == 'spyking_circus' : graph = False geometry = True else : graph = True geometry = True file_name = Path ( file_name ) assert file_name is not None abspath = file_name . absolute ( ) if geometry : if 'location' in recording . ...
def merge_properties ( item_properties , prop_name , merge_value ) : """Tries to figure out which type of property value that should be merged and invoke the right function . Returns new properties if the merge was successful otherwise False ."""
existing_value = item_properties . get ( prop_name , None ) if not existing_value : # A node without existing values for the property item_properties [ prop_name ] = merge_value else : if type ( merge_value ) is int or type ( merge_value ) is str : item_properties [ prop_name ] = existing_value + merge_...
def DbPutDeviceAttributeProperty ( self , argin ) : """Create / Update device attribute property ( ies ) in database : param argin : Str [ 0 ] = Device name Str [ 1 ] = Attribute number Str [ 2 ] = Attribute name Str [ 3 ] = Property number Str [ 4 ] = Property name Str [ 5 ] = Property value : type :...
self . _log . debug ( "In DbPutDeviceAttributeProperty()" ) device_name = argin [ 0 ] nb_attributes = int ( argin [ 1 ] ) self . db . put_device_attribute_property ( device_name , nb_attributes , argin [ 2 : ] )
def _read_mat_mnu0 ( filename ) : """Import a . mat file with single potentials ( A B M ) into a pandas DataFrame Also export some variables of the md struct into a separate structure"""
print ( 'read_mag_single_file' ) mat = sio . loadmat ( filename ) df_emd = _extract_emd ( mat ) return df_emd
def get_point_in_block ( cls , x , y , block_idx , block_size ) : """Get point coordinates in next block . Parameters x : ` int ` X coordinate in current block . y : ` int ` Y coordinate in current block . block _ index : ` int ` Current block index in next block . block _ size : ` int ` Current b...
if block_idx == 0 : return y , x if block_idx == 1 : return x , y + block_size if block_idx == 2 : return x + block_size , y + block_size if block_idx == 3 : x , y = block_size - 1 - y , block_size - 1 - x return x + block_size , y raise IndexError ( 'block index out of range: %d' % block_idx )
def assign ( self , value , termenc ) : """> > > scanner = DefaultScanner ( ) > > > scanner . assign ( " 01234 " , " ascii " ) > > > scanner . _ data u ' 01234'"""
if self . _termenc != termenc : self . _decoder = codecs . getincrementaldecoder ( termenc ) ( errors = 'replace' ) self . _termenc = termenc self . _data = self . _decoder . decode ( value )
def update ( self ) : """Update the group . Returns a Command ."""
def process_result ( result ) : self . raw = result return Command ( 'get' , self . path , process_result = process_result )
def sample_measurement_ops ( self , measurement_ops : List [ ops . GateOperation ] , repetitions : int = 1 ) -> Dict [ str , np . ndarray ] : """Samples from the system at this point in the computation . Note that this does not collapse the wave function . In contrast to ` sample ` which samples qubits , this t...
bounds = { } # type : Dict [ str , Tuple ] all_qubits = [ ] # type : List [ ops . Qid ] current_index = 0 for op in measurement_ops : gate = op . gate if not isinstance ( gate , ops . MeasurementGate ) : raise ValueError ( '{} was not a MeasurementGate' . format ( gate ) ) key = protocols . measurem...
async def start_component ( workload : CoroutineFunction [ T ] , * args : Any , ** kwargs : Any ) -> Component [ T ] : """Starts the passed ` workload ` with additional ` commands ` and ` events ` pipes . The workload will be executed as a task . A simple example . Note that here , the component is exclusively ...
commands_a , commands_b = pipe ( ) events_a , events_b = pipe ( ) task = asyncio . create_task ( workload ( * args , commands = commands_b , events = events_b , ** kwargs ) ) component = Component [ T ] ( commands_a , events_a , task ) await component . wait_for_start ( ) return component
def update_cancel_operation_by_id ( cls , cancel_operation_id , cancel_operation , ** kwargs ) : """Update CancelOperation Update attributes of CancelOperation This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . updat...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _update_cancel_operation_by_id_with_http_info ( cancel_operation_id , cancel_operation , ** kwargs ) else : ( data ) = cls . _update_cancel_operation_by_id_with_http_info ( cancel_operation_id , cancel_operation , ** kwargs ) ...
def environment ( request = None ) : """Return ` ` COMPRESS _ ENABLED ` ` , ` ` SITE _ NAME ` ` , and any settings listed in ` ` ICEKIT _ CONTEXT _ PROCESSOR _ SETTINGS ` ` as context ."""
context = { 'COMPRESS_ENABLED' : settings . COMPRESS_ENABLED , 'SITE_NAME' : settings . SITE_NAME , } for key in settings . ICEKIT_CONTEXT_PROCESSOR_SETTINGS : context [ key ] = getattr ( settings , key , None ) return context
def str2bytes ( x ) : """Convert input argument to bytes"""
if type ( x ) is bytes : return x elif type ( x ) is str : return bytes ( [ ord ( i ) for i in x ] ) else : return str2bytes ( str ( x ) )
def stream ( self , to = values . unset , from_ = values . unset , parent_call_sid = values . unset , status = values . unset , start_time_before = values . unset , start_time = values . unset , start_time_after = values . unset , end_time_before = values . unset , end_time = values . unset , end_time_after = values . ...
limits = self . _version . read_limits ( limit , page_size ) page = self . page ( to = to , from_ = from_ , parent_call_sid = parent_call_sid , status = status , start_time_before = start_time_before , start_time = start_time , start_time_after = start_time_after , end_time_before = end_time_before , end_time = end_tim...
def cmp_name ( first_node , second_node ) : """Compare two name recursively . : param first _ node : First node : param second _ node : Second state : return : 0 if same name , 1 if names are differents ."""
if len ( first_node . children ) == len ( second_node . children ) : for first_child , second_child in zip ( first_node . children , second_node . children ) : for key in first_child . __dict__ . keys ( ) : if key . startswith ( '_' ) : continue if first_child . __dic...
def dump_item ( inbox , type = 'file' , prefix = None , suffix = None , dir = None , timeout = 320 , buffer = None ) : """Writes the first element of the inbox as a file of a specified type . The type can be ' file ' , ' fifo ' or ' socket ' corresponding to typical files , named pipes ( FIFOs ) . FIFOs and TCP...
# get a random filename generator names = tempfile . _get_candidate_names ( ) names . rng . seed ( ) # re - seed rng after the fork # try to own the file if type in ( 'file' , 'fifo' ) : prefix = prefix or 'tmp_papy_%s' % type suffix = suffix or '' dir = dir or tempfile . gettempdir ( ) while True : # c...
def gaussian_pdf ( std = 10.0 , mean = 0.0 ) : """Gaussian PDF for orientation averaging . Args : std : The standard deviation in degrees of the Gaussian PDF mean : The mean in degrees of the Gaussian PDF . This should be a number in the interval [ 0 , 180) Returns : pdf ( x ) , a function that returns ...
norm_const = 1.0 def pdf ( x ) : return norm_const * np . exp ( - 0.5 * ( ( x - mean ) / std ) ** 2 ) * np . sin ( np . pi / 180.0 * x ) norm_dev = quad ( pdf , 0.0 , 180.0 ) [ 0 ] # ensure that the integral over the distribution equals 1 norm_const /= norm_dev return pdf
def apply_filters ( stream , filters , lexer = None ) : """Use this method to apply an iterable of filters to a stream . If lexer is given it ' s forwarded to the filter , otherwise the filter receives ` None ` ."""
def _apply ( filter_ , stream ) : for token in filter_ . filter ( lexer , stream ) : yield token for filter_ in filters : stream = _apply ( filter_ , stream ) return stream
def _cryptodome_encrypt ( cipher_factory , plaintext , key , iv ) : """Use a Pycryptodome cipher factory to encrypt data . : param cipher _ factory : Factory callable that builds a Pycryptodome Cipher instance based on the key and IV : type cipher _ factory : callable : param bytes plaintext : Plaintext dat...
encryptor = cipher_factory ( key , iv ) return encryptor . encrypt ( plaintext )
def percentile ( p , arr = None ) : """Returns the pth percentile of the input array ( the value that is at least as great as p % of the values in the array ) . If arr is not provided , percentile returns itself curried with p > > > percentile ( 74.9 , [ 1 , 3 , 5 , 9 ] ) > > > percentile ( 75 , [ 1 , 3 , 5...
if arr is None : return lambda arr : percentile ( p , arr ) if hasattr ( p , '__iter__' ) : return np . array ( [ percentile ( x , arr ) for x in p ] ) if p == 0 : return min ( arr ) assert 0 < p <= 100 , 'Percentile requires a percent' i = ( p / 100 ) * len ( arr ) return sorted ( arr ) [ math . ceil ( i )...
def copy_pkg ( self , filename , _ ) : """Copy a package to the repo ' s Package subdirectory . Args : filename : Path for file to copy . _ : Ignored . Used for compatibility with JDS repos ."""
basename = os . path . basename ( filename ) self . _copy ( filename , os . path . join ( self . connection [ "mount_point" ] , "Packages" , basename ) )
def create_tag ( tag , escaper = EscapedHTMLString , opening_only = False , body = None , escape_body = False , escape_attr = True , indent = 0 , attrs = None , ** other_attrs ) : """Create an XML / HTML tag . This function create a full XML / HTML tag , putting toghether an optional inner body and a dictionary...
if attrs is None : attrs = { } for key , value in iteritems ( other_attrs ) : if value is not None : if key . endswith ( '_' ) : attrs [ key [ : - 1 ] ] = value else : attrs [ key ] = value out = "<%s" % tag for key , value in iteritems ( attrs ) : if escape_attr : ...
def _remember_avatarness ( self , character , graph , node , is_avatar = True , branch = None , turn = None , tick = None ) : """Use this to record a change in avatarness . Should be called whenever a node that wasn ' t an avatar of a character now is , and whenever a node that was an avatar of a character no...
branch = branch or self . branch turn = turn or self . turn tick = tick or self . tick self . _avatarness_cache . store ( character , graph , node , branch , turn , tick , is_avatar ) self . query . avatar_set ( character , graph , node , branch , turn , tick , is_avatar )
def from_signing_credentials ( cls , credentials , ** kwargs ) : """Creates a new : class : ` google . auth . jwt . OnDemandCredentials ` instance from an existing : class : ` google . auth . credentials . Signing ` instance . The new instance will use the same signer as the existing instance and will use the...
kwargs . setdefault ( 'issuer' , credentials . signer_email ) kwargs . setdefault ( 'subject' , credentials . signer_email ) return cls ( credentials . signer , ** kwargs )
def get_fp_version ( self ) : """: return : the fingerprint version"""
command = const . CMD_OPTIONS_RRQ command_string = b'~ZKFPVersion\x00' response_size = 1024 cmd_response = self . __send_command ( command , command_string , response_size ) if cmd_response . get ( 'status' ) : response = self . __data . split ( b'=' , 1 ) [ - 1 ] . split ( b'\x00' ) [ 0 ] response = response ....
def add_rect ( img , box , color = None , thickness = 1 ) : """Draws a bounding box inside the image . : param img : Input image : param box : Box object that defines the bounding box . : param color : Color of the box : param thickness : Thickness of line : return : Rectangle added image"""
if color is None : color = COL_GRAY box = box . to_int ( ) cv . rectangle ( img , box . top_left ( ) , box . bottom_right ( ) , color , thickness )
def relation_factory ( relation_name ) : """Get the RelationFactory for the given relation name . Looks for a RelationFactory in the first file matching : ` ` $ CHARM _ DIR / hooks / relations / { interface } / { provides , requires , peer } . py ` `"""
role , interface = hookenv . relation_to_role_and_interface ( relation_name ) if not ( role and interface ) : hookenv . log ( 'Unable to determine role and interface for relation ' '{}' . format ( relation_name ) , hookenv . ERROR ) return None return _find_relation_factory ( _relation_module ( role , interface...
def set_level ( name , level ) : """Set level for given logger : param name : Name of logger to set the level for : param level : The new level , see possible levels from python logging library"""
if name is None or name == "" or name == "bench" : logging . getLogger ( "bench" ) . setLevel ( level ) loggername = "bench." + name logging . getLogger ( loggername ) . setLevel ( level )
def find_asts ( self , ast_root , name ) : '''Finds an AST node with the given name and the entire subtree under it . A function borrowed from scottfrazer . Thank you Scott Frazer ! : param ast _ root : The WDL AST . The whole thing generally , but really any portion that you wish to search . : param name :...
nodes = [ ] if isinstance ( ast_root , wdl_parser . AstList ) : for node in ast_root : nodes . extend ( self . find_asts ( node , name ) ) elif isinstance ( ast_root , wdl_parser . Ast ) : if ast_root . name == name : nodes . append ( ast_root ) for attr_name , attr in ast_root . attributes ...
def _read_message ( self ) : """必须启动新的greenlet , 否则会有内存泄漏"""
job = gevent . spawn ( super ( GConnection , self ) . _read_message ) job . join ( )
def _handleUssd ( self , lines ) : """Handler for USSD event notification line ( s )"""
if self . _ussdSessionEvent : # A sendUssd ( ) call is waiting for this response - parse it self . _ussdResponse = self . _parseCusdResponse ( lines ) # Notify waiting thread self . _ussdSessionEvent . set ( )
def __file_hash_and_stat ( self , load ) : '''Common code for hashing and stating files'''
if 'env' in load : # " env " is not supported ; Use " saltenv " . load . pop ( 'env' ) if 'path' not in load or 'saltenv' not in load : return '' , None if not isinstance ( load [ 'saltenv' ] , six . string_types ) : load [ 'saltenv' ] = six . text_type ( load [ 'saltenv' ] ) fnd = self . find_file ( salt ....
def write_usage ( self , prog , args = '' , prefix = 'Usage: ' ) : """Writes a usage line into the buffer . : param prog : the program name . : param args : whitespace separated list of arguments . : param prefix : the prefix for the first line ."""
usage_prefix = '%*s%s ' % ( self . current_indent , prefix , prog ) text_width = self . width - self . current_indent if text_width >= ( term_len ( usage_prefix ) + 20 ) : # The arguments will fit to the right of the prefix . indent = ' ' * term_len ( usage_prefix ) self . write ( wrap_text ( args , text_width ...
def write_points ( self , fid ) : """Write the grid points to the GMSH - command file . Parameters fid : file object for the command file ( . geo )"""
for nr , point in enumerate ( self . Points ) : fid . write ( 'Point({0}) = {{{1}, {2}, 0, {3}}};\n' . format ( nr + 1 , point [ 0 ] , point [ 1 ] , self . Charlengths [ nr ] ) )
def all_legal_moves ( self ) : 'Returns a np . array of size go . N * * 2 + 1 , with 1 = legal , 0 = illegal'
# by default , every move is legal legal_moves = np . ones ( [ N , N ] , dtype = np . int8 ) # . . . unless there is already a stone there legal_moves [ self . board != EMPTY ] = 0 # calculate which spots have 4 stones next to them # padding is because the edge always counts as a lost liberty . adjacent = np . ones ( [...
async def delete ( self ) : """Delete this Fabric ."""
if self . id == self . _origin . Fabric . _default_fabric_id : raise CannotDelete ( "Default fabric cannot be deleted." ) await self . _handler . delete ( id = self . id )
def build_traversal ( self , traversal ) : """traverse a relationship from a node to a set of nodes"""
# build source rhs_label = ':' + traversal . target_class . __label__ # build source lhs_ident = self . build_source ( traversal . source ) rhs_ident = traversal . name + rhs_label self . _ast [ 'return' ] = traversal . name self . _ast [ 'result_class' ] = traversal . target_class rel_ident = self . create_ident ( ) s...
def get_social_share_link ( context , share_link , object_url , object_title ) : """Construct the social share link for the request object ."""
request = context [ 'request' ] url = unicode ( object_url ) if 'http' not in object_url . lower ( ) : full_path = '' . join ( ( 'http' , ( '' , 's' ) [ request . is_secure ( ) ] , '://' , request . META [ 'HTTP_HOST' ] , url ) ) else : full_path = url return share_link . get_share_url ( full_path , object_titl...
def mean_vertex_normals ( vertex_count , faces , face_normals , ** kwargs ) : """Find vertex normals from the mean of the faces that contain that vertex . Parameters vertex _ count : int The number of vertices faces refer to faces : ( n , 3 ) int List of vertex indices face _ normals : ( n , 3 ) float...
def summed_sparse ( ) : # use a sparse matrix of which face contains each vertex to # figure out the summed normal at each vertex # allow cached sparse matrix to be passed if 'sparse' in kwargs : sparse = kwargs [ 'sparse' ] else : sparse = index_sparse ( vertex_count , faces ) summed = spar...
def AddHeader ( self , header , value ) : '''Add a header to send .'''
self . user_headers . append ( ( header , value ) ) return self
def _mod_bufsize_linux ( iface , * args , ** kwargs ) : '''Modify network interface buffer sizes using ethtool'''
ret = { 'result' : False , 'comment' : 'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>' } cmd = '/sbin/ethtool -G ' + iface if not kwargs : return ret if args : ret [ 'comment' ] = 'Unknown arguments: ' + ' ' . join ( [ six . text_type ( item ) for item in args ] ) return ret eargs = '' for...
def __remove_queue_logging_handler ( ) : '''This function will run once the additional loggers have been synchronized . It just removes the QueueLoggingHandler from the logging handlers .'''
global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None : # Already removed return root_logger = logging . getLogger ( ) for handler in root_logger . handlers : if handler is LOGGING_STORE_HANDLER : root_logger . removeHandler ( LOGGING_STORE_HANDLER ) # Redefine the null handler to None s...
def GetCSR ( self ) : """Return our CSR ."""
return rdf_crypto . CertificateSigningRequest ( common_name = self . common_name , private_key = self . private_key )
def get_repositories_and_digests ( self ) : """Returns a map of images to their repositories and a map of media types to each digest it creates a map of images to digests , which is need to create the image - > repository map and uses the same loop structure as media _ types - > digest , but the image - > diges...
digests = { } # image - > digests typed_digests = { } # media _ type - > digests for registry in self . workflow . push_conf . docker_registries : for image in self . workflow . tag_conf . images : image_str = image . to_str ( ) if image_str in registry . digests : image_digests = regist...
def find_skill ( self , param , author = None , skills = None ) : # type : ( str , str , List [ SkillEntry ] ) - > SkillEntry """Find skill by name or url"""
if param . startswith ( 'https://' ) or param . startswith ( 'http://' ) : repo_id = SkillEntry . extract_repo_id ( param ) for skill in self . list ( ) : if skill . id == repo_id : return skill name = SkillEntry . extract_repo_name ( param ) path = SkillEntry . create_path ( self . ...
def get_pools ( time_span = None , api_code = None ) : """Get number of blocks mined by each pool . : param str time _ span : duration of the chart . Default is 4days ( optional ) : param str api _ code : Blockchain . info API code ( optional ) : return : an instance of dict : { str , int }"""
resource = 'pools' if time_span is not None : resource += '?timespan=' + time_span if api_code is not None : resource += '&api_code=' + api_code response = util . call_api ( resource , base_url = 'https://api.blockchain.info/' ) json_response = json . loads ( response ) return { k : v for ( k , v ) in json_resp...
def import_name_or_class ( name ) : "Import an obect as either a fully qualified , dotted name ,"
if isinstance ( name , str ) : # for " a . b . c . d " - > [ ' a . b . c ' , ' d ' ] module_name , object_name = name . rsplit ( '.' , 1 ) # _ _ import _ _ loads the multi - level of module , but returns # the top level , which we have to descend into mod = __import__ ( module_name ) components = na...
def define_function ( self , function , name = None ) : """Define the Python function within the CLIPS environment . If a name is given , it will be the function name within CLIPS . Otherwise , the name of the Python function will be used . The Python function will be accessible within CLIPS via its name as...
name = name if name is not None else function . __name__ ENVIRONMENT_DATA [ self . _env ] . user_functions [ name ] = function self . build ( DEFFUNCTION . format ( name ) )
def ball ( center , radius = 1. , bdy = True ) : '''Returns the indicator function of a ball . : param center : A vector - like numpy array , defining the center of the ball . \n len ( center ) fixes the dimension . : param radius : Float or int , the radius of the ball : param bdy : Bool , When ` ` x...
center = _np . array ( center ) # copy input parameter dim = len ( center ) if bdy : def ball_indicator ( x ) : if len ( x ) != dim : raise ValueError ( 'input has wrong dimension (%i instead of %i)' % ( len ( x ) , dim ) ) if _np . linalg . norm ( x - center ) <= radius : re...
def to_xdr_object ( self ) : """Creates an XDR Operation object that represents this : class : ` AccountMerge ` ."""
destination = account_xdr_object ( self . destination ) self . body . type = Xdr . const . ACCOUNT_MERGE self . body . destination = destination return super ( AccountMerge , self ) . to_xdr_object ( )
def warn_if_fields_defined_in_meta ( fields , Meta ) : """Warns user that fields defined in Meta . fields or Meta . additional will be ignored : param dict fields : A dictionary of fields name field object pairs : param Meta : the schema ' s Meta class"""
if getattr ( Meta , "fields" , None ) or getattr ( Meta , "additional" , None ) : declared_fields = set ( fields . keys ( ) ) if ( set ( getattr ( Meta , "fields" , set ( ) ) ) > declared_fields or set ( getattr ( Meta , "additional" , set ( ) ) ) > declared_fields ) : warnings . warn ( "Only explicitly...
def get_review_requests ( self ) : """: calls : ` GET / repos / : owner / : repo / pulls / : number / requested _ reviewers < https : / / developer . github . com / v3 / pulls / review _ requests / > ` _ : rtype : tuple of : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . NamedUser . Na...
return ( github . PaginatedList . PaginatedList ( github . NamedUser . NamedUser , self . _requester , self . url + "/requested_reviewers" , None , list_item = 'users' ) , github . PaginatedList . PaginatedList ( github . Team . Team , self . _requester , self . url + "/requested_reviewers" , None , list_item = 'teams'...
def read ( url , ** args ) : """Get the object from a ftp URL ."""
all_ = args . pop ( 'all' , False ) password = args . pop ( 'password' , '' ) if not password : raise ValueError ( 'password' ) try : username , __ = url . username . split ( ';' ) except ValueError : username = url . username if not username : username = os . environ . get ( 'USERNAME' ) username =...
def cmd ( send , msg , args ) : """Runs eix with the given arguments . Syntax : { command } < package >"""
if not msg : result = subprocess . run ( [ 'eix' , '-c' ] , env = { 'EIX_LIMIT' : '0' , 'HOME' : os . environ [ 'HOME' ] } , stdout = subprocess . PIPE , universal_newlines = True ) if result . returncode : send ( "eix what?" ) return send ( choice ( result . stdout . splitlines ( ) ) ) ...
def _get_callers ( items , stage , special_cases = False ) : """Retrieve available callers for the provided stage . Handles special cases like CNVkit that can be in initial or standard depending on if fed into Lumpy analysis ."""
callers = utils . deepish_copy ( _CALLERS [ stage ] ) if special_cases and "cnvkit" in callers : has_lumpy = any ( "lumpy" in get_svcallers ( d ) or "lumpy" in d [ "config" ] [ "algorithm" ] . get ( "svcaller_orig" , [ ] ) for d in items ) if has_lumpy and any ( "lumpy_usecnv" in dd . get_tools_on ( d ) for d i...
def link_android ( self , path , pkg ) : """Link ' s the android project to this library . 1 . Includes this project ' s directory in the app ' s android / settings . gradle It adds : include ' : < project - name > ' project ( ' : < project - name > ' ) . projectDir = new File ( rootProject . projectDir...
bundle_id = self . ctx [ 'bundle_id' ] pkg_root = join ( path , pkg ) # : Check if it ' s already linked with open ( join ( 'android' , 'settings.gradle' ) ) as f : settings_gradle = f . read ( ) with open ( join ( 'android' , 'app' , 'build.gradle' ) ) as f : build_gradle = f . read ( ) # : Find the MainApplic...
def unhandled ( self , key ) : """Handle other keyboard actions not handled by the ListBox widget ."""
self . key = key self . size = self . tui . get_cols_rows ( ) if self . search is True : if self . enter is False and self . no_matches is False : if len ( key ) == 1 and key . isprintable ( ) : self . search_string += key self . _search ( ) elif self . enter is True and not self . s...
def get_cli ( ) : """Load cli options"""
parser = argparse . ArgumentParser ( prog = "auto_version" , description = "auto version v%s: a tool to control version numbers" % __version__ , ) parser . add_argument ( "--target" , action = "append" , default = [ ] , help = "Files containing version info. " "Assumes unique variable names between files. (default: %s)...
def view ( self , request , group , ** kwargs ) : """Display and store comments ."""
if request . method == 'POST' : message = request . POST . get ( 'message' ) if message is not None and message . strip ( ) : comment = GroupComments ( group = group , author = request . user , message = message . strip ( ) ) comment . save ( ) msg = _ ( u'Comment added.' ) if re...
def __runTimer ( self ) : """运行在计时器线程中的循环函数"""
while self . __timerActive : # 创建计时器事件 event = Event ( type_ = EVENT_TIMER ) # 向队列中存入计时器事件 self . put ( event ) # 等待 sleep ( self . __timerSleep )
def _parse_version_reply ( self ) : "waiting for a version reply"
if len ( self . _data ) >= 2 : reply = self . _data [ : 2 ] self . _data = self . _data [ 2 : ] ( version , method ) = struct . unpack ( 'BB' , reply ) if version == 5 and method in [ 0x00 , 0x02 ] : self . version_reply ( method ) else : if version != 5 : self . version_...
def is_rpm_installed ( ) : """Tests if the rpm command is present ."""
try : version_result = subprocess . run ( [ "rpm" , "--usage" ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) rpm_installed = not version_result . returncode except FileNotFoundError : rpm_installed = False return rpm_installed
def notice ( self , client , message ) : """send a notice to client"""
if client and message : messages = utils . split_message ( message , self . config . max_length ) for msg in messages : client . fwrite ( ':{c.srv} NOTICE {c.nick} :{msg}' , msg = msg )
def substitute ( self , msg , kind ) : """Run a kind of substitution on a message . : param str msg : The message to run substitutions against . : param str kind : The kind of substitution to run , one of ` ` subs ` ` or ` ` person ` ` ."""
# Safety checking . if 'lists' not in self . master . _sorted : raise RepliesNotSortedError ( "You must call sort_replies() once you are done loading RiveScript documents" ) if kind not in self . master . _sorted [ "lists" ] : raise RepliesNotSortedError ( "You must call sort_replies() once you are done loading...
def paginate ( iter , ** kwargs ) : """A wrapper around the Paginator that takes config data : param iter : Query object or any iterables : param kwargs : - page : current page - per _ page : max number of items per page - total : Max number of items . If not provided , it will use the query to count - ...
kwargs . setdefault ( "page" , int ( request . args . get ( 'page' , 1 ) ) ) kwargs . setdefault ( "per_page" , int ( config ( "PAGINATION_PER_PAGE" , 1 ) ) ) kwargs . setdefault ( "padding" , int ( config ( "PAGINATION_PADDING" , 0 ) ) ) return Paginator ( iter , ** kwargs )
def area_poly_sphere ( lat , lon , r_sphere ) : '''Calculates the area enclosed by an arbitrary polygon on the sphere . Parameters lat : iterable The latitudes , in degrees , of the vertex locations of the polygon , in clockwise order . lon : iterable The longitudes , in degrees , of the vertex location...
dtr = np . pi / 180. def _tranlon ( plat , plon , qlat , qlon ) : t = np . sin ( ( qlon - plon ) * dtr ) * np . cos ( qlat * dtr ) b = ( np . sin ( qlat * dtr ) * np . cos ( plat * dtr ) - np . cos ( qlat * dtr ) * np . sin ( plat * dtr ) * np . cos ( ( qlon - plon ) * dtr ) ) return np . arctan2 ( t , b ) ...
def contains_set ( self , other , atol = 0.0 ) : """Return ` ` True ` ` if ` ` other ` ` is ( almost ) contained in this set . Parameters other : ` Set ` Set to be tested . atol : float , optional Maximum allowed distance in maximum norm from ` ` other ` ` to ` ` self ` ` . Raises AttributeError i...
if self is other : return True try : return ( self . approx_contains ( other . min ( ) , atol ) and self . approx_contains ( other . max ( ) , atol ) ) except AttributeError : raise AttributeError ( 'cannot test {!r} without `min` and `max` ' 'methods' . format ( other ) )
def get_unit_by_abbreviation ( unit_abbreviation , ** kwargs ) : """Returns a single unit by abbreviation . Used as utility function to resolve string to id"""
try : if unit_abbreviation is None : unit_abbreviation = '' unit_i = db . DBSession . query ( Unit ) . filter ( Unit . abbreviation == unit_abbreviation . strip ( ) ) . one ( ) return JSONObject ( unit_i ) except NoResultFound : # The dimension does not exist raise ResourceNotFoundError ( "Unit ...
def init_storage ( ) : """Initialize the local dictionnaries cache in ~ / . crosswords / dicts ."""
# http : / / stackoverflow . com / a / 600612/735926 try : os . makedirs ( DICTS_PATH ) except OSError as ex : if ex . errno != errno . EEXIST or not os . path . isdir ( DICTS_PATH ) : raise
def hash ( self ) : ''': rtype : int : return : hash of the field'''
hashed = super ( String , self ) . hash ( ) return khash ( hashed , self . _max_size )
def read_vcf ( vcf_file ) : """Read a vcf file to a dict of lists . : param str vcf _ file : Path to a vcf file . : return : dict of lists of vcf records : rtype : dict"""
vcf_dict = [ ] with open ( vcf_file , 'r' ) as invcf : for line in invcf : if line . startswith ( '#' ) : continue line = line . strip ( ) . split ( ) vcf_dict . append ( ( line [ 0 ] , line [ 1 ] , line [ 3 ] , line [ 4 ] ) ) return vcf_dict
def setData ( self , index , value , role = QtCore . Qt . EditRole ) : """Reimplemented from QtCore . QAbstractItemModel You can only set the value . : param index : the index to edit , column should be 1. : type index : : class : ` PySide . QtCore . QModelIndex ` : param value : the new value for the confi...
if index . isValid ( ) : if role == QtCore . Qt . EditRole : if index . column ( ) == 1 : p = index . internalPointer ( ) k = self . get_key ( p , index . row ( ) ) # we could just set the value # BUT for listvalues etc it will not work strval = se...
def verify_path ( self , mold_id_path ) : """Lookup and verify path ."""
try : path = self . lookup_path ( mold_id_path ) if not exists ( path ) : raise KeyError except KeyError : raise_os_error ( ENOENT ) return path
def run ( file_path , include_dirs = [ ] , dlems = False , nogui = False ) : """Function for running from a script or shell ."""
import argparse args = argparse . Namespace ( ) args . lems_file = file_path args . I = include_dirs args . dlems = dlems args . nogui = nogui main ( args = args )
def list_keys ( self , secret = False ) : """List the keys currently in the keyring . The GnuPG option ' - - show - photos ' , according to the GnuPG manual , " does not work with - - with - colons " , but since we can ' t rely on all versions of GnuPG to explicitly handle this correctly , we should probably ...
which = 'public-keys' if secret : which = 'secret-keys' args = [ ] args . append ( "--fixed-list-mode" ) args . append ( "--fingerprint" ) args . append ( "--with-colons" ) args . append ( "--list-options no-show-photos" ) args . append ( "--list-%s" % ( which ) ) p = self . _open_subprocess ( args ) # there might ...
def get_configparser ( filename = '' ) : """Read main configuration file and all files from * conf . d * subdirectory and return parsed configuration as a * * configparser . RawConfigParser * * instance ."""
filename = filename or os . environ . get ( 'SHELTER_CONFIG_FILENAME' , '' ) if not filename : raise ImproperlyConfiguredError ( _ ( "Configuration file is not defined. You must either " "set 'SHELTER_CONFIG_FILENAME' environment variable or " "'-f/--config-file' command line argument." ) ) parser = six . moves . c...
def qc ( args ) : """% prog qc prefix Expects data files including : 1 . ` prefix . bedpe ` draws Bezier curve between paired reads 2 . ` prefix . sizes ` draws length of the contig / scaffold 3 . ` prefix . gaps . bed ` mark the position of the gaps in sequence 4 . ` prefix . bed . coverage ` plots the b...
from jcvi . graphics . glyph import Bezier p = OptionParser ( qc . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) prefix , = args scf = prefix # All these files * must * be present in the current folder bedpefile = prefix + ".bedpe" fastafile = prefix + ".fa...
def set_target ( self , setpoint ) : """Higher level abstraction for setting the speed register . This register is responsible for telling the grizzly at what speed or position to drive at . The different control modes and type it expects is documented in the table below : Mode Type Range NO _ PID 16.16 f...
fixed_set = int ( setpoint * ( 2 ** 16 ) ) buf = [ cast_to_byte ( fixed_set >> 8 * i ) for i in range ( 5 ) ] self . set_register ( Addr . Speed , buf )
def setQuery ( self , query ) : """Sets the query for this widget to the inputed query . This will clear completely the current inforamation and reest all containers to the inputed query information . : param query | < orb . Query >"""
if not self . isVisible ( ) : self . _loadQuery = query else : self . _loadQuery = None if self . _initialized and hash ( query ) == hash ( self . query ( ) ) : return self . _initialized = True self . clear ( ) self . addContainer ( query )
def listRuns ( self , run_num = - 1 , logical_file_name = "" , block_name = "" , dataset = "" ) : """List run known to DBS ."""
if ( '%' in logical_file_name or '%' in block_name or '%' in dataset ) : dbsExceptionHandler ( 'dbsException-invalid-input' , " DBSDatasetRun/listRuns. No wildcards are allowed in logical_file_name, block_name or dataset.\n." ) conn = self . dbi . connection ( ) tran = False try : ret = self . runlist . execute...
def load_file ( cls , package_name , root_dir , relative_dirs ) : """Load and parse documentation in a list of projects . Returns a list of ParsedNodes ."""
extension = "[!.#~]*.md" file_matches = dbt . clients . system . find_matching ( root_dir , relative_dirs , extension ) for file_match in file_matches : file_contents = dbt . clients . system . load_file_contents ( file_match . get ( 'absolute_path' ) , strip = False ) parts = dbt . utils . split_path ( file_ma...
def nla_for_each_nested ( nla , rem ) : """Iterate over a stream of nested attributes . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / include / netlink / attr . h # L274 Positional arguments : nla - - attribute containing the nested attributes ( nlattr class instance ) . rem - - initiali...
pos = nlattr ( nla_data ( nla ) ) rem . value = nla_len ( nla ) while nla_ok ( pos , rem ) : yield pos pos = nla_next ( pos , rem )
def initialize_options ( self ) : """Run parent initialization and then fix the scripts var ."""
install . initialize_options ( self ) # leave the proper script according to the platform script = SCRIPT_WIN if sys . platform == "win32" else SCRIPT_REST self . distribution . scripts = [ script ]
def beacon ( config ) : '''Read the last btmp file and return information on the failed logins'''
ret = [ ] users = { } groups = { } defaults = None for config_item in config : if 'users' in config_item : users = config_item [ 'users' ] if 'groups' in config_item : groups = config_item [ 'groups' ] if 'defaults' in config_item : defaults = config_item [ 'defaults' ] with salt . u...
def create_action ( self ) : """Create actions related to channel selection ."""
actions = { } act = QAction ( 'Load Montage...' , self ) act . triggered . connect ( self . load_channels ) act . setEnabled ( False ) actions [ 'load_channels' ] = act act = QAction ( 'Save Montage...' , self ) act . triggered . connect ( self . save_channels ) act . setEnabled ( False ) actions [ 'save_channels' ] = ...
def cublasChpmv ( handle , uplo , n , alpha , AP , x , incx , beta , y , incy ) : """Matrix - vector product for Hermitian - packed matrix ."""
status = _libcublas . cublasChpmv_v2 ( handle , _CUBLAS_FILL_MODE [ uplo ] , n , ctypes . byref ( cuda . cuFloatComplex ( alpha . real , alpha . imag ) ) , int ( AP ) , int ( x ) , incx , ctypes . byref ( cuda . cuFloatComplex ( beta . real , beta . imag ) ) , int ( y ) , incy ) cublasCheckStatus ( status )
def _compute_mod_regs ( self , regs_init , regs_fini ) : """Compute modified registers ."""
assert regs_init . keys ( ) == regs_fini . keys ( ) modified_regs = [ ] for reg in regs_init : if regs_init [ reg ] != regs_fini [ reg ] : modified_regs . append ( reg ) return modified_regs