signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def H8 ( self ) : "Sum entropy ."
return - ( self . p_xplusy * np . log ( self . p_xplusy + self . eps ) ) . sum ( 1 )
def _calc_outliers_bounds ( self , data , method , coeff , window ) : """Calculate the lower and higher bound for outlier detection . Parameters data : pd . DataFrame ( ) Input dataframe . method : str Method to use for calculating the lower and higher bounds . coeff : int Coefficient to use in calcul...
if method == "std" : lowBound = ( data . mean ( axis = 0 ) - coeff * data . std ( axis = 0 ) ) . values [ 0 ] highBound = ( data . mean ( axis = 0 ) + coeff * data . std ( axis = 0 ) ) . values [ 0 ] elif method == "rstd" : rl_mean = data . rolling ( window = window ) . mean ( how = any ) rl_std = data ...
def srf_cap ( self , column = None , value = None , ** kwargs ) : """Fiscal dollar amounts for State Revolving Fund Capitalization Grants . > > > GICS ( ) . srf _ cap ( ' grant _ number ' , ' 340001900 ' )"""
return self . _resolve_call ( 'GIC_SRF_CAP' , column , value , ** kwargs )
def relative_to ( source_path : Union [ str , pathlib . Path ] , target_path : Union [ str , pathlib . Path ] ) -> pathlib . Path : """Generates relative path from ` ` source _ path ` ` to ` ` target _ path ` ` . Handles the case of paths without a common prefix . > > > import pathlib > > > source = pathlib ....
source_path = pathlib . Path ( source_path ) . absolute ( ) if source_path . is_file ( ) : source_path = source_path . parent target_path = pathlib . Path ( target_path ) . absolute ( ) common_prefix = find_common_prefix ( [ source_path , target_path ] ) if not common_prefix : raise ValueError ( "No common pref...
def __merge ( cls , * multicolors ) : """Produces a new : class : ` Multicolor ` object resulting from gathering information from all supplied : class : ` Multicolor ` instances . New : class : ` Multicolor ` is created and its : attr : ` Multicolor . multicolors ` attribute is updated with similar attributes of ...
result = cls ( ) for multicolor in multicolors : result . multicolors = result . multicolors + multicolor . multicolors return result
def previous ( self ) -> "ArrayEntry" : """Return an instance node corresponding to the previous entry . Raises : NonexistentInstance : If the receiver is the first entry of the parent array ."""
try : newval , nbef = self . before . pop ( ) except IndexError : raise NonexistentInstance ( self . json_pointer ( ) , "previous of first" ) from None return ArrayEntry ( self . index - 1 , nbef , self . after . cons ( self . value ) , newval , self . parinst , self . schema_node , self . timestamp )
def param_name_list ( self ) : """returns the list of all parameter names : return : list of list of strings ( for each light model separately )"""
name_list = [ ] for func in self . func_list : name_list . append ( func . param_names ) return name_list
def _send_dweet ( payload , url , params = None , session = None ) : """Send a dweet to dweet . io"""
data = json . dumps ( payload ) headers = { 'Content-type' : 'application/json' } return _request ( 'post' , url , data = data , headers = headers , params = params , session = session )
def gen_experiment_ref ( experiment_tag , n = 10 ) : """Generate a random string for naming . Parameters experiment _ tag : : obj : ` str ` tag to prefix name with n : int number of random chars to use Returns : obj : ` str ` string experiment ref"""
experiment_id = gen_experiment_id ( n = n ) return '{0}_{1}' . format ( experiment_tag , experiment_id )
def json_data ( self ) : """Returns data as JSON Returns : json _ data ( str ) : JSON representation of data , as created in make _ data"""
def stringify_keys ( d ) : if not isinstance ( d , dict ) : return d return dict ( ( str ( k ) , stringify_keys ( v ) ) for k , v in d . items ( ) ) data = self . make_data ( ) json_data = json . dumps ( stringify_keys ( data ) ) return json_data
def filter ( self , chromosome , ** kwargs ) : """The default filter mixes applied all SNPs and ignores Insertions and Deletions ."""
def appendAllele ( alleles , sources , snp ) : pos = snp . start if snp . alt [ 0 ] == '-' : pass # print warn % ( ' DELETION ' , snpSet , snp . start , snp . chromosomeNumber ) elif snp . ref [ 0 ] == '-' : pass # print warn % ( ' INSERTION ' , snpSet , snp . start , snp . c...
def verifymessage ( self , address , signature , message ) : """Verifies that a message has been signed by an address . Args : address ( str ) : address claiming to have signed the message signature ( str ) : ECDSA signature message ( str ) : plaintext message which was signed Returns : bool : True if t...
verified = self . rpc . call ( "verifymessage" , address , signature , message ) self . logger . debug ( "Signature verified: %s" % str ( verified ) ) return verified
def modifyPdpContextAccept ( ) : """MODIFY PDP CONTEXT ACCEPT Section 9.5.7"""
a = TpPd ( pd = 0x8 ) b = MessageType ( mesType = 0x45 ) # 01000101 packet = a / b return packet
def lookup ( self , asn = None , inc_raw = False , retry_count = 3 , response = None , field_list = None , asn_alts = None , asn_methods = None ) : """The function for retrieving and parsing ASN origin whois information via port 43 / tcp ( WHOIS ) . Args : asn ( : obj : ` str ` ) : The ASN ( required ) . in...
if asn [ 0 : 2 ] != 'AS' : asn = 'AS{0}' . format ( asn ) if asn_methods is None : if asn_alts is None : lookups = [ 'whois' , 'http' ] else : from warnings import warn warn ( 'ASNOrigin.lookup() asn_alts argument has been deprecated' ' and will be removed. You should now use the asn...
def to_native ( self , value ) : """Return the value as a dict , raising error if conversion to dict is not possible"""
if isinstance ( value , dict ) : return value elif isinstance ( value , six . string_types ) : native_value = json . loads ( value ) if isinstance ( native_value , dict ) : return native_value else : raise ConversionError ( u'Cannot load value as a dict: {}' . format ( value ) )
def update_txn_with_extra_data ( self , txn ) : """All the data of the transaction might not be stored in ledger so the extra data that is omitted from ledger needs to be fetched from the appropriate data store : param txn : : return :"""
# For RAW and ENC attributes , only hash is stored in the ledger . if get_type ( txn ) == ATTRIB : txn_data = get_payload_data ( txn ) # The key needs to be present and not None key = RAW if ( RAW in txn_data and txn_data [ RAW ] is not None ) else ENC if ( ENC in txn_data and txn_data [ ENC ] is not None )...
def reset_new_request ( self ) : """Remove the non - sense args from the self . ignore , return self . new _ request"""
raw_url = self . new_request [ 'url' ] parsed_url = urlparse ( raw_url ) qsl = parse_qsl ( parsed_url . query ) new_url = self . _join_url ( parsed_url , [ i for i in qsl if i not in self . ignore [ 'qsl' ] ] ) self . new_request [ 'url' ] = new_url self . logger_function ( 'ignore: %s' % self . ignore ) for key in sel...
def getLayoutNames ( self ) : """This function returns the list of layouts for the current db ."""
if self . _db == '' : raise FMError , 'No database was selected' request = [ ] request . append ( uu ( { '-db' : self . _db } ) ) request . append ( uu ( { '-layoutnames' : '' } ) ) result = self . _doRequest ( request ) result = FMResultset . FMResultset ( result ) layoutNames = [ ] for layoutName in result . resu...
def push ( self ) : """Pushes updated plot data via the Comm ."""
if self . renderer . mode == 'server' : return if self . comm is None : raise Exception ( 'Renderer does not have a comm.' ) if self . _root and 'embedded' in self . _root . tags : # Allows external libraries to prevent comm updates return msg = self . renderer . diff ( self , binary = True ) if msg is None...
def leak ( self ) : """Leak the adequate amount of data from the bucket . This should be called before any consumption takes place . Returns : int : the new capacity of the bucket"""
capacity , last_leak = self . storage . mget ( self . key_amount , self . key_last_leak , coherent = True ) now = time . time ( ) if last_leak : elapsed = now - last_leak decrement = elapsed * self . rate new_capacity = max ( int ( capacity - decrement ) , 0 ) else : new_capacity = 0 self . storage . ms...
def etv ( b , component , dataset , solve_for = None , ** kwargs ) : """compute the ETV column from the time _ ephem and time _ ecl columns ( used in the ETV dataset )"""
time_ephem = b . get_parameter ( qualifier = 'time_ephems' , component = component , dataset = dataset , context = [ 'dataset' , 'model' ] ) # need to provide context to avoid getting the constraint time_ecl = b . get_parameter ( qualifier = 'time_ecls' , component = component , dataset = dataset ) etv = b . get_parame...
def real ( self ) : """Real part"""
return self . __class__ . create ( self . term . real , * self . ranges )
def remote_list ( timestamps = True ) : """Return a list of the remotely available dictionnaries . Each element is a tuple of the dictionnary name and its last modification date as a timestamp ."""
r = get_remote_file ( DICTS_URL ) lst = [ ] for f in r . text . split ( '\n' ) : if not f : continue name , date = f . split ( ':' ) name = name . replace ( '.txt' , '' ) lst . append ( ( name , int ( date ) ) if timestamps else name ) return lst
def compare_branches_tags_commits ( self , project_id , from_id , to_id ) : """Compare branches , tags or commits : param project _ id : The ID of a project : param from _ id : the commit sha or branch name : param to _ id : the commit sha or branch name : return : commit list and diff between two branches ...
data = { 'from' : from_id , 'to' : to_id } request = requests . get ( '{0}/{1}/repository/compare' . format ( self . projects_url , project_id ) , params = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout , headers = self . headers ) if request . status_code == 200 : return request ...
def _get_parameter ( self , name , eopatch ) : """Collects the parameter either from initialization parameters or from EOPatch"""
if hasattr ( self , name ) and getattr ( self , name ) is not None : return getattr ( self , name ) if name == 'bbox' and eopatch . bbox : return eopatch . bbox if name in eopatch . meta_info : return eopatch . meta_info [ name ] if name == 'maxcc' : return 1.0 if name == 'time_difference' : return ...
def _read_xml_db ( self ) : """read metadata from an xml string stored in a DB . : return : the root element of the xml : rtype : ElementTree . Element"""
try : metadata_str = self . db_io . read_metadata_from_uri ( self . layer_uri , 'xml' ) root = ElementTree . fromstring ( metadata_str ) return root except HashNotFoundError : return None
def delete_channel ( self , channel_id ) : """Deletes channel"""
req = requests . delete ( self . channel_path ( channel_id ) ) return req
def best_genomes ( self , n ) : """Returns the n most fit genomes ever seen ."""
def key ( g ) : return g . fitness return sorted ( self . most_fit_genomes , key = key , reverse = True ) [ : n ]
def wrap ( scope , lines , format = BARE_FORMAT ) : """Wrap a stream of lines in armour . Takes a stream of lines , for example , the following single line : Line ( 1 , " Lorem ipsum dolor . " ) Or the following multiple lines : Line ( 1 , " Lorem ipsum " ) Line ( 2 , " dolor " ) Line ( 3 , " sit amet ....
for line in iterate ( lines ) : prefix = suffix = '' if line . first and line . last : prefix = format . single . prefix suffix = format . single . suffix else : prefix = format . multiple . prefix if line . first else format . intra . prefix suffix = format . multiple . suff...
def collect_output ( self , out_file = None ) : """Run : func : ` collect _ output ` on the job ' s output directory ."""
if self . logger . isEnabledFor ( logging . INFO ) : self . logger . info ( "collecting output %s" , " to %s" % out_file if out_file else '' ) self . logger . info ( "self.output %s" , self . output ) return collect_output ( self . output , out_file )
def cancel ( self ) : """撤单 Arguments : amount { int } - - 撤单数量"""
self . cancel_amount = self . amount - self . trade_amount if self . trade_amount == 0 : # 未交易 直接订单全撤 self . _status = ORDER_STATUS . CANCEL_ALL else : # 部分交易 剩余订单全撤 self . _status = ORDER_STATUS . CANCEL_PART
def full_name ( decl , with_defaults = True ) : """Returns declaration full qualified name . If ` decl ` belongs to anonymous namespace or class , the function will return C + + illegal qualified name . Args : decl ( declaration _ t ) : declaration for which the full qualified name should be calculated . ...
if None is decl : raise RuntimeError ( "Unable to generate full name for None object!" ) if with_defaults : if not decl . cache . full_name : path = declaration_path ( decl ) if path == [ "" ] : # Declarations without names are allowed ( for examples class # or struct instances ) . In th...
def show_image ( kwargs , call = None ) : '''Show the details from aliyun image'''
if call != 'function' : raise SaltCloudSystemExit ( 'The show_images function must be called with ' '-f or --function' ) if not isinstance ( kwargs , dict ) : kwargs = { } location = get_location ( ) if 'location' in kwargs : location = kwargs [ 'location' ] params = { 'Action' : 'DescribeImages' , 'RegionI...
def get_rt_data ( self , code ) : """获取指定股票的分时数据 : param code : 股票代码 , 例如 , HK . 00700 , US . APPL : return : ( ret , data ) ret = = RET _ OK 返回pd dataframe数据 , data . DataFrame数据 , 数据列格式如下 ret ! = RET _ OK 返回错误字符串 参数 类型 说明 code str 股票代码 time str 时间 ( yyyy - MM - dd HH : mm : ss ) ( 美股默认是美东时间 , 港股A股默认...
if code is None or is_str ( code ) is False : error_str = ERROR_STR_PREFIX + "the type of param in code is wrong" return RET_ERROR , error_str query_processor = self . _get_sync_query_processor ( RtDataQuery . pack_req , RtDataQuery . unpack_rsp ) kargs = { "code" : code , "conn_id" : self . get_sync_conn_id ( ...
def is_triangular ( self , var ) : """Test if a variable is on a triangular grid This method first checks the ` grid _ type ` attribute of the variable ( if existent ) whether it is equal to ` ` " unstructered " ` ` , then it checks whether the bounds are not two - dimensional . Parameters var : xarray . ...
warn ( "The 'is_triangular' method is depreceated and will be removed " "soon! Use the 'is_unstructured' method!" , DeprecationWarning , stacklevel = 1 ) return str ( var . attrs . get ( 'grid_type' ) ) == 'unstructured' or self . _check_triangular_bounds ( var ) [ 0 ]
def _find_complete_block_bounds ( self , table , used_cells , possible_block_start , start_pos , end_pos ) : '''Finds the end of a block from a start location and a suggested end location .'''
block_start = list ( possible_block_start ) block_end = list ( possible_block_start ) table_row = table [ block_start [ 0 ] ] used_row = used_cells [ block_start [ 0 ] ] # Find which column the titles end on for column_index in range ( block_start [ 1 ] , end_pos [ 1 ] + 1 ) : # Ensure we catch the edge case of the dat...
def null ( self , field , ** validations ) : """* Asserts the field as JSON null . * The field consists of parts separated by spaces , the parts being object property names or array indices starting from 0 , and the root being the instance created by the last request ( see ` Output ` for it ) . For assertin...
values = [ ] for found in self . _find_by_field ( field ) : reality = found [ "reality" ] schema = { "type" : "null" } skip = self . _input_boolean ( validations . pop ( "skip" , False ) ) if not skip : self . _assert_schema ( schema , reality ) values . append ( reality ) return values
def ParseOptions ( cls , options , output_module ) : """Parses and validates options . Args : options ( argparse . Namespace ) : parser options . output _ module ( XLSXOutputModule ) : output module to configure . Raises : BadConfigObject : when the output module object is of the wrong type . BadConfigO...
if not isinstance ( output_module , xlsx . XLSXOutputModule ) : raise errors . BadConfigObject ( 'Output module is not an instance of XLSXOutputModule' ) fields = cls . _ParseStringOption ( options , 'fields' , default_value = cls . _DEFAULT_FIELDS ) additional_fields = cls . _ParseStringOption ( options , 'additio...
def _integrate_scipy ( self , intern_xout , intern_y0 , intern_p , atol = 1e-8 , rtol = 1e-8 , first_step = None , with_jacobian = None , force_predefined = False , name = None , ** kwargs ) : """Do not use directly ( use ` ` integrate ( ' scipy ' , . . . ) ` ` ) . Uses ` scipy . integrate . ode < http : / / docs...
from scipy . integrate import ode ny = intern_y0 . shape [ - 1 ] nx = intern_xout . shape [ - 1 ] results = [ ] for _xout , _y0 , _p in zip ( intern_xout , intern_y0 , intern_p ) : if name is None : if self . j_cb is None : name = 'dopri5' else : name = 'lsoda' if with_ja...
def _id ( self ) : """Handle identifiers and reserverd keywords ."""
result = '' while self . char is not None and ( self . char . isalnum ( ) or self . char == '_' ) : result += self . char self . advance ( ) token = RESERVED_KEYWORDS . get ( result , Token ( Nature . ID , result ) ) return token
def add_errors ( self , * errors : Union [ BaseSchemaError , SchemaErrorCollection ] ) -> None : """Adds errors to the error store for the schema"""
for error in errors : self . _error_cache . add ( error )
def export_for_schema ( self ) : """Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement ."""
ret = "{'class': 'NetworkTopologyStrategy'" for dc , repl_factor in sorted ( self . dc_replication_factors . items ( ) ) : ret += ", '%s': '%d'" % ( dc , repl_factor ) return ret + "}"
def _start ( self ) : """Starts the instantiation queue ( called by its bundle activator )"""
try : # Try to register to factory events with use_ipopo ( self . __context ) as ipopo : ipopo . add_listener ( self ) except BundleException : # Service not yet present pass # Register the iPOPO service listener self . __context . add_service_listener ( self , specification = SERVICE_IPOPO )
def rev_reg_id2cred_def_id__tag ( rr_id : str ) -> ( str , str ) : """Given a revocation registry identifier , return its corresponding credential definition identifier and ( stringified int ) tag . : param rr _ id : revocation registry identifier : return : credential definition identifier and tag"""
return ( ':' . join ( rr_id . split ( ':' ) [ 2 : - 2 ] ) , # rev reg id comprises ( prefixes ) : < cred _ def _ id > : ( suffixes ) str ( rr_id . split ( ':' ) [ - 1 ] ) # tag is last token )
def replace ( self , accountID , orderSpecifier , ** kwargs ) : """Replace an Order in an Account by simultaneously cancelling it and creating a replacement Order Args : accountID : Account Identifier orderSpecifier : The Order Specifier order : Specification of the replacing Order Returns : v20...
request = Request ( 'PUT' , '/v3/accounts/{accountID}/orders/{orderSpecifier}' ) request . set_path_param ( 'accountID' , accountID ) request . set_path_param ( 'orderSpecifier' , orderSpecifier ) body = EntityDict ( ) if 'order' in kwargs : body . set ( 'order' , kwargs [ 'order' ] ) request . set_body_dict ( body...
def count ( a , axis = None ) : """Count the non - masked elements of the array along the given axis . . . note : : Currently limited to operating on a single axis . : param axis : Axis or axes along which the operation is performed . The default ( axis = None ) is to perform the operation over all the dime...
axes = _normalise_axis ( axis , a ) if axes is None or len ( axes ) != 1 : msg = "This operation is currently limited to a single axis" raise AxisSupportError ( msg ) return _Aggregation ( a , axes [ 0 ] , _CountStreamsHandler , _CountMaskedStreamsHandler , np . dtype ( 'i' ) , { } )
def run ( self ) : '''run - Starts the thread . bgwrite and bgwrite _ chunk automatically start the thread .'''
# If we are chaining after another process , wait for it to complete . # We use a flag here instead of joining the thread for various reasons chainAfter = self . chainAfter if chainAfter is not None : chainPollTime = self . backgroundIOPriority . chainPollTime while chainAfter . finished is False : time...
def unlock ( self , source_node , check_status = True ) : """Unlock the task , set its status to ` S _ READY ` so that the scheduler can submit it . source _ node is the : class : ` Node ` that removed the lock Call task . check _ status if check _ status is True ."""
if self . status != self . S_LOCKED : raise RuntimeError ( "Trying to unlock a task with status %s" % self . status ) self . _status = self . S_READY if check_status : self . check_status ( ) self . history . info ( "Unlocked by %s" , source_node )
def createFile ( dataArray = None , outfile = None , header = None ) : """Create a simple fits file for the given data array and header . Returns either the FITS object in - membory when outfile = = None or None when the FITS file was written out to a file ."""
# Insure that at least a data - array has been provided to create the file assert ( dataArray is not None ) , "Please supply a data array for createFiles" try : # Create the output file fitsobj = fits . HDUList ( ) if header is not None : try : del ( header [ 'NAXIS1' ] ) del ( h...
def merge_requests ( self , ** kwargs ) : """List the merge requests related to this milestone . Args : all ( bool ) : If True , return all the items , without pagination per _ page ( int ) : Number of items to retrieve per request page ( int ) : ID of the page to return ( starts with page 1) as _ list ( ...
path = '%s/%s/merge_requests' % ( self . manager . path , self . get_id ( ) ) data_list = self . manager . gitlab . http_list ( path , as_list = False , ** kwargs ) manager = GroupIssueManager ( self . manager . gitlab , parent = self . manager . _parent ) # FIXME ( gpocentek ) : the computed manager path is not correc...
def hide_routemap_holder_route_map_content_set_local_preference_local_preference_value ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hide_routemap_holder = ET . SubElement ( config , "hide-routemap-holder" , xmlns = "urn:brocade.com:mgmt:brocade-ip-policy" ) route_map = ET . SubElement ( hide_routemap_holder , "route-map" ) name_key = ET . SubElement ( route_map , "name" ) name_key . text = kwargs . pop ( 'name' ) ...
def gps2_rtk_encode ( self , time_last_baseline_ms , rtk_receiver_id , wn , tow , rtk_health , rtk_rate , nsats , baseline_coords_type , baseline_a_mm , baseline_b_mm , baseline_c_mm , accuracy , iar_num_hypotheses ) : '''RTK GPS data . Gives information on the relative baseline calculation the GPS is reporting ...
return MAVLink_gps2_rtk_message ( time_last_baseline_ms , rtk_receiver_id , wn , tow , rtk_health , rtk_rate , nsats , baseline_coords_type , baseline_a_mm , baseline_b_mm , baseline_c_mm , accuracy , iar_num_hypotheses )
def list_types_view ( request , semester , profile = None ) : """View the details of a particular WorkshiftType ."""
page_name = "Workshift Types" full_management = utils . can_manage ( request . user , semester ) any_management = utils . can_manage ( request . user , semester , any_pool = True ) types = WorkshiftType . objects . all ( ) type_shifts = [ RegularWorkshift . objects . filter ( workshift_type = i , pool__semester = semes...
def join ( self , master ) : """Join this speaker to another " master " speaker ."""
self . avTransport . SetAVTransportURI ( [ ( 'InstanceID' , 0 ) , ( 'CurrentURI' , 'x-rincon:{0}' . format ( master . uid ) ) , ( 'CurrentURIMetaData' , '' ) ] ) self . _zgs_cache . clear ( ) self . _parse_zone_group_state ( )
def detect_port ( port ) : '''Detect if the port is used'''
socket_test = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) try : socket_test . connect ( ( '127.0.0.1' , int ( port ) ) ) socket_test . close ( ) return True except : return False
def get_min_col_num ( mention ) : """Return the lowest column number that a Mention occupies . : param mention : The Mention to evaluate . If a candidate is given , default to its first Mention . : rtype : integer or None"""
span = _to_span ( mention ) if span . sentence . is_tabular ( ) : return span . sentence . cell . col_start else : return None
def __serve_forever ( self ) : """Main loop for the CLI . return True if we should continue ( no exit key has been pressed )"""
# Start a counter used to compute the time needed for # update and export the stats counter = Counter ( ) # Update stats self . stats . update ( ) logger . debug ( 'Stats updated in {} seconds' . format ( counter . get ( ) ) ) # Export stats counter_export = Counter ( ) self . stats . export ( self . stats ) logger . d...
def file_upload ( context , id , path ) : """file _ upload ( context , id , path ) Upload a file in a component > > > dcictl component - file - upload [ OPTIONS ] : param string id : ID of the component to attach file [ required ] : param string path : Path to the file to upload [ required ]"""
result = component . file_upload ( context , id = id , file_path = path ) utils . format_output ( result , context . format )
def update_security_group ( self , security_group , body = None ) : """Updates a security group ."""
return self . put ( self . security_group_path % security_group , body = body )
def get_prop_value ( name , props , default = None ) : # type : ( str , Dict [ str , Any ] , Any ) - > Any """Returns the value of a property or the default one : param name : Name of a property : param props : Dictionary of properties : param default : Default value : return : The value of the property or ...
if not props : return default try : return props [ name ] except KeyError : return default
def get_public_agents_public_ip ( ) : """Provides a list public IPs for public agents in the cluster"""
public_ip_list = [ ] agents = get_public_agents ( ) for agent in agents : status , public_ip = shakedown . run_command_on_agent ( agent , "/opt/mesosphere/bin/detect_ip_public" ) public_ip_list . append ( public_ip ) return public_ip_list
def append_text_column ( self , text : str , index : int ) : """Add value to the output row , width based on index"""
width = self . columns [ index ] [ "width" ] return f"{text:<{width}}"
def date_time_between_dates ( self , datetime_start = None , datetime_end = None , tzinfo = None ) : """Takes two DateTime objects and returns a random datetime between the two given datetimes . Accepts DateTime objects . : param datetime _ start : DateTime : param datetime _ end : DateTime : param tzinfo...
if datetime_start is None : datetime_start = datetime . now ( tzinfo ) if datetime_end is None : datetime_end = datetime . now ( tzinfo ) timestamp = self . generator . random . randint ( datetime_to_timestamp ( datetime_start ) , datetime_to_timestamp ( datetime_end ) , ) try : if tzinfo is None : ...
def _start_drone ( self ) : """Restarts the drone"""
with open ( self . config_file , 'r' ) as config_file : self . config = json . load ( config_file , object_hook = asciify ) mode = None if self . config [ 'general' ] [ 'mode' ] == '' or self . config [ 'general' ] [ 'mode' ] is None : logger . info ( 'Drone has not been configured, awaiting configuration from ...
def subblocks ( a , * ranges ) : """This function produces a distributed array from a subset of the blocks in the ` a ` . The result and ` a ` will have the same number of dimensions . For example , subblocks ( a , [ 0 , 1 ] , [ 2 , 4 ] ) will produce a DistArray whose objectids are [ [ a . objectids [ 0 ...
ranges = list ( ranges ) if len ( ranges ) != a . ndim : raise Exception ( "sub_blocks expects to receive a number of ranges " "equal to a.ndim, but it received {} ranges and " "a.ndim = {}." . format ( len ( ranges ) , a . ndim ) ) for i in range ( len ( ranges ) ) : # We allow the user to pass in an empty list to...
def sagemaker_timestamp ( ) : """Return a timestamp with millisecond precision ."""
moment = time . time ( ) moment_ms = repr ( moment ) . split ( '.' ) [ 1 ] [ : 3 ] return time . strftime ( "%Y-%m-%d-%H-%M-%S-{}" . format ( moment_ms ) , time . gmtime ( moment ) )
def _file_path ( cls , checksum , download_dir ) : """returns a file ' s relative local path based on the nesting parameters and the files hash : param checksum : a string checksum : param download _ dir : root directory for filestore : return : relative Path object"""
checksum = checksum . lower ( ) file_prefix = '_' . join ( [ 'files' ] + list ( map ( str , cls . DIRECTORY_NAME_LENGTHS ) ) ) path_pieces = [ download_dir , '.hca' , 'v2' , file_prefix ] checksum_index = 0 assert ( sum ( cls . DIRECTORY_NAME_LENGTHS ) <= len ( checksum ) ) for prefix_length in cls . DIRECTORY_NAME_LEN...
def get_cache_buster ( src_path , method = 'importtime' ) : """Return a string that can be used as a parameter for cache - busting URLs for this asset . : param src _ path : Filesystem path to the file we ' re generating a cache - busting value for . : param method : Method for cache - busting . Supported...
try : fn = _BUST_METHODS [ method ] except KeyError : raise KeyError ( 'Unsupported busting method value: %s' % method ) return fn ( src_path )
def dump ( cursor ) : """Display the AST represented by the cursor"""
def node_children ( node ) : return list ( node . get_children ( ) ) def print_node ( node ) : text = node . spelling or node . displayname kind = str ( node . kind ) . split ( '.' ) [ 1 ] return '{} {}' . format ( kind , text ) return draw_tree ( cursor , node_children , print_node )
def trim_wav_ms ( in_path : Path , out_path : Path , start_time : int , end_time : int ) -> None : """Extracts part of a WAV File . First attempts to call sox . If sox is unavailable , it backs off to pydub + ffmpeg . Args : in _ path : A path to the source file to extract a portion of out _ path : A path...
try : trim_wav_sox ( in_path , out_path , start_time , end_time ) except FileNotFoundError : # Then sox isn ' t installed , so use pydub / ffmpeg trim_wav_pydub ( in_path , out_path , start_time , end_time ) except subprocess . CalledProcessError : # Then there is an issue calling sox . Perhaps the input file i...
def from_dict ( cls , serialized ) : '''Create a new ErrorInfo object from a JSON deserialized dictionary @ param serialized The JSON object { dict } @ return ErrorInfo object'''
if serialized is None : return None macaroon = serialized . get ( 'Macaroon' ) if macaroon is not None : macaroon = bakery . Macaroon . from_dict ( macaroon ) path = serialized . get ( 'MacaroonPath' ) cookie_name_suffix = serialized . get ( 'CookieNameSuffix' ) visit_url = serialized . get ( 'VisitURL' ) wait_...
def decode ( self , content , apple_fix = False ) : """Decode content using the set charset . : param content : content do decode : param apple _ fix : fix Apple txdata bug : return : decoded ( and fixed ) content"""
content = content . decode ( self . encoding ) content = content . replace ( '\r' , '' ) if apple_fix : content = apple_data_fix ( content ) return content
def find_device ( vidpid ) : """Finds a connected device with the given VID : PID . Returns the serial port url ."""
for port in list_ports . comports ( ) : if re . search ( vidpid , port [ 2 ] , flags = re . IGNORECASE ) : return port [ 0 ] raise exceptions . RoasterLookupError
def make_niche_grid ( res_dict , world_size = ( 60 , 60 ) ) : """Converts dictionary specifying where resources are to nested lists specifying what sets of resources are where . res _ dict - a dictionary in which keys are resources in the environment and values are list of tuples representing the cells they '...
# Initialize array to represent world world = initialize_grid ( world_size , set ( ) ) # Fill in data on niches present in each cell of the world for res in res_dict : for cell in res_dict [ res ] : world [ cell [ 1 ] ] [ cell [ 0 ] ] . add ( res ) return world
def get_fitting ( self , fitting = None , ** kwargs ) : """[ NOT IMPLEMENTED ] : raises NotImplementedError : because it isn ' t"""
raise NotImplementedError if fitting is not None : kwargs [ 'fitting' ] = fitting kwargs [ 'context' ] = 'fitting' return self . filter ( ** kwargs )
def request ( self , method , url , headers = None , raise_exception = True , ** kwargs ) : """Main method for routing HTTP requests to the configured Vault base _ uri . : param method : HTTP method to use with the request . E . g . , GET , POST , etc . : type method : str : param url : Partial URL path to se...
if '//' in url : # Vault CLI treats a double forward slash ( ' / / ' ) as a single forward slash for a given path . # To avoid issues with the requests module ' s redirection logic , we perform the same translation here . logger . warning ( 'Replacing double-slashes ("//") in path with single slash ("/") to avoid V...
def schedule_at ( unixtime , target = None , args = ( ) , kwargs = None ) : """insert a greenlet into the scheduler to be run at a set time If provided a function , it is wrapped in a new greenlet : param unixtime : the unix timestamp at which the new greenlet should be started : type unixtime : int or floa...
if target is None : def decorator ( target ) : return schedule_at ( unixtime , target , args = args , kwargs = kwargs ) return decorator if isinstance ( target , compat . greenlet ) or target is compat . main_greenlet : glet = target else : glet = greenlet ( target , args , kwargs ) state . time...
def _join_gene ( query , gene_name , gene_symbol , gene_id ) : """helper function to add a query join to Gene model : param ` sqlalchemy . orm . query . Query ` query : SQL Alchemy query : param str gene _ name : gene name : param str gene _ symbol : gene symbol : param int gene _ id : NCBI Gene identifier ...
if gene_name or gene_symbol : query = query . join ( models . Gene ) if gene_symbol : query = query . filter ( models . Gene . gene_symbol . like ( gene_symbol ) ) if gene_name : query = query . filter ( models . Gene . gene_name . like ( gene_name ) ) if gene_id : query = query ...
def defines ( self , id , domain = 'messages' ) : """Checks if a message has a translation ( it does not take into account the fallback mechanism ) . @ rtype : bool @ return : true if the message has a translation , false otherwise"""
assert isinstance ( id , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) return id in self . messages . get ( domain , { } )
def add_session ( session = None ) : r"""Add a session to the SessionActivity table . : param session : Flask Session object to add . If None , ` ` session ` ` is used . The object is expected to have a dictionary entry named ` ` " user _ id " ` ` and a field ` ` sid _ s ` `"""
user_id , sid_s = session [ 'user_id' ] , session . sid_s with db . session . begin_nested ( ) : session_activity = SessionActivity ( user_id = user_id , sid_s = sid_s , ip = request . remote_addr , country = _ip2country ( request . remote_addr ) , ** _extract_info_from_useragent ( request . headers . get ( 'User-A...
def qteStopRecordingHook ( self , msgObj ) : """Stop macro recording . The signals from the event handler are disconnected and the event handler policy set to default ."""
# Update status flag and disconnect all signals . if self . qteRecording : self . qteRecording = False self . qteMain . qteStatus ( 'Macro recording stopped' ) self . qteMain . qtesigKeyparsed . disconnect ( self . qteKeyPress ) self . qteMain . qtesigAbort . disconnect ( self . qteStopRecordingHook )
def pickle_dumps ( self , protocol = None ) : """Return a string with the pickle representation . ` protocol ` selects the pickle protocol . self . pickle _ protocol is used if ` protocol ` is None"""
strio = StringIO ( ) pmg_pickle_dump ( self , strio , protocol = self . pickle_protocol if protocol is None else protocol ) return strio . getvalue ( )
def _prepare_temp_dir ( self ) : """Cleans up and prepare temporary directory ."""
shell_call ( [ 'rm' , '-rf' , os . path . join ( self . _temp_dir , '*' ) ] ) # NOTE : we do not create self . _ extracted _ submission _ dir # this is intentional because self . _ tmp _ extracted _ dir or it ' s subdir # will be renames into self . _ extracted _ submission _ dir os . mkdir ( self . _tmp_extracted_dir ...
def add ( self , agent_id , media_type , media_file ) : """新增其它类型永久素材 详情请参考 https : / / qydev . weixin . qq . com / wiki / index . php ? title = % E4 % B8%8A % E4 % BC % A0 % E6 % B0 % B8 % E4 % B9%85 % E7 % B4 % A0 % E6%9D % 90 : param agent _ id : 企业应用的id : param media _ type : 媒体文件类型 , 分别有图片 ( image ) 、 ...
params = { 'agentid' : agent_id , 'type' : media_type , } return self . _post ( url = 'material/add_material' , params = params , files = { 'media' : media_file } )
def refactor_with_2to3 ( source_text , fixer_names , filename = '' ) : """Use lib2to3 to refactor the source . Return the refactored source code ."""
from lib2to3 . refactor import RefactoringTool fixers = [ 'lib2to3.fixes.fix_' + name for name in fixer_names ] tool = RefactoringTool ( fixer_names = fixers , explicit = fixers ) from lib2to3 . pgen2 import tokenize as lib2to3_tokenize try : # The name parameter is necessary particularly for the " import " fixer . ...
async def observer_orm_notify ( self , message ) : """Process notification from ORM ."""
@ database_sync_to_async def get_observers ( table ) : # Find all observers with dependencies on the given table . return list ( Observer . objects . filter ( dependencies__table = table , subscribers__isnull = False ) . distinct ( 'pk' ) . values_list ( 'pk' , flat = True ) ) observers_ids = await get_observers ( ...
def query ( querystr , connection = None , ** connectkwargs ) : """Execute a query of the given SQL database"""
if connection is None : connection = connect ( ** connectkwargs ) cursor = connection . cursor ( ) cursor . execute ( querystr ) return cursor . fetchall ( )
def create_index ( self , key , reindex = True , sparse = False ) : """Creates an index if it does not exist then performs a full reindex for this collection"""
warnings . warn ( 'Index support is currently very alpha and is not guaranteed' ) if isinstance ( key , ( list , tuple ) ) : index_name = ',' . join ( key ) index_columns = ', ' . join ( '%s text' % f for f in key ) else : index_name = key index_columns = '%s text' % key table_name = '[%s{%s}]' % ( self...
def reindex ( report ) : """Reindex report so that ' TOTAL ' is the last row"""
index = list ( report . index ) i = index . index ( 'TOTAL' ) return report . reindex ( index [ : i ] + index [ i + 1 : ] + [ 'TOTAL' ] )
def data_path ( self ) -> DataPath : """Return the receiver ' s data path ."""
dp = self . data_parent ( ) return ( dp . data_path ( ) if dp else "" ) + "/" + self . iname ( )
def toggle ( self , * args ) : """If no arguments are specified , toggle the state of all LEDs . If arguments are specified , they must be the indexes of the LEDs you wish to toggle . For example : : from gpiozero import LEDBoard leds = LEDBoard ( 2 , 3 , 4 , 5) leds . toggle ( 0 ) # turn on the first LED...
self . _stop_blink ( ) if args : for index in args : self [ index ] . toggle ( ) else : super ( LEDBoard , self ) . toggle ( )
def get_domain ( self ) : """: returns : opposite vertices of the bounding prism for this object . : rtype : ndarray ( [ min ] , [ max ] )"""
if self . domain is None : return np . array ( [ self . points . min ( axis = 0 ) , self . points . max ( axis = 0 ) ] ) return self . domain
def loglike ( self , endog , mu , freq_weights = 1. , scale = 1. ) : """The log - likelihood in terms of the fitted mean response . Parameters endog : array - like Endogenous response variable mu : array - like Fitted mean response variable freq _ weights : array - like 1d array of frequency weights ....
if isinstance ( self . link , L . Power ) and self . link . power == 1 : # This is just the loglikelihood for classical OLS nobs2 = endog . shape [ 0 ] / 2. SSR = np . sum ( ( endog - self . fitted ( mu ) ) ** 2 , axis = 0 ) llf = - np . log ( SSR ) * nobs2 llf -= ( 1 + np . log ( np . pi / nobs2 ) ) * ...
def NgramScorer ( frequency_map ) : """Compute the score of a text by using the frequencies of ngrams . Example : > > > fitness = NgramScorer ( english . unigrams ) > > > fitness ( " ABC " ) -4.3622319742618245 Args : frequency _ map ( dict ) : ngram to frequency mapping"""
# Calculate the log probability length = len ( next ( iter ( frequency_map ) ) ) # TODO : 0.01 is a magic number . Needs to be better than that . floor = math . log10 ( 0.01 / sum ( frequency_map . values ( ) ) ) ngrams = frequency . frequency_to_probability ( frequency_map , decorator = math . log10 ) def inner ( text...
def ignore_missing_email_protection_eku_cb ( ok , ctx ) : """For verifying PKCS7 signature , m2Crypto uses OpenSSL ' s PKCS7 _ verify ( ) . The latter requires that ExtendedKeyUsage extension , if present , contains ' emailProtection ' OID . ( Is it because S / MIME is / was the primary use case for PKCS7 ? )...
# The error we want to ignore is indicated by X509 _ V _ ERR _ INVALID _ PURPOSE . err = ctx . get_error ( ) if err != m2 . X509_V_ERR_INVALID_PURPOSE : return ok # PKCS7 _ verify ( ) has this requriement only for the signing certificate . # Do not modify the behavior for certificates upper in the chain . if ctx . ...
def get_set_num_ruptures ( src ) : """Extract the number of ruptures and set it"""
if not src . num_ruptures : t0 = time . time ( ) src . num_ruptures = src . count_ruptures ( ) dt = time . time ( ) - t0 clsname = src . __class__ . __name__ if dt > 10 : if 'Area' in clsname : logging . warning ( '%s.count_ruptures took %d seconds, perhaps the ' 'area discretiza...
async def _executemany ( self , query , dps , cursor ) : """executemany"""
result_map = None if isinstance ( query , str ) : await cursor . executemany ( query , dps ) elif isinstance ( query , DDLElement ) : raise exc . ArgumentError ( "Don't mix sqlalchemy DDL clause " "and execution with parameters" ) elif isinstance ( query , ClauseElement ) : compiled = query . compile ( dial...
def route_table_create_or_update ( name , resource_group , ** kwargs ) : '''. . versionadded : : 2019.2.0 Create or update a route table within a specified resource group . : param name : The name of the route table to create . : param resource _ group : The resource group name assigned to the route table ....
if 'location' not in kwargs : rg_props = __salt__ [ 'azurearm_resource.resource_group_get' ] ( resource_group , ** kwargs ) if 'error' in rg_props : log . error ( 'Unable to determine location from resource group specified.' ) return False kwargs [ 'location' ] = rg_props [ 'location' ] netc...
def instance ( * args , ** kwargs ) : """Singleton to return only one instance of Config . : returns : instance of Config"""
if not hasattr ( Config , "_instance" ) or Config . _instance is None : Config . _instance = Config ( * args , ** kwargs ) return Config . _instance
def on_date ( self , date , only_count = False ) : '''Filters out only the rows that match the spectified date . Works only on a Result that has _ start and _ end columns . : param date : date can be anything Pandas . Timestamp supports parsing : param only _ count : return back only the match count'''
if not self . check_in_bounds ( date ) : raise ValueError ( 'Date %s is not in the queried range.' % date ) date = Timestamp ( date ) after_start = self . _start <= date before_end = ( self . _end > date ) | self . _end_isnull if only_count : return np . sum ( before_end & after_start ) else : return self ....