signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def create ( cls , session , record , endpoint_override = None , out_type = None , ** add_params ) : """Create an object on HelpScout . Args : session ( requests . sessions . Session ) : Authenticated session . record ( helpscout . BaseModel ) : The record to be created . endpoint _ override ( str , optiona...
cls . _check_implements ( 'create' ) data = record . to_api ( ) params = { 'reload' : True , } params . update ( ** add_params ) data . update ( params ) return cls ( endpoint_override or '/%s.json' % cls . __endpoint__ , data = data , request_type = RequestPaginator . POST , singleton = True , session = session , out_...
def level ( self , level , time = 0 ) : """( Helper ) Set light to specified level"""
if level <= 0 : self . _elk . send ( pf_encode ( self . _index ) ) elif level >= 98 : self . _elk . send ( pn_encode ( self . _index ) ) else : self . _elk . send ( pc_encode ( self . _index , 9 , level , time ) )
def getcentresurl ( idcentre , * args , ** kwargs ) : """Request Centres URL . If idcentre is set , you ' ll get a response adequate for a MambuCentre object . If not set , you ' ll get a response adequate for a MambuCentres object . See mambucentre module and pydoc for further information . Currently imple...
getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset"...
def get_consumer_cfg ( config , only , qty ) : """Get the consumers config , possibly filtering the config if only or qty is set . : param config : The consumers config section : type config : helper . config . Config : param str only : When set , filter to run only this consumer : param int qty : When se...
consumers = dict ( config . application . Consumers or { } ) if only : for key in list ( consumers . keys ( ) ) : if key != only : del consumers [ key ] if qty : consumers [ only ] [ 'qty' ] = qty return consumers
def api ( func = None , timeout = API_TIMEOUT ) : # incoming """provide a request / response api receives any requests here and return value is the response all functions must have the following signature - request _ id - entity ( partition / routing key ) followed by kwargs"""
if func is None : return partial ( api , timeout = timeout ) else : wrapper = _get_api_decorator ( func = func , timeout = timeout ) return wrapper
def HasDataStream ( self , name , case_sensitive = True ) : """Determines if the file entry has specific data stream . Args : name ( str ) : name of the data stream . case _ sensitive ( Optional [ bool ] ) : True if the name is case sensitive . Returns : bool : True if the file entry has the data stream ....
if not isinstance ( name , py2to3 . STRING_TYPES ) : raise ValueError ( 'Name is not a string.' ) name_lower = name . lower ( ) for data_stream in self . _GetDataStreams ( ) : if data_stream . name == name : return True if not case_sensitive and data_stream . name . lower ( ) == name_lower : ...
def load_config_module ( ) : """If the config . py file exists , import it as a module . If it does not exist , call sys . exit ( ) with a request to run oaepub configure ."""
import imp config_path = config_location ( ) try : config = imp . load_source ( 'config' , config_path ) except IOError : log . critical ( 'Config file not found. oaepub exiting...' ) sys . exit ( 'Config file not found. Please run \'oaepub configure\'' ) else : log . debug ( 'Config file loaded from {0...
def _post_init ( self ) : """Set up the device path and type code ."""
self . _led_type_code = self . manager . get_typecode ( 'LED' ) self . device_path = os . path . realpath ( os . path . join ( self . path , 'device' ) ) if '::' in self . name : chardev , code_name = self . name . split ( '::' ) if code_name in self . manager . codes [ 'LED_type_codes' ] : self . code ...
def matches ( self , verbosity = Verbosity . TERSE ) : """Shows partial matches and activations . Returns a tuple containing the combined sum of the matches for each pattern , the combined sum of partial matches and the number of activations . The verbosity parameter controls how much to output : * Verbos...
data = clips . data . DataObject ( self . _env ) lib . EnvMatches ( self . _env , self . _rule , verbosity , data . byref ) return tuple ( data . value )
def addProteinGroup ( self , groupRepresentative ) : """Adds a new protein group and returns the groupId . The groupId is defined using an internal counter , which is incremented every time a protein group is added . The groupRepresentative is added as a leading protein . : param groupRepresentative : the p...
groupId = self . _getNextGroupId ( ) self . groups [ groupId ] = ProteinGroup ( groupId , groupRepresentative ) self . addLeadingToGroups ( groupRepresentative , groupId ) return groupId
def get_n_r ( self ) : """return the values of n and r for the next round"""
return math . floor ( self . n / self . eta ** self . i + _epsilon ) , math . floor ( self . r * self . eta ** self . i + _epsilon )
def write_grid_tpl ( self , name , tpl_file , zn_array ) : """write a template file a for grid - based multiplier parameters Parameters name : str the base parameter name tpl _ file : str the template file to write zn _ array : numpy . ndarray an array used to skip inactive cells Returns df : pand...
parnme , x , y = [ ] , [ ] , [ ] with open ( os . path . join ( self . m . model_ws , tpl_file ) , 'w' ) as f : f . write ( "ptf ~\n" ) for i in range ( self . m . nrow ) : for j in range ( self . m . ncol ) : if zn_array [ i , j ] < 1 : pname = ' 1.0 ' else : ...
def interact_GxE_1dof ( snps , pheno , env , K = None , covs = None , test = 'lrt' ) : """Univariate GxE fixed effects interaction linear mixed model test for all pairs of SNPs and environmental variables . Args : snps : [ N x S ] SP . array of S SNPs for N individuals pheno : [ N x 1 ] SP . array of 1 phen...
N = snps . shape [ 0 ] if K is None : K = SP . eye ( N ) if covs is None : covs = SP . ones ( ( N , 1 ) ) assert ( env . shape [ 0 ] == N and pheno . shape [ 0 ] == N and K . shape [ 0 ] == N and K . shape [ 1 ] == N and covs . shape [ 0 ] == N ) , "shapes missmatch" Inter0 = SP . ones ( ( N , 1 ) ) pv = SP . z...
def get ( self , id ) : """Retrieves the job with the selected ID . : param str id : The ID of the job : returns : The dictionary of the job if found , None otherwise"""
self . cur . execute ( "SELECT * FROM jobs WHERE hash=?" , ( id , ) ) item = self . cur . fetchone ( ) if item : return dict ( zip ( ( "id" , "description" , "last-run" , "next-run" , "last-run-result" ) , item ) ) return None
def to_dot ( self ) : """Produces a ball and stick graph of this state machine . Returns ` graphviz . Digraph ` A ball and stick visualization of this state machine ."""
from graphviz import Digraph dot = Digraph ( format = 'png' ) for state in self . states : if isinstance ( state , TransientState ) : dot . node ( state . state_id , style = 'dashed' ) else : dot . node ( state . state_id ) for transition in state . transition_set : dot . edge ( stat...
def filteritems ( predicate , dict_ ) : """Return a new dictionary comprising of items for which ` ` predicate ` ` returns True . : param predicate : Predicate taking a key - value pair , or None . . versionchanged : 0.0.2 ` ` predicate ` ` is now taking a key - value pair as a single argument ."""
predicate = all if predicate is None else ensure_callable ( predicate ) ensure_mapping ( dict_ ) return dict_ . __class__ ( ifilter ( predicate , iteritems ( dict_ ) ) )
def _ParseKey ( self , knowledge_base , registry_key , value_name ) : """Parses a Windows Registry key for a preprocessing attribute . Args : knowledge _ base ( KnowledgeBase ) : to fill with preprocessing information . registry _ key ( dfwinreg . WinRegistryKey ) : Windows Registry key . value _ name ( str...
try : registry_value = registry_key . GetValueByName ( value_name ) except IOError as exception : raise errors . PreProcessFail ( ( 'Unable to retrieve Windows Registry key: {0:s} value: {1:s} ' 'with error: {2!s}' ) . format ( registry_key . path , value_name , exception ) ) if registry_value : value_objec...
def dehydrate ( self , comp , broker ) : """Saves a component in the given broker to the file system ."""
if not self . meta_data : raise Exception ( "Hydration meta_path not set. Can't dehydrate." ) if not self . created : fs . ensure_path ( self . meta_data , mode = 0o770 ) if self . data : fs . ensure_path ( self . data , mode = 0o770 ) self . created = True c = comp doc = None try : name = d...
def fetch_check ( self , master ) : '''check for missing parameters periodically'''
if self . param_period . trigger ( ) : if master is None : return if len ( self . mav_param_set ) == 0 : master . param_fetch_all ( ) elif self . mav_param_count != 0 and len ( self . mav_param_set ) != self . mav_param_count : if master . time_since ( 'PARAM_VALUE' ) >= 1 : ...
def createAssetFromURL ( self , url , async = False , metadata = None , callback = None ) : """Users the passed URL to load data . If async = false a json with the result is returned otherwise a json with an asset _ id is returned . : param url : : param metadata : arbitrary additional description information f...
audio = { 'uri' : url } config = { 'async' : async } if callback is not None : config [ 'callback' ] = callback if metadata is not None : body = { 'audio' : audio , 'config' : config , 'metadata' : metadata } else : body = { 'audio' : audio , 'config' : config } return self . _checkReturn ( requests . post ...
def save_to_conf ( self ) : """Save settings to configuration file"""
for checkbox , ( option , _default ) in list ( self . checkboxes . items ( ) ) : self . set_option ( option , checkbox . isChecked ( ) ) for radiobutton , ( option , _default ) in list ( self . radiobuttons . items ( ) ) : self . set_option ( option , radiobutton . isChecked ( ) ) for lineedit , ( option , _def...
def parse_reports ( self ) : """Find RSeQC gene _ body _ coverage reports and parse their data"""
# Set up vars self . gene_body_cov_hist_counts = dict ( ) self . gene_body_cov_hist_percent = dict ( ) # TODO - Do separate parsing step to find skewness values # and add these to the general stats table ? # Go through files and parse data for f in self . find_log_files ( 'rseqc/gene_body_coverage' ) : # RSeQC > = v2.4...
def current_module_name ( frame ) : """Get name of module of currently running function from inspect / trace stack frame . Parameters frame : stack frame Stack frame obtained via trace or inspect Returns modname : string Currently running function module name"""
if frame is None : return None if hasattr ( frame . f_globals , '__name__' ) : return frame . f_globals [ '__name__' ] else : mod = inspect . getmodule ( frame ) if mod is None : return '' else : return mod . __name__
def execute_as ( collector ) : """Execute a command ( after the - - ) as an assumed role ( specified by - - artifact )"""
# Gonna assume role anyway . . . collector . configuration [ 'amazon' ] . _validated = True # Find the arn we want to assume account_id = collector . configuration [ 'accounts' ] [ collector . configuration [ 'aws_syncr' ] . environment ] arn = "arn:aws:iam::{0}:role/{1}" . format ( account_id , collector . configurati...
def create ( ctx ) : """Create default config file"""
import shutil this_dir , this_filename = os . path . split ( __file__ ) default_config_file = os . path . join ( this_dir , "apis/example-config.yaml" ) config_file = ctx . obj [ "configfile" ] shutil . copyfile ( default_config_file , config_file ) print_message ( "Config file created: {}" . format ( config_file ) )
def euclidean ( x , y ) : """Standard euclidean distance . . . math : : D ( x , y ) = \ sqrt { \ sum _ i ( x _ i - y _ i ) ^ 2}"""
result = 0.0 for i in range ( x . shape [ 0 ] ) : result += ( x [ i ] - y [ i ] ) ** 2 return np . sqrt ( result )
def graph_repr ( self ) : """Short repr to use when rendering Pipeline graphs ."""
# Replace any floating point numbers in the expression # with their scientific notation final = re . sub ( r"[-+]?\d*\.\d+" , lambda x : format ( float ( x . group ( 0 ) ) , '.2E' ) , self . _expr ) # Graphviz interprets ` \ l ` as " divide label into lines , left - justified " return "Expression:\\l {}\\l" . format (...
def line_transformation_suggestor ( line_transformation , line_filter = None ) : """Returns a suggestor ( a function that takes a list of lines and yields patches ) where suggestions are the result of line - by - line transformations . @ param line _ transformation Function that , given a line , returns another...
def suggestor ( lines ) : for line_number , line in enumerate ( lines ) : if line_filter and not line_filter ( line ) : continue candidate = line_transformation ( line ) if candidate is None : yield Patch ( line_number ) else : yield Patch ( line_n...
def get_attr ( obj , string_rep , default = _get_attr_raise_on_attribute_error , separator = "." ) : """getattr via a chain of attributes like so : > > > import datetime > > > some _ date = datetime . date . today ( ) > > > get _ attr ( some _ date , " month . numerator . _ _ doc _ _ " ) ' int ( x [ , base ...
attribute_chain = string_rep . split ( separator ) current_obj = obj for attr in attribute_chain : try : current_obj = getattr ( current_obj , attr ) except AttributeError : if default is _get_attr_raise_on_attribute_error : raise AttributeError ( "Bad attribute \"{}\" in chain: \"{}...
def get_certificate ( ) : '''Read openvswitch certificate from disk'''
if os . path . exists ( CERT_PATH ) : log ( 'Reading ovs certificate from {}' . format ( CERT_PATH ) ) with open ( CERT_PATH , 'r' ) as cert : full_cert = cert . read ( ) begin_marker = "-----BEGIN CERTIFICATE-----" end_marker = "-----END CERTIFICATE-----" begin_index = full_cert...
def _dict_lower ( dictionary : dict ) : """Convert allowed state transitions / target states to lowercase ."""
return { key . lower ( ) : [ value . lower ( ) for value in value ] for key , value in dictionary . items ( ) }
def read_cz_lsm_event_list ( fd , byte_order ) : """Read LSM events from file and return as list of ( time , type , text ) ."""
count = struct . unpack ( byte_order + 'II' , fd . read ( 8 ) ) [ 1 ] events = [ ] while count > 0 : esize , etime , etype = struct . unpack ( byte_order + 'IdI' , fd . read ( 16 ) ) etext = stripnull ( fd . read ( esize - 16 ) ) events . append ( ( etime , etype , etext ) ) count -= 1 return events
def min_func ( fun , bounds_min , bounds_max , d = None , rmax = 10 , n0 = 64 , nswp = 10 , verb = True , smooth_fun = None ) : """Find ( approximate ) minimal value of the function on a d - dimensional grid ."""
if d is None : d = len ( bounds_min ) a = np . asanyarray ( bounds_min ) . copy ( ) b = np . asanyarray ( bounds_max ) . copy ( ) else : a = np . ones ( d ) * bounds_min b = np . ones ( d ) * bounds_max if smooth_fun is None : smooth_fun = lambda p , lam : ( math . pi / 2 - np . arctan ( p - lam...
def get_status ( self ) : """Returns a dictionary containing all relevant status information to be broadcast across the network ."""
return { "host" : self . __hostid , "status" : self . _service_status_announced , "statustext" : CommonService . human_readable_state . get ( self . _service_status_announced ) , "service" : self . _service_name , "serviceclass" : self . _service_class_name , "utilization" : self . _utilization . report ( ) , "workflow...
def add_line ( self , start , end , color = ( 0.5 , 0.5 , 0.5 ) , width = 1 ) : """Adds a line . Args : start : Starting coordinates for line . end : Ending coordinates for line . color : Color for text as RGB . Defaults to grey . width : Width of line . Defaults to 1."""
source = vtk . vtkLineSource ( ) source . SetPoint1 ( start ) source . SetPoint2 ( end ) vertexIDs = vtk . vtkStringArray ( ) vertexIDs . SetNumberOfComponents ( 1 ) vertexIDs . SetName ( "VertexIDs" ) # Set the vertex labels vertexIDs . InsertNextValue ( "a" ) vertexIDs . InsertNextValue ( "b" ) source . GetOutput ( )...
def execute_file ( self , filename ) : """Execute a file and provide feedback to the user . : param filename : The pathname of the file to execute ( a string ) . : returns : Whatever the executed file returns on stdout ( a string ) ."""
logger . info ( "Executing file: %s" , format_path ( filename ) ) contents = self . context . execute ( filename , capture = True ) . stdout num_lines = len ( contents . splitlines ( ) ) logger . debug ( "Execution of %s yielded % of output." , format_path ( filename ) , pluralize ( num_lines , 'line' ) ) return conten...
def ilength ( self , s , s_tol = ILENGTH_S_TOL , maxits = ILENGTH_MAXITS , error = ILENGTH_ERROR , min_depth = ILENGTH_MIN_DEPTH ) : """Returns a float , t , such that self . length ( 0 , t ) is approximately s . See the inv _ arclength ( ) docstring for more details ."""
return inv_arclength ( self , s , s_tol = s_tol , maxits = maxits , error = error , min_depth = min_depth )
def cmd2list ( cmd ) : '''Executes a command through the operating system and returns the output as a list , or on error a string with the standard error . EXAMPLE : > > > from subprocess import Popen , PIPE > > > CMDout2array ( ' ls - l ' )'''
p = Popen ( cmd , stdout = PIPE , stderr = PIPE , shell = True ) stdout , stderr = p . communicate ( ) if p . returncode != 0 and stderr != '' : return "ERROR: %s\n" % ( stderr ) else : return stdout . split ( '\n' )
def submissions_between ( reddit_session , subreddit , lowest_timestamp = None , highest_timestamp = None , newest_first = True , extra_cloudsearch_fields = None , verbosity = 1 ) : """Yield submissions between two timestamps . If both ` ` highest _ timestamp ` ` and ` ` lowest _ timestamp ` ` are unspecified , ...
def debug ( msg , level ) : if verbosity >= level : sys . stderr . write ( msg + '\n' ) def format_query_field ( k , v ) : if k in [ "nsfw" , "self" ] : # even though documentation lists " no " and " yes " # as possible values , in reality they don ' t work if v not in [ 0 , 1 , "0" , "1" ] ...
def get_vehicle_health_report ( session , vehicle_index ) : """Get complete vehicle health report ."""
profile = get_profile ( session ) _validate_vehicle ( vehicle_index , profile ) return session . get ( VHR_URL , params = { 'uuid' : profile [ 'vehicles' ] [ vehicle_index ] [ 'uuid' ] } ) . json ( )
def delete_user ( query ) : """Delete a user ."""
user = _query_to_user ( query ) if click . confirm ( f'Are you sure you want to delete {user!r}?' ) : user_manager . delete ( user , commit = True ) click . echo ( f'Successfully deleted {user!r}' ) else : click . echo ( 'Cancelled.' )
def customer_permit ( self , session ) : '''taobao . increment . customer . permit 开通增量消息服务 提供app为自己的用户开通增量消息服务功能'''
request = TOPRequest ( 'taobao.increment.customer.permit' ) self . create ( self . execute ( request , session ) , fields = [ 'app_customer' , ] , models = { 'app_customer' : AppCustomer } ) return self . app_customer
def lastPrePrepareSeqNo ( self , n ) : """This will _ lastPrePrepareSeqNo to values greater than its previous values else it will not . To forcefully override as in case of ` revert ` , directly set ` self . _ lastPrePrepareSeqNo `"""
if n > self . _lastPrePrepareSeqNo : self . _lastPrePrepareSeqNo = n else : self . logger . debug ( '{} cannot set lastPrePrepareSeqNo to {} as its ' 'already {}' . format ( self , n , self . _lastPrePrepareSeqNo ) )
def split_layers ( lower , upper , __fval = None , ** fval ) : """Split 2 layers previously bound . This call un - links calls bind _ top _ down and bind _ bottom _ up . It is the opposite of # noqa : E501 bind _ layers . Please have a look at their docs : - help ( split _ bottom _ up ) - help ( split _ t...
if __fval is not None : fval . update ( __fval ) split_bottom_up ( lower , upper , ** fval ) split_top_down ( lower , upper , ** fval )
def recurse ( record , index , stop_types = STOP_TYPES , already_seen = None , type_group = False ) : """Depth first traversal of a tree , all children are yielded before parent record - - dictionary record to be recursed upon index - - mapping ' address ' ids to dictionary records stop _ types - - types whic...
if already_seen is None : already_seen = set ( ) if record [ 'address' ] not in already_seen : already_seen . add ( record [ 'address' ] ) if 'refs' in record : for child in children ( record , index , stop_types = stop_types ) : if child [ 'address' ] not in already_seen : ...
def _actual_key ( self , key ) : """Translate provided key into the key used in the topology . Tries the unmodified key , the key with the default namespace , and the country converter . Raises a ` ` KeyError ` ` if none of these finds a suitable definition in ` ` self . topology ` ` ."""
if key in self or key in ( "RoW" , "GLO" ) : return key elif ( self . default_namespace , key ) in self : return ( self . default_namespace , key ) if isinstance ( key , str ) and self . coco : new = coco . convert ( names = [ key ] , to = 'ISO2' , not_found = None ) if new in self : if new not ...
def min_mean_cycle ( graph , weight , start = 0 ) : """Minimum mean cycle by Karp : param graph : directed graph in listlist or listdict format : param weight : in matrix format or same listdict graph : param int start : vertex that should be contained in cycle : returns : cycle as vertex list , average arc...
INF = float ( 'inf' ) n = len ( graph ) # compute distances dist = [ [ INF ] * n ] prec = [ [ None ] * n ] dist [ 0 ] [ start ] = 0 for ell in range ( 1 , n + 1 ) : dist . append ( [ INF ] * n ) prec . append ( [ None ] * n ) for node in range ( n ) : for neighbor in graph [ node ] : alt...
def focus ( self , f ) : """Get a new UI proxy copy with the given focus . Return a new UI proxy object as the UI proxy is immutable . Args : f ( 2 - : obj : ` tuple ` / 2 - : obj : ` list ` / : obj : ` str ` ) : the focus point , it can be specified as 2 - list / 2 - tuple coordinates ( x , y ) in Normalized...
ret = copy . copy ( self ) ret . _focus = f return ret
def _update ( self , baseNumber , magnification ) : '''update self . value with basenumber and time interval Args : baseNumber ( str ) : self . baseNumber magnification ( str ) : self . magnification'''
interval = int ( baseNumber * magnification ) self . value = [ IntegerSingle ( interval ) ]
def jpeg_compression ( x , severity = 1 ) : """Conduct jpeg compression to images . Args : x : numpy array , uncorrupted image , assumed to have uint8 pixel in [ 0,255 ] . severity : integer , severity of corruption . Returns : numpy array , image with uint8 pixels in [ 0,255 ] . Applied jpeg compression ...
c = [ 25 , 18 , 15 , 10 , 7 ] [ severity - 1 ] x = tfds . core . lazy_imports . PIL_Image . fromarray ( x . astype ( np . uint8 ) ) output = io . BytesIO ( ) x . save ( output , 'JPEG' , quality = c ) output . seek ( 0 ) x = tfds . core . lazy_imports . PIL_Image . open ( output ) return np . asarray ( x )
def _handler_response ( self , response , data = None ) : """error code response : " request " : " / statuses / home _ timeline . json " , " error _ code " : " 20502 " , " error " : " Need you follow uid . " : param response : : return :"""
if response . status_code == 200 : data = response . json ( ) if isinstance ( data , dict ) and data . get ( "error_code" ) : raise WeiboAPIError ( data . get ( "request" ) , data . get ( "error_code" ) , data . get ( "error" ) ) else : return data else : raise WeiboRequestError ( "Weibo...
async def _dump_variant ( self , writer , elem , elem_type = None , params = None ) : """Dumps variant type to the writer . Supports both wrapped and raw variant . : param writer : : param elem : : param elem _ type : : param params : : return :"""
if isinstance ( elem , VariantType ) or elem_type . WRAPS_VALUE : await dump_uint ( writer , elem . variant_elem_type . VARIANT_CODE , 1 ) await self . dump_field ( writer , getattr ( elem , elem . variant_elem ) , elem . variant_elem_type ) else : fdef = find_variant_fdef ( elem_type , elem ) await dum...
def precip ( self , start , end , ** kwargs ) : r"""Returns precipitation observations at a user specified location for a specified time . Users must specify at least one geographic search parameter ( ' stid ' , ' state ' , ' country ' , ' county ' , ' radius ' , ' bbox ' , ' cwa ' , ' nwsfirezone ' , ' gacc ' ...
self . _check_geo_param ( kwargs ) kwargs [ 'start' ] = start kwargs [ 'end' ] = end kwargs [ 'token' ] = self . token return self . _get_response ( 'stations/precipitation' , kwargs )
def stack1d ( * points ) : """Fill out the columns of matrix with a series of points . This is because ` ` np . hstack ( ) ` ` will just make another 1D vector out of them and ` ` np . vstack ( ) ` ` will put them in the rows . Args : points ( Tuple [ numpy . ndarray , . . . ] ) : Tuple of 1D points ( i . e...
result = np . empty ( ( 2 , len ( points ) ) , order = "F" ) for index , point in enumerate ( points ) : result [ : , index ] = point return result
def create_hardlink ( self , dest_path : str ) : '''create hardlink for the directory ( includes childs ) .'''
# self dirinfo = DirectoryInfo ( dest_path ) dirinfo . ensure_created ( ) # child for item in self . list_items ( ) : item . create_hardlink ( os . path . join ( dest_path , item . path . name ) )
def open_scubadir_file ( self , name , mode ) : '''Opens a file in the ' scubadir ' This file will automatically be bind - mounted into the container , at a path given by the ' container _ path ' property on the returned file object .'''
path = os . path . join ( self . __scubadir_hostpath , name ) assert not os . path . exists ( path ) # Make any directories required mkdir_p ( os . path . dirname ( path ) ) f = File ( path , mode ) f . container_path = os . path . join ( self . __scubadir_contpath , name ) return f
def make_sentence_with_start ( self , beginning , strict = True , ** kwargs ) : """Tries making a sentence that begins with ` beginning ` string , which should be a string of one to ` self . state ` words known to exist in the corpus . If strict = = True , then markovify will draw its initial inspiration on...
split = tuple ( self . word_split ( beginning ) ) word_count = len ( split ) if word_count == self . state_size : init_states = [ split ] elif word_count > 0 and word_count < self . state_size : if strict : init_states = [ ( BEGIN , ) * ( self . state_size - word_count ) + split ] else : ini...
def do_stack_resource ( self , args ) : """Use specified stack resource . stack _ resource - h for detailed help ."""
parser = CommandArgumentParser ( ) parser . add_argument ( '-s' , '--stack-name' , dest = 'stack-name' , help = 'name of the stack resource' ) ; parser . add_argument ( '-i' , '--logical-id' , dest = 'logical-id' , help = 'logical id of the child resource' ) ; args = vars ( parser . parse_args ( args ) ) stackName = ar...
def trigger ( self , event , filter = None , update = None , documents = None , ids = None , replacements = None ) : """Trigger the after _ save hook on documents , if present ."""
if not self . has_trigger ( event ) : return if documents is not None : pass elif ids is not None : documents = self . find_by_ids ( ids , read_use = "primary" ) elif filter is not None : documents = self . find ( filter , read_use = "primary" ) else : raise Exception ( "Trigger couldn't filter docu...
def remove_dns_challenge_txt ( self , zone_id , domain , txt_challenge ) : """Remove DNS challenge TXT ."""
print ( "Deleting DNS challenge.." ) resp = self . route53 . change_resource_record_sets ( HostedZoneId = zone_id , ChangeBatch = self . get_dns_challenge_change_batch ( 'DELETE' , domain , txt_challenge ) ) return resp
def wait ( self , job_id , timeout = None ) : """Wait until the job given by job _ id has a new update . : param job _ id : the id of the job to wait for . : param timeout : how long to wait for a job state change before timing out . : return : Job object corresponding to job _ id"""
return self . storage . wait_for_job_update ( job_id , timeout = timeout )
def handleTagChange ( self , item ) : """Handles the tag change information for this widget . : param item | < QListWidgetItem >"""
# : note PySide = = operator not defined for QListWidgetItem . In this # in this case , we ' re just checking if the object is the exact # same , so ' is ' works just fine . create_item = self . createItem ( ) if item is create_item : self . addTag ( create_item . text ( ) ) elif self . isTagValid ( item . text ( )...
def _convert_item ( self , item ) : """take a parsed item as input and returns a python dictionary the keys will be saved into the Node model either in their respective fields or in the hstore " data " field : param item : object representing parsed item"""
item = self . parse_item ( item ) # name is required if not item [ 'name' ] : raise Exception ( 'Expected property %s not found in item %s.' % ( self . keys [ 'name' ] , item ) ) elif len ( item [ 'name' ] ) > 75 : item [ 'name' ] = item [ 'name' ] [ : 75 ] if not item [ 'status' ] : item [ 'status' ] = sel...
def delaunay2D ( plist , mode = 'xy' , tol = None ) : """Create a mesh from points in the XY plane . If ` mode = ' fit ' ` then the filter computes a best fitting plane and projects the points onto it . . . hint : : | delaunay2d | | delaunay2d . py | _"""
pd = vtk . vtkPolyData ( ) vpts = vtk . vtkPoints ( ) vpts . SetData ( numpy_to_vtk ( plist , deep = True ) ) pd . SetPoints ( vpts ) delny = vtk . vtkDelaunay2D ( ) delny . SetInputData ( pd ) if tol : delny . SetTolerance ( tol ) if mode == 'fit' : delny . SetProjectionPlaneMode ( vtk . VTK_BEST_FITTING_PLANE...
def cache_incr ( self , key ) : """Non - atomic cache increment operation . Not optimal but consistent across different cache backends ."""
cache . set ( key , cache . get ( key , 0 ) + 1 , self . expire_after ( ) )
def remover ( self , id_groupl3 ) : """Remove Group L3 from by the identifier . : param id _ groupl3 : Identifier of the Group L3 . Integer value and greater than zero . : return : None : raise InvalidParameterError : The identifier of Group L3 is null and invalid . : raise GrupoL3NaoExisteError : Group L3 ...
if not is_valid_int_param ( id_groupl3 ) : raise InvalidParameterError ( u'The identifier of Group L3 is invalid or was not informed.' ) url = 'groupl3/' + str ( id_groupl3 ) + '/' code , xml = self . submit ( None , 'DELETE' , url ) return self . response ( code , xml )
def mark_as_read ( self ) : """Marks this message as read in the cloud : return : Success / Failure : rtype : bool"""
if self . object_id is None or self . __is_draft : raise RuntimeError ( 'Attempting to mark as read an unsaved Message' ) data = { self . _cc ( 'isRead' ) : True } url = self . build_url ( self . _endpoints . get ( 'get_message' ) . format ( id = self . object_id ) ) response = self . con . patch ( url , data = dat...
def text_length ( elem ) : """Returns length of the content in this element . Return value is not correct but it is * * good enough * * * ."""
if not elem : return 0 value = elem . value ( ) try : value = len ( value ) except : value = 0 try : for a in elem . elements : value += len ( a . value ( ) ) except : pass return value
def set_string ( self , string_options ) : """Set a series of properties using a string . For example : : ' fred = 12 , tile ' ' [ fred = 12 ] '"""
vo = ffi . cast ( 'VipsObject *' , self . pointer ) cstr = _to_bytes ( string_options ) result = vips_lib . vips_object_set_from_string ( vo , cstr ) return result == 0
def _map_content_row_to_dict ( self , row ) : """Convert dictionary keys from raw csv format ( see CONTENT _ INFO _ HEADER ) , to ricecooker - like keys , e . g . , ' Title * ' - - > ' title '"""
row_cleaned = _clean_dict ( row ) license_id = row_cleaned [ CONTENT_LICENSE_ID_KEY ] if license_id : license_dict = dict ( license_id = row_cleaned [ CONTENT_LICENSE_ID_KEY ] , description = row_cleaned . get ( CONTENT_LICENSE_DESCRIPTION_KEY , None ) , copyright_holder = row_cleaned . get ( CONTENT_LICENSE_COPYRI...
def clone_to ( self , target_catalog ) : """need to clone both the enclosed object + the wrapping asset"""
def _clone ( obj_id ) : package_name = obj_id . get_identifier_namespace ( ) . split ( '.' ) [ 0 ] obj_name = obj_id . get_identifier_namespace ( ) . split ( '.' ) [ 1 ] . lower ( ) catalogs = { 'assessment' : 'bank' , 'repository' : 'repository' } my_catalog_name = catalogs [ package_name . lower ( ) ]...
def _get_m2m_field ( model , sender ) : """Get the field name from a model and a sender from m2m _ changed signal ."""
for field in getattr ( model , '_tracked_fields' , [ ] ) : if isinstance ( model . _meta . get_field ( field ) , ManyToManyField ) : if getattr ( model , field ) . through == sender : return field for field in getattr ( model , '_tracked_related_fields' , { } ) . keys ( ) : if isinstance ( m...
def do_execute ( self ) : """The actual execution of the actor . : return : None if successful , otherwise error message : rtype : str"""
if self . storagehandler is None : return "No storage handler available!" sname = str ( self . resolve_option ( "storage_name" ) ) if sname not in self . storagehandler . storage : return "No storage item called '" + sname + "' present!" self . _output . append ( Token ( self . storagehandler . storage [ sname ...
def get_somatic_variantcallers ( items ) : """Retrieve all variant callers for somatic calling , handling somatic / germline ."""
out = [ ] for data in items : vcs = dd . get_variantcaller ( data ) if isinstance ( vcs , dict ) and "somatic" in vcs : vcs = vcs [ "somatic" ] if not isinstance ( vcs , ( list , tuple ) ) : vcs = [ vcs ] out += vcs return set ( vcs )
def NewData ( self , text ) : '''Method which is called by the SAX parser upon encountering text inside a tag : param text : the text encountered : return : None , has side effects modifying the class itself'''
sint = ignore_exception ( ValueError ) ( int ) if len ( self . tags ) > 0 : if self . tags [ - 1 ] == "beat-type" or self . tags [ - 1 ] == "beats" : if sint ( text ) is int : self . chars [ self . tags [ - 1 ] ] = text if self . validateData ( text ) : if len ( self . tags ) > 0 : i...
def get_program ( self , program_path , controller = None ) : """Find the program within this manifest . If key is found , and it contains a list , iterate over the list and return the program that matches the controller tag . NOTICE : program _ path must have a leading slash ."""
if not program_path or program_path [ 0 ] != '/' : raise ValueError ( "program_path must be a full path with leading slash" ) items = program_path [ 1 : ] . split ( '/' ) result = self for item in items : result = result [ item ] if hasattr ( result , "lower" ) : # string redirect return self . get_program ...
def rtruncated_pareto ( alpha , m , b , size = None ) : """Random bounded Pareto variates ."""
u = random_number ( size ) return ( - ( u * b ** alpha - u * m ** alpha - b ** alpha ) / ( b ** alpha * m ** alpha ) ) ** ( - 1. / alpha )
def _add_constraints ( self , relation ) : """Add the given relation as one or more constraints . Return a list of the names of the constraints added ."""
names = [ ] expression = relation . expression for value_set in expression . value_sets ( ) : name = next ( self . _constr_names ) self . _p . addConstr ( self . _grb_expr_from_value_set ( value_set ) , self . CONSTR_SENSE_MAP [ relation . sense ] , - float ( expression . offset ) , name ) names . append ( ...
def is_ipv6 ( entry ) : """Check if the string provided is a valid ipv6 address : param entry : A string representation of an IP address : return : True if valid , False if invalid"""
try : if socket . inet_pton ( socket . AF_INET6 , entry ) : return True except socket . error : return False
def retry_func_accept_retry_state ( retry_func ) : """Wrap " retry " function to accept " retry _ state " parameter ."""
if not six . callable ( retry_func ) : return retry_func if func_takes_retry_state ( retry_func ) : return retry_func @ _utils . wraps ( retry_func ) def wrapped_retry_func ( retry_state ) : warn_about_non_retry_state_deprecation ( 'retry' , retry_func , stacklevel = 4 ) return retry_func ( retry_state ...
def get_default_set ( self , login_data ) : """记录退出时的播放状态"""
self . cookies = login_data . get ( 'cookies' , '' ) self . user_name = login_data . get ( 'user_name' , '' ) print ( '\033[31m♥\033[0m Get local token - Username: \033[33m%s\033[0m' % login_data [ 'user_name' ] ) self . channel = login_data . get ( 'channel' , 0 ) print ( '\033[31m♥\033[0m Get channel [\033[32m OK \03...
def keep_scan ( cls , result_key , token ) : """Define a property that is set to the list of lines that contain the given token . Uses the get method of the log file ."""
def _scan ( self ) : return self . get ( token ) cls . scan ( result_key , _scan )
def past_datetime ( self , start_date = '-30d' , tzinfo = None ) : """Get a DateTime object based on a random date between a given date and 1 second ago . Accepts date strings that can be recognized by strtotime ( ) . : param start _ date Defaults to " - 30d " : param tzinfo : timezone , instance of datetim...
return self . date_time_between ( start_date = start_date , end_date = '-1s' , tzinfo = tzinfo , )
def recursively_compute_variable ( self , var , start_date = None , end_date = None , time_offset = None , model = None , ** DataAttrs ) : """Compute a variable recursively , loading data where needed . An obvious requirement here is that the variable must eventually be able to be expressed in terms of model - ...
if var . variables is None : return self . _load_or_get_from_model ( var , start_date , end_date , time_offset , model , ** DataAttrs ) else : data = [ self . recursively_compute_variable ( v , start_date , end_date , time_offset , model , ** DataAttrs ) for v in var . variables ] return var . func ( * data...
def Parse ( factory , file ) : """Parses the input file and returns C code and corresponding header file ."""
entities = [ ] while 1 : # Just gets the whole struct nicely formatted data = GetNextStruct ( file ) if not data : break entities . extend ( ProcessStruct ( factory , data ) ) return entities
def get_object_metadata ( obj , ** kw ) : """Get object metadata : param obj : Content object : returns : Dictionary of extracted object metadata"""
# inject metadata of volatile data metadata = { "actor" : get_user_id ( ) , "roles" : get_roles ( ) , "action" : "" , "review_state" : api . get_review_status ( obj ) , "active" : api . is_active ( obj ) , "snapshot_created" : DateTime ( ) . ISO ( ) , "modified" : api . get_modification_date ( obj ) . ISO ( ) , "remote...
def parse_doc_dict ( text = None , split_character = "::" ) : """Returns a dictionary of the parsed doc for example the following would return { ' a ' : ' A ' , ' b ' : ' B ' } : : a : A b : B : param split _ character : : param text : str of the text to parse , by default uses calling function doc : pa...
text = text or function_doc ( 2 ) text = text . split ( split_character , 1 ) [ - 1 ] text = text . split ( ':param' ) [ 0 ] . split ( ':return' ) [ 0 ] text = text . strip ( ) . split ( '\n' ) def clean ( t ) : return t . split ( ':' , 1 ) [ 0 ] . strip ( ) , t . split ( ':' , 1 ) [ 1 ] . strip ( ) return dict ( c...
def find_results_gen ( search_term , field = 'title' ) : '''Return a generator of the results returned by a search of the protein data bank . This generator is used internally . Parameters search _ term : str The search keyword field : str The type of information to record about each entry Examples ...
scan_params = make_query ( search_term , querytype = 'AdvancedKeywordQuery' ) search_result_ids = do_search ( scan_params ) all_titles = [ ] for pdb_result in search_result_ids : result = describe_pdb ( pdb_result ) if field in result . keys ( ) : yield result [ field ]
def hostapi_info ( index = None ) : """Return a generator with information about each host API . If index is given , only one dictionary for the given host API is returned ."""
if index is None : return ( hostapi_info ( i ) for i in range ( _pa . Pa_GetHostApiCount ( ) ) ) else : info = _pa . Pa_GetHostApiInfo ( index ) if not info : raise RuntimeError ( "Invalid host API" ) assert info . structVersion == 1 return { 'name' : ffi . string ( info . name ) . decode ( ...
def get_exdesc ( ) : """Retrieve contract exception ( s ) message ( s ) . If the custom contract is specified with only one exception the return value is the message associated with that exception ; if the custom contract is specified with several exceptions , the return value is a dictionary whose keys are...
# First frame is own function ( get _ exdesc ) , next frame is the calling # function , of which its name is needed fname = inspect . getframeinfo ( sys . _getframe ( 1 ) ) [ 2 ] # Find function object in stack count = 0 fobj = None while not ( fobj and hasattr ( fobj , "exdesc" ) ) : count = count + 1 try : ...
def get_max_devices_per_port_for_storage_bus ( self , bus ) : """Returns the maximum number of devices which can be attached to a port for the given storage bus . in bus of type : class : ` StorageBus ` The storage bus type to get the value for . return max _ devices _ per _ port of type int The maximum n...
if not isinstance ( bus , StorageBus ) : raise TypeError ( "bus can only be an instance of type StorageBus" ) max_devices_per_port = self . _call ( "getMaxDevicesPerPortForStorageBus" , in_p = [ bus ] ) return max_devices_per_port
def get_app_nodes ( self , app_label ) : """Get all nodes for given app : param str app _ label : app label : rtype : list"""
return [ node for node in self . graph . nodes if node [ 0 ] == app_label ]
def get_tracking_beacon ( self , tracking_beacons_id , ** data ) : """GET / tracking _ beacons / : tracking _ beacons _ id / Returns the : format : ` tracking _ beacon ` with the specified : tracking _ beacons _ id ."""
return self . get ( "/tracking_beacons/{0}/" . format ( tracking_beacons_id ) , data = data )
def getResourceSubscription ( self , ep , res ) : '''Get list of all subscriptions for a resource ` ` res ` ` on an endpoint ` ` ep ` ` : param str ep : name of endpoint : param str res : name of resource : return : successful ` ` . status _ code ` ` / ` ` . is _ done ` ` . Check the ` ` . error ` ` : rtype...
result = asyncResult ( ) result . endpoint = ep result . resource = res data = self . _getURL ( "/subscriptions/" + ep + res ) if data . status_code == 200 : # immediate success result . error = False result . is_done = True result . result = data . content else : result . error = response_codes ( "unsu...
def bin_remove ( self ) : """Remove Slackware packages"""
packages = self . args [ 1 : ] options = [ "-r" , "--removepkg" ] additional_options = [ "--deps" , "--check-deps" , "--tag" , "--checklist" ] flag , extra = "" , [ ] flags = [ "-warn" , "-preserve" , "-copy" , "-keep" ] # merge - - check - deps and - - deps options if ( additional_options [ 1 ] in self . args and addi...
def onGamePlayed ( self , mid = None , author_id = None , game_id = None , game_name = None , score = None , leaderboard = None , thread_id = None , thread_type = None , ts = None , metadata = None , msg = None , ) : """Called when the client is listening , and somebody plays a game : param mid : The action ID ...
log . info ( '{} played "{}" in {} ({})' . format ( author_id , game_name , thread_id , thread_type . name ) )
def setUp ( self , mfd_conf ) : '''Input core configuration parameters as specified in the configuration file : param dict mfd _ conf : Configuration file containing the following attributes : * ' Type ' - Choose between the 1st , 2nd or 3rd type of recurrence model { ' First ' | ' Second ' | ' Third ' } ...
self . mfd_type = mfd_conf [ 'Model_Type' ] self . mfd_model = 'Anderson & Luco (Arbitrary) ' + self . mfd_type self . mfd_weight = mfd_conf [ 'Model_Weight' ] self . bin_width = mfd_conf [ 'MFD_spacing' ] self . mmin = mfd_conf [ 'Minimum_Magnitude' ] self . mmax = None self . mmax_sigma = None self . b_value = mfd_co...
def skip_build ( self ) : """Check if build should be skipped"""
skip_msg = self . config . get ( 'skip' , '[ci skip]' ) return ( os . environ . get ( 'CODEBUILD_BUILD_SUCCEEDING' ) == '0' or self . info [ 'current_tag' ] or skip_msg in self . info [ 'head' ] [ 'message' ] )
def register ( cls , app , base_route = None , subdomain = None , route_prefix = None , trailing_slash = None ) : """Registers a FlaskView class for use with a specific instance of a Flask app . Any methods not prefixes with an underscore are candidates to be routed and will have routes registered when this met...
if cls is FlaskView : raise TypeError ( "cls must be a subclass of FlaskView, not FlaskView itself" ) if base_route : cls . orig_base_route = cls . base_route cls . base_route = base_route if route_prefix : cls . orig_route_prefix = cls . route_prefix cls . route_prefix = route_prefix if not subdoma...
def precision ( x , p ) : """Returns a string representation of ` x ` formatted with precision ` p ` . Based on the webkit javascript implementation taken ` from here < https : / / code . google . com / p / webkit - mirror / source / browse / JavaScriptCore / kjs / number _ object . cpp > ` _ , and implemente...
import math x = float ( x ) if x == 0.0 : return "0." + "0" * ( p - 1 ) out = [ ] if x < 0 : out . append ( "-" ) x = - x e = int ( math . log10 ( x ) ) tens = math . pow ( 10 , e - p + 1 ) n = math . floor ( x / tens ) if n < math . pow ( 10 , p - 1 ) : e = e - 1 tens = math . pow ( 10 , e - p + 1 ...