signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def prep_ip_port ( opts ) : '''parse host : port values from opts [ ' master ' ] and return valid : master : ip address or hostname as a string master _ port : ( optional ) master returner port as integer e . g . : - master : ' localhost : 1234 ' - > { ' master ' : ' localhost ' , ' master _ port ' : 1234} ...
ret = { } # Use given master IP if " ip _ only " is set or if master _ ip is an ipv6 address without # a port specified . The is _ ipv6 check returns False if brackets are used in the IP # definition such as master : ' [ : : 1 ] : 1234 ' . if opts [ 'master_uri_format' ] == 'ip_only' : ret [ 'master' ] = ipaddress ...
def add ( self , networkipv6_id , ipv6_id ) : """List all DHCPRelayIPv4. : param : Object DHCPRelayIPv4 : return : Following dictionary : " networkipv6 " : < networkipv4 _ id > , " id " : < id > , " ipv6 " : { " block1 " : < block1 > , " block2 " : < block2 > , " block3 " : < block3 > , " block4 "...
data = dict ( ) data [ 'networkipv6' ] = networkipv6_id data [ 'ipv6' ] = dict ( ) data [ 'ipv6' ] [ 'id' ] = ipv6_id uri = 'api/dhcprelayv6/' return self . post ( uri , data = data )
def string_to_decimal ( value , strict = True ) : """Return a decimal corresponding to the string representation of a number . @ param value : a string representation of an decimal number . @ param strict : indicate whether the specified string MUST be of a valid decimal number representation . @ return :...
if is_undefined ( value ) : if strict : raise ValueError ( 'The value cannot be null' ) return None try : return float ( value ) except ValueError : raise ValueError ( 'The specified string "%s" does not represent an integer' % value )
def mangle_agreement ( correct_sentence ) : """Given a correct sentence , return a sentence or sentences with a subject verb agreement error"""
# # Examples # Back in the 1800s , people were much shorter and much stronger . # This sentence begins with the introductory phrase , ' back in the 1800s ' # which means that it should have the past tense verb . Any other verb would # be incorrect . # Jack and jill went up the hill . # This sentence is different ; ' go...
def _conditional_error ( self , req , response ) : """Respond with an error . Don ' t bother writing if a response has already started being written ."""
if not req or req . sent_headers : return try : req . simple_response ( response ) except errors . FatalSSLAlert : pass except errors . NoSSLError : self . _handle_no_ssl ( req )
def copyToLocal ( self , paths , dst , check_crc = False ) : '''Copy files that match the file source pattern to the local name . Source is kept . When copying multiple , files , the destination must be a directory . : param paths : Paths to copy : type paths : list of strings : param dst : Destination pa...
if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "copyToLocal: no path given" ) if not dst : raise InvalidInputException ( "copyToLocal: no destination given" ) dst = self . _normalize_path ( dst ) processor = lambda p...
def is_response_to_head ( response ) : """Checks whether the request of a response has been a HEAD - request . Handles the quirks of AppEngine . : param conn : : type conn : : class : ` httplib . HTTPResponse `"""
# FIXME : Can we do this somehow without accessing private httplib _ method ? method = response . _method if isinstance ( method , int ) : # Platform - specific : Appengine return method == 3 return method . upper ( ) == 'HEAD'
def _parse ( self , stream , context , path ) : """Parse stream to find a given byte string ."""
start = stream . tell ( ) read_bytes = "" if self . max_length : read_bytes = stream . read ( self . max_length ) else : read_bytes = stream . read ( ) skip = read_bytes . find ( self . find ) + len ( self . find ) stream . seek ( start + skip ) return skip
def override_from_dict ( self , values_dict ) : """Override existing hyperparameter values , parsing new values from a dictionary . Args : values _ dict : Dictionary of name : value pairs . Returns : The ` HParams ` instance . Raises : KeyError : If a hyperparameter in ` values _ dict ` doesn ' t exist ...
for name , value in values_dict . items ( ) : self . set_hparam ( name , value ) return self
def print_info ( self ) : """prints some info that the user may find useful"""
d = dir ( self ) self . plugins = [ ] for key in d : if key . startswith ( "info_" ) : self . plugins . append ( key ) for key in self . plugins : if self . echo : Console . ok ( "> {0}" . format ( key . replace ( "_" , " " , 1 ) ) ) exec ( "self.%s()" % key )
def annual_reading_counts ( kind = 'all' ) : """Returns a list of dicts , one per year of reading . In year order . Each dict is like this ( if kind is ' all ' ) : { ' year ' : datetime . date ( 2003 , 1 , 1 ) , ' book ' : 12 , # only included if kind is ' all ' or ' book ' ' periodical ' : 18 , # only incl...
if kind == 'all' : kinds = [ 'book' , 'periodical' ] else : kinds = [ kind ] # This will have keys of years ( strings ) and dicts of data : # '2003 ' : { ' books ' : 12 , ' periodicals ' : 18 } , counts = OrderedDict ( ) for k in kinds : qs = Reading . objects . exclude ( end_date__isnull = True ) . filter ...
def Equals ( self , other ) : """Returns true of self and other are approximately equal ."""
return ( self . _approxEq ( self . x , other . x ) and self . _approxEq ( self . y , other . y ) and self . _approxEq ( self . z , other . z ) )
def plot_histograms ( ertobj , keys , ** kwargs ) : """Generate histograms for one or more keys in the given container . Parameters ertobj : container instance or : class : ` pandas . DataFrame ` data object which contains the data . keys : str or list of strings which keys ( column names ) to plot merg...
# you can either provide a DataFrame or an ERT object if isinstance ( ertobj , pd . DataFrame ) : df = ertobj else : df = ertobj . data if df . shape [ 0 ] == 0 : raise Exception ( 'No data present, cannot plot' ) if isinstance ( keys , str ) : keys = [ keys , ] figures = { } merge_figs = kwargs . get (...
def _read_csv_lines ( path ) : """Opens CSV file ` path ` and returns list of rows . Pass output of this function to ` csv . DictReader ` for reading data ."""
csv_file = open ( path , 'r' ) csv_lines_raw = csv_file . readlines ( ) csv_lines_clean = [ line for line in csv_lines_raw if len ( line . strip ( ) ) > 0 ] return csv_lines_clean
def main ( args ) : """Main Entry Point"""
try : import __main__ parser = argparse . ArgumentParser ( usage = '%(prog)s [options] command\n\nVersion\n %(prog)s version ' + str ( __version__ ) , formatter_class = argparse . RawTextHelpFormatter ) parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + str ( __version__ ) )...
def language ( self ) -> str : """Get a random language . : return : Random language . : Example : Irish ."""
languages = self . _data [ 'language' ] return self . random . choice ( languages )
def write_message ( msg , indent = False , mtype = 'standard' , caption = False ) : """Writes message if verbose mode is set ."""
if ( mtype == 'debug' and config . DEBUG ) or ( mtype != 'debug' and config . VERBOSE ) or mtype == 'error' : message ( msg , indent = indent , mtype = mtype , caption = caption )
def disconnect ( self ) : """Disconnect all connected signal types from this receiver ."""
for signal , kwargs in self . connections : signal . disconnect ( self , ** kwargs )
def __write_add_tmpl ( tag_key , tag_list ) : '''Generate the HTML file for adding . : param tag _ key : key of the tags . : param tag _ list : list of the tags . : return : None'''
add_file = os . path . join ( OUT_DIR , 'add' , 'add_' + tag_key . split ( '_' ) [ 1 ] + '.html' ) add_widget_arr = [ ] # var _ dic = eval ( ' dic _ vars . ' + bianliang ) for sig in tag_list : html_sig = '_' . join ( [ 'html' , sig ] ) # var _ html = eval ( ' html _ vars . ' + html _ sig ) var_html = HTML_...
def get_sdb_keys ( self , path ) : """Return the keys for a SDB , which are need for the full secure data path"""
list_resp = get_with_retry ( self . cerberus_url + '/v1/secret/' + path + '/?list=true' , headers = self . HEADERS ) throw_if_bad_response ( list_resp ) return list_resp . json ( ) [ 'data' ] [ 'keys' ]
def write ( filename , mesh , file_format = None , ** kwargs ) : """Writes mesh together with data to a file . : params filename : File to write to . : type filename : str : params point _ data : Named additional point data to write to the file . : type point _ data : dict"""
if not file_format : # deduce file format from extension file_format = _filetype_from_filename ( filename ) # check cells for sanity for key , value in mesh . cells . items ( ) : if key [ : 7 ] == "polygon" : assert value . shape [ 1 ] == int ( key [ 7 : ] ) else : assert value . shape [ 1 ]...
def iflat_nodes ( self , status = None , op = "==" , nids = None ) : """Generators that produces a flat sequence of nodes . if status is not None , only the tasks with the specified status are selected . nids is an optional list of node identifiers used to filter the nodes ."""
nids = as_set ( nids ) if status is None : if not ( nids and self . node_id not in nids ) : yield self for work in self : if nids and work . node_id not in nids : continue yield work for task in work : if nids and task . node_id not in nids : ...
def pythonize ( self , val ) : """Convert value into a boolean : param val : value to convert : type val : bool , int , str : return : boolean corresponding to value : : { ' 1 ' : True , ' yes ' : True , ' true ' : True , ' on ' : True , '0 ' : False , ' no ' : False , ' false ' : False , ' off ' : False ...
__boolean_states__ = { '1' : True , 'yes' : True , 'true' : True , 'on' : True , '0' : False , 'no' : False , 'false' : False , 'off' : False } if isinstance ( val , bool ) : return val val = unique_value ( val ) . lower ( ) if val in list ( __boolean_states__ . keys ( ) ) : return __boolean_states__ [ val ] ra...
def setStyleConfig ( config = None , showhelp = False ) : """set / update global style configurations for magblock elements update Magblock . _ styleconfig _ dict and _ styleconfig _ json : param config : configuration dict or json : param showhelp : if True , print showhelp information , default is False :...
if showhelp : print ( "The input configuration string should be with the format like:" ) print ( MagBlock . _MagBlock__styleconfig_json ) print ( "with all or part of new properties, e.g." ) print ( json . dumps ( { 'quad' : { 'fc' : 'blue' } } ) ) else : if config is None : config = MagBloc...
def parent ( self , parent ) : """Copy context from the parent into this instance as well as adjusting or depth value to indicate where we exist in a command tree ."""
self . _parent = parent if parent : pctx = dict ( ( x , getattr ( parent , x ) ) for x in parent . context_keys ) self . inject_context ( pctx ) self . depth = parent . depth + 1 for command in self . subcommands . values ( ) : command . parent = self # bump . else : self . depth = 0
def get_all_boards ( * args , ** kwargs ) : """Returns every board on 4chan . Returns : dict of : class : ` basc _ py4chan . Board ` : All boards ."""
# Use https based on how the Board class instances are to be instantiated https = kwargs . get ( 'https' , args [ 1 ] if len ( args ) > 1 else False ) # Dummy URL generator , only used to generate the board list which doesn ' t # require a valid board name url_generator = Url ( None , https ) _fetch_boards_metadata ( u...
def parse ( cls , ss ) : """Parses an existing connection string This method will return a : class : ` ~ . ConnectionString ` object which will allow further inspection on the input parameters . : param string ss : The existing connection string : return : A new : class : ` ~ . ConnectionString ` object"""
up = urlparse ( ss ) path = up . path query = up . query if '?' in path : path , _ = up . path . split ( '?' ) if path . startswith ( '/' ) : path = path [ 1 : ] bucket = path options = parse_qs ( query ) scheme = up . scheme hosts = up . netloc . split ( ',' ) return cls ( bucket = bucket , options = options ,...
def iso8601 ( self , tzinfo = None , end_datetime = None ) : """: param tzinfo : timezone , instance of datetime . tzinfo subclass : example ' 2003-10-21T16:05:52 + 0000'"""
return self . date_time ( tzinfo , end_datetime = end_datetime ) . isoformat ( )
def close ( self ) : """Close the hub and wait for it to be closed . This may only be called in the root fiber . After this call returned , Gruvi cannot be used anymore in the current thread . The main use case for calling this method is to clean up resources in a multi - threaded program where you want to ...
if self . _loop is None : return if fibers . current ( ) . parent is not None : raise RuntimeError ( 'close() may only be called in the root fiber' ) elif compat . get_thread_ident ( ) != self . _thread : raise RuntimeError ( 'cannot close() from a different thread' ) self . _closing = True self . _interrup...
def maximum_distance ( value ) : """: param value : input string corresponding to a valid maximum distance : returns : a IntegrationDistance mapping"""
dic = floatdict ( value ) for trt , magdists in dic . items ( ) : if isinstance ( magdists , list ) : # could be a scalar otherwise magdists . sort ( ) # make sure the list is sorted by magnitude for mag , dist in magdists : # validate the magnitudes magnitude ( mag ) return Inte...
def format_endpoint_returns_doc ( endpoint ) : """Return documentation about the resource that an endpoint returns ."""
description = clean_description ( py_doc_trim ( endpoint . _returns . _description ) ) return { 'description' : description , 'resource_name' : endpoint . _returns . _value_type , 'resource_type' : endpoint . _returns . __class__ . __name__ }
def array_controller_by_location ( self , location ) : """Returns array controller instance by location : returns Instance of array controller"""
for member in self . get_members ( ) : if member . location == location : return member
def register_endpoints ( self ) : """See super class method satosa . backends . base . BackendModule # register _ endpoints : rtype list [ ( str , ( ( satosa . context . Context , Any ) - > Any , Any ) ) ]"""
url_map = [ ] sp_endpoints = self . sp . config . getattr ( "endpoints" , "sp" ) for endp , binding in sp_endpoints [ "assertion_consumer_service" ] : parsed_endp = urlparse ( endp ) url_map . append ( ( "^%s$" % parsed_endp . path [ 1 : ] , functools . partial ( self . authn_response , binding = binding ) ) ) ...
def nameddict ( name , props ) : """Point = nameddict ( ' Point ' , [ ' x ' , ' y ' ] ) pt = Point ( x = 1 , y = 2) pt . y = 3 print pt"""
class NamedDict ( object ) : def __init__ ( self , * args , ** kwargs ) : self . __store = { } . fromkeys ( props ) if args : for i , k in enumerate ( props [ : len ( args ) ] ) : self [ k ] = args [ i ] for k , v in kwargs . items ( ) : self [ k ] = v...
def polarisText ( ) : """polarisText part of _ TypedList objects"""
def fget ( self ) : _out = '' _n = '\n' if len ( self ) : if self . parent : _out = '%s%s%s' % ( _out , PolarisText ( * self . parent ) . out , _n ) _out = _out + _n . join ( map ( lambda x : x . polarisText , self ) ) else : _out = '' return _out return locals ( ...
def get_extana_led ( self , cached = True ) : """Returns the current ( R , G , B ) colour of the SK8 - ExtAna LED . Args : cached ( bool ) : if True , returns the locally cached state of the LED ( based on the last call to : meth : ` set _ extana _ led ` ) . Otherwise query the device for the current state ...
if cached and self . led_state is not None : return self . led_state extana_led = self . get_characteristic_handle_from_uuid ( UUID_EXTANA_LED ) if extana_led is None : logger . warn ( 'Failed to find handle for ExtAna LED' ) return None rgb = self . dongle . _read_attribute ( self . conn_handle , extana_le...
def ensure_environment ( variables ) : """Check os . environ to ensure that a given collection of variables has been set . : param variables : A collection of environment variable names : returns : os . environ : raises IncompleteEnvironment : if any variables are not set , with the exception ' s ` ` vari...
missing = [ v for v in variables if v not in os . environ ] if missing : formatted = ', ' . join ( missing ) message = 'Environment variables not set: {}' . format ( formatted ) raise IncompleteEnvironment ( message , missing ) return os . environ
def _evalQUnits ( self , datetimeString , sourceTime ) : """Evaluate text passed by L { _ partialParseQUnits ( ) }"""
s = datetimeString . strip ( ) sourceTime = self . _evalDT ( datetimeString , sourceTime ) # Given string is a time string with single char units like " 5 h 30 m " modifier = '' # TODO m = self . ptc . CRE_QUNITS . search ( s ) if m is not None : units = m . group ( 'qunits' ) quantity = s [ : m . start ( 'quni...
def fetch_all_first_values ( session : Session , select_statement : Select ) -> List [ Any ] : """Returns a list of the first values in each row returned by a ` ` SELECT ` ` query . A Core version of this sort of thing : http : / / xion . io / post / code / sqlalchemy - query - values . html Args : sessio...
rows = session . execute ( select_statement ) # type : ResultProxy try : return [ row [ 0 ] for row in rows ] except ValueError as e : raise MultipleResultsFound ( str ( e ) )
def _parse_global_section ( self , cfg_handler ) : """Parse global ( [ versionner ] ) section : param cfg _ handler : : return :"""
# global configuration if 'versionner' in cfg_handler : cfg = cfg_handler [ 'versionner' ] if 'file' in cfg : self . version_file = cfg [ 'file' ] if 'date_format' in cfg : self . date_format = cfg [ 'date_format' ] if 'up_part' in cfg : self . up_part = cfg [ 'up_part' ] if ...
def _maybe_from_pandas ( data , feature_names , feature_types ) : """Extract internal data from pd . DataFrame"""
try : import pandas as pd except ImportError : return data , feature_names , feature_types if not isinstance ( data , pd . DataFrame ) : return data , feature_names , feature_types dtypes = data . dtypes if not all ( dtype . name in ( 'int64' , 'float64' , 'bool' ) for dtype in dtypes ) : raise ValueErr...
def _iter_texts ( self , tree ) : """Iterates over texts in given HTML tree ."""
skip = ( not isinstance ( tree , lxml . html . HtmlElement ) # comments , etc . or tree . tag in self . skipped_tags ) if not skip : if tree . text : yield Text ( tree . text , tree , 'text' ) for child in tree : for text in self . _iter_texts ( child ) : yield text if tree . tail : ...
def _load ( self , ** kwargs ) : """wrapped with load , override that in a subclass to customize"""
if 'uri' in self . _meta_data : error = "There was an attempt to assign a new uri to this " "resource, the _meta_data['uri'] is %s and it should" " not be changed." % ( self . _meta_data [ 'uri' ] ) raise URICreationCollision ( error ) requests_params = self . _handle_requests_params ( kwargs ) self . _check_lo...
def get_comparable_values ( self ) : """Return a tupple of values representing the unicity of the object"""
return ( str ( self . name ) , str ( self . description ) , str ( self . constraints ) )
def present ( name , timespec , tag = None , user = None , job = None , unique_tag = False ) : '''. . versionchanged : : 2017.7.0 Add a job to queue . job : string Command to run . timespec : string The ' timespec ' follows the format documented in the at ( 1 ) manpage . tag : string Make a tag for th...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } # if job is missing , use name if not job : job = name # quick return on test = True if __opts__ [ 'test' ] : ret [ 'result' ] = None ret [ 'comment' ] = 'job {0} added and will run on {1}' . format ( job , timespec , ) return ...
def MAO ( self , day1 , day2 , rev = 0 ) : """This is MAO ( Moving Average Oscillator ) , not BIAS . It ' s only ' MAday1 - MAday2 ' . 乖離率 , MAday1 - MAday2 兩日之移動平均之差 return list : [0 ] is the times of high , low or equal [0 ] is times [1 ] is the MAO data [1 ] rev = 0 : ↑ ↓ or - , rev = 1:1 - 1 0 回...
day1MA = self . MA_serial ( day1 ) [ 1 ] day2MA = self . MA_serial ( day2 ) [ 1 ] bw = abs ( day1 - day2 ) if len ( day1MA ) > len ( day2MA ) : day1MAs = day1MA [ bw : ] day2MAs = day2MA [ : ] elif len ( day1MA ) < len ( day2MA ) : day1MAs = day1MA [ : ] day2MAs = day2MA [ bw : ] else : day1MAs = da...
def extract_tags ( cls , obj ) : """Extract tags from the given object : param Any obj : Object to use as context : return : Tags to add on span : rtype : dict"""
return dict ( [ ( "request.{}" . format ( attr ) , obj . get ( attr , None ) ) for attr in cls . TAGS ] )
def pushnotify ( subject , message , api = "pushover" , priority = 0 , timestamp = None ) : """Send push notifications using pre - existing APIs Requires a config ` pushnotify . ini ` file in the user home area containing the necessary api tokens and user keys . Default API : " pushover " Config file format...
import types assert type ( priority ) is int and - 1 <= priority <= 2 , "Priority should be and int() between -1 and 2" cfgfile = op . join ( op . expanduser ( "~" ) , "pushnotify.ini" ) Config = ConfigParser ( ) if op . exists ( cfgfile ) : Config . read ( cfgfile ) else : sys . exit ( "Push notification confi...
def media_url ( self , with_ssl = False ) : """Used to return a base media URL . Depending on whether we ' re serving media remotely or locally , this either hands the decision off to the backend , or just uses the value in settings . STATIC _ URL . args : with _ ssl : ( bool ) If True , return an HTTPS url...
if self . serve_remote : # Hand this off to whichever backend is being used . url = self . remote_media_url ( with_ssl ) else : # Serving locally , just use the value in settings . py . url = self . local_media_url return url . rstrip ( '/' )
def observe ( self , path , callback , timeout = None , ** kwargs ) : # pragma : no cover """Perform a GET with observe on a certain path . : param path : the path : param callback : the callback function to invoke upon notifications : param timeout : the timeout of the request : return : the response to th...
request = self . mk_request ( defines . Codes . GET , path ) request . observe = 0 for k , v in kwargs . items ( ) : if hasattr ( request , k ) : setattr ( request , k , v ) return self . send_request ( request , callback , timeout )
def handleProfileChange ( self ) : """Emits that the current profile has changed ."""
# restore the profile settings prof = self . currentProfile ( ) vwidget = self . viewWidget ( ) if vwidget : prof . restore ( vwidget ) if not self . signalsBlocked ( ) : self . currentProfileChanged . emit ( self . currentProfile ( ) )
def install ( plugin_name , * args , ** kwargs ) : '''Install plugin packages based on specified Conda channels . . . versionchanged : : 0.19.1 Do not save rollback info on dry - run . . . versionchanged : : 0.24 Remove channels argument . Use Conda channels as configured in Conda environment . Note tha...
if isinstance ( plugin_name , types . StringTypes ) : plugin_name = [ plugin_name ] # Perform installation conda_args = ( [ 'install' , '-y' , '--json' ] + list ( args ) + plugin_name ) install_log_js = ch . conda_exec ( * conda_args , verbose = False ) install_log = json . loads ( install_log_js . split ( '\x00' )...
def get_attachments ( self ) : """Return the objects from the UIDs given in the request"""
# Create a mapping of source ARs for copy uids = self . request . form . get ( "attachment_uids" , [ ] ) return map ( self . get_object_by_uid , uids )
def compile_state_invariants ( self , state : Sequence [ tf . Tensor ] ) -> List [ TensorFluent ] : '''Compiles the state invarints given current ` state ` fluents . Args : state ( Sequence [ tf . Tensor ] ) : The current state fluents . Returns : A list of : obj : ` rddl2tf . fluent . TensorFluent ` .'''
scope = self . state_invariant_scope ( state ) invariants = [ ] with self . graph . as_default ( ) : with tf . name_scope ( 'state_invariants' ) : for p in self . rddl . domain . invariants : fluent = self . _compile_expression ( p , scope ) invariants . append ( fluent ) ret...
def forget ( self , key ) : """Remove an item from the cache . : param key : The cache key : type key : str : rtype : bool"""
return bool ( self . _redis . delete ( self . _prefix + key ) )
def check_board ( self ) : """Check the board status and give feedback ."""
num_mines = np . sum ( self . info_map == 12 ) num_undiscovered = np . sum ( self . info_map == 11 ) num_questioned = np . sum ( self . info_map == 10 ) if num_mines > 0 : return 0 elif np . array_equal ( self . info_map == 9 , self . mine_map ) : return 1 elif num_undiscovered > 0 or num_questioned > 0 : r...
def cancel_link_unlink_mode ( self ) : """Cancel linking or unlinking mode"""
self . logger . info ( "cancel_link_unlink_mode" ) self . scene_command ( '08' ) # should send http : / / 0.0.0.0/0?08 = I = 0 # # TODO check return status status = self . hub . get_buffer_status ( ) return status
def _tail_profile ( self , db , interval ) : """Tails the system . profile collection"""
latest_doc = None while latest_doc is None : time . sleep ( interval ) latest_doc = db [ 'system.profile' ] . find_one ( ) current_time = latest_doc [ 'ts' ] while True : time . sleep ( interval ) cursor = db [ 'system.profile' ] . find ( { 'ts' : { '$gte' : current_time } } ) . sort ( 'ts' , pymongo . ...
def is_filled ( self , point ) : """Query a point to see if the voxel cell it lies in is filled or not . Parameters point : ( 3 , ) float , point in space Returns is _ filled : bool , is cell occupied or not"""
index = self . point_to_index ( point ) in_range = ( np . array ( index ) < np . array ( self . shape ) ) . all ( ) if in_range : is_filled = self . matrix [ index ] else : is_filled = False return is_filled
def NotifyQueue ( self , notification , ** kwargs ) : """This signals that there are new messages available in a queue ."""
self . _MultiNotifyQueue ( notification . session_id . Queue ( ) , [ notification ] , ** kwargs )
def _get_method_doc ( self ) : """Return method documentations ."""
ret = { } for method_name in self . methods : method = getattr ( self , method_name , None ) if method : ret [ method_name ] = method . __doc__ return ret
def close_report ( self , ledger_id , report_id , callback_uri = None ) : u"""Close Report When you PUT to a report , it will start the process of closing it . When the closing process is complete ( i . e . when report . status = = ' closed ' ) mCASH does a POST call to callback _ uri , if provided . This cal...
arguments = { 'callback_uri' : callback_uri } return self . do_req ( 'PUT' , self . merchant_api_base_url + '/ledger/' + ledger_id + '/report/' + report_id + '/' , arguments )
def warning ( message , css_path = CSS_PATH ) : """Print a warning message on the rich text view"""
env = Environment ( ) env . loader = FileSystemLoader ( osp . join ( CONFDIR_PATH , 'templates' ) ) warning = env . get_template ( "warning.html" ) return warning . render ( css_path = css_path , text = message )
def first ( n , it , constructor = list ) : """> > > first ( 3 , iter ( [ 1,2,3,4 ] ) ) [1 , 2 , 3] > > > first ( 3 , iter ( [ 1,2,3,4 ] ) , iter ) # doctest : + ELLIPSIS < itertools . islice object at . . . > > > > first ( 3 , iter ( [ 1,2,3,4 ] ) , tuple ) (1 , 2 , 3)"""
return constructor ( itertools . islice ( it , n ) )
def install_file ( package , formula_tar , member , formula_def , conn = None ) : '''Install a single file to the file system'''
if member . name == package : return False if conn is None : conn = init ( ) node_type = six . text_type ( __opts__ . get ( 'spm_node_type' ) ) out_path = conn [ 'formula_path' ] tld = formula_def . get ( 'top_level_dir' , package ) new_name = member . name . replace ( '{0}/' . format ( package ) , '' , 1 ) if ...
def flux_r ( q_vars : List [ fl . Var ] , i : int , j : int ) : """Make Fluxion with the distance between body i and j"""
return fl . sqrt ( flux_r2 ( q_vars , i , j ) )
def connect ( db_url = None , pooling = hgvs . global_config . uta . pooling , application_name = None , mode = None , cache = None ) : """Connect to a uta / ncbi database instance . : param db _ url : URL for database connection : type db _ url : string : param pooling : whether to use connection pooling ( p...
_logger . debug ( 'connecting to ' + str ( db_url ) + '...' ) if db_url is None : db_url = _get_ncbi_db_url ( ) url = _parse_url ( db_url ) if url . scheme == 'postgresql' : conn = NCBI_postgresql ( url = url , pooling = pooling , application_name = application_name , mode = mode , cache = cache ) else : # fell...
def get_value ( self , series , key ) : """Fast lookup of value from 1 - dimensional ndarray . Only use this if you know what you ' re doing ."""
# if we have something that is Index - like , then # use this , e . g . DatetimeIndex # Things like ` Series . _ get _ value ` ( via . at ) pass the EA directly here . s = getattr ( series , '_values' , series ) if isinstance ( s , ( ExtensionArray , Index ) ) and is_scalar ( key ) : # GH 20882 , 21257 # Unify Index an...
async def set_async ( self , type_name , entity ) : """Sets an entity asynchronously using the API . Shortcut for using async _ call ( ) with the ' Set ' method . : param type _ name : The type of entity : param entity : The entity to set : raise MyGeotabException : Raises when an exception occurs on the MyGe...
return await self . call_async ( 'Set' , type_name = type_name , entity = entity )
def rh45 ( msg ) : """Radio height . Args : msg ( String ) : 28 bytes hexadecimal message string Returns : int : radio height in ft"""
d = hex2bin ( data ( msg ) ) if d [ 38 ] == '0' : return None rh = bin2int ( d [ 39 : 51 ] ) * 16 return rh
def getComicData ( self , comic ) : """Return dictionary with comic info ."""
if comic not in self . data : if os . path . exists ( self . jsonFn ( comic ) ) : with codecs . open ( self . jsonFn ( comic ) , 'r' , self . encoding ) as f : self . data [ comic ] = json . load ( f ) else : self . data [ comic ] = { 'pages' : { } } return self . data [ comic ]
def setInstrumentParameters ( self , instrpars ) : """This method overrides the superclass to set default values into the parameter dictionary , in case empty entries are provided ."""
pri_header = self . _image [ 0 ] . header usingDefaultGain = False usingDefaultReadnoise = False if self . _isNotValid ( instrpars [ 'gain' ] , instrpars [ 'gnkeyword' ] ) : instrpars [ 'gnkeyword' ] = None if self . _isNotValid ( instrpars [ 'rdnoise' ] , instrpars [ 'rnkeyword' ] ) : instrpars [ 'rnkeyword' ]...
def find_nearest_neighbor ( query , vectors , ban_set , cossims = None ) : """query is a 1d numpy array corresponding to the vector to which you want to find the closest vector vectors is a 2d numpy array corresponding to the vectors you want to consider ban _ set is a set of indicies within vectors you want ...
if cossims is None : cossims = np . matmul ( vectors , query , out = cossims ) else : np . matmul ( vectors , query , out = cossims ) rank = len ( cossims ) - 1 result_i = np . argpartition ( cossims , rank ) [ rank ] while result_i in ban_set : rank -= 1 result_i = np . argpartition ( cossims , rank ) ...
def prepare ( args ) : """% prog prepare " B . oleracea " * . fastq Scan input fastq files ( see below ) and create ` in _ groups . csv ` and ` in _ libs . csv ` . The species name does not really matter ."""
from jcvi . utils . table import write_csv from jcvi . formats . base import write_file from jcvi . formats . fastq import guessoffset , readlen p = OptionParser ( prepare . __doc__ + FastqNamings ) p . add_option ( "--corr" , default = False , action = "store_true" , help = "Extra parameters for corrected data [defaul...
def _launch ( self , run_config , args , ** kwargs ) : """Launch the process and return the process object ."""
del kwargs try : with sw ( "popen" ) : return subprocess . Popen ( args , cwd = run_config . cwd , env = run_config . env ) except OSError : logging . exception ( "Failed to launch" ) raise SC2LaunchError ( "Failed to launch: %s" % args )
def _get_element_properties ( name , element_type , server = None ) : '''Get an element ' s properties'''
properties = { } data = _api_get ( '{0}/{1}/property' . format ( element_type , name ) , server ) # Get properties into a dict if any ( data [ 'extraProperties' ] [ 'properties' ] ) : for element in data [ 'extraProperties' ] [ 'properties' ] : properties [ element [ 'name' ] ] = element [ 'value' ] ret...
def construct_graph ( args ) : """Preliminary HFOS application Launcher"""
app = Core ( args ) setup_root ( app ) if args [ 'debug' ] : from circuits import Debugger hfoslog ( "Starting circuits debugger" , lvl = warn , emitter = 'GRAPH' ) dbg = Debugger ( ) . register ( app ) # TODO : Make these configurable from modules , navdata is _ very _ noisy # but should not be lis...
def participants ( self ) : """agents + computers ( i . e . all non - observers )"""
ret = [ ] for p in self . players : try : if p . isComputer : ret . append ( p ) if not p . isObserver : ret . append ( p ) # could cause an exception if player isn ' t a PlayerPreGame except AttributeError : pass return ret
def register_with_model ( self , name , model ) : '''Called during the creation of a the : class : ` StdModel ` class when : class : ` Metaclass ` is initialised . It fills : attr : ` Field . name ` and : attr : ` Field . model ` . This is an internal function users should never call .'''
if self . name : raise FieldError ( 'Field %s is already registered\ with a model' % self ) self . name = name self . attname = self . get_attname ( ) self . model = model meta = model . _meta self . meta = meta meta . dfields [ name ] = self meta . fields . append ( self ) if not self . primary_key : self . a...
def minutes_from_utc ( self ) : """The timezone offset of this point in time object as + / - minutes from UTC . A positive value of the timezone offset indicates minutes east of UTC , and a negative value indicates minutes west of UTC . 0 , if this object represents a time interval ."""
offset = 0 if self . __datetime is not None and self . __datetime . utcoffset ( ) is not None : offset = self . __datetime . utcoffset ( ) . seconds / 60 if self . __datetime . utcoffset ( ) . days == - 1 : offset = - ( ( 60 * 24 ) - offset ) return int ( offset )
def register_stats_handler ( app , server_name , prefix = '/status/' ) : """Register the stats handler with a Flask app , serving routes with a given prefix . The prefix defaults to ' / _ stats / ' , which is generally what you want ."""
if not prefix . endswith ( '/' ) : prefix += '/' handler = functools . partial ( bottlestats , server_name ) app . get ( prefix , callback = handler ) app . get ( prefix + '<path:path>' , callback = handler )
def bind_transient ( type_to_bind : hexdi . core . restype , accessor : hexdi . core . clstype ) : """shortcut for bind _ type with PerResolveLifeTimeManager on root container : param type _ to _ bind : type that will be resolved by accessor : param accessor : accessor for resolving object"""
hexdi . core . get_root_container ( ) . bind_type ( type_to_bind , accessor , lifetime . PerResolveLifeTimeManager )
async def invite_details ( self , abbreviated : bool ) -> dict : """Get the invite details that were sent or can be sent to the endpoint . : param abbreviated : abbreviate invite details or not Example : phone _ number = ' 8019119191' connection = await Connection . create ( ' foobar123 ' ) invite _ detai...
if not hasattr ( Connection . invite_details , "cb" ) : self . logger . debug ( "vcx_connection_invite_details: Creating callback" ) Connection . invite_details . cb = create_cb ( CFUNCTYPE ( None , c_uint32 , c_uint32 , c_char_p ) ) c_connection_handle = c_uint32 ( self . handle ) c_abbreviated = c_bool ( abbr...
def _http_request ( self , service_type , ** kwargs ) : """Perform an HTTP Request using base _ url and parameters given by kwargs . Results are expected to be given in JSON format and are parsed to python data structures ."""
request_params = urlencode ( kwargs ) request_params = request_params . replace ( '%28' , '' ) . replace ( '%29' , '' ) uri = '%s%s?api_key=%s&%s' % ( self . base_url , service_type , self . api_key , request_params ) header , response = self . conn . request ( uri , method = 'GET' ) return header , response
def get_dns_servers ( interface = 'Local Area Connection' ) : '''Return a list of the configured DNS servers of the specified interface CLI Example : . . code - block : : bash salt ' * ' win _ dns _ client . get _ dns _ servers ' Local Area Connection ' '''
# remove any escape characters interface = interface . split ( '\\' ) interface = '' . join ( interface ) with salt . utils . winapi . Com ( ) : c = wmi . WMI ( ) for iface in c . Win32_NetworkAdapter ( NetEnabled = True ) : if interface == iface . NetConnectionID : iface_config = c . Win32_...
def probe_plugins ( ) : """Runs uWSGI to determine what plugins are available and prints them out . Generic plugins come first then after blank line follow request plugins ."""
plugins = UwsgiRunner ( ) . get_plugins ( ) for plugin in sorted ( plugins . generic ) : click . secho ( plugin ) click . secho ( '' ) for plugin in sorted ( plugins . request ) : click . secho ( plugin )
def copy_to_placeholder ( self , placeholder , sort_order = None ) : """. . versionadded : 1.0 Copy the entire queryset to a new object . Returns a queryset with the newly created objects ."""
qs = self . all ( ) # Get clone for item in qs : # Change the item directly in the resultset . item . copy_to_placeholder ( placeholder , sort_order = sort_order , in_place = True ) if sort_order is not None : sort_order += 1 return qs
def GetAttributeNames ( self ) : """Retrieves the names of all attributes . Returns : list [ str ] : attribute names ."""
attribute_names = [ ] for attribute_name in iter ( self . __dict__ . keys ( ) ) : # Not using startswith to improve performance . if attribute_name [ 0 ] == '_' : continue attribute_names . append ( attribute_name ) return attribute_names
def interpret_defintion_annotations ( potential_definition_inds , aux_note ) : """Try to extract annotation definition information from annotation notes . Information that may be contained : - fs - sample = 0 , label _ state = 22 , aux _ note = ' # # time resolution : XXX ' - custom annotation label definitio...
fs = None custom_labels = [ ] if len ( potential_definition_inds ) > 0 : i = 0 while i < len ( potential_definition_inds ) : if aux_note [ i ] . startswith ( '## ' ) : if not fs : search_fs = rx_fs . findall ( aux_note [ i ] ) if search_fs : ...
def _evaluate ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ evaluate PURPOSE : evaluate the potential at R , z INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : Phi ( R , z ) HISTORY : 2010-07-10 - Started - Bovy ( NYU )"""
if self . alpha == 2. : return nu . log ( R ** 2. + z ** 2. ) / 2. else : return - ( R ** 2. + z ** 2. ) ** ( 1. - self . alpha / 2. ) / ( self . alpha - 2. )
def _format_date ( val , unit ) : """Format dates . : param val : Value ( just the value , not a quantity ) : param unit : Unit . Should be ' rad ' or ' s ' : return : A string representation of this date . > > > _ format _ date ( 4914741782.503475 , ' s ' ) "14 - Aug - 2014/14:03:03" """
if val == numpy . floor ( val ) and unit == 'd' : # Do not show time part if 0 return quantity ( val , unit ) . formatted ( 'YMD_ONLY' ) else : return quantity ( val , unit ) . formatted ( 'DMY' )
def display ( self ) : '''Displays statistics about our LM'''
voc_list = [ ] doc_ids = self . term_count_n . keys ( ) doc_ids . sort ( ) for doc_id in doc_ids : ngrams = len ( self . term_count_n [ doc_id ] [ 'ngrams' ] ) print 'n-Grams (doc %s): %d' % ( str ( doc_id ) , ngrams ) ngrams1 = len ( self . term_count_n_1 [ doc_id ] [ 'ngrams' ] ) print '(n-1)-Grams (d...
def qteSetAppletSignature ( self , appletSignatures : ( str , tuple , list ) ) : """Specify the applet signatures with which this macro is compatible . Qtmacs uses this information at run time to determine if this macro is compatible with a particular applet , as specified by the applet ' s signature . Note t...
# Convert the argument to a tuple if it is not already a tuple # or list . if not isinstance ( appletSignatures , ( tuple , list ) ) : appletSignatures = appletSignatures , # Ensure that all arguments in the tuple / list are strings . for idx , val in enumerate ( appletSignatures ) : if not isinstance ( val , s...
def _projection ( self , a , b , c ) : """Return projection of ( a , b ) onto ( a , c ) Arguments are point locations , not indexes ."""
ab = b - a ac = c - a return a + ( ( ab * ac ) . sum ( ) / ( ac * ac ) . sum ( ) ) * ac
def pad_to_same ( self ) : """Pad shorter pianorolls with zeros at the end along the time axis to make the resulting pianoroll lengths the same as the maximum pianoroll length among all the tracks ."""
max_length = self . get_max_length ( ) for track in self . tracks : if track . pianoroll . shape [ 0 ] < max_length : track . pad ( max_length - track . pianoroll . shape [ 0 ] )
def add_file ( self , file_obj ) : """Add new file into the storage . Args : file _ obj ( file ) : Opened file - like object . Returns : obj : Path where the file - like object is stored contained with hash in : class : ` . PathAndHash ` object . Raises : AssertionError : If the ` file _ obj ` is not fi...
BalancedDiscStorage . _check_interface ( file_obj ) file_hash = self . _get_hash ( file_obj ) dir_path = self . _create_dir_path ( file_hash ) final_path = os . path . join ( dir_path , file_hash ) def copy_to_file ( from_file , to_path ) : with open ( to_path , "wb" ) as out_file : for part in self . _get_...
def parse_plist ( self , preferences_file ) : """Try to reset preferences from preference _ file ."""
preferences_file = os . path . expanduser ( preferences_file ) # Try to open using FoundationPlist . If it ' s not available , # fall back to plistlib and hope it ' s not binary encoded . try : prefs = FoundationPlist . readPlist ( preferences_file ) except NameError : try : prefs = plistlib . readPlist...
def operator_is ( u ) : """operator _ is operator ."""
global _aux if np . ndim ( u ) == 2 : P = _P2 elif np . ndim ( u ) == 3 : P = _P3 else : raise ValueError ( "u has an invalid number of dimensions " "(should be 2 or 3)" ) if u . shape != _aux . shape [ 1 : ] : _aux = np . zeros ( ( len ( P ) , ) + u . shape ) for _aux_i , P_i in zip ( _aux , P ) : ...
def shred ( key_name : str , value : t . Any , field_names : t . Iterable [ str ] = SHRED_DATA_FIELD_NAMES ) -> t . Union [ t . Any , str ] : """Replaces sensitive data in ` ` value ` ` with ` ` * ` ` if ` ` key _ name ` ` contains something that looks like a secret . : param field _ names : a list of key names t...
key_name = key_name . lower ( ) need_shred = False for data_field_name in field_names : if data_field_name in key_name : need_shred = True break if not need_shred : return value return '*' * len ( str ( value ) )
def number_of_subkeys ( self ) : """int : number of subkeys within the key ."""
if not self . _registry_key and self . _registry : self . _GetKeyFromRegistry ( ) return len ( self . _subkeys )