signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def from_json ( cls , raw ) : """Helper to construct a blob from a dict . Args : raw ( dict ) : Raw blob representation . Returns : NodeBlob : A NodeBlob object or None ."""
if raw is None : return None bcls = None _type = raw . get ( 'type' ) try : bcls = cls . _blob_type_map [ BlobType ( _type ) ] except ( KeyError , ValueError ) as e : logger . warning ( 'Unknown blob type: %s' , _type ) if DEBUG : raise_from ( exception . ParseException ( 'Parse error for %s' % ...
def detachRequestMsOriginating ( ) : """DETACH REQUEST Section 9.4.5.2"""
a = TpPd ( pd = 0x3 ) b = MessageType ( mesType = 0x5 ) # 00000101 c = DetachTypeAndSpareHalfOctets ( ) packet = a / b / c return packet
def reset ( self ) : """Reset openthread device , not equivalent to stop and start"""
logger . debug ( 'DUT> reset' ) self . _log and self . pause ( ) self . _sendline ( 'reset' ) self . _read ( ) self . _log and self . resume ( )
def create_service ( self , customer_id , name , publish_key = None , comment = None ) : """Create a service ."""
body = self . _formdata ( { "customer_id" : customer_id , "name" : name , "publish_key" : publish_key , "comment" : comment , } , FastlyService . FIELDS ) content = self . _fetch ( "/service" , method = "POST" , body = body ) return FastlyService ( self , content )
def activated ( self , value ) : """Setter for * * self . _ _ activated * * attribute . : param value : Attribute value . : type value : bool"""
if value is not None : assert type ( value ) is bool , "'{0}' attribute: '{1}' type is not 'bool'!" . format ( "activated" , value ) self . __activated = value
def _draw_inner_connector ( context , width , height ) : """Draw the connector for container states Connector for container states can be connected from the inside and the outside . Thus the connector is split in two parts : A rectangle on the inside and an arrow on the outside . This methods draws the inner re...
c = context # Current pos is center # Arrow is drawn upright gap = height / 6. connector_height = ( height - gap ) / 2. # First move to bottom left corner c . rel_move_to ( - width / 2. , height / 2. ) # Draw inner connector ( rectangle ) c . rel_line_to ( width , 0 ) c . rel_line_to ( 0 , - connector_height ) c . rel_...
def _fix_sitk_bug ( self , path , metadata ) : """There is a bug in simple ITK for Z axis in 3D images . This is a fix : param path : : param metadata : : return :"""
ds = dicom . read_file ( path ) ds . SpacingBetweenSlices = str ( metadata [ "voxelsize_mm" ] [ 0 ] ) [ : 16 ] dicom . write_file ( path , ds )
def set_debug_listener ( stream ) : """Break into a debugger if receives the SIGUSR1 signal"""
def debugger ( sig , frame ) : launch_debugger ( frame , stream ) if hasattr ( signal , 'SIGUSR1' ) : signal . signal ( signal . SIGUSR1 , debugger ) else : logger . warn ( "Cannot set SIGUSR1 signal for debug mode." )
def get_provisioned_gsi_write_units ( table_name , gsi_name ) : """Returns the number of provisioned write units for the table : type table _ name : str : param table _ name : Name of the DynamoDB table : type gsi _ name : str : param gsi _ name : Name of the GSI : returns : int - - Number of write units"...
try : desc = DYNAMODB_CONNECTION . describe_table ( table_name ) except JSONResponseError : raise for gsi in desc [ u'Table' ] [ u'GlobalSecondaryIndexes' ] : if gsi [ u'IndexName' ] == gsi_name : write_units = int ( gsi [ u'ProvisionedThroughput' ] [ u'WriteCapacityUnits' ] ) break logger ....
def kruskal_align ( U , V , permute_U = False , permute_V = False ) : """Aligns two KTensors and returns a similarity score . Parameters U : KTensor First kruskal tensor to align . V : KTensor Second kruskal tensor to align . permute _ U : bool If True , modifies ' U ' to align the KTensors ( default ...
# Compute similarity matrices . unrm = [ f / np . linalg . norm ( f , axis = 0 ) for f in U . factors ] vnrm = [ f / np . linalg . norm ( f , axis = 0 ) for f in V . factors ] sim_matrices = [ np . dot ( u . T , v ) for u , v in zip ( unrm , vnrm ) ] cost = 1 - np . mean ( np . abs ( sim_matrices ) , axis = 0 ) # Solve...
def getCenters ( self ) : """Returns histogram ' s centers ."""
return np . arange ( self . histogram . size ) * self . binWidth + self . minValue
def id_generator ( size = 15 , random_state = None ) : """Helper function to generate random div ids . This is useful for embedding HTML into ipython notebooks ."""
chars = list ( string . ascii_uppercase + string . digits ) return '' . join ( random_state . choice ( chars , size , replace = True ) )
def get_host ( environ ) : # type : ( Dict [ str , str ] ) - > str """Return the host for the given WSGI environment . Yanked from Werkzeug ."""
if environ . get ( "HTTP_HOST" ) : rv = environ [ "HTTP_HOST" ] if environ [ "wsgi.url_scheme" ] == "http" and rv . endswith ( ":80" ) : rv = rv [ : - 3 ] elif environ [ "wsgi.url_scheme" ] == "https" and rv . endswith ( ":443" ) : rv = rv [ : - 4 ] elif environ . get ( "SERVER_NAME" ) : ...
def unsubscribe ( request , watch_id ) : """Unsubscribe from ( i . e . delete ) the watch of ID ` ` watch _ id ` ` . Expects an ` ` s ` ` querystring parameter matching the watch ' s secret . GET will result in a confirmation page ( or a failure page if the secret is wrong ) . POST will actually delete the wa...
ext = getattr ( settings , 'TIDINGS_TEMPLATE_EXTENSION' , 'html' ) # Grab the watch and secret ; complain if either is wrong : try : watch = Watch . objects . get ( pk = watch_id ) # ' s ' is for ' secret ' but saves wrapping in mails secret = request . GET . get ( 's' ) if secret != watch . secret : ...
def _get_html_contents ( html ) : """Process a HTML block and detects whether it is a code block , a math block , or a regular HTML block ."""
parser = MyHTMLParser ( ) parser . feed ( html ) if parser . is_code : return ( 'code' , parser . data . strip ( ) ) elif parser . is_math : return ( 'math' , parser . data . strip ( ) ) else : return '' , ''
async def add ( self , rule , kwargs = None ) : """Increments the counter for the given * rule * and * kwargs * . If this pair of * rule * and * kwargs * doesn ' t already have a counter , it is created . * rule * is the : class : ` rule . Rule ` instance that got the match . * kwargs * is an optional dict ...
index = self [ rule . name ] . increment ( kwargs ) if self [ rule . name ] [ index ] >= rule . limit : await rule . action . run ( kwargs )
def zpad ( v , Nv ) : """Zero - pad initial axes of array to specified size . Padding is applied to the right , top , etc . of the array indices . Parameters v : array _ like Array to be padded Nv : tuple Sizes to which each of initial indices should be padded Returns vp : ndarray Padded array"""
vp = np . zeros ( Nv + v . shape [ len ( Nv ) : ] , dtype = v . dtype ) axnslc = tuple ( [ slice ( 0 , x ) for x in v . shape ] ) vp [ axnslc ] = v return vp
def do_cd ( self , path = '/' ) : """change current working directory"""
path = path [ 0 ] if path == ".." : self . current_path = "/" . join ( self . current_path [ : - 1 ] . split ( "/" ) [ 0 : - 1 ] ) + '/' elif path == '/' : self . current_path = "/" else : if path [ - 1 ] == '/' : self . current_path += path else : self . current_path += path + '/' resp ...
def choices ( self ) : """Retrieve choices from API if possible"""
if not self . _choices : gandi = self . gandi or GandiContextHelper ( ) self . _choices = self . _get_choices ( gandi ) if not self . _choices : api = gandi . get_api_connector ( ) gandi . echo ( 'Please check that you are connecting to the good ' "api '%s' and that it's running." % ( api . ...
def emit ( self ) : """Serialize response . : return response : Instance of django . http . Response"""
# Skip serialize if not isinstance ( self . response , SerializedHttpResponse ) : return self . response self . response . content = self . serialize ( self . response . response ) self . response [ 'Content-type' ] = self . media_type return self . response
def iter_python_modules ( tile ) : """Iterate over all python products in the given tile . This will yield tuples where the first entry is the path to the module containing the product the second entry is the appropriate import string to include in an entry point , and the third entry is the entry point nam...
for product_type in tile . PYTHON_PRODUCTS : for product in tile . find_products ( product_type ) : entry_point = ENTRY_POINT_MAP . get ( product_type ) if entry_point is None : raise BuildError ( "Found an unknown python product (%s) whose entrypoint could not be determined (%s)" % ( pr...
def depth_november_average_ground_temperature ( self , value = None ) : """Corresponds to IDD Field ` depth _ november _ average _ ground _ temperature ` Args : value ( float ) : value for IDD Field ` depth _ november _ average _ ground _ temperature ` Unit : C if ` value ` is None it will not be checked ag...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `depth_november_average_ground_temperature`' . format ( value ) ) self . _depth_november_average_ground_temperature = value
def playbook ( self ) : """Include the Playbook Module . . . Note : : Playbook methods can be accessed using ` ` tcex . playbook . < method > ` ` ."""
if self . _playbook is None : from . tcex_playbook import TcExPlaybook self . _playbook = TcExPlaybook ( self ) return self . _playbook
def mount ( self , path , fs ) : # type : ( Text , Union [ FS , Text ] ) - > None """Mounts a host FS object on a given path . Arguments : path ( str ) : A path within the MountFS . fs ( FS or str ) : A filesystem ( instance or URL ) to mount ."""
if isinstance ( fs , text_type ) : from . opener import open_fs fs = open_fs ( fs ) if not isinstance ( fs , FS ) : raise TypeError ( "fs argument must be an FS object or a FS URL" ) if fs is self : raise ValueError ( "Unable to mount self" ) _path = forcedir ( abspath ( normpath ( path ) ) ) for mount_...
def is_file_opened ( self , filename = None ) : """Return if filename is in the editor stack . Args : filename : Name of the file to search for . If filename is None , then checks if any file is open . Returns : True : If filename is None and a file is open . False : If filename is None and no files are...
if filename is None : # Is there any file opened ? return len ( self . data ) > 0 else : return self . has_filename ( filename )
def ingest_volumes_param ( self , volumes ) : """This is for ingesting the " volumes " of a pod spec"""
data = { } for volume in volumes : if volume . get ( 'hostPath' , { } ) . get ( 'path' ) : data [ volume . get ( 'name' ) ] = { 'path' : volume . get ( 'hostPath' , { } ) . get ( 'path' ) , } elif volume . get ( 'emptyDir' ) : data [ volume . get ( 'name' ) ] = { } else : data [ volu...
def result ( self , * args , ** kwargs ) : """Construye la consulta SQL"""
prettify = kwargs . get ( 'pretty' , False ) self . __prepareData__ ( ) sql = 'SELECT ' sql += ', ' . join ( self . fields ) if len ( self . tables ) > 0 : if prettify : sql += '\n' else : sql += ' ' sql += 'FROM ' sql += ', ' . join ( self . tables ) if self . where_criteria . size ( ) ...
def load ( self , revision_path ) : """Load revision file . : param revision _ path : : type revision _ path : str"""
if not os . path . exists ( revision_path ) : raise RuntimeError ( "revision file does not exist." ) with open ( revision_path , mode = 'r' ) as f : text = f . read ( ) rev_strings = text . split ( "## " ) for rev_string in rev_strings : if len ( rev_string ) == 0 or rev_string [ : 2 ] == "# " :...
def setup ( self , target = None , strict = False , minify = False , line_numbers = False , keep_lines = False , no_tco = False ) : """Initializes parsing parameters ."""
if target is None : target = "" else : target = str ( target ) . replace ( "." , "" ) if target in pseudo_targets : target = pseudo_targets [ target ] if target not in targets : raise CoconutException ( "unsupported target Python version " + ascii ( target ) , extra = "supported targets are " + ', ' . j...
def namedb_create_token_genesis ( con , initial_account_balances , genesis_block_history ) : """Create the initial account balances . All accounts will be locked , and will have been created at the genesis date for Blockstack ( i . e . FIRST _ BLOCK _ MAINNET ) The genesis block has multiple " stages " that e...
namedb_query_execute ( con , "BEGIN" , ( ) ) for account_info in initial_account_balances : # check required fields for f in [ 'address' , 'type' , 'value' ] : assert f in account_info , 'BUG: missing {} in {}' . format ( f , account_info ) metadata = None address = None try : address = ...
def create ( self , article , attachment , inline = False , file_name = None , content_type = None ) : """This function creates attachment attached to article . : param article : Numeric article id or : class : ` Article ` object . : param attachment : File object or os path to file : param inline : If true ,...
return HelpdeskAttachmentRequest ( self ) . post ( self . endpoint . create , article = article , attachments = attachment , inline = inline , file_name = file_name , content_type = content_type )
def _read_tcp_options ( self , size ) : """Read TCP option list . Positional arguments : * size - - int , length of option list Returns : * tuple - - TCP option list * dict - - extracted TCP option"""
counter = 0 # length of read option list optkind = list ( ) # option kind list options = dict ( ) # dict of option data while counter < size : # get option kind kind = self . _read_unpack ( 1 ) # fetch corresponding option tuple opts = TCP_OPT . get ( kind ) enum = OPT_TYPE . get ( kind ) if opts is...
def account_policy ( name = None , allow_users_to_change_password = None , hard_expiry = None , max_password_age = None , minimum_password_length = None , password_reuse_prevention = None , require_lowercase_characters = None , require_numbers = None , require_symbols = None , require_uppercase_characters = None , regi...
config = locals ( ) ret = { 'name' : 'Account Policy' , 'result' : True , 'comment' : '' , 'changes' : { } } info = __salt__ [ 'boto_iam.get_account_policy' ] ( region , key , keyid , profile ) if not info : ret [ 'comment' ] = 'Account policy is not Enabled.' ret [ 'result' ] = False return ret for key , v...
def btc_is_p2wsh_address ( address ) : """Is the given address a p2wsh address ?"""
wver , whash = segwit_addr_decode ( address ) if whash is None : return False if len ( whash ) != 32 : return False return True
def get_size ( self ) : """Retrieves the size of the file - like object . Returns : int : size of the file - like object data . Raises : IOError : if the file - like object has not been opened . OSError : if the file - like object has not been opened ."""
if not self . _is_open : raise IOError ( 'Not opened.' ) if not hasattr ( self . _file_object , 'get_size' ) : if not self . _size : current_offset = self . get_offset ( ) self . seek ( 0 , os . SEEK_END ) self . _size = self . get_offset ( ) self . seek ( current_offset , os . S...
def dt_to_timestamp ( dt ) : """Converts from a : class : ` ~ datetime . datetime ` object to an integer timestamp , suitable interoperation with : func : ` time . time ` and other ` Epoch - based timestamps ` . . . _ Epoch - based timestamps : https : / / en . wikipedia . org / wiki / Unix _ time > > > abs...
if dt . tzinfo : td = dt - EPOCH_AWARE else : td = dt - EPOCH_NAIVE return total_seconds ( td )
def to_json ( self , extras = None ) : """Convert a model into a json using the playhouse shortcut ."""
extras = extras or { } to_dict = model_to_dict ( self ) to_dict . update ( extras ) return json . dumps ( to_dict , cls = sel . serializers . JsonEncoder )
def init ( cfg ) : """Initialiaze na3x : param cfg : db , triggers , environment variables configuration"""
global na3x_cfg with open ( cfg [ NA3X_DB ] ) as db_cfg_file : na3x_cfg [ NA3X_DB ] = json . load ( db_cfg_file , strict = False ) with open ( cfg [ NA3X_TRIGGERS ] ) as triggers_cfg_file : na3x_cfg [ NA3X_TRIGGERS ] = json . load ( triggers_cfg_file , strict = False ) with open ( cfg [ NA3X_ENV ] ) as env_cfg_...
def all_status ( ) : '''Return a composite of all status data and info for this minion . Warning : There is a LOT here ! CLI Example : . . code - block : : bash salt ' * ' status . all _ status'''
return { 'cpuinfo' : cpuinfo ( ) , 'cpustats' : cpustats ( ) , 'diskstats' : diskstats ( ) , 'diskusage' : diskusage ( ) , 'loadavg' : loadavg ( ) , 'meminfo' : meminfo ( ) , 'netdev' : netdev ( ) , 'netstats' : netstats ( ) , 'uptime' : uptime ( ) , 'vmstats' : vmstats ( ) , 'w' : w ( ) }
def _extract_id_from_batch_response ( r , name = 'id' ) : """Unholy , forward - compatible , mess for extraction of id / oid from a soon - to - be ( deprecated ) batch response ."""
names = name + 's' if names in r : # soon - to - be deprecated batch reponse if 'errors' in r and r [ 'errors' ] : raise GeneralException ( r [ 'errors' ] [ 0 ] [ 'desc' ] ) id = r [ names ] [ 0 ] else : # new - style simplified api response id = r [ name ] return int ( id )
def Open ( self ) : """Opens the USB device for this setting , and claims the interface ."""
# Make sure we close any previous handle open to this usb device . port_path = tuple ( self . port_path ) with self . _HANDLE_CACHE_LOCK : old_handle = self . _HANDLE_CACHE . get ( port_path ) if old_handle is not None : old_handle . Close ( ) self . _read_endpoint = None self . _write_endpoint = None f...
def check_geophysical_vars_fill_value ( self , ds ) : '''Check that geophysical variables contain fill values . : param netCDF4 . Dataset ds : An open netCDF dataset'''
results = [ ] for geo_var in get_geophysical_variables ( ds ) : results . append ( self . _has_var_attr ( ds , geo_var , '_FillValue' , '_FillValue' , BaseCheck . MEDIUM ) , ) return results
def distL1 ( x1 , y1 , x2 , y2 ) : """Compute the L1 - norm ( Manhattan ) distance between two points . The distance is rounded to the closest integer , for compatibility with the TSPLIB convention . The two points are located on coordinates ( x1 , y1 ) and ( x2 , y2 ) , sent as parameters"""
return int ( abs ( x2 - x1 ) + abs ( y2 - y1 ) + .5 )
def complete_multipart_upload ( self , bucket , object_name , upload_id , parts_list , content_type = None , metadata = { } ) : """Complete a multipart upload . N . B . This can be possibly be a slow operation . @ param bucket : The bucket name @ param object _ name : The object name @ param upload _ id : T...
data = self . _build_complete_multipart_upload_xml ( parts_list ) objectname_plus = '%s?uploadId=%s' % ( object_name , upload_id ) details = self . _details ( method = b"POST" , url_context = self . _url_context ( bucket = bucket , object_name = objectname_plus ) , headers = self . _headers ( content_type ) , metadata ...
def get_relation_count_query_for_self_join ( self , query , parent ) : """Add the constraints for a relationship count query on the same table . : type query : eloquent . orm . Builder : type parent : eloquent . orm . Builder : rtype : eloquent . orm . Builder"""
query . select ( QueryExpression ( 'COUNT(*)' ) ) table_prefix = self . _query . get_query ( ) . get_connection ( ) . get_table_prefix ( ) hash_ = self . get_relation_count_hash ( ) query . from_ ( '%s AS %s%s' % ( self . _table , table_prefix , hash_ ) ) key = self . wrap ( self . get_qualified_parent_key_name ( ) ) r...
def import_basemap ( ) : """Try to import Basemap and print out a useful help message if Basemap is either not installed or is missing required environment variables . Returns has _ basemap : bool Basemap : Basemap package if possible else None"""
Basemap = None has_basemap = True has_cartopy = import_cartopy ( ) [ 0 ] try : from mpl_toolkits . basemap import Basemap WARNINGS [ 'has_basemap' ] = True except ImportError : has_basemap = False # if they have installed cartopy , no warning is needed if has_cartopy : return has_basemap , F...
def expandFunction ( self , func , args = [ ] ) : """applies the given function to each of this stimulus ' s memerships when autoparamters are applied : param func : callable to execute for each version of the stimulus : type instancemethod : : param args : arguments to feed to func : type args : list : r...
# initilize array to hold all varied parameters params = self . _autoParams . allData ( ) steps = self . autoParamRanges ( ) ntraces = 1 for p in steps : ntraces = ntraces * len ( p ) varylist = [ [ None for x in range ( len ( params ) ) ] for y in range ( ntraces ) ] x = 1 for iset , step_set in enumerate ( steps ...
def Rx ( rads : Union [ float , sympy . Basic ] ) -> XPowGate : """Returns a gate with the matrix e ^ { - i X rads / 2 } ."""
pi = sympy . pi if protocols . is_parameterized ( rads ) else np . pi return XPowGate ( exponent = rads / pi , global_shift = - 0.5 )
def get_plat_operator ( auth , url , headers = HEADERS ) : '''Funtion takes no inputs and returns a list of dictionaties of all of the operators currently configured on the HPE IMC system : return : list of dictionaries'''
get_operator_url = '/imcrs/plat/operator?start=0&size=1000&orderBy=id&desc=false&total=false' f_url = url + get_operator_url try : r = requests . get ( f_url , auth = auth , headers = headers ) plat_oper_list = json . loads ( r . text ) return plat_oper_list [ 'operator' ] except requests . exceptions . Req...
def unhide_selected ( ) : '''Unhide the selected objects'''
hidden_state = current_representation ( ) . hidden_state selection_state = current_representation ( ) . selection_state res = { } # Take the hidden state and flip the selected atoms bits . for k in selection_state : visible = hidden_state [ k ] . invert ( ) visible_and_selected = visible . add ( selection_state...
def slurpChompedLines ( file , expand = False ) : r"""Return ` ` file ` ` a list of chomped lines . See ` slurpLines ` ."""
f = _normalizeToFile ( file , "r" , expand ) try : return list ( chompLines ( f ) ) finally : f . close ( )
def openOnlyAccel ( self , cycleFreq = 0x00 ) : """Trun on device into Accelerometer Only Low Power Mode @ param cycleFreq can be choise : @ see VAL _ PWR _ MGMT _ 2 _ LP _ WAKE _ CTRL _ 1_25HZ is default @ see VAL _ PWR _ MGMT _ 2 _ LP _ WAKE _ CTRL _ 5HZ @ see VAL _ PWR _ MGMT _ 2 _ LP _ WAKE _ CTRL _ 20H...
self . openWith ( accel = True , gyro = False , temp = False , cycle = True , cycleFreq = cycleFreq )
def labels ( self , nodeids = None ) : """Return the list of labels for * nodeids * , or all labels . Args : nodeids : an iterable of nodeids for predications to get labels from ; if ` None ` , return labels for all predications Note : This returns the label of each predication , even if it ' s shared...
if nodeids is None : nodeids = self . _nodeids _eps = self . _eps return [ _eps [ nid ] [ 2 ] for nid in nodeids ]
def add_transitions_from_selected_state_to_parent ( ) : """Generates the default success transition of a state to its parent success port : return :"""
task_string = "create transition" sub_task_string = "to parent state" selected_state_m , msg = get_selected_single_state_model_and_check_for_its_parent ( ) if selected_state_m is None : logger . warning ( "Can not {0} {1}: {2}" . format ( task_string , sub_task_string , msg ) ) return logger . debug ( "Check to...
def allocator_disabled ( self ) : """Return a simplified one - word answer to the question , ' Has the automatic shard allocator been disabled for this cluster ? ' The answer will be one of " disabled " ( yes ) , " enabled " ( no ) , or " unknown " ."""
state = "unknown" setting_getters = [ lambda s : s [ 'cluster.routing.allocation.disable_allocation' ] , lambda s : s [ 'cluster' ] [ 'routing' ] [ 'allocation' ] [ 'disable_allocation' ] ] settings = self . get ( '/_cluster/settings' ) for i in [ 'persistent' , 'transient' ] : for getter in setting_getters : ...
def add_default_fields ( self , names , ** kwargs ) : """Adds one or more empty default fields to self . Parameters names : ( list of ) string ( s ) The names of the fields to add . Must be a field in self ' s default fields . Other keyword args are any arguments passed to self ' s default fields . Retu...
if isinstance ( names , string_types ) : names = [ names ] default_fields = self . default_fields ( include_virtual = False , ** kwargs ) # parse out any virtual fields arr = self . __class__ ( 1 , field_kwargs = kwargs ) # try to perserve order sortdict = dict ( [ [ nm , ii ] for ii , nm in enumerate ( names ) ] )...
def append ( self , exp ) : """Args : exp ( Experience ) :"""
if self . _curr_size < self . max_size : self . _assign ( self . _curr_pos , exp ) self . _curr_pos = ( self . _curr_pos + 1 ) % self . max_size self . _curr_size += 1 else : self . _assign ( self . _curr_pos , exp ) self . _curr_pos = ( self . _curr_pos + 1 ) % self . max_size
def resolve_resource_type ( self , resource_dict ) : """Returns the Resource class corresponding to the ' Type ' key in the given resource dict . : param dict resource _ dict : the resource dict to resolve : returns : the resolved Resource class : rtype : class"""
if not self . can_resolve ( resource_dict ) : raise TypeError ( "Resource dict has missing or invalid value for key Type. Event Type is: {}." . format ( resource_dict . get ( 'Type' ) ) ) if resource_dict [ 'Type' ] not in self . resource_types : raise TypeError ( "Invalid resource type {resource_type}" . forma...
def _convert_flux ( wavelengths , fluxes , out_flux_unit , area = None , vegaspec = None ) : """Flux conversion for PHOTLAM < - > X ."""
flux_unit_names = ( fluxes . unit . to_string ( ) , out_flux_unit . to_string ( ) ) if PHOTLAM . to_string ( ) not in flux_unit_names : raise exceptions . SynphotError ( 'PHOTLAM must be one of the conversion units but get ' '{0}.' . format ( flux_unit_names ) ) # VEGAMAG if VEGAMAG . to_string ( ) in flux_unit_nam...
def task_done ( self ) : """mark that a " job " ( corresponding to a : meth : ` put ` or : meth : ` put _ nowait ` call ) is finished the : meth : ` join ` method won ' t complete until the number of : meth : ` task _ done ` calls equals the number of : meth : ` put ` calls"""
if not self . _open_tasks : raise ValueError ( "task_done() called too many times" ) self . _open_tasks -= 1 if not self . _open_tasks : self . _jobs_done . set ( )
def sampler ( self , n_samples , duration , random_state = None ) : '''Construct a sampler object for this pump ' s operators . Parameters n _ samples : None or int > 0 The number of samples to generate duration : int > 0 The duration ( in frames ) of each sample patch random _ state : None , int , or n...
return Sampler ( n_samples , duration , random_state = random_state , * self . ops )
def FindDevices ( cls , setting_matcher , device_matcher = None , usb_info = '' , timeout_ms = None ) : """Find and yield the devices that match . Args : setting _ matcher : Function that returns the setting to use given a usb1 . USBDevice , or None if the device doesn ' t have a valid setting . device _ ma...
ctx = usb1 . USBContext ( ) for device in ctx . getDeviceList ( skip_on_error = True ) : setting = setting_matcher ( device ) if setting is None : continue handle = cls ( device , setting , usb_info = usb_info , timeout_ms = timeout_ms ) if device_matcher is None or device_matcher ( handle ) : ...
def requirements ( filename ) : """Reads requirements from a file ."""
with open ( filename ) as f : return [ x . strip ( ) for x in f . readlines ( ) if x . strip ( ) ]
def merge ( self , ref_name : str ) : """Merges two refs Args : ref _ name : ref to merge in the current one"""
if self . is_dirty ( ) : LOGGER . error ( 'repository is dirty; cannot merge: %s' , ref_name ) sys . exit ( - 1 ) LOGGER . info ( 'merging ref: "%s" into branch: %s' , ref_name , self . get_current_branch ( ) ) self . repo . git . merge ( ref_name )
def encode ( hrp , witver , witprog ) : """Encode a segwit address ."""
ret = bech32_encode ( hrp , [ witver ] + convertbits ( witprog , 8 , 5 ) ) if decode ( ret ) == ( None , None ) : return None return ret
def get_referenced_object ( self ) : """: rtype : core . BunqModel : raise : BunqException"""
if self . _UserLight is not None : return self . _UserLight if self . _UserPerson is not None : return self . _UserPerson if self . _UserCompany is not None : return self . _UserCompany if self . _UserApiKey is not None : return self . _UserApiKey raise exception . BunqException ( self . _ERROR_NULL_FIE...
async def _verkey_for ( self , target : str ) -> str : """Given a DID , retrieve its verification key , looking in wallet , then pool . Given a verification key or None , return input . Raise WalletState if the wallet is closed . Given a recipient DID not in the wallet , raise AbsentPool if the instance has n...
LOGGER . debug ( 'BaseAnchor._verkey_for >>> target: %s' , target ) rv = target if rv is None or not ok_did ( rv ) : # it ' s None or already a verification key LOGGER . debug ( 'BaseAnchor._verkey_for <<< %s' , rv ) return rv if self . wallet . handle : try : rv = await did . key_for_local_did ( se...
def get_dispatcher_event ( self , name ) : """Retrieves an Event object by name Args : name ( str ) : The name of the : class : ` Event ` or : class : ` ~ pydispatch . properties . Property ` object to retrieve Returns : The : class : ` Event ` instance for the event or property definition . . versionad...
e = self . __property_events . get ( name ) if e is None : e = self . __events [ name ] return e
def _build_task_heads ( self , head_modules ) : """Creates and attaches task _ heads to the appropriate network layers"""
# Make task head layer assignments num_layers = len ( self . config [ "layer_out_dims" ] ) task_head_layers = self . _set_task_head_layers ( num_layers ) # task _ head _ layers stores the layer whose output is input to task head t # task _ map stores the task heads that appear at each layer self . task_map = defaultdic...
def close ( self ) : '''close the graph'''
self . close_graph . set ( ) if self . is_alive ( ) : self . child . join ( 2 )
def keypoint_flip ( bbox , d , rows , cols ) : """Flip a keypoint either vertically , horizontally or both depending on the value of ` d ` . Raises : ValueError : if value of ` d ` is not - 1 , 0 or 1."""
if d == 0 : bbox = keypoint_vflip ( bbox , rows , cols ) elif d == 1 : bbox = keypoint_hflip ( bbox , rows , cols ) elif d == - 1 : bbox = keypoint_hflip ( bbox , rows , cols ) bbox = keypoint_vflip ( bbox , rows , cols ) else : raise ValueError ( 'Invalid d value {}. Valid values are -1, 0 and 1' ....
def get_item ( self , repository_id , path , project = None , scope_path = None , recursion_level = None , include_content_metadata = None , latest_processed_change = None , download = None , version_descriptor = None , include_content = None , resolve_lfs = None ) : """GetItem . Get Item Metadata and / or Conten...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) query_parameters = { } if path is not None : q...
def nt_commonpath ( paths ) : # pylint : disable = too - many - locals """Given a sequence of NT path names , return the longest common sub - path ."""
from ntpath import splitdrive if not paths : raise ValueError ( 'commonpath() arg is an empty sequence' ) check_arg_types ( 'commonpath' , * paths ) if isinstance ( paths [ 0 ] , bytes ) : sep = b'\\' altsep = b'/' curdir = b'.' else : sep = '\\' altsep = '/' curdir = '.' drivesplits = [ spl...
def spans ( self , container ) : """Recursively yield all the : class : ` SingleStyledText ` items in this mixed - styled text ."""
for child in self . children ( container ) : container . register_styled ( child ) for span in child . spans ( container ) : yield span
def check_password ( self , raw_password ) : """Returns a boolean of whether the raw _ password was correct . Handles hashing formats behind the scenes ."""
def setter ( raw_password ) : self . set_password ( raw_password ) self . save ( update_fields = [ self . PASSWORD_FIELD ] ) return check_password ( raw_password , getattr ( self , self . PASSWORD_FIELD ) , setter )
def auth_data ( self ) : '''Gather and create the authorization data sets We ' re looking at several constructs here . Standard eauth : allow jsmith to auth via pam , and execute any command on server web1 external _ auth : pam : jsmith : - web1: Django eauth : Import the django library , dynamicall...
auth_data = self . opts [ 'external_auth' ] merge_lists = self . opts [ 'pillar_merge_lists' ] if 'django' in auth_data and '^model' in auth_data [ 'django' ] : auth_from_django = salt . auth . django . retrieve_auth_entries ( ) auth_data = salt . utils . dictupdate . merge ( auth_data , auth_from_django , stra...
def http_responder_factory ( proto ) : """The default factory function which creates a GrowlerHTTPResponder with this object as the parent protocol , and the application ' s req / res factory functions . To change the default responder , overload this method with the same to return your own responder . ...
return GrowlerHTTPResponder ( proto , request_factory = proto . http_application . _request_class , response_factory = proto . http_application . _response_class , )
def _run_server_ops ( state , host , progress = None ) : '''Run all ops for a single server .'''
logger . debug ( 'Running all ops on {0}' . format ( host ) ) for op_hash in state . get_op_order ( ) : op_meta = state . op_meta [ op_hash ] logger . info ( '--> {0} {1} on {2}' . format ( click . style ( '--> Starting operation:' , 'blue' ) , click . style ( ', ' . join ( op_meta [ 'names' ] ) , bold = True )...
def create ( self ) : """Create an instance of the current target in the database If a target with the current name and params already exists , no second instance is created ."""
session = client . get_client ( ) . create_session ( ) if not self . _base_query ( session ) . count ( ) > 0 : # store a new target instance to the database marker = ORMTargetMarker ( name = self . name , params = self . params ) session . add ( marker ) session . commit ( ) session . close ( )
def register_serializers ( self , serializers ) : """Adds extra serializers ; generally registered during the handler lifecycle"""
for new_serializer in serializers : if not isinstance ( new_serializer , serializer . Base ) : msg = "registered serializer %s.%s does not inherit from prestans.serializer.Serializer" % ( new_serializer . __module__ , new_serializer . __class__ . __name__ ) raise TypeError ( msg ) self . _serializer...
def get_urls ( self ) : """Generate the list of URL patterns including the registered single object routers urls ."""
base_urls = super ( SimpleRouter , self ) . get_urls ( ) single_urls = sum ( [ r . urls for r in self . _single_object_registry ] , [ ] ) nested_urls = sum ( [ r . urls for r in self . _nested_object_registry ] , [ ] ) return base_urls + single_urls + nested_urls
def get_context ( self ) : """Create a dict with the context data context is not required , but if it is defined it should be a tuple"""
if not self . context : return else : assert isinstance ( self . context , tuple ) , 'Expected a Tuple not {0}' . format ( type ( self . context ) ) for model in self . context : model_cls = utils . get_model_class ( model ) key = utils . camel_to_snake ( model_cls . __name__ ) self . context_data [...
def by_summoner ( self , region , encrypted_summoner_id ) : """FOR KR SUMMONERS , A 404 WILL ALWAYS BE RETURNED . Valid codes must be no longer than 256 characters and only use valid characters : 0-9 , a - z , A - Z , and - : param string region : the region to execute this request on : param string encrypt...
url , query = ThirdPartyCodeApiV4Urls . by_summoner ( region = region , encrypted_summoner_id = encrypted_summoner_id ) return self . _raw_request ( self . by_summoner . __name__ , region , url , query )
def sample ( self , n = 100 , seed = None ) : """Extract random sample of records . Parameters n : int , optional , default = 100 The number of data points to sample . seed : int , optional , default = None Random seed ."""
if n < 1 : raise ValueError ( "Number of samples must be larger than 0, got '%g'" % n ) if seed is None : seed = random . randint ( 0 , 2 ** 32 ) if self . mode == 'spark' : result = asarray ( self . values . tordd ( ) . values ( ) . takeSample ( False , n , seed ) ) else : basedims = [ self . shape [ d...
def get_attribute ( self , attribute_name , no_cache = False ) : """Gets the passed attribute of this group . : param attribute _ name : The name of the attribute to get . : type attribute _ name : str : param no _ cache ( optional ) : Set to True to pull the attribute directly from an LDAP search instead of ...
attributes = self . get_attributes ( no_cache ) if attribute_name not in attributes : logger . debug ( "ADGroup {group_dn} does not have the attribute " "'{attribute}'." . format ( group_dn = self . group_dn , attribute = attribute_name ) ) return None else : raw_attribute = attributes [ attribute_name ] ...
def from_value ( cls , ion_type , value , annotations = ( ) ) : """Constructs a value as a copy with an associated Ion type and annotations . Args : ion _ type ( IonType ) : The associated Ion type . value ( Any ) : The value to construct from , generally of type ` ` cls ` ` . annotations ( Sequence [ unico...
if value is None : value = IonPyNull ( ) else : args , kwargs = cls . _to_constructor_args ( value ) value = cls ( * args , ** kwargs ) value . ion_event = None value . ion_type = ion_type value . ion_annotations = annotations return value
def update_attributes ( self , attributes ) : """Releases named attributes from this service . Returns update response object ."""
attribute_update = self . _post_object ( self . update_api . attributes . update , attributes ) return ExistAttributeResponse ( attribute_update )
def parse_args ( args ) : """This parses the arguments and returns a tuple containing : ( args , command , command _ args ) For example , " - - config = bar start - - with = baz " would return : ( [ ' - - config = bar ' ] , ' start ' , [ ' - - with = baz ' ] )"""
index = None for arg_i , arg in enumerate ( args ) : if not arg . startswith ( '-' ) : index = arg_i break # Unable to parse any arguments if index is None : return ( args , None , [ ] ) return ( args [ : index ] , args [ index ] , args [ ( index + 1 ) : ] )
def _model ( self , beta ) : """Creates the structure of the model Parameters beta : np . array Contains untransformed starting values for latent variables Returns mu : np . array Contains the predicted values for the time series Y : np . array Contains the length - adjusted time series ( accounting...
Y = np . array ( [ reg [ self . lags : reg . shape [ 0 ] ] for reg in self . data ] ) # Transform latent variables beta = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] ) params = [ ] col_length = 1 + self . ylen * self . lags for i in ra...
def log_variable_sizes ( var_list , tag , verbose = True , mesh_to_impl = None ) : """Log the sizes and shapes of variables , and the total size . Args : var _ list : a list of variables ; defaults to trainable _ variables tag : a string ; defaults to " Trainable Variables " verbose : bool , if True , log e...
if not var_list : return name_to_var = { v . name : v for v in var_list } total_size = 0 total_slice_size = 0 for v_name in sorted ( list ( name_to_var ) ) : v = name_to_var [ v_name ] v_size = v . shape . size if mesh_to_impl is not None : slice_size = mesh_to_impl [ v . mesh ] . slice_size ( v...
def append ( self , name , value = None , sublist = None , seq = None ) : """Add one name / value entry to the main context of the rolne . If you are wanting to " append " another rolne , see the ' extend ' method instead . Example of use : > > > # setup an example rolne first > > > my _ var = rolne ( ) ...
if sublist is None : sublist = [ ] new_seq = lib . _seq ( self , seq ) new_tuple = ( name , value , sublist , new_seq ) self . data . append ( new_tuple ) return
def get_recipes_in_cookbook ( name ) : """Gets the name of all recipes present in a cookbook Returns a list of dictionaries"""
recipes = { } path = None cookbook_exists = False metadata_exists = False for cookbook_path in cookbook_paths : path = os . path . join ( cookbook_path , name ) path_exists = os . path . exists ( path ) # cookbook exists if present in any of the cookbook paths cookbook_exists = cookbook_exists or path_e...
def read_from_file ( cls , filename ) : """Construct a MolecularDistortion object from a file"""
with open ( filename ) as f : lines = list ( line for line in f if line [ 0 ] != '#' ) r = [ ] t = [ ] for line in lines [ : 3 ] : values = list ( float ( word ) for word in line . split ( ) ) r . append ( values [ : 3 ] ) t . append ( values [ 3 ] ) transformation = Complete ( r , t ) affected_atoms = ...
def sens_power_board_encode ( self , timestamp , pwr_brd_status , pwr_brd_led_status , pwr_brd_system_volt , pwr_brd_servo_volt , pwr_brd_mot_l_amp , pwr_brd_mot_r_amp , pwr_brd_servo_1_amp , pwr_brd_servo_2_amp , pwr_brd_servo_3_amp , pwr_brd_servo_4_amp , pwr_brd_aux_amp ) : '''Monitoring of power board status ...
return MAVLink_sens_power_board_message ( timestamp , pwr_brd_status , pwr_brd_led_status , pwr_brd_system_volt , pwr_brd_servo_volt , pwr_brd_mot_l_amp , pwr_brd_mot_r_amp , pwr_brd_servo_1_amp , pwr_brd_servo_2_amp , pwr_brd_servo_3_amp , pwr_brd_servo_4_amp , pwr_brd_aux_amp )
def all_subclasses ( cls ) : """An iterator over all subclasses of ` cls ` ."""
for s in cls . __subclasses__ ( ) : yield s for c in s . all_subclasses ( ) : yield c
def _handle_request_error ( self , orig_request , error , start_response ) : """Handle a request error , converting it to a WSGI response . Args : orig _ request : An ApiRequest , the original request from the user . error : A RequestError containing information about the error . start _ response : A functi...
headers = [ ( 'Content-Type' , 'application/json' ) ] status_code = error . status_code ( ) body = error . rest_error ( ) response_status = '%d %s' % ( status_code , httplib . responses . get ( status_code , 'Unknown Error' ) ) cors_handler = self . _create_cors_handler ( orig_request ) return util . send_wsgi_response...
def _similarity_distance ( s1 , s2 , ignore ) : '''compute similarity with distance measurement'''
g = 0.0 try : g_ = cosine ( _flat_sum_array ( _get_wv ( s1 , ignore ) ) , _flat_sum_array ( _get_wv ( s2 , ignore ) ) ) if is_digit ( g_ ) : g = g_ except : pass u = _nearby_levenshtein_distance ( s1 , s2 ) logging . debug ( "g: %s, u: %s" % ( g , u ) ) if u >= 0.99 : r = 1.0 elif u > 0.9 : ...
def cmd_feed ( ) : """Показывает последние операции в ленте ."""
r = rocket . operations . cool_feed . get ( ) r = handle_error ( r ) j = r . json ( ) lines = [ ] for date , operations in sorted ( list ( j [ "dates" ] . items ( ) ) ) : lines += [ [ click . style ( "===== %s =====" % date , fg = "blue" , bold = True ) , None , None , None ] ] + [ [ op [ "merchant" ] [ "name" ] , ...
def file_to_png ( fp ) : """Convert an image to PNG format with Pillow . : arg file - like fp : The image file . : rtype : bytes"""
import PIL . Image # pylint : disable = import - error with io . BytesIO ( ) as dest : PIL . Image . open ( fp ) . save ( dest , "PNG" , optimize = True ) return dest . getvalue ( )
def to_verify_funds ( pronac , dt ) : """Checks how much money is left for the project to verify , using raised _ funds - verified _ funds This value can be negative ( a project can verify more money than the value approved )"""
project_raised_funds = data . raised_funds_by_project . loc [ pronac ] [ 'CaptacaoReal' ] dataframe = data . planilha_comprovacao project_verified = dataframe . loc [ dataframe [ 'PRONAC' ] == str ( pronac ) ] if project_verified . empty : project_verified_funds = 0 else : pronac_funds = project_verified [ [ "i...