signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
async def get_power_settings ( self ) -> List [ Setting ] : """Get power settings ."""
return [ Setting . make ( ** x ) for x in await self . services [ "system" ] [ "getPowerSettings" ] ( { } ) ]
def _match_type ( self , i ) : """Looks at line ' i ' to see if the line matches a module user type def ."""
self . col_match = self . RE_TYPE . match ( self . _source [ i ] ) if self . col_match is not None : self . section = "types" self . el_type = CustomType self . el_name = self . col_match . group ( "name" ) return True else : return False
def task_loop ( tasks , execute , wait = None , store = TaskStore ( ) ) : """The inner task loop for a task runner . execute : A function that runs a task . It should take a task as its sole argument , and may optionally return a TaskResult . wait : ( optional , None ) A function to run whenever there aren ' ...
completed = set ( ) failed = set ( ) exceptions = [ ] def collect ( task ) : args = [ ] kwargs = { } for arg in task . args : if isinstance ( arg , Task ) : args . append ( store . get ( arg . name ) ) else : args . append ( arg ) for key in task . kwargs : ...
def create ( self , hostname , ** kwargs ) : """Create new EC2 instance named ` ` hostname ` ` . You may specify keyword arguments matching those of ` ` _ _ init _ _ ` ` ( e . g . ` ` size ` ` , ` ` ami ` ` ) to override any defaults given when the object was created , or to fill in parameters not given at in...
# Create creating = "Creating '%s' (a %s instance of %s)" % ( hostname , kwargs [ 'size' ] , kwargs [ 'ami' ] ) with self . msg ( creating ) : instance = self . _create ( hostname , kwargs ) # Name with self . msg ( "Tagging as '%s'" % hostname ) : try : instance . rename ( hostname ) # One - time r...
def custom_background_code ( ) : """Custom code run in a background thread . Prints the current block height . This function is run in a daemonized thread , which means it can be instantly killed at any moment , whenever the main thread quits . If you need more safety , don ' t use a daemonized thread and han...
while True : logger . info ( "Block %s / %s" , str ( Blockchain . Default ( ) . Height ) , str ( Blockchain . Default ( ) . HeaderHeight ) ) sleep ( 15 )
def pformat_ast ( node , include_attributes = INCLUDE_ATTRIBUTES_DEFAULT , indent = INDENT_DEFAULT ) : """Pretty - format an AST tree element Parameters node : ast . AST Top - level node to render . include _ attributes : bool , optional Whether to include node attributes . Default False . indent : str ...
def _fmt ( node , prefix , level ) : def with_indent ( * strs ) : return '' . join ( ( ( indent * level , ) + strs ) ) with_prefix = partial ( with_indent , prefix ) if isinstance ( node , Name ) : # Special Case : # Render Name nodes on a single line . yield with_prefix ( type ( node ) ...
def from_json ( self , json_text ) : """Deserialize a JSON object into this object . This method will check that the JSON object has the required keys and will set each of the keys in that JSON object as an instance attribute of this object . : param json _ text : the JSON text or object to deserialize from...
if type ( json_text ) in [ str , unicode ] : j = json . loads ( json_text ) else : j = json_text try : for p in self . properties : if p == 't' : t = convert_iso_stamp ( j [ p ] , self . tz ) setattr ( self , 't' , t ) else : setattr ( self , p , j [ p ] )...
def match ( self , property_set_ , debug ) : """Returns the alternative condition for this alternative , if the condition is satisfied by ' property _ set ' ."""
# The condition is composed of all base non - conditional properties . # It ' s not clear if we should expand ' self . requirements _ ' or not . # For one thing , it would be nice to be able to put # < toolset > msvc - 6.0 # in requirements . # On the other hand , if we have < variant > release in condition it # does n...
def from_json ( cls , data ) : """Create EPW from json dictionary . Args : data : { " location " : { } , / / ladybug location schema " data _ collections " : [ ] , / / list of hourly annual hourly data collection schemas for each of the 35 fields within the EPW file . " metadata " : { } , / / dict of me...
# Initialize the class with all data missing epw_obj = cls ( None ) epw_obj . _is_header_loaded = True epw_obj . _is_data_loaded = True # Check required and optional keys required_keys = ( 'location' , 'data_collections' ) option_keys_dict = ( 'metadata' , 'heating_dict' , 'cooling_dict' , 'extremes_dict' , 'extreme_ho...
def TeXLaTeXStrFunction ( target = None , source = None , env = None ) : """A strfunction for TeX and LaTeX that scans the source file to decide the " flavor " of the source and then returns the appropriate command string ."""
if env . GetOption ( "no_exec" ) : # find these paths for use in is _ LaTeX to search for included files basedir = os . path . split ( str ( source [ 0 ] ) ) [ 0 ] abspath = os . path . abspath ( basedir ) if is_LaTeX ( source , env , abspath ) : result = env . subst ( '$LATEXCOM' , 0 , target , sou...
def add_find_links ( self , urls ) : """Add ` urls ` to the list that will be prescanned for searches"""
for url in urls : if ( self . to_scan is None # if we have already " gone online " or not URL_SCHEME ( url ) # or it ' s a local file / directory or url . startswith ( 'file:' ) or list ( distros_for_url ( url ) ) # or a direct package link ) : # then go ahead and process it now self . scan_url ...
def network_get ( auth = None , ** kwargs ) : '''Get a single network filters A Python dictionary of filter conditions to push down CLI Example : . . code - block : : bash salt ' * ' neutronng . network _ get name = XLB4'''
cloud = get_operator_cloud ( auth ) kwargs = _clean_kwargs ( ** kwargs ) return cloud . get_network ( ** kwargs )
def aspirate ( self , volume : float = None , location : Union [ types . Location , Well ] = None , rate : float = 1.0 ) -> 'InstrumentContext' : """Aspirate a volume of liquid ( in microliters / uL ) using this pipette from the specified location If only a volume is passed , the pipette will aspirate from it...
self . _log . debug ( "aspirate {} from {} at {}" . format ( volume , location if location else 'current position' , rate ) ) if isinstance ( location , Well ) : point , well = location . bottom ( ) loc = types . Location ( point + types . Point ( 0 , 0 , self . well_bottom_clearance ) , well ) self . move_...
def text ( self ) : """A string representing the textual content of this run , with content child elements like ` ` < w : tab / > ` ` translated to their Python equivalent ."""
text = '' for child in self : if child . tag == qn ( 'w:t' ) : t_text = child . text text += t_text if t_text is not None else '' elif child . tag == qn ( 'w:tab' ) : text += '\t' elif child . tag in ( qn ( 'w:br' ) , qn ( 'w:cr' ) ) : text += '\n' return text
def is_retaincase ( bunchdt , data , commdct , idfobject , fieldname ) : """test if case has to be retained for that field"""
thiscommdct = getfieldcomm ( bunchdt , data , commdct , idfobject , fieldname ) return 'retaincase' in thiscommdct
def spectral_clustering ( geom , K , eigen_solver = 'dense' , random_state = None , solver_kwds = None , renormalize = True , stabalize = True , additional_vectors = 0 ) : """Spectral clustering for find K clusters by using the eigenvectors of a matrix which is derived from a set of similarities S . Parameters ...
# Step 1 : get similarity matrix if geom . affinity_matrix is None : S = geom . compute_affinity_matrix ( ) else : S = geom . affinity_matrix # Check for stability method , symmetric solvers require this if eigen_solver in [ 'lobpcg' , 'amg' ] : stabalize = True if stabalize : geom . laplacian_type = 's...
def usedoc ( other ) : '''Decorator which copies _ _ doc _ _ of given object into decorated one . Usage : > > > def fnc1 ( ) : . . . " " " docstring " " " . . . pass > > > @ usedoc ( fnc1) . . . def fnc2 ( ) : . . . pass > > > fnc2 . _ _ doc _ _ ' docstring ' collections . abc . D : param other ...
def inner ( fnc ) : fnc . __doc__ = fnc . __doc__ or getattr ( other , '__doc__' ) return fnc return inner
def get_formatter_by_name ( _alias , ** options ) : """Lookup and instantiate a formatter by alias . Raises ClassNotFound if not found ."""
cls = find_formatter_class ( _alias ) if cls is None : raise ClassNotFound ( "no formatter found for name %r" % _alias ) return cls ( ** options )
def is_submodule_included ( src , tgt ) : """Check that the tgt ' s submodule is included by src , if they belong to the same module ."""
if tgt is None or not hasattr ( tgt , 'i_orig_module' ) : return True if ( tgt . i_orig_module . keyword == 'submodule' and src . i_orig_module != tgt . i_orig_module and src . i_orig_module . i_modulename == tgt . i_orig_module . i_modulename ) : if src . i_orig_module . search_one ( 'include' , tgt . i_orig_m...
def pause ( self , message : Optional [ Message_T ] = None , ** kwargs ) -> None : """Pause the session for further interaction ."""
if message : asyncio . ensure_future ( self . send ( message , ** kwargs ) ) raise _PauseException
def _send_register_payload ( self , websocket ) : """Send the register payload ."""
file = os . path . join ( os . path . dirname ( __file__ ) , HANDSHAKE_FILE_NAME ) data = codecs . open ( file , 'r' , 'utf-8' ) raw_handshake = data . read ( ) handshake = json . loads ( raw_handshake ) handshake [ 'payload' ] [ 'client-key' ] = self . client_key yield from websocket . send ( json . dumps ( handshake ...
def handle ( self , * args , ** options ) : """Load a default admin user"""
try : admin = User . objects . get ( username = 'admin' ) except User . DoesNotExist : admin = User ( username = 'admin' , first_name = 'admin' , last_name = 'admin' , email = 'admin@localhost.localdomain' , is_staff = True , is_active = True , is_superuser = True , ) admin . set_password ( 'admin' ) admin . sa...
def one_way_portal ( self , other , ** stats ) : """Connect a portal from here to another node , and return it ."""
return self . character . new_portal ( self , other , symmetrical = False , ** stats )
def FromBinary ( cls , record_data , record_count = 1 ) : """Create an UpdateRecord subclass from binary record data . This should be called with a binary record blob ( NOT including the record type header ) and it will decode it into a SetDeviceTagRecord . Args : record _ data ( bytearray ) : The raw recor...
_cmd , _address , _resp_length , payload = cls . _parse_rpc_info ( record_data ) try : os_info , app_info , update_os , update_app = struct . unpack ( "<LLBB" , payload ) update_os = bool ( update_os ) update_app = bool ( update_app ) if update_app and not update_os : tag , version = _parse_info...
def update ( self , ** kwargs ) : """Update existing user . https : / / www . keycloak . org / docs - api / 2.5 / rest - api / index . html # _ userrepresentation : param str first _ name : first _ name for user : param str last _ name : last _ name for user : param str email : Email for user : param bool...
payload = { } for k , v in self . user . items ( ) : payload [ k ] = v for key in USER_KWARGS : from keycloak . admin . clientroles import to_camel_case if key in kwargs : payload [ to_camel_case ( key ) ] = kwargs [ key ] result = self . _client . put ( url = self . _client . get_full_url ( self . ...
def m2o_to_m2m ( cr , model , table , field , source_field ) : """Recreate relations in many2many fields that were formerly many2one fields . Use rename _ columns in your pre - migrate script to retain the column ' s old value , then call m2o _ to _ m2m in your post - migrate script . : param model : The ta...
return m2o_to_x2m ( cr , model , table , field , source_field )
def _clean ( self ) : """Recursively check that all nodes are reachable ."""
found_ids = { } nodes = [ self . _nodes [ _node . Root . ID ] ] while nodes : node = nodes . pop ( ) found_ids [ node . id ] = None nodes = nodes + node . children for node_id in self . _nodes : if node_id in found_ids : continue logger . error ( 'Dangling node: %s' , node_id ) for node_id i...
def deactivate ( self , asset_manager_id ) : """Is is only possible to deactivate an asset manager if your client _ id is also the client _ id that was used to originally create the asset manager . : param asset _ manager _ id : : return :"""
self . logger . info ( 'Deactivate Asset Manager: %s' , asset_manager_id ) url = '%s/asset-managers/%s' % ( self . endpoint , asset_manager_id ) response = self . session . delete ( url ) if response . ok : self . logger . info ( 'Successfully deactivated Asset Manager: %s' , asset_manager_id ) return json_to_a...
def check_seq_exists ( self , seq , amount_ntermwildcards ) : """Look up sequence in sqlite DB . Returns True or False if it exists ( or not ) . When looking up a reversed DB with ntermwildcards : we reverse the sequence of the pep and add a LIKE and % - suffix to the query ."""
cursor = self . get_cursor ( ) if amount_ntermwildcards > 0 : seq = seq [ : : - 1 ] sqlseq = '{}{}' . format ( seq , '%' ) # FIXME non - parametrized string binding because if ? binding is # used the INDEX is not used when looking up , apparently because # the query cant be optimized when using LIKE...
def md5_object ( obj ) : """If an object is hashable , return the string of the MD5. Parameters obj : object Returns md5 : str , MD5 hash"""
hasher = hashlib . md5 ( ) if isinstance ( obj , basestring ) and PY3 : # in python3 convert strings to bytes before hashing hasher . update ( obj . encode ( 'utf-8' ) ) else : hasher . update ( obj ) md5 = hasher . hexdigest ( ) return md5
def credentials ( login = None ) : """Find user credentials . We should have parsed the command line for a ` ` - - login ` ` option . We will try to find credentials in environment variables . We will ask user if we cannot find any in arguments nor environment"""
if not login : login = environ . get ( "PROF_LOGIN" ) password = environ . get ( "PROF_PASSWORD" ) if not login : try : login = input ( "login? " ) print ( "\t\tDon't get prompted everytime. Store your login in the ``~/.profrc`` config file" ) except KeyboardInterrupt : exit ( 0 ) if...
def yum_group_install ( ** kwargs ) : """instals a yum group"""
for grp in list ( kwargs [ 'groups' ] ) : log_green ( "installing %s ..." % grp ) if 'repo' in kwargs : repo = kwargs [ 'repo' ] sudo ( "yum groupinstall -y --quiet " "--enablerepo=%s '%s'" % ( repo , grp ) ) else : sudo ( "yum groups mark install -y --quiet '%s'" % grp ) sud...
def download ( self , url ) : """Download the docuemnt . @ param url : A document url . @ type url : str . @ return : A file pointer to the docuemnt . @ rtype : file - like"""
store = DocumentStore ( ) fp = store . open ( url ) if fp is None : fp = self . options . transport . open ( Request ( url ) ) content = fp . read ( ) fp . close ( ) ctx = self . plugins . document . loaded ( url = url , document = content ) content = ctx . document sax = Parser ( ) return sax . parse ( string = co...
def register_repository ( name , location , installation_policy = None ) : '''Register a PSGet repository on the local machine : param name : The name for the repository : type name : ` ` str ` ` : param location : The URI for the repository : type location : ` ` str ` ` : param installation _ policy : Th...
# Putting quotes around the parameter protects against command injection flags = [ ( 'Name' , name ) ] flags . append ( ( 'SourceLocation' , location ) ) if installation_policy is not None : flags . append ( ( 'InstallationPolicy' , installation_policy ) ) params = '' for flag , value in flags : params += '-{0}...
def _index_loopbacks ( self ) : """Finds all loopbacks and stores them in : attr : ` loopbacks `"""
self . loopbacks = { } try : result = _util . check_output_ ( [ 'losetup' , '-a' ] ) for line in result . splitlines ( ) : m = re . match ( r'(.+): (.+) \((.+)\).*' , line ) if m : self . loopbacks [ m . group ( 1 ) ] = m . group ( 3 ) except Exception : pass
def field_to_json ( self , type_code , key , * args , ** kwargs ) : """Convert a field to a JSON - serializable representation ."""
assert ':' not in key to_json = self . field_function ( type_code , 'to_json' ) key_and_type = "%s:%s" % ( key , type_code ) json_value = to_json ( * args , ** kwargs ) return key_and_type , json_value
def run ( self ) : """Run GapFill command"""
# Load compound information def compound_name ( id ) : if id not in self . _model . compounds : return id return self . _model . compounds [ id ] . properties . get ( 'name' , id ) # Calculate penalty if penalty file exists penalties = { } if self . _args . penalty is not None : for line in self . _...
def _nailgunnable_combined_classpath ( self ) : """Register all of the component tools of the rsc compile task as a " combined " jvm tool . This allows us to invoke their combined classpath in a single nailgun instance ( see # 7089 and #7092 ) . We still invoke their classpaths separately when not using nailgun...
cp = [ ] cp . extend ( self . tool_classpath ( 'rsc' ) ) # Add zinc ' s classpath so that it can be invoked from the same nailgun instance . cp . extend ( super ( RscCompile , self ) . get_zinc_compiler_classpath ( ) ) return cp
def continuous_subpaths ( self ) : """Breaks self into its continuous components , returning a list of continuous subpaths . I . e . ( all ( subpath . iscontinuous ( ) for subpath in self . continuous _ subpaths ( ) ) and self = = concatpaths ( self . continuous _ subpaths ( ) ) )"""
subpaths = [ ] subpath_start = 0 for i in range ( len ( self ) - 1 ) : if self [ i ] . end != self [ ( i + 1 ) % len ( self ) ] . start : subpaths . append ( Path ( * self [ subpath_start : i + 1 ] ) ) subpath_start = i + 1 subpaths . append ( Path ( * self [ subpath_start : len ( self ) ] ) ) retur...
def close_connection ( self , connection , force = False ) : """overriding the baseclass function , this routine will decline to close a connection at the end of a transaction context . This allows for reuse of connections ."""
if force : try : connection . close ( ) except self . operational_exceptions : self . config . logger . error ( 'ConnectionFactory - failed closing' ) for name , conn in self . pool . iteritems ( ) : if conn is connection : break del self . pool [ name ] else : pa...
def _blob_end_handler_factory ( ) : """Generates the handler for the end of a blob value . This includes the base - 64 data and the two closing braces ."""
def expand_res ( res ) : if res is None : return 0 , 0 return res def action ( c , ctx , prev , res , is_first ) : num_digits , num_pads = expand_res ( res ) if c in _BASE64_DIGITS : if prev == _CLOSE_BRACE or prev == _BASE64_PAD : _illegal_character ( c , ctx . set_ion_type ...
def contract ( s ) : """> > > assert contract ( " 1 1 1 2 2 3 " ) = = " 3*1 2*2 1*3" > > > assert contract ( " 1 1 3 2 3 " ) = = " 2*1 1*3 1*2 1*3" """
if not s : return s tokens = s . split ( ) old = tokens [ 0 ] count = [ [ 1 , old ] ] for t in tokens [ 1 : ] : if t == old : count [ - 1 ] [ 0 ] += 1 else : old = t count . append ( [ 1 , t ] ) return " " . join ( "%d*%s" % ( c , t ) for c , t in count )
def _write_csv ( self , datasets , filename ) : """Write CSV : param datasets : Datasets : param filename : File Name"""
with open ( '/' . join ( [ self . output , filename ] ) , mode = 'w' , encoding = self . encoding ) as write_file : writer = csv . writer ( write_file , delimiter = ',' ) for i , row in enumerate ( datasets ) : if i == 0 : # header writer . writerow ( list ( row . keys ( ) ) ) writer...
def configure_sources ( update = False , sources_var = 'install_sources' , keys_var = 'install_keys' ) : """Configure multiple sources from charm configuration . The lists are encoded as yaml fragments in the configuration . The fragment needs to be included as a string . Sources and their corresponding keys ...
sources = safe_load ( ( config ( sources_var ) or '' ) . strip ( ) ) or [ ] keys = safe_load ( ( config ( keys_var ) or '' ) . strip ( ) ) or None if isinstance ( sources , six . string_types ) : sources = [ sources ] if keys is None : for source in sources : add_source ( source , None ) else : if i...
def value_to_db ( self , value ) : """Returns field ' s single value prepared for saving into a database ."""
if isinstance ( value , six . string_types ) : value = value . encode ( "utf_8" ) return value
def parse_JSON ( self , JSON_string ) : """Parses a list of * Observation * instances out of raw JSON data . Only certain properties of the data are used : if these properties are not found or cannot be parsed , an error is issued . : param JSON _ string : a raw JSON string : type JSON _ string : str : re...
if JSON_string is None : raise ParseResponseError ( 'JSON data is None' ) d = json . loads ( JSON_string ) observation_parser = ObservationParser ( ) if 'cod' in d : # Check if server returned errors : this check overcomes the lack of use # of HTTP error status codes by the OWM API 2.5 . This mechanism is # suppose...
def _wrap_function_return ( val ) : """Recursively walks each thing in val , opening lists and dictionaries , converting all occurrences of UnityGraphProxy to an SGraph , UnitySFrameProxy to SFrame , and UnitySArrayProxy to SArray ."""
if type ( val ) is _UnityGraphProxy : return _SGraph ( _proxy = val ) elif type ( val ) is _UnitySFrameProxy : return _SFrame ( _proxy = val ) elif type ( val ) is _UnitySArrayProxy : return _SArray ( _proxy = val ) elif type ( val ) is _UnityModel : # we need to cast it up to the appropriate type uid =...
def __get_extra_extension_classes ( paths ) : """Banana banana"""
extra_classes = [ ] wset = pkg_resources . WorkingSet ( [ ] ) distributions , _ = wset . find_plugins ( pkg_resources . Environment ( paths ) ) for dist in distributions : sys . path . append ( dist . location ) wset . add ( dist ) for entry_point in wset . iter_entry_points ( group = 'hotdoc.extensions' , name...
def reverse_terra ( xyz_au , gast , iterations = 3 ) : """Convert a geocentric ( x , y , z ) at time ` t ` to latitude and longitude . Returns a tuple of latitude , longitude , and elevation whose units are radians and meters . Based on Dr . T . S . Kelso ' s quite helpful article " Orbital Coordinate Systems...
x , y , z = xyz_au R = sqrt ( x * x + y * y ) lon = ( arctan2 ( y , x ) - 15 * DEG2RAD * gast - pi ) % tau - pi lat = arctan2 ( z , R ) a = ERAD / AU_M f = 1.0 / IERS_2010_INVERSE_EARTH_FLATTENING e2 = 2.0 * f - f * f i = 0 while i < iterations : i += 1 C = 1.0 / sqrt ( 1.0 - e2 * ( sin ( lat ) ** 2.0 ) ) l...
def to_dot ( self , name = 'EXPR' ) : # pragma : no cover """Convert to DOT language representation ."""
parts = [ 'graph' , name , '{' , 'rankdir=BT;' ] for ex in self . iter_dfs ( ) : exid = ex . node . id ( ) if ex is Zero : parts += [ "n{} [label=0,shape=box];" . format ( exid ) ] elif ex is One : parts += [ "n{} [label=1,shape=box];" . format ( exid ) ] elif isinstance ( ex , Literal )...
def open_tablebase_native ( directory : PathLike , * , libgtb : Any = None , LibraryLoader : Any = ctypes . cdll ) -> NativeTablebase : """Opens a collection of tables for probing using libgtb . In most cases : func : ` ~ chess . gaviota . open _ tablebase ( ) ` should be used . Use this function only if you do...
libgtb = libgtb or ctypes . util . find_library ( "gtb" ) or "libgtb.so.1.0.1" tables = NativeTablebase ( LibraryLoader . LoadLibrary ( libgtb ) ) tables . add_directory ( directory ) return tables
def batch_update_reimburse ( self , openid , reimburse_status , invoice_list ) : """报销方批量更新发票信息 详情请参考 https : / / mp . weixin . qq . com / wiki ? id = mp1496561749 _ f7T6D : param openid : 用户的 Open ID : param reimburse _ status : 发票报销状态 : param invoice _ list : 发票列表 : type invoice _ list : list [ dict ]...
return self . _post ( 'reimburse/updatestatusbatch' , data = { 'openid' : openid , 'reimburse_status' : reimburse_status , 'invoice_list' : invoice_list , } , )
def p_optional_value ( t ) : """optional _ value : value | empty"""
# return value or None . t [ 0 ] = t [ 1 ] # Note this must be unsigned value = t [ 0 ] if value is None or value [ 0 ] . isdigit ( ) : return msg = '' if value [ 0 ] == '-' : msg = "Can't use negative index %s" % value elif value not in name_dict : msg = "Can't derefence index %s" % value else : data =...
def convert_softmax ( net , node , module , builder ) : """Convert a softmax layer from mxnet to coreml . Parameters net : network A mxnet network object . node : layer Node to convert . module : module An module for MXNet builder : NeuralNetworkBuilder A neural network builder object ."""
input_name , output_name = _get_input_output_name ( net , node ) name = node [ 'name' ] param = _get_attr ( node ) if param is not None and 'axis' in param : axis = literal_eval ( param [ 'axis' ] ) assert axis == 1 , "Only softmax with axis 1 is supported" builder . add_softmax ( name = name , input_name = inp...
def run ( lang , files , session_id , cluster_size , code , clean , build , exec , terminal , basedir , rm , env , env_range , build_range , exec_range , max_parallel , mount , stats , tag , resources , quiet ) : '''Run the given code snippet or files in a session . Depending on the session ID you give ( default ...
if quiet : vprint_info = vprint_wait = vprint_done = _noop else : vprint_info = print_info vprint_wait = print_wait vprint_done = print_done if files and code : print ( 'You can run only either source files or command-line ' 'code snippet.' , file = sys . stderr ) sys . exit ( 1 ) if not files a...
def _calculate_variogram_model ( lags , semivariance , variogram_model , variogram_function , weight ) : """Function that fits a variogram model when parameters are not specified . Returns variogram model parameters that minimize the RMSE between the specified variogram function and the actual calculated variog...
if variogram_model == 'linear' : x0 = [ ( np . amax ( semivariance ) - np . amin ( semivariance ) ) / ( np . amax ( lags ) - np . amin ( lags ) ) , np . amin ( semivariance ) ] bnds = ( [ 0. , 0. ] , [ np . inf , np . amax ( semivariance ) ] ) elif variogram_model == 'power' : x0 = [ ( np . amax ( semivaria...
def apply ( self ) : """Apply the rules of the context to its occurrences . This method executes all the functions defined in self . tasks in the order they are listed . Every function that acts as a context task receives the Context object itself as its only argument . The contextualized occurrences are ...
raw_operations = copy . deepcopy ( self . occurrences ) for task in self . tasks : task ( self ) self . occurrences = raw_operations
def get_samplepos_of_bitseq ( self , start_message : int , start_index : int , end_message : int , end_index : int , include_pause : bool ) : """Determine on which place ( regarding samples ) a bit sequence is : rtype : tuple [ int , int ]"""
try : if start_message > end_message : start_message , end_message = end_message , start_message if start_index >= len ( self . messages [ start_message ] . bit_sample_pos ) - 1 : start_index = len ( self . messages [ start_message ] . bit_sample_pos ) - 1 if not include_pause : ...
def export_account_state ( self , account_state ) : """Make an account state presentable to external consumers"""
return { 'address' : account_state [ 'address' ] , 'type' : account_state [ 'type' ] , 'credit_value' : '{}' . format ( account_state [ 'credit_value' ] ) , 'debit_value' : '{}' . format ( account_state [ 'debit_value' ] ) , 'lock_transfer_block_id' : account_state [ 'lock_transfer_block_id' ] , 'block_id' : account_st...
def SummaryMetadata ( self , run , tag ) : """Return the summary metadata for the given tag on the given run . Args : run : A string name of the run for which summary metadata is to be retrieved . tag : A string name of the tag whose summary metadata is to be retrieved . Raises : KeyError : If the run...
accumulator = self . GetAccumulator ( run ) return accumulator . SummaryMetadata ( tag )
def create_magic_packet ( macaddress ) : """Create a magic packet . A magic packet is a packet that can be used with the for wake on lan protocol to wake up a computer . The packet is constructed from the mac address given as a parameter . Args : macaddress ( str ) : the mac address that should be parsed ...
if len ( macaddress ) == 12 : pass elif len ( macaddress ) == 17 : sep = macaddress [ 2 ] macaddress = macaddress . replace ( sep , '' ) else : raise ValueError ( 'Incorrect MAC address format' ) # Pad the synchronization stream data = b'FFFFFFFFFFFF' + ( macaddress * 16 ) . encode ( ) send_data = b'' #...
def updated ( self ) : 'return datetime . datetime'
return dateutil . parser . parse ( str ( self . f . latestRevision . updated ) )
def _subtotals ( self ) : """Composed tuple storing actual sequence of _ Subtotal objects ."""
return tuple ( _Subtotal ( subtotal_dict , self . valid_elements ) for subtotal_dict in self . _iter_valid_subtotal_dicts ( ) )
def cache ( self , con ) : """Put a connection back into the pool cache ."""
try : if self . _reset == 2 : con . reset ( ) # reset the connection completely else : if self . _reset or con . _transaction : try : con . rollback ( ) # rollback a possible transaction except Exception : pass s...
async def _read ( self , path , * , raw = None , recurse = None , dc = None , separator = None , keys = None , watch = None , consistency = None ) : """Returns the specified key Parameters : dc ( str ) : Specify datacenter that will be used . Defaults to the agent ' s local datacenter . watch ( Blocking ) :...
response = await self . _api . get ( "/v1/kv" , path , params = { "raw" : raw , "dc" : dc , "recurse" : recurse , "separator" : separator , "keys" : keys } , watch = watch , consistency = consistency ) return response
def get_string ( self ) : """make a string representation of the general error report"""
ostr = '' errtotal = self . deletions [ 'total' ] + self . insertions [ 'total' ] + self . mismatches ostr += 'from ' + str ( self . alignment_length ) + ' bp of alignment' + "\n" ostr += ' ' + str ( float ( errtotal ) / float ( self . alignment_length ) ) + " error rate\n" ostr += ' ' + str ( float ( self . mismat...
def payload ( self ) : """Get the payload of the resource according to the content type specified by required _ content _ type or " text / plain " by default . : return : the payload ."""
if self . _content_type is not None : try : return self . _payload [ self . _content_type ] except KeyError : raise KeyError ( "Content-Type not available" ) else : if defines . Content_types [ "text/plain" ] in self . _payload : return self . _payload [ defines . Content_types [ "te...
def show_editor ( self ) : """Create , setup and display the shortcut editor dialog ."""
index = self . proxy_model . mapToSource ( self . currentIndex ( ) ) row , column = index . row ( ) , index . column ( ) shortcuts = self . source_model . shortcuts context = shortcuts [ row ] . context name = shortcuts [ row ] . name sequence_index = self . source_model . index ( row , SEQUENCE ) sequence = sequence_i...
def _validate_columns ( self ) : """Validate the options in the styles"""
geom_cols = { 'the_geom' , 'the_geom_webmercator' , } col_overlap = set ( self . style_cols ) & geom_cols if col_overlap : raise ValueError ( 'Style columns cannot be geometry ' 'columns. `{col}` was chosen.' . format ( col = ',' . join ( col_overlap ) ) )
def _instantiate_players ( self , player_dict ) : """Create a list of player instances for both the home and away teams . For every player listed on the boxscores page , create an instance of the BoxscorePlayer class for that player and add them to a list of players for their respective team . Parameters ...
home_players = [ ] away_players = [ ] for player_id , details in player_dict . items ( ) : player = BoxscorePlayer ( player_id , details [ 'name' ] , details [ 'data' ] ) if details [ 'team' ] == HOME : home_players . append ( player ) else : away_players . append ( player ) return away_play...
def generate ( env ) : """Add Builders and construction variables for MSVC + + to an Environment ."""
static_obj , shared_obj = SCons . Tool . createObjBuilders ( env ) # TODO ( batch ) : shouldn ' t reach in to cmdgen this way ; necessary # for now to bypass the checks in Builder . DictCmdGenerator . _ _ call _ _ ( ) # and allow . cc and . cpp to be compiled in the same command line . static_obj . cmdgen . source_ext_...
def params_of_mean ( value = array ( [ - .005 , 1. ] ) , tau = .1 , rate = 4. ) : """Intercept and slope of rate stochastic of poisson distribution Rate stochastic must be positive for t in [ 0 , T ] p ( intercept , slope | tau , rate ) = N ( slope | 0 , tau ) Exp ( intercept | rate ) 1 ( intercept > 0 ) 1 ( ...
def logp ( value , tau , rate ) : if value [ 1 ] > 0 and value [ 1 ] + value [ 0 ] * 110 > 0 : return normal_like ( value [ 0 ] , 0. , tau ) + exponential_like ( value [ 1 ] , rate ) else : return - Inf def random ( tau , rate ) : val = zeros ( 2 ) val [ 0 ] = rnormal ( 0. , tau ) va...
def set_text ( self , text ) : """Set the filter text ."""
text = text . strip ( ) new_text = self . text ( ) + text self . setText ( new_text )
def arg ( self , i ) : """Returns the ith argument . Raise a SimProcedureArgumentError if we don ' t have such an argument available . : param int i : The index of the argument to get : return : The argument : rtype : object"""
if self . use_state_arguments : r = self . cc . arg ( self . state , i ) else : if i >= len ( self . arguments ) : raise SimProcedureArgumentError ( "Argument %d does not exist." % i ) r = self . arguments [ i ] # pylint : disable = unsubscriptable - object l . debug ( "returning argument" ) return ...
def saveAsLibSVMFile ( data , dir ) : """Save labeled data in LIBSVM format . : param data : an RDD of LabeledPoint to be saved : param dir : directory to save the data > > > from tempfile import NamedTemporaryFile > > > from fileinput import input > > > from pyspark . mllib . regression import LabeledPoi...
lines = data . map ( lambda p : MLUtils . _convert_labeled_point_to_libsvm ( p ) ) lines . saveAsTextFile ( dir )
def isentropic_T_rise_compression ( T1 , P1 , P2 , k , eta = 1 ) : r'''Calculates the increase in temperature of a fluid which is compressed or expanded under isentropic , adiabatic conditions assuming constant Cp and Cv . The polytropic model is the same equation ; just provide ` n ` instead of ` k ` and use...
dT = T1 * ( ( P2 / P1 ) ** ( ( k - 1.0 ) / k ) - 1.0 ) / eta return T1 + dT
def get_monotone_constraints ( self ) : """Get the monotone constraints of the Dataset . Returns monotone _ constraints : numpy array or None Monotone constraints : - 1 , 0 or 1 , for each feature in the Dataset ."""
if self . monotone_constraints is None : self . monotone_constraints = self . get_field ( 'monotone_constraints' ) return self . monotone_constraints
def next_version ( self , object , relations_as_of = 'end' ) : """Return the next version of the given object . In case there is no next object existing , meaning the given object is the current version , the function returns this version . Note that if object ' s version _ end _ date is None , this does not ...
if object . version_end_date is None : next = object else : next = self . filter ( Q ( identity = object . identity ) , Q ( version_start_date__gte = object . version_end_date ) ) . order_by ( 'version_start_date' ) . first ( ) if not next : raise ObjectDoesNotExist ( "next_version couldn't find a n...
async def postprocess_websocket ( self , response : Optional [ Response ] , websocket_context : Optional [ WebsocketContext ] = None , ) -> Response : """Postprocess the websocket acting on the response . Arguments : response : The response after the websocket is finalized . webcoket _ context : The websocket...
websocket_ = ( websocket_context or _websocket_ctx_stack . top ) . websocket functions = ( websocket_context or _websocket_ctx_stack . top ) . _after_websocket_functions blueprint = websocket_ . blueprint if blueprint is not None : functions = chain ( functions , self . after_websocket_funcs [ blueprint ] ) functio...
def db_to_dict ( db ) : """Returns the : class : ` dict ` representation of a database object . The returned : class : ` dict ` is meant to be consumed by : class : ` ~ bang . deployers . cloud . ServerDeployer ` objects ."""
return { A . database . HOST : db . hostname , A . database . PORT : db . port , }
def get_tag ( self , tag_id ) : """Get a single tag represented by ` tag _ id ` . The requested tag must belong to the current user . : param tag _ id : ID fo the tag to retrieve ."""
url = self . _generate_url ( 'tags/{0}' . format ( tag_id ) ) return self . get ( url )
def add_license ( key , description , safety_checks = True , service_instance = None ) : '''Adds a license to the vCenter or ESXi host key License key . description License description added in as a label . safety _ checks Specify whether to perform safety check or to skip the checks and try performin...
log . trace ( 'Adding license \'%s\'' , key ) salt . utils . vmware . add_license ( service_instance , key , description ) return True
def run_command ( command , input_data = None , out_pipe = subprocess . PIPE , err_pipe = subprocess . PIPE , env = None , ** kwargs ) : """Runs a command non - interactively Args : command ( list of str ) : args of the command to execute , including the command itself as command [ 0 ] as ` [ ' ls ' , ' - l '...
if env is None : env = os . environ . copy ( ) with LogTask ( 'Run command: %s' % ' ' . join ( '"%s"' % arg for arg in command ) , logger = LOGGER , level = 'debug' , ) as task : command_result = _run_command ( command = command , input_data = input_data , out_pipe = out_pipe , err_pipe = err_pipe , env = env ,...
def __datetime_to_epoch ( self , date_time ) : """Converts a python datetime to unix epoch , accounting for time zones and such . Assumes UTC if timezone is not given ."""
date_time_utc = None if date_time . tzinfo is None : date_time_utc = date_time . replace ( tzinfo = pytz . utc ) else : date_time_utc = date_time . astimezone ( pytz . utc ) epoch_utc = datetime . datetime . utcfromtimestamp ( 0 ) . replace ( tzinfo = pytz . utc ) return ( date_time_utc - epoch_utc ) . total_se...
def validate_driver ( f ) : """Check driver on"""
def check_driver ( request ) : drivers = get_all_driver ( ) drivers = filter ( drivers , request ) if drivers : return f ( request , drivers ) else : raise Exception ( 'Driver is not found' ) return check_driver
def gifs_categories_category_get ( self , api_key , category , ** kwargs ) : """Category Tags Endpoint . Returns a list of tags for a given category . NOTE ` limit ` and ` offset ` must both be set ; otherwise they ' re ignored . This method makes a synchronous HTTP request by default . To make an asynchronou...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . gifs_categories_category_get_with_http_info ( api_key , category , ** kwargs ) else : ( data ) = self . gifs_categories_category_get_with_http_info ( api_key , category , ** kwargs ) return data
def import_oracle ( self ) : """Return an import oracle that can help look up and categorize imports . : rtype : : class : ` ImportOracle `"""
return ImportOracle ( go_dist = self . go_dist , workunit_factory = self . context . new_workunit )
def scan_upto ( self , regex ) : """Scan up to , but not including , the given regex . > > > s = Scanner ( " test string " ) > > > s . scan ( ' t ' ) > > > s . scan _ upto ( r ' ' ) ' est ' > > > s . pos > > > s . pos _ history [0 , 1 , 4]"""
pos = self . pos if self . scan_until ( regex ) is not None : self . pos -= len ( self . matched ( ) ) # Remove the intermediate position history entry . self . pos_history . pop ( - 2 ) return self . pre_match ( ) [ pos : ]
def _build_query ( self , table , tree , visitor ) : """Build a scan / query from a statement"""
kwargs = { } index = None if tree . using : index_name = kwargs [ "index" ] = tree . using [ 1 ] index = table . get_index ( index_name ) if tree . where : constraints = ConstraintExpression . from_where ( tree . where ) possible_hash = constraints . possible_hash_fields ( ) possible_range = constra...
def renameElement ( self , oldname , newname , info ) : """Called back after a user chose a new name for an element ."""
log . debug ( "Renaming %s into %s in %s" % ( oldname , newname , self . current_filename ) ) start , end = info try : t = self . doc . binding [ start ] except : self . mainwin . showStatus ( "Unexpected error in renameElement" ) return # Determine type of the to - be - renamed element and Androguard inter...
def get_gc_property ( value , is_bytes = False ) : """Get ` GC ` property ."""
obj = unidata . ascii_properties if is_bytes else unidata . unicode_properties if value . startswith ( '^' ) : negate = True value = value [ 1 : ] else : negate = False value = unidata . unicode_alias [ 'generalcategory' ] . get ( value , value ) assert 1 <= len ( value ) <= 2 , 'Invalid property!' if not n...
def get_tag_cloud ( context , steps = 6 , min_count = None , template = 'zinnia/tags/tag_cloud.html' ) : """Return a cloud of published tags ."""
tags = Tag . objects . usage_for_queryset ( Entry . published . all ( ) , counts = True , min_count = min_count ) return { 'template' : template , 'tags' : calculate_cloud ( tags , steps ) , 'context_tag' : context . get ( 'tag' ) }
def flatten ( items ) : """Yield items from any nested iterable . > > > list ( flatten ( [ [ 1 , 2 , 3 ] , [ [ 4 , 5 ] , 6 , 7 ] ] ) ) [1 , 2 , 3 , 4 , 5 , 6 , 7]"""
for x in items : if isinstance ( x , Iterable ) and not isinstance ( x , ( str , bytes ) ) : for sub_x in flatten ( x ) : yield sub_x else : yield x
def is_storage ( url , storage = None ) : """Check if file is a local file or a storage file . File is considered local if : - URL is a local path . - URL starts by " file : / / " - a " storage " is provided . Args : url ( str ) : file path or URL storage ( str ) : Storage name . Returns : bool : ...
if storage : return True split_url = url . split ( '://' , 1 ) if len ( split_url ) == 2 and split_url [ 0 ] . lower ( ) != 'file' : return True return False
def on_pick_button_pressed ( cls , ev ) : """Callback called when the user press the button for accepting the picked author . This element calls validations , before accepting the choice ."""
cls . hide_errors ( ) selected_code = cls . _pick_selected_option ( ) if not selected_code : cls . select_el . style . border = "2px solid red" return cls . selected_code = selected_code cls . code = str ( selected_code ) cls . original_author_el . value = cls . code_to_data [ selected_code ] . get ( "alt_name"...
def close_websockets ( self ) : """Close websocket connection to remote browser ."""
self . log . info ( "Websocket Teardown called" ) for key in list ( self . soclist . keys ( ) ) : if self . soclist [ key ] : self . soclist [ key ] . close ( ) self . soclist . pop ( key )
def _suitableVerbExpansion ( foundSubcatChain ) : '''V6tab etteantud jadast osa , mis sobib : * ) kui liikmeid on 3 , keskmine on konjuktsioon ning esimene ja viimane klapivad , tagastab selle kolmiku ; Nt . ei _ 0 saa _ 0 lihtsalt välja astuda _ ? ja _ ? uttu tõmmata _ ? = > astuda ja tõmmata * ) kui ...
markings = [ ] tokens = [ ] nonConjTokens = [ ] for ( marking , token ) in foundSubcatChain : markings . append ( marking ) tokens . append ( token ) if marking != '&' : nonConjTokens . append ( token ) if ( len ( markings ) == 3 and markings [ 0 ] == markings [ 2 ] and markings [ 0 ] != '&' and mar...
def list_recent_networks ( self ) -> List [ Network ] : """List the most recently created version of each network ( by name ) ."""
most_recent_times = ( self . session . query ( Network . name . label ( 'network_name' ) , func . max ( Network . created ) . label ( 'max_created' ) ) . group_by ( Network . name ) . subquery ( 'most_recent_times' ) ) and_condition = and_ ( most_recent_times . c . network_name == Network . name , most_recent_times . c...
def to_text ( self , origin = None , relativize = True , ** kw ) : """Convert the message to text . The I { origin } , I { relativize } , and any other keyword arguments are passed to the rrset to _ wire ( ) method . @ rtype : string"""
s = cStringIO . StringIO ( ) print >> s , 'id %d' % self . id print >> s , 'opcode %s' % dns . opcode . to_text ( dns . opcode . from_flags ( self . flags ) ) rc = dns . rcode . from_flags ( self . flags , self . ednsflags ) print >> s , 'rcode %s' % dns . rcode . to_text ( rc ) print >> s , 'flags %s' % dns . flags . ...
def get_orbits ( official = '%' ) : """Query the orbit table for the object whose official desingation matches parameter official . By default all entries are returned"""
sql = "SELECT * FROM orbits WHERE official LIKE '%s' " % ( official , ) cfeps . execute ( sql ) return mk_dict ( cfeps . fetchall ( ) , cfeps . description )