signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def groupby ( self , key_column_names , operations , * args ) :
"""Perform a group on the key _ column _ names followed by aggregations on the
columns listed in operations .
The operations parameter is a dictionary that indicates which
aggregation operators to use and which columns to use them on . The
avai... | # some basic checking first
# make sure key _ column _ names is a list
if isinstance ( key_column_names , str ) :
key_column_names = [ key_column_names ]
# check that every column is a string , and is a valid column name
my_column_names = self . column_names ( )
key_columns_array = [ ]
for column in key_column_name... |
def get_plugins_info ( self ) :
"""Collect the current live info from all the registered plugins .
Return a dictionary , keyed on the plugin name .""" | d = { }
for p in self . plugins :
d . update ( p . get_info ( ) )
return d |
def body_block_attribution ( tag ) :
"extract the attribution content for figures , tables , videos" | attributions = [ ]
if raw_parser . attrib ( tag ) :
for attrib_tag in raw_parser . attrib ( tag ) :
attributions . append ( node_contents_str ( attrib_tag ) )
if raw_parser . permissions ( tag ) : # concatenate content from from the permissions tag
for permissions_tag in raw_parser . permissions ( tag )... |
def mkdir_p ( self , mode = 0o777 ) :
"""Like : meth : ` mkdir ` , but does not raise an exception if the
directory already exists .""" | with contextlib . suppress ( FileExistsError ) :
self . mkdir ( mode )
return self |
def clean_url ( url , force_scheme = None ) :
"""Cleans the given URL .""" | # URL should be ASCII according to RFC 3986
url = str ( url )
# Collapse . . / . . / and related
url_parts = urlparse . urlparse ( url )
path_parts = [ ]
for part in url_parts . path . split ( '/' ) :
if part == '.' :
continue
elif part == '..' :
if path_parts :
path_parts . pop ( )
... |
def get_object_metadata ( self , container , obj , prefix = None ) :
"""Returns the metadata for the specified object as a dict .""" | return self . _manager . get_object_metadata ( container , obj , prefix = prefix ) |
def zipLists ( * lists ) :
"""Checks to see if all of the lists are the same length , and throws
an AssertionError otherwise . Returns the zipped lists .""" | length = len ( lists [ 0 ] )
for i , list_ in enumerate ( lists [ 1 : ] ) :
if len ( list_ ) != length :
msg = "List at index {} has length {} != {}" . format ( i + 1 , len ( list_ ) , length )
raise AssertionError ( msg )
return zip ( * lists ) |
def cposr ( string , chars , start ) :
"""Find the first occurrence in a string of a character belonging
to a collection of characters , starting at a specified location ,
searching in reverse .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / cposr _ c . html
: param string :... | string = stypes . stringToCharP ( string )
chars = stypes . stringToCharP ( chars )
start = ctypes . c_int ( start )
return libspice . cposr_c ( string , chars , start ) |
def get_ancestors ( self , include_self = False , depth = None ) :
"""Return all the ancestors of this object .""" | if self . is_root_node ( ) :
if not include_self :
return self . _toplevel ( ) . objects . none ( )
else : # Filter on pk for efficiency .
return self . _toplevel ( ) . objects . filter ( pk = self . pk )
params = { "%s__child" % self . _closure_parentref ( ) : self . pk }
if depth is not None :... |
def write_to_file ( data , path ) :
"""Export extracted fields to json
Appends . json to path if missing and generates json file in specified directory , if not then in root
Parameters
data : dict
Dictionary of extracted fields
path : str
directory to save generated json file
Notes
Do give file name... | if path . endswith ( '.json' ) :
filename = path
else :
filename = path + '.json'
with codecs . open ( filename , "w" , encoding = 'utf-8' ) as json_file :
for line in data :
line [ 'date' ] = line [ 'date' ] . strftime ( '%d/%m/%Y' )
print ( type ( json ) )
print ( json )
json . dump ( ... |
def format_field ( self , value , format_spec ) :
"""Format specifiers are described in : func : ` format _ field ` which is a
static function .""" | if format_spec :
spec , arg = format_spec [ 0 ] , format_spec [ 1 : ]
arg = arg or None
else :
spec = arg = None
return self . _format_field ( spec , arg , value , self . numeric_locale ) |
def configure ( self , ext ) :
"""Configures the given Extension object using this build configuration .""" | ext . include_dirs += self . include_dirs
ext . library_dirs += self . library_dirs
ext . libraries += self . libraries
ext . extra_compile_args += self . extra_compile_args
ext . extra_link_args += self . extra_link_args
ext . extra_objects += self . extra_objects |
def _FormatHostname ( self , event ) :
"""Formats the hostname .
Args :
event ( EventObject ) : event .
Returns :
str : formatted hostname field .""" | hostname = self . _output_mediator . GetHostname ( event )
return self . _FormatField ( hostname ) |
def _set_slot ( self , v , load = False ) :
"""Setter method for slot , mapped from YANG variable / qos / cpu / slot ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ slot is considered as a private
method . Backends looking to populate this variable should
d... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "slot_id" , slot . slot , yang_name = "slot" , rest_name = "slot" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'slot-id' , extensions = { u'ta... |
def is_rpm ( path ) :
"""Attempt to validate the path as an actual ( S ) RPM . If an exception
is raised then this is not an RPM .""" | import magic
m = magic . open ( magic . MAGIC_MIME )
m . load ( )
mime = m . file ( path )
# rpms or directories are cool
if 'rpm' in mime or 'directory' in mime :
return True
else :
juicer . utils . Log . log_info ( "error: File `%s` is not an rpm" % path )
return False |
def update ( self , instance , validated_data ) :
'''We want to set all the required fields if admin is set , and we want
to use the password hashing method if password is set .''' | admin = validated_data . pop ( 'is_superuser' , None )
password = validated_data . pop ( 'password' , None )
if validated_data . get ( 'email' ) is not None :
validated_data [ 'username' ] = validated_data [ 'email' ]
for attr , value in validated_data . items ( ) :
setattr ( instance , attr , value )
if admin ... |
def bernard_auth ( func ) :
"""Authenticates the users based on the query - string - provided token""" | @ wraps ( func )
async def wrapper ( request : Request ) :
def get_query_token ( ) :
token_key = settings . WEBVIEW_TOKEN_KEY
return request . query . get ( token_key , '' )
def get_header_token ( ) :
header_key = settings . WEBVIEW_HEADER_NAME
return request . headers . get ( he... |
from typing import List
def parse_music ( music_string : str ) -> List [ int ] :
"""Input to this function is a string representing musical notes in a special ASCII format .
Your task is to parse this string and return list of integers corresponding to how many beats does each
note last .
Here is a legend :
... | # define the mapping of notes to beats
notes_to_beats = { 'o' : 4 , 'o|' : 2 , '.|' : 1 }
# split the string into an array of notes
notes = music_string . split ( )
# generate the array of beats corresponding to each note
beats = [ notes_to_beats [ note ] for note in notes ]
return beats |
def is_ip_addr_list ( value , min = None , max = None ) :
"""Check that the value is a list of IP addresses .
You can optionally specify the minimum and maximum number of members .
Each list member is checked that it is an IP address .
> > > vtor = Validator ( )
> > > vtor . check ( ' ip _ addr _ list ' , (... | return [ is_ip_addr ( mem ) for mem in is_list ( value , min , max ) ] |
def get_acgt_geno_marker ( self , marker ) :
"""Gets the genotypes for a given marker ( ACGT format ) .
Args :
marker ( str ) : The name of the marker .
Returns :
numpy . ndarray : The genotypes of the marker ( ACGT format ) .""" | # Getting the marker ' s genotypes
geno , snp_position = self . get_geno_marker ( marker , return_index = True )
# Returning the ACGT ' s format of the genotypes
return self . _allele_encoding [ snp_position ] [ geno ] |
def _add_data_to_general_stats ( self , data ) :
"""Add data for the general stats in a Picard - module specific manner""" | headers = _get_general_stats_headers ( )
self . general_stats_headers . update ( headers )
header_names = ( 'ERROR_count' , 'WARNING_count' , 'file_validation_status' )
general_data = dict ( )
for sample in data :
general_data [ sample ] = { column : data [ sample ] [ column ] for column in header_names }
if sa... |
def get_posts ( self , offset = 0 , limit = 1000 , order = None , filters = None ) :
"""This method returns list of Posts for this Data Source starting at a given offset and not more than limit
It will call content - specific methods :
_ format ( ) to format output from the DataStore""" | order = self . _get_order ( order )
cache_key = self . get_cache_key ( offset , limit , order , filters )
content = cache . get ( cache_key )
# if content :
# return content
try :
if self . up_to_date ( ) :
pass
# not time to update yet
else :
self . update ( )
except :
raise
pas... |
def parse_compound_table_file ( path , f ) :
"""Parse a tab - separated file containing compound IDs and properties
The compound properties are parsed according to the header which specifies
which property is contained in each column .""" | context = FilePathContext ( path )
for i , row in enumerate ( csv . DictReader ( f , delimiter = str ( '\t' ) ) ) :
if 'id' not in row or row [ 'id' ] . strip ( ) == '' :
raise ParseError ( 'Expected `id` column in table' )
props = { key : value for key , value in iteritems ( row ) if value != '' }
... |
def lerp ( vec1 , vec2 , time ) :
"""Lerp between vec1 to vec2 based on time . Time is clamped between 0 and 1.""" | if isinstance ( vec1 , Vector2 ) and isinstance ( vec2 , Vector2 ) : # Clamp the time value into the 0-1 range .
if time < 0 :
time = 0
elif time > 1 :
time = 1
x_lerp = vec1 [ 0 ] + time * ( vec2 [ 0 ] - vec1 [ 0 ] )
y_lerp = vec1 [ 1 ] + time * ( vec2 [ 1 ] - vec1 [ 1 ] )
return Ve... |
def write_offsets_to_file ( cls , json_file_name , consumer_offsets_data ) :
"""Save built consumer - offsets data to given json file .""" | # Save consumer - offsets to file
with open ( json_file_name , "w" ) as json_file :
try :
json . dump ( consumer_offsets_data , json_file )
except ValueError :
print ( "Error: Invalid json data {data}" . format ( data = consumer_offsets_data ) )
raise
print ( "Consumer offset data sa... |
def last_job_statuses ( self ) -> List [ str ] :
"""The last constants of the job in this experiment .""" | statuses = [ ]
for status in self . jobs . values_list ( 'status__status' , flat = True ) :
if status is not None :
statuses . append ( status )
return statuses |
def overlay_gateway_access_lists_ipv4_out_ipv4_acl_out_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( overlay_gateway , "name" )
name_key . text = kwargs . pop ( 'name' )
access_lists = ET . SubElement ( overlay_gateway , "access-lists" )
ipv4 ... |
def get_freesasa_annotations ( self , outdir , include_hetatms = False , force_rerun = False ) :
"""Run ` ` freesasa ` ` on this structure and store the calculated properties in the corresponding ChainProps""" | if self . file_type != 'pdb' :
log . error ( '{}: unable to run freesasa with "{}" file type. Please change file type to "pdb"' . format ( self . id , self . file_type ) )
return
# Parse the structure to store chain sequences
if self . structure :
parsed = self . structure
else :
parsed = self . parse_s... |
async def export_chat_invite_link ( self , chat_id : typing . Union [ base . Integer , base . String ] ) -> base . String :
"""Use this method to generate a new invite link for a chat ; any previously generated link is revoked .
The bot must be an administrator in the chat for this to work and must have the appro... | payload = generate_payload ( ** locals ( ) )
result = await self . request ( api . Methods . EXPORT_CHAT_INVITE_LINK , payload )
return result |
def produce_scansion ( self , stresses : list , syllables_wspaces : List [ str ] , offset_map : Dict [ int , int ] ) -> str :
"""Create a scansion string that has stressed and unstressed syllable positions in locations
that correspond with the original texts syllable vowels .
: param stresses list of syllable p... | scansion = list ( " " * len ( string_utils . flatten ( syllables_wspaces ) ) )
unstresses = string_utils . get_unstresses ( stresses , len ( syllables_wspaces ) )
try :
for idx in unstresses :
location = offset_map . get ( idx )
if location is not None :
scansion [ location ] = self . co... |
def commandstr ( command ) :
"""Convert command into string .""" | if command == CMD_MESSAGE_ERROR :
msg = "CMD_MESSAGE_ERROR"
elif command == CMD_MESSAGE_LIST :
msg = "CMD_MESSAGE_LIST"
elif command == CMD_MESSAGE_PASSWORD :
msg = "CMD_MESSAGE_PASSWORD"
elif command == CMD_MESSAGE_MP3 :
msg = "CMD_MESSAGE_MP3"
elif command == CMD_MESSAGE_DELETE :
msg = "CMD_MESSAG... |
def format_strings ( self , ** kwargs ) :
"""String substitution of name .""" | return mutablerecords . CopyRecord ( self , name = util . format_string ( self . name , kwargs ) ) |
def _on_read_complete ( self , data ) :
"""数据获取结束""" | request = self . app . request_class ( self , data )
self . _handle_request ( request ) |
def which ( cmd ) :
"""Returns full path to a executable .
Args :
cmd ( str ) : Executable command to search for .
Returns :
( str ) Full path to command . None if it is not found .
Example : :
full _ path _ to _ python = which ( " python " )""" | def is_exe ( fp ) :
return os . path . isfile ( fp ) and os . access ( fp , os . X_OK )
fpath , fname = os . path . split ( cmd )
if fpath :
if is_exe ( cmd ) :
return cmd
else :
for path in os . environ [ "PATH" ] . split ( os . pathsep ) :
exe_file = os . path . join ( path , cmd )
... |
def validate_swagger_schema ( schema_dir , resource_listing ) :
"""Validate the structure of Swagger schemas against the spec .
* * Valid only for Swagger v1.2 spec * *
Note : It is possible that resource _ listing is not present in
the schema _ dir . The path is passed in the call so that ssv
can fetch the... | schema_filepath = os . path . join ( schema_dir , API_DOCS_FILENAME )
swagger_spec_validator . validator12 . validate_spec ( resource_listing , urlparse . urljoin ( 'file:' , pathname2url ( os . path . abspath ( schema_filepath ) ) ) , ) |
def broken_faces ( mesh , color = None ) :
"""Return the index of faces in the mesh which break the
watertight status of the mesh .
Parameters
mesh : Trimesh object
color : ( 4 , ) uint8 , will set broken faces to this color
None , will not alter mesh colors
Returns
broken : ( n , ) int , indexes of m... | adjacency = nx . from_edgelist ( mesh . face_adjacency )
broken = [ k for k , v in dict ( adjacency . degree ( ) ) . items ( ) if v != 3 ]
broken = np . array ( broken )
if color is not None : # if someone passed a broken color
color = np . array ( color )
if not ( color . shape == ( 4 , ) or color . shape == (... |
def location ( value ) :
"""Transform an IP address into an approximate location .
Example output :
* Zwolle , The Netherlands
* The Netherlands
* None""" | try :
location = geoip ( ) and geoip ( ) . city ( value )
except Exception :
try :
location = geoip ( ) and geoip ( ) . country ( value )
except Exception as e :
warnings . warn ( str ( e ) )
location = None
if location and location [ 'country_name' ] :
if 'city' in location and ... |
async def get_attached_modules ( request ) :
"""On success ( including an empty " modules " list if no modules are detected ) :
/ / status : 200
" modules " : [
/ * * name of module * /
" name " : " string " ,
/ * * model identifier ( i . e . part number ) * /
" model " : " string " ,
/ * * unique ser... | hw = hw_from_req ( request )
if ff . use_protocol_api_v2 ( ) :
hw_mods = await hw . discover_modules ( )
module_data = [ { 'name' : mod . name ( ) , 'displayName' : mod . display_name ( ) , 'port' : mod . port , 'serial' : mod . device_info . get ( 'serial' ) , 'model' : mod . device_info . get ( 'model' ) , 'f... |
def check_required_keys ( self , required_keys ) :
'''raise InsufficientGraftMPackageException if this package does not
conform to the standard of the given package''' | h = self . _contents_hash
for key in required_keys :
if key not in h :
raise InsufficientGraftMPackageException ( "Package missing key %s" % key ) |
def clear_spatial_unit_conditions ( self ) :
"""stub""" | if ( self . get_spatial_unit_conditions_metadata ( ) . is_read_only ( ) or self . get_zone_conditions_metadata ( ) . is_required ( ) ) :
raise NoAccess ( )
self . my_osid_object_form . _my_map [ 'spatialUnitConditions' ] = self . _zone_conditions_metadata [ 'default_object_values' ] [ 0 ] |
def get ( self , name = None , plugin = None ) :
"""Returns requested shared objects .
: param name : Name of a request shared object
: type name : str or None
: param plugin : Plugin , which has registered the requested shared object
: type plugin : GwBasePattern instance or None""" | if plugin is not None :
if name is None :
shared_objects_list = { }
for key in self . _shared_objects . keys ( ) :
if self . _shared_objects [ key ] . plugin == plugin :
shared_objects_list [ key ] = self . _shared_objects [ key ]
return shared_objects_list
el... |
def remove_server ( self , server_id ) :
"""Remove a registered WBEM server from the subscription manager . This
also unregisters listeners from that server and removes all owned
indication subscriptions , owned indication filters and owned listener
destinations .
Parameters :
server _ id ( : term : ` str... | # Validate server _ id
server = self . _get_server ( server_id )
# Delete any instances we recorded to be cleaned up
if server_id in self . _owned_subscriptions :
inst_list = self . _owned_subscriptions [ server_id ]
# We iterate backwards because we change the list
for i in six . moves . range ( len ( inst... |
def register_bec_task ( self , * args , ** kwargs ) :
"""Register a BEC task .""" | kwargs [ "task_class" ] = BecTask
return self . register_task ( * args , ** kwargs ) |
def random ( self , max_number = None ) :
"""Return a random integer between min and max ( inclusive ) .""" | min_number = self . obj
if max_number is None :
min_number = 0
max_number = self . obj
return random . randrange ( min_number , max_number ) |
async def _send_plain_text ( self , request : Request , stack : Stack ) :
"""Sends plain text using ` _ send _ text ( ) ` .""" | await self . _send_text ( request , stack , None ) |
def replace_namespaced_lease ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""replace _ namespaced _ lease # noqa : E501
replace the specified Lease # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_lease_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . replace_namespaced_lease_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
... |
def _apply_rule ( self , dates ) :
"""Apply the given offset / observance to a DatetimeIndex of dates .
Parameters
dates : DatetimeIndex
Dates to apply the given offset / observance rule
Returns
Dates with rules applied""" | if self . observance is not None :
return dates . map ( lambda d : self . observance ( d ) )
if self . offset is not None :
if not isinstance ( self . offset , list ) :
offsets = [ self . offset ]
else :
offsets = self . offset
for offset in offsets : # if we are adding a non - vectorize... |
def set_comment ( self , format , * args ) :
"""Add comment to config item before saving to disk . You can add as many
comment lines as you like . If you use a null format , all comments are
deleted .""" | return lib . zconfig_set_comment ( self . _as_parameter_ , format , * args ) |
def get ( self , url_type ) :
"""Accepts either ' public ' or ' private ' as a parameter , and returns the
corresponding value for ' public _ url ' or ' private _ url ' , respectively .""" | lowtype = url_type . lower ( )
if lowtype == "public" :
return self . public_url
elif lowtype == "private" :
return self . private_url
else :
raise ValueError ( "Valid values are 'public' or 'private'; " "received '%s'." % url_type ) |
def _make_command_filename ( self , exe ) :
"""The internal function to build up a filename based on a command .""" | outfn = os . path . join ( self . commons [ 'cmddir' ] , self . name ( ) , self . _mangle_command ( exe ) )
# check for collisions
if os . path . exists ( outfn ) :
inc = 2
while True :
newfn = "%s_%d" % ( outfn , inc )
if not os . path . exists ( newfn ) :
outfn = newfn
... |
def get_static_properties ( self ) :
"""Returns a dictionary of STATICPROPERTIES
Examples
> > > reader = XBNReader ( ' xbn _ test . xml ' )
> > > reader . get _ static _ properties ( )
{ ' FORMAT ' : ' MSR DTAS XML ' , ' VERSION ' : ' 0.2 ' , ' CREATOR ' : ' Microsoft Research DTAS ' }""" | return { tags . tag : tags . get ( 'VALUE' ) for tags in self . bnmodel . find ( 'STATICPROPERTIES' ) } |
def mount ( cls , mount_point , lower_dir , upper_dir , mount_table = None ) :
"""Execute the mount . This requires root""" | ensure_directories ( mount_point , lower_dir , upper_dir )
# Load the mount table if it isn ' t given
if not mount_table :
mount_table = MountTable . load ( )
# Check if the mount _ point is in use
if mount_table . is_mounted ( mount_point ) : # Throw an error if it is
raise AlreadyMounted ( )
# Build mount opt... |
def next ( self ) :
"""Returns the next query result .
: return :
The next query result .
: rtype : dict
: raises StopIteration : If no more result is left .""" | if self . _has_finished :
raise StopIteration
if not len ( self . _buffer ) :
results = self . fetch_next_block ( )
self . _buffer . extend ( results )
if not len ( self . _buffer ) :
raise StopIteration
return self . _buffer . popleft ( ) |
def all_partitions ( mechanism , purview , node_labels = None ) :
"""Return all possible partitions of a mechanism and purview .
Partitions can consist of any number of parts .
Args :
mechanism ( tuple [ int ] ) : A mechanism .
purview ( tuple [ int ] ) : A purview .
Yields :
KPartition : A partition of... | for mechanism_partition in partitions ( mechanism ) :
mechanism_partition . append ( [ ] )
n_mechanism_parts = len ( mechanism_partition )
max_purview_partition = min ( len ( purview ) , n_mechanism_parts )
for n_purview_parts in range ( 1 , max_purview_partition + 1 ) :
n_empty = n_mechanism_pa... |
def start_server ( broker , backend = None , port = 12223 , max_tasks = 10000 , max_workers = 100 , blocking = False , debug = False ) : # pragma : no cover
"""Starts a Clearly Server programmatically .""" | _setup_logging ( debug )
queue_listener_dispatcher = Queue ( )
listener = EventListener ( broker , queue_listener_dispatcher , backend = backend , max_tasks_in_memory = max_tasks , max_workers_in_memory = max_workers )
dispatcher = StreamingDispatcher ( queue_listener_dispatcher )
clearlysrv = ClearlyServer ( listener ... |
def appendDatastore ( self , store ) :
'''Appends datastore ` store ` to this collection .''' | if not isinstance ( store , Datastore ) :
raise TypeError ( "stores must be of type %s" % Datastore )
self . _stores . append ( store ) |
def start ( self , channel = None ) :
"""Start this emulated device .
This triggers the controller to call start on all peripheral tiles in
the device to make sure they start after the controller does and then
it waits on each one to make sure they have finished initializing
before returning .
Args :
ch... | super ( EmulatedDevice , self ) . start ( channel )
self . emulator . start ( ) |
def listdirs ( path = '.' ) :
"""generator that returns all directories of * path *""" | import os
for f in os . listdir ( path ) :
if isdir ( join ( path , f ) ) :
yield join ( path , f ) if path != '.' else f |
def encodeSequence ( seq_vec , vocab , neutral_vocab , maxlen = None , seq_align = "start" , pad_value = "N" , encode_type = "one_hot" ) :
"""Convert a list of genetic sequences into one - hot - encoded array .
# Arguments
seq _ vec : list of strings ( genetic sequences )
vocab : list of chars : List of " wor... | if isinstance ( neutral_vocab , str ) :
neutral_vocab = [ neutral_vocab ]
if isinstance ( seq_vec , str ) :
raise ValueError ( "seq_vec should be an iterable returning " + "strings not a string itself" )
assert len ( vocab [ 0 ] ) == len ( pad_value )
assert pad_value in neutral_vocab
assert encode_type in [ "o... |
def poke_native ( getstate ) :
"""Serializer factory for types which state can be natively serialized .
Arguments :
getstate ( callable ) : takes an object and returns the object ' s state
to be passed to ` pokeNative ` .
Returns :
callable : serializer ( ` poke ` routine ) .""" | def poke ( service , objname , obj , container , visited = None , _stack = None ) :
service . pokeNative ( objname , getstate ( obj ) , container )
return poke |
def remove ( name = None , pkgs = None , jail = None , chroot = None , root = None , all_installed = False , force = False , glob = False , dryrun = False , recurse = False , regex = False , pcre = False , ** kwargs ) :
'''Remove a package from the database and system
. . note : :
This function can accessed usi... | del kwargs
# Unused parameter
try :
pkg_params = __salt__ [ 'pkg_resource.parse_targets' ] ( name , pkgs ) [ 0 ]
except MinionError as exc :
raise CommandExecutionError ( exc )
targets = [ ]
old = list_pkgs ( jail = jail , chroot = chroot , root = root , with_origin = True )
for pkg in pkg_params . items ( ) : ... |
def install ( self , apk_path , destination_dir = None , timeout_ms = None ) :
"""Install apk to device .
Doesn ' t support verifier file , instead allows destination directory to be
overridden .
Arguments :
apk _ path : Local path to apk to install .
destination _ dir : Optional destination directory . U... | if not destination_dir :
destination_dir = '/data/local/tmp/'
basename = os . path . basename ( apk_path )
destination_path = destination_dir + basename
self . push ( apk_path , destination_path , timeout_ms = timeout_ms )
return self . Shell ( 'pm install -r "%s"' % destination_path , timeout_ms = timeout_ms ) |
def pyeapi_call ( method , * args , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Invoke an arbitrary method from the ` ` pyeapi ` ` library .
This function forwards the existing connection details to the
: mod : ` pyeapi . run _ commands < salt . module . arista _ pyeapi . run _ commands > `
execution fun... | pyeapi_kwargs = pyeapi_nxos_api_args ( ** kwargs )
return __salt__ [ 'pyeapi.call' ] ( method , * args , ** pyeapi_kwargs ) |
def create_log2fc_bigwigs ( matrix , outdir , args ) : # type : ( pd . DataFrame , str , Namespace ) - > None
"""Create bigwigs from matrix .""" | call ( "mkdir -p {}" . format ( outdir ) , shell = True )
genome_size_dict = args . chromosome_sizes
outpaths = [ ]
for bed_file in matrix [ args . treatment ] :
outpath = join ( outdir , splitext ( basename ( bed_file ) ) [ 0 ] + "_log2fc.bw" )
outpaths . append ( outpath )
data = create_log2fc_data ( matrix ,... |
def advise ( self , item , stop = False ) :
"""Request updates when DDE data changes .""" | hszItem = DDE . CreateStringHandle ( self . _idInst , item , CP_WINUNICODE )
hDdeData = DDE . ClientTransaction ( LPBYTE ( ) , 0 , self . _hConv , hszItem , CF_TEXT , XTYP_ADVSTOP if stop else XTYP_ADVSTART , TIMEOUT_ASYNC , LPDWORD ( ) )
DDE . FreeStringHandle ( self . _idInst , hszItem )
if not hDdeData :
raise D... |
def create ( recipients , data , cipher , flags = 0 ) :
"""Creates and encrypts message
@ param recipients - list of X509 objects
@ param data - contents of the message
@ param cipher - CipherType object
@ param flags - flag""" | recp = StackOfX509 ( recipients )
bio = Membio ( data )
cms_ptr = libcrypto . CMS_encrypt ( recp . ptr , bio . bio , cipher . cipher , flags )
if cms_ptr is None :
raise CMSError ( "encrypt EnvelopedData" )
return EnvelopedData ( cms_ptr ) |
def get_build_template ( template_name , params = None , to_file = None ) :
'''get _ build template returns a string or file for a particular build template , which is
intended to build a version of a Singularity image on a cloud resource .
: param template _ name : the name of the template to retrieve in build... | base = get_installdir ( )
template_folder = "%s/build/scripts" % ( base )
template_file = "%s/%s" % ( template_folder , template_name )
if os . path . exists ( template_file ) :
bot . debug ( "Found template %s" % template_file )
# Implement when needed - substitute params here
# Will need to read in file i... |
def credits ( self ) :
"""Returns either a tuple representing the credit range or a
single integer if the range is set to one value .
Use self . cred to always get the tuple .""" | if self . cred [ 0 ] == self . cred [ 1 ] :
return self . cred [ 0 ]
return self . cred |
def get_stack_var ( name , depth = 0 ) :
'''This function may fiddle with the locals of the calling function ,
to make it the root function of the fiber . If called from a short - lived
function be sure to use a bigger frame depth .
Returns the fiber state or None .''' | base_frame = _get_base_frame ( depth )
if not base_frame : # Frame not found
raise RuntimeError ( "Base frame not found" )
# Lookup up the frame stack starting at the base frame for the fiber state
level = 0
frame = base_frame
while frame :
locals = frame . f_locals
value = locals . get ( name )
if valu... |
def iter_chunks ( self ) :
"""Yield each readable chunk present in the region .
Chunks that can not be read for whatever reason are silently skipped .
Warning : this function returns a : class : ` nbt . nbt . NBTFile ` object , use ` ` Chunk ( nbtfile ) ` ` to get a
: class : ` nbt . chunk . Chunk ` instance ... | for m in self . get_metadata ( ) :
try :
yield self . get_chunk ( m . x , m . z )
except RegionFileFormatError :
pass |
def _convert_hdxobjects ( self , hdxobjects ) : # type : ( List [ HDXObjectUpperBound ] ) - > List [ HDXObjectUpperBound ]
"""Helper function to convert supplied list of HDX objects to a list of dict
Args :
hdxobjects ( List [ T < = HDXObject ] ) : List of HDX objects to convert
Returns :
List [ Dict ] : Li... | newhdxobjects = list ( )
for hdxobject in hdxobjects :
newhdxobjects . append ( hdxobject . data )
return newhdxobjects |
def _spot_check_that_elements_produced_by_this_generator_have_attribute ( self , name ) :
"""Helper function to spot - check that the items produces by this generator have the attribute ` name ` .""" | g_tmp = self . values_gen . spawn ( )
sample_element = next ( g_tmp ) [ 0 ]
try :
getattr ( sample_element , name )
except AttributeError :
raise AttributeError ( f"Items produced by {self} do not have the attribute '{name}'" ) |
def extract_firmware ( self ) :
'''Extract camera firmware ( tag is called ' software ' in EXIF )''' | fields = [ 'Image Software' ]
software , _ = self . _extract_alternative_fields ( fields , default = "" , field_type = str )
return software |
def workspaces ( self , index = None ) :
"""return generator for all all workspace instances""" | c = self . centralWidget ( )
if index is None :
return ( c . widget ( n ) for n in range ( c . count ( ) ) )
else :
return c . widget ( index ) |
def calculate_trans ( thickness_cm : np . float , miu_per_cm : np . array ) :
"""calculate the transmission signal using the formula
transmission = exp ( - thickness _ cm * atoms _ per _ cm3 * 1e - 24 * sigma _ b )
Parameters :
thickness : float ( in cm )
atoms _ per _ cm3 : float ( number of atoms per cm3 ... | transmission = np . exp ( - thickness_cm * miu_per_cm )
return np . array ( transmission ) |
def __remove_obsolete_metadata ( self ) :
"""Removes obsolete entries from the metadata of all stored routines .""" | clean = { }
for key , _ in self . _source_file_names . items ( ) :
if key in self . _pystratum_metadata :
clean [ key ] = self . _pystratum_metadata [ key ]
self . _pystratum_metadata = clean |
def deserialize ( cls , target_class , pagination_response ) :
""": type target _ class : client . Pagination | type
: type pagination _ response : dict
: rtype : client . Pagination""" | pagination = client . Pagination ( )
pagination . __dict__ . update ( cls . parse_pagination_dict ( pagination_response ) )
return pagination |
def query_builder ( self , paths_rows = None , lat = None , lon = None , address = None , start_date = None , end_date = None , cloud_min = None , cloud_max = None ) :
"""Builds the proper search syntax ( query ) for Landsat API .
: param paths _ rows :
A string in this format : " 003,003,004,004 " . Must be in... | query = [ ]
or_string = ''
and_string = ''
search_string = ''
if paths_rows : # Coverting rows and paths to paired list
new_array = create_paired_list ( paths_rows )
paths_rows = [ '(%s)' % self . row_path_builder ( i [ 0 ] , i [ 1 ] ) for i in new_array ]
or_string = '+OR+' . join ( map ( str , paths_rows ... |
def accel_quit ( self , * args ) :
"""Callback to prompt the user whether to quit Guake or not .""" | procs = self . notebook_manager . get_running_fg_processes_count ( )
tabs = self . notebook_manager . get_n_pages ( )
notebooks = self . notebook_manager . get_n_notebooks ( )
prompt_cfg = self . settings . general . get_boolean ( 'prompt-on-quit' )
prompt_tab_cfg = self . settings . general . get_int ( 'prompt-on-clos... |
def copy ( self ) :
"""Return a shallow copy of this graph .""" | other = DirectedGraph ( )
other . _vertices = set ( self . _vertices )
other . _forwards = { k : set ( v ) for k , v in self . _forwards . items ( ) }
other . _backwards = { k : set ( v ) for k , v in self . _backwards . items ( ) }
return other |
def get_actions ( actions ) :
"""Get actions .""" | new_actions = [ ]
if actions :
for action in actions :
action_obj = get_action ( action )
if action_obj :
new_actions . append ( action_obj )
return new_actions |
def icp ( a , b , initial = np . identity ( 4 ) , threshold = 1e-5 , max_iterations = 20 , ** kwargs ) :
"""Apply the iterative closest point algorithm to align a point cloud with
another point cloud or mesh . Will only produce reasonable results if the
initial transformation is roughly correct . Initial transf... | a = np . asanyarray ( a , dtype = np . float64 )
if not util . is_shape ( a , ( - 1 , 3 ) ) :
raise ValueError ( 'points must be (n,3)!' )
is_mesh = util . is_instance_named ( b , 'Trimesh' )
if not is_mesh :
b = np . asanyarray ( b , dtype = np . float64 )
if not util . is_shape ( b , ( - 1 , 3 ) ) :
... |
def to_vcf ( self , path , rename = None , number = None , description = None , fill = None , write_header = True ) :
r"""Write to a variant call format ( VCF ) file .
Parameters
path : string
File path .
rename : dict , optional
Rename these columns in the VCF .
number : dict , optional
Override the ... | write_vcf ( path , callset = self , rename = rename , number = number , description = description , fill = fill , write_header = write_header ) |
def load_json ( file ) :
"""Load JSON file at app start""" | here = os . path . dirname ( os . path . abspath ( __file__ ) )
with open ( os . path . join ( here , file ) ) as jfile :
data = json . load ( jfile )
return data |
def render_tile ( cells , ti , tj , render , params , metadata , layout , summary ) :
"""Render each cell in the tile and stitch it into a single image""" | image_size = params [ "cell_size" ] * params [ "n_tile" ]
tile = Image . new ( "RGB" , ( image_size , image_size ) , ( 255 , 255 , 255 ) )
keys = cells . keys ( )
for i , key in enumerate ( keys ) :
print ( "cell" , i + 1 , "/" , len ( keys ) , end = '\r' )
cell_image = render ( cells [ key ] , params , metadat... |
def get_graph_metadata ( self , graph ) :
"""Get the model metadata from a given onnx graph .""" | _params = set ( )
for tensor_vals in graph . initializer :
_params . add ( tensor_vals . name )
input_data = [ ]
for graph_input in graph . input :
if graph_input . name not in _params :
shape = [ val . dim_value for val in graph_input . type . tensor_type . shape . dim ]
input_data . append ( (... |
def outputs ( ctx , client , revision , paths ) :
r"""Show output files in the repository .
< PATHS > Files to show . If no files are given all output files are shown .""" | graph = Graph ( client )
filter = graph . build ( paths = paths , revision = revision )
output_paths = graph . output_paths
click . echo ( '\n' . join ( graph . _format_path ( path ) for path in output_paths ) )
if paths :
if not output_paths :
ctx . exit ( 1 )
from renku . models . _datastructures impo... |
def collection ( self , attribute ) :
"""Returns the collection corresponding the attribute name .""" | return { "dependencies" : self . dependencies , "publics" : self . publics , "members" : self . members , "types" : self . types , "executables" : self . executables , "interfaces" : self . interfaces } [ attribute ] |
def remove_type_from_resource ( type_id , resource_type , resource_id , ** kwargs ) :
"""Remove a resource type trom a resource""" | node_id = resource_id if resource_type == 'NODE' else None
link_id = resource_id if resource_type == 'LINK' else None
group_id = resource_id if resource_type == 'GROUP' else None
resourcetype = db . DBSession . query ( ResourceType ) . filter ( ResourceType . type_id == type_id , ResourceType . ref_key == resource_type... |
def derivative ( self , point ) :
"""Derivative of this operator .
` ` PowerOperator ( p ) . derivative ( y ) ( x ) = = p * y * * ( p - 1 ) * x ` `
Parameters
point : ` domain ` element
The point in which to take the derivative
Returns
derivative : ` Operator `
The derivative in ` ` point ` `
Exampl... | return self . exponent * MultiplyOperator ( point ** ( self . exponent - 1 ) , domain = self . domain , range = self . range ) |
def snapshots ( self ) :
"""Get all Volumes of type Snapshot . Updates every time - no caching .
: return : a ` list ` of all the ` ScaleIO _ Volume ` that have a are of type Snapshot .
: rtype : list""" | self . connection . _check_login ( )
response = self . connection . _do_get ( "{}/{}" . format ( self . connection . _api_url , "types/Volume/instances" ) ) . json ( )
all_volumes_snapshot = [ ]
for volume in response :
if volume [ 'volumeType' ] == 'Snapshot' :
all_volumes_snapshot . append ( Volume . from... |
def download ( feature_type , output_base_path , extent , progress_dialog = None , server_url = None ) :
"""Download shapefiles from Kartoza server .
. . versionadded : : 3.2
: param feature _ type : What kind of features should be downloaded .
Currently ' buildings ' , ' building - points ' or ' roads ' are ... | if not server_url :
server_url = PRODUCTION_SERVER
# preparing necessary data
min_longitude = extent [ 0 ]
min_latitude = extent [ 1 ]
max_longitude = extent [ 2 ]
max_latitude = extent [ 3 ]
box = ( '{min_longitude},{min_latitude},{max_longitude},' '{max_latitude}' ) . format ( min_longitude = min_longitude , min_... |
def resolve ( self ) :
'Resolve pathname shell variables and ~ userdir' | return os . path . expandvars ( os . path . expanduser ( self . fqpn ) ) |
def hgetall ( self , key , * , encoding = _NOTSET ) :
"""Get all the fields and values in a hash .""" | fut = self . execute ( b'HGETALL' , key , encoding = encoding )
return wait_make_dict ( fut ) |
def scan ( self , search_path = None ) :
"""Scan ` search _ path ` for distributions usable in this environment
Any distributions found are added to the environment .
` search _ path ` should be a sequence of ` ` sys . path ` ` items . If not
supplied , ` ` sys . path ` ` is used . Only distributions conformi... | if search_path is None :
search_path = sys . path
for item in search_path :
for dist in find_distributions ( item ) :
self . add ( dist ) |
def initialize ( self , conf , ctx ) :
"""Initialization steps :
1 . Prepare elasticsearch connection , including details for indexing .""" | config = get_config ( ) [ 'ElasticsearchIndexBolt' ]
elasticsearch_class = import_name ( config [ 'elasticsearch_class' ] )
self . es = elasticsearch_class ( ** config [ 'elasticsearch_init' ] )
self . index = config [ 'index' ]
self . doc_type = config [ 'doc_type' ] |
def generateAcceptHeader ( * elements ) :
"""Generate an accept header value
[ str or ( str , float ) ] - > str""" | parts = [ ]
for element in elements :
if type ( element ) is str :
qs = "1.0"
mtype = element
else :
mtype , q = element
q = float ( q )
if q > 1 or q <= 0 :
raise ValueError ( 'Invalid preference factor: %r' % q )
qs = '%0.1f' % ( q , )
parts . ap... |
def delete_floatingip ( self , floatingip_id ) :
'''Deletes the specified floatingip''' | ret = self . network_conn . delete_floatingip ( floatingip_id )
return ret if ret else True |
def relabel_squeeze ( data ) :
"""Makes relabeling of data if there are unused values .""" | palette , index = np . unique ( data , return_inverse = True )
data = index . reshape ( data . shape )
# realy slow solution
# unq = np . unique ( data )
# actual _ label = 0
# for lab in unq :
# data [ data = = lab ] = actual _ label
# actual _ label + = 1
# one another solution probably slower
# arr = data
# data = (... |
from collections import Counter
from itertools import chain
def element_frequency ( lists ) :
"""Calculate the frequency of each element in a list of lists using collections module .
Examples :
> > > element _ frequency ( [ [ 1 , 2 , 3 , 2 ] , [ 4 , 5 , 6 , 2 ] , [ 7 , 1 , 9 , 5 ] ] )
{2 : 3 , 1 : 2 , 5 : 2 ,... | freq_table = Counter ( chain ( * lists ) )
return freq_table |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.