signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def insert ( self ) :
"""Insert this document""" | from mongoframes . queries import to_refs
# Send insert signal
signal ( 'insert' ) . send ( self . __class__ , frames = [ self ] )
# Prepare the document to be inserted
document = to_refs ( self . _document )
# Insert the document and update the Id
self . _id = self . get_collection ( ) . insert_one ( document ) . inse... |
def _decode_v2 ( value ) :
"""Decode ' : ' and ' $ ' characters encoded by ` _ encode ` .""" | if re . search ( r'(?<!\$):' , value ) :
raise ValueError ( "Unescaped ':' in the encoded string" )
decode_colons = value . replace ( '$:' , ':' )
if re . search ( r'(?<!\$)(\$\$)*\$([^$]|\Z)' , decode_colons ) :
raise ValueError ( "Unescaped '$' in encoded string" )
return decode_colons . replace ( '$$' , '$' ... |
def save ( obj , path ) :
"""Pickle ( serialize ) object to input file path
Parameters
obj : any object
path : string
File path""" | with open ( path , 'wb' ) as f :
try :
pickle . dump ( obj , f , protocol = pickle . HIGHEST_PROTOCOL )
except Exception as e :
print ( 'Pickling failed for object {0}, path {1}' . format ( obj , path ) )
print ( 'Error message: {0}' . format ( e ) ) |
def isSequence ( arg ) :
"""Check if input is iterable .""" | if hasattr ( arg , "strip" ) :
return False
if hasattr ( arg , "__getslice__" ) :
return True
if hasattr ( arg , "__iter__" ) :
return True
return False |
def to_paginated_list ( self , result , _ns , _operation , ** kwargs ) :
"""Convert a controller result to a paginated list .
The result format is assumed to meet the contract of this page class ' s ` parse _ result ` function .""" | items , context = self . parse_result ( result )
headers = dict ( )
paginated_list = PaginatedList ( items = items , _page = self , _ns = _ns , _operation = _operation , _context = context , )
return paginated_list , headers |
def _set_show_mpls_ldp_statistics ( self , v , load = False ) :
"""Setter method for show _ mpls _ ldp _ statistics , mapped from YANG variable / brocade _ mpls _ rpc / show _ mpls _ ldp _ statistics ( rpc )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ show _ mpls _ ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = show_mpls_ldp_statistics . show_mpls_ldp_statistics , is_leaf = True , yang_name = "show-mpls-ldp-statistics" , rest_name = "show-mpls-ldp-statistics" , parent = self , path_helper = self . _path_helper , extmethods = self . ... |
def create_node ( self , network , participant ) :
"""Create a node for a participant .""" | return self . models . MCMCPAgent ( network = network , participant = participant ) |
def _get_banner ( ) :
"""Return a banner message for the interactive console .""" | result = ''
result += '\nPython %s' % _sys . version
result += '\n\nWbemcli interactive shell'
result += '\n%s' % _get_connection_info ( )
# Give hint about exiting . Most people exit with ' quit ( ) ' which will
# not return from the interact ( ) method , and thus will not write
# the history .
if _sys . platform == '... |
def make_catalogs_backup ( catalogs , local_catalogs_dir = "" , include_metadata = True , include_data = True , include_metadata_xlsx = False , use_short_path = False ) :
"""Realiza una copia local de los datos y metadatos de un catálogo .
Args :
catalogs ( list or dict ) : Lista de catálogos ( elementos que ... | if isinstance ( catalogs , list ) :
for catalog in catalogs :
try :
make_catalog_backup ( catalog , local_catalogs_dir = local_catalogs_dir , include_metadata = include_metadata , include_metadata_xlsx = include_metadata_xlsx , include_data = include_data , use_short_path = use_short_path )
... |
def create_job ( batch_service_client , job_id , pool_id ) :
"""Creates a job with the specified ID , associated with the specified pool .
: param batch _ service _ client : A Batch service client .
: type batch _ service _ client : ` azure . batch . BatchServiceClient `
: param str job _ id : The ID for the ... | print ( 'Creating job [{}]...' . format ( job_id ) )
job = batch . models . JobAddParameter ( id = job_id , pool_info = batch . models . PoolInformation ( pool_id = pool_id ) )
try :
batch_service_client . job . add ( job )
except batchmodels . batch_error . BatchErrorException as err :
print_batch_exception ( ... |
def create_ikepolicy ( name , profile = None , ** kwargs ) :
'''Creates a new IKEPolicy
CLI Example :
. . code - block : : bash
salt ' * ' neutron . create _ ikepolicy ikepolicy - name
phase1 _ negotiation _ mode = main auth _ algorithm = sha1
encryption _ algorithm = aes - 128 pfs = group5
: param name... | conn = _auth ( profile )
return conn . create_ikepolicy ( name , ** kwargs ) |
def _list_distributions ( conn , name = None , region = None , key = None , keyid = None , profile = None , ) :
'''Private function that returns an iterator over all CloudFront distributions .
The caller is responsible for all boto - related error handling .
name
( Optional ) Only yield the distribution with ... | for dl_ in conn . get_paginator ( 'list_distributions' ) . paginate ( ) :
distribution_list = dl_ [ 'DistributionList' ]
if 'Items' not in distribution_list : # If there are no items , AWS omits the ` Items ` key for some reason
continue
for partial_dist in distribution_list [ 'Items' ] :
ta... |
def _get_perez_coefficients ( perezmodel ) :
'''Find coefficients for the Perez model
Parameters
perezmodel : string ( optional , default = ' allsitescomposite1990 ' )
a character string which selects the desired set of Perez
coefficients . If model is not provided as an input , the default ,
'1990 ' will... | coeffdict = { 'allsitescomposite1990' : [ [ - 0.0080 , 0.5880 , - 0.0620 , - 0.0600 , 0.0720 , - 0.0220 ] , [ 0.1300 , 0.6830 , - 0.1510 , - 0.0190 , 0.0660 , - 0.0290 ] , [ 0.3300 , 0.4870 , - 0.2210 , 0.0550 , - 0.0640 , - 0.0260 ] , [ 0.5680 , 0.1870 , - 0.2950 , 0.1090 , - 0.1520 , - 0.0140 ] , [ 0.8730 , - 0.3920 ... |
def copy_heroku_to_local ( id ) :
"""Copy a Heroku database locally .""" | heroku_app = HerokuApp ( dallinger_uid = id )
try :
subprocess . call ( [ "dropdb" , heroku_app . name ] )
except Exception :
pass
heroku_app . pg_pull ( ) |
def assert_json_subset ( first , second ) :
"""Assert that a JSON object or array is a subset of another JSON object
or array .
The first JSON object or array must be supplied as a JSON - compatible
dict or list , the JSON object or array to check must be a string , an
UTF - 8 bytes object , or a JSON - com... | if not isinstance ( second , ( dict , list , str , bytes ) ) :
raise TypeError ( "second must be dict, list, str, or bytes" )
if isinstance ( second , bytes ) :
second = second . decode ( "utf-8" )
if isinstance ( second , _Str ) :
parsed_second = json_loads ( second )
else :
parsed_second = second
if n... |
def get_imports ( fname ) :
"""get a list of imports from a Python program""" | txt = ''
with open ( fname , 'r' ) as f :
for line in f :
if line [ 0 : 6 ] == 'import' :
txt += '<PRE>' + strip_text_after_string ( line [ 7 : ] , ' as ' ) + '</PRE>\n'
return txt + '<BR>' |
def _Rzderiv ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ Rzderiv
PURPOSE :
evaluate the mixed R , z derivative for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
d2phi / dR / dz
HISTORY :
2013-08-28 - Written - Bovy ( I... | Rz = R ** 2. + z ** 2.
sqrtRz = numpy . sqrt ( Rz )
return - R * z * ( - 4. * Rz - 3. * self . a * sqrtRz + 3. * ( self . a ** 2. + Rz + 2. * self . a * sqrtRz ) * numpy . log ( 1. + sqrtRz / self . a ) ) * Rz ** - 2.5 * ( self . a + sqrtRz ) ** - 2. |
def eliminate_repeats ( text ) :
'''Returns a list of words that occur in the text . Eliminates stopwords .''' | bannedwords = read_file ( 'stopwords.txt' )
alphabet = 'abcdefghijklmnopqrstuvwxyz'
words = text . split ( )
standardwords = [ ]
for word in words :
newstr = ''
for char in word :
if char in alphabet or char in alphabet . upper ( ) :
newstr += char
if newstr not in standardwords and news... |
def trainClassifier ( self ) :
"""Self - consistently train the classifier""" | self . loadPopulationMetadata ( )
self . loadSimResults ( )
cut_geometry , flags_geometry = self . applyGeometry ( self . data_population [ 'RA' ] , self . data_population [ 'DEC' ] )
cut_detect_sim_results_sig = ( np . logical_or ( np . logical_and ( self . data_sim [ 'SIG' ] >= self . config [ self . algorithm ] [ 's... |
def parseTlvProperties ( response ) :
"""return the GET _ TLV _ PROPERTIES structure
@ param response : result of L { FEATURE _ GET _ TLV _ PROPERTIES }
@ rtype : dict
@ return : a dict""" | d = { 'raw' : response , }
# create a new list to consume it
tmp = list ( response )
while tmp :
tag = tmp [ 0 ]
len = tmp [ 1 ]
data = tmp [ 2 : 2 + len ]
if PCSCv2_PART10_PROPERTY_sFirmwareID == tag : # convert to a string
data = "" . join ( [ chr ( c ) for c in data ] )
# we now suppose t... |
def node_conv ( obj ) :
"""This is the " string conversion " routine that we have our substitutions
use to return Nodes , not strings . This relies on the fact that an
EntryProxy object has a get ( ) method that returns the underlying
Node that it wraps , which is a bit of architectural dependence
that we m... | try :
get = obj . get
except AttributeError :
if isinstance ( obj , SCons . Node . Node ) or SCons . Util . is_Sequence ( obj ) :
result = obj
else :
result = str ( obj )
else :
result = get ( )
return result |
def get_levels_and_coordinates_names ( self ) :
"""Get the current level of the high level mean plot and the name of
the corrisponding site , study , etc . As well as the code for the
current coordinate system .
Returns
( high _ level _ type , high _ level _ name , coordinate _ system ) : tuple object
con... | if self . COORDINATE_SYSTEM == "geographic" :
dirtype = 'DA-DIR-GEO'
elif self . COORDINATE_SYSTEM == "tilt-corrected" :
dirtype = 'DA-DIR-TILT'
else :
dirtype = 'DA-DIR'
if self . level_box . GetValue ( ) == 'sample' :
high_level_type = 'samples'
if self . level_box . GetValue ( ) == 'site' :
high_... |
def urls ( self ) :
"Returns a list of ( value , URL ) tuples ." | # First , check the urls ( ) method for each plugin .
plugin_urls = [ ]
for plugin_name , plugin in self . model . model_databrowse ( ) . plugins . items ( ) :
urls = plugin . urls ( plugin_name , self )
if urls is not None : # plugin _ urls . append ( urls )
values = self . values ( )
return zi... |
def fromJSON ( value ) :
"""loads the GP object from a JSON string""" | j = json . loads ( value )
v = GPLinearUnit ( )
if "defaultValue" in j :
v . value = j [ 'defaultValue' ]
else :
v . value = j [ 'value' ]
if 'paramName' in j :
v . paramName = j [ 'paramName' ]
elif 'name' in j :
v . paramName = j [ 'name' ]
return v |
def get_config_values ( config_path , section , default = 'default' ) :
"""Parse ini config file and return a dict of values .
The provided section overrides any values in default section .""" | values = { }
if not os . path . isfile ( config_path ) :
raise IpaUtilsException ( 'Config file not found: %s' % config_path )
config = configparser . ConfigParser ( )
try :
config . read ( config_path )
except Exception :
raise IpaUtilsException ( 'Config file format invalid.' )
try :
values . update (... |
def _counts_to_coverages ( sample_data , counts_in_1x ) :
"""If the user specified read length and genome size in the config ,
convert the raw counts / bases into the depth of coverage .""" | if not counts_in_1x :
return { None : None }
return OrderedDict ( ( _count_to_coverage ( x , counts_in_1x ) , _count_to_coverage ( y , counts_in_1x ) ) for x , y in sample_data . items ( ) ) |
def _verifyHostKey ( self , hostKey , fingerprint ) :
"""Called when ssh transport requests us to verify a given host key .
Return a deferred that callback if we accept the key or errback if we
decide to reject it .""" | if fingerprint in self . knownHosts :
return defer . succeed ( True )
return defer . fail ( UnknownHostKey ( hostKey , fingerprint ) ) |
def transaction_location_id ( self , transaction_location_id ) :
"""Sets the transaction _ location _ id of this AdditionalRecipientReceivableRefund .
The ID of the location that created the receivable . This is the location ID on the associated transaction .
: param transaction _ location _ id : The transactio... | if transaction_location_id is None :
raise ValueError ( "Invalid value for `transaction_location_id`, must not be `None`" )
if len ( transaction_location_id ) < 1 :
raise ValueError ( "Invalid value for `transaction_location_id`, length must be greater than or equal to `1`" )
self . _transaction_location_id = t... |
def vector ( x , y = None , z = 0.0 ) :
"""Return a 3D numpy array representing a vector ( of type ` numpy . float64 ` ) .
If ` y ` is ` ` None ` ` , assume input is already in the form ` [ x , y , z ] ` .""" | if y is None : # assume x is already [ x , y , z ]
return np . array ( x , dtype = np . float64 )
return np . array ( [ x , y , z ] , dtype = np . float64 ) |
def find_request ( ) :
'''Inspect running environment for request object . There should be one ,
but don ' t rely on it .''' | frame = inspect . currentframe ( )
request = None
f = frame
while not request and f :
if 'request' in f . f_locals and isinstance ( f . f_locals [ 'request' ] , HttpRequest ) :
request = f . f_locals [ 'request' ]
f = f . f_back
del frame
return request |
def get_auth_token_login_url ( self , auth_token_ticket , authenticator , private_key , service_url , username , ) :
'''Build an auth token login URL .
See https : / / github . com / rbCAS / CASino / wiki / Auth - Token - Login for details .''' | auth_token , auth_token_signature = self . _build_auth_token_data ( auth_token_ticket , authenticator , private_key , username = username , )
logging . debug ( '[CAS] AuthToken: {}' . format ( auth_token ) )
url = self . _get_auth_token_login_url ( auth_token = auth_token , auth_token_signature = auth_token_signature ,... |
def write_main_jobwrappers ( self ) :
'''Writes out ' jobs ' as wrapped toil objects in preparation for calling .
: return : A string representing this .''' | main_section = ''
# toil cannot technically start with multiple jobs , so an empty
# ' initialize _ jobs ' function is always called first to get around this
main_section = main_section + '\n job0 = Job.wrapJobFn(initialize_jobs)\n'
# declare each job in main as a wrapped toil function in order of priority
for w... |
def _convert_to ( maybe_device , convert_to ) :
'''Convert a device name , UUID or LABEL to a device name , UUID or
LABEL .
Return the fs _ spec required for fstab .''' | # Fast path . If we already have the information required , we can
# save one blkid call
if not convert_to or ( convert_to == 'device' and maybe_device . startswith ( '/' ) ) or maybe_device . startswith ( '{}=' . format ( convert_to . upper ( ) ) ) :
return maybe_device
# Get the device information
if maybe_device... |
def extract_js_links ( bs4 ) :
"""Extracting js links from BeautifulSoup object
: param bs4 : ` BeautifulSoup `
: return : ` list ` List of links""" | links = extract_links ( bs4 )
real_js = [ anchor for anchor in links if anchor . endswith ( ( '.js' , '.JS' ) ) ]
js_tags = [ anchor [ 'src' ] for anchor in bs4 . select ( 'script[type="text/javascript"]' ) if anchor . has_attr ( 'src' ) ]
return list ( set ( real_js + js_tags ) ) |
def add ( self , key , item ) :
"""Add a new key / item pair to the dictionary . Resets an existing
key value only if this is an exact match to a known key .""" | mmkeys = self . mmkeys
if mmkeys is not None and not ( key in self . data ) : # add abbreviations as short as minkeylength
# always add at least one entry ( even for key = " " )
lenkey = len ( key )
start = min ( self . minkeylength , lenkey )
# cache references to speed up loop a bit
mmkeysGet = mmkeys... |
def loadgrants ( source = None , setspec = None , all_grants = False ) :
"""Harvest grants from OpenAIRE .
: param source : Load the grants from a local sqlite db ( offline ) .
The value of the parameter should be a path to the local file .
: type source : str
: param setspec : Harvest specific set through ... | assert all_grants or setspec or source , "Either '--all', '--setspec' or '--source' is required parameter."
if all_grants :
harvest_all_openaire_projects . delay ( )
elif setspec :
click . echo ( "Remote grants loading sent to queue." )
harvest_openaire_projects . delay ( setspec = setspec )
else : # if sou... |
def create_cache ( directory , compress_level = 6 , value_type_is_binary = False , ** kwargs ) :
"""Create a html cache . Html string will be automatically compressed .
: param directory : path for the cache directory .
: param compress _ level : 0 ~ 9 , 9 is slowest and smallest .
: param kwargs : other argu... | cache = diskcache . Cache ( directory , disk = CompressedDisk , disk_compress_level = compress_level , disk_value_type_is_binary = value_type_is_binary , ** kwargs )
return cache |
def _GetStat ( self ) :
"""Retrieves a stat object .
Returns :
VFSStat : a stat object .
Raises :
BackEndError : when the encoded stream is missing .""" | stat_object = vfs_stat . VFSStat ( )
# File data stat information .
stat_object . size = self . path_spec . range_size
# File entry type stat information .
stat_object . type = stat_object . TYPE_FILE
return stat_object |
def run ( self , * args , ** kwargs ) :
"""Run this program with Parameters , Redirects , and Pipes . If shell = True , this command is
executed as a string directly on the shell ; otherwise , it ' s executed using Popen processes
and appropriate streams .
: param args : 0 or more of Parameter , Redirect , an... | # Get default for kwarg shell
shell = kwargs . get ( 'shell' , False )
# Output log info for this command
run_cmd = self . __generate_cmd ( * args , shell = True )
log_header = 'Running {}\n{}\n' . format ( self . software_name , run_cmd )
if _Settings . logger . _is_active ( ) :
_Settings . logger . _write ( log_h... |
def fingerprint_from_raw_ssh_pub_key ( key ) :
"""Encode a raw SSH key ( string of bytes , as from
` str ( paramiko . AgentKey ) ` ) to a fingerprint in the typical
'54 : c7:4c : 93 : cf : ff : e3:32:68 : bc : 89:6e : 5e : 22 : b5:9c ' form .""" | fp_plain = hashlib . md5 ( key ) . hexdigest ( )
return ':' . join ( a + b for a , b in zip ( fp_plain [ : : 2 ] , fp_plain [ 1 : : 2 ] ) ) |
def valueAt ( self , point ) :
"""Returns the value within the chart for the given point .
: param point | < QPoint >
: return { < str > axis name : < variant > value , . . }""" | chart_point = self . uiChartVIEW . mapFromParent ( point )
scene_point = self . uiChartVIEW . mapToScene ( chart_point )
return self . renderer ( ) . valueAt ( self . axes ( ) , scene_point ) |
def _get_k ( self ) :
'''Accessing self . k indirectly allows for creating the kvstore table
if necessary .''' | if not self . ready :
self . k . create ( )
# create table if it does not exist .
self . ready = True
return self . k |
def responseReceived ( self , response , tag ) :
"""Receives some characters of a netstring .
Whenever a complete response is received , this method calls the
deferred associated with it .
@ param response : A complete response generated by exiftool .
@ type response : C { bytes }
@ param tag : The tag as... | self . _queue . pop ( tag ) . callback ( response ) |
def _dispatch ( self , textgroup , directory ) :
"""Run the dispatcher over a textgroup .
: param textgroup : Textgroup object that needs to be dispatched
: param directory : Directory in which the textgroup was found""" | if textgroup . id in self . dispatcher . collection :
self . dispatcher . collection [ textgroup . id ] . update ( textgroup )
else :
self . dispatcher . dispatch ( textgroup , path = directory )
for work_urn , work in textgroup . works . items ( ) :
if work_urn in self . dispatcher . collection [ textgroup... |
def avgwaittime_get ( self , service_staff_id , start_date , end_date , session ) :
'''taobao . wangwang . eservice . avgwaittime . get 平均等待时长
根据客服ID和日期 , 获取该客服 " 当日接待的所有客户的平均等待时长 " 。 备注 :
- 1 、 如果是操作者ID = 被查者ID , 返回被查者ID的 " 当日接待的所有客户的平均等待时长 " 。
- 2 、 如果操作者是组管理员 , 他可以查询他的组中的所有子帐号的 " 当日接待的所有客户的平均等待时长 " 。
- 3... | request = TOPRequest ( 'taobao.wangwang.eservice.avgwaittime.get' )
request [ 'service_staff_id' ] = service_staff_id
request [ 'start_date' ] = start_date
request [ 'end_date' ] = end_date
self . create ( self . execute ( request , session ) )
return self . waiting_time_list_on_days |
def get_input_channel ( entity ) :
"""Similar to : meth : ` get _ input _ peer ` , but for : tl : ` InputChannel ` ' s alone .""" | try :
if entity . SUBCLASS_OF_ID == 0x40f202fd : # crc32 ( b ' InputChannel ' )
return entity
except AttributeError :
_raise_cast_fail ( entity , 'InputChannel' )
if isinstance ( entity , ( types . Channel , types . ChannelForbidden ) ) :
return types . InputChannel ( entity . id , entity . access_h... |
def _parse_extra ( self , fp ) :
"""Parse and store the config comments and create maps for dot notion lookup""" | comment = ''
section = ''
fp . seek ( 0 )
for line in fp :
line = line . rstrip ( )
if not line :
if comment :
comment += '\n'
continue
if line . startswith ( '#' ) : # Comment
comment += line + '\n'
continue
if line . startswith ( '[' ) : # Section
se... |
def organizations_create_many ( self , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / organizations # create - many - organizations" | api_path = "/api/v2/organizations/create_many.json"
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def list_locations ( self , provider = None ) :
'''List all available locations in configured cloud systems''' | mapper = salt . cloud . Map ( self . _opts_defaults ( ) )
return salt . utils . data . simple_types_filter ( mapper . location_list ( provider ) ) |
def color_string ( color , string ) :
"""Colorizes a given string , if coloring is available .""" | if not color_available :
return string
return color + string + colorama . Fore . RESET |
def stop ( self ) :
"""Tell the sender thread to finish and wait for it to stop sending
( should be at most " timeout " seconds ) .""" | if self . interval is not None :
self . _queue . put_nowait ( None )
self . _thread . join ( )
self . interval = None |
def _flatten_subsection ( subsection , _type , offset , parent ) :
'''Flatten a subsection from its nested version
Args :
subsection : Nested subsection as produced by _ parse _ section , except one level in
_ type : type of section , ie : AXON , etc
parent : first element has this as it ' s parent
offset... | for row in subsection : # TODO : Figure out what these correspond to in neurolucida
if row in ( 'Low' , 'Generated' , 'High' , ) :
continue
elif isinstance ( row [ 0 ] , StringType ) :
if len ( row ) in ( 4 , 5 , ) :
if len ( row ) == 5 :
assert row [ 4 ] [ 0 ] == 'S'... |
def delete_script ( self , script_id ) :
"""Deletes a stored script .
script _ id : = id of stored script .
status = pi . delete _ script ( sid )""" | res = yield from self . _pigpio_aio_command ( _PI_CMD_PROCD , script_id , 0 )
return _u2i ( res ) |
def do_youtube_dl ( worker , site , page ) :
'''Runs youtube - dl configured for ` worker ` and ` site ` to download videos from
` page ` .
Args :
worker ( brozzler . BrozzlerWorker ) : the calling brozzler worker
site ( brozzler . Site ) : the site we are brozzling
page ( brozzler . Page ) : the page we ... | with tempfile . TemporaryDirectory ( prefix = 'brzl-ydl-' ) as tempdir :
ydl = _build_youtube_dl ( worker , tempdir , site )
ie_result = _try_youtube_dl ( worker , ydl , site , page )
outlinks = set ( )
if ie_result and ie_result . get ( 'extractor' ) == 'youtube:playlist' : # youtube watch pages as out... |
def add_surf ( self , surf , color = SKIN_COLOR , vertex_colors = None , values = None , limits_c = None , colormap = COLORMAP , alpha = 1 , colorbar = False ) :
"""Add surfaces to the visualization .
Parameters
surf : instance of wonambi . attr . anat . Surf
surface to be plotted
color : tuple or ndarray ,... | colors , limits = _prepare_colors ( color = color , values = values , limits_c = limits_c , colormap = colormap , alpha = alpha )
# meshdata uses numpy array , in the correct dimension
vertex_colors = colors . rgba
if vertex_colors . shape [ 0 ] == 1 :
vertex_colors = tile ( vertex_colors , ( surf . n_vert , 1 ) )
... |
def snake_case ( a_string ) :
"""Returns a snake cased version of a string .
: param a _ string : any : class : ` str ` object .
Usage :
> > > snake _ case ( ' FooBar ' )
" foo _ bar " """ | partial = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , a_string )
return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , partial ) . lower ( ) |
def _handle_amqp_frame ( self , data_in ) :
"""Unmarshal a single AMQP frame and return the result .
: param data _ in : socket data
: return : data _ in , channel _ id , frame""" | if not data_in :
return data_in , None , None
try :
byte_count , channel_id , frame_in = pamqp_frame . unmarshal ( data_in )
return data_in [ byte_count : ] , channel_id , frame_in
except pamqp_exception . UnmarshalingException :
pass
except specification . AMQPFrameError as why :
LOGGER . error ( '... |
def fit ( self , t , y , dy = None ) :
"""Fit the multiterm Periodogram model to the data .
Parameters
t : array _ like , one - dimensional
sequence of observation times
y : array _ like , one - dimensional
sequence of observed values
dy : float or array _ like ( optional )
errors on observed values""... | # For linear models , dy = 1 is equivalent to no errors
if dy is None :
dy = 1
self . t , self . y , self . dy = np . broadcast_arrays ( t , y , dy )
self . _fit ( self . t , self . y , self . dy )
self . _best_period = None
# reset best period in case of refitting
if self . fit_period :
self . _best_period = s... |
def get_stats_monthly ( start = None , end = None , ** kwargs ) :
"""MOVED to iexfinance . iexdata . get _ stats _ summary""" | import warnings
warnings . warn ( WNG_MSG % ( "get_stats_monthly" , "iexdata.get_stats_summary" ) )
return MonthlySummaryReader ( start = start , end = end , ** kwargs ) . fetch ( ) |
def add_self_edges ( self , weight = None , copy = False ) :
'''Adds all i - > i edges . weight may be a scalar or 1d array .''' | ii = np . arange ( self . num_vertices ( ) )
return self . add_edges ( ii , ii , weight = weight , symmetric = False , copy = copy ) |
def managed ( name , peers = None , servers = None ) :
'''Manages the configuration of NTP peers and servers on the device , as specified in the state SLS file .
NTP entities not specified in these lists will be removed whilst entities not configured on the device will be set .
SLS Example :
. . code - block ... | ret = _default_ret ( name )
result = ret . get ( 'result' , False )
comment = ret . get ( 'comment' , '' )
changes = ret . get ( 'changes' , { } )
if not ( isinstance ( peers , list ) or isinstance ( servers , list ) ) : # none of the is a list
return ret
# just exit
if isinstance ( peers , list ) and not _check ( ... |
async def parseResults ( self , api_data ) :
"""See CoverSource . parseResults .""" | results = [ ]
# get xml results list
xml_text = api_data . decode ( "utf-8" )
xml_root = xml . etree . ElementTree . fromstring ( xml_text )
status = xml_root . get ( "status" )
if status != "ok" :
raise Exception ( "Unexpected Last.fm response status: %s" % ( status ) )
img_elements = xml_root . findall ( "album/i... |
def module_settings ( self ) :
"""Get Module settings . Uses GET to / settings / modules interface .
: Returns : ( dict ) Module settings as shown ` here < https : / / cloud . knuverse . com / docs / api / # api - Module _ Settings - Get _ the _ module _ settings > ` _ .""" | response = self . _get ( url . settings_modules )
self . _check_response ( response , 200 )
return self . _create_response ( response ) |
def disco_query ( self ) :
"""Makes a request to the discovery server
: type context : satosa . context . Context
: type internal _ req : satosa . internal . InternalData
: rtype : satosa . response . SeeOther
: param context : The current context
: param internal _ req : The request
: return : Response... | return_url = self . sp . config . getattr ( "endpoints" , "sp" ) [ "discovery_response" ] [ 0 ] [ 0 ]
loc = self . sp . create_discovery_service_request ( self . discosrv , self . sp . config . entityid , ** { "return" : return_url } )
return SeeOther ( loc ) |
def Parse ( self , conditions , host_data ) :
"""Runs methods that evaluate whether collected host _ data has an issue .
Args :
conditions : A list of conditions to determine which Methods to trigger .
host _ data : A map of artifacts and rdf data .
Returns :
A CheckResult populated with Anomalies if an i... | result = CheckResult ( check_id = self . check_id )
methods = self . SelectChecks ( conditions )
result . ExtendAnomalies ( [ m . Parse ( conditions , host_data ) for m in methods ] )
return result |
def get_network_adapter ( self , slot ) :
"""Returns the network adapter associated with the given slot .
Slots are numbered sequentially , starting with zero . The total
number of adapters per machine is defined by the
: py : func : ` ISystemProperties . get _ max _ network _ adapters ` property ,
so the m... | if not isinstance ( slot , baseinteger ) :
raise TypeError ( "slot can only be an instance of type baseinteger" )
adapter = self . _call ( "getNetworkAdapter" , in_p = [ slot ] )
adapter = INetworkAdapter ( adapter )
return adapter |
def get_log_entries_by_search ( self , log_entry_query , log_entry_search ) :
"""Pass through to provider LogEntrySearchSession . get _ log _ entries _ by _ search""" | # Implemented from azosid template for -
# osid . resource . ResourceSearchSession . get _ resources _ by _ search _ template
if not self . _can ( 'search' ) :
raise PermissionDenied ( )
return self . _provider_session . get_log_entries_by_search ( log_entry_query , log_entry_search ) |
def _get_more_data ( self , file , timeout ) :
"""Return data from the file , if available . If no data is received
by the timeout , then raise RuntimeError .""" | timeout = datetime . timedelta ( seconds = timeout )
timer = Stopwatch ( )
while timer . split ( ) < timeout :
data = file . read ( )
if data :
return data
raise RuntimeError ( "Timeout" ) |
def from_dataset ( cls , dataset , constraints = ( ) , ** kwargs ) :
"""Construct a optimized inverse model from an existing dataset .
A LWLR forward model is constructed by default .""" | fm = LWLRForwardModel ( dataset . dim_x , dataset . dim_y , ** kwargs )
fm . dataset = dataset
im = cls . from_forward ( fm , constraints = constraints , ** kwargs )
return im |
def product_of_three_primes ( n : int ) -> bool :
"""Checks if the given number is a product of three distinct prime numbers . Returns true if it is , false otherwise .
Assumption : The input number ( n ) is less than 100.
Example :
product _ of _ three _ primes ( 30 ) returns True
30 = 2 * 3 * 5
Args :
... | # Check if a number is prime
def check_prime ( p ) :
for item in range ( 2 , p ) :
if p % item == 0 :
return False
return True
# Iterate for possible prime factors
for first in range ( 2 , 101 ) :
if check_prime ( first ) :
for second in range ( 2 , 101 ) :
if check_p... |
def next ( self ) :
"""Gets next entry as a dictionary .
Returns :
object - Object key / value pair representing a row .
{ key1 : value1 , key2 : value2 , . . . }""" | try :
entry = { }
row = self . _csv_reader . next ( )
for i in range ( 0 , len ( row ) ) :
entry [ self . _headers [ i ] ] = row [ i ]
return entry
except Exception as e : # close our file when we ' re done reading .
self . _file . close ( )
raise e |
def unpunctuate ( s , * , char_blacklist = string . punctuation ) :
"""Remove punctuation from string s .""" | # remove punctuation
s = "" . join ( c for c in s if c not in char_blacklist )
# remove consecutive spaces
return " " . join ( filter ( None , s . split ( " " ) ) ) |
def plot2dhist ( xdata , ydata , cmap = 'binary' , interpolation = 'nearest' , fig = None , logscale = True , xbins = None , ybins = None , nbins = 50 , pts_only = False , ** kwargs ) :
"""Plots a 2d density histogram of provided data
: param xdata , ydata : ( array - like )
Data to plot .
: param cmap : ( op... | setfig ( fig )
if pts_only :
plt . plot ( xdata , ydata , ** kwargs )
return
ok = ( ~ np . isnan ( xdata ) & ~ np . isnan ( ydata ) & ~ np . isinf ( xdata ) & ~ np . isinf ( ydata ) )
if ~ ok . sum ( ) > 0 :
logging . warning ( '{} x values and {} y values are nan' . format ( np . isnan ( xdata ) . sum ( ) ... |
def snipstr ( string , width = 79 , snipat = None , ellipsis = '...' ) :
"""Return string cut to specified length .
> > > snipstr ( ' abcdefghijklmnop ' , 8)
' abc . . . op '""" | if snipat is None :
snipat = 0.5
if ellipsis is None :
if isinstance ( string , bytes ) :
ellipsis = b'...'
else :
ellipsis = u'\u2026'
# does not print on win - py3.5
esize = len ( ellipsis )
splitlines = string . splitlines ( )
# TODO : finish and test multiline snip
result = [ ]
f... |
def coords ( self ) :
"""Returns a tuple representing the location of the address in a
GIS coords format , i . e . ( longitude , latitude ) .""" | x , y = ( "lat" , "lng" ) if self . order == "lat" else ( "lng" , "lat" )
try :
return ( self [ "location" ] [ x ] , self [ "location" ] [ y ] )
except KeyError :
return None |
def _ensure_tree ( path ) :
"""Create a directory ( and any ancestor directories required ) .
: param path : Directory to create""" | try :
os . makedirs ( path )
except OSError as e :
if e . errno == errno . EEXIST :
if not os . path . isdir ( path ) :
raise
else :
return False
elif e . errno == errno . EISDIR :
return False
else :
raise
else :
return True |
def load ( self , filename , ** kwargs ) :
"""Parse a file specified with the filename and return an numpy array
Parameters
filename : string
A path of a file
Returns
ndarray
An instance of numpy array""" | with open ( filename , 'r' ) as f :
return self . parse ( f , ** kwargs ) |
def from_dict ( cls , data ) :
"""Converts this from a dictionary to a object .""" | data = dict ( data )
cause = data . get ( 'cause' )
if cause is not None :
data [ 'cause' ] = cls . from_dict ( cause )
return cls ( ** data ) |
def hash_evidence ( text : str , type : str , reference : str ) -> str :
"""Create a hash for an evidence and its citation .
: param text : The evidence text
: param type : The corresponding citation type
: param reference : The citation reference""" | s = u'{type}:{reference}:{text}' . format ( type = type , reference = reference , text = text )
return hashlib . sha512 ( s . encode ( 'utf8' ) ) . hexdigest ( ) |
def run ( self ) :
"""Run the plugin .""" | if self . workflow . builder . base_from_scratch :
self . log . info ( "Skipping comparing components: unsupported for FROM-scratch images" )
return
worker_metadatas = self . workflow . postbuild_results . get ( PLUGIN_FETCH_WORKER_METADATA_KEY )
comp_list = self . get_component_list_from_workers ( worker_metad... |
def sync_state_context ( self , state , context ) :
"""sync state context .""" | if isinstance ( state , NDArray ) :
return state . as_in_context ( context )
elif isinstance ( state , ( tuple , list ) ) :
synced_state = ( self . sync_state_context ( i , context ) for i in state )
if isinstance ( state , tuple ) :
return tuple ( synced_state )
else :
return list ( syn... |
def getConnectorVersion ( self ) :
"""GET the current Connector version .
: returns : asyncResult object , populates error and result fields
: rtype : asyncResult""" | result = asyncResult ( )
data = self . _getURL ( "/" , versioned = False )
result . fill ( data )
if data . status_code == 200 :
result . error = False
else :
result . error = response_codes ( "get_mdc_version" , data . status_code )
result . is_done = True
return result |
def expand_brackets ( s ) :
"""Remove whitespace and expand all brackets .""" | s = '' . join ( s . split ( ) )
while True :
start = s . find ( '(' )
if start == - 1 :
break
count = 1
# Number of hanging open brackets
p = start + 1
while p < len ( s ) :
if s [ p ] == '(' :
count += 1
if s [ p ] == ')' :
count -= 1
if n... |
def get_reservation_ports ( session , reservation_id , model_name = 'Generic Traffic Generator Port' ) :
"""Get all Generic Traffic Generator Port in reservation .
: return : list of all Generic Traffic Generator Port resource objects in reservation""" | reservation_ports = [ ]
reservation = session . GetReservationDetails ( reservation_id ) . ReservationDescription
for resource in reservation . Resources :
if resource . ResourceModelName == model_name :
reservation_ports . append ( resource )
return reservation_ports |
def get_page_children_dict ( self , page_qs = None ) :
"""Returns a dictionary of lists , where the keys are ' path ' values for
pages , and the value is a list of children pages for that page .""" | children_dict = defaultdict ( list )
for page in page_qs or self . pages_for_display :
children_dict [ page . path [ : - page . steplen ] ] . append ( page )
return children_dict |
def update_workspace_config ( namespace , workspace , cnamespace , configname , body ) :
"""Update method configuration in workspace .
Args :
namespace ( str ) : project to which workspace belongs
workspace ( str ) : Workspace name
cnamespace ( str ) : Configuration namespace
configname ( str ) : Configur... | uri = "workspaces/{0}/{1}/method_configs/{2}/{3}" . format ( namespace , workspace , cnamespace , configname )
return __post ( uri , json = body ) |
def remove_trailing_white_spaces ( self ) :
"""Removes document trailing white spaces .
: return : Method success .
: rtype : bool""" | cursor = self . textCursor ( )
block = self . document ( ) . findBlockByLineNumber ( 0 )
while block . isValid ( ) :
cursor . setPosition ( block . position ( ) )
if re . search ( r"\s+$" , block . text ( ) ) :
cursor . movePosition ( QTextCursor . EndOfBlock )
cursor . movePosition ( QTextCurso... |
def create_configmap ( name , namespace , data , source = None , template = None , saltenv = 'base' , ** kwargs ) :
'''Creates the kubernetes configmap as defined by the user .
CLI Examples : :
salt ' minion1 ' kubernetes . create _ configmap settings default ' { " example . conf " : " # example file " } '
sa... | if source :
data = __read_and_render_yaml_file ( source , template , saltenv )
elif data is None :
data = { }
data = __enforce_only_strings_dict ( data )
body = kubernetes . client . V1ConfigMap ( metadata = __dict_to_object_meta ( name , namespace , { } ) , data = data )
cfg = _setup_conn ( ** kwargs )
try :
... |
def _add_new_methods ( cls ) :
"""Add all generated methods to result class .""" | for name , method in cls . context . new_methods . items ( ) :
if hasattr ( cls . context . new_class , name ) :
raise ValueError ( "Name collision in state machine class - '{name}'." . format ( name ) )
setattr ( cls . context . new_class , name , method ) |
def get_description_by_type ( self , type_p ) :
"""This is the same as : py : func : ` get _ description ` except that you can specify which types
should be returned .
in type _ p of type : class : ` VirtualSystemDescriptionType `
out types of type : class : ` VirtualSystemDescriptionType `
out refs of type... | if not isinstance ( type_p , VirtualSystemDescriptionType ) :
raise TypeError ( "type_p can only be an instance of type VirtualSystemDescriptionType" )
( types , refs , ovf_values , v_box_values , extra_config_values ) = self . _call ( "getDescriptionByType" , in_p = [ type_p ] )
types = [ VirtualSystemDescriptionT... |
def build_inventory ( setup ) :
'''Builds an inventory for use as part of an
` dynamic Ansible inventory < http : / / docs . ansible . com / ansible / intro _ dynamic _ inventory . html > ` _
according to the
` script conventions < http : / / docs . ansible . com / ansible / developing _ inventory . html # sc... | inventory = dict ( )
inventory [ 'all' ] = dict ( )
inventory [ 'all' ] [ 'vars' ] = { 'provider' : setup . cloud . provider , 'region' : setup . cloud . region , 'key_name' : setup . cloud . key_name , 'key_file' : os . path . expandvars ( os . path . expanduser ( setup . cloud . key_file_public ) ) , 'network' : setu... |
def theme ( self , value ) :
"""Setter for * * self . _ _ theme * * attribute .
: param value : Attribute value .
: type value : dict""" | if value is not None :
assert type ( value ) is dict , "'{0}' attribute: '{1}' type is not 'dict'!" . format ( "theme" , value )
self . __theme = value |
def translate ( self ) :
"""Compile the variable lookup .""" | ident = self . ident
expr = ex_rvalue ( VARIABLE_PREFIX + ident )
return [ expr ] , set ( [ ident ] ) , set ( ) |
def _parse_commit_response ( commit_response_pb ) :
"""Extract response data from a commit response .
: type commit _ response _ pb : : class : ` . datastore _ pb2 . CommitResponse `
: param commit _ response _ pb : The protobuf response from a commit request .
: rtype : tuple
: returns : The pair of the nu... | mut_results = commit_response_pb . mutation_results
index_updates = commit_response_pb . index_updates
completed_keys = [ mut_result . key for mut_result in mut_results if mut_result . HasField ( "key" ) ]
# Message field ( Key )
return index_updates , completed_keys |
def annotate_snvs ( adapter , vcf_obj ) :
"""Annotate all variants in a VCF
Args :
adapter ( loqusdb . plugin . adapter )
vcf _ obj ( cyvcf2 . VCF )
Yields :
variant ( cyvcf2 . Variant ) : Annotated variant""" | variants = { }
for nr_variants , variant in enumerate ( vcf_obj , 1 ) : # Add the variant to current batch
variants [ get_variant_id ( variant ) ] = variant
# If batch len = = 1000 we annotate the batch
if ( nr_variants % 1000 ) == 0 :
for var_obj in adapter . search_variants ( list ( variants . key... |
def existing ( self ) :
"""find existing content assigned to this layout""" | catalog = api . portal . get_tool ( 'portal_catalog' )
results = [ ]
layout_path = self . _get_layout_path ( self . request . form . get ( 'layout' , '' ) )
for brain in catalog ( layout = layout_path ) :
results . append ( { 'title' : brain . Title , 'url' : brain . getURL ( ) } )
return json . dumps ( { 'total' :... |
def preparse ( template_text , lookup = None ) :
"""Do any special processing of a template , including recognizing the templating language
and resolving file : references , then return an appropriate wrapper object .
Currently Tempita and Python string interpolation are supported .
` lookup ` is an optional ... | # First , try to resolve file : references to their contents
template_path = None
try :
is_file = template_text . startswith ( "file:" )
except ( AttributeError , TypeError ) :
pass
# not a string
else :
if is_file :
template_path = template_text [ 5 : ]
if template_path . startswith ( '... |
def add_bundle ( name , scripts = [ ] , files = [ ] , scriptsdir = SCRIPTSDIR , filesdir = FILESDIR ) :
"""High level , simplified interface for creating a bundle which
takes the bundle name , a list of script file names in a common
scripts directory , and a list of absolute target file paths , of
which the b... | scriptmap = makemap ( scripts , join ( PATH , scriptsdir ) )
filemap = dict ( zip ( files , [ join ( PATH , filesdir , os . path . basename ( f ) ) for f in files ] ) )
new_bundle ( name , scriptmap , filemap ) |
def aws_cli ( * cmd ) :
"""Invoke aws command .""" | old_env = dict ( os . environ )
try : # Environment
env = os . environ . copy ( )
env [ 'LC_CTYPE' ] = u'en_US.UTF'
os . environ . update ( env )
# Run awscli in the same process
exit_code = create_clidriver ( ) . main ( * cmd )
# Deal with problems
if exit_code > 0 :
raise RuntimeEr... |
def _decode_signature ( self , signature ) :
"""Decode the internal fields of the base64 - encoded signature .""" | sig = a2b_base64 ( signature )
if len ( sig ) != 65 :
raise EncodingError ( "Wrong length, expected 65" )
# split into the parts .
first = byte2int ( sig )
r = from_bytes_32 ( sig [ 1 : 33 ] )
s = from_bytes_32 ( sig [ 33 : 33 + 32 ] )
# first byte encodes a bits we need to know about the point used in signature
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.