signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_paths ( scheme = _get_default_scheme ( ) , vars = None , expand = True ) : """Return a mapping containing an install scheme . ` ` scheme ` ` is the install scheme name . If not provided , it will return the default scheme for the current platform ."""
_ensure_cfg_read ( ) if expand : return _expand_vars ( scheme , vars ) else : return dict ( _SCHEMES . items ( scheme ) )
def load_de_novos ( path , exclude_indels = True ) : """load mutations into dict indexed by HGNC ID . Args : path : path to file containing de novo data . This should have five tab - separated columns e . g . hgnc chr pos consequence var _ type CTC1 17 8139190 missense _ variant snv CTC1 17 8139191 fram...
genes = { } with open ( path , "r" ) as handle : header = handle . readline ( ) . strip ( ) . split ( "\t" ) for line in handle : line = line . rstrip ( ) . split ( "\t" ) gene = line [ 0 ] position = int ( line [ 2 ] ) - 1 consequence = line [ 3 ] var_type = line [ 4 ] ...
def on_reset_button ( self , _ ) : """Reset graph data and display empty graph"""
for graph in self . visible_graphs . values ( ) : graph . reset ( ) for graph in self . graphs . values ( ) : try : graph . source . reset ( ) except NotImplementedError : pass # Reset clock self . clock_view . set_text ( ZERO_TIME ) self . update_displayed_information ( )
def reference_year ( self , index ) : """Return the reference publication year ."""
# TODO Use meta : parsedDate field instead ? ref_date = self . reference_date ( index ) try : # NB : datetime . year returns an int . return parse ( ref_date ) . year except ValueError : matched = re . search ( r"\d{4}" , ref_date ) if matched : return int ( matched . group ( ) ) else : ...
def players ( game_id ) : """Gets player / coach / umpire information for the game with matching id ."""
# get data data = mlbgame . data . get_players ( game_id ) # parse data parsed = etree . parse ( data ) root = parsed . getroot ( ) output = { } output [ 'game_id' ] = game_id # get player / coach data for team in root . findall ( 'team' ) : type = team . attrib [ 'type' ] + "_team" # the type is either home _ ...
def strip_accents ( s ) : """Strip accents to prepare for slugification ."""
nfkd = unicodedata . normalize ( 'NFKD' , unicode ( s ) ) return u'' . join ( ch for ch in nfkd if not unicodedata . combining ( ch ) )
def cmd_snap_fence ( self , args ) : '''snap fence to KML'''
threshold = 10.0 if len ( args ) > 0 : threshold = float ( args [ 0 ] ) fencemod = self . module ( 'fence' ) loader = fencemod . fenceloader changed = False for i in range ( 0 , loader . count ( ) ) : fp = loader . point ( i ) lat = fp . lat lon = fp . lng best = None best_dist = ( threshold + 1...
def _module_info_to_proto ( module_info , export_scope = None ) : """Serializes ` module _ into ` . Args : module _ info : An instance of ` ModuleInfo ` . export _ scope : Optional ` string ` . Name scope to remove . Returns : An instance of ` module _ pb2 . SonnetModule ` ."""
def strip_name_scope ( name_scope ) : return ops . strip_name_scope ( name_scope , export_scope ) def process_leafs ( value ) : return strip_name_scope ( _graph_element_to_path ( value ) ) module_info_def = module_pb2 . SonnetModule ( module_name = module_info . module_name , scope_name = strip_name_scope ( mod...
def get_def_conf ( ) : '''return default configurations as simple dict'''
ret = dict ( ) for k , v in defConf . items ( ) : ret [ k ] = v [ 0 ] return ret
def connection_from_url ( url , ** kw ) : """Given a url , return an : class : ` . ConnectionPool ` instance of its host . This is a shortcut for not having to parse out the scheme , host , and port of the url before creating an : class : ` . ConnectionPool ` instance . : param url : Absolute URL string tha...
scheme , host , port = get_host ( url ) if scheme == 'https' : return HTTPSConnectionPool ( host , port = port , ** kw ) else : return HTTPConnectionPool ( host , port = port , ** kw )
def export ( self , filename , offset = 0 , length = None ) : """Exports byte array to specified destination Args : filename ( str ) : destination to output file offset ( int ) : byte offset ( default : 0)"""
self . __validate_offset ( filename = filename , offset = offset , length = length ) with open ( filename , 'w' ) as f : if length is None : length = len ( self . data ) - offset if offset > 0 : output = self . data [ offset : length ] else : output = self . data [ : length ] f ....
def revoke_api_key ( ) : """Form submission handler for revoking API keys ."""
build = g . build form = forms . RevokeApiKeyForm ( ) if form . validate_on_submit ( ) : api_key = models . ApiKey . query . get ( form . id . data ) if api_key . build_id != build . id : logging . debug ( 'User does not have access to API key=%r' , api_key . id ) abort ( 403 ) api_key . act...
async def ask_opinion ( self , addr , artifact ) : """Ask an agent ' s opinion about an artifact . : param str addr : Address of the agent which opinion is asked : type addr : : py : class : ` ~ creamas . core . agent . CreativeAgent ` : param object artifact : artifact to be evaluated : returns : agent ' s...
remote_agent = await self . env . connect ( addr ) return await remote_agent . evaluate ( artifact )
def _get_post_data ( cls , args ) : '''Return the post data .'''
if args . post_data : return args . post_data elif args . post_file : return args . post_file . read ( )
async def close ( self , wait_for_completion = True ) : """Close window . Parameters : * wait _ for _ completion : If set , function will return after device has reached target position ."""
await self . set_position ( position = Position ( position_percent = 100 ) , wait_for_completion = wait_for_completion )
def base ( self ) : """Returns properties that are neither incidental nor free ."""
result = [ p for p in self . lazy_properties if not ( p . feature . incidental or p . feature . free ) ] result . extend ( self . base_ ) return result
def get_report ( self , report_type , qs = None ) : """Get data from the report endpoint"""
if qs is None : qs = { } url = self . api_url + "/company/{0}/reports/{1}" . format ( self . company_id , report_type ) result = self . get ( url , params = qs ) return result
def read ( self , tid , length , offset , fh ) : """Read from a file . Data is obtained from ` ` YTStor ` ` object ( which is kept under ` fh ` descriptor ) using its ` ` read ` ` method . Parameters tid : str Path to file . Original ` path ` argument is converted to tuple identifier by ` ` _ pathdec ` ` de...
try : return self . fds [ fh ] . read ( offset , length , fh ) except AttributeError : # control file if tid [ 1 ] not in ( " next" , " prev" ) : raise FuseOSError ( errno . EINVAL ) return self . __sh_script [ offset : offset + length ] except KeyError : # descriptor does not exist . raise Fuse...
def remove ( self , link_type , product , linked_product , identifierType = None ) : """Remove a product link : param link _ type : type of link , one of ' cross _ sell ' , ' up _ sell ' , ' related ' or ' grouped ' : param product : ID or SKU of product : param linked _ product : ID or SKU of linked produc...
return bool ( self . call ( 'catalog_product_link.remove' , [ link_type , product , linked_product , identifierType ] ) )
def reverse_params ( url_name , params = None , ** kwargs ) : """compute the reverse url of ` ` url _ name ` ` and add to it parameters from ` ` params ` ` as querystring : param unicode url _ name : a URL pattern name : param params : Some parameter to append to the reversed URL : type params : : obj : ` d...
url = reverse ( url_name , ** kwargs ) params = urlencode ( params if params else { } ) if params : return u"%s?%s" % ( url , params ) else : return url
def _scan_response ( self ) : """Create scan response data ."""
voltage = struct . pack ( "<H" , int ( self . voltage * 256 ) ) reading = struct . pack ( "<HLLL" , 0xFFFF , 0 , 0 , 0 ) response = voltage + reading return response
def bound_weights ( weights , minimum = None , maximum = None ) : """Bound a weight list so that all outcomes fit within specified bounds . The probability distribution within the ` ` minimum ` ` and ` ` maximum ` ` values remains the same . Weights in the list with outcomes outside of ` ` minimum ` ` and ` `...
# Copy weights to avoid side - effects bounded_weights = weights [ : ] # Remove weights outside of minimum and maximum if minimum is not None and maximum is not None : if maximum < minimum : raise ValueError bounded_weights = [ bw for bw in bounded_weights if minimum <= bw [ 0 ] <= maximum ] elif minimu...
def chain_list ( self ) : """GET / chain Use the Chain API to retrieve the current state of the blockchain . The returned BlockchainInfo message is defined inside fabric . proto . message BlockchainInfo { uint64 height = 1; bytes currentBlockHash = 2; bytes previousBlockHash = 3; : return : json body ...
res = self . _get ( self . _url ( "/chain" ) ) return self . _result ( res , True )
def __execute_bisz ( self , instr ) : """Execute BISZ instruction ."""
op0_val = self . read_operand ( instr . operands [ 0 ] ) op2_val = 1 if op0_val == 0 else 0 self . write_operand ( instr . operands [ 2 ] , op2_val ) return None
def get_assessment_part_form_for_update ( self , assessment_part_id ) : """Gets the assessment part form for updating an existing assessment part . A new assessment part form should be requested for each update transaction . arg : assessment _ part _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Assessm...
collection = JSONClientValidated ( 'assessment_authoring' , collection = 'AssessmentPart' , runtime = self . _runtime ) if not isinstance ( assessment_part_id , ABCId ) : raise errors . InvalidArgument ( 'the argument is not a valid OSID Id' ) if ( assessment_part_id . get_identifier_namespace ( ) != 'assessment_au...
def can_delete_assets ( self ) : """Tests if this user can delete ` ` Assets ` ` . A return of true does not guarantee successful authorization . A return of false indicates that it is known deleting an ` ` Asset ` ` will result in a ` ` PermissionDenied ` ` . This is intended as a hint to an application th...
url_path = construct_url ( 'authorization' , bank_id = self . _catalog_idstr ) return self . _get_request ( url_path ) [ 'assetHints' ] [ 'canDelete' ]
def ready ( self ) : """Sets up the application after startup ."""
self . log ( 'Got' , len ( schemastore ) , 'data and' , len ( configschemastore ) , 'component schemata.' , lvl = debug )
def sessions_info ( self , hosts ) : """Returns ClientInfo per session . : param hosts : comma separated lists of members of the ZK ensemble . : returns : A dictionary of ( session _ id , ClientInfo ) ."""
info_by_id = { } for server_endpoint , dump in self . dump_by_server ( hosts ) . items ( ) : server_ip , server_port = server_endpoint for line in dump . split ( "\n" ) : mat = self . IP_PORT_REGEX . match ( line ) if mat is None : continue ip , port , sid = mat . groups ( ) ...
def _init_metadata ( self ) : """stub"""
self . _min_string_length = None self . _max_string_length = None self . _solution_metadata = { 'element_id' : Id ( self . my_osid_object_form . _authority , self . my_osid_object_form . _namespace , 'solution' ) , 'element_label' : 'Solution' , 'required' : False , 'read_only' : False , 'linked' : False , 'array' : Fa...
def _merge_states ( self , states ) : """Merges a list of states . : param states : the states to merge : returns SimState : the resulting state"""
if self . _hierarchy : optimal , common_history , others = self . _hierarchy . most_mergeable ( states ) else : optimal , common_history , others = states , None , [ ] if len ( optimal ) >= 2 : # We found optimal states ( states that share a common ancestor ) to merge . # Compute constraints for each state star...
def assignMgtKey ( self , CorpNum , MgtKeyType , ItemKey , MgtKey , UserID = None ) : """관리번호할당 args CorpNum : 팝빌회원 사업자번호 MgtKeyType : 세금계산서 유형 , SELL - 매출 , BUY - 매입 , TRUSTEE - 위수탁 ItemKey : 아이템키 ( Search API로 조회 가능 ) MgtKey : 세금계산서에 할당ᄒ...
if MgtKeyType == None or MgtKeyType == '' : raise PopbillException ( - 99999999 , "세금계산서 발행유형이 입력되지 않았습니다." ) if ItemKey == None or ItemKey == '' : raise PopbillException ( - 99999999 , "아이템키가 입력되지 않았습니다." ) if MgtKey == None or MgtKey == '' : raise PopbillException ( - 99999999 , "관리번호가 입력되지 않았습니다." ) post...
def exec_after_request_actions ( actions , response , ** kwargs ) : """Executes actions of the " after " and " after _ METHOD " groups . A " response " var will be injected in the current context ."""
current_context [ "response" ] = response groups = ( "after_" + flask . request . method . lower ( ) , "after" ) try : rv = execute_actions ( actions , limit_groups = groups , ** kwargs ) except ReturnValueException as e : rv = e . value if rv : return rv return response
def to_csv ( self , filename , stimuli = None , inhibitors = None , prepend = "" ) : """Writes the list of clampings to a CSV file Parameters filename : str Absolute path where to write the CSV file stimuli : Optional [ list [ str ] ] List of stimuli names . If given , stimuli are converted to { 0,1 } ins...
self . to_dataframe ( stimuli , inhibitors , prepend ) . to_csv ( filename , index = False )
def NextToken ( self ) : """Fetch the next token by trying to match any of the regexes in order ."""
# Nothing in the input stream - no token can match . if not self . buffer : return current_state = self . state for token in self . _tokens : # Does the rule apply to us ? if token . state_regex and not token . state_regex . match ( current_state ) : continue if self . verbose : logging . de...
def times ( filenames , tolerance = 2 ) : """For the given file ( s ) , return the time ranges available . Tolerance sets the number of seconds between time ranges . Any gaps larger than tolerance seconds will result in a new time range . : param filenames : Single filename ( string ) or list of filenames :...
times = { } delta = datetime . timedelta ( seconds = tolerance ) if isinstance ( filenames , str ) : filenames = [ filenames ] for filename in filenames : with open ( filename , 'r' ) as stream : times [ filename ] = list ( ) header , packet = stream . read ( ) start , stop = header . ti...
def hibernate ( app ) : """Pause an experiment and remove costly resources ."""
log ( "The database backup URL is..." ) backup_url = data . backup ( app ) log ( backup_url ) log ( "Scaling down the web servers..." ) heroku_app = HerokuApp ( app ) heroku_app . scale_down_dynos ( ) log ( "Removing addons..." ) addons = [ "heroku-postgresql" , # " papertrail " , "heroku-redis" , ] for addon in addons...
def size ( self , width = None , height = None ) : u'''Set / get window size .'''
sc = System . Console if width is not None and height is not None : sc . BufferWidth , sc . BufferHeight = width , height else : return sc . BufferWidth , sc . BufferHeight if width is not None and height is not None : sc . WindowWidth , sc . WindowHeight = width , height else : return sc . WindowWidth ...
def read_fits_bintable ( self , hdu = 1 , drop_nonscalar_ok = True , ** kwargs ) : """Open as a FITS file , read in a binary table , and return it as a : class : ` pandas . DataFrame ` , converted with : func : ` pkwit . numutil . fits _ recarray _ to _ data _ frame ` . The * hdu * argument specifies which HD...
from astropy . io import fits from . numutil import fits_recarray_to_data_frame as frtdf with fits . open ( text_type ( self ) , mode = 'readonly' , ** kwargs ) as hdulist : return frtdf ( hdulist [ hdu ] . data , drop_nonscalar_ok = drop_nonscalar_ok )
def linkify_one_command_with_commands ( self , commands , prop ) : """Link a command : param commands : object commands : type commands : object : param prop : property name : type prop : str : return : None"""
if not hasattr ( self , prop ) : return command = getattr ( self , prop ) . strip ( ) if not command : setattr ( self , prop , None ) return data = { "commands" : commands , "call" : command } if hasattr ( self , 'poller_tag' ) : data . update ( { "poller_tag" : self . poller_tag } ) if hasattr ( self ,...
def _updateRepo ( self , func , * args , ** kwargs ) : """Runs the specified function that updates the repo with the specified arguments . This method ensures that all updates are transactional , so that if any part of the update fails no changes are made to the repo ."""
# TODO how do we make this properly transactional ? self . _repo . open ( datarepo . MODE_WRITE ) try : func ( * args , ** kwargs ) self . _repo . commit ( ) finally : self . _repo . close ( )
def order_by ( self , field_path , direction = ASCENDING ) : """Modify the query to add an order clause on a specific field . See : meth : ` ~ . firestore _ v1beta1 . client . Client . field _ path ` for more information on * * field paths * * . Successive : meth : ` ~ . firestore _ v1beta1 . query . Query . ...
field_path_module . split_field_path ( field_path ) # raises order_pb = self . _make_order ( field_path , direction ) new_orders = self . _orders + ( order_pb , ) return self . __class__ ( self . _parent , projection = self . _projection , field_filters = self . _field_filters , orders = new_orders , limit = self . _li...
def deserialize_date ( attr ) : """Deserialize ISO - 8601 formatted string into Date object . : param str attr : response string to be deserialized . : rtype : Date : raises : DeserializationError if string format invalid ."""
if isinstance ( attr , ET . Element ) : attr = attr . text if re . search ( r"[^\W\d_]" , attr , re . I + re . U ) : raise DeserializationError ( "Date must have only digits and -. Received: %s" % attr ) # This must NOT use defaultmonth / defaultday . Using None ensure this raises an exception . return isodate ...
def redirect ( to , headers = None , status = 302 , content_type = "text/html; charset=utf-8" ) : """Abort execution and cause a 302 redirect ( by default ) . : param to : path or fully qualified URL to redirect to : param headers : optional dict of headers to include in the new request : param status : statu...
headers = headers or { } # URL Quote the URL before redirecting safe_to = quote_plus ( to , safe = ":/%#?&=@[]!$&'()*+,;" ) # According to RFC 7231 , a relative URI is now permitted . headers [ "Location" ] = safe_to return HTTPResponse ( status = status , headers = headers , content_type = content_type )
def assign_comments ( self , tree , comments ) : """Capture any comments in the tree header _ comments stores comments preceding a node"""
comments = list ( comments ) comments . sort ( key = lambda c : c . line ) idx_by_line = { 0 : 0 } # { line _ no : comment _ idx } for i , c in enumerate ( comments ) : if c . line not in idx_by_line : idx_by_line [ c . line ] = i idx = [ ] # convert comment tokens to strings , and remove any line breaks se...
def add_output_variable ( self , var ) : """Adds the argument variable as one of the output variable"""
assert ( isinstance ( var , Variable ) ) self . output_variable_list . append ( var )
def from_data ( data ) : """Construct a Prettytable from list of rows ."""
if len ( data ) == 0 : # pragma : no cover return None else : ptable = PrettyTable ( ) ptable . field_names = data [ 0 ] . keys ( ) for row in data : ptable . add_row ( row ) return ptable
def dict ( self ) : """A dict that holds key / values for all of the properties in the object . : return :"""
from collections import OrderedDict SKIP_KEYS = ( ) return OrderedDict ( ( p . key , getattr ( self , p . key ) ) for p in self . __mapper__ . attrs if p . key not in SKIP_KEYS )
def risk ( self , domain , ** kwargs ) : """Returns back the risk score for a given domain"""
return self . _results ( 'risk' , '/v1/risk' , items_path = ( 'components' , ) , domain = domain , cls = Reputation , ** kwargs )
def update_network ( network , name , profile = None ) : '''Updates a network CLI Example : . . code - block : : bash salt ' * ' neutron . update _ network network - name new - network - name : param network : ID or name of network to update : param name : Name of this network : param profile : Profile ...
conn = _auth ( profile ) return conn . update_network ( network , name )
def nla_next ( nla , remaining ) : """Return next attribute in a stream of attributes . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / attr . c # L171 Calculates the offset to the next attribute based on the attribute given . The attribute provided is assumed to be accessible , the ca...
totlen = int ( NLA_ALIGN ( nla . nla_len ) ) remaining . value -= totlen return nlattr ( bytearray_ptr ( nla . bytearray , totlen ) )
def copy ( self ) : """Return a copy of ourself ."""
new_dict = IDict ( std = self . _std ) new_dict . update ( self . store ) return new_dict
def to_file ( self , f ) : """Write vocab to a file . : param ( file ) f : a file object , e . g . as returned by calling ` open ` File format : word0 < TAB > count0 word1 < TAB > count1 word with index 0 is on the 0th line and so on . . ."""
for word in self . _index2word : count = self . _counts [ word ] f . write ( u'{}\t{}\n' . format ( word , count ) . encode ( 'utf-8' ) )
def point_line_distance ( point , start , end ) : """Distance from a point to a line , formed by two points Args : point ( : obj : ` Point ` ) start ( : obj : ` Point ` ) : line point end ( : obj : ` Point ` ) : line point Returns : float : distance to line , in degrees"""
if start == end : return distance ( point , start ) else : un_dist = abs ( ( end . lat - start . lat ) * ( start . lon - point . lon ) - ( start . lat - point . lat ) * ( end . lon - start . lon ) ) n_dist = sqrt ( ( end . lat - start . lat ) ** 2 + ( end . lon - start . lon ) ** 2 ) if n_dist == 0 : ...
def _get_argname_value ( self , argname ) : '''Return the argname value looking up on all possible attributes'''
# Let ' s see if there ' s a private function to get the value argvalue = getattr ( self , '__get_{0}__' . format ( argname ) , None ) if argvalue is not None and callable ( argvalue ) : argvalue = argvalue ( ) if argvalue is None : # Let ' s see if the value is defined as a public class variable argvalue = get...
def _add_fluent_indexes ( self ) : """Add the index commands fluently specified on columns :"""
for column in self . _columns : for index in [ 'primary' , 'unique' , 'index' ] : column_index = column . get ( index ) if column_index is True : getattr ( self , index ) ( column . name ) break elif column_index : getattr ( self , index ) ( column . name ...
def _setContent ( self ) : '''create string representation of doc / lit message container . If message element is simple ( primitive ) , use python type as base class .'''
try : simple = self . _simple except AttributeError : raise RuntimeError , 'call setUp first' # TODO : Hidden contract . Must set self . ns before getNSAlias . . . # File " / usr / local / python / lib / python2.4 / site - packages / ZSI / generate / containers . py " , line 625 , in _ setContent # kw [ ' messa...
def dataframe2sasdata ( self , df : 'pd.DataFrame' , table : str = '_df' , libref : str = '' , results : str = '' , keep_outer_quotes : bool = False ) -> 'SASdata' : """This method imports a Pandas Data Frame to a SAS Data Set , returning the SASdata object for the new Data Set . : param df : Pandas Data Frame to...
if libref != '' : if libref . upper ( ) not in self . assigned_librefs ( ) : print ( "The libref specified is not assigned in this SAS Session." ) return None if results == '' : results = self . results if self . nosub : print ( "too complicated to show the code, read the source :), sorry." ...
def load_cPkl ( fpath , verbose = None , n = None ) : """Loads a pickled file with optional verbosity . Aims for compatibility between python2 and python3. TestPickleExtentsSimple : > > > def makedata _ simple ( ) : > > > data = np . empty ( ( 500 , 2 * * 20 ) , dtype = np . uint8 ) + 1 > > > return data ...
verbose = _rectify_verb_read ( verbose ) if verbose : print ( '[util_io] * load_cPkl(%r)' % ( util_path . tail ( fpath , n = n ) , ) ) try : with open ( fpath , 'rb' ) as file_ : data = pickle . load ( file_ ) except UnicodeDecodeError : if six . PY3 : # try to open python2 pickle with open ...
def match_variant_sequence_to_reference_context ( variant_sequence , reference_context , min_transcript_prefix_length , max_transcript_mismatches , include_mismatches_after_variant = False , max_trimming_attempts = 2 ) : """Iteratively trim low - coverage subsequences of a variant sequence until it either matches...
variant_sequence_in_reading_frame = None # if we can ' t get the variant sequence to match this reference # context then keep trimming it by coverage until either for i in range ( max_trimming_attempts + 1 ) : # check the reverse - complemented prefix if the reference context is # on the negative strand since variant s...
def send_sms ( self , frm , to , text ) : """Sends a simple text message . Example usage : : > > > msg = " Cherie , n ' oublie pas les gauffres ! " > > > nexmo . send _ sms ( ' + 33123456780 ' , ' + 33987654321 ' , msg ) : arg frm : The ` from ` field , a phone number ( international format with or withou...
frm = re . sub ( '[^\d]' , '' , frm ) to = re . sub ( '[^\d]' , '' , to ) api_url = '%s/sms/json' % API_ENDPOINT params = { 'api_key' : self . api_key , 'api_secret' : self . api_secret , 'from' : frm , 'to' : to , 'text' : text , } return self . send_request ( api_url , params , method = 'POST' )
def close ( self , title , matchClass = False ) : """Close the specified window gracefully Usage : C { window . close ( title , matchClass = False ) } @ param title : window title to match against ( as case - insensitive substring match ) @ param matchClass : if True , match on the window class instead of the...
if matchClass : self . _run_wmctrl ( [ "-c" , title , "-x" ] ) else : self . _run_wmctrl ( [ "-c" , title ] )
def _parent_foreign_key_mappings ( cls ) : """Get a mapping of foreign name to the local name of foreign keys"""
parent_rel = cls . __mapper__ . relationships . get ( cls . export_parent ) if parent_rel : return { l . name : r . name for ( l , r ) in parent_rel . local_remote_pairs } return { }
def a_star_search ( start , successors , state_value , is_goal ) : """This is a searching function of A *"""
if is_goal ( start ) : return [ start ] explored = [ ] g = 1 h = state_value ( start ) f = g + h p = [ start ] frontier = [ ( f , g , h , p ) ] while frontier : f , g , h , path = frontier . pop ( 0 ) s = path [ - 1 ] for ( action , state ) in successors ( s , path_actions ( path ) [ - 1 ] if len ( path...
def callback ( msg , _ ) : """Callback function called by libnl upon receiving messages from the kernel . Positional arguments : msg - - nl _ msg class instance containing the data sent by the kernel . Returns : An integer , value of NL _ OK . It tells libnl to proceed with processing the next kernel messag...
# First convert ` msg ` into something more manageable . nlh = nlmsg_hdr ( msg ) iface = ifinfomsg ( nlmsg_data ( nlh ) ) hdr = IFLA_RTA ( iface ) remaining = ctypes . c_int ( nlh . nlmsg_len - NLMSG_LENGTH ( iface . SIZEOF ) ) # Now iterate through each rtattr stored in ` iface ` . while RTA_OK ( hdr , remaining ) : #...
def _get_loggers ( ) : """Return list of Logger classes ."""
from . . import loader modules = loader . get_package_modules ( 'logger' ) return list ( loader . get_plugins ( modules , [ _Logger ] ) )
def trail ( self ) : """Get all visitors by IP and then list the pages they visited in order ."""
inner = ( self . get_query ( ) . select ( PageView . ip , PageView . url ) . order_by ( PageView . timestamp ) ) return ( PageView . select ( PageView . ip , fn . array_agg ( PageView . url ) . alias ( 'urls' ) ) . from_ ( inner . alias ( 't1' ) ) . group_by ( PageView . ip ) )
def import_locations ( self , cells_file ) : """Parse OpenCellID . org data files . ` ` import _ locations ( ) ` ` returns a dictionary with keys containing the OpenCellID . org _ database identifier , and values consisting of a ` ` Cell ` ` objects . It expects cell files in the following format : : 2274...
self . _cells_file = cells_file field_names = ( 'ident' , 'latitude' , 'longitude' , 'mcc' , 'mnc' , 'lac' , 'cellid' , 'crange' , 'samples' , 'created' , 'updated' ) parse_date = lambda s : datetime . datetime . strptime ( s , '%Y-%m-%d %H:%M:%S' ) field_parsers = ( int , float , float , int , int , int , int , int , ...
def nginx_web_ssl_config ( self ) : """Nginx web ssl config"""
dt = [ self . nginx_web_dir , self . nginx_ssl_dir ] return nginx_conf_string . simple_ssl_web_conf . format ( dt = dt )
def register_module ( module_name , module_class ) : """: return : None"""
assert isinstance ( module_name , str ) assert isinstance ( module_class , type ) if module_name not in ModuleRegistry : ModuleRegistry [ module_name ] = module_class else : raise Exception ( "double registration in module registry" )
def instruments ( self , accountID , ** kwargs ) : """Get the list of tradeable instruments for the given Account . The list of tradeable instruments is dependent on the regulatory division that the Account is located in , thus should be the same for all Accounts owned by a single user . Args : accountID ...
request = Request ( 'GET' , '/v3/accounts/{accountID}/instruments' ) request . set_path_param ( 'accountID' , accountID ) request . set_param ( 'instruments' , kwargs . get ( 'instruments' ) ) response = self . ctx . request ( request ) if response . content_type is None : return response if not response . content_...
def get_path ( * args , module = a99 ) : """Returns full path to specified module Args : * args : are added at the end of module path with os . path . join ( ) module : Python module , defaults to a99 Returns : path string > > > get _ path ( )"""
p = os . path . abspath ( os . path . join ( os . path . split ( module . __file__ ) [ 0 ] , * args ) ) return p
def document ( self , document_tree , backend = None ) : """Create a : class : ` DocumentTemplate ` object based on the given document tree and this template configuration Args : document _ tree ( DocumentTree ) : tree of the document ' s contents backend : the backend to use when rendering the document"""
return self . template ( document_tree , configuration = self , backend = backend )
def merge_vertices ( self , digits = None , textured = True ) : """If a mesh has vertices that are closer than trimesh . constants . tol . merge reindex faces to reference the same index for both vertices . Parameters digits : int If specified overrides tol . merge textured : bool If True avoids mergi...
grouping . merge_vertices ( self , digits = digits , textured = textured )
def dispatch ( self , * args , ** kwargs ) : """This decorator sets this view to have restricted permissions ."""
return super ( AnimalYearArchive , self ) . dispatch ( * args , ** kwargs )
def extra_action ( self , names , provider , action , ** kwargs ) : '''Perform actions with block storage devices Example : . . code - block : : python client . extra _ action ( names = [ ' myblock ' ] , action = ' volume _ create ' , provider = ' my - nova ' , kwargs = { ' voltype ' : ' SSD ' , ' size ' : ...
mapper = salt . cloud . Map ( self . _opts_defaults ( ) ) providers = mapper . map_providers_parallel ( ) if provider in providers : provider += ':{0}' . format ( next ( six . iterkeys ( providers [ provider ] ) ) ) else : return False if isinstance ( names , six . string_types ) : names = names . split ( '...
def _rest_patch ( self , suburi , request_headers , request_body ) : """REST PATCH operation . HTTP response codes could be 500 , 404 , 202 etc ."""
return self . _rest_op ( 'PATCH' , suburi , request_headers , request_body )
def add_scoped_variable ( self , name , data_type = None , default_value = None , scoped_variable_id = None ) : """Adds a scoped variable to the container state : param name : The name of the scoped variable : param data _ type : An optional data type of the scoped variable : param default _ value : An option...
if scoped_variable_id is None : # All data port ids have to passed to the id generation as the data port id has to be unique inside a state scoped_variable_id = generate_data_port_id ( self . get_data_port_ids ( ) ) self . _scoped_variables [ scoped_variable_id ] = ScopedVariable ( name , data_type , default_value ...
def logout ( self ) : """Log out the user . > > > odoo . logout ( ) True * Python 2 : * : return : ` True ` if the operation succeed , ` False ` if no user was logged : raise : : class : ` odoorpc . error . RPCError ` : raise : ` urllib2 . URLError ` ( connection error ) * Python 3 : * : return : ` ...
if not self . _env : return False self . json ( '/web/session/destroy' , { } ) self . _env = None self . _login = None self . _password = None return True
def _pvals_from_chi_squared ( self , pairwise_chisq ) : """return statistical significance for props ' columns . * pairwise _ chisq * ( ndarray ) Matrix of chi - squared values ( bases for Wishart CDF )"""
return self . _intersperse_insertion_rows_and_columns ( 1.0 - WishartCDF ( pairwise_chisq , self . _n_min , self . _n_max ) . values )
def random_sent ( self , index ) : """Get one sample from corpus consisting of two sentences . With prob . 50 % these are two subsequent sentences from one doc . With 50 % the second sentence will be a random one from another doc . : param index : int , index of sample . : return : ( str , str , int ) , sente...
t1 , t2 = self . get_corpus_line ( index ) if random . random ( ) > 0.5 : label = 0 else : t2 = self . get_random_line ( ) label = 1 assert len ( t1 ) > 0 assert len ( t2 ) > 0 return t1 , t2 , label
def _run ( self ) : # type : ( Downloader ) - > None """Execute Downloader : param Downloader self : this"""
# mark start self . _start_time = blobxfer . util . datetime_now ( ) logger . info ( 'blobxfer start time: {0}' . format ( self . _start_time ) ) # ensure destination path blobxfer . operations . download . Downloader . ensure_local_destination ( self . _creds , self . _spec , self . _general_options . dry_run ) logger...
def createDocument ( self , initDict = None ) : """create and returns a document populated with the defaults or with the values in initDict"""
if initDict is not None : return self . createDocument_ ( initDict ) else : if self . _validation [ "on_load" ] : self . _validation [ "on_load" ] = False return self . createDocument_ ( self . defaultDocument ) self . _validation [ "on_load" ] = True else : return self . cre...
def _refreshNodeFromTarget ( self ) : """Updates the config settings"""
for key , value in self . viewBox . state . items ( ) : if key != "limits" : childItem = self . childByNodeName ( key ) childItem . data = value else : # limits contains a dictionary as well for limitKey , limitValue in value . items ( ) : limitChildItem = self . limitsItem ....
def add_event_callback ( channel , callback , bouncetime = None ) : """: param channel : the channel based on the numbering system you have specified ( : py : attr : ` GPIO . BOARD ` , : py : attr : ` GPIO . BCM ` or : py : attr : ` GPIO . SUNXI ` ) . : param callback : TODO : param bouncetime : ( optional ) ...
_check_configured ( channel , direction = IN ) if bouncetime is not None : if _gpio_warnings : warnings . warn ( "bouncetime is not (yet) fully supported, continuing anyway. Use GPIO.setwarnings(False) to disable warnings." , stacklevel = 2 ) pin = get_gpio_pin ( _mode , channel ) event . add_edge_callback ...
def initialize_hashes ( self ) : """Create new hashlib objects for each hash we are going to calculate ."""
if ( 'md5' in self . hashes ) : self . md5_calc = hashlib . md5 ( ) if ( 'sha-1' in self . hashes ) : self . sha1_calc = hashlib . sha1 ( ) if ( 'sha-256' in self . hashes ) : self . sha256_calc = hashlib . sha256 ( )
def delete_file ( self , path , prefixed_path , source_storage ) : """Checks if the target file should be deleted if it already exists"""
if isinstance ( self . storage , CumulusStorage ) : if self . storage . exists ( prefixed_path ) : try : etag = self . storage . _get_object ( prefixed_path ) . etag digest = "{0}" . format ( hashlib . md5 ( source_storage . open ( path ) . read ( ) ) . hexdigest ( ) ) if...
def require_session_started ( func ) : """Check if API sessions are started and start them if not"""
@ functools . wraps ( func ) def inner_func ( self , * pargs , ** kwargs ) : if not self . session_started : logger . info ( 'Starting session for required meta method' ) self . start_session ( ) return func ( self , * pargs , ** kwargs ) return inner_func
def to_cloudformation ( self , ** kwargs ) : """Returns the Lambda layer to which this SAM Layer corresponds . : param dict kwargs : already - converted resources that may need to be modified when converting this macro to pure CloudFormation : returns : a list of vanilla CloudFormation Resources , to which this...
resources = [ ] # Append any CFN resources : intrinsics_resolver = kwargs [ "intrinsics_resolver" ] resources . append ( self . _construct_lambda_layer ( intrinsics_resolver ) ) return resources
def get_subdomain_resolver ( name , db_path = None , zonefiles_dir = None ) : """Static method for determining the last - known resolver for a domain name . Returns the resolver URL on success Returns None on error"""
opts = get_blockstack_opts ( ) if not is_subdomains_enabled ( opts ) : log . warn ( "Subdomain support is disabled" ) return None if db_path is None : db_path = opts [ 'subdomaindb_path' ] if zonefiles_dir is None : zonefiles_dir = opts [ 'zonefiles' ] db = SubdomainDB ( db_path , zonefiles_dir ) resolv...
def close ( self , timeout : int = 5 ) -> None : """Stop a ffmpeg instance . Return a coroutine"""
if self . _read_task is not None and not self . _read_task . cancelled ( ) : self . _read_task . cancel ( ) return super ( ) . close ( timeout )
def create ( self , date_at = None , minutes = 0 , note = '' , user_id = None , project_id = None , service_id = None ) : """date _ at - date of time entry . Format YYYY - MM - DD . default : today minutes - default : 0 note - default : ' ' ( empty string ) user _ id - default : actual user id ( only admin us...
keywords = { 'date_at' : date_at , 'minutes' : minutes , 'note' : note , 'user_id' : user_id , 'project_id' : project_id , 'service_id' : service_id , } foo = dict ( ) foo [ 'time_entry' ] = keywords path = partial ( _path , self . adapter ) path = _path ( self . adapter ) return self . _post ( path , ** foo )
def auth_token ( self , apikey = None , secret = None , email = None , password = None ) : """Get authentication token . Uses POST to / auth interface . : Returns : ( str ) Authentication JWT"""
if ( apikey and secret ) or ( self . _apikey and self . _secret ) : body = { "key_id" : apikey or self . _apikey , "secret" : secret or self . _secret } elif ( email and password ) or ( self . _email and self . _password ) : body = { "user" : email or self . _email , "password" : password or self . _password } ...
def _is_target_valid ( self , cfg , target ) : # pylint : disable = no - self - use """Check if the resolved target is valid . : param cfg : The CFG analysis object . : param int target : The target to check . : return : True if the target is valid . False otherwise . : rtype : bool"""
if self . base_state is not None : try : if self . base_state . solver . is_true ( ( self . base_state . memory . permissions ( target ) & 4 ) == 4 ) : return True except SimMemoryError : pass return False if cfg . _addr_in_exec_memory_regions ( target ) : # the jump target is ex...
def update ( cls , session , record ) : """Update a record . Args : session ( requests . sessions . Session ) : Authenticated session . record ( helpscout . BaseModel ) : The record to be updated . Returns : helpscout . BaseModel : Freshly updated record ."""
cls . _check_implements ( 'update' ) data = record . to_api ( ) del data [ 'id' ] data [ 'reload' ] = True return cls ( '/%s/%s.json' % ( cls . __endpoint__ , record . id ) , data = data , request_type = RequestPaginator . PUT , singleton = True , session = session , )
def _make_f_expectation ( self , expr ) : """Calculates : math : ` < F > ` in eq . 12 ( see Ale et al . 2013 ) to calculate : math : ` < F > ` for EACH VARIABLE combination . : param expr : an expression : return : a column vector . Each row correspond to an element of counter . : rtype : : class : ` sympy . ...
# compute derivatives for EACH ENTRY in COUNTER derives = sp . Matrix ( [ derive_expr_from_counter_entry ( expr , self . __species , tuple ( c . n_vector ) ) for c in self . __n_counter ] ) # Computes the factorial terms for EACH entry in COUNTER factorial_terms = sp . Matrix ( [ get_one_over_n_factorial ( tuple ( c . ...
def clamped_interpolation ( skimage_range , sinogram ) : """Interpolate in a possibly smaller space . Sets all points that would be outside the domain to match the boundary values ."""
min_x = skimage_range . domain . min ( ) [ 1 ] max_x = skimage_range . domain . max ( ) [ 1 ] def interpolation_wrapper ( x ) : x = ( x [ 0 ] , np . maximum ( min_x , np . minimum ( max_x , x [ 1 ] ) ) ) return sinogram . interpolation ( x ) return interpolation_wrapper
def unregisterContextEngineId ( self , contextEngineId , pduTypes ) : """Unregister application with dispatcher"""
# 4.3.4 if contextEngineId is None : # Default to local snmpEngineId contextEngineId , = self . mibInstrumController . mibBuilder . importSymbols ( '__SNMP-FRAMEWORK-MIB' , 'snmpEngineID' ) for pduType in pduTypes : k = contextEngineId , pduType if k in self . _appsRegistration : del self . _appsReg...
async def handle_request ( self , request , write_callback , stream_callback ) : """Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object , so exception handling must be done here : param request : HTTP Request object : param write _ ...
# Define ` response ` var here to remove warnings about # allocation before assignment below . response = None cancelled = False try : # Request Middleware response = await self . _run_request_middleware ( request ) # No middleware results if not response : # Execute Handler # Fetch handler from router ...
def set_window ( self , windowC , windowW ) : """Sets visualization window : param windowC : window center : param windowW : window width : return :"""
if not ( windowW and windowC ) : windowW = np . max ( self . img ) - np . min ( self . img ) windowC = ( np . max ( self . img ) + np . min ( self . img ) ) / 2.0 self . imgmax = windowC + ( windowW / 2 ) self . imgmin = windowC - ( windowW / 2 ) self . windowC = windowC self . windowW = windowW
def cancel_entrust ( self , entrust_no ) : """对未成交的调仓进行伪撤单 : param entrust _ no : : return :"""
xq_entrust_list = self . _get_xq_history ( ) is_have = False for xq_entrusts in xq_entrust_list : status = xq_entrusts [ "status" ] # 调仓状态 for entrust in xq_entrusts [ "rebalancing_histories" ] : if entrust [ "id" ] == entrust_no and status == "pending" : is_have = True buy_o...