signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def render_tag ( tag , attrs = None , content = None , close = True ) : """Render a HTML tag"""
builder = "<{tag}{attrs}>{content}" if content or close : builder += "</{tag}>" return format_html ( builder , tag = tag , attrs = mark_safe ( flatatt ( attrs ) ) if attrs else "" , content = text_value ( content ) , )
def list ( context , job_id , sort , limit , where , verbose ) : """list ( context , sort , limit , where , verbose ) List all files . > > > dcictl file - list job - id [ OPTIONS ] : param string sort : Field to apply sort : param integer limit : Max number of rows to return : param string where : An opti...
result = job . list_files ( context , id = job_id , sort = sort , limit = limit , verbose = verbose , where = where ) utils . format_output ( result , context . format , verbose = verbose )
def cv ( params , train_set , num_boost_round = 100 , folds = None , nfold = 5 , stratified = True , shuffle = True , metrics = None , fobj = None , feval = None , init_model = None , feature_name = 'auto' , categorical_feature = 'auto' , early_stopping_rounds = None , fpreproc = None , verbose_eval = None , show_stdv ...
if not isinstance ( train_set , Dataset ) : raise TypeError ( "Traninig only accepts Dataset object" ) params = copy . deepcopy ( params ) if fobj is not None : params [ 'objective' ] = 'none' for alias in [ "num_iterations" , "num_iteration" , "n_iter" , "num_tree" , "num_trees" , "num_round" , "num_rounds" , ...
def get_cutout ( self , resource , resolution , x_range , y_range , z_range , time_range = None , id_list = [ ] , access_mode = CacheMode . no_cache , ** kwargs ) : """Get a cutout from the volume service . Args : resource ( intern . resource . boss . resource . ChannelResource ) : Channel or layer resource . ...
return self . service . get_cutout ( resource , resolution , x_range , y_range , z_range , time_range , id_list , self . url_prefix , self . auth , self . session , self . session_send_opts , access_mode , ** kwargs )
def split_heads ( x : mx . sym . Symbol , depth_per_head : int , heads : int ) -> mx . sym . Symbol : """Returns a symbol with head dimension folded into batch and depth divided by the number of heads . : param x : Symbol of shape ( batch , length , depth ) . : param depth _ per _ head : Depth per head . : pa...
# ( batch , length , heads , depth _ per _ head ) x = mx . sym . reshape ( data = x , shape = ( 0 , - 1 , heads , depth_per_head ) ) # ( batch , heads , length , depth / heads ) x = mx . sym . transpose ( data = x , axes = ( 0 , 2 , 1 , 3 ) ) # ( batch * heads , length , depth / heads ) return mx . sym . reshape ( data...
def ref ( host , seq , takeoff , emergency = False ) : """Basic behaviour of the drone : take - off / landing , emergency stop / reset ) Parameters : seq - - sequence number takeoff - - True : Takeoff / False : Land emergency - - True : Turn off the engines"""
p = 0b10001010101000000000000000000 if takeoff : p |= 0b1000000000 if emergency : p |= 0b100000000 at ( host , 'REF' , seq , [ p ] )
def save ( self , path , group = None ) : """Save array to a Numpy . npy , hdf , or text file . When saving a complex array as text , the real and imaginary parts are saved as the first and second column respectively . When using hdf format , the data is stored as a single vector , along with relevant attribu...
ext = _os . path . splitext ( path ) [ 1 ] if ext == '.npy' : _numpy . save ( path , self . numpy ( ) ) elif ext == '.txt' : if self . kind == 'real' : _numpy . savetxt ( path , self . numpy ( ) ) elif self . kind == 'complex' : output = _numpy . vstack ( ( self . numpy ( ) . real , self . n...
def _get_all ( self , _type ) : """Gets all instances implementing type < _ type >"""
if _type not in self . modules : raise ValueError ( "No such module, %s" % _type ) if not self . insts_implementing . get ( _type , None ) : raise ValueError ( "No instance implementing %s" % _type ) return self . insts_implementing [ _type ]
def work_wait ( self ) : """Wait for new jobs to arrive"""
if len ( self . queues_with_notify ) > 0 : # https : / / github . com / antirez / redis / issues / 874 connections . redis . blpop ( * ( self . queues_with_notify + [ max ( 1 , int ( self . config [ "max_latency" ] ) ) ] ) ) else : gevent . sleep ( self . config [ "max_latency" ] )
def _validate_valueschema ( self , schema , field , value ) : """{ ' type ' : [ ' dict ' , ' string ' ] , ' validator ' : ' bulk _ schema ' , ' forbidden ' : [ ' rename ' , ' rename _ handler ' ] }"""
schema_crumb = ( field , 'valueschema' ) if isinstance ( value , Mapping ) : validator = self . _get_child_validator ( document_crumb = field , schema_crumb = schema_crumb , schema = dict ( ( k , schema ) for k in value ) ) validator ( value , update = self . update , normalize = False ) if validator . _err...
def declare_actor ( self , actor ) : # pragma : no cover """Declare a new actor on this broker . Declaring an Actor twice replaces the first actor with the second by name . Parameters : actor ( Actor ) : The actor being declared ."""
self . emit_before ( "declare_actor" , actor ) self . declare_queue ( actor . queue_name ) self . actors [ actor . actor_name ] = actor self . emit_after ( "declare_actor" , actor )
def get_events ( conn , stackname ) : """Get the events in batches and return in chronological order"""
next = None event_list = [ ] while 1 : events = conn . describe_stack_events ( stackname , next ) event_list . append ( events ) if events . next_token is None : break next = events . next_token time . sleep ( 1 ) return reversed ( sum ( event_list , [ ] ) )
def create_free_shipping_promotion ( cls , free_shipping_promotion , ** kwargs ) : """Create FreeShippingPromotion Create a new FreeShippingPromotion This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . create _ free _...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _create_free_shipping_promotion_with_http_info ( free_shipping_promotion , ** kwargs ) else : ( data ) = cls . _create_free_shipping_promotion_with_http_info ( free_shipping_promotion , ** kwargs ) return data
async def _handle ( self , reader , writer ) : """Handle a single TCP connection Parses requests , finds appropriate handlers and returns responses"""
peer = writer . get_extra_info ( 'peername' ) self . _logger . debug ( 'New connection from {}' . format ( peer ) ) try : # Loop handling requests while True : # Read the request req = Request ( ) await req . _read ( reader ) # Find and execute handler res = None for path_reg...
def load_stock_quantity ( self , symbol : str ) -> Decimal ( 0 ) : """retrieves stock quantity"""
book = self . get_gc_book ( ) collection = SecuritiesAggregate ( book ) sec = collection . get_aggregate_for_symbol ( symbol ) quantity = sec . get_quantity ( ) return quantity
def _make_object_dict ( self , obj ) : """Processes an object , exporting its data as a nested dictionary . : param obj : An object : return : A nested dictionary of object data"""
data = { } for attr in dir ( obj ) : if attr [ 0 ] is not '_' and attr is not 'status' : datum = getattr ( obj , attr ) if not isinstance ( datum , types . MethodType ) : data . update ( self . _handle_object ( attr , datum ) ) return data
def p_toc ( self , toc ) : '''toc : HEADERSEC opttexts TOC opttexts'''
toc [ 0 ] = TableOfContent ( toc [ 1 ] , toc [ 2 ] , [ ] ) self . toc = toc [ 0 ]
def _get_params_for_optimizer ( self , prefix , named_parameters ) : """Parse kwargs configuration for the optimizer identified by the given prefix . Supports param group assignment using wildcards : optimizer _ _ lr = 0.05, optimizer _ _ param _ groups = [ ( ' rnn * . period ' , { ' lr ' : 0.3 , ' momentum...
kwargs = self . _get_params_for ( prefix ) params = list ( named_parameters ) pgroups = [ ] for pattern , group in kwargs . pop ( 'param_groups' , [ ] ) : matches = [ i for i , ( name , _ ) in enumerate ( params ) if fnmatch . fnmatch ( name , pattern ) ] if matches : p = [ params . pop ( i ) [ 1 ] for ...
def Astat ( delta , k , G , n ) : """delta : contig size k : reads mapped in contig G : total genome size n : total reads mapped to genome"""
return n * delta * 1. / G - k * ln2
def _send_invitation ( request , project ) : """The logged in project leader OR administrator wants to invite somebody ."""
form = forms . InviteUserApplicationForm ( request . POST or None ) if request . method == 'POST' : if form . is_valid ( ) : email = form . cleaned_data [ 'email' ] applicant , existing_person = get_applicant_from_email ( email ) # If applicant is None then there were multiple persons found ...
def passthrough_repl ( self , inputstring , ** kwargs ) : """Add back passthroughs ."""
out = [ ] index = None for c in append_it ( inputstring , None ) : try : if index is not None : if c is not None and c in nums : index += c elif c == unwrapper and index : ref = self . get_ref ( "passthrough" , index ) out . append ( re...
def subsample_indexes ( data , n_samples = 1000 , size = 0.5 ) : """Given data points data , where axis 0 is considered to delineate points , return a list of arrays where each array is indexes a subsample of the data of size ` ` size ` ` . If size is > = 1 , then it will be taken to be an absolute size . If ...
if size == - 1 : size = len ( data ) elif ( size < 1 ) and ( size > 0 ) : size = int ( round ( size * len ( data ) ) ) elif size > 1 : pass else : raise ValueError ( "size cannot be {0}" . format ( size ) ) base = np . tile ( np . arange ( len ( data ) ) , ( n_samples , 1 ) ) for sample in base : np...
def authenticate ( realm , authid , details ) : """application _ name : name of your application version : version of your application required _ components dictionary of components required for you application and their version required " component " : " 1.1 " , " component2 " : " 0.1 " , when all the ...
global _start global _waiting import json ticket = json . loads ( details [ 'ticket' ] ) if 'application_name' not in ticket and 'version' not in ticket : raise ApplicationError ( 'could not start the authentication of an app,\ field application_name or version is missing' ) application_name = ticket [...
def get_gradebook_column_lookup_session_for_gradebook ( self , gradebook_id , proxy ) : """Gets the ` ` OsidSession ` ` associated with the gradebook column lookup service for the given gradebook . arg : gradebook _ id ( osid . id . Id ) : the ` ` Id ` ` of the gradebook arg : proxy ( osid . proxy . Proxy ) : a...
if not self . supports_gradebook_column_lookup ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . GradebookColumnLookupSession ( gradebook_id , proxy , self . _runtime )
def traverse_dict ( dicc , keys , default_value = None ) : """Recorre un diccionario siguiendo una lista de claves , y devuelve default _ value en caso de que alguna de ellas no exista . Args : dicc ( dict ) : Diccionario a ser recorrido . keys ( list ) : Lista de claves a ser recorrida . Puede contener i...
for key in keys : if isinstance ( dicc , dict ) and key in dicc : dicc = dicc [ key ] elif ( isinstance ( dicc , list ) and isinstance ( key , int ) and key < len ( dicc ) ) : dicc = dicc [ key ] else : return default_value return dicc
def left_axis_label ( self , label , position = None , rotation = 60 , offset = 0.08 , ** kwargs ) : """Sets the label on the left axis . Parameters label : String The axis label position : 3 - Tuple of floats , None The position of the text label rotation : float , 60 The angle of rotation of the lab...
if not position : position = ( - offset , 3. / 5 , 2. / 5 ) self . _labels [ "left" ] = ( label , position , rotation , kwargs )
def main ( net , df = None ) : '''Run in load _ data module ( which runs when file is loaded or dataframe is loaded ) , check for duplicate row / col names , and add index to names if necesary'''
if df is None : df = net . export_df ( ) # rows rows = df . index . tolist ( ) if type ( rows [ 0 ] ) is str : if len ( rows ) != len ( list ( set ( rows ) ) ) : new_rows = add_index_list ( rows ) df . index = new_rows elif type ( rows [ 0 ] ) is tuple : row_names = [ ] for inst_row in r...
def update ( self , session , title = None , bulletin = None , desc = None ) : '''taobao . shop . remainshowcase . get 获取卖家店铺剩余橱窗数量 目前只支持标题 、 公告和描述的更新'''
request = TOPRequest ( 'taobao.shop.remainshowcase.get' ) if title != None : request [ 'title' ] = title if bulletin != None : request [ 'bulletin' ] = bulletin if desc != None : request [ 'desc' ] = desc self . create ( self . execute ( request , session ) [ 'shop' ] ) return self
def copy ( chain : MiningChain ) -> MiningChain : """Make a copy of the chain at the given state . Actions performed on the resulting chain will not affect the original chain ."""
if not isinstance ( chain , MiningChain ) : raise ValidationError ( "`at_block_number` may only be used with 'MiningChain" ) base_db = chain . chaindb . db if not isinstance ( base_db , AtomicDB ) : raise ValidationError ( "Unsupported database type: {0}" . format ( type ( base_db ) ) ) if isinstance ( base_db ...
def add_multiifo_output_list_opt ( self , opt , outputs ) : """Add an option that determines a list of outputs from multiple detectors . Files will be supplied as - - opt ifo1 : input1 ifo2 : input2"""
# NOTE : Here we have to use the raw arguments functionality as the # file and ifo are not space separated . self . add_raw_arg ( opt ) self . add_raw_arg ( ' ' ) for outfile in outputs : self . add_raw_arg ( outfile . ifo ) self . add_raw_arg ( ':' ) self . add_raw_arg ( outfile . name ) self . add_raw...
def intr_read ( self , dev_handle , ep , intf , size , timeout ) : r"""Perform an interrut read . dev _ handle is the value returned by the open _ device ( ) method . The ep parameter is the bEndpointAddress field whose endpoint the data will be received from . intf is the bInterfaceNumber field of the inte...
_not_implemented ( self . intr_read )
def check_is_admin ( context ) : """Check if roles contains ' admin ' role according to policy settings ."""
init ( ) credentials = context . to_policy_values ( ) target = credentials return _ENFORCER . authorize ( 'admin_required' , target , credentials )
def compose ( self , data ) : """condense reaction container to CGR . see init for details about cgr _ type : param data : ReactionContainer : return : CGRContainer"""
g = self . __separate ( data ) if self . __cgr_type in ( 1 , 2 , 3 , 4 , 5 , 6 ) else self . __condense ( data ) g . meta . update ( data . meta ) return g
def set_requests_per_second ( self , req_per_second ) : '''Adjusts the request / second at run - time'''
self . req_per_second = req_per_second self . req_duration = 1 / self . req_per_second
def addKwdArgsToSig ( sigStr , kwArgsDict ) : """Alter the passed function signature string to add the given kewords"""
retval = sigStr if len ( kwArgsDict ) > 0 : retval = retval . strip ( ' ,)' ) # open up the r . h . s . for more args for k in kwArgsDict : if retval [ - 1 ] != '(' : retval += ", " retval += str ( k ) + "=" + str ( kwArgsDict [ k ] ) retval += ')' retval = retval return retv...
def encode_byte_values ( map_ : Dict ) : """Converts values that are of type ` bytes ` to strings ."""
for k , v in map_ . items ( ) : if isinstance ( v , bytes ) : map_ [ k ] = encode_hex ( v )
def check_time_coordinate ( self , ds ) : '''Check variables defining time are valid under CF CF § 4.4 Variables representing time must always explicitly include the units attribute ; there is no default value . The units attribute takes a string value formatted as per the recommendations in the Udunits pac...
ret_val = [ ] for name in cfutil . get_time_variables ( ds ) : variable = ds . variables [ name ] # Has units has_units = hasattr ( variable , 'units' ) if not has_units : result = Result ( BaseCheck . HIGH , False , self . section_titles [ '4.4' ] , [ '%s does not have units' % name ] ) ...
def corner_depots ( self ) -> Set [ Point2 ] : """Finds the 2 depot positions on the outside"""
if len ( self . upper2_for_ramp_wall ) == 2 : points = self . upper2_for_ramp_wall p1 = points . pop ( ) . offset ( ( self . x_offset , self . y_offset ) ) # still an error with pixelmap ? p2 = points . pop ( ) . offset ( ( self . x_offset , self . y_offset ) ) center = p1 . towards ( p2 , p1 . dist...
def cleanup_files_on_ev3 ( ) : """cleanup files in homedir on EV3."""
list = get_base_ev3dev_cmd ( ) + [ 'cleanup' ] env = os . environ . copy ( ) env [ "PYTHONUSERBASE" ] = THONNY_USER_BASE proc = subprocess . Popen ( list , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True , env = env ) dlg = MySubprocessDialog ( get_workbench ( ) , proc , "Delete fi...
def patched_fork ( self ) : """Fork a child process ."""
pid = self . original_os_fork ( ) if not pid : _LOG ( 'Fork detected. Reinstalling Manhole.' ) self . reinstall ( ) return pid
def remove_element_attributes ( elem_to_parse , * args ) : """Removes the specified keys from the element ' s attributes , and returns a dict containing the attributes that have been removed ."""
element = get_element ( elem_to_parse ) if element is None : return element if len ( args ) : attribs = element . attrib return { key : attribs . pop ( key ) for key in args if key in attribs } return { }
def to_list_str ( value , encode = None ) : """recursively convert list content into string : arg list value : The list that need to be converted . : arg function encode : Function used to encode object ."""
result = [ ] for index , v in enumerate ( value ) : if isinstance ( v , dict ) : result . append ( to_dict_str ( v , encode ) ) continue if isinstance ( v , list ) : result . append ( to_list_str ( v , encode ) ) continue if encode : result . append ( encode ( v ) ) ...
def save_file ( fullpath , entry ) : """Save a message file out , without mangling the headers"""
with tempfile . NamedTemporaryFile ( 'w' , delete = False ) as file : tmpfile = file . name # we can ' t just use file . write ( str ( entry ) ) because otherwise the # headers " helpfully " do MIME encoding normalization . # str ( val ) is necessary to get around email . header ' s encoding # shena...
def web_task ( f ) : """Checks if the task is called through the web interface . Task return value should be in format { ' data ' : . . . } ."""
@ wraps ( f ) def web_task_decorator ( * args , ** kwargs ) : jc = JobContext . get_current_context ( ) if not isinstance ( jc , WebJobContext ) : raise Exception ( "The WebTask is not called through the web interface." ) data = f ( * args , ** kwargs ) jc . add_responder ( WebTaskResponder ( da...
def alerts ( self ) : """Gets the Alerts API client . Returns : Alerts :"""
if not self . __alerts : self . __alerts = Alerts ( self . __connection ) return self . __alerts
def yield_all_dir_path ( dir_abspath ) : """* * 中文文档 * * 遍历dir _ abspath目录下的所有子目录 , 返回绝对路径 。"""
if os . path . isdir ( dir_abspath ) : for current_folder , folderlist , _ in os . walk ( dir_abspath ) : for folder in folderlist : yield os . path . join ( current_folder , folder ) else : raise Exception ( "'%s' may not exists or is not a directory!" % dir_abspath )
def url ( self , _url , ** kwargs ) : """This will return the url for a Request instead of actually performing the request , and then store it in self [ ' label ' ] . * Note the API call isn ' t actually made but it is setup to call save or open _ as _ file : param _ url : str of the sub url of the api call...
api_call = self . _create_api_call ( 'get' , _url , kwargs ) data = self . _clean_arguments ( kwargs . pop ( 'data' , None ) ) params = self . _clean_arguments ( kwargs ) api_call . set_request ( method = 'GET' , data = data , params = params , sub_url = _url ) api_call . _stage = 'URL' return api_call . url
def get_public_key_info ( self ) : """Analyze the public key information we have in our scriptSig . Returns { ' status ' : true , ' type ' : ' singlesig ' | ' multisig ' , ' public _ keys ' : [ . . . ] , ' num _ sigs ' : . . . } on success Returns { ' error ' : . . . } on error"""
script_parts = virtualchain . btc_script_deserialize ( base64 . b64decode ( self . sig ) ) if len ( script_parts ) < 2 : return { 'error' : 'Signature script does not appear to encode any public keys' } if len ( script_parts ) == 2 : # possibly p2pkh pubkey = script_parts [ 1 ] . encode ( 'hex' ) try : ...
def reset ( self ) : """" Reset the state as new"""
self . last_usage = None self . last_collect = None self . last_metrics = None self . snapshot_countdown = 0 self . run ( )
def mcluster ( args ) : """% prog mcluster * . consensus Cluster across samples using consensus sequences ."""
p = OptionParser ( mcluster . __doc__ ) add_consensus_options ( p ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) consensusfiles = args minlength = opts . minlength cpus = opts . cpus pf = opts . prefix pctid = find_pctid ( consensusfiles ) pf += ...
def indexables ( self ) : """create the indexables from the table description"""
if self . _indexables is None : d = self . description # the index columns is just a simple index self . _indexables = [ GenericIndexCol ( name = 'index' , axis = 0 ) ] for i , n in enumerate ( d . _v_names ) : dc = GenericDataIndexableCol ( name = n , pos = i , values = [ n ] , version = self ....
def _blend ( self , new , old , ratio ) : """Blend the new colour with the old according to the ratio . : param new : The new colour ( or None if not required ) . : param old : The old colour . : param ratio : The ratio to blend new and old : returns : the new colour index to use for the required blend ."""
# Don ' t bother blending if none is required . if new is None : return old # Check colour blend cache for a quick answer . key = ( min ( new , old ) , max ( new , old ) ) if key in self . _blends : return self . _blends [ key ] # No quick answer - do it the long way . . . First lookup the RGB values # for both...
def _add ( self , * rules ) : # type : ( Iterable [ Type [ Rule ] ] ) - > Generator [ Type [ Rule ] ] """Add rules into the set . Each rule is validated and split if needed . The method add the rules into dictionary , so the rule can be deleted with terminals or nonterminals . : param rules : Rules to insert . ...
for rule in rules : if rule in self : continue self . _validate_rule ( rule ) for rule in rules : for r in self . _split_rules ( rule ) : for side in r . rule : for s in side : self . _assign_map [ s ] . add ( r ) super ( ) . add ( r ) yield r
def size ( self , pairs_only = False ) : '''Calculate the size of the lineage . Inputs ( optional ) pairs _ only : count only paired sequences Returns Lineage size ( int )'''
if pairs_only : return len ( self . just_pairs ) else : return len ( self . heavies )
def create ( cls , class_name : str , monoid_type = Union [ Monoid , str ] ) : """Create Writer subclass using specified monoid type . lets us create a Writer that uses a different monoid than str for the log ."""
def unit ( cls , value ) : if hasattr ( monoid_type , "empty" ) : log = monoid_type . empty ( ) else : log = monoid_type ( ) return cls ( value , log ) return type ( class_name , ( Writer , ) , dict ( unit = classmethod ( unit ) ) )
def clear_content ( self ) : """Remove all content child elements from this < w : body > element . Leave the < w : sectPr > element if it is present ."""
if self . sectPr is not None : content_elms = self [ : - 1 ] else : content_elms = self [ : ] for content_elm in content_elms : self . remove ( content_elm )
def step_i_run_command ( context , command ) : """Run a command as subprocess , collect its output and returncode ."""
command_util . ensure_workdir_exists ( context ) context . command_result = command_shell . run ( command , cwd = context . workdir ) command_util . workdir_save_coverage_files ( context . workdir ) if False and DEBUG : print ( u"run_command: {0}" . format ( command ) ) print ( u"run_command.output {0}" . forma...
def maxLength ( self ) : """Maximum length of object ."""
value = self . _schema . get ( "maxLength" , None ) if value is None : return if not isinstance ( value , int ) : raise SchemaError ( "maxLength value {0!r} is not an integer" . format ( value ) ) return value
def _apply_search_backrefs ( pattern , flags = 0 ) : """Apply the search backrefs to the search pattern ."""
if isinstance ( pattern , ( str , bytes ) ) : re_verbose = bool ( VERBOSE & flags ) re_unicode = None if bool ( ( ASCII | LOCALE ) & flags ) : re_unicode = False elif bool ( UNICODE & flags ) : re_unicode = True if not ( flags & DEBUG ) : pattern = _cached_search_compile ( pa...
def simxDisplayDialog ( clientID , titleText , mainText , dialogType , initialText , titleColors , dialogColors , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
if titleColors != None : c_titleColors = ( ct . c_float * 6 ) ( * titleColors ) else : c_titleColors = None if dialogColors != None : c_dialogColors = ( ct . c_float * 6 ) ( * dialogColors ) else : c_dialogColors = None c_dialogHandle = ct . c_int ( ) c_uiHandle = ct . c_int ( ) if sys . version_info [ ...
def path ( self , which = None ) : """Extend ` ` nailgun . entity _ mixins . Entity . path ` ` . The format of the returned path depends on the value of ` ` which ` ` : delete _ manifest / katello / api / v2 / organizations / : organization _ id / subscriptions / delete _ manifest manifest _ history / kat...
if which in ( 'delete_manifest' , 'manifest_history' , 'refresh_manifest' , 'upload' ) : _check_for_value ( 'organization' , self . get_values ( ) ) # pylint : disable = no - member return self . organization . path ( 'subscriptions/{0}' . format ( which ) ) return super ( Subscription , self ) . path ( whi...
def new_message ( self , resource = None ) : """Creates a new message to be sent or stored : param str resource : Custom resource to be used in this message ( Defaults to parent main _ resource ) : return : New empty message : rtype : Message"""
return Message ( parent = self , main_resource = resource , is_draft = True )
def grids ( fig = None , value = 'solid' ) : """Sets the value of the grid _ lines for the axis to the passed value . The default value is ` solid ` . Parameters fig : Figure or None ( default : None ) The figure for which the axes should be edited . If the value is None , the current figure is used . v...
if fig is None : fig = current_figure ( ) for a in fig . axes : a . grid_lines = value
def append_account_merge_op ( self , destination , source = None ) : """Append a : class : ` AccountMerge < stellar _ base . operation . AccountMerge > ` operation to the list of operations . : param str destination : The ID of the offer . 0 for new offer . Set to existing offer ID to update or delete . :...
op = operation . AccountMerge ( destination , source ) return self . append_op ( op )
def check_power ( self ) : """Returns the power state of the smart plug ."""
packet = bytearray ( 16 ) packet [ 0 ] = 1 response = self . send_packet ( 0x6a , packet ) err = response [ 0x22 ] | ( response [ 0x23 ] << 8 ) if err == 0 : payload = self . decrypt ( bytes ( response [ 0x38 : ] ) ) if type ( payload [ 0x4 ] ) == int : if payload [ 0x4 ] == 1 or payload [ 0x4 ] == 3 or...
def connectionLost ( self , reason = None ) : """Callback handler from twisted when a connection was lost ."""
try : self . connected = False self . stop_block_loop ( ) self . stop_peerinfo_loop ( ) self . stop_header_loop ( ) self . ReleaseBlockRequests ( ) self . leader . RemoveConnectedPeer ( self ) time_expired = self . time_expired ( HEARTBEAT_BLOCKS ) # some NEO - cli versions have a 30s ti...
def _scheduleRestart ( self , when : Union [ datetime , str ] , failTimeout ) -> None : """Schedules node restart to a newer version : param version : version to restart to : param when : restart time"""
logger . info ( "{}'s restarter processing restart" . format ( self ) ) if isinstance ( when , str ) : when = dateutil . parser . parse ( when ) now = datetime . utcnow ( ) . replace ( tzinfo = dateutil . tz . tzutc ( ) ) logger . info ( "Restart of node '{}' has been scheduled on {}" . format ( self . nodeName , w...
def fuzzy_match ( image , template , normed_tolerance = None , raw_tolerance = None , method = 'correlation' ) : """Determines , using one of two methods , whether a match ( es ) is present and returns the positions of the bottom right corners of the matches . Fuzzy matches returns regions , so the center of ea...
if method == 'correlation' : if not raw_tolerance : raw_tolerance = 0.95 if not normed_tolerance : normed_tolerance = 0.95 results = np . array ( match_via_correlation ( image , template , raw_tolerance = raw_tolerance , normed_tolerance = normed_tolerance ) ) elif method == 'correlation coe...
def load_merge_candidate ( self , filename = None , config = None ) : """Open the candidate config and replace ."""
self . config_replace = False self . _load_candidate ( filename , config , False )
def _match_mask ( mask , ctype ) : """Determine if a content type mask matches a given content type . : param mask : The content type mask , taken from the Accept header . : param ctype : The content type to match to the mask ."""
# Handle the simple cases first if '*' not in mask : return ctype == mask elif mask == '*/*' : return True elif not mask . endswith ( '/*' ) : return False mask_major = mask [ : - 2 ] ctype_major = ctype . split ( '/' , 1 ) [ 0 ] return ctype_major == mask_major
def _hide_parameters ( self , file_name ) : """hide the parameters that had been hidden Args : file _ name : config file that has the information about which parameters are hidden"""
try : in_data = load_b26_file ( file_name ) except : in_data = { } def set_item_visible ( item , is_visible ) : if isinstance ( is_visible , dict ) : for child_id in range ( item . childCount ( ) ) : child = item . child ( child_id ) if child . name in is_visible : ...
def getShape ( self , includeJunctions = False ) : """Returns the shape of the lane in 2d . This function returns the shape of the lane , as defined in the net . xml file . The returned shape is a list containing numerical 2 - tuples representing the x , y coordinates of the shape points . For includeJuncti...
if includeJunctions and not self . _edge . isSpecial ( ) : if self . _shapeWithJunctions is None : self . _shapeWithJunctions = addJunctionPos ( self . _shape , self . _edge . getFromNode ( ) . getCoord ( ) , self . _edge . getToNode ( ) . getCoord ( ) ) return self . _shapeWithJunctions return self . _...
def plot ( self , xmin , xmax , idx_input = 0 , idx_output = 0 , points = 100 , ** kwargs ) -> None : """Call method | anntools . ANN . plot | of all | anntools . ANN | objects handled by the actual | anntools . SeasonalANN | object ."""
for toy , ann_ in self : ann_ . plot ( xmin , xmax , idx_input = idx_input , idx_output = idx_output , points = points , label = str ( toy ) , ** kwargs ) pyplot . legend ( )
def create_paired_list ( value ) : """Create a list of paired items from a string . : param value : the format must be 003,003,004,004 ( commas with no space ) : type value : String : returns : List : example : > > > create _ paired _ list ( ' 003,003,004,004 ' ) [ [ ' 003 ' , ' 003 ' ] , [ ' 004 ...
if isinstance ( value , list ) : value = "," . join ( value ) array = re . split ( '\D+' , value ) # Make sure the elements in the list are even and pairable if len ( array ) % 2 == 0 : new_array = [ list ( array [ i : i + 2 ] ) for i in range ( 0 , len ( array ) , 2 ) ] return new_array else : raise Va...
def simple_transpile_modname_source_target ( self , spec , modname , source , target ) : """The original simple transpile method called by compile _ transpile on each target ."""
opener = self . opener bd_target = self . _generate_transpile_target ( spec , target ) logger . info ( 'Transpiling %s to %s' , source , bd_target ) with opener ( source , 'r' ) as reader , opener ( bd_target , 'w' ) as _writer : writer = SourceWriter ( _writer ) self . transpiler ( spec , reader , writer ) ...
def received ( self ) : """A : class : ` ~ charms . reactive . endpoints . JSONUnitDataView ` of the data received from this remote unit over the relation , with values being automatically decoded as JSON ."""
if self . _data is None : self . _data = JSONUnitDataView ( hookenv . relation_get ( unit = self . unit_name , rid = self . relation . relation_id ) ) return self . _data
def draw ( self , pen , filterRedundantPoints = False ) : """draw self using pen"""
from fontTools . pens . pointPen import PointToSegmentPen pointPen = PointToSegmentPen ( pen ) self . drawPoints ( pointPen , filterRedundantPoints = filterRedundantPoints )
def update_placeholder_formats ( self , format_string , placeholder_formats ) : """Update a format string adding formats if they are not already present ."""
# Tokenize the format string and process them output = [ ] for token in self . tokens ( format_string ) : if ( token . group ( "placeholder" ) and ( not token . group ( "format" ) ) and token . group ( "key" ) in placeholder_formats ) : output . append ( "{%s%s}" % ( token . group ( "key" ) , placeholder_fo...
def QA_fetch_account ( message = { } , db = DATABASE ) : """get the account Arguments : query _ mes { [ type ] } - - [ description ] Keyword Arguments : collection { [ type ] } - - [ description ] ( default : { DATABASE } ) Returns : [ type ] - - [ description ]"""
collection = DATABASE . account return [ res for res in collection . find ( message , { "_id" : 0 } ) ]
def stop ( self , wait = True ) : '''Stop the Bokeh Server . This stops and removes all Bokeh Server ` ` IOLoop ` ` callbacks , as well as stops the ` ` HTTPServer ` ` that this instance was configured with . Args : fast ( bool ) : Whether to wait for orderly cleanup ( default : True ) Returns : None'...
assert not self . _stopped , "Already stopped" self . _stopped = True self . _tornado . stop ( wait ) self . _http . stop ( )
def checkUserManage ( worksheet , request , redirect = True ) : """Checks if the current user has granted access to the worksheet and if has also privileges for managing it . If the user has no granted access and redirect ' s value is True , redirects to / manage _ results view . Otherwise , does nothing"""
allowed = worksheet . checkUserManage ( ) if allowed == False and redirect == True : # Redirect to / manage _ results view destination_url = worksheet . absolute_url ( ) + "/manage_results" request . response . redirect ( destination_url )
def get_slowest_files ( cls , num = 10 ) : """Returns the slowest num files . : param num : The maximum number of results to be returned : type num : int"""
cur = cls . get_cursor ( ) q = ( "SELECT file, SUM(elapsed) as sum_elapsed FROM {} GROUP BY file" " ORDER BY sum_elapsed DESC LIMIT {}" ) cur . execute ( q . format ( cls . meta [ 'table' ] , num ) ) result = cur . fetchall ( ) # Don ' t return the weird invalid row if no tests were run if not all ( [ cls . is_valid_ro...
def roundrect ( surface , rect , color , rounding = 5 , unit = PIXEL ) : """Draw an antialiased round rectangle on the surface . surface : destination rect : rectangle color : rgb or rgba radius : 0 < = radius < = 1 : source : http : / / pygame . org / project - AAfilledRoundedRect - 2349 - . html"""
if unit == PERCENT : rounding = int ( min ( rect . size ) / 2 * rounding / 100 ) rect = pygame . Rect ( rect ) color = pygame . Color ( * color ) alpha = color . a color . a = 0 pos = rect . topleft rect . topleft = 0 , 0 rectangle = pygame . Surface ( rect . size , SRCALPHA ) circle = pygame . Surface ( [ min ( re...
def return_item_count_on_page ( self , page = 1 , total_items = 1 ) : """Return the number of items on page . Args : * page = The Page to test for * total _ items = the total item count Returns : * Integer - Which represents the calculated number of items on page ."""
up_to_page = ( ( page - 1 ) * self . page_items ) # Number of items up to the page in question if total_items > up_to_page : # Remove all the items up to the page in question count = total_items - up_to_page if count >= self . page_items : # The remaining items are greater than the items per page # so the answer is...
def vhel_to_vgsr ( coordinate , vhel , vsun ) : """Convert a velocity from a heliocentric radial velocity to the Galactic standard of rest ( GSR ) . Parameters coordinate : : class : ` ~ astropy . coordinates . SkyCoord ` An Astropy SkyCoord object or anything object that can be passed to the SkyCoord ini...
if vsun is None : vsun = coord . Galactocentric . galcen_v_sun . to_cartesian ( ) . xyz return vhel + _get_vproj ( coordinate , vsun )
def error ( self , flag_message = "Error" , padding = None , force = False ) : """Log Level : : attr : ERROR @ flag _ message : # str flags the message with the given text using : func : flag @ padding : # str ' top ' , ' bottom ' or ' all ' , adds a new line to the specified area with : func : padd @ col...
if self . should_log ( self . ERROR ) or force : self . _print_message ( flag_message = flag_message , color = colors . error_color , padding = padding )
def save ( df , path ) : """Args : df ( DataFlow ) : the DataFlow to serialize . path ( str ) : output tfrecord file ."""
if os . environ . get ( 'TENSORPACK_COMPATIBLE_SERIALIZE' , 'msgpack' ) == 'msgpack' : def _dumps ( dp ) : return dumps ( dp ) else : def _dumps ( dp ) : return dumps ( dp ) . to_pybytes ( ) size = _reset_df_and_get_size ( df ) with tf . python_io . TFRecordWriter ( path ) as writer , get_tqdm (...
def select_each ( conn , query : str , parameter_groups , name = None ) : """Run select query for each parameter set in single transaction ."""
with conn : with conn . cursor ( name = name ) as cursor : for parameters in parameter_groups : cursor . execute ( query , parameters ) yield cursor . fetchone ( )
def _tokenize ( self , source , name , filename = None , state = None ) : """Called by the parser to do the preprocessing and filtering for all the extensions . Returns a : class : ` ~ jinja2 . lexer . TokenStream ` ."""
source = self . preprocess ( source , name , filename ) stream = self . lexer . tokenize ( source , name , filename , state ) for ext in self . iter_extensions ( ) : stream = ext . filter_stream ( stream ) if not isinstance ( stream , TokenStream ) : stream = TokenStream ( stream , name , filename ) ret...
def attributes_js ( cls , attributes ) : """Generates JS code to look up attributes on JS objects from an attributes specification dictionary . If the specification references a plotting particular plotting handle it will also generate JS code to get the ID of the object . Simple example ( when referencing ...
assign_template = '{assign}{{id: {obj_name}["id"], value: {obj_name}{attr_getters}}};\n' conditional_template = 'if (({obj_name} != undefined)) {{ {assign} }}' code = '' for key , attr_path in sorted ( attributes . items ( ) ) : data_assign = 'data["{key}"] = ' . format ( key = key ) attrs = attr_path . split (...
def astra_data ( astra_geom , datatype , data = None , ndim = 2 , allow_copy = False ) : """Create an ASTRA data object . Parameters astra _ geom : dict ASTRA geometry object for the data creator , must correspond to the given ` ` datatype ` ` . datatype : { ' volume ' , ' projection ' } Type of the dat...
if data is not None : if isinstance ( data , ( DiscreteLpElement , np . ndarray ) ) : ndim = data . ndim else : raise TypeError ( '`data` {!r} is neither DiscreteLpElement ' 'instance nor a `numpy.ndarray`' . format ( data ) ) else : ndim = int ( ndim ) if datatype == 'volume' : astra_dt...
def prepare_components ( self ) : """Prepare components that are going to be generated based on user options . : return : Updated list of components . : rtype : dict"""
# Register the components based on user option # First , tabular report generated_components = deepcopy ( all_default_report_components ) # Rohmat : I need to define the definitions here , I can ' t get # the definition using definition helper method . component_definitions = { impact_report_pdf_component [ 'key' ] : i...
def convert_simpleFaultSource ( self , node ) : """Convert the given node into a simple fault object . : param node : a node with tag areaGeometry : returns : a : class : ` openquake . hazardlib . source . SimpleFaultSource ` instance"""
geom = node . simpleFaultGeometry msr = valid . SCALEREL [ ~ node . magScaleRel ] ( ) fault_trace = self . geo_line ( geom ) mfd = self . convert_mfdist ( node ) with context ( self . fname , node ) : try : hypo_list = valid . hypo_list ( node . hypoList ) except AttributeError : hypo_list = ( )...
def axes ( self ) : """Dimensions in which an actual resizing is performed ."""
return tuple ( i for i in range ( self . domain . ndim ) if self . domain . shape [ i ] != self . range . shape [ i ] )
def cutarelease ( project_name , version_files , dry_run = False ) : """Cut a release . @ param project _ name { str } @ param version _ files { list } List of paths to files holding the version info for this project . If none are given it attempts to guess the version file : package . json or VERSION . t...
dry_run_str = dry_run and " (dry-run)" or "" if not version_files : log . info ( "guessing version file" ) candidates = [ "package.json" , "VERSION.txt" , "VERSION" , "%s.py" % project_name , "lib/%s.py" % project_name , "%s.js" % project_name , "lib/%s.js" % project_name , ] for candidate in candidates : ...
def from_raw_message ( cls , rawmessage ) : """Create a user data instance from a raw byte stream ."""
empty = cls . create_empty ( 0x00 ) userdata_dict = cls . normalize ( empty , rawmessage ) return Userdata ( userdata_dict )
def reset ( self ) : """Reset the state of the instance to when it was constructed"""
self . operations = [ ] self . _last_overflow = 'WRAP' self . overflow ( self . _default_overflow or self . _last_overflow )
def get_mean_and_std ( dataset ) : """Compute the mean and std value of dataset ."""
dataloader = torch . utils . data . DataLoader ( dataset , batch_size = 1 , shuffle = True , num_workers = 2 ) mean = torch . zeros ( 3 ) std = torch . zeros ( 3 ) print ( "==> Computing mean and std.." ) for inputs , _ in dataloader : for i in range ( 3 ) : mean [ i ] += inputs [ : , i , : , : ] . mean ( )...
def hum44 ( msg ) : """humidity Args : msg ( String ) : 28 bytes hexadecimal message string Returns : float : percentage of humidity , [ 0 - 100 ] %"""
d = hex2bin ( data ( msg ) ) if d [ 49 ] == '0' : return None hm = bin2int ( d [ 50 : 56 ] ) * 100.0 / 64 return round ( hm , 1 )
def setup_resume ( self ) : """Setup debugger to " resume " execution"""
self . frame_calling = None self . frame_stop = None self . frame_return = None self . frame_suspend = False self . pending_stop = False if not IKBreakpoint . any_active_breakpoint : self . disable_tracing ( ) return