signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def delete ( self , customer_id , token_id , data = { } , ** kwargs ) :
"""Delete Given Token For a Customer
Args :
customer _ id : Customer Id for which tokens have to be deleted
token _ id : Id for which TOken object has to be deleted
Returns :
Dict for deleted token""" | url = "{}/{}/tokens/{}" . format ( self . base_url , customer_id , token_id )
return self . delete_url ( url , data , ** kwargs ) |
def rename ( self , old_key , new_key ) :
"""Rename a file .
: param old _ key : Old key that holds the object .
: param new _ key : New key that will hold the object .
: returns : The object that has been renamed .""" | assert new_key not in self
assert old_key != new_key
file_ = self [ old_key ]
old_data = self . filesmap [ old_key ]
# Create a new version with the new name
obj = ObjectVersion . create ( bucket = self . bucket , key = new_key , _file_id = file_ . obj . file_id )
# Delete old key
self . filesmap [ new_key ] = self . f... |
def set_step_input_context ( self , context ) :
"""Append step ' s ' in ' parameters to context , if they exist .
Append the [ in ] dictionary to the context . This will overwrite
existing values if the same keys are already in there . I . e if
in _ parameters has { ' eggs ' : ' boiled ' } and key ' eggs ' al... | logger . debug ( "starting" )
if self . in_parameters is not None :
parameter_count = len ( self . in_parameters )
if parameter_count > 0 :
logger . debug ( f"Updating context with {parameter_count} 'in' " "parameters." )
context . update ( self . in_parameters )
logger . debug ( "done" ) |
def normpath ( path ) :
"""Norm given system path with all available norm or expand functions
in os . path .""" | expanded = os . path . expanduser ( os . path . expandvars ( path ) )
return os . path . normcase ( os . path . normpath ( expanded ) ) |
def plot ( self , atDataset , errorbars = False , grid = False ) :
"""use matplotlib methods for plotting
Parameters
atDataset : allantools . Dataset ( )
a dataset with computed data
errorbars : boolean
Plot errorbars . Defaults to False
grid : boolean
Plot grid . Defaults to False""" | if errorbars :
self . ax . errorbar ( atDataset . out [ "taus" ] , atDataset . out [ "stat" ] , yerr = atDataset . out [ "stat_err" ] , )
else :
self . ax . plot ( atDataset . out [ "taus" ] , atDataset . out [ "stat" ] , )
self . ax . set_xlabel ( "Tau" )
self . ax . set_ylabel ( atDataset . out [ "stat_id" ] ... |
def _wait_until_exp ( self , timeout , error , function , * args ) :
"""This replaces the method from Selenium2Library to fix the major logic error in it""" | error = error . replace ( '<TIMEOUT>' , self . _format_timeout ( timeout ) )
def wait_func ( ) :
return None if function ( * args ) else error
self . _wait_until_no_error_exp ( timeout , wait_func ) |
def extract_db_info ( self , obj , keys ) :
"""Extract metadata from serialized file""" | result = { }
if isinstance ( obj , dict ) :
try :
qc = obj [ 'quality_control' ]
except KeyError :
qc = QC . UNKNOWN
elif isinstance ( obj , DataFrame ) :
with obj . open ( ) as hdulist :
qc = self . datamodel . get_quality_control ( hdulist )
else :
qc = QC . UNKNOWN
result [ 'q... |
def get_image ( path , search_path ) :
"""Get an Image object . If the path is given as absolute , it will be
relative to the content directory ; otherwise it will be relative to the
search path .
path - - the image ' s filename
search _ path - - a search path for the image ( string or list of strings )""" | if path . startswith ( '@' ) :
return StaticImage ( path [ 1 : ] , search_path )
if path . startswith ( '//' ) or '://' in path :
return RemoteImage ( path , search_path )
if os . path . isabs ( path ) :
file_path = utils . find_file ( os . path . relpath ( path , '/' ) , config . content_folder )
else :
... |
def get_paths_from_to ( self , goobj_start , goid_end = None , dn0_up1 = True ) :
"""Get a list of paths from goobj _ start to either top or goid _ end .""" | paths = [ ]
# Queue of terms to be examined ( and storage for their paths )
working_q = cx . deque ( [ [ goobj_start ] ] )
# Loop thru GO terms until we have examined all needed GO terms
adjfnc = self . adjdir [ dn0_up1 ]
while working_q : # print " WORKING QUEUE LEN ( { } ) " . format ( len ( working _ q ) )
path_... |
def find_tokens ( sentence , pattern ) :
"""Find all tokens from parts of sentence fitted to pattern , being on the end of matched sub - tree ( of sentence )
: param sentence : sentence from Spacy ( see : http : / / spacy . io / docs / # doc - spans - sents ) representing complete statement
: param pattern : pa... | if not verify_pattern ( pattern ) :
raise PatternSyntaxException ( pattern )
def _match_node ( t , p , tokens ) :
pat_node = p . pop ( 0 ) if p else ""
res = not pat_node or ( _match_token ( t , pat_node , False ) and ( not p or _match_edge ( t . children , p , tokens ) ) )
if res and not p :
to... |
def date_to_string ( date ) :
"""Transform a date or datetime object into a string and return it .
Examples :
> > > date _ to _ string ( datetime . datetime ( 2012 , 1 , 3 , 12 , 23 , 34 , tzinfo = UTC ) )
'2012-01-03T12:23:34 + 00:00'
> > > date _ to _ string ( datetime . datetime ( 2012 , 1 , 3 , 12 , 23 ... | if isinstance ( date , datetime . datetime ) : # Create an ISO 8601 datetime string
date_str = date . strftime ( '%Y-%m-%dT%H:%M:%S' )
tzstr = date . strftime ( '%z' )
if tzstr : # Yes , this is ugly . And no , I haven ' t found a better way to have a
# truly ISO 8601 datetime with timezone in Python .
... |
def _addProteinIdsToGroupMapping ( self , proteinIds , groupId ) :
"""Add a groupId to one or multiple entries of the internal
proteinToGroupId mapping .
: param proteinIds : a proteinId or a list of proteinIds , a proteinId
must be a string .
: param groupId : str , a groupId""" | for proteinId in AUX . toList ( proteinIds ) :
self . _proteinToGroupIds [ proteinId ] . add ( groupId ) |
def add_label_to_table ( self , row , col , txt ) :
"""Add a label to specified cell in table .""" | label = QLabel ( txt )
label . setMargin ( 5 )
label . setAlignment ( Qt . AlignLeft | Qt . AlignVCenter )
self . table . setCellWidget ( row , col , label ) |
def compute_merkleproof_for ( merkletree : 'MerkleTreeState' , element : Keccak256 ) -> List [ Keccak256 ] :
"""Containment proof for element .
The proof contains only the entries that are sufficient to recompute the
merkleroot , from the leaf ` element ` up to ` root ` .
Raises :
IndexError : If the elemen... | idx = merkletree . layers [ LEAVES ] . index ( element )
proof = [ ]
for layer in merkletree . layers :
if idx % 2 :
pair = idx - 1
else :
pair = idx + 1
# with an odd number of elements the rightmost one does not have a pair .
if pair < len ( layer ) :
proof . append ( layer [ p... |
def autoconnect ( ) :
"""Sets up a thread to detect when USB devices are plugged and unplugged .
If the device looks like a MicroPython board , then it will automatically
connect to it .""" | if not USE_AUTOCONNECT :
return
try :
import pyudev
except ImportError :
return
context = pyudev . Context ( )
monitor = pyudev . Monitor . from_netlink ( context )
connect_thread = threading . Thread ( target = autoconnect_thread , args = ( monitor , ) , name = 'AutoConnect' )
connect_thread . daemon = Tru... |
def find_guest ( name , quiet = False , path = None ) :
'''Returns the host for a container .
path
path to the container parent
default : / var / lib / lxc ( system default )
. . versionadded : : 2015.8.0
. . code - block : : bash
salt - run lxc . find _ guest name''' | if quiet :
log . warning ( "'quiet' argument is being deprecated." ' Please migrate to --quiet' )
for data in _list_iter ( path = path ) :
host , l = next ( six . iteritems ( data ) )
for x in 'running' , 'frozen' , 'stopped' :
if name in l [ x ] :
if not quiet :
__jid_ev... |
def _modify ( self , paths : Union [ str , List [ str ] ] , metadata_for_paths : Union [ IrodsMetadata , List [ IrodsMetadata ] ] , operation : str ) :
"""Modifies the metadata of the entity or entities in iRODS with the given path .
: param path : the paths of the entity or entities to modify
: param metadata ... | if isinstance ( paths , str ) :
paths = [ paths ]
if isinstance ( metadata_for_paths , IrodsMetadata ) :
metadata_for_paths = [ metadata_for_paths for _ in paths ]
elif len ( paths ) != len ( metadata_for_paths ) :
raise ValueError ( "Metadata not supplied for all paths - either supply a single IrodsMetadat... |
def process_npdu ( self , npdu ) :
"""encode NPDUs from the service access point and send them downstream .""" | if _debug :
DeviceToDeviceClientService . _debug ( "process_npdu %r" , npdu )
# broadcast messages go to everyone
if npdu . pduDestination . addrType == Address . localBroadcastAddr :
destList = self . connections . keys ( )
else :
conn = self . connections . get ( npdu . pduDestination , None )
if not ... |
def folders ( self ) :
'''gets the property value for folders''' | if self . _folders is None :
self . __init ( )
if self . _folders is not None and isinstance ( self . _folders , list ) :
if len ( self . _folders ) == 0 :
self . _loadFolders ( )
return self . _folders |
def select_from_cluster ( idx_key , idx_list , measure_vect ) :
"""Select a single source from a cluster and make it the new cluster key
Parameters
idx _ key : int
index of the current key for a cluster
idx _ list : [ int , . . . ]
list of the other source indices in the cluster
measure _ vect : np . na... | best_idx = idx_key
best_measure = measure_vect [ idx_key ]
out_list = [ idx_key ] + idx_list
for idx , measure in zip ( idx_list , measure_vect [ idx_list ] ) :
if measure < best_measure :
best_idx = idx
best_measure = measure
out_list . remove ( best_idx )
return best_idx , out_list |
def make_map ( config ) :
"""Create , configure and return the routes Mapper""" | map = Mapper ( directory = config [ 'pylons.paths' ] [ 'controllers' ] , always_scan = config [ 'debug' ] )
map . minimization = False
map . explicit = False
# The ErrorController route ( handles 404/500 error pages ) ; it should
# likely stay at the top , ensuring it can always be resolved
map . connect ( '/error/{act... |
def file_set_properties ( object_id , input_params = { } , always_retry = True , ** kwargs ) :
"""Invokes the / file - xxxx / setProperties API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Properties # API - method % 3A - % 2Fclass - xxxx % 2FsetProperties""" | return DXHTTPRequest ( '/%s/setProperties' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def _list_objects ( self , client_kwargs , path , max_request_entries ) :
"""Lists objects .
args :
client _ kwargs ( dict ) : Client arguments .
path ( str ) : Path relative to current locator .
max _ request _ entries ( int ) : If specified , maximum entries returned
by request .
Returns :
generator... | kwargs = dict ( prefix = path )
if max_request_entries :
kwargs [ 'limit' ] = max_request_entries
else :
kwargs [ 'full_listing' ] = True
with _handle_client_exception ( ) :
response = self . client . get_container ( client_kwargs [ 'container' ] , ** kwargs )
for obj in response [ 1 ] :
yield obj . pop... |
def create_metadata ( name , ext_version = None , schema = None , user = None , host = None , port = None , maintenance_db = None , password = None , runas = None ) :
'''Get lifecycle information about an extension
CLI Example :
. . code - block : : bash
salt ' * ' postgres . create _ metadata adminpack''' | installed_ext = get_installed_extension ( name , user = user , host = host , port = port , maintenance_db = maintenance_db , password = password , runas = runas )
ret = [ _EXTENSION_NOT_INSTALLED ]
if installed_ext :
ret = [ _EXTENSION_INSTALLED ]
if ( ext_version is not None and _pg_is_older_ext_ver ( installe... |
def create_event ( name , message_type , routing_key = 'everyone' , ** kwargs ) :
'''Create an event on the VictorOps service
. . code - block : : yaml
webserver - warning - message :
victorops . create _ event :
- message _ type : ' CRITICAL '
- entity _ id : ' webserver / diskspace '
- state _ message... | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
if __opts__ [ 'test' ] :
ret [ 'comment' ] = 'Need to create event: {0}' . format ( name )
return ret
res = __salt__ [ 'victorops.create_event' ] ( message_type = message_type , routing_key = routing_key , ** kwargs )
if res [ 'result'... |
def _increment_plugin_stat ( self , name , item ) :
'''Increments the total stat counters
@ param name : The formal name of the plugin
@ param dict : the loaded message object for HLL counter''' | item [ 'ts' ] = time . time ( )
if 'plugins' in self . stats_dict :
self . logger . debug ( "Incremented plugin '{p}' plugin stats" . format ( p = name ) )
for key in self . stats_dict [ 'plugins' ] [ name ] :
if key == 'lifetime' :
self . stats_dict [ 'plugins' ] [ name ] [ key ] . incremen... |
def save_code ( self , authorization_code ) :
"""Stores the data belonging to an authorization code token in memcache .
See : class : ` oauth2 . store . AuthCodeStore ` .""" | key = self . _generate_cache_key ( authorization_code . code )
self . mc . set ( key , { "client_id" : authorization_code . client_id , "code" : authorization_code . code , "expires_at" : authorization_code . expires_at , "redirect_uri" : authorization_code . redirect_uri , "scopes" : authorization_code . scopes , "dat... |
def _create_ret_object ( self , status = SUCCESS , data = None , error = False , error_message = None , error_cause = None ) :
"""Create generic reponse objects .
: param str status : The SUCCESS or FAILURE of the request
: param obj data : The data to return
: param bool error : Set to True to add Error resp... | ret = { }
if status == self . FAILURE :
ret [ 'status' ] = self . FAILURE
else :
ret [ 'status' ] = self . SUCCESS
ret [ 'data' ] = data
if error :
ret [ 'error' ] = { }
if error_message is not None :
ret [ 'error' ] [ 'message' ] = error_message
if error_cause is not None :
ret [ 'e... |
def fetch ( self , payment_id , data = { } , ** kwargs ) :
"""Fetch Payment for given Id
Args :
payment _ id : Id for which payment object has to be retrieved
Returns :
Payment dict for given payment Id""" | return super ( Payment , self ) . fetch ( payment_id , data , ** kwargs ) |
def get_sequence_rule_form_for_create ( self , assessment_part_id , next_assessment_part_id , sequence_rule_record_types ) :
"""Gets the sequence rule form for creating new sequence rules between two assessment parts .
A new form should be requested for each create transaction .
arg : assessment _ part _ id ( o... | for arg in sequence_rule_record_types :
if not isinstance ( arg , ABCId ) :
raise errors . InvalidArgument ( 'one or more argument array elements is not a valid OSID ${arg0_type}' )
if sequence_rule_record_types == [ ] :
obj_form = objects . SequenceRuleForm ( bank_id = self . _catalog_id , runtime = se... |
def binary ( self ) :
"""Return the name of the build .""" | def _get_binary ( ) : # Retrieve all entries from the remote virtual folder
parser = self . _create_directory_parser ( self . path )
if not parser . entries :
raise errors . NotFoundError ( 'No entries found' , self . path )
# Download the first matched directory entry
pattern = re . compile ( s... |
def multi_find_peaks ( arr , thresh , trig_int , debug = 0 , starttime = False , samp_rate = 1.0 , parallel = True , full_peaks = False , cores = None ) :
"""Wrapper for find - peaks for multiple arrays .
: type arr : numpy . ndarray
: param arr : 2 - D numpy array is required
: type thresh : list
: param t... | peaks = [ ]
if not parallel :
for sub_arr , arr_thresh in zip ( arr , thresh ) :
peaks . append ( find_peaks2_short ( arr = sub_arr , thresh = arr_thresh , trig_int = trig_int , debug = debug , starttime = starttime , samp_rate = samp_rate , full_peaks = full_peaks ) )
else :
if cores is None :
... |
def get_results ( self ) :
"""Gets results .
Returns
results : dictionary""" | return { 'status' : self . status , 'error_msg' : self . error_msg , 'k' : self . k , 'x' : self . x , 'lam' : self . lam * self . obj_sca , 'nu' : self . nu * self . obj_sca , 'mu' : self . mu * self . obj_sca , 'pi' : self . pi * self . obj_sca } |
def text ( self ) :
"""Return string value of scalar , whatever value it was parsed as .""" | if isinstance ( self . _value , CommentedMap ) :
raise TypeError ( "{0} is a mapping, has no text value." . format ( repr ( self ) ) )
if isinstance ( self . _value , CommentedSeq ) :
raise TypeError ( "{0} is a sequence, has no text value." . format ( repr ( self ) ) )
return self . _text |
def _strfactory ( cls , line ) :
"""factory method for an EPOitem
: param line : a line of input""" | cmp = line . rstrip ( ) . split ( )
chrom = cmp [ 2 ]
if not chrom . startswith ( "chr" ) :
chrom = "chr%s" % chrom
instance = tuple . __new__ ( cls , ( cmp [ 0 ] , cmp [ 1 ] , chrom , int ( cmp [ 3 ] ) , int ( cmp [ 4 ] ) , { '1' : '+' , '-1' : '-' } [ cmp [ 5 ] ] , cmp [ 6 ] ) )
span = instance . end - instance .... |
def visit_For ( self , node ) :
'''For loop creates aliasing between the target
and the content of the iterator
> > > from pythran import passmanager
> > > pm = passmanager . PassManager ( ' demo ' )
> > > module = ast . parse ( " " "
. . . def foo ( a ) :
. . . for i in a :
> > > result = pm . gather... | iter_aliases = self . visit ( node . iter )
if all ( isinstance ( x , ContainerOf ) for x in iter_aliases ) :
target_aliases = set ( )
for iter_alias in iter_aliases :
target_aliases . add ( iter_alias . containee )
else :
target_aliases = { node . target }
self . add ( node . target , target_aliase... |
def mean_squared_error ( df , col_true , col_pred = None ) :
"""Compute mean squared error of a predicted DataFrame .
Note that this method will trigger the defined flow to execute .
: param df : predicted data frame
: type df : DataFrame
: param col _ true : column name of true value
: type col _ true : ... | if not col_pred :
col_pred = get_field_name_by_role ( df , FieldRole . PREDICTED_VALUE )
return _run_evaluation_node ( df , col_true , col_pred ) [ 'mse' ] |
def fetch_uptodate ( self , ) :
"""Set and return whether the currently loaded entity is
the newest version in the department .
: returns : True , if newest version . False , if there is a newer version .
None , if there is nothing loaded yet .
: rtype : bool | None
: raises : None""" | tfi = self . get_taskfileinfo ( )
if tfi :
self . _uptodate = tfi . is_latest ( )
else :
self . _uptodate = None
return self . _uptodate |
def _map_over_linters ( self , py_files , non_test_files , md_files , stamp_directory , mapper ) :
"""Run mapper over passed in files , returning a list of results .""" | dispatch = [ ( "flake8" , lambda : mapper ( _run_flake8 , py_files , stamp_directory , self . show_lint_files ) ) , ( "pyroma" , lambda : [ _stamped_deps ( stamp_directory , _run_pyroma , "setup.py" , self . show_lint_files ) ] ) , ( "mdl" , lambda : [ _run_markdownlint ( md_files , self . show_lint_files ) ] ) , ( "po... |
def get_connection ( self , internal = False ) :
"""Get a live connection to this instance .
: param bool internal : Whether or not to use a DC internal network connection .
: rtype : : py : class : ` redis . client . StrictRedis `""" | # Determine the connection string to use .
connect_string = self . connect_string
if internal :
connect_string = self . internal_connect_string
# Stripe Redis protocol prefix coming from the API .
connect_string = connect_string . strip ( 'redis://' )
host , port = connect_string . split ( ':' )
# Build and return ... |
def _write_aedr ( self , f , gORz , attrNum , entryNum , value , pdataType , pnumElems , zVar ) :
'''Writes an aedr into the end of the file .
Parameters :
f : file
The current open CDF file
gORz : bool
True if this entry is for a global or z variable , False if r variable
attrNum : int
Number of the ... | f . seek ( 0 , 2 )
byte_loc = f . tell ( )
if ( gORz == True or zVar != True ) :
section_type = CDF . AgrEDR_
else :
section_type = CDF . AzEDR_
nextAEDR = 0
if pdataType is None : # Figure out Data Type if not supplied
if isinstance ( value , ( list , tuple ) ) :
avalue = value [ 0 ]
else :
... |
def conditions ( self , trigger_id ) :
"""Get all conditions for a specific trigger .
: param trigger _ id : Trigger definition id to be retrieved
: return : list of condition objects""" | response = self . _get ( self . _service_url ( [ 'triggers' , trigger_id , 'conditions' ] ) )
return Condition . list_to_object_list ( response ) |
def put ( self , username , password , email = None , full_name = None ) :
"""This will create a PnP user
: param username : str of the username give my the player
: param password : str of the password which will be hashed
: param email : str of the user ' s email address
: param full _ name : str of the f... | return self . connection . put ( 'user/signup' , data = dict ( username = username , password = password , email = email , full_name = full_name ) ) |
def console ( ) :
'''cli hook
return - - integer - - the exit code''' | parser = argparse . ArgumentParser ( description = "backup/restore PostgreSQL databases" , add_help = False )
parser . add_argument ( "--version" , action = 'version' , version = "%(prog)s {}" . format ( __version__ ) )
parent_parser = argparse . ArgumentParser ( add_help = False )
parent_parser . add_argument ( "-d" ,... |
def lowest_common_ancestor ( root , p , q ) :
""": type root : Node
: type p : Node
: type q : Node
: rtype : Node""" | while root :
if p . val > root . val < q . val :
root = root . right
elif p . val < root . val > q . val :
root = root . left
else :
return root |
def is_time_day_valid ( self , timestamp ) :
"""Check if it is within start time and end time of the DateRange
: param timestamp : time to check
: type timestamp : int
: return : True if t in range , False otherwise
: rtype : bool""" | ( start_time , end_time ) = self . get_start_and_end_time ( timestamp )
return start_time <= timestamp <= end_time |
def get_extension_status_for_users ( self , extension_id ) :
"""GetExtensionStatusForUsers .
[ Preview API ] Returns extension assignment status of all account users for the given extension
: param str extension _ id : The extension to check the status of the users for .
: rtype : { ExtensionAssignmentDetails... | route_values = { }
if extension_id is not None :
route_values [ 'extensionId' ] = self . _serialize . url ( 'extension_id' , extension_id , 'str' )
response = self . _send ( http_method = 'GET' , location_id = '5434f182-7f32-4135-8326-9340d887c08a' , version = '5.0-preview.1' , route_values = route_values )
return ... |
def _read_packet ( self ) :
"""Reads and decodes a single packet
Reads a single packet from the device and
stores the data from it in the current Command
object""" | # Grab command , send it and decode response
cmd = self . _commands_to_read . popleft ( )
try :
raw_data = self . _interface . read ( )
raw_data = bytearray ( raw_data )
decoded_data = cmd . decode_data ( raw_data )
except Exception as exception :
self . _abort_all_transfers ( exception )
raise
deco... |
def find_completions_at_cursor ( ast_tree , filename , line , col , root_env = gcl . default_env ) :
"""Find completions at the cursor .
Return a dict of { name = > Completion } objects .""" | q = gcl . SourceQuery ( filename , line , col - 1 )
rootpath = ast_tree . find_tokens ( q )
if is_identifier_position ( rootpath ) :
return find_inherited_key_completions ( rootpath , root_env )
try :
ret = find_deref_completions ( rootpath , root_env ) or enumerate_scope ( rootpath , root_env = root_env )
... |
def _handle_actions ( self , state , current_run , func , sp_addr , accessed_registers ) :
"""For a given state and current location of of execution , will update a function by adding the offets of
appropriate actions to the stack variable or argument registers for the fnc .
: param SimState state : upcoming st... | se = state . solver
if func is not None and sp_addr is not None : # Fix the stack pointer ( for example , skip the return address on the stack )
new_sp_addr = sp_addr + self . project . arch . call_sp_fix
actions = [ a for a in state . history . recent_actions if a . bbl_addr == current_run . addr ]
for a i... |
def request_client_list ( self , req , msg ) :
"""Request the list of connected clients .
The list of clients is sent as a sequence of # client - list informs .
Informs
addr : str
The address of the client as host : port with host in dotted quad
notation . If the address of the client could not be determi... | # TODO Get list of ClientConnection * instances and implement a standard
# ' address - print ' method in the ClientConnection class
clients = self . _client_conns
num_clients = len ( clients )
for conn in clients :
addr = conn . address
req . inform ( addr )
return req . make_reply ( 'ok' , str ( num_clients ) ... |
def get_root_item ( self , item ) :
"""Return the root item of the specified item .""" | root_item = item
while isinstance ( root_item . parent ( ) , QTreeWidgetItem ) :
root_item = root_item . parent ( )
return root_item |
def delete ( fun ) :
'''Remove specific function contents of minion . Returns True on success .
CLI Example :
. . code - block : : bash
salt ' * ' mine . delete ' network . interfaces ' ''' | if __opts__ [ 'file_client' ] == 'local' :
data = __salt__ [ 'data.get' ] ( 'mine_cache' )
if isinstance ( data , dict ) and fun in data :
del data [ fun ]
return __salt__ [ 'data.update' ] ( 'mine_cache' , data )
load = { 'cmd' : '_mine_delete' , 'id' : __opts__ [ 'id' ] , 'fun' : fun , }
return _m... |
def paths_in_directory ( input_directory ) :
"""Generate a list of all files in input _ directory , each as a list containing path components .""" | paths = [ ]
for base_path , directories , filenames in os . walk ( input_directory ) :
relative_path = os . path . relpath ( base_path , input_directory )
path_components = relative_path . split ( os . sep )
if path_components [ 0 ] == "." :
path_components = path_components [ 1 : ]
if path_comp... |
def fix_argument_only ( self ) :
'''fix _ argument _ only ( ) - > Either or Unit ( Argument )
` < arg > | ARG | < arg3 > ` - >
` Required ( Argument ( ' < arg > ' , ' ARG ' , ' < arg3 > ' ) ) `
` [ < arg > ] | [ ARG ] | [ < arg3 > ] ` - >
` Optional ( Argument ( ' < arg > ' , ' ARG ' , ' < arg3 > ' ) ) `
... | # for idx , branch in enumerate ( self ) :
# if isinstance ( branch [ 0 ] , Either ) :
# self [ idx ] = branch . fix ( )
first_type = type ( self [ 0 ] )
if first_type not in ( Required , Optional ) :
return self
for branch in self :
if not ( len ( branch ) == 1 and isinstance ( branch , first_type ) and isinst... |
def get_author_tags ( index_page ) :
"""Parse ` authors ` from HTML ` ` < meta > ` ` and dublin core .
Args :
index _ page ( str ) : HTML content of the page you wisht to analyze .
Returns :
list : List of : class : ` . SourceString ` objects .""" | dom = dhtmlparser . parseString ( index_page )
authors = [ get_html_authors ( dom ) , get_dc_authors ( dom ) , ]
return sum ( authors , [ ] ) |
def _apply_krauss_multi_qubit ( krauss : Union [ Tuple [ Any ] , Sequence [ Any ] ] , args : 'ApplyChannelArgs' ) -> np . ndarray :
"""Use numpy ' s einsum to apply a multi - qubit channel .""" | for krauss_op in krauss :
np . copyto ( dst = args . target_tensor , src = args . auxiliary_buffer0 )
krauss_tensor = np . reshape ( krauss_op . astype ( args . target_tensor . dtype ) , ( 2 , ) * len ( args . left_axes ) * 2 )
linalg . targeted_left_multiply ( krauss_tensor , args . target_tensor , args . ... |
def SLH_to_qutip ( slh , full_space = None , time_symbol = None , convert_as = 'pyfunc' ) :
"""Generate and return QuTiP representation matrices for the Hamiltonian
and the collapse operators . Any inhomogeneities in the Lindblad operators
( resulting from coherent drives ) will be moved into the Hamiltonian , ... | if full_space :
if not full_space >= slh . space :
raise AlgebraError ( "full_space=" + str ( full_space ) + " needs to " "at least include slh.space = " + str ( slh . space ) )
else :
full_space = slh . space
if full_space == TrivialSpace :
raise AlgebraError ( "Cannot convert SLH object in Trivial... |
def harmonicmean ( inlist ) :
"""Calculates the harmonic mean of the values in the passed list .
That is : n / ( 1 / x1 + 1 / x2 + . . . + 1 / xn ) . Assumes a ' 1D ' list .
Usage : lharmonicmean ( inlist )""" | sum = 0
for item in inlist :
sum = sum + 1.0 / item
return len ( inlist ) / sum |
def set_room_topic ( self , topic ) :
"""Set room topic .
Returns :
boolean : True if the topic changed , False if not""" | try :
self . client . api . set_room_topic ( self . room_id , topic )
self . topic = topic
return True
except MatrixRequestError :
return False |
def default_static_path ( ) :
"""Return the path to the javascript bundle""" | fdir = os . path . dirname ( __file__ )
return os . path . abspath ( os . path . join ( fdir , '../assets/' ) ) |
def colormapped_bedfile ( self , genome , cmap = None ) :
"""Create a BED file with padj encoded as color
Features will be colored according to adjusted pval ( phred
transformed ) . Downregulated features have the sign flipped .
Parameters
cmap : matplotlib colormap
Default is matplotlib . cm . RdBu _ r
... | if self . db is None :
raise ValueError ( "FeatureDB required" )
db = gffutils . FeatureDB ( self . db )
def scored_feature_generator ( d ) :
for i in range ( len ( d ) ) :
try :
feature = db [ d . ix [ i ] ]
except gffutils . FeatureNotFoundError :
raise gffutils . Featu... |
def set_source_yahoo_options ( self ) :
"""Set data source to yahoo finance , specifically to download financial options data""" | self . data_worker = data_worker
self . worker_args = { "function" : Options , "input" : self . input_queue , "output" : self . output_map , "source" : 'yahoo' }
self . source_name = "Yahoo Finance Options" |
def process ( self , * args , ** kwargs ) :
"""args : list of arguments for the ` runnable `
kwargs : dictionary of arguments for the ` runnable `""" | try :
timeout_seconds = self . timeout_timedelta . total_seconds ( )
with timeout ( self . run , timeout_seconds ) as run :
run ( * args , ** kwargs )
except Exception as e :
if self . verbose :
if isinstance ( e , TimeoutError ) :
logger . error ( 'SafeTask timed out: %s' , e , ... |
def main ( config , log ) :
"""Main function . Runs the program .
: param dict config : Dictionary from get _ arguments ( ) .
: param logging . Logger log : Logger for this function . Populated by with _ log ( ) decorator .""" | validate ( config )
paths_and_urls = get_urls ( config )
if not paths_and_urls :
log . warning ( 'No artifacts; nothing to download.' )
return
# Download files .
total_size = 0
chunk_size = max ( min ( max ( v [ 1 ] for v in paths_and_urls . values ( ) ) // 50 , 1048576 ) , 1024 )
log . info ( 'Downloading file... |
def _sample_mvn ( mean , cov , cov_structure = None , num_samples = None ) :
"""Returns a sample from a D - dimensional Multivariate Normal distribution
: param mean : [ . . . , N , D ]
: param cov : [ . . . , N , D ] or [ . . . , N , D , D ]
: param cov _ structure : " diag " or " full "
- " diag " : cov h... | mean_shape = tf . shape ( mean )
S = num_samples if num_samples is not None else 1
D = mean_shape [ - 1 ]
leading_dims = mean_shape [ : - 2 ]
num_leading_dims = tf . size ( leading_dims )
if cov_structure == "diag" : # mean : [ . . . , N , D ] and cov [ . . . , N , D ]
with tf . control_dependencies ( [ tf . assert... |
def apps_installations_job_status_show ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / apps # get - requirements - install - status" | api_path = "/api/v2/apps/installations/job_statuses/{id}.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def modify_polygon ( self , pid , polygon , value ) :
"""Modify parts of a parameter set by setting all parameters located
in , or touching , the provided : class : ` shapely . geometry . Polygon `
instance .
Parameters
pid : int
id of parameter set to vary
polygon : : class : ` shapely . geometry . Pol... | # create grid polygons
grid_polygons = [ ]
for x , z in zip ( self . grid . grid [ 'x' ] , self . grid . grid [ 'z' ] ) :
coords = [ ( a , b ) for a , b in zip ( x , z ) ]
grid_polygons . append ( shapgeo . Polygon ( coords ) )
# now determine elements in area
elements_in_area = [ ]
for nr , element in enumerat... |
def setup_map ( self , londel = 1. , latdel = 1. , * args , ** kwargs ) :
"""SETUP _ MAP : Draw the map and coastlines .
@ note : To be compliant with self . legend ( ) - > setup _ map ( ) must be called after legend""" | s = kwargs [ 's' ] if kwargs . has_key ( 's' ) else 25
edgecolor = kwargs [ 'edgecolor' ] if kwargs . has_key ( 'edgecolor' ) else 'none'
bathy = kwargs . get ( 'bathy' , not kwargs . get ( 'nobathy' , False ) )
# Plot Sequence
self . drawcoastlines ( )
if bathy :
cs = self . drawbathy ( ** kwargs )
self . drawpara... |
def _analyze_read_write ( self ) :
"""Compute variables read / written / . . .""" | write_var = [ x . variables_written_as_expression for x in self . nodes ]
write_var = [ x for x in write_var if x ]
write_var = [ item for sublist in write_var for item in sublist ]
write_var = list ( set ( write_var ) )
# Remove dupplicate if they share the same string representation
write_var = [ next ( obj ) for i ,... |
def to_dict ( self ) :
"""Render a MessageElement as python dict
: return : Python dict representation
: rtype : dict""" | obj_dict = super ( Text , self ) . to_dict ( )
texts_dict = None
if isinstance ( self . text , list ) :
texts_dict = [ t . to_dict ( ) for t in self . text ]
child_dict = { 'type' : self . __class__ . __name__ , 'text' : texts_dict }
obj_dict . update ( child_dict )
return obj_dict |
def vsend ( self , picture , argptr ) :
"""Send a ' picture ' message to the socket ( or actor ) . This is a va _ list
version of zsock _ send ( ) , so please consult its documentation for the
details .""" | return lib . zsock_vsend ( self . _as_parameter_ , picture , argptr ) |
def _len_slice ( obj ) :
'''Slice length .''' | try :
return ( ( obj . stop - obj . start + 1 ) // obj . step )
except ( AttributeError , TypeError ) :
return 0 |
def agent_check_deregister ( consul_url = None , token = None , checkid = None ) :
'''The agent will take care of deregistering the check from the Catalog .
: param consul _ url : The Consul server URL .
: param checkid : The ID of the check to deregister from Consul .
: return : Boolean and message indicatin... | ret = { }
if not consul_url :
consul_url = _get_config ( )
if not consul_url :
log . error ( 'No Consul URL found.' )
ret [ 'message' ] = 'No Consul URL found.'
ret [ 'res' ] = False
return ret
if not checkid :
raise SaltInvocationError ( 'Required argument "checkid" is missi... |
def sequences_to_string ( self ) :
"""Convert state indices to a string of characters""" | return { k : '' . join ( self . states [ v ] ) for ( k , v ) in self . sequences . items ( ) } |
def generate_doc_dict ( module , user ) :
"""Compile a Pale module ' s documentation into a python dictionary .
The returned dictionary is suitable to be rendered by a JSON formatter ,
or passed to a template engine , or manipulated in some other way .""" | from pale import extract_endpoints , extract_resources , is_pale_module
if not is_pale_module ( module ) :
raise ValueError ( """The passed in `module` (%s) is not a pale module. `paledoc`
only works on modules with a `_module_type` set to equal
`pale.ImplementationModule`.""" )
modu... |
def get_tags ( blog_id , username , password ) :
"""wp . getTags ( blog _ id , username , password )
= > tag structure [ ]""" | authenticate ( username , password )
site = Site . objects . get_current ( )
return [ tag_structure ( tag , site ) for tag in Tag . objects . usage_for_queryset ( Entry . published . all ( ) , counts = True ) ] |
def _build_page ( self , filepath ) :
"""To build from filepath , relative to pages _ dir""" | filename = filepath . split ( "/" ) [ - 1 ]
# If filename starts with _ ( underscore ) or . ( dot ) do not build
if not filename . startswith ( ( "_" , "." ) ) and ( filename . endswith ( PAGE_FORMAT ) ) :
meta = self . _get_page_meta ( filepath )
content = self . _get_page_content ( filepath )
# The defaul... |
def _create_container_args ( kwargs ) :
"""Convert arguments to create ( ) to arguments to create _ container ( ) .""" | # Copy over kwargs which can be copied directly
create_kwargs = { }
for key in copy . copy ( kwargs ) :
if key in RUN_CREATE_KWARGS :
create_kwargs [ key ] = kwargs . pop ( key )
host_config_kwargs = { }
for key in copy . copy ( kwargs ) :
if key in RUN_HOST_CONFIG_KWARGS :
host_config_kwargs [ ... |
def get_for ( self , query_type , value ) :
"""Create a query and run it for the given arg if it doesn ' t exist , and
return the tweets for the query .""" | from yacms . twitter . models import Query
lookup = { "type" : query_type , "value" : value }
query , created = Query . objects . get_or_create ( ** lookup )
if created :
query . run ( )
elif not query . interested :
query . interested = True
query . save ( )
return query . tweets . all ( ) |
def receive_data ( self ) : # pragma : no cover ; no covered since qt event loop
'''Infinite loop via QObject . moveToThread ( ) , does not block event loop''' | while ( not self . _stop_readout . wait ( 0.01 ) ) : # use wait ( ) , do not block
if self . _send_data :
if self . socket_type != zmq . DEALER :
raise RuntimeError ( 'You send data without a bidirectional ' 'connection! Define a bidirectional ' 'connection.' )
self . receiver . send ( s... |
def parse_args ( self , args ) :
"""Parses positional arguments and returns ` ` ( values , args , order ) ` `
for the parsed options and arguments as well as the leftover
arguments if there are any . The order is a list of objects as they
appear on the command line . If arguments appear multiple times they
... | state = ParsingState ( args )
try :
self . _process_args_for_options ( state )
self . _process_args_for_args ( state )
except UsageError :
if self . ctx is None or not self . ctx . resilient_parsing :
raise
return state . opts , state . largs , state . order |
def get_input_shape ( sym , proto_obj ) :
"""Helper function to obtain the shape of an array""" | arg_params = proto_obj . arg_dict
aux_params = proto_obj . aux_dict
model_input_shape = [ data [ 1 ] for data in proto_obj . model_metadata . get ( 'input_tensor_data' ) ]
data_names = [ data [ 0 ] for data in proto_obj . model_metadata . get ( 'input_tensor_data' ) ]
# creating dummy inputs
inputs = [ ]
for in_shape i... |
def _compute_missing_deps ( self , src_tgt , actual_deps ) :
"""Computes deps that are used by the compiler but not specified in a BUILD file .
These deps are bugs waiting to happen : the code may happen to compile because the dep was
brought in some other way ( e . g . , by some other root target ) , but that ... | analyzer = self . _analyzer
def must_be_explicit_dep ( dep ) : # We don ' t require explicit deps on the java runtime , so we shouldn ' t consider that
# a missing dep .
return ( dep not in analyzer . bootstrap_jar_classfiles and not dep . startswith ( DistributionLocator . cached ( ) . real_home ) )
def target_or_... |
def prepareSiiImport ( siiContainer , specfile , path , qcAttr , qcLargerBetter , qcCutoff , rankAttr , rankLargerBetter ) :
"""Prepares the ` ` siiContainer ` ` for the import of peptide spectrum matching
results . Adds entries to ` ` siiContainer . container ` ` and to
` ` siiContainer . info ` ` .
: param ... | if specfile not in siiContainer . info :
siiContainer . addSpecfile ( specfile , path )
else :
raise Exception ( '...' )
siiContainer . info [ specfile ] [ 'qcAttr' ] = qcAttr
siiContainer . info [ specfile ] [ 'qcLargerBetter' ] = qcLargerBetter
siiContainer . info [ specfile ] [ 'qcCutoff' ] = qcCutoff
siiCon... |
def deleteTable ( self , login , tableName ) :
"""Parameters :
- login
- tableName""" | self . send_deleteTable ( login , tableName )
self . recv_deleteTable ( ) |
def post_delete_helper ( form_tag = True ) :
"""Message ' s delete form layout helper""" | helper = FormHelper ( )
helper . form_action = '.'
helper . attrs = { 'data_abide' : '' }
helper . form_tag = form_tag
helper . layout = Layout ( ButtonHolderPanel ( Row ( Column ( 'confirm' , css_class = 'small-12 medium-8' ) , Column ( Submit ( 'submit' , _ ( 'Submit' ) ) , css_class = 'small-12 medium-4 text-right' ... |
def reload ( self ) :
"""Reloads this VirtualBox VM .""" | result = yield from self . _control_vm ( "reset" )
log . info ( "VirtualBox VM '{name}' [{id}] reloaded" . format ( name = self . name , id = self . id ) )
log . debug ( "Reload result: {}" . format ( result ) ) |
def read ( self , names ) :
"""Convert names into descriptions""" | descrs = [ ]
for name in names :
mo = re . match ( self . short_regex , name )
if mo :
idx = mo . lastindex
# matching group index , starting from 1
suffix = self . suffix [ idx - 1 ] . replace ( r':\|' , ':|' )
descrs . append ( mo . group ( mo . lastindex ) + suffix + name [ mo... |
def frameify ( self , state , data ) :
"""Yield the data as a single frame .""" | try :
yield state . recv_buf + data
except FrameSwitch :
pass
finally :
state . recv_buf = '' |
def get_init_kwargs ( self ) :
"""Generates keyword arguments for creating a new Docker client instance .
: return : Keyword arguments as defined through this configuration .
: rtype : dict""" | init_kwargs = { }
for k in self . init_kwargs :
if k in self . core_property_set :
init_kwargs [ k ] = getattr ( self , k )
elif k in self :
init_kwargs [ k ] = self [ k ]
return init_kwargs |
def get_experiment_status ( port ) :
'''get the status of an experiment''' | result , response = check_rest_server_quick ( port )
if result :
return json . loads ( response . text ) . get ( 'status' )
return None |
def link_attrs ( self , func ) :
"""Add a callback for adding attributes to links .
The callback should take a single argument , the url , and
should return additional text to be inserted in the link tag ,
i . e . ` ` " target = " _ blank " ` ` .
You can use this method as a decorator on the function you
... | @ libmarkdown . e_flags_callback
def _link_attrs_func ( string , size , context ) :
ret = func ( string [ : size ] )
if ret is not None :
buf = ctypes . create_string_buffer ( ret )
self . _alloc . append ( buf )
return ctypes . addressof ( buf )
self . _link_attrs_func = _link_attrs_fun... |
def set_check ( self , name , state ) :
'''set a status value''' | if self . child . is_alive ( ) :
self . parent_pipe . send ( CheckItem ( name , state ) ) |
def get_info ( self , version ) :
"""parses out the relevant information in version
and returns it to the user in a dictionary""" | ret = super ( PandasStore , self ) . get_info ( version )
ret [ 'col_names' ] = version [ 'dtype_metadata' ]
ret [ 'handler' ] = self . __class__ . __name__
ret [ 'dtype' ] = ast . literal_eval ( version [ 'dtype' ] )
return ret |
def download_experiment ( self , experiment_id ) :
"""download _ experiment :""" | req = self . query_records ( 'experiment' , self . access_key , self . secret_key , query = 'download/' + experiment_id )
print req . text
return |
def fetch_current_cloudformation_template ( service_name , environment , cf_client ) :
"""Fetch the currently - deployed template for the given service in the given
environment and return it .""" | stack_name = get_stack_name ( environment , service_name )
logger . debug ( 'Fetching template for `%s`' , stack_name )
result = cf_client . get_template ( StackName = stack_name )
return jsonify ( result [ 'TemplateBody' ] ) |
def get_filter ( q : tldap . Q , fields : Dict [ str , tldap . fields . Field ] , pk : str ) :
"""Translate the Q tree into a filter string to search for , or None
if no results possible .""" | # check the details are valid
if q . negated and len ( q . children ) == 1 :
op = b"!"
elif q . connector == tldap . Q . AND :
op = b"&"
elif q . connector == tldap . Q . OR :
op = b"|"
else :
raise ValueError ( "Invalid value of op found" )
# scan through every child
search = [ ]
for child in q . child... |
def reset ( self , commit = 'HEAD' , working_tree = False , paths = None , head = False , ** kwargs ) :
"""Reset the index to reflect the tree at the given commit . This will not
adjust our HEAD reference as opposed to HEAD . reset by default .
: param commit :
Revision , Reference or Commit specifying the co... | # what we actually want to do is to merge the tree into our existing
# index , which is what git - read - tree does
new_inst = type ( self ) . from_tree ( self . repo , commit )
if not paths :
self . entries = new_inst . entries
else :
nie = new_inst . entries
for path in paths :
path = self . _to_r... |
def remove_coreference ( self , coid ) :
"""Removes the coreference with specific identifier
@ type coid : string
@ param coid : the coreference identifier""" | for this_node in self . node . findall ( 'coref' ) :
if this_node . get ( 'id' ) == coid :
self . node . remove ( this_node )
break |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.