signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def compute_trigonometric_terms ( self , thetas , phis ) : """Computes trigonometric terms that are required to calculate bond orientational order parameters using internal variables . Args : thetas ( [ float ] ) : polar angles of all neighbors in radians . phis ( [ float ] ) : azimuth angles of all neigh...
if len ( thetas ) != len ( phis ) : raise ValueError ( "List of polar and azimuthal angles have to be" " equal!" ) self . _pow_sin_t . clear ( ) self . _pow_cos_t . clear ( ) self . _sin_n_p . clear ( ) self . _cos_n_p . clear ( ) self . _pow_sin_t [ 1 ] = [ sin ( float ( t ) ) for t in thetas ] self . _pow_cos_t [...
def get_variable_info ( cls , hads_var_name ) : """Returns a tuple of ( mmi name , units , english name , english description ) or None ."""
if hads_var_name == "UR" : return ( "wind_gust_from_direction" , "degrees from N" , "Wind Gust from Direction" , "Direction from which wind gust is blowing when maximum wind speed is observed. Meteorological Convention. Wind is motion of air relative to the surface of the earth." , ) elif hads_var_name in [ "VJA" ...
def vzero ( v ) : """Indicate whether a 3 - vector is the zero vector . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / vzero _ c . html : param v : Vector to be tested : type v : 3 - Element Array of floats : return : true if and only if v is the zero vector : rtype : bool...
v = stypes . toDoubleVector ( v ) return bool ( libspice . vzero_c ( v ) )
def config_copy ( args ) : """Copy a method config to new name / space / namespace / project ( or all 4)"""
if not ( args . tospace or args . toname or args . toproject or args . tonamespace ) : raise RuntimeError ( 'A new config name OR workspace OR project OR ' + 'namespace must be given (or all)' ) copy = fapi . get_workspace_config ( args . fromproject , args . fromspace , args . namespace , args . config ) fapi . _c...
def op_at_code_loc ( code , loc , opc ) : """Return the instruction name at code [ loc ] using opc to look up instruction names . Returns ' got IndexError ' if code [ loc ] is invalid . ` code ` is instruction bytecode , ` loc ` is an offset ( integer ) and ` opc ` is an opcode module from ` xdis ` ."""
try : op = code [ loc ] except IndexError : return 'got IndexError' return opc . opname [ op ]
def inject_resource ( ident_hash , file , filename , media_type ) : """Injects the contents of ` ` file ` ` ( a file - like object ) into the database as ` ` filename ` ` with ` ` media _ type ` ` in association with the content at ` ` ident _ hash ` ` ."""
resource_hash = get_file_sha1 ( file ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : s_ident_hash = split_ident_hash ( ident_hash ) module_ident = lookup_module_ident ( * s_ident_hash ) fileid , resource_hash = insert_file ( file , media_type ) upsert_module_...
def findpeak_multi ( x , y , dy , N , Ntolerance , Nfit = None , curve = 'Lorentz' , return_xfit = False , return_stat = False ) : """Find multiple peaks in the dataset given by vectors x and y . Points are searched for in the dataset where the N points before and after have strictly lower values than them . To...
if Nfit is None : Nfit = N # find points where the curve grows for N points before them and # decreases for N points after them . To accomplish this , we create # an indicator array of the sign of the first derivative . sgndiff = np . sign ( np . diff ( y ) ) xdiff = x [ : - 1 ] # associate difference values to the...
async def get_name_endpoint ( request : web . Request ) -> web . Response : """Get the name of the robot . This information is also accessible in / server / update / health , but this endpoint provides symmetry with POST / server / name . GET / server / name - > 200 OK , { ' name ' : robot name }"""
return web . json_response ( data = { 'name' : request . app [ DEVICE_NAME_VARNAME ] } , status = 200 )
def _setup_config ( self , dist , filename , section , vars , verbosity ) : """Called to setup an application , given its configuration file / directory . The default implementation calls ` ` package . websetup . setup _ config ( command , filename , section , vars ) ` ` or ` ` package . websetup . setup _ ...
modules = [ line . strip ( ) for line in dist . get_metadata_lines ( 'top_level.txt' ) if line . strip ( ) and not line . strip ( ) . startswith ( '#' ) ] if not modules : print ( 'No modules are listed in top_level.txt' ) print ( 'Try running python setup.py egg_info to regenerate that file' ) for mod_name in ...
def get_sources ( self ) : """Returns target ' s non - deferred sources if exists or the default sources if defined . : rtype : : class : ` GlobsWithConjunction ` NB : once ivy is implemented in the engine , we can fetch sources natively here , and / or refactor how deferred sources are implemented . see : ...
source = getattr ( self , 'source' , None ) sources = getattr ( self , 'sources' , None ) if source is not None and sources is not None : raise Target . IllegalArgument ( self . address . spec , 'Cannot specify both source and sources attribute.' ) if source is not None : if not isinstance ( source , string_typ...
def connect_head_namespaced_service_proxy ( self , name , namespace , ** kwargs ) : # noqa : E501 """connect _ head _ namespaced _ service _ proxy # noqa : E501 connect HEAD requests to proxy of Service # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP reques...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . connect_head_namespaced_service_proxy_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . connect_head_namespaced_service_proxy_with_http_info ( name , namespace , ** kwargs ) # ...
def _check_gle_response ( result ) : """Return getlasterror response as a dict , or raise OperationFailure ."""
# Did getlasterror itself fail ? _check_command_response ( result ) if result . get ( "wtimeout" , False ) : # MongoDB versions before 1.8.0 return the error message in an " errmsg " # field . If " errmsg " exists " err " will also exist set to None , so we # have to check for " errmsg " first . raise WTimeoutError...
def _unregister_service ( self ) : """Unregisters the provided service , if needed"""
if self . _registration is not None : # Ignore error try : self . _registration . unregister ( ) except BundleException as ex : # Only log the error at this level logger = logging . getLogger ( "-" . join ( ( self . _ipopo_instance . name , "ServiceRegistration" ) ) ) logger . error ( "E...
def contract_multiplier ( self ) : """[ float ] 合约乘数 , 例如沪深300股指期货的乘数为300.0 ( 期货专用 )"""
try : return self . __dict__ [ "contract_multiplier" ] except ( KeyError , ValueError ) : raise AttributeError ( "Instrument(order_book_id={}) has no attribute 'contract_multiplier' " . format ( self . order_book_id ) )
def viterbi_decode ( tag_sequence : torch . Tensor , transition_matrix : torch . Tensor , tag_observations : Optional [ List [ int ] ] = None ) : """Perform Viterbi decoding in log space over a sequence given a transition matrix specifying pairwise ( transition ) potentials between tags and a matrix of shape ( ...
sequence_length , num_tags = list ( tag_sequence . size ( ) ) if tag_observations : if len ( tag_observations ) != sequence_length : raise ConfigurationError ( "Observations were provided, but they were not the same length " "as the sequence. Found sequence of length: {} and evidence: {}" . format ( sequenc...
def _pirls ( self , X , Y , weights ) : """Performs stable PIRLS iterations to estimate GAM coefficients Parameters X : array - like of shape ( n _ samples , m _ features ) containing input data Y : array - like of shape ( n , ) containing target data weights : array - like of shape ( n , ) containing...
modelmat = self . _modelmat ( X ) # build a basis matrix for the GLM n , m = modelmat . shape # initialize GLM coefficients if model is not yet fitted if ( not self . _is_fitted or len ( self . coef_ ) != self . terms . n_coefs or not np . isfinite ( self . coef_ ) . all ( ) ) : # initialize the model self . coef_ ...
def css_tag ( parser , token ) : """Renders a tag to include the stylesheet . It takes an optional second parameter for the media attribute ; the default media is " screen , projector " . Usage : : { % css " < somefile > . css " [ " < projection type ( s ) > " ] % } Examples : : { % css " myfile . css " %...
path = get_path_from_tokens ( token ) tokens = token . split_contents ( ) if len ( tokens ) > 2 : # Get the media types from the tag call provided by the user . media_type = tokens [ 2 ] [ 1 : - 1 ] else : # Default values . media_type = "screen, projection" return CssTagNode ( path , media_type = media_type )
def range ( self , * args ) : """Generate an integer Array containing an arithmetic progression ."""
args = list ( args ) args . insert ( 0 , self . obj ) return self . _wrap ( range ( * args ) )
def _new_population_gsa ( population , fitnesses , velocities , lower_bounds , upper_bounds , grav_initial , grav_reduction_rate , iteration , max_iterations ) : """Generate a new population as given by GSA algorithm . In GSA paper , grav _ initial is G _ i"""
# Update the gravitational constant , and the best and worst of the population # Calculate the mass and acceleration for each solution # Update the velocity and position of each solution population_size = len ( population ) solution_size = len ( population [ 0 ] ) # In GSA paper , grav is G grav = _next_grav_gsa ( grav...
def set_integration_time ( self , integration_time ) : """Sets the integration time for the TC34725 . Provide one of these constants : - TCS34725 _ INTEGRATIONTIME _ 2_4MS = 2.4ms - 1 cycle - Max Count : 1024 - TCS34725 _ INTEGRATIONTIME _ 24MS = 24ms - 10 cycles - Max Count : 10240 - TCS34725 _ INTEGRATION...
self . _integration_time = integration_time self . _write8 ( TCS34725_ATIME , integration_time )
def get_assessment_parts_by_banks ( self , bank_ids ) : """Gets the list of assessment part corresponding to a list of ` ` Banks ` ` . arg : bank _ ids ( osid . id . IdList ) : list of bank ` ` Ids ` ` return : ( osid . assessment . authoring . AssessmentPartList ) - list of assessment parts raise : NullArg...
# Implemented from template for # osid . resource . ResourceBinSession . get _ resources _ by _ bins assessment_part_list = [ ] for bank_id in bank_ids : assessment_part_list += list ( self . get_assessment_parts_by_bank ( bank_id ) ) return objects . AssessmentPartList ( assessment_part_list )
def make_data_iter_plan ( self ) : "make a random data iteration plan"
# truncate each bucket into multiple of batch - size bucket_n_batches = [ ] for i in range ( len ( self . data ) ) : bucket_n_batches . append ( np . floor ( ( self . data [ i ] ) / self . batch_size ) ) self . data [ i ] = self . data [ i ] [ : int ( bucket_n_batches [ i ] * self . batch_size ) ] bucket_plan =...
def pwned_password ( password ) : """Checks a password against the Pwned Passwords database ."""
if not isinstance ( password , text_type ) : raise TypeError ( 'Password values to check must be Unicode strings.' ) password_hash = hashlib . sha1 ( password . encode ( 'utf-8' ) ) . hexdigest ( ) . upper ( ) prefix , suffix = password_hash [ : 5 ] , password_hash [ 5 : ] results = _get_pwned ( prefix ) if results...
def check_additional_images ( self , kwargs_ps , kwargs_lens ) : """checks whether additional images have been found and placed in kwargs _ ps : param kwargs _ ps : point source kwargs : return : bool , True if more image positions are found than originally been assigned"""
ra_image_list , dec_image_list = self . _pointSource . image_position ( kwargs_ps = kwargs_ps , kwargs_lens = kwargs_lens ) if len ( ra_image_list ) > 0 : if len ( ra_image_list [ 0 ] ) > self . _param . num_point_source_images : return True return False
def unsubscribe ( self , channel , * channels ) : """Unsubscribe from specific channels . Arguments can be instances of : class : ` ~ aioredis . Channel ` ."""
conn = self . _pool_or_conn return conn . execute_pubsub ( b'UNSUBSCRIBE' , channel , * channels )
def get_productivity_stats ( self ) : """Return the user ' s productivity stats . : return : A JSON - encoded representation of the user ' s productivity stats . : rtype : A JSON - encoded object . > > > from pytodoist import todoist > > > user = todoist . login ( ' john . doe @ gmail . com ' , ' password...
response = API . get_productivity_stats ( self . api_token ) _fail_if_contains_errors ( response ) return response . json ( )
def get_task_ids ( tids ) : """handle task - id formats such as : habitica todos done 3 habitica todos done 1,2,3 habitica todos done 2 3 habitica todos done 1-3,4 8 tids is a seq like ( last example above ) ( ' 1-3,4 ' ' 8 ' )"""
logging . debug ( 'raw task ids: %s' % tids ) task_ids = [ ] for raw_arg in tids : for bit in raw_arg . split ( ',' ) : if '-' in bit : start , stop = [ int ( e ) for e in bit . split ( '-' ) ] task_ids . extend ( range ( start , stop + 1 ) ) else : task_ids . app...
def _notf ( ins ) : '''Negates top of the stack ( 48 bits )'''
output = _float_oper ( ins . quad [ 2 ] ) output . append ( 'call __NOTF' ) output . append ( 'push af' ) REQUIRES . add ( 'notf.asm' ) return output
def disconnect ( self ) : """Gracefully close connection to stomp server ."""
if self . _connected : self . _connected = False self . _conn . disconnect ( )
def _deconstruct_binary ( self , data ) : """Extract binary components in the packet ."""
attachments = [ ] data = self . _deconstruct_binary_internal ( data , attachments ) return data , attachments
def minmax ( self , minimum = None , maximum = None ) : """Min / Max Sets or gets the minimum and maximum number of items for the Array Arguments minimum { uint } - - The minimum value maximum { uint } - - The maximum value Raises : ValueError Returns : None"""
# If neither minimum or maximum is set , this is a getter if ( minimum is None and maximum is None ) : return { "minimum" : self . _minimum , "maximum" : self . _maximum } # If the minimum is set if minimum is not None : # If the value is not a valid int or long if not isinstance ( minimum , ( int , long ) ) : ...
def preRotate ( self , theta ) : """Calculate pre rotation and replace current matrix ."""
while theta < 0 : theta += 360 while theta >= 360 : theta -= 360 epsilon = 1e-5 if abs ( 0 - theta ) < epsilon : pass elif abs ( 90.0 - theta ) < epsilon : a = self . a b = self . b self . a = self . c self . b = self . d self . c = - a self . d = - b elif abs ( 180.0 - theta ) < eps...
def load_plugins_from_module ( module_name ) : """Imports a module and returns dictionary of discovered Intake plugins . Plugin classes are instantiated and added to the dictionary , keyed by the name attribute of the plugin object ."""
plugins = { } try : if module_name . endswith ( '.py' ) : import imp mod = imp . load_source ( 'module.name' , module_name ) else : mod = importlib . import_module ( module_name ) except Exception as e : logger . debug ( "Import module <{}> failed: {}" . format ( module_name , e ) ) ...
def enumerate_zones ( self ) : """Return a list of ( zone _ id , zone _ name ) tuples"""
zones = [ ] for controller in range ( 1 , 8 ) : for zone in range ( 1 , 17 ) : zone_id = ZoneID ( zone , controller ) try : name = yield from self . get_zone_variable ( zone_id , 'name' ) if name : zones . append ( ( zone_id , name ) ) except CommandEx...
def depersist ( self , key ) : """Remove ` ` key ` ` from dictionary . : param key : Key to remove from Zookeeper . : type key : string"""
self . connection . retry ( self . connection . delete , self . __path_of ( key ) ) self . __increment_last_updated ( )
def unprotect_branches ( self ) : "Unprotect branches of the GitLab project"
g = self . gitlab url = g [ 'url' ] + "/projects/" + g [ 'repo' ] + "/repository/branches" query = { 'private_token' : g [ 'token' ] } unprotected = 0 r = requests . get ( url , params = query ) r . raise_for_status ( ) for branch in r . json ( ) : if branch [ 'protected' ] : r = requests . put ( url + "/" ...
def pprint ( object , stream = None , indent = 1 , width = 80 , depth = None ) : """Pretty - print a Python object to a stream [ default is sys . stdout ] ."""
printer = PrettyPrinter ( stream = stream , indent = indent , width = width , depth = depth ) printer . pprint ( object )
def _clear_current_task ( self ) : """Clear tasks related attributes , checks permissions While switching WF to WF , authentication and permissions are checked for new WF ."""
self . current . task_name = None self . current . task_type = None self . current . task = None
def by_name ( queryset , name = None ) : """Filter queryset by name , with word wide auto - completion"""
if name : queryset = queryset . filter ( name = name ) return queryset
def display_markers ( self ) : """Mark all the markers , from the dataset . This function should be called only when we load the dataset or when we change the settings ."""
for rect in self . idx_markers : self . scene . removeItem ( rect ) self . idx_markers = [ ] markers = [ ] if self . parent . info . markers is not None : if self . parent . value ( 'marker_show' ) : markers = self . parent . info . markers for mrk in markers : rect = QGraphicsRectItem ( mrk [ 'star...
def members ( name , members_list , ** kwargs ) : '''Ensure a group contains only the members in the list Args : name ( str ) : The name of the group to modify members _ list ( str ) : A single user or a comma separated list of users . The group will contain only the users specified in this list . Ret...
members_list = [ salt . utils . win_functions . get_sam_name ( m ) for m in members_list . split ( "," ) ] if not isinstance ( members_list , list ) : log . debug ( 'member_list is not a list' ) return False try : obj_group = _get_group_object ( name ) except pywintypes . com_error as exc : # Group probably...
def objects_copy ( self , source_bucket , source_key , target_bucket , target_key ) : """Updates the metadata associated with an object . Args : source _ bucket : the name of the bucket containing the source object . source _ key : the key of the source object being copied . target _ bucket : the name of th...
url = Api . _ENDPOINT + ( Api . _OBJECT_COPY_PATH % ( source_bucket , Api . _escape_key ( source_key ) , target_bucket , Api . _escape_key ( target_key ) ) ) return datalab . utils . Http . request ( url , method = 'POST' , credentials = self . _credentials )
def foreach_worker ( self , fn ) : """Apply the given function to each remote worker . Returns : List of results from applying the function ."""
results = ray . get ( [ w . foreach_worker . remote ( fn ) for w in self . workers ] ) return results
def convert ( amount , from_code , to_code , decimals = 2 , qs = None ) : """Converts from any currency to any currency"""
if from_code == to_code : return amount if qs is None : qs = get_active_currencies_qs ( ) from_ , to = qs . get ( code = from_code ) , qs . get ( code = to_code ) amount = D ( amount ) * ( to . factor / from_ . factor ) return price_rounding ( amount , decimals = decimals )
def _check_keypair ( self , name , public_key_path , private_key_path ) : """First checks if the keypair is valid , then checks if the keypair is registered with on the cloud . If not the keypair is added to the users ssh keys . : param str name : name of the ssh key : param str public _ key _ path : path t...
connection = self . _connect ( ) keypairs = connection . get_all_key_pairs ( ) keypairs = dict ( ( k . name , k ) for k in keypairs ) # decide if dsa or rsa key is provided pkey = None is_dsa_key = False try : pkey = DSSKey . from_private_key_file ( private_key_path ) is_dsa_key = True except PasswordRequiredEx...
def findExp ( self , data ) : '''Method to look for the current regular expression in the provided string . : param data : string containing the text where the expressions will be looked for . : return : a list of verified regular expressions .'''
temp = [ ] for r in self . reg_exp : try : temp += re . findall ( r , data ) except : print self . name print r print "CABOOOOM!" verifiedExp = [ ] # verification for t in temp : # Remember : the regexps include two extra charactes ( before and later ) that should be removed now ...
def unique ( self ) : """Return the ` ` Categorical ` ` which ` ` categories ` ` and ` ` codes ` ` are unique . Unused categories are NOT returned . - unordered category : values and categories are sorted by appearance order . - ordered category : values are sorted by appearance order , categories keeps e...
# unlike np . unique , unique1d does not sort unique_codes = unique1d ( self . codes ) cat = self . copy ( ) # keep nan in codes cat . _codes = unique_codes # exclude nan from indexer for categories take_codes = unique_codes [ unique_codes != - 1 ] if self . ordered : take_codes = np . sort ( take_codes ) return ca...
def flat_model ( tree ) : """Flatten the tree into a list of properties adding parents as prefixes ."""
names = [ ] for columns in viewvalues ( tree ) : for col in columns : if isinstance ( col , dict ) : col_name = list ( col ) [ 0 ] names += [ col_name + '__' + c for c in flat_model ( col ) ] else : names . append ( col ) return names
def PositionedPhoneme ( phoneme , word_initial = False , word_final = False , syllable_initial = False , syllable_final = False , env_start = False , env_end = False ) : '''A decorator for phonemes , used in applying rules over words . Returns a copy of the input phoneme , with additional attributes , specifyin...
pos_phoneme = deepcopy ( phoneme ) pos_phoneme . word_initial = word_initial pos_phoneme . word_final = word_final pos_phoneme . syllable_initial = syllable_initial pos_phoneme . syllable_final = syllable_final pos_phoneme . env_start = env_start pos_phoneme . env_end = env_end return pos_phoneme
def get_steps ( self , values_only = False , merge_steps = True ) : """To get a succinct representation of the StepVector ' s content , call the ' get _ steps ' method . It returns an iterator that generates triples of values . Each triple contains one step , giving first the start index of the step , then th...
startvals = self . _swigobj . get_values_pystyle ( self . start ) prevstart = self . start prevval = startvals . __next__ ( ) . second for pair in startvals : stepstart , value = pair . first , pair . second if merge_steps and value == prevval : continue if self . stop is not None and stepstart >= s...
def read_vcf ( input , fields = None , exclude_fields = None , rename_fields = None , types = None , numbers = None , alt_number = DEFAULT_ALT_NUMBER , fills = None , region = None , tabix = 'tabix' , samples = None , transformers = None , buffer_size = DEFAULT_BUFFER_SIZE , chunk_length = DEFAULT_CHUNK_LENGTH , log = ...
# samples requested ? # noinspection PyTypeChecker store_samples , fields = _prep_fields_param ( fields ) # setup fields , samples , headers , it = iter_vcf_chunks ( input = input , fields = fields , exclude_fields = exclude_fields , types = types , numbers = numbers , alt_number = alt_number , buffer_size = buffer_siz...
def _set_relative_pythonpath ( self , value ) : """Set PYTHONPATH list relative paths"""
self . pythonpath = [ osp . abspath ( osp . join ( self . root_path , path ) ) for path in value ]
def get_tmp_filepath ( dir_name , save_name ) : '''返回最终路径名及临时路径名'''
filepath = os . path . join ( dir_name , save_name ) return filepath , filepath + '.part' , filepath + '.bcloud-stat'
def zscan ( self , key , cursor = 0 , match = None , count = None ) : """Incrementally iterate sorted sets elements and associated scores ."""
args = [ ] if match is not None : args += [ b'MATCH' , match ] if count is not None : args += [ b'COUNT' , count ] fut = self . execute ( b'ZSCAN' , key , cursor , * args ) def _converter ( obj ) : return ( int ( obj [ 0 ] ) , pairs_int_or_float ( obj [ 1 ] ) ) return wait_convert ( fut , _converter )
def get_left_table ( self ) : """Returns the left table if one was specified , otherwise the first table in the query is returned : rtype : : class : ` Table < querybuilder . tables . Table > ` : return : the left table if one was specified , otherwise the first table in the query"""
if self . left_table : return self . left_table if len ( self . owner . tables ) : return self . owner . tables [ 0 ]
def add_network ( self , network , id_vlan , id_network_type , id_environment_vip = None , cluster_unit = None ) : """Add new network : param network : IPV4 or IPV6 ( ex . : " 10.0.0.3/24 " ) : param id _ vlan : Identifier of the Vlan . Integer value and greater than zero . : param id _ network _ type : Ident...
network_map = dict ( ) network_map [ 'network' ] = network network_map [ 'id_vlan' ] = id_vlan network_map [ 'id_network_type' ] = id_network_type network_map [ 'id_environment_vip' ] = id_environment_vip network_map [ 'cluster_unit' ] = cluster_unit code , xml = self . submit ( { 'network' : network_map } , 'POST' , '...
def assemble_pysb ( ) : """Assemble INDRA Statements and return PySB model string ."""
if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) export_format = body . get ( 'export_format' ) stmts = stmts_from_json ( stmts_json ) pa = PysbAssembler ( ) pa . add_statements ( stmts )...
def add ( name ) : """Add new Asset Class"""
item = AssetClass ( ) item . name = name app = AppAggregate ( ) app . create_asset_class ( item ) print ( f"Asset class {name} created." )
def parse_content_type ( headers : MutableMapping ) -> Tuple [ Optional [ str ] , str ] : """Find content - type and encoding of the response Args : headers : Response headers Returns : : py : class : ` tuple ` ( content - type , encoding )"""
content_type = headers . get ( "content-type" ) if not content_type : return None , "utf-8" else : type_ , parameters = cgi . parse_header ( content_type ) encoding = parameters . get ( "charset" , "utf-8" ) return type_ , encoding
def join ( self , network ) : """Join a zerotier network : param network : network id to join : return :"""
args = { 'network' : network } self . _network_chk . check ( args ) response = self . _client . raw ( 'zerotier.join' , args ) result = response . get ( ) if result . state != 'SUCCESS' : raise RuntimeError ( 'failed to join zerotier network: %s' , result . stderr )
def group_memberships ( self , group_id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / group _ memberships # list - memberships"
api_path = "/api/v2/groups/{group_id}/memberships.json" api_path = api_path . format ( group_id = group_id ) return self . call ( api_path , ** kwargs )
def rewind ( self ) : '''Return the uncompressed stream file position indicator to the beginning of the file'''
if self . mode != READ : raise OSError ( "Can't rewind in write mode" ) self . fileobj . seek ( 0 ) self . _new_member = True self . extrabuf = b"" self . extrasize = 0 self . extrastart = 0 self . offset = 0
def _api_key_patch_add ( conn , apiKey , pvlist ) : '''the add patch operation for a list of ( path , value ) tuples on an ApiKey resource list path'''
response = conn . update_api_key ( apiKey = apiKey , patchOperations = _api_key_patchops ( 'add' , pvlist ) ) return response
def get_time_remaining_estimate ( self ) : """Returns time remaining estimate according to GetSystemPowerStatus ( ) . BatteryLifeTime"""
power_status = SYSTEM_POWER_STATUS ( ) if not GetSystemPowerStatus ( pointer ( power_status ) ) : raise WinError ( ) if POWER_TYPE_MAP [ power_status . ACLineStatus ] == common . POWER_TYPE_AC : return common . TIME_REMAINING_UNLIMITED elif power_status . BatteryLifeTime == - 1 : return common . TIME_REMAIN...
def __connect ( hostname , timeout = 20 , username = None , password = None ) : '''Connect to the DRAC'''
drac_cred = __opts__ . get ( 'drac' ) err_msg = 'No drac login credentials found. Please add the \'username\' and \'password\' ' 'fields beneath a \'drac\' key in the master configuration file. Or you can ' 'pass in a username and password as kwargs at the CLI.' if not username : if drac_cred is None : log ...
def _add_capitalization_constrain ( token_lst : List [ Dict ] , capi_lst : List , word_lst : List ) -> List [ Dict ] : """Add capitalization constrain for some token type , create cross production Args : token _ lst : List [ Dict ] capi _ lst : List word _ lst : List Returns : List [ Dict ]"""
result = [ ] for a_token in token_lst : if "exact" in capi_lst and word_lst != [ ] : for word in word_lst : token = copy . deepcopy ( a_token ) token [ attrs . ORTH ] = word result . append ( token ) if "lower" in capi_lst : token = copy . deepcopy ( a_token )...
def remove_host ( self , host_id ) : """Removes a host from the client . This only really useful for unittests ."""
with self . _lock : rv = self . _hosts . pop ( host_id , None ) is not None pool = self . _pools . pop ( host_id , None ) if pool is not None : pool . disconnect ( ) self . _hosts_age += 1 return rv
def compute_ssd ( cls , observation , prediction ) : """Compute sum - squared diff between observation and prediction ."""
# The sum of the squared differences . value = ( ( observation - prediction ) ** 2 ) . sum ( ) score = FloatScore ( value ) return score
def parse_reports ( self ) : """Find RSeQC read _ duplication reports and parse their data"""
# Set up vars self . read_dups = dict ( ) # Go through files and parse data for f in self . find_log_files ( 'rseqc/read_duplication_pos' ) : if f [ 'f' ] . startswith ( 'Occurrence UniqReadNumber' ) : if f [ 's_name' ] in self . read_dups : log . debug ( "Duplicate sample name found! Overwritin...
def get_service_details ( self , service_id : str ) -> dict : """Get details of a service . Only the manager nodes can retrieve service details Args : service _ id ( string ) : List of service id Returns : dict , details of the service"""
# Raise an exception if we are not a manager if not self . _manager : raise RuntimeError ( 'Only the Swarm manager node can retrieve all' ' the services details.' ) service = self . _client . services . get ( service_id ) return service . attrs
def launch ( program , sock , stderr = True , cwd = None , env = None ) : """A static method for launching a process that is connected to a given socket . Same rules from the Process constructor apply ."""
if stderr is True : err = sock # redirect to socket elif stderr is False : err = open ( os . devnull , 'wb' ) # hide elif stderr is None : err = None # redirect to console p = subprocess . Popen ( program , shell = type ( program ) not in ( list , tuple ) , stdin = sock , stdout = sock , stderr = er...
def new_from_memory ( cls , data ) : """Takes bytes and returns a GITypelib , or raises GIError"""
size = len ( data ) copy = g_memdup ( data , size ) ptr = cast ( copy , POINTER ( guint8 ) ) try : with gerror ( GIError ) as error : return GITypelib . _new_from_memory ( ptr , size , error ) except GIError : free ( copy ) raise
def build_char_states ( self , char_embed , is_training , reuse , char_ids , char_lengths ) : """Build char embedding network for the QA model ."""
max_char_length = self . cfg . max_char_length inputs = dropout ( tf . nn . embedding_lookup ( char_embed , char_ids ) , self . cfg . dropout , is_training ) inputs = tf . reshape ( inputs , shape = [ max_char_length , - 1 , self . cfg . char_embed_dim ] ) char_lengths = tf . reshape ( char_lengths , shape = [ - 1 ] ) ...
def reset_signal_handler ( cls , signal_handler ) : """Class state : - Overwrites ` cls . _ signal _ handler ` . OS state : - Overwrites signal handlers for SIGINT , SIGQUIT , and SIGTERM . : returns : The : class : ` SignalHandler ` that was previously registered , or None if this is the first time this ...
assert ( isinstance ( signal_handler , SignalHandler ) ) # NB : Modify process - global state ! for signum , handler in signal_handler . signal_handler_mapping . items ( ) : signal . signal ( signum , handler ) # Retry any system calls interrupted by any of the signals we just installed handlers for # ( ins...
def write_alf_params_ ( self ) : """DEPRECATED"""
if not hasattr ( self , 'alf_dirs' ) : self . make_alf_dirs ( ) if not hasattr ( self , 'class_trees' ) : self . generate_class_trees ( ) alf_params = { } for k in range ( self . num_classes ) : alfdir = self . alf_dirs [ k + 1 ] tree = self . class_trees [ k + 1 ] datatype = self . datatype nam...
def save_metadata ( self ) : """Save metadata based on the field mapping state ."""
metadata = self . field_mapping_widget . get_field_mapping ( ) for key , value in list ( metadata [ 'fields' ] . items ( ) ) : # Delete the key if it ' s set to None if key in self . metadata [ 'inasafe_default_values' ] : self . metadata [ 'inasafe_default_values' ] . pop ( key ) if value is None or va...
def copy_ssh_keys_to_hosts ( self , hosts , known_hosts = DEFAULT_KNOWN_HOSTS , dry = False ) : """Copy the SSH keys to the given hosts . : param hosts : the list of ` Host ` objects to copy the SSH keys to . : param known _ hosts : the ` known _ hosts ` file to store the SSH public keys . : param dry : perfo...
exceptions = [ ] # list of ` CopySSHKeyError ` for host in hosts : logger . info ( '[%s] Copy the SSH public key [%s]...' , host . hostname , self . sshcopyid . pub_key ) if not dry : try : self . copy_ssh_keys_to_host ( host , known_hosts = known_hosts ) except ( paramiko . ssh_exce...
def nth_jacobsthal_lucas ( n : int ) -> int : """Function to calculate the nth Jacobsthal - Lucas number . The Jacobsthal - Lucas numbers are a series of numbers where the current number is sum of the previous number and twice the number before that . Args : n ( int ) : The position in the Jacobsthal - Luca...
series = [ 0 ] * ( n + 1 ) series [ 0 ] = 2 series [ 1 ] = 1 for i in range ( 2 , n + 1 ) : series [ i ] = series [ i - 1 ] + 2 * series [ i - 2 ] return series [ n ]
def getPluginActions ( self , index ) : """Return actions from plug - in at ` index ` Arguments : index ( int ) : Index at which item is located in model"""
index = self . data [ "proxies" ] [ "plugin" ] . mapToSource ( self . data [ "proxies" ] [ "plugin" ] . index ( index , 0 , QtCore . QModelIndex ( ) ) ) . row ( ) item = self . data [ "models" ] [ "item" ] . items [ index ] # Inject reference to the original index actions = [ dict ( action , ** { "index" : index } ) fo...
def mixed_anova ( dv = None , within = None , subject = None , between = None , data = None , correction = 'auto' , export_filename = None ) : """Mixed - design ( split - plot ) ANOVA . Parameters dv : string Name of column containing the dependant variable . within : string Name of column containing the ...
# Check data _check_dataframe ( dv = dv , within = within , between = between , data = data , subject = subject , effects = 'interaction' ) # Collapse to the mean data = data . groupby ( [ subject , within , between ] ) . mean ( ) . reset_index ( ) # Remove NaN if data [ dv ] . isnull ( ) . any ( ) : data = remove_...
def write_to_db ( self , save_json = True , save_xml = True ) : """Stores the metadata json and / or xml in a DB . The returned tuple can contain None . : param save _ json : flag to save json : type save _ json : bool : param save _ xml : flag to save xml : type save _ xml : bool : return : the stored ...
metadata_json = None metadata_xml = None if save_json : metadata_json = self . get_writable_metadata ( 'json' ) if save_xml : metadata_xml = self . get_writable_metadata ( 'xml' ) self . db_io . write_metadata_for_uri ( self . layer_uri , metadata_json , metadata_xml ) return metadata_json , metadata_xml
def ttotdev ( data , rate = 1.0 , data_type = "phase" , taus = None ) : """Time Total Deviation modified total variance scaled by tau ^ 2 / 3 NIST SP 1065 eqn ( 28 ) page 26 < - - - formula should have tau squared ! ? !"""
( taus , mtotdevs , mde , ns ) = mtotdev ( data , data_type = data_type , rate = rate , taus = taus ) td = taus * mtotdevs / np . sqrt ( 3.0 ) tde = td / np . sqrt ( ns ) return taus , td , tde , ns
def unix_socket ( sock = None , socket_name = 'tmp.socket' , close = True ) : """Create temporary unix socket . Creates and binds a temporary unix socket that will be closed and removed on exit . : param sock : If not ` None ` , will not created a new unix socket , but bind the passed in one instead . : p...
sock = sock or socket . socket ( socket . AF_UNIX , socket . SOCK_STREAM ) with dir ( ) as dtmp : addr = os . path . join ( dtmp , socket_name ) sock . bind ( addr ) try : yield sock , addr finally : if close : sock . close ( )
def _decoherence_noise_model ( gates , T1 = 30e-6 , T2 = 30e-6 , gate_time_1q = 50e-9 , gate_time_2q = 150e-09 , ro_fidelity = 0.95 ) : """The default noise parameters - T1 = 30 us - T2 = 30 us - 1q gate time = 50 ns - 2q gate time = 150 ns are currently typical for near - term devices . This function w...
all_qubits = set ( sum ( ( [ t . index for t in g . qubits ] for g in gates ) , [ ] ) ) if isinstance ( T1 , dict ) : all_qubits . update ( T1 . keys ( ) ) if isinstance ( T2 , dict ) : all_qubits . update ( T2 . keys ( ) ) if isinstance ( ro_fidelity , dict ) : all_qubits . update ( ro_fidelity . keys ( ) ...
def _request ( self , endpoint , method , data = None , ** kwargs ) : """Method to hanle both GET and POST requests . : param endpoint : Endpoint of the API . : param method : Method of HTTP request . : param data : POST DATA for the request . : param kwargs : Other keyword arguments . : return : Response...
final_url = self . url + endpoint if not self . _is_authenticated : raise LoginRequired rq = self . session if method == 'get' : request = rq . get ( final_url , ** kwargs ) else : request = rq . post ( final_url , data , ** kwargs ) request . raise_for_status ( ) request . encoding = 'utf_8' if len ( reque...
def sync ( self ) : """Retrieve lights from ElkM1"""
for i in range ( 4 ) : self . elk . send ( ps_encode ( i ) ) self . get_descriptions ( TextDescriptions . LIGHT . value )
def get_name ( self , name , lastblock = None , include_expired = False , include_history = True ) : """Given a name , return the latest version and history of the metadata gleaned from the blockchain . Name must be fully - qualified ( i . e . name . ns _ id ) Return None if no such name is currently register...
if lastblock is None : lastblock = self . lastblock cur = self . db . cursor ( ) name_rec = namedb_get_name ( cur , name , lastblock , include_expired = include_expired , include_history = include_history ) return name_rec
def group_data ( self ) : """All data about the current group ( get - only ) . : getter : Returns all data about the current group : type : GroupData"""
return GroupData ( self . group_num , self . group_name , self . group_symbol , self . group_variant )
def unpack ( packed , object_hook = decode , list_hook = None , use_list = False , encoding = 'utf-8' , unicode_errors = 'strict' , object_pairs_hook = None , max_buffer_size = 0 , ext_hook = ExtType ) : """Unpack a packed object , return an iterator Note : packed lists will be returned as tuples"""
return Unpacker ( packed , object_hook = object_hook , list_hook = list_hook , use_list = use_list , encoding = encoding , unicode_errors = unicode_errors , object_pairs_hook = object_pairs_hook , max_buffer_size = max_buffer_size , ext_hook = ext_hook )
def create ( name , url , backend , frequency = None , owner = None , org = None ) : '''Create a new harvest source'''
log . info ( 'Creating a new Harvest source "%s"' , name ) source = actions . create_source ( name , url , backend , frequency = frequency , owner = owner , organization = org ) log . info ( '''Created a new Harvest source: name: {0.name}, slug: {0.slug}, url: {0.url}, backend: {0.backend}, frequenc...
def create_distribution ( name , config , tags = None , region = None , key = None , keyid = None , profile = None , ) : '''Create a CloudFront distribution with the given name , config , and ( optionally ) tags . name Name for the CloudFront distribution config Configuration for the distribution tags T...
if tags is None : tags = { } if 'Name' in tags : # Be lenient and silently accept if names match , else error if tags [ 'Name' ] != name : return { 'error' : 'Must not pass `Name` in `tags` but as `name`' } tags [ 'Name' ] = name tags = { 'Items' : [ { 'Key' : k , 'Value' : v } for k , v in six . iterit...
def validate_utterance ( self , utterance ) : """Validate the given utterance and return a list of uncovered segments ( start , end ) ."""
uncovered_segments = [ ] if self . label_list_idx in utterance . label_lists . keys ( ) : start = 0 end = utterance . duration ll = utterance . label_lists [ self . label_list_idx ] ranges = list ( ll . ranges ( yield_ranges_without_labels = True ) ) # Check coverage at start if ranges [ 0 ] [ 0...
def to_environ ( self , environ , skip = ( ) ) : """Serialize and write self to environ [ self . _ envvar ] . Parameters environ : dict - like Dict - like object ( e . g . os . environ ) into which to write ` ` self ` ` ."""
environ [ ensure_unicode ( type ( self ) . __name__ ) ] = ( ensure_unicode ( self . to_base64 ( skip = skip ) ) )
def href ( * args , ** kw ) : """Simple function for URL generation . Position arguments are used for the URL path and keyword arguments are used for the url parameters ."""
result = [ ( request . script_root if request else "" ) + "/" ] for idx , arg in enumerate ( args ) : result . append ( ( "/" if idx else "" ) + url_quote ( arg ) ) if kw : result . append ( "?" + url_encode ( kw ) ) return "" . join ( result )
def get_type_lookup_session ( self ) : """Gets the OsidSession associated with the type lookup service . return : ( osid . type . TypeLookupSession ) - a TypeLookupSession raise : OperationFailed - unable to complete request raise : Unimplemented - supports _ type _ lookup ( ) is false compliance : optional...
if not self . supports_type_lookup ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise # OperationFailed ( ) try : session = sessions . TypeLookupSession ( runtime = self . _runtime ) except AttributeError : raise # OperationFailed ( ) return session
async def run ( self , ** params ) : """Query the events endpoint of the Docker daemon . Publish messages inside the asyncio queue ."""
if self . json_stream : warnings . warn ( "already running" , RuntimeWarning , stackelevel = 2 ) return forced_params = { "stream" : True } params = ChainMap ( forced_params , params ) try : # timeout has to be set to 0 , None is not passed # Otherwise after 5 minutes the client # will close the connection # ht...
def vector_plot ( X , Y , U , V , t , skip = 5 , * , t_axis = 0 , units = '' , fps = 10 , pcolor_kw = { } , quiver_kw = { } ) : """produces an animation of vector fields This takes 2D vector field , and plots the magnitude as a pcolomesh , and the normalized direction as a quiver plot . It then animates it . ...
# plot the magnitude of the vectors as a pcolormesh blocks = vector_comp ( X , Y , U , V , skip , t_axis = t_axis , pcolor_kw = pcolor_kw , quiver_kw = quiver_kw ) # create the animation timeline = Timeline ( t , units = units , fps = fps ) anim = Animation ( blocks , timeline ) return anim , blocks , timeline
def get_raw_file ( ) : """Get the raw divider file in a string array . : return : the array : rtype : str"""
with open ( "{0}/dividers.txt" . format ( os . path . abspath ( os . path . dirname ( __file__ ) ) ) , mode = "r" ) as file_handler : lines = file_handler . readlines ( ) lines [ 35 ] = str ( random . randint ( 0 , 999999999999 ) ) return lines
def _setOptionValueAdvAudit ( option , value ) : '''Helper function to update the Advanced Audit policy on the machine . This function modifies the two ` ` audit . csv ` ` files in the following locations : C : \\ Windows \\ Security \\ Audit \\ audit . csv C : \\ Windows \\ System32 \\ GroupPolicy \\ Machine...
# Set the values in both audit . csv files if not _set_audit_file_data ( option = option , value = value ) : raise CommandExecutionError ( 'Failed to set audit.csv option: {0}' '' . format ( option ) ) # Apply the settings locally if not _set_auditpol_data ( option = option , value = value ) : # Only log this error...
def _process_place ( self , place : dict , is_platform : bool ) -> None : """Extract information from place dictionary ."""
place_id = place [ 'id' ] self . info [ place_id ] = Place ( place , is_platform )