signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def add ( self , value ) :
"""Add a value to the buffer .""" | ind = int ( self . _ind % self . shape )
self . _pos = self . _ind % self . shape
self . _values [ ind ] = value
if self . _ind < self . shape :
self . _ind += 1
# fast fill
else :
self . _ind += self . _splitValue
self . _splitPos += self . _splitValue
self . _cached = False |
def export_avg_losses_ebrisk ( ekey , dstore ) :
""": param ekey : export key , i . e . a pair ( datastore key , fmt )
: param dstore : datastore object""" | name = ekey [ 0 ]
oq = dstore [ 'oqparam' ]
dt = oq . loss_dt ( )
value = dstore [ name ] . value
# shape ( A , L )
writer = writers . CsvWriter ( fmt = writers . FIVEDIGITS )
assets = get_assets ( dstore )
dest = dstore . build_fname ( name , 'mean' , 'csv' )
array = numpy . zeros ( len ( value ) , dt )
for l , lt in ... |
def playTone ( self , freq , reps = 1 , delay = 0.1 , muteDelay = 0.0 ) :
"""\~english Play a tone
\~chinese 播放音符
\~english
@ param freq
@ param reps
@ param delay > = 0 ( s ) if 0 means do not delay . tone play will be Stop immediately < br >
@ param muteDelay > = 0 ( s ) If 0 means no pause after play... | if freq == 0 :
self . stopTone ( )
self . _delay ( delay )
# sleep ( delay )
return False
if self . _pwmPlayer == None :
self . _initPWMPlayer ( freq )
for r in range ( 0 , reps ) :
self . _pwmPlayer . start ( self . TONE_DUTY )
self . _pwmPlayer . ChangeFrequency ( freq )
self . _delay ... |
def encodeWord ( self , word ) :
"""Encode word in API format .
: param word : Word to encode .
: returns : Encoded word .""" | encoded_word = word . encode ( encoding = self . encoding , errors = 'strict' )
return Encoder . encodeLength ( len ( word ) ) + encoded_word |
def delete_user ( deleted_user_id , ** kwargs ) :
"""Delete a user""" | # check _ perm ( kwargs . get ( ' user _ id ' ) , ' edit _ user ' )
try :
user_i = db . DBSession . query ( User ) . filter ( User . id == deleted_user_id ) . one ( )
db . DBSession . delete ( user_i )
except NoResultFound :
raise ResourceNotFoundError ( "User (user_id=%s) does not exist" % ( deleted_user_i... |
def get_word_under_cursor ( self ) :
"""Returns the document word under cursor .
: return : Word under cursor .
: rtype : QString""" | if not re . match ( r"^\w+$" , foundations . strings . to_string ( self . get_previous_character ( ) ) ) :
return QString ( )
cursor = self . textCursor ( )
cursor . movePosition ( QTextCursor . PreviousWord , QTextCursor . MoveAnchor )
cursor . movePosition ( QTextCursor . EndOfWord , QTextCursor . KeepAnchor )
re... |
def set_trigger_group_bit_mask ( self , trigger_group_bit_mask ) :
"""Set the trigger _ group _ bit _ mask for the current group / button .""" | set_cmd = self . _create_set_property_msg ( "_trigger_group_bit_mask" , 0x0c , trigger_group_bit_mask )
self . _send_method ( set_cmd , self . _property_set ) |
def start_trajectory ( self , trajectory_id , time_scale = 1.0 , relative = False , reversed = False , group_mask = ALL_GROUPS ) :
"""starts executing a specified trajectory
: param trajectory _ id : id of the trajectory ( previously defined by
define _ trajectory )
: param time _ scale : time factor ; 1.0 = ... | self . _send_packet ( struct . pack ( '<BBBBBf' , self . COMMAND_START_TRAJECTORY , group_mask , relative , reversed , trajectory_id , time_scale ) ) |
def get_editor ( self , file ) :
"""Returns the Model editor associated with given file .
: param file : File to search editors for .
: type file : unicode
: return : Editor .
: rtype : Editor""" | for editor in self . __model . list_editors ( ) :
if editor . file == file :
return editor |
def value_iteration ( self , v_init = None , epsilon = None , max_iter = None ) :
"""Solve the optimization problem by value iteration . See the
` solve ` method .""" | if self . beta == 1 :
raise NotImplementedError ( self . _error_msg_no_discounting )
if max_iter is None :
max_iter = self . max_iter
if epsilon is None :
epsilon = self . epsilon
try :
tol = epsilon * ( 1 - self . beta ) / ( 2 * self . beta )
except ZeroDivisionError : # Raised if beta = 0
tol = np... |
def masked_within_block_local_attention_1d ( q , k , v , block_length = 64 , name = None ) :
"""Attention to the source and a neighborhood to the left within a block .
The sequence is divided into blocks of length block _ length . Attention for a
given query position can only see memory positions less than or e... | with tf . variable_scope ( name , default_name = "within_local_attention_1d" , values = [ q , k , v ] ) :
batch , heads , length , depth_k = common_layers . shape_list ( q )
depth_v = common_layers . shape_list ( v ) [ - 1 ]
if isinstance ( block_length , tf . Tensor ) :
const = tf . contrib . util ... |
def disconnect ( self , * args , ** kwargs ) :
"""Close connection , see : meth : ` . CMClient . disconnect `""" | self . logged_on = False
CMClient . disconnect ( self , * args , ** kwargs ) |
def _jinja_sub ( self , st ) :
"""Create a Jina template engine , then perform substitutions on a string""" | if isinstance ( st , string_types ) :
from jinja2 import Template
try :
for i in range ( 5 ) : # Only do 5 recursive substitutions .
st = Template ( st ) . render ( ** ( self . _top . dict ) )
if '{{' not in st :
break
return st
except Exception as e :... |
def docker_monitor ( self , cidfile , tmpdir_prefix , cleanup_cidfile , process ) : # type : ( Text , Text , bool , subprocess . Popen ) - > None
"""Record memory usage of the running Docker container .""" | # Todo : consider switching to ` docker create ` / ` docker start `
# instead of ` docker run ` as ` docker create ` outputs the container ID
# to stdout , but the container is frozen , thus allowing us to start the
# monitoring process without dealing with the cidfile or too - fast
# container execution
cid = None
whi... |
def candidates ( self , word ) :
"""Generate possible spelling corrections for the provided word up to
an edit distance of two , if and only when needed
Args :
word ( str ) : The word for which to calculate candidate spellings
Returns :
set : The set of words that are possible candidates""" | if self . known ( [ word ] ) : # short - cut if word is correct already
return { word }
# get edit distance 1 . . .
res = [ x for x in self . edit_distance_1 ( word ) ]
tmp = self . known ( res )
if tmp :
return tmp
# if still not found , use the edit distance 1 to calc edit distance 2
if self . _distance == 2 ... |
def _unhash ( hashed , alphabet ) :
"""Restores a number tuple from hashed using the given ` alphabet ` index .""" | number = 0
len_alphabet = len ( alphabet )
for character in hashed :
position = alphabet . index ( character )
number *= len_alphabet
number += position
return number |
def match_events ( ref , est , window , distance = None ) :
"""Compute a maximum matching between reference and estimated event times ,
subject to a window constraint .
Given two lists of event times ` ` ref ` ` and ` ` est ` ` , we seek the largest set
of correspondences ` ` ( ref [ i ] , est [ j ] ) ` ` suc... | if distance is not None : # Compute the indices of feasible pairings
hits = np . where ( distance ( ref , est ) <= window )
else :
hits = _fast_hit_windows ( ref , est , window )
# Construct the graph input
G = { }
for ref_i , est_i in zip ( * hits ) :
if est_i not in G :
G [ est_i ] = [ ]
G [ e... |
def validate_redis ( self , db_data , user_data , oper ) :
"""Validate data in Redis .
Args :
db _ data ( str ) : The data store in Redis .
user _ data ( str ) : The user provided data .
oper ( str ) : The comparison operator .
Returns :
bool : True if the data passed validation .""" | passed = True
# convert any int to string since playbooks don ' t support int values
if isinstance ( db_data , int ) :
db_data = str ( db_data )
if isinstance ( user_data , int ) :
user_data = str ( user_data )
# try to sort list of strings for simple comparisons
# if list has a more complex data structure the ... |
def getquerydict ( self , sep = '&' , encoding = 'utf-8' , errors = 'strict' ) :
"""Split the query component into individual ` name = value ` pairs
separated by ` sep ` and return a dictionary of query variables .
The dictionary keys are the unique query variable names and
the values are lists of values for ... | dict = collections . defaultdict ( list )
for name , value in self . getquerylist ( sep , encoding , errors ) :
dict [ name ] . append ( value )
return dict |
def verify_contracts ( ) :
"""Verify that the contracts are deployed correctly in the network .
: raise Exception : raise exception if the contracts are not deployed correctly .""" | artifacts_path = ConfigProvider . get_config ( ) . keeper_path
logger . info ( f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}' )
if os . environ . get ( 'KEEPER_NETWORK_NAME' ) :
logger . warning ( f'The `KEEPER_NETWORK_NAME` env var is set to ' f'{os.environ.get("KEEPER_NETWORK_NAME")}. ' f'This... |
def only_extras ( self ) :
"""Return True if this instance only has key , value pairs for keys
that are not defined in c _ params .
: return : True / False""" | known = [ key for key in self . _dict . keys ( ) if key in self . c_param ]
if not known :
return True
else :
return False |
def var ( type = None , # noqa
default = None , name = None , title = None , description = None , required = True , examples = None , encoder = None , decoder = None , min = None , # noqa
max = None , # noqa
unique = None , contains = None , ** kwargs , ) :
"""Creates a config variable .
Use this method to create... | # NOTE : this method overrides some of the builtin Python method names on purpose in
# order to supply a readable and easy to understand api
# In this case it is not dangerous as they are only overriden in the scope and are
# never used within the scope
kwargs . update ( dict ( default = default , type = type ) )
retur... |
def add_presenter ( self , presenter ) :
"""Add presenter to a collection . If the given presenter is a : class : ` . WWebEnhancedPresenter ` instance
then public routes are checked ( via : meth : ` . . WWebEnhancedPresenter . _ _ public _ routes _ _ ` method ) and are
added in this route map
: param presente... | self . __presenter_collection . add ( presenter )
if issubclass ( presenter , WWebEnhancedPresenter ) is True :
for route in presenter . __public_routes__ ( ) :
self . route_map ( ) . append ( route ) |
def build_info ( self ) :
"""Return the build ' s info""" | if 'build_info' not in self . _memo :
self . _memo [ 'build_info' ] = _get_url ( self . artifact_url ( 'json' ) ) . json ( )
return self . _memo [ 'build_info' ] |
def draw_summary ( self , history , title = "" ) :
"""Inserts a text summary at the top that lists the number of steps and total
training time .""" | # Generate summary string
time_str = str ( history . get_total_time ( ) ) . split ( "." ) [ 0 ]
# remove microseconds
summary = "Step: {} Time: {}" . format ( history . step , time_str )
if title :
summary = title + "\n\n" + summary
self . figure . suptitle ( summary ) |
def put_document ( document_path : str , content_type : str , presigned_url : str ) -> str :
"""Convenience method for putting a document to presigned url .
> > > from las import Client
> > > client = Client ( endpoint = ' < api endpoint > ' )
> > > client . put _ document ( document _ path = ' document . jpe... | body = pathlib . Path ( document_path ) . read_bytes ( )
headers = { 'Content-Type' : content_type }
put_document_response = requests . put ( presigned_url , data = body , headers = headers )
put_document_response . raise_for_status ( )
return put_document_response . content . decode ( ) |
def fetch_next_block ( self ) :
"""Returns a block of results with respecting retry policy .
This method only exists for backward compatibility reasons . ( Because QueryIterable
has exposed fetch _ next _ block api ) .
: return :
List of results .
: rtype : list""" | if not self . _has_more_pages ( ) :
return [ ]
if len ( self . _buffer ) : # if there is anything in the buffer returns that
res = list ( self . _buffer )
self . _buffer . clear ( )
return res
else : # fetches the next block
return self . _fetch_next_block ( ) |
def service_healthy ( service_name , app_id = None ) :
"""Check whether a named service is healthy
: param service _ name : the service name
: type service _ name : str
: param app _ id : app _ id to filter
: type app _ id : str
: return : True if healthy , False otherwise
: rtype : bool""" | marathon_client = marathon . create_client ( )
apps = marathon_client . get_apps_for_framework ( service_name )
if apps :
for app in apps :
if ( app_id is not None ) and ( app [ 'id' ] != "/{}" . format ( str ( app_id ) ) ) :
continue
if ( app [ 'tasksHealthy' ] ) and ( app [ 'tasksRunni... |
def cmd ( send , msg , args ) :
"""Causes the bot to snack on something .
Syntax : { command } [ object ]""" | if not msg :
send ( "This tastes yummy!" )
elif msg == args [ 'botnick' ] :
send ( "wyang says Cannibalism is generally frowned upon." )
else :
send ( "%s tastes yummy!" % msg . capitalize ( ) ) |
def team_players ( self , team ) :
"""Prints the team players in a pretty format""" | players = sorted ( team , key = lambda d : d [ 'shirtNumber' ] )
click . secho ( "%-4s %-25s %-20s %-20s %-15s" % ( "N." , "NAME" , "POSITION" , "NATIONALITY" , "BIRTHDAY" ) , bold = True , fg = self . colors . MISC )
fmt = ( u"{shirtNumber:<4} {name:<28} {position:<23} {nationality:<23}" u" {dateOfBirth:<18}"... |
def get_edge_pathways ( self , edge_id ) :
"""Get the pathways associated with an edge .
Parameters
edge _ id : tup ( int , int )
Returns
tup ( str , str ) | None , the edge as a pair of 2 pathways if the edge id
is in this network""" | vertex0_id , vertex1_id = edge_id
pw0 = self . get_pathway_from_vertex_id ( vertex0_id )
pw1 = self . get_pathway_from_vertex_id ( vertex1_id )
if not pw0 or not pw1 :
return None
return ( pw0 , pw1 ) |
def maybe_convert_dtype ( data , copy ) :
"""Convert data based on dtype conventions , issuing deprecation warnings
or errors where appropriate .
Parameters
data : np . ndarray or pd . Index
copy : bool
Returns
data : np . ndarray or pd . Index
copy : bool
Raises
TypeError : PeriodDType data is pa... | if is_float_dtype ( data ) : # Note : we must cast to datetime64 [ ns ] here in order to treat these
# as wall - times instead of UTC timestamps .
data = data . astype ( _NS_DTYPE )
copy = False
# TODO : deprecate this behavior to instead treat symmetrically
# with integer dtypes . See discussion in GH ... |
def pagerank_limit_push ( s , r , w_i , a_i , push_node , rho ) :
"""Performs a random step without a self - loop .""" | # Calculate the A and B quantities to infinity
A_inf = rho * r [ push_node ]
B_inf = ( 1 - rho ) * r [ push_node ]
# Update approximate Pagerank and residual vectors
s [ push_node ] += A_inf
r [ push_node ] = 0.0
# Update residual vector at push node ' s adjacent nodes
r [ a_i ] += B_inf * w_i |
def parse_elements ( elements ) :
"""Parse waypoint data elements .
Args :
elements ( list ) : Data values for fix
Returns :
nmea . Waypoint : Object representing data""" | if not len ( elements ) == 5 :
raise ValueError ( 'Invalid WPL waypoint data' )
# Latitude and longitude are checked for validity during Fix
# instantiation
latitude = parse_latitude ( elements [ 0 ] , elements [ 1 ] )
longitude = parse_longitude ( elements [ 2 ] , elements [ 3 ] )
name = elements [ 4 ]
return Wayp... |
def dhcp_options_present ( name , dhcp_options_id = None , vpc_name = None , vpc_id = None , domain_name = None , domain_name_servers = None , ntp_servers = None , netbios_name_servers = None , netbios_node_type = None , tags = None , region = None , key = None , keyid = None , profile = None ) :
'''Ensure a set of... | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
_new = { 'domain_name' : domain_name , 'domain_name_servers' : domain_name_servers , 'ntp_servers' : ntp_servers , 'netbios_name_servers' : netbios_name_servers , 'netbios_node_type' : netbios_node_type }
# boto provides no " update _ dhcp _ o... |
def unregister ( self , obj = None ) :
"""Unregisters the object from the system . If None is supplied , then
all objects will be unregistered
: param obj : < str > or < orb . Database > or < orb . Schema > or None""" | if obj is None :
self . __databases . clear ( )
self . __schemas . clear ( )
elif isinstance ( obj , orb . Schema ) :
self . __schemas . pop ( obj . name ( ) , None )
elif isinstance ( obj , orb . Database ) :
if obj == self . __current_db :
self . __current_db = None
self . __databases . po... |
def multiplicon_file ( self , value ) :
"""Setter for _ multiplicon _ file attribute""" | assert os . path . isfile ( value ) , "%s is not a valid file" % value
self . _multiplicon_file = value |
def data_received ( self , data ) :
"""Handle received data .""" | self . _data_buffer += data . decode ( )
if not self . _data_buffer . endswith ( '\r\n' ) :
return
data = self . _data_buffer
self . _data_buffer = ''
# clear buffer
for cmd in data . strip ( ) . split ( '\r\n' ) :
data = json . loads ( cmd )
if not isinstance ( data , list ) :
data = [ data ]
f... |
def get_installed_distributions ( skip = stdlib_pkgs ) :
"""Return a list of installed Distribution objects .
` ` skip ` ` argument is an iterable of lower - case project names to
ignore ; defaults to stdlib _ pkgs""" | return [ d for d in pkg_resources . working_set if d . key not in skip ] |
def bisect_key_left ( self , key ) :
"""Similar to the * bisect * module in the standard library , this returns an
appropriate index to insert a value with a given * key * . If values with
* key * are already present , the insertion point will be before ( to the
left of ) any existing entries .""" | _maxes = self . _maxes
if not _maxes :
return 0
pos = bisect_left ( _maxes , key )
if pos == len ( _maxes ) :
return self . _len
idx = bisect_left ( self . _keys [ pos ] , key )
return self . _loc ( pos , idx ) |
def is_id_only ( self ) :
"""Return True if identifier information only .""" | for key , value in self . items ( ) :
if key not in { 'names' , 'labels' , 'roles' } and value :
return False
if self . names or self . labels :
return True
return False |
def do_open ( self , args ) :
"""Open resource by number , resource name or alias : open 3""" | if not args :
print ( 'A resource name must be specified.' )
return
if self . current :
print ( 'You can only open one resource at a time. Please close the current one first.' )
return
if args . isdigit ( ) :
try :
args = self . resources [ int ( args ) ] [ 0 ]
except IndexError :
... |
def get_request_authorization ( method , resource , key , params , headers ) :
""": return bytes ( PY2 ) or string ( PY2)""" | if not key :
return six . b ( '' )
content = method + "\n"
if 'Content-MD5' in headers :
content += headers [ 'Content-MD5' ]
content += '\n'
if 'Content-Type' in headers :
content += headers [ 'Content-Type' ]
content += "\n"
content += headers [ 'Date' ] + "\n"
content += Util . canonicalized_log_headers ... |
def _gen_prov ( self ) :
"""Extracts provenance information from the pipeline into a PipelineProv
object
Returns
prov : dict [ str , * ]
A dictionary containing the provenance information to record
for the pipeline""" | # Export worfklow graph to node - link data format
wf_dict = nx_json . node_link_data ( self . workflow . _graph )
# Replace references to Node objects with the node ' s provenance
# information and convert to a dict organised by node name to allow it
# to be compared more easily . Also change link node - references fr... |
def _get_bit ( self , n , hash_bytes ) :
"""Determines if the n - th bit of passed bytes is 1 or 0.
Arguments :
hash _ bytes - List of hash byte values for which the n - th bit value
should be checked . Each element of the list should be an integer from
0 to 255.
Returns :
True if the bit is 1 . False i... | if hash_bytes [ n // 8 ] >> int ( 8 - ( ( n % 8 ) + 1 ) ) & 1 == 1 :
return True
return False |
def get_exchange ( self , vhost , name ) :
"""Gets a single exchange which requires a vhost and name .
: param string vhost : The vhost containing the target exchange
: param string name : The name of the exchange
: returns : dict""" | vhost = quote ( vhost , '' )
name = quote ( name , '' )
path = Client . urls [ 'exchange_by_name' ] % ( vhost , name )
exch = self . _call ( path , 'GET' )
return exch |
def initialize ( self ) :
'''Calling this function initializes the printer .
Args :
None
Returns :
None
Raises :
None''' | self . fonttype = self . font_types [ 'bitmap' ]
self . send ( chr ( 27 ) + chr ( 64 ) ) |
def ensure_unicode ( text ) :
u"""helper to ensure that text passed to WriteConsoleW is unicode""" | if isinstance ( text , str ) :
try :
return text . decode ( pyreadline_codepage , u"replace" )
except ( LookupError , TypeError ) :
return text . decode ( u"ascii" , u"replace" )
return text |
def _load_kgXref ( filename ) :
"""Load UCSC kgXref table .
Parameters
filename : str
path to kgXref file
Returns
df : pandas . DataFrame
kgXref table if loading was successful , else None""" | try :
df = pd . read_table ( filename , names = [ "kgID" , "mRNA" , "spID" , "spDisplayID" , "geneSymbol" , "refseq" , "protAcc" , "description" , "rfamAcc" , "tRnaName" , ] , index_col = 0 , dtype = object , )
return df
except Exception as err :
print ( err )
return None |
def parse_redis_url ( url ) :
"""Given a url like redis : / / localhost : 6379/0 , return a dict with host , port ,
and db members .""" | warnings . warn ( "Use redis.StrictRedis.from_url instead" , DeprecationWarning , stacklevel = 2 )
parsed = urllib . parse . urlsplit ( url )
return { 'host' : parsed . hostname , 'port' : parsed . port , 'db' : int ( parsed . path . replace ( '/' , '' ) ) , } |
def ProcessPathSpec ( self , mediator , path_spec ) :
"""Processes a path specification .
Args :
mediator ( ParserMediator ) : mediates the interactions between
parsers and other components , such as storage and abort signals .
path _ spec ( dfvfs . PathSpec ) : path specification .""" | self . last_activity_timestamp = time . time ( )
self . processing_status = definitions . STATUS_INDICATOR_RUNNING
file_entry = path_spec_resolver . Resolver . OpenFileEntry ( path_spec , resolver_context = mediator . resolver_context )
if file_entry is None :
display_name = mediator . GetDisplayNameForPathSpec ( p... |
def debug_channel ( mdf , group , channel , dependency , file = None ) :
"""use this to print debug information in case of errors
Parameters
mdf : MDF
source MDF object
group : dict
group
channel : Channel
channel object
dependency : ChannelDependency
channel dependency object""" | print ( "MDF" , "=" * 76 , file = file )
print ( "name:" , mdf . name , file = file )
print ( "version:" , mdf . version , file = file )
print ( "read fragment size:" , mdf . _read_fragment_size , file = file )
print ( "write fragment size:" , mdf . _write_fragment_size , file = file )
print ( )
parents , dtypes = mdf ... |
def wr_py_goea_results ( self , fout_py , goea_results , ** kws ) :
"""Save GOEA results into Python package containing list of namedtuples .""" | var_name = kws . get ( "var_name" , "goea_results" )
docstring = kws . get ( "docstring" , "" )
sortby = kws . get ( "sortby" , None )
if goea_results :
from goatools . nt_utils import wr_py_nts
nts_goea = goea_results
# If list has GOEnrichmentRecords or verbose namedtuples , exclude some fields .
if h... |
def serialise ( self , element : Element , ** kwargs ) -> str :
"""Serialises the given element into JSON .
> > > JSONSerialiser ( ) . serialise ( String ( content = ' Hello ' ) )
' { " element " : " string " , " content " : " Hello " } '""" | return json . dumps ( self . serialise_dict ( element ) , ** kwargs ) |
def update_pipeline_field ( self , pipeline_key , field ) :
'''Upates pipeline field as specified
Args :
pipeline _ keykey for pipeline where the fields lives
field StreakField object with fresh data
returns ( status code , updated field dict )''' | uri = '/' . join ( [ self . api_uri , self . pipelines_suffix , pipeline_key , self . fields_suffix ] )
return self . _update_field ( uri , field ) |
def export ( self , obj ) :
"""Returns value from the provided object converted to export
representation .""" | value = self . get_value ( obj )
if value is None :
return ""
return self . widget . render ( value , obj ) |
def VerifyStructure ( self , parser_mediator , line ) :
"""Verify that this file is a XChat log file .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
line ( str ) : line from a text file .
Returns :
bool : True if th... | try :
structure = self . _HEADER . parseString ( line )
except pyparsing . ParseException :
logger . debug ( 'Not a XChat log file' )
return False
_ , month , day , hours , minutes , seconds , year = structure . date_time
month = timelib . MONTH_DICT . get ( month . lower ( ) , 0 )
time_elements_tuple = ( y... |
def recursive_chmod ( path , mode = 0755 ) :
"""Recursively change ` ` mode ` ` for given ` ` path ` ` . Same as ` ` chmod - R mode ` ` .
Args :
path ( str ) : Path of the directory / file .
mode ( octal int , default 0755 ) : New mode of the file .
Warning :
Don ' t forget to add ` ` 0 ` ` at the beginni... | passwd_reader . set_permissions ( path , mode = mode )
if os . path . isfile ( path ) :
return
# recursively change mode of all subdirectories
for root , dirs , files in os . walk ( path ) :
for fn in files + dirs :
passwd_reader . set_permissions ( os . path . join ( root , fn ) , mode = mode ) |
def get_price_id_list ( self , package_keyname , item_keynames , core = None ) :
"""Converts a list of item keynames to a list of price IDs .
This function is used to convert a list of item keynames into
a list of price IDs that are used in the Product _ Order verifyOrder ( )
and placeOrder ( ) functions .
... | mask = 'id, itemCategory, keyName, prices[categories]'
items = self . list_items ( package_keyname , mask = mask )
prices = [ ]
category_dict = { "gpu0" : - 1 , "pcie_slot0" : - 1 }
for item_keyname in item_keynames :
try : # Need to find the item in the package that has a matching
# keyName with the current it... |
def headers ( self ) :
"""The contig ID must be twenty characters or fewer . The names of the headers created following SPAdes assembly
are usually far too long . This renames them as the sample name""" | for sample in self . metadata . samples : # Create an attribute to store the path / file name of the fasta file with fixed headers
sample . general . fixedheaders = sample . general . bestassemblyfile . replace ( '.fasta' , '.ffn' )
sample . general . fixedheaders = os . path . abspath ( sample . general . fixe... |
def forward_substitution ( matrix_l , matrix_b ) :
"""Forward substitution method for the solution of linear systems .
Solves the equation : math : ` Ly = b ` using forward substitution method
where : math : ` L ` is a lower triangular matrix and : math : ` b ` is a column matrix .
: param matrix _ l : L , lo... | q = len ( matrix_b )
matrix_y = [ 0.0 for _ in range ( q ) ]
matrix_y [ 0 ] = float ( matrix_b [ 0 ] ) / float ( matrix_l [ 0 ] [ 0 ] )
for i in range ( 1 , q ) :
matrix_y [ i ] = float ( matrix_b [ i ] ) - sum ( [ matrix_l [ i ] [ j ] * matrix_y [ j ] for j in range ( 0 , i ) ] )
matrix_y [ i ] /= float ( matr... |
def users_reset_avatar ( self , user_id = None , username = None , ** kwargs ) :
"""Reset a user ’ s avatar""" | if user_id :
return self . __call_api_post ( 'users.resetAvatar' , userId = user_id , kwargs = kwargs )
elif username :
return self . __call_api_post ( 'users.resetAvatar' , username = username , kwargs = kwargs )
else :
raise RocketMissingParamException ( 'userID or username required' ) |
def get ( self , request , path = None , ** resources ) :
"""Proxy request to GA .""" | tracker = Tracker ( self . _meta . account_id , self . _meta . domain or request . META . get ( 'SERVER_NAME' ) )
visitor = Visitor ( )
visitor . extract_from_server_meta ( request . META )
session = Session ( )
page = Page ( path )
tracker . track_pageview ( page , session , visitor ) |
def getSolrType ( self , field ) :
"""Returns the SOLR type of the specified field name .
Assumes the convention of dynamic fields using an underscore + type character
code for the field name .""" | ftype = 'string'
try :
ftype = self . fieldtypes [ field ]
return ftype
except Exception :
pass
fta = field . split ( '_' )
if len ( fta ) > 1 :
ft = fta [ len ( fta ) - 1 ]
try :
ftype = self . fieldtypes [ ft ]
# cache the type so it ' s used next time
self . fieldtypes [ f... |
def show_md5_view ( md5 ) :
'''Renders template with ` stream _ sample ` of the md5.''' | if not WORKBENCH :
return flask . redirect ( '/' )
md5_view = WORKBENCH . stream_sample ( md5 )
return flask . render_template ( 'templates/md5_view.html' , md5_view = list ( md5_view ) , md5 = md5 ) |
def add_issue_type ( self , name , ** attrs ) :
"""Add a Issue type to the project and returns a
: class : ` IssueType ` object .
: param name : name of the : class : ` IssueType `
: param attrs : optional attributes for : class : ` IssueType `""" | return IssueTypes ( self . requester ) . create ( self . id , name , ** attrs ) |
def get_auth_error_message ( self ) :
'''create an informative error message if there is an issue authenticating''' | errors = [ "Authentication error retrieving ec2 inventory." ]
if None in [ os . environ . get ( 'AWS_ACCESS_KEY_ID' ) , os . environ . get ( 'AWS_SECRET_ACCESS_KEY' ) ] :
errors . append ( ' - No AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment vars found' )
else :
errors . append ( ' - AWS_ACCESS_KEY_ID ... |
def set_base_headers ( self , hdr ) :
"""Set metadata in FITS headers .""" | hdr = super ( StareImageBaseRecipe , self ) . set_base_headers ( hdr )
# Update EXP to 0
hdr [ 'EXP' ] = 0
return hdr |
def find_exact ( self , prefix ) :
'''Find the exact child with the given prefix''' | matches = self . find_all ( prefix )
if len ( matches ) == 1 :
match = matches . pop ( )
if match . prefix == prefix :
return match
return None |
def retrieve ( self , aclass ) :
"""Look for a specifc class / name in the packet""" | resu = [ ]
for x in self . payload :
try :
if isinstance ( aclass , str ) :
if x . name == aclass :
resu . append ( x )
else :
if isinstance ( x , aclass ) :
resu . append ( x )
resu += x . retrieve ( aclass )
except :
pass
... |
def edge_betweenness_bin ( G ) :
'''Edge betweenness centrality is the fraction of all shortest paths in
the network that contain a given edge . Edges with high values of
betweenness centrality participate in a large number of shortest paths .
Parameters
A : NxN np . ndarray
binary directed / undirected c... | n = len ( G )
BC = np . zeros ( ( n , ) )
# vertex betweenness
EBC = np . zeros ( ( n , n ) )
# edge betweenness
for u in range ( n ) :
D = np . zeros ( ( n , ) )
D [ u ] = 1
# distance from u
NP = np . zeros ( ( n , ) )
NP [ u ] = 1
# number of paths from u
P = np . zeros ( ( n , n ) )
... |
def list_nodes_full ( call = None , for_output = True ) :
'''Return a list of the VMs that are on the provider''' | if call == 'action' :
raise SaltCloudSystemExit ( 'The list_nodes_full function must be called with -f or --function.' )
return _list_nodes ( full = True , for_output = for_output ) |
def get_reserved_resources ( role = None ) :
"""resource types from state summary include : reserved _ resources
: param role : the name of the role if for reserved and if None all reserved
: type role : str
: return : resources ( cpu , mem )
: rtype : Resources""" | rtype = 'reserved_resources'
cpus = 0.0
mem = 0.0
summary = DCOSClient ( ) . get_state_summary ( )
if 'slaves' in summary :
agents = summary . get ( 'slaves' )
for agent in agents :
resource_reservations = agent . get ( rtype )
reservations = [ ]
if role is None or '*' in role :
... |
def cluster_applications ( self , state = None , final_status = None , user = None , queue = None , limit = None , started_time_begin = None , started_time_end = None , finished_time_begin = None , finished_time_end = None ) :
"""With the Applications API , you can obtain a collection of resources ,
each of which... | path = '/ws/v1/cluster/apps'
legal_states = set ( [ s for s , _ in YarnApplicationState ] )
if state is not None and state not in legal_states :
msg = 'Yarn Application State %s is illegal' % ( state , )
raise IllegalArgumentError ( msg )
legal_final_statuses = set ( [ s for s , _ in FinalApplicationStatus ] )
... |
def _to_torch ( Z , dtype = None ) :
"""Converts a None , list , np . ndarray , or torch . Tensor to torch . Tensor""" | if isinstance ( Z , list ) :
return [ Classifier . _to_torch ( z , dtype = dtype ) for z in Z ]
else :
return Classifier . _to_torch ( Z ) |
def apply_security_groups ( self , security_groups ) :
"""Applies security groups to the load balancer .
Applying security groups that are already registered with the
Load Balancer has no effect .
: type security _ groups : string or List of strings
: param security _ groups : The name of the security group... | if isinstance ( security_groups , str ) or isinstance ( security_groups , unicode ) :
security_groups = [ security_groups ]
new_sgs = self . connection . apply_security_groups_to_lb ( self . name , security_groups )
self . security_groups = new_sgs |
def data ( request ) :
"""Return server side data .""" | columns = [ ColumnDT ( User . id ) , ColumnDT ( User . name ) , ColumnDT ( Address . description ) , ColumnDT ( func . strftime ( "%d-%m-%Y" , User . birthday ) ) , ColumnDT ( User . age ) ]
query = DBSession . query ( ) . select_from ( User ) . join ( Address ) . filter ( Address . id > 4 )
rowTable = DataTables ( req... |
def convert_pdf_to_txt ( filename : str = None , blob : bytes = None , config : TextProcessingConfig = _DEFAULT_CONFIG ) -> str :
"""Converts a PDF file to text .
Pass either a filename or a binary object .""" | pdftotext = tools [ 'pdftotext' ]
if pdftotext : # External command method
if filename :
return get_cmd_output ( pdftotext , filename , '-' )
else :
return get_cmd_output_from_stdin ( blob , pdftotext , '-' , '-' )
elif pdfminer : # Memory - hogging method
with get_filelikeobject ( filename ... |
def set_state ( self , state ) :
""": param state : a boolean of true ( on ) or false ( ' off ' )
: return : nothing""" | _field = self . binary_state_name ( )
values = { "desired_state" : { _field : state } }
response = self . api_interface . local_set_state ( self , values , type_override = "binary_switche" )
self . _update_state_from_response ( response ) |
def leftsibling ( node ) :
"""Return Left Sibling of ` node ` .
> > > from anytree import Node
> > > dan = Node ( " Dan " )
> > > jet = Node ( " Jet " , parent = dan )
> > > jan = Node ( " Jan " , parent = dan )
> > > joe = Node ( " Joe " , parent = dan )
> > > leftsibling ( dan )
> > > leftsibling ( ... | if node . parent :
pchildren = node . parent . children
idx = pchildren . index ( node )
if idx :
return pchildren [ idx - 1 ]
else :
return None
else :
return None |
async def get_volume_information ( self ) -> List [ Volume ] :
"""Get the volume information .""" | res = await self . services [ "audio" ] [ "getVolumeInformation" ] ( { } )
volume_info = [ Volume . make ( services = self . services , ** x ) for x in res ]
if len ( volume_info ) < 1 :
logging . warning ( "Unable to get volume information" )
elif len ( volume_info ) > 1 :
logging . debug ( "The device seems t... |
def load_parser_options_from_env ( parser_class : t . Type [ BaseParser ] , env : t . Optional [ t . Dict [ str , str ] ] = None ) -> t . Dict [ str , t . Any ] :
"""Extracts arguments from ` ` parser _ class . _ _ init _ _ ` ` and populates them from environment variables .
Uses ` ` _ _ init _ _ ` ` argument typ... | env = env or os . environ
sentinel = object ( )
spec : inspect . FullArgSpec = inspect . getfullargspec ( parser_class . __init__ )
environment_parser = EnvironmentParser ( scope = parser_class . __name__ . upper ( ) , env = env )
stop_args = [ 'self' ]
safe_types = [ int , bool , str ]
init_args = { }
for arg_name in ... |
def type_decisioner ( marc_xml , mono_callback , multimono_callback , periodical_callback ) :
"""Detect type of the ` marc _ xml ` . Call proper callback .
Args :
marc _ xml ( str ) : Filename or XML string . Don ' t use ` ` \\ n ` ` in case of
filename .
mono _ callback ( fn reference ) : Callback in case ... | marc_xml = _read_content_or_path ( marc_xml )
record = MARCXMLRecord ( marc_xml )
if record . is_monographic or record . is_single_unit :
return mono_callback ( )
elif record . is_multi_mono :
return multimono_callback ( )
elif record . is_continuing :
return periodical_callback ( )
raise ValueError ( "Can'... |
def Seek ( self , offset , whence = os . SEEK_SET ) :
"""Seek to an offset in the file .""" | if whence == os . SEEK_SET :
self . offset = offset
elif whence == os . SEEK_CUR :
self . offset += offset
elif whence == os . SEEK_END :
self . offset = self . size + offset
else :
raise ValueError ( "Illegal whence value %s" % whence ) |
def stat_object ( self , bucket_name , object_name , sse = None ) :
"""Check if an object exists .
: param bucket _ name : Bucket of object .
: param object _ name : Name of object
: return : Object metadata if object exists""" | headers = { }
if sse :
is_valid_sse_c_object ( sse = sse )
headers . update ( sse . marshal ( ) )
is_valid_bucket_name ( bucket_name )
is_non_empty_string ( object_name )
response = self . _url_open ( 'HEAD' , bucket_name = bucket_name , object_name = object_name , headers = headers )
etag = response . headers ... |
def _get_command_buffer ( self , host_id , command_name ) :
"""Returns the command buffer for the given command and arguments .""" | buf = self . _cb_poll . get ( host_id )
if buf is not None :
return buf
if self . _max_concurrency is not None :
while len ( self . _cb_poll ) >= self . _max_concurrency :
self . join ( timeout = 1.0 )
def connect ( ) :
return self . connection_pool . get_connection ( command_name , shard_hint = hos... |
def add ( self , pattern , method = None , call = None , name = None ) :
"""Add a url pattern .
Args :
pattern ( : obj : ` str ` ) : URL pattern to add . This is usually ' / '
separated path . Parts of the URL can be parameterised using
curly braces .
Examples : " / " , " / path / to / resource " , " / re... | if not pattern . endswith ( '/' ) :
pattern += '/'
parts = tuple ( pattern . split ( '/' ) [ 1 : ] )
node = self . _routes
for part in parts :
node = node . setdefault ( part , { } )
if method is None :
node [ 'GET' ] = call
elif isinstance ( method , str ) :
node [ method . upper ( ) ] = call
else :
... |
def canonical_name ( name ) :
"""Find the canonical name for the given window in scipy . signal
Parameters
name : ` str `
the name of the window you want
Returns
realname : ` str `
the name of the window as implemented in ` scipy . signal . window `
Raises
ValueError
if ` ` name ` ` cannot be reso... | if name . lower ( ) == 'planck' : # make sure to handle the Planck window
return 'planck'
try : # use equivalence introduced in scipy 0.16.0
# pylint : disable = protected - access
return scipy_windows . _win_equiv [ name . lower ( ) ] . __name__
except AttributeError : # old scipy
try :
return geta... |
def from_env ( ) :
"""Get host / port settings from the environment .""" | if 'MICROMONGO_URI' in os . environ :
return ( os . environ [ 'MICROMONGO_URI' ] , )
host = os . environ . get ( 'MICROMONGO_HOST' , 'localhost' )
port = int ( os . environ . get ( 'MICROMONGO_PORT' , 27017 ) )
return ( host , port ) |
def extended ( self ) -> ListP :
"""The body structure attributes with extension data .""" | parts = [ part . extended for part in self . parts ]
return ListP ( [ _Concatenated ( parts ) , String . build ( self . subtype ) , _ParamsList ( self . content_type_params ) , String . build ( self . content_disposition ) , String . build ( self . content_language ) , String . build ( self . content_location ) ] ) |
def _eval_xpath ( self , xpath ) :
"""Evaluates xpath expressions .
Either string or XPath object .""" | if isinstance ( xpath , etree . XPath ) :
result = xpath ( self . _dataObject )
else :
result = self . _dataObject . xpath ( xpath , namespaces = self . _namespaces )
# print ' Xpath expression : ' , xpath
# print etree . tostring ( self . _ dataObject )
# print ' Got Result : \ n % s \ n End Result ' % result
... |
def Send ( self , message ) :
"""Send a message through Fleetspeak .
Args :
message : A message protocol buffer .
Returns :
Size of the message in bytes .
Raises :
ValueError : If message is not a common _ pb2 . Message .""" | if not isinstance ( message , common_pb2 . Message ) :
raise ValueError ( "Send requires a fleetspeak.Message" )
if message . destination . service_name == "system" :
raise ValueError ( "Only predefined messages can have destination.service_name == \"system\"" )
return self . _SendImpl ( message ) |
def get_gmm_pdf ( self , x ) :
"""Calculate the GMM likelihood for a single point .
. . math : :
y = \\ sum _ { i = 1 } ^ { N } w _ i
\\ times \\ text { normpdf } ( x , x _ i , \\ sigma _ i ) / \\ sum _ { i = 1 } ^ { N } w _ i
: label : gmm - likelihood
Arguments
x : float
Point at which likelihood ne... | def my_norm_pdf ( xt , mu , sigma ) :
z = ( xt - mu ) / sigma
return ( math . exp ( - 0.5 * z * z ) / ( math . sqrt ( 2. * np . pi ) * sigma ) )
y = 0
if ( x < self . min_limit ) :
return 0
if ( x > self . max_limit ) :
return 0
for _x in range ( self . points . size ) :
y += ( my_norm_pdf ( x , sel... |
def handler ( self , handler_class ) :
"""Link to an API handler class ( e . g . piston or DRF ) .""" | self . handler_class = handler_class
# we take the docstring from the handler class , not the methods
if self . docs is None and handler_class . __doc__ :
self . docs = clean_docstring ( handler_class . __doc__ )
return handler_class |
def create_token ( cls , number , exp_month , exp_year , cvc , api_key = djstripe_settings . STRIPE_SECRET_KEY , ** kwargs ) :
"""Creates a single use token that wraps the details of a credit card . This token can be used in
place of a credit card dictionary with any API method . These tokens can only be used onc... | card = { "number" : number , "exp_month" : exp_month , "exp_year" : exp_year , "cvc" : cvc }
card . update ( kwargs )
return stripe . Token . create ( api_key = api_key , card = card ) |
def read_spec ( path , http_client = None ) :
"""Reads in a swagger spec file used to initialize a SwaggerClient
: param path : String path to local swagger spec file .
: param http _ client : : class : ` bravado . requests _ client . RequestsClient `
: return : : class : ` bravado _ core . spec . Spec `""" | with open ( path , 'r' ) as f :
spec_dict = json . loads ( f . read ( ) )
return SwaggerClient . from_spec ( spec_dict , http_client = http_client , config = SPEC_CONFIG ) |
def extract_params ( params ) :
"""Extracts the values of a set of parameters , recursing into nested dictionaries .""" | values = [ ]
if isinstance ( params , dict ) :
for key , value in params . items ( ) :
values . extend ( extract_params ( value ) )
elif isinstance ( params , list ) :
for value in params :
values . extend ( extract_params ( value ) )
else :
values . append ( params )
return values |
def _merge_struct ( lhs , rhs , type_ ) :
"""Helper for ' _ merge _ by _ type ' .""" | fields = type_ . struct_type . fields
lhs , rhs = list ( lhs . list_value . values ) , list ( rhs . list_value . values )
candidate_type = fields [ len ( lhs ) - 1 ] . type
first = rhs . pop ( 0 )
if first . HasField ( "null_value" ) or candidate_type . code in _UNMERGEABLE_TYPES :
lhs . append ( first )
else :
... |
def start_import ( self , version_id = None ) :
"""Starts importing this draft layerversion ( cancelling any running import ) , even
if the data object hasn ’ t changed from the previous version .
: raises Conflict : if this version is already published .""" | if not version_id :
version_id = self . version . id
target_url = self . _client . get_url ( 'VERSION' , 'POST' , 'import' , { 'layer_id' : self . id , 'version_id' : version_id } )
r = self . _client . request ( 'POST' , target_url , json = { } )
return self . _deserialize ( r . json ( ) , self . _manager ) |
def get_env_dict ( root_section ) :
"""Read all Lago variables from the environment .
The lookup format is :
LAGO _ VARNAME - will land into ' lago ' section
LAGO _ _ SECTION1 _ _ VARNAME - will land into ' section1 ' section , notice
the double ' _ _ ' .
LAGO _ _ LONG _ SECTION _ NAME _ _ VARNAME - will ... | env_lago = defaultdict ( dict )
decider = re . compile ( ( r'^{0}(?:_(?!_)|(?P<has>__))' r'(?(has)(?P<section>.+?)__)' r'(?P<name>.+)$' ) . format ( root_section . upper ( ) ) )
for key , value in os . environ . iteritems ( ) :
match = decider . match ( key )
if not match :
continue
if not match . g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.