signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def min_heap_sort ( arr , simulation = False ) : """Heap Sort that uses a min heap to sort an array in ascending order Complexity : O ( n log ( n ) )"""
iteration = 0 if simulation : print ( "iteration" , iteration , ":" , * arr ) for i in range ( 0 , len ( arr ) - 1 ) : iteration = min_heapify ( arr , i , simulation , iteration ) return arr
def calculate_jacobsthal ( num ) : """A function to calculate the nth jacobsthal number using dynamic programming . The function calculates previously unknown jacobsthal numbers and stores them for future use . Examples : > > > calculate _ jacobsthal ( 5) 11 > > > calculate _ jacobsthal ( 2) > > > calcu...
jacobsthal = [ 0 ] * ( num + 1 ) # Create a list to hold the jacobsthal numbers jacobsthal [ 0 ] = 0 jacobsthal [ 1 ] = 1 for i in range ( 2 , num + 1 ) : jacobsthal [ i ] = jacobsthal [ i - 1 ] + 2 * jacobsthal [ i - 2 ] return jacobsthal [ num ]
def Serialize ( self , writer ) : """Serialize full object . Args : writer ( neo . IO . BinaryWriter ) :"""
super ( ContractState , self ) . Serialize ( writer ) self . Code . Serialize ( writer ) writer . WriteUInt8 ( self . ContractProperties ) writer . WriteVarString ( self . Name ) writer . WriteVarString ( self . CodeVersion ) writer . WriteVarString ( self . Author ) writer . WriteVarString ( self . Email ) writer . Wr...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'fonts' ) and self . fonts is not None : _dict [ 'fonts' ] = [ x . _to_dict ( ) for x in self . fonts ] return _dict
async def _response_handler ( self ) : """监听响应数据的协程函数 . ` connect ` 被调用后会被创建为一个协程并放入事件循环 ."""
if self . debug is True : if self . debug is True : print ( "listenning response!" ) while True : try : res = await self . reader . readuntil ( self . SEPARATOR ) except : raise else : response = self . decoder ( res ) self . _status_code_check ( response )
def agents ( self ) : """| Description : IDs of agents involved in the chat"""
if self . api and self . agent_ids : return self . api . _get_agents ( self . agent_ids )
def std_input ( prompt = "" , style = None ) : """Very simple Python2/3 - compatible input method . : param prompt : prompt message : param style : dictionary of ansi _ wrap keyword - arguments"""
p = ansi_wrap ( prompt , ** ( style or { } ) ) try : return raw_input ( p ) . strip ( ) except NameError : return input ( p ) . strip ( )
def update ( self ) : '''Check and update the object with conditional request : rtype : Boolean value indicating whether the object is changed'''
conditionalRequestHeader = dict ( ) if self . etag is not None : conditionalRequestHeader [ Consts . REQ_IF_NONE_MATCH ] = self . etag if self . last_modified is not None : conditionalRequestHeader [ Consts . REQ_IF_MODIFIED_SINCE ] = self . last_modified status , responseHeaders , output = self . _requester . ...
def get ( feature , obj , ** kwargs ) : '''Obtain a feature from a set of morphology objects Parameters : feature ( string ) : feature to extract obj : a neuron , population or neurite tree * * kwargs : parameters to forward to underlying worker functions Returns : features as a 1D or 2D numpy array .''...
feature = ( NEURITEFEATURES [ feature ] if feature in NEURITEFEATURES else NEURONFEATURES [ feature ] ) return _np . array ( list ( feature ( obj , ** kwargs ) ) )
def closed ( self , code , reason = None ) : """Handler called when the WebSocket is closed . Status code 1000 denotes a normal close ; all others are errors ."""
if code != 1000 : self . _error = errors . SignalFlowException ( code , reason ) _logger . info ( 'Lost WebSocket connection with %s (%s: %s).' , self , code , reason ) for c in self . _channels . values ( ) : c . offer ( WebSocketComputationChannel . END_SENTINEL ) self . _channels . clear ( ) with...
def postComponents ( self , name , status , ** kwargs ) : '''Create a new component . : param name : Name of the component : param status : Status of the component ; 1-4 : param description : ( optional ) Description of the component : param link : ( optional ) A hyperlink to the component : param order :...
kwargs [ 'name' ] = name kwargs [ 'status' ] = status return self . __postRequest ( '/components' , kwargs )
def path_shift ( self , shift = 1 ) : '''Shift path fragments from PATH _ INFO to SCRIPT _ NAME and vice versa . : param shift : The number of path fragments to shift . May be negative to change the shift direction . ( default : 1)'''
script_name = self . environ . get ( 'SCRIPT_NAME' , '/' ) self [ 'SCRIPT_NAME' ] , self . path = path_shift ( script_name , self . path , shift ) self [ 'PATH_INFO' ] = self . path
def _indicator ( self , indicator_data ) : """Return previously stored indicator or new indicator . Args : indicator _ data ( dict | obj ) : An Indicator dict or instance of Indicator object . Returns : dict | obj : The new Indicator dict / object or the previously stored dict / object ."""
if isinstance ( indicator_data , dict ) : # get xid from dict xid = indicator_data . get ( 'xid' ) else : # get xid from object xid = indicator_data . xid if self . indicators . get ( xid ) is not None : # return existing indicator from memory indicator_data = self . indicators . get ( xid ) elif self . ind...
def list_dhcp_agent_hosting_networks ( self , network , ** _params ) : """Fetches a list of dhcp agents hosting a network ."""
return self . get ( ( self . network_path + self . DHCP_AGENTS ) % network , params = _params )
def calc_dihedral ( point1 , point2 , point3 , point4 ) : """Calculates a dihedral angle Here , two planes are defined by ( point1 , point2 , point3 ) and ( point2 , point3 , point4 ) . The angle between them is returned . Parameters point1 , point2 , point3 , point4 : array - like , shape = ( 3 , ) , dtype...
points = np . array ( [ point1 , point2 , point3 , point4 ] ) x = np . cross ( points [ 1 ] - points [ 0 ] , points [ 2 ] - points [ 1 ] ) y = np . cross ( points [ 2 ] - points [ 1 ] , points [ 3 ] - points [ 2 ] ) return angle ( x , y )
def get_field_def ( schema , # type : GraphQLSchema parent_type , # type : GraphQLObjectType field_name , # type : str ) : # type : ( . . . ) - > Optional [ GraphQLField ] """This method looks up the field on the given type defintion . It has special casing for the two introspection fields , _ _ schema and _ _ ...
if field_name == "__schema" and schema . get_query_type ( ) == parent_type : return SchemaMetaFieldDef elif field_name == "__type" and schema . get_query_type ( ) == parent_type : return TypeMetaFieldDef elif field_name == "__typename" : return TypeNameMetaFieldDef return parent_type . fields . get ( field_...
def get_address_nonce ( self , address , api_token ) : """Looks up the address nonce of this address Neccesary for the transaction creation"""
broadcast_url = self . base_url + '?module=proxy&action=eth_getTransactionCount' broadcast_url += '&address=%s' % address broadcast_url += '&tag=latest' if api_token : '&apikey=%s' % api_token response = requests . get ( broadcast_url , ) if int ( response . status_code ) == 200 : # the int ( res , 0 ) transforms t...
def air_gap ( self , volume : float = None , height : float = None ) -> 'InstrumentContext' : """Pull air into the pipette current tip at the current location : param volume : The amount in uL to aspirate air into the tube . ( Default will use all remaining volume in tip ) : type volume : float : param heig...
if not self . hw_pipette [ 'has_tip' ] : raise hc . NoTipAttachedError ( 'Pipette has no tip. Aborting air_gap' ) if height is None : height = 5 loc = self . _ctx . location_cache if not loc or not isinstance ( loc . labware , Well ) : raise RuntimeError ( 'No previous Well cached to perform air gap' ) targ...
def _check_cache_minions ( self , expr , delimiter , greedy , search_type , regex_match = False , exact_match = False ) : '''Helper function to search for minions in master caches If ' greedy ' , then return accepted minions matched by the condition or those absent from the cache . If not ' greedy ' return the ...
cache_enabled = self . opts . get ( 'minion_data_cache' , False ) def list_cached_minions ( ) : return self . cache . list ( 'minions' ) if greedy : minions = [ ] for fn_ in salt . utils . data . sorted_ignorecase ( os . listdir ( os . path . join ( self . opts [ 'pki_dir' ] , self . acc ) ) ) : if ...
def _resample ( self , arrays , ji_windows ) : """Resample all arrays with potentially different resolutions to a common resolution ."""
# get a destination array template win_dst = ji_windows [ self . dst_res ] aff_dst = self . _layer_meta [ self . _res_indices [ self . dst_res ] [ 0 ] ] [ "transform" ] arrays_dst = list ( ) for i , array in enumerate ( arrays ) : arr_dst = np . zeros ( ( int ( win_dst . height ) , int ( win_dst . width ) ) ) i...
def vector_distance ( v1 , v2 ) : """Given 2 vectors of multiple dimensions , calculate the euclidean distance measure between them ."""
dist = 0 for dim in v1 : for x in v1 [ dim ] : dd = int ( v1 [ dim ] [ x ] ) - int ( v2 [ dim ] [ x ] ) dist = dist + dd ** 2 return dist
def zinnia_statistics ( template = 'zinnia/tags/statistics.html' ) : """Return statistics on the content of Zinnia ."""
content_type = ContentType . objects . get_for_model ( Entry ) discussions = get_comment_model ( ) . objects . filter ( content_type = content_type ) entries = Entry . published categories = Category . objects tags = tags_published ( ) authors = Author . published replies = discussions . filter ( flags = None , is_publ...
def get_instance ( self , payload ) : """Build an instance of NotificationInstance : param dict payload : Payload response from the API : returns : twilio . rest . notify . v1 . service . notification . NotificationInstance : rtype : twilio . rest . notify . v1 . service . notification . NotificationInstance"...
return NotificationInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , )
def gff ( args ) : """% prog gff * . gff Draw exons for genes based on gff files . Each gff file should contain only one gene , and only the " mRNA " and " CDS " feature will be drawn on the canvas ."""
align_choices = ( "left" , "center" , "right" ) p = OptionParser ( gff . __doc__ ) p . add_option ( "--align" , default = "left" , choices = align_choices , help = "Horizontal alignment [default: %default]" ) p . add_option ( "--noUTR" , default = False , action = "store_true" , help = "Do not plot UTRs [default: %defa...
def validate_collection ( self , name_or_collection , scandata = False , full = False , session = None ) : """Validate a collection . Returns a dict of validation info . Raises CollectionInvalid if validation fails . : Parameters : - ` name _ or _ collection ` : A Collection object or the name of a collec...
name = name_or_collection if isinstance ( name , Collection ) : name = name . name if not isinstance ( name , string_type ) : raise TypeError ( "name_or_collection must be an instance of " "%s or Collection" % ( string_type . __name__ , ) ) result = self . command ( "validate" , _unicode ( name ) , scandata = s...
def Planck_wavenumber ( n , T ) : '''The Planck function ( flux density for blackbody radition ) in wavenumber space n is wavenumber in 1 / cm T is temperature in Kelvin Formula from Raymond Pierrehumbert , " Principles of Planetary Climate " , page 140.'''
# convert to mks units n = n * 100. return c_light * Planck_frequency ( n * c_light , T )
def result ( self ) : """Formats the result ."""
for value in six . itervalues ( self . __result ) : value . sort ( key = _humanSortKey ) return self . __result
def create_assessment ( self , assessment_form ) : """Creates a new ` ` Assessment ` ` . arg : assessment _ form ( osid . assessment . AssessmentForm ) : the form for this ` ` Assessment ` ` return : ( osid . assessment . Assessment ) - the new ` ` Assessment ` ` raise : IllegalState - ` ` assessment _ form...
# Implemented from template for # osid . resource . ResourceAdminSession . create _ resource _ template collection = JSONClientValidated ( 'assessment' , collection = 'Assessment' , runtime = self . _runtime ) if not isinstance ( assessment_form , ABCAssessmentForm ) : raise errors . InvalidArgument ( 'argument typ...
def aggr ( self , group , ** named_attributes ) : """Aggregation of the type U ( ' attr1 ' , ' attr2 ' ) . aggr ( group , computation = " QueryExpression " ) has the primary key ( ' attr1 ' , ' attr2 ' ) and performs aggregation computations for all matching elements of ` group ` . : param group : The query exp...
return ( GroupBy . create ( self , group = group , keep_all_rows = False , attributes = ( ) , named_attributes = named_attributes ) if self . primary_key else Projection . create ( group , attributes = ( ) , named_attributes = named_attributes , include_primary_key = False ) )
def _transform_coefficients ( self , NN , HHw , CCw , ffparm , polycf , any_pwl , npol , nw ) : """Transforms quadratic coefficients for w into coefficients for x ."""
nnw = any_pwl + npol + nw M = csr_matrix ( ( ffparm [ : , 3 ] , ( range ( nnw ) , range ( nnw ) ) ) ) MR = M * ffparm [ : , 2 ] # FIXME : Possibly column 1. HMR = HHw * MR MN = M * NN HH = MN . T * HHw * MN CC = MN . T * ( CCw - HMR ) # Constant term of cost . C0 = 1. / 2. * MR . T * HMR + sum ( polycf [ : , 2 ] ) retu...
def norm ( values , min = None , max = None ) : """Unity - based normalization to scale data into 0-1 range . ( values - min ) / ( max - min ) Args : values : Array of values to be normalized min ( float , optional ) : Lower bound of normalization range max ( float , optional ) : Upper bound of normalizat...
min = np . min ( values ) if min is None else min max = np . max ( values ) if max is None else max return ( values - min ) / ( max - min )
def sell_limit ( self , quantity , price , ** kwargs ) : """Shortcut for ` ` instrument . order ( " SELL " , . . . ) ` ` and accepts all of its ` optional parameters < # qtpylib . instrument . Instrument . order > ` _ : Parameters : quantity : int Order quantity price : float Limit price"""
kwargs [ 'limit_price' ] = price kwargs [ 'order_type' ] = "LIMIT" self . parent . order ( "SELL" , self , quantity = quantity , ** kwargs )
def is_presence_handler ( type_ , from_ , cb ) : """Return true if ` cb ` has been decorated with : func : ` presence _ handler ` for the given ` type _ ` and ` from _ ` ."""
try : handlers = aioxmpp . service . get_magic_attr ( cb ) except AttributeError : return False return aioxmpp . service . HandlerSpec ( ( _apply_presence_handler , ( type_ , from_ ) ) , require_deps = ( SimplePresenceDispatcher , ) ) in handlers
def logout ( self ) : """* * DEPRECATED * * : Deauthorize use of this database ."""
warnings . warn ( "Database.logout() is deprecated" , DeprecationWarning , stacklevel = 2 ) # Sockets will be deauthenticated as they are used . self . client . _purge_credentials ( self . name )
def _init ( self , state , initiate_arg ) : '''Set initial state of the task . Called from initiate . @ param initiate _ arg : either the PartnerClass object ( StartTask ) or an agent _ id ( RestartTask )'''
state . descriptor = None state . hosts = state . agent . query_partners ( 'hosts' ) state . current_index = - 1 self . log ( '%s task initiated, will be trying to start a ' '%r on one of the hosts: %r' , str ( self . __class__ . __name__ ) , initiate_arg , state . hosts ) if len ( state . hosts ) == 0 : # FIXME : Here...
def depend ( * args ) : """Decorator to declare dependencies to other modules . Recommended usage is : : import other _ module @ depend ( other _ module . ModuleClass ) class MyModule ( Module ) : : param \ * args : depended module classes ."""
def decfunc ( cls ) : if not 'depends' in cls . __dict__ : cls . depends = [ ] cls . depends . extend ( list ( args ) ) for a in args : if not hasattr ( a , 'referencedBy' ) : a . referencedBy = [ ] a . referencedBy . append ( cls ) return cls return decfunc
def setup_logger ( logger , stream , filename = None , fmt = None ) : """Set up a logger ( if no handlers exist ) for console output , and file ' tee ' output if desired ."""
if len ( logger . handlers ) < 1 : console = logging . StreamHandler ( stream ) console . setLevel ( logging . DEBUG ) console . setFormatter ( logging . Formatter ( fmt ) ) logger . addHandler ( console ) logger . setLevel ( logging . DEBUG ) logger . propagate = False if filename : ...
def populate ( self , priority , address , rtr , data ) : """: return : None"""
assert isinstance ( data , bytes ) self . needs_firmware_priority ( priority ) self . needs_no_rtr ( rtr ) self . needs_data ( data , 6 ) self . set_attributes ( priority , address , rtr ) self . module_type = data [ 0 ] prefix = bytes ( [ 0 , 0 ] ) ( self . current_serial , ) = struct . unpack ( '>L' , prefix + data [...
def crypto_pwhash_scryptsalsa208sha256_ll ( passwd , salt , n , r , p , dklen = 64 , maxmem = SCRYPT_MAX_MEM ) : """Derive a cryptographic key using the ` ` passwd ` ` and ` ` salt ` ` given as input . The work factor can be tuned by by picking different values for the parameters : param bytes passwd : : ...
ensure ( isinstance ( n , integer_types ) , raising = TypeError ) ensure ( isinstance ( r , integer_types ) , raising = TypeError ) ensure ( isinstance ( p , integer_types ) , raising = TypeError ) ensure ( isinstance ( passwd , bytes ) , raising = TypeError ) ensure ( isinstance ( salt , bytes ) , raising = TypeError ...
def _changes ( cur , dns_proto , dns_servers , ip_proto , ip_addrs , gateway ) : '''Compares the current interface against the desired configuration and returns a dictionary describing the changes that need to be made .'''
changes = { } cur_dns_proto = ( 'static' if 'Statically Configured DNS Servers' in cur else 'dhcp' ) if cur_dns_proto == 'static' : if isinstance ( cur [ 'Statically Configured DNS Servers' ] , list ) : cur_dns_servers = cur [ 'Statically Configured DNS Servers' ] else : cur_dns_servers = [ cur ...
def conditional ( self , condition , name ) : """Defines a ' condition ' when conditional element of ' name ' exists if ` condition ` is true . ` condition ` can contain multiple conditions combined together using Logical Expressions ( & & , | | ) . Example : | Conditional | mycondition = = 1 | foo | | u8 |...
self . _message_stack . append ( ConditionalTemplate ( condition , name , self . _current_container ) )
def source ( self , value ) : """Setter for * * self . _ _ source * * attribute . : param value : Attribute value . : type value : unicode"""
if value is not None : assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "source" , value ) assert os . path . exists ( value ) , "'{0}' attribute: '{1}' file doesn't exists!" . format ( "source" , value ) self . __source = value
def received_message ( self , m ) : """Push upstream messages to downstream ."""
# TODO : No support for binary messages m = str ( m ) logger . debug ( "Incoming upstream WS: %s" , m ) uwsgi . websocket_send ( m ) logger . debug ( "Send ok" )
def refresh ( self ) -> None : """Update the actual simulation values based on the toy - value pairs . Usually , one does not need to call refresh explicitly . The " magic " methods _ _ call _ _ , _ _ setattr _ _ , and _ _ delattr _ _ invoke it automatically , when required . Instantiate a 1 - dimensional |...
if not self : self . values [ : ] = 0. elif len ( self ) == 1 : values = list ( self . _toy2values . values ( ) ) [ 0 ] self . values [ : ] = self . apply_timefactor ( values ) else : for idx , date in enumerate ( timetools . TOY . centred_timegrid ( self . simulationstep ) ) : values = self . i...
def _resource_deletion ( resource ) : """Recalculate consumption details and save resource details"""
if resource . __class__ not in CostTrackingRegister . registered_resources : return new_configuration = { } price_estimate = models . PriceEstimate . update_resource_estimate ( resource , new_configuration ) price_estimate . init_details ( )
def generateSummary ( self , extraLapse = TYPICAL_LAPSE ) : '''Generates a summary of the status of the expected scripts broken based on the log . This summary ( a list of strings ) is returned as well as a list with the dates ( which can be used to index the log ) of the most recent attempts at the failed jobs...
scriptsRun = self . scriptsRun body = [ ] numberOfFailed = 0 numberWithWarnings = 0 failedList = [ ] successList = [ ] warningsList = [ ] for name , details in sorted ( scriptsRun . iteritems ( ) ) : status = None daysSinceSuccess = None if details [ "lastSuccess" ] and expectedScripts . get ( name ) : ...
def show_rich_text ( self , text , collapse = False , img_path = '' ) : """Show text in rich mode"""
self . switch_to_plugin ( ) self . switch_to_rich_text ( ) context = generate_context ( collapse = collapse , img_path = img_path , css_path = self . css_path ) self . render_sphinx_doc ( text , context )
def _handle_call ( self , actual_call , stubbed_call ) : """Extends Stub call handling behavior to be callable by default ."""
self . _actual_calls . append ( actual_call ) use_call = stubbed_call or actual_call return use_call . return_value
def load ( self , filename , params = None , force = False , depthrange = None , timerange = None , output_is_dict = True , ** kwargs ) : """NetCDF data loader : parameter filename : file name : parameter params : a list of variables to load ( default : load ALL variables ) . : parameter depthrange : if a dep...
if ( params is not None ) & isinstance ( params , str ) : params = [ params ] # Open file self . _filename = filename try : ncf = ncfile ( self . _filename , "r" ) except Exception , e : warn ( repr ( e ) , stacklevel = 2 ) return { } # Load global attributes akeys = ncf . ncattrs ( ) attrStr = OrderedD...
def disable_availability_zones ( self , load_balancer_name , zones_to_remove ) : """Remove availability zones from an existing Load Balancer . All zones must be in the same region as the Load Balancer . Removing zones that are not registered with the Load Balancer has no effect . You cannot remove all zones...
params = { 'LoadBalancerName' : load_balancer_name } self . build_list_params ( params , zones_to_remove , 'AvailabilityZones.member.%d' ) return self . get_list ( 'DisableAvailabilityZonesForLoadBalancer' , params , None )
def _add_decision_criteria ( self , criteria_dict ) : """Adds Decision Criteria to the ProbModelXML . Parameters criteria _ dict : dict Dictionary containing Deecision Criteria data . For example : { ' effectiveness ' : { } , ' cost ' : { } } Examples > > > writer = ProbModelXMLWriter ( model ) > > > ...
decision_tag = etree . SubElement ( self . xml , 'DecisionCriteria' , attrib = { } ) for criteria in sorted ( criteria_dict ) : criteria_tag = etree . SubElement ( decision_tag , 'Criterion' , attrib = { 'name' : criteria } ) self . _add_additional_properties ( criteria_tag , criteria_dict [ criteria ] )
def create_bundle ( self , bundleId , data = None ) : """Creates a bundle using Globalization Pipeline service"""
headers = { 'content-type' : 'application/json' } url = self . __get_base_bundle_url ( ) + "/" + bundleId if data is None : data = { } data [ 'sourceLanguage' ] = 'en' data [ 'targetLanguages' ] = [ ] data [ 'notes' ] = [ ] data [ 'metadata' ] = { } data [ 'partner' ] = '' data [ 'segmentSep...
def _extract_docs_return ( self ) : """Extract return description and type"""
if self . dst . style [ 'in' ] == 'numpydoc' : data = '\n' . join ( [ d . rstrip ( ) . replace ( self . docs [ 'out' ] [ 'spaces' ] , '' , 1 ) for d in self . docs [ 'in' ] [ 'raw' ] . splitlines ( ) ] ) self . docs [ 'in' ] [ 'return' ] = self . dst . numpydoc . get_return_list ( data ) self . docs [ 'in' ...
def get ( self , key ) : """Gets the value of the property of the given key . Args : key ( str ) : Key of the property to look - up ."""
match = self . _get_match ( key = key ) if not match : return None return self . _get_value_from_match ( key = key , match = match )
def _format_multirow ( self , row , ilevels , i , rows ) : r"""Check following rows , whether row should be a multirow e . g . : becomes : a & 0 & \ multirow { 2 } { * } { a } & 0 & & 1 & & 1 & b & 0 & \ cline { 1-2} b & 0 &"""
for j in range ( ilevels ) : if row [ j ] . strip ( ) : nrow = 1 for r in rows [ i + 1 : ] : if not r [ j ] . strip ( ) : nrow += 1 else : break if nrow > 1 : # overwrite non - multirow entry row [ j ] = '\\multirow{{{nrow:d...
def exps ( self , opttype , strike ) : """Prices for given strike on all available dates . Parameters opttype : str ( ' call ' or ' put ' ) strike : numeric Returns df : : class : ` pandas . DataFrame ` eq : float Price of underlying . qt : : class : ` datetime . datetime ` Time of quote . See A...
_relevant = _relevant_rows ( self . data , ( strike , slice ( None ) , opttype , ) , "No key for {} {}" . format ( strike , opttype ) ) _index = _relevant . index . get_level_values ( 'Expiry' ) _columns = [ 'Price' , 'Time_Val' , 'Last' , 'Bid' , 'Ask' , 'Vol' , 'Open_Int' ] _df = pd . DataFrame ( index = _index , col...
def _allocate_segment ( self , session , net_id , source ) : """Allocate segment from pool . Return allocated db object or None ."""
with session . begin ( subtransactions = True ) : hour_lapse = utils . utc_time_lapse ( self . seg_timeout ) count = ( session . query ( self . model ) . filter ( self . model . delete_time < hour_lapse ) . update ( { "delete_time" : None } ) ) select = ( session . query ( self . model ) . filter_by ( alloc...
def _setup_output_file ( self , output_filename , args , write_header = True ) : """Open and prepare output file ."""
# write command line into outputFile # ( without environment variables , they are documented by benchexec ) try : output_file = open ( output_filename , 'w' ) # override existing file except IOError as e : sys . exit ( e ) if write_header : output_file . write ( ' ' . join ( map ( util . escape_string_s...
def delete_service_network ( self , tenant_name , network ) : """Delete service network on the DCNM . : param tenant _ name : name of tenant the network belongs to : param network : object that contains network parameters"""
network_info = { } part_name = network . part_name if not part_name : part_name = self . _part_name seg_id = str ( network . segmentation_id ) if network . vlan : vlan_id = str ( network . vlan ) if network . mob_domain_name is not None : mob_domain_name = network . mob_domain_name else : # The ...
def destroy ( self ) : """A reimplemented destructor . This destructor will remove itself from the superview ."""
widget = self . widget if widget is not None : widget . removeFromSuperview ( ) super ( UiKitView , self ) . destroy ( )
def discard_all ( self , filterfunc = None ) : """Discard all waiting messages . : param filterfunc : A filter function to only discard the messages this filter returns . : returns : the number of messages discarded . * WARNING * : All incoming messages will be ignored and not processed . Example using fi...
if not filterfunc : return self . backend . queue_purge ( self . queue ) if self . no_ack or self . auto_ack : raise Exception ( "discard_all: Can't use filter with auto/no-ack." ) discarded_count = 0 while True : message = self . fetch ( ) if message is None : return discarded_count if filt...
def handle_closed_task ( self , task_name , record ) : """Do everything needed when a task is closed Params : task _ name ( str ) : name of the task that is finishing record ( logging . LogRecord ) : log record with all the info Returns : None"""
if task_name not in self . tasks : return if self . main_failed : self . mark_parent_tasks_as_failed ( self . cur_task ) if self . tasks [ task_name ] . failed : record . msg = ColorFormatter . colored ( 'red' , END_TASK_ON_ERROR_MSG ) else : record . msg = ColorFormatter . colored ( 'green' , END_TASK_...
def load_conll ( f , features , n_features = ( 2 ** 16 ) , split = False ) : """Load CoNLL file , extract features on the tokens and vectorize them . The ConLL file format is a line - oriented text format that describes sequences in a space - separated format , separating the sequences with blank lines . Typi...
fh = FeatureHasher ( n_features = n_features , input_type = "string" ) labels = [ ] lengths = [ ] with _open ( f ) as f : raw_X = _conll_sequences ( f , features , labels , lengths , split ) X = fh . transform ( raw_X ) return X , np . asarray ( labels ) , np . asarray ( lengths , dtype = np . int32 )
def dispatch_job_hook ( self , link , key , job_config , logfile , stream = sys . stdout ) : """Hook to dispatch a single job"""
raise NotImplementedError ( "SysInterface.dispatch_job_hook" )
def page_for_in ( self , leaderboard_name , member , page_size = DEFAULT_PAGE_SIZE ) : '''Determine the page where a member falls in the named leaderboard . @ param leaderboard [ String ] Name of the leaderboard . @ param member [ String ] Member name . @ param page _ size [ int ] Page size to be used in dete...
rank_for_member = None if self . order == self . ASC : rank_for_member = self . redis_connection . zrank ( leaderboard_name , member ) else : rank_for_member = self . redis_connection . zrevrank ( leaderboard_name , member ) if rank_for_member is None : rank_for_member = 0 else : rank_for_member += 1 re...
def open ( self ) : """Retrieve this file ' s attributes from the server . Returns a Future . . . versionchanged : : 2.0 No longer accepts a callback argument . . . versionchanged : : 0.2 : class : ` ~ motor . MotorGridOut ` now opens itself on demand , calling ` ` open ` ` explicitly is rarely needed ....
return self . _framework . chain_return_value ( self . _ensure_file ( ) , self . get_io_loop ( ) , self )
def read_annotation_file ( annotation_file , annotation_type ) : """read _ annotation _ file ( annotation _ file , annotation _ type ) - > annotations Reads annotations from the given ` ` annotation _ file ` ` . The way , how annotations are read depends on the given ` ` annotation _ type ` ` . Depending on t...
annotations = [ { } ] with open ( annotation_file ) as f : if annotation_type == 'idiap' : # This is a special format where we have enumerated annotations , and a ' gender ' for line in f : positions = line . rstrip ( ) . split ( ) if positions : if positions [ 0 ] . ...
def zone_update ( cls , zone_id , records ) : """Update records for a zone"""
cls . echo ( 'Creating new zone file' ) new_version_id = Zone . new ( zone_id ) cls . echo ( 'Updating zone records' ) cls . call ( 'domain.zone.record.set' , zone_id , new_version_id , records ) cls . echo ( 'Activation of new zone version' ) Zone . set ( zone_id , new_version_id ) return new_version_id
def apply_RGB_matrix ( var1 , var2 , var3 , rgb_type , convtype = "xyz_to_rgb" ) : """Applies an RGB working matrix to convert from XYZ to RGB . The arguments are tersely named var1 , var2 , and var3 to allow for the passing of XYZ _ or _ RGB values . var1 is X for XYZ , and R for RGB . var2 and var3 follow s...
convtype = convtype . lower ( ) # Retrieve the appropriate transformation matrix from the constants . rgb_matrix = rgb_type . conversion_matrices [ convtype ] logger . debug ( " \* Applying RGB conversion matrix: %s->%s" , rgb_type . __class__ . __name__ , convtype ) # Stuff the RGB / XYZ values into a NumPy matrix fo...
def mark_streamer ( self , index ) : """Manually mark a streamer that should trigger . The next time check _ streamers is called , the given streamer will be manually marked that it should trigger , which will cause it to trigger unless it has no data . Args : index ( int ) : The index of the streamer tha...
self . _logger . debug ( "Marking streamer %d manually" , index ) if index >= len ( self . streamers ) : raise ArgumentError ( "Invalid streamer index" , index = index , num_streamers = len ( self . streamers ) ) self . _manually_triggered_streamers . add ( index )
def get_api_root_view ( self , api_urls = None ) : """Return a basic root view ."""
api_root_dict = OrderedDict ( ) list_name = self . routes [ 0 ] . name for prefix , viewset , basename in self . registry : api_root_dict [ prefix ] = list_name . format ( basename = basename ) class APIRootView ( views . APIView ) : _ignore_model_permissions = True exclude_from_schema = True def get ( ...
def add_link_type_vlan ( enode , portlbl , name , vlan_id , shell = None ) : """Add a new virtual link with the type set to VLAN . Creates a new vlan device { name } on device { port } . Will raise an exception if value is already assigned . : param enode : Engine node to communicate with . : type enode : t...
assert name if name in enode . ports : raise ValueError ( 'Port {name} already exists' . format ( name = name ) ) assert portlbl assert vlan_id port = enode . ports [ portlbl ] cmd = 'ip link add link {dev} name {name} type vlan id {vlan_id}' . format ( dev = port , name = name , vlan_id = vlan_id ) response = enod...
def close ( self , clear = False ) : """Do final refresh and remove from manager If ` ` leave ` ` is True , the default , the effect is the same as : py : meth : ` refresh ` ."""
if clear and not self . leave : self . clear ( ) else : self . refresh ( ) self . manager . remove ( self )
def correlation ( P , obs1 , obs2 = None , times = [ 1 ] , k = None ) : r"""Time - correlation for equilibrium experiment . Parameters P : ( M , M ) ndarray Transition matrix obs1 : ( M , ) ndarray Observable , represented as vector on state space obs2 : ( M , ) ndarray ( optional ) Second observable ...
M = P . shape [ 0 ] T = np . asarray ( times ) . max ( ) if T < M : return correlation_matvec ( P , obs1 , obs2 = obs2 , times = times ) else : return correlation_decomp ( P , obs1 , obs2 = obs2 , times = times , k = k )
def unsubscribe ( self , peer_jid ) : """Unsubscribe from the presence of the given ` peer _ jid ` ."""
self . client . enqueue ( stanza . Presence ( type_ = structs . PresenceType . UNSUBSCRIBE , to = peer_jid ) )
def authorize ( context , action , target , do_raise = True ) : """Verify that the action is valid on the target in this context . : param context : monasca project context : param action : String representing the action to be checked . This should be colon separated for clarity . : param target : Dictionar...
init ( ) credentials = context . to_policy_values ( ) try : result = _ENFORCER . authorize ( action , target , credentials , do_raise = do_raise , action = action ) return result except policy . PolicyNotRegistered : LOG . exception ( 'Policy not registered' ) raise except Exception : LOG . debug ( ...
def asyncPipeLoop ( context = None , _INPUT = None , conf = None , embed = None , ** kwargs ) : """An operator that asynchronously loops over the input and performs the embedded submodule . Not loopable . Parameters context : pipe2py . Context object _ INPUT : asyncPipe like object ( twisted Deferred iterab...
cust_func = get_cust_func ( context , conf , embed , parse_embed , ** kwargs ) opts . update ( { 'cust_func' : cust_func } ) splits = yield asyncGetSplits ( _INPUT , conf , ** cdicts ( opts , kwargs ) ) gathered = yield asyncStarMap ( asyncParseResult , splits ) _OUTPUT = utils . multiplex ( gathered ) returnValue ( _O...
def wait_for_host ( self , host ) : """Throttle requests to one host ."""
t = time . time ( ) if host in self . times : due_time = self . times [ host ] if due_time > t : wait = due_time - t time . sleep ( wait ) t = time . time ( ) wait_time = random . uniform ( self . wait_time_min , self . wait_time_max ) self . times [ host ] = t + wait_time
def get_metadata ( filename , scan , paramfile = '' , ** kwargs ) : """Parses sdm file to define metadata for observation , including scan info , image grid parameters , pipeline memory usage , etc . Mirrors parsems . get _ metadata ( ) . If paramfile defined , it will use it ( filename or RT . Params instanc...
# create primary state dictionary d = { } # set workdir d [ 'filename' ] = os . path . abspath ( filename ) d [ 'workdir' ] = os . path . dirname ( d [ 'filename' ] ) # define parameters of pipeline via Params object params = pp . Params ( paramfile ) for k in params . defined : # fill in default params d [ k ] = p...
def remote_close ( self ) : """Called by remote worker to state that no more data will be transferred"""
self . fp . close ( ) self . fp = None # on windows , os . rename does not automatically unlink , so do it # manually if os . path . exists ( self . destfile ) : os . unlink ( self . destfile ) os . rename ( self . tmpname , self . destfile ) self . tmpname = None if self . mode is not None : os . chmod ( self ...
def _synthesize_single_subprocess_helper ( self , text , voice_code , output_file_path = None , return_audio_data = True ) : """This is an helper function to synthesize a single text fragment via ` ` subprocess ` ` . If ` ` output _ file _ path ` ` is ` ` None ` ` , the audio data will not persist to file at th...
# return zero if text is the empty string if len ( text ) == 0 : # NOTE sample _ rate , codec , data do not matter # if the duration is 0.000 = > set them to None self . log ( u"len(text) is zero: returning 0.000" ) return ( True , ( TimeValue ( "0.000" ) , None , None , None ) ) # create a temporary output fil...
def distance_two ( GPS_RAW1 , GPS_RAW2 , horizontal = True ) : '''distance between two points'''
if hasattr ( GPS_RAW1 , 'Lat' ) : lat1 = radians ( GPS_RAW1 . Lat ) lat2 = radians ( GPS_RAW2 . Lat ) lon1 = radians ( GPS_RAW1 . Lng ) lon2 = radians ( GPS_RAW2 . Lng ) alt1 = GPS_RAW1 . Alt alt2 = GPS_RAW2 . Alt elif hasattr ( GPS_RAW1 , 'cog' ) : lat1 = radians ( GPS_RAW1 . lat ) * 1.0e-7...
def send_produce_request ( self , payloads = None , acks = 1 , timeout = DEFAULT_REPLICAS_ACK_MSECS , fail_on_error = True , callback = None ) : """Encode and send some ProduceRequests ProduceRequests will be grouped by ( topic , partition ) and then sent to a specific broker . Output is a list of responses in ...
encoder = partial ( KafkaCodec . encode_produce_request , acks = acks , timeout = timeout ) if acks == 0 : decoder = None else : decoder = KafkaCodec . decode_produce_response resps = yield self . _send_broker_aware_request ( payloads , encoder , decoder ) returnValue ( self . _handle_responses ( resps , fail_o...
def from_stream ( cls , stream ) : """Extract data from stream . Returns None if some error occurred ."""
cycles = [ ] while True : scf_cycle = GroundStateScfCycle . from_stream ( stream ) if scf_cycle is None : break cycles . append ( scf_cycle ) return cls ( cycles ) if cycles else None
from typing import List def has_zero_sum_pair ( nums : List [ int ] ) -> bool : """Identifies if a list contains a pair of distinct elements , whose sum equals to zero . Args : nums : The list of numbers which is to be checked for pairs summing to zero . Returns : A boolean indicating whether there are two ...
for idx , num1 in enumerate ( nums ) : for num2 in nums [ idx + 1 : ] : if num1 + num2 == 0 : return True return False
def write_file ( self , molecule , inpfile ) : """Write an ADF input file . Parameters molecule : Molecule The molecule for this task . inpfile : str The name where the input file will be saved ."""
mol_blocks = [ ] atom_block = AdfKey ( "Atoms" , options = [ "cartesian" ] ) for site in molecule : atom_block . add_subkey ( AdfKey ( str ( site . specie ) , list ( site . coords ) ) ) mol_blocks . append ( atom_block ) if molecule . charge != 0 : netq = molecule . charge ab = molecule . spin_multiplicity ...
def get_export_configuration ( self , config_id ) : """Retrieve the ExportConfiguration with the given ID : param string config _ id : ID for which to search : return : a : class : ` meteorpi _ model . ExportConfiguration ` or None , or no match was found ."""
sql = ( 'SELECT uid, exportConfigId, exportType, searchString, targetURL, ' 'targetUser, targetPassword, exportName, description, active ' 'FROM archive_exportConfig WHERE exportConfigId = %s' ) return first_from_generator ( self . generators . export_configuration_generator ( sql = sql , sql_args = ( config_id , ) ) )
def reduce_terms ( term_doc_matrix , scores , num_term_to_keep = None ) : '''Parameters term _ doc _ matrix : TermDocMatrix or descendant scores : array - like Same length as number of terms in TermDocMatrix . num _ term _ to _ keep : int , default = 4000. Should be > 0 . Number of terms to keep . Will ke...
terms_to_show = AutoTermSelector . get_selected_terms ( term_doc_matrix , scores , num_term_to_keep ) return term_doc_matrix . remove_terms ( set ( term_doc_matrix . get_terms ( ) ) - set ( terms_to_show ) )
def get_sample_values ( self ) : """Read the rows specifying Samples and return a dictionary with related data . keys are : headers - row with " Samples " in column 0 . These headers are used as dictionary keys in the rows below . prices - Row with " Analysis Price " in column 0. total _ analyses - Row ...
res = { 'samples' : [ ] } lines = self . getOriginalFile ( ) . data . splitlines ( ) reader = csv . reader ( lines ) next_rows_are_sample_rows = False for row in reader : if not any ( row ) : continue if next_rows_are_sample_rows : vals = [ x . strip ( ) for x in row ] if not any ( vals ...
def _converged ( self , X ) : """Covergence if | | likehood - last _ likelihood | | < tolerance"""
if len ( self . responsibilities ) < 2 : return False diff = np . linalg . norm ( self . responsibilities [ - 1 ] - self . responsibilities [ - 2 ] ) return diff <= self . tolerance
def run_step ( self , context ) : """Run a single pipeline step . Args : context : ( pypyr . context . Context ) The pypyr context . This arg will mutate ."""
logger . debug ( "starting" ) # the in params should be added to context before step execution . self . set_step_input_context ( context ) if self . while_decorator : self . while_decorator . while_loop ( context , self . run_foreach_or_conditional ) else : self . run_foreach_or_conditional ( context ) logger ....
def _generate_args ( pipeline , future , queue_name , base_path ) : """Generate the params used to describe a Pipeline ' s depedencies . The arguments passed to this method may be normal values , Slot instances ( for named outputs ) , or PipelineFuture instances ( for referring to the default output slot ) . ...
params = { 'args' : [ ] , 'kwargs' : { } , 'after_all' : [ ] , 'output_slots' : { } , 'class_path' : pipeline . _class_path , 'queue_name' : queue_name , 'base_path' : base_path , 'backoff_seconds' : pipeline . backoff_seconds , 'backoff_factor' : pipeline . backoff_factor , 'max_attempts' : pipeline . max_attempts , '...
def _load_calib ( self ) : """Load and compute intrinsic and extrinsic calibration parameters ."""
# We ' ll build the calibration parameters as a dictionary , then # convert it to a namedtuple to prevent it from being modified later data = { } # Load the rigid transformation from IMU to velodyne data [ 'T_velo_imu' ] = self . _load_calib_rigid ( 'calib_imu_to_velo.txt' ) # Load the camera intrinsics and extrinsics ...
def get_vault_hierarchy_design_session ( self ) : """Gets the session designing vault hierarchies . return : ( osid . authorization . VaultHierarchyDesignSession ) - a ` ` VaultHierarchyDesignSession ` ` raise : OperationFailed - unable to complete request raise : Unimplemented - ` ` supports _ vault _ hier...
if not self . supports_vault_hierarchy_design ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . VaultHierarchyDesignSession ( runtime = self . _runtime )
def build_markdown ( toc_headlines , body , spacer = 0 , placeholder = None ) : """Returns a string with the Markdown output contents incl . the table of contents . Keyword arguments : toc _ headlines : lines for the table of contents as created by the create _ toc function . body : contents of the Markdo...
if spacer : spacer_line = [ '\n<div style="height:%spx;"></div>\n' % ( spacer ) ] toc_markdown = "\n" . join ( toc_headlines + spacer_line ) else : toc_markdown = "\n" . join ( toc_headlines ) body_markdown = "\n" . join ( body ) . strip ( ) if placeholder : markdown = body_markdown . replace ( placehol...
def do_exit ( self , arg_list : List [ str ] ) -> bool : """Exit the application with an optional exit code . Usage : exit [ exit _ code ] Where : * exit _ code - integer exit code to return to the shell"""
# If an argument was provided if arg_list : try : self . exit_code = int ( arg_list [ 0 ] ) except ValueError : self . perror ( "{} isn't a valid integer exit code" . format ( arg_list [ 0 ] ) ) self . exit_code = - 1 self . _should_quit = True return self . _STOP_AND_EXIT
def push ( self , buf ) : """Push a buffer into the source ."""
self . _src . emit ( 'push-buffer' , Gst . Buffer . new_wrapped ( buf ) )
def delete ( args ) : """Delete NApps from server ."""
mgr = NAppsManager ( ) for napp in args [ '<napp>' ] : mgr . set_napp ( * napp ) LOG . info ( 'Deleting NApp %s from server...' , mgr . napp_id ) try : mgr . delete ( ) LOG . info ( ' Deleted.' ) except requests . HTTPError as exception : if exception . response . status_code ==...
def import_qutip ( ) : """Try importing the qutip module , log an error if unsuccessful . : return : The qutip module if successful or None : rtype : Optional [ module ]"""
global _QUTIP_ERROR_LOGGED try : import qutip except ImportError : # pragma no coverage qutip = None if not _QUTIP_ERROR_LOGGED : _log . error ( "Could not import qutip. Tomography tools will not function." ) _QUTIP_ERROR_LOGGED = True return qutip
def get_alignak_configuration ( self , section = SECTION_CONFIGURATION , legacy_cfg = False , macros = False ) : """Get the Alignak configuration parameters . All the variables included in the SECTION _ CONFIGURATION section except the variables starting with ' cfg ' and the macros . If ` lecagy _ cfg ` is Tr...
configuration = self . _search_sections ( section ) if section not in configuration : return [ ] for prop , _ in list ( configuration [ section ] . items ( ) ) : # Only legacy configuration items if legacy_cfg : if not prop . startswith ( 'cfg' ) : configuration [ section ] . pop ( prop ) ...