signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _RunScripts ( self , run_dir = None ) : """Retrieve metadata scripts and execute them . Args : run _ dir : string , the base directory location of the temporary directory ."""
with _CreateTempDir ( self . script_type , run_dir = run_dir ) as dest_dir : try : self . logger . info ( 'Starting %s scripts.' , self . script_type ) script_dict = self . retriever . GetScripts ( dest_dir ) self . executor . RunScripts ( script_dict ) finally : self . logger . ...
def add_field_processors ( config , processors , model , field ) : """Add processors for model field . Under the hood , regular nefertari event subscribed is created which calls field processors in order passed to this function . Processors are passed following params : * * * new _ value * * : New value of ...
before_change_events = ( BeforeCreate , BeforeUpdate , BeforeReplace , BeforeUpdateMany , BeforeRegister , ) def wrapper ( event , _processors = processors , _field = field ) : proc_kw = { 'new_value' : event . field . new_value , 'instance' : event . instance , 'field' : event . field , 'request' : event . view . ...
def FromString ( cls , desc ) : """Create a new stimulus from a description string . The string must have the format : [ time : ] [ system ] input X = Y where X and Y are integers . The time , if given must be a time _ interval , which is an integer followed by a time unit such as second ( s ) , minute ( ...
if language . stream is None : language . get_language ( ) parse_exp = Optional ( time_interval ( 'time' ) - Literal ( ':' ) . suppress ( ) ) - language . stream ( 'stream' ) - Literal ( '=' ) . suppress ( ) - number ( 'value' ) try : data = parse_exp . parseString ( desc ) time = 0 if 'time' in data : ...
def __live_receivers ( signal ) : """Return all signal handlers that are currently still alive for the input ` signal ` . Args : signal : A signal name . Returns : A list of callable receivers for the input signal ."""
with __lock : __purge ( ) receivers = [ funcref ( ) for funcref in __receivers [ signal ] ] return receivers
def clear ( self ) : """Clear all waiters . This method will remove any current scheduled waiter with an asyncio . CancelledError exception ."""
for _ , waiter in self . waiters ( ) : if isinstance ( waiter , asyncio . Future ) and not waiter . done ( ) : waiter . set_exception ( asyncio . CancelledError ( ) ) self . _waiters = { }
def normalizeRotationAngle ( value ) : """Normalizes an angle . * Value must be a : ref : ` type - int - float ` . * Value must be between - 360 and 360. * If the value is negative , it is normalized by adding it to 360 * Returned value is a ` ` float ` ` between 0 and 360."""
if not isinstance ( value , ( int , float ) ) : raise TypeError ( "Angle must be instances of " ":ref:`type-int-float`, not %s." % type ( value ) . __name__ ) if abs ( value ) > 360 : raise ValueError ( "Angle must be between -360 and 360." ) if value < 0 : value = value + 360 return float ( value )
def _normalize_string ( self , text ) : '''Prepares incoming text for parsing : removes excessive spaces , tabs , newlines , etc .'''
conversion = { # newlines '\r?\n' : ' ' , # replace excessive empty spaces '\s+' : ' ' , # convert all types of hyphens / dashes to a # simple old - school dash # from http : / / utf8 - chartable . de / unicode - utf8 - table . pl ? # start = 8192 & number = 128 & utf8 = string - literal '‐' : '-' , '‑' : '-' , '‒' : '...
def setSeed ( self , value ) : """Sets the seed to value ."""
self . seed = value random . seed ( self . seed ) if self . verbosity >= 0 : print ( "Conx using seed:" , self . seed )
def simple_ins_from_obs ( obsnames , insfilename = 'model.output.ins' ) : """writes an instruction file that assumes wanting to read the values names in obsnames in order one per line from a model output file Args : obsnames : list of obsnames to read in insfilename : filename for INS file ( default : model...
with open ( insfilename , 'w' ) as ofp : ofp . write ( 'pif ~\n' ) [ ofp . write ( '!{0}!\n' . format ( cob ) ) for cob in obsnames ]
def ReadCronJobRuns ( self , job_id , cursor = None ) : """Reads all cron job runs for a given job id ."""
query = """ SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs WHERE job_id = %s """ cursor . execute ( query , [ job_id ] ) runs = [ self . _CronJobRunFromRow ( row ) for row in cursor . fetchall ( ) ] return sorted ( runs , key = lambda run : run . started_at , reverse = True )
def daemonize ( enable_stdio_inheritance = False , auto_close_fds = True , keep_fds = None ) : # pragma nocover """Standard daemonization of a process . http : / / www . svbug . com / documentation / comp . unix . programmer - FAQ / faq _ 2 . html # SEC16"""
if os . fork ( ) : os . _exit ( 0 ) os . setsid ( ) if os . fork ( ) : os . _exit ( 0 ) os . umask ( 0o22 ) # In both the following any file descriptors above stdin # stdout and stderr are left untouched . The inheritence # option simply allows one to have output go to a file # specified by way of shell redirec...
def repmi ( instr , marker , value , lenout = None ) : """Replace a marker with an integer . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / repmi _ c . html : param instr : Input string . : type instr : str : param marker : Marker to be replaced . : type marker : str : p...
if lenout is None : lenout = ctypes . c_int ( len ( instr ) + len ( marker ) + 15 ) instr = stypes . stringToCharP ( instr ) marker = stypes . stringToCharP ( marker ) value = ctypes . c_int ( value ) out = stypes . stringToCharP ( lenout ) libspice . repmi_c ( instr , marker , value , lenout , out ) return stypes ...
def validate_response ( response , validator_map ) : """Validates response against our schemas . : param response : the response object to validate : type response : : class : ` pyramid . response . Response ` : type validator _ map : : class : ` pyramid _ swagger . load _ schema . ValidatorMap `"""
validator = validator_map . response # Short circuit if we are supposed to not validate anything . returns_nothing = validator . schema . get ( 'type' ) == 'void' body_empty = response . body in ( None , b'' , b'{}' , b'null' ) if returns_nothing and body_empty : return # Don ' t attempt to validate non - success r...
def addFeatureSA ( self , callback , default = None , name = None ) : """Add a feature to the suffix array . The callback must return a sequence such that the feature at position i is attached to the suffix referenced by self . SA [ i ] . It is called with one argument : the instance of SuffixArray self . ...
if name is None : featureName = callback . __name__ else : featureName = name featureValues = callback ( self ) setattr ( self , "_%s_values" % featureName , featureValues ) setattr ( self , "%s_default" % featureName , default ) self . features . append ( featureName ) def findFeature ( substring ) : res =...
def process ( self , state , procedure , ret_to = None , inline = None , force_addr = None , ** kwargs ) : """Perform execution with a state . : param state : The state with which to execute : param procedure : An instance of a SimProcedure to run : param ret _ to : The address to return to when this procedur...
return super ( SimEngineProcedure , self ) . process ( state , procedure , ret_to = ret_to , inline = inline , force_addr = force_addr )
def highlight_multi_regex ( str_ , pat_to_color , reflags = 0 ) : """FIXME Use pygments instead . must be mututally exclusive"""
# import colorama # from colorama import Fore , Style # color = Fore . MAGENTA # color = Fore . RED # match = re . search ( pat , str _ , flags = reflags ) colored = str_ to_replace = [ ] for pat , color in pat_to_color . items ( ) : matches = list ( re . finditer ( pat , str_ , flags = reflags ) ) for match in...
def uncertainty_K ( self ) : """Estimate of the element - wise asymptotic standard deviation in the rate matrix"""
if self . information_ is None : self . _build_information ( ) sigma_K = _ratematrix . sigma_K ( self . information_ , theta = self . theta_ , n = self . n_states_ ) return sigma_K
def inferSuperimposedSequenceObjects ( exp , sequenceId , objectId , sequences , objects ) : """Run inference on the given sequence ."""
# Create the ( loc , feat ) pairs for this sequence for column 0. objectSensations = { 0 : [ pair for pair in sequences [ sequenceId ] ] } inferConfig = { "object" : sequenceId , "numSteps" : len ( objectSensations [ 0 ] ) , "pairs" : objectSensations , } inferenceSDRSequence = sequences . provideObjectToInfer ( inferC...
def color_array_by_hue_mix ( value , palette ) : """Figure out the appropriate color for a binary string value by averaging the colors corresponding the indices of each one that it contains . Makes for visualizations that intuitively show patch overlap ."""
if int ( value , 2 ) > 0 : # Convert bits to list and reverse order to avoid issues with # differing lengths int_list = [ int ( i ) for i in list ( value [ 2 : ] ) ] int_list . reverse ( ) # since this is a 1D array , we need the zeroth elements # of np . nonzero . locs = np . nonzero ( int_list ) [...
def sync_remotes ( self , force = False ) : """Pull down all non - local items and save them into remotes _ storage ."""
connectors = juicer . utils . get_login_info ( ) [ 0 ] for repo , items in self . iterrepos ( ) : repoid = "%s-%s" % ( repo , self . current_env ) for rpm in items : # don ' t bother syncing down if it ' s already in the pulp repo it needs to go to if not rpm . path . startswith ( juicer . utils . pulp_...
def create ( project : 'projects.Project' ) -> COMPONENT : """: return :"""
try : from bokeh . resources import Resources as BokehResources bokeh_resources = BokehResources ( mode = 'absolute' ) except Exception : bokeh_resources = None if bokeh_resources is None : environ . log ( BOKEH_WARNING ) return COMPONENT ( [ ] , [ ] ) return definitions . merge_components ( _assemb...
def has_pending ( self ) : """Return True if there are pending test items This indicates that collection has finished and nodes are still processing test items , so this can be thought of as " the scheduler is active " ."""
if self . pending : return True for pending in self . node2pending . values ( ) : if pending : return True return False
def manifest ( self , subvol ) : """Generator for manifest , yields 7 - tuples"""
subvol_path = os . path . join ( self . path , str ( subvol ) ) builtin_path = os . path . join ( subvol_path , MANIFEST_DIR [ 1 : ] , str ( subvol ) ) manifest_path = os . path . join ( MANIFEST_DIR , str ( subvol ) ) if os . path . exists ( builtin_path ) : # Stream the manifest written into the ( read - only ) templ...
def plasma_get ( object_id ) : """Get an object directly from plasma without going through object table . Precondition : plasma _ prefetch ( object _ id ) has been called before ."""
client = ray . worker . global_worker . plasma_client plasma_id = ray . pyarrow . plasma . ObjectID ( object_id ) while not client . contains ( plasma_id ) : pass return client . get ( plasma_id )
def _import_marshaller_modules ( self , m ) : """Imports the modules required by the marshaller . Parameters m : marshaller The marshaller to load the modules for . Returns success : bool Whether the modules ` m ` requires could be imported successfully or not ."""
try : for name in m . required_modules : if name not in sys . modules : if _has_importlib : importlib . import_module ( name ) else : __import__ ( name ) except ImportError : return False except : raise else : return True
def _parse_memory_embedded_health ( self , data ) : """Parse the get _ host _ health _ data ( ) for essential properties : param data : the output returned by get _ host _ health _ data ( ) : returns : memory size in MB . : raises IloError , if unable to get the memory details ."""
memory_mb = 0 memory = self . _get_memory_details_value_based_on_model ( data ) if memory is None : msg = "Unable to get memory data. Error: Data missing" raise exception . IloError ( msg ) total_memory_size = 0 for memory_item in memory : memsize = memory_item [ self . MEMORY_SIZE_TAG ] [ "VALUE" ] if ...
def get_project_content_commit_date ( root_dir = '.' , exclusions = None ) : """Get the datetime for the most recent commit to a project that affected Sphinx content . * Content * is considered any file with one of these extensions : - ` ` rst ` ` ( README . rst and LICENSE . rst are excluded ) - ` ` ipynb ...
logger = logging . getLogger ( __name__ ) # Supported ' content ' extensions extensions = ( 'rst' , 'ipynb' , 'png' , 'jpeg' , 'jpg' , 'svg' , 'gif' ) content_paths = [ ] for extname in extensions : content_paths += get_filepaths_with_extension ( extname , root_dir = root_dir ) # Known files that should be excluded...
def _zeropad ( sig , N , axis = 0 ) : """pads with N zeros at the end of the signal , along given axis"""
# ensures concatenation dimension is the first sig = np . moveaxis ( sig , axis , 0 ) # zero pad out = np . zeros ( ( sig . shape [ 0 ] + N , ) + sig . shape [ 1 : ] ) out [ : sig . shape [ 0 ] , ... ] = sig # put back axis in place out = np . moveaxis ( out , 0 , axis ) return out
def remove_trailing_spaces ( self , index = None ) : """Remove trailing spaces"""
if index is None : index = self . get_stack_index ( ) finfo = self . data [ index ] finfo . editor . remove_trailing_spaces ( )
def get_callback_url ( self , ** kwargs ) : """Returns a relative URL for invoking this Pipeline ' s callback method . Args : kwargs : Dictionary mapping keyword argument names to single values that should be passed to the callback when it is invoked . Raises : UnexpectedPipelineError if this is invoked o...
# TODO : Support positional parameters . if not self . async : raise UnexpectedPipelineError ( 'May only call get_callback_url() method for asynchronous pipelines.' ) kwargs [ 'pipeline_id' ] = self . _pipeline_key . name ( ) params = urllib . urlencode ( sorted ( kwargs . items ( ) ) ) return '%s/callback?%s' % ( ...
def _future_done ( self , future ) : """Will be called when the coroutine is done"""
try : # notify the subscribers ( except result is an exception or NONE ) result = future . result ( ) # may raise exception if result is not NONE : self . notify ( result ) # may also raise exception except asyncio . CancelledError : return except Exception : # pylint : disable = broad -...
def _default_plugins ( self ) : """Get entry points to load any plugins installed . The build process should create an " entry _ points . json " file with all of the data from the installed entry points ."""
plugins = { } try : with open ( 'entry_points.json' ) as f : entry_points = json . load ( f ) for ep , obj in entry_points . items ( ) : plugins [ ep ] = [ ] for name , src in obj . items ( ) : plugins [ ep ] . append ( Plugin ( name = name , source = src ) ) except Exception...
def translate_cds ( seq , full_codons = True , ter_symbol = "*" ) : """translate a DNA or RNA sequence into a single - letter amino acid sequence using the standard translation table If full _ codons is True , a sequence whose length isn ' t a multiple of three generates a ValueError ; else an ' X ' will be a...
if seq is None : return None if len ( seq ) == 0 : return "" if full_codons and len ( seq ) % 3 != 0 : raise ValueError ( "Sequence length must be a multiple of three" ) seq = replace_u_to_t ( seq ) seq = seq . upper ( ) protein_seq = list ( ) for i in range ( 0 , len ( seq ) - len ( seq ) % 3 , 3 ) : t...
def update_tracking_terms ( self ) : """Terms must be one - per - line . Blank lines will be skipped ."""
import codecs with codecs . open ( self . filename , "r" , encoding = 'utf8' ) as input : # read all the lines lines = input . readlines ( ) # build a set of terms new_terms = set ( ) for line in lines : line = line . strip ( ) if len ( line ) : new_terms . add ( line ) r...
def is_empty ( self ) : """Returns True if the root node contains no child elements , no text , and no attributes other than * * type * * . Returns False if any are present ."""
non_type_attributes = [ attr for attr in self . node . attrib . keys ( ) if attr != 'type' ] return len ( self . node ) == 0 and len ( non_type_attributes ) == 0 and not self . node . text and not self . node . tail
def render ( self , template_name : str , ** kwargs : Any ) -> "Future[None]" : """Renders the template with the given arguments as the response . ` ` render ( ) ` ` calls ` ` finish ( ) ` ` , so no other output methods can be called after it . Returns a ` . Future ` with the same semantics as the one returne...
if self . _finished : raise RuntimeError ( "Cannot render() after finish()" ) html = self . render_string ( template_name , ** kwargs ) # Insert the additional JS and CSS added by the modules on the page js_embed = [ ] js_files = [ ] css_embed = [ ] css_files = [ ] html_heads = [ ] html_bodies = [ ] for module in g...
def set_value ( self , name , value , PY2_frontend ) : """Set the value of a variable"""
import cloudpickle ns = self . _get_reference_namespace ( name ) # We send serialized values in a list of one element # from Spyder to the kernel , to be able to send them # at all in Python 2 svalue = value [ 0 ] # We need to convert svalue to bytes if the frontend # runs in Python 2 and the kernel runs in Python 3 if...
def str_to_datetime ( ts ) : """Format a string to a datetime object . This functions supports several date formats like YYYY - MM - DD , MM - DD - YYYY and YY - MM - DD . When the given data is None or an empty string , the function returns None . : param ts : string to convert : returns : a datetime obj...
if not ts : return None try : return dateutil . parser . parse ( ts ) . replace ( tzinfo = None ) except Exception : raise InvalidDateError ( date = str ( ts ) )
async def make_transition_register ( self , request : 'Request' ) : """Use all underlying stacks to generate the next transition register ."""
register = { } for stack in self . _stacks : register = await stack . patch_register ( register , request ) return register
def capture_events ( receiver , dest ) : """Capture all events sent to ` receiver ` in the sequence ` dest ` . This is a generator , and it is best used with ` ` yield from ` ` . The observable effect of using this generator with ` ` yield from ` ` is identical to the effect of using ` receiver ` with ` ` yie...
# the following code is a copy of the formal definition of ` yield from ` # in PEP 380 , with modifications to capture the value sent during yield _i = iter ( receiver ) try : _y = next ( _i ) except StopIteration as _e : return _e . value try : while True : try : _s = yield _y e...
def list_unique ( cls ) : '''Return all unique namespaces : returns : a list of all predicates : rtype : list of ckan . model . semantictag . Predicate objects'''
query = meta . Session . query ( Predicate ) . distinct ( Predicate . namespace ) return query . all ( )
def draw_geoscale ( ax , minx = 0 , maxx = 175 ) : """Draw geological epoch on million year ago ( mya ) scale ."""
a , b = .1 , .6 # Correspond to 200mya and 0mya def cv ( x ) : return b - ( x - b ) / ( maxx - minx ) * ( b - a ) ax . plot ( ( a , b ) , ( .5 , .5 ) , "k-" ) tick = .015 for mya in xrange ( maxx - 25 , 0 , - 25 ) : p = cv ( mya ) ax . plot ( ( p , p ) , ( .5 , .5 - tick ) , "k-" ) ax . text ( p , .5 - ...
def search ( signal = '' , action = '' , signals = SIGNALS ) : """Search the signals DB for signal named * signal * , and which action matches * action * in a case insensitive way . : param signal : Regex for signal name . : param action : Regex for default action . : param signals : Database of signals ....
sig_re = re . compile ( signal , re . IGNORECASE ) act_re = re . compile ( action , re . IGNORECASE ) res = [ ] for code in signals : sig , act , _ = signals [ code ] if sig_re . match ( sig ) and act_re . match ( act ) : res . append ( explain ( code , signals = signals ) ) return res
def add_task_file_manager ( self , task_file_manager ) : """Add a task file manager . Only available after that the Plugin Manager is loaded"""
if not self . _loaded : raise PluginManagerNotLoadedException ( ) self . _task_factory . add_custom_task_file_manager ( task_file_manager )
def _GetSocket ( self ) : """Establishes a connection to an nsrlsvr instance . Returns : socket . _ socketobject : socket connected to an nsrlsvr instance or None if a connection cannot be established ."""
try : return socket . create_connection ( ( self . _host , self . _port ) , self . _SOCKET_TIMEOUT ) except socket . error as exception : logger . error ( 'Unable to connect to nsrlsvr with error: {0!s}.' . format ( exception ) )
def plot ( self , resolution_constant_regions = 20 , resolution_smooth_regions = 200 ) : """Return arrays x , y for plotting the piecewise constant function . Just the minimum number of straight lines are returned if ` ` eps = 0 ` ` , otherwise ` resolution _ constant _ regions ` plotting intervals are insed ...
if self . eps == 0 : x = [ ] ; y = [ ] for I , value in zip ( self . _indicator_functions , self . _values ) : x . append ( I . L ) y . append ( value ) x . append ( I . R ) y . append ( value ) return x , y else : n = float ( resolution_smooth_regions ) / self . eps ...
def parsed ( self ) : """Get the code object which represents the compiled Python file . This property is cached and only parses the content once ."""
if not self . _parsed : self . _parsed = compile ( self . content , self . path , 'exec' ) return self . _parsed
def run ( commands , shell = None , prompt_template = "default" , speed = 1 , quiet = False , test_mode = False , commentecho = False , ) : """Main function for " magic - running " a list of commands ."""
if not quiet : secho ( "We'll do it live!" , fg = "red" , bold = True ) secho ( "STARTING SESSION: Press Ctrl-C at any time to exit." , fg = "yellow" , bold = True , ) click . pause ( ) click . clear ( ) state = SessionState ( shell = shell , prompt_template = prompt_template , speed = speed , test_mode = t...
def support_autoupload_param_hostip ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) support = ET . SubElement ( config , "support" , xmlns = "urn:brocade.com:mgmt:brocade-ras" ) autoupload_param = ET . SubElement ( support , "autoupload-param" ) hostip = ET . SubElement ( autoupload_param , "hostip" ) hostip . text = kwargs . pop ( 'hostip' ) callback = kwargs . pop ...
def streamReachAndWatershed ( self , delineate , out_stream_order_grid , out_network_connectivity_tree , out_network_coordinates , out_stream_reach_file , out_watershed_grid , pit_filled_elevation_grid = None , flow_dir_grid = None , contributing_area_grid = None , stream_raster_grid = None , outlet_shapefile = None ) ...
log ( "PROCESS: StreamReachAndWatershed" ) if pit_filled_elevation_grid : self . pit_filled_elevation_grid = pit_filled_elevation_grid if flow_dir_grid : self . flow_dir_grid = flow_dir_grid if contributing_area_grid : self . contributing_area_grid = contributing_area_grid if stream_raster_grid : self ....
def as_ipywidget ( self ) : """Provides an IPywidgets player that can be used in a notebook ."""
from IPython . display import Audio return Audio ( data = self . y , rate = self . sr )
def kill ( self , dwExitCode = 0 ) : """Terminates the thread execution . @ note : If the C { lpInjectedMemory } member contains a valid pointer , the memory is freed . @ type dwExitCode : int @ param dwExitCode : ( Optional ) Thread exit code ."""
hThread = self . get_handle ( win32 . THREAD_TERMINATE ) win32 . TerminateThread ( hThread , dwExitCode ) # Ugliest hack ever , won ' t work if many pieces of code are injected . # Seriously , what was I thinking ? Lame ! : ( if self . pInjectedMemory is not None : try : self . get_process ( ) . free ( self...
def current_boost_dir ( ) : """Returns the ( relative ) path to the Boost source - directory this file is located in ( if any ) ."""
# Path to directory containing this script . path = os . path . dirname ( os . path . realpath ( __file__ ) ) # Making sure it is located in " $ { boost - dir } / libs / mpl / preprocessed " . for directory in reversed ( [ "libs" , "mpl" , "preprocessed" ] ) : ( head , tail ) = os . path . split ( path ) if tai...
def set_phases ( self , literals = [ ] ) : """Sets polarities of a given list of variables ."""
if self . minisat : pysolvers . minisat22_setphases ( self . minisat , literals )
def stack ( self , level = - 1 , dropna = True ) : """Stack the prescribed level ( s ) from columns to index . Return a reshaped DataFrame or Series having a multi - level index with one or more new inner - most levels compared to the current DataFrame . The new inner - most levels are created by pivoting the...
from pandas . core . reshape . reshape import stack , stack_multiple if isinstance ( level , ( tuple , list ) ) : return stack_multiple ( self , level , dropna = dropna ) else : return stack ( self , level , dropna = dropna )
def pull ( name , version , force = False ) : """Pull a released IOTile component into the current working directory The component is found using whatever DependencyResolvers are installed and registered as part of the default DependencyResolverChain . This is the same mechanism used in iotile depends update ...
chain = DependencyResolverChain ( ) ver = SemanticVersionRange . FromString ( version ) chain . pull_release ( name , ver , force = force )
def hold ( name = None , pkgs = None , sources = None , normalize = True , ** kwargs ) : # pylint : disable = W0613 '''. . versionadded : : 2014.7.0 Version - lock packages . . note : : Requires the appropriate ` ` versionlock ` ` plugin package to be installed : - On RHEL 5 : ` ` yum - versionlock ` ` - ...
_check_versionlock ( ) if not name and not pkgs and not sources : raise SaltInvocationError ( 'One of name, pkgs, or sources must be specified.' ) if pkgs and sources : raise SaltInvocationError ( 'Only one of pkgs or sources can be specified.' ) targets = [ ] if pkgs : targets . extend ( pkgs ) elif source...
def populate_metadata ( model , MetadataClass ) : """For a given model and metadata class , ensure there is metadata for every instance ."""
content_type = ContentType . objects . get_for_model ( model ) for instance in model . objects . all ( ) : create_metadata_instance ( MetadataClass , instance )
def update_leads_list ( self , leads_list_id , name , team_id = None ) : """Update a leads list . : param name : Name of the list to update . Must be defined . : param team _ id : The id of the list to share this list with . : return : 204 Response ."""
params = self . base_params payload = { 'name' : name } if team_id : payload [ 'team_id' ] = team_id endpoint = self . base_endpoint . format ( 'leads_lists/' + str ( leads_list_id ) ) return self . _query_hunter ( endpoint , params , 'put' , payload )
def getpcmd ( pid ) : """Returns command of process . : param pid :"""
if os . name == "nt" : # Use wmic command instead of ps on Windows . cmd = 'wmic path win32_process where ProcessID=%s get Commandline 2> nul' % ( pid , ) with os . popen ( cmd , 'r' ) as p : lines = [ line for line in p . readlines ( ) if line . strip ( "\r\n " ) != "" ] if lines : ...
def delete_index ( self , cardinality ) : """Delete index for the table with the given cardinality . Parameters cardinality : int The cardinality of the index to delete ."""
DatabaseConnector . delete_index ( self , cardinality ) query = "DROP INDEX IF EXISTS idx_{0}_gram_varchar;" . format ( cardinality ) self . execute_sql ( query ) query = "DROP INDEX IF EXISTS idx_{0}_gram_normalized_varchar;" . format ( cardinality ) self . execute_sql ( query ) query = "DROP INDEX IF EXISTS idx_{0}_g...
def _handleInvertAxesSelected ( self , evt ) : """Called when the invert all menu item is selected"""
if len ( self . _axisId ) == 0 : return for i in range ( len ( self . _axisId ) ) : if self . _menu . IsChecked ( self . _axisId [ i ] ) : self . _menu . Check ( self . _axisId [ i ] , False ) else : self . _menu . Check ( self . _axisId [ i ] , True ) self . _toolbar . set_active ( self . g...
def addSiiToContainer ( siiContainer , specfile , siiList ) : """Adds the ` ` Sii ` ` elements contained in the siiList to the appropriate list in ` ` siiContainer . container [ specfile ] ` ` . : param siiContainer : instance of : class : ` maspy . core . SiiContainer ` : param specfile : unambiguous identif...
for sii in siiList : if sii . id not in siiContainer . container [ specfile ] : siiContainer . container [ specfile ] [ sii . id ] = list ( ) siiContainer . container [ specfile ] [ sii . id ] . append ( sii )
def getFoundIn ( self , foundin_name , projectarea_id = None , projectarea_name = None , archived = False ) : """Get : class : ` rtcclient . models . FoundIn ` object by its name : param foundin _ name : the foundin name : param projectarea _ id : the : class : ` rtcclient . project _ area . ProjectArea ` id ...
self . log . debug ( "Try to get <FoundIn %s>" , foundin_name ) if not isinstance ( foundin_name , six . string_types ) or not foundin_name : excp_msg = "Please specify a valid PlannedFor name" self . log . error ( excp_msg ) raise exception . BadValue ( excp_msg ) foundins = self . _getFoundIns ( projectar...
def deviance_information_criterions ( mean_posterior_lls , ll_per_sample ) : r"""Calculates the Deviance Information Criteria ( DIC ) using three methods . This returns a dictionary returning the ` ` DIC _ 2002 ` ` , the ` ` DIC _ 2004 ` ` and the ` ` DIC _ Ando _ 2011 ` ` method . The first is based on Spiegel...
mean_deviance = - 2 * np . mean ( ll_per_sample , axis = 1 ) deviance_at_mean = - 2 * mean_posterior_lls pd_2002 = mean_deviance - deviance_at_mean pd_2004 = np . var ( ll_per_sample , axis = 1 ) / 2.0 return { 'DIC_2002' : np . nan_to_num ( mean_deviance + pd_2002 ) , 'DIC_2004' : np . nan_to_num ( mean_deviance + pd_...
def launch_browser ( self , soup ) : """Launch a browser to display a page , for debugging purposes . : param : soup : Page contents to display , supplied as a bs4 soup object ."""
with tempfile . NamedTemporaryFile ( delete = False , suffix = '.html' ) as file : file . write ( soup . encode ( ) ) webbrowser . open ( 'file://' + file . name )
def config ( ) : """Loads and returns a ConfigParser from ` ` ~ / . deepdish . conf ` ` ."""
conf = ConfigParser ( ) # Set up defaults conf . add_section ( 'io' ) conf . set ( 'io' , 'compression' , 'zlib' ) conf . read ( os . path . expanduser ( '~/.deepdish.conf' ) ) return conf
def run ( self , * args , ** kwargs ) : """The Node main method , running in a child process ( similar to Process . run ( ) but also accepts args ) A children class can override this method , but it needs to call super ( ) . run ( * args , * * kwargs ) for the node to start properly and call update ( ) as expec...
# TODO : make use of the arguments ? since run is now the target for Process . . . exitstatus = None # keeping the semantic of multiprocessing . Process : running process has None if setproctitle and self . new_title : setproctitle . setproctitle ( "{0}" . format ( self . name ) ) print ( '[{proc}] Proc started as ...
def Start ( self , hostname , port ) : """Starts the process status RPC server . Args : hostname ( str ) : hostname or IP address to connect to for requests . port ( int ) : port to connect to for requests . Returns : bool : True if the RPC server was successfully started ."""
if not self . _Open ( hostname , port ) : return False self . _rpc_thread = threading . Thread ( name = self . _THREAD_NAME , target = self . _xmlrpc_server . serve_forever ) self . _rpc_thread . start ( ) return True
def plugin_privileges ( self , name ) : """Retrieve list of privileges to be granted to a plugin . Args : name ( string ) : Name of the remote plugin to examine . The ` ` : latest ` ` tag is optional , and is the default if omitted . Returns : A list of dictionaries representing the plugin ' s permissio...
params = { 'remote' : name , } headers = { } registry , repo_name = auth . resolve_repository_name ( name ) header = auth . get_config_header ( self , registry ) if header : headers [ 'X-Registry-Auth' ] = header url = self . _url ( '/plugins/privileges' ) return self . _result ( self . _get ( url , params = params...
def get_error ( self , xml ) : '''Obtem do XML de resposta , o código e a descrição do erro . O XML corresponde ao corpo da resposta HTTP de código 500. : param xml : XML contido na resposta da requisição HTTP . : return : Tupla com o código e a descrição do erro contido no XML : ( < codigo _ erro ...
map = loads ( xml ) network_map = map [ 'networkapi' ] error_map = network_map [ 'erro' ] return int ( error_map [ 'codigo' ] ) , str ( error_map [ 'descricao' ] )
def run_cufflinks ( data ) : """Quantitate transcript expression with Cufflinks"""
if "cufflinks" in dd . get_tools_off ( data ) : return [ [ data ] ] work_bam = dd . get_work_bam ( data ) ref_file = dd . get_sam_ref ( data ) out_dir , fpkm_file , fpkm_isoform_file = cufflinks . run ( work_bam , ref_file , data ) data = dd . set_cufflinks_dir ( data , out_dir ) data = dd . set_fpkm ( data , fpkm_...
def xiphias_get_users ( self , peer_jids : Union [ str , List [ str ] ] ) : """Calls the new format xiphias message to request user data such as profile creation date and background picture URL . : param peer _ jids : one jid , or a list of jids"""
return self . _send_xmpp_element ( xiphias . UsersRequest ( peer_jids ) )
def to_dict ( self ) : """Return the user as a dict ."""
public_keys = [ public_key . b64encoded for public_key in self . public_keys ] return dict ( name = self . name , passwd = self . passwd , uid = self . uid , gid = self . gid , gecos = self . gecos , home_dir = self . home_dir , shell = self . shell , public_keys = public_keys )
def create_finance_metrics ( metrics : list , pronacs : list ) : """Creates metrics , creating an Indicator if it doesn ' t already exists Metrics are created for projects that are in pronacs and saved in database . args : metrics : list of names of metrics that will be calculated pronacs : pronacs in dat...
missing = missing_metrics ( metrics , pronacs ) print ( f"There are {len(missing)} missing metrics!" ) processors = mp . cpu_count ( ) print ( f"Using {processors} processors to calculate metrics!" ) indicators_qs = FinancialIndicator . objects . filter ( project_id__in = [ p for p , _ in missing ] ) indicators = { i ....
def _load_package ( self , json_line , installed_packages ) : """Returns the user _ package ( name , version , source ) , and the list of envs registered when the package was loaded"""
if len ( json_line ) == 0 : return { } , set ( [ ] ) valid_json = False try : user_package = json . loads ( json_line ) valid_json = True except ValueError : user_package = { } package_name = user_package [ 'name' ] if 'name' in user_package else None module_name = package_name . replace ( '-' , '_' ) i...
def install_pyenv ( name , user = None ) : '''Install pyenv if not installed . Allows you to require pyenv be installed prior to installing the plugins . Useful if you want to install pyenv plugins via the git or file modules and need them installed before installing any rubies . Use the pyenv . root config...
ret = { 'name' : name , 'result' : None , 'comment' : '' , 'changes' : { } } if __opts__ [ 'test' ] : ret [ 'comment' ] = 'pyenv is set to be installed' return ret return _check_and_install_python ( ret , user )
def _infer_transform_options ( transform ) : """figure out what transform options should be by examining the provided regexes for keywords"""
TransformOptions = collections . namedtuple ( "TransformOptions" , [ 'CB' , 'dual_index' , 'triple_index' , 'MB' , 'SB' ] ) CB = False SB = False MB = False dual_index = False triple_index = False for rx in transform . values ( ) : if not rx : continue if "CB1" in rx : if "CB3" in rx : ...
def deref ( data , spec : dict ) : """Return dereference data : param data : : param spec : : return :"""
if isinstance ( data , Sequence ) : is_dict = False gen = enumerate ( data ) elif not isinstance ( data , Mapping ) : return data elif '$ref' in data : return deref ( get_ref ( spec , data [ '$ref' ] ) , spec ) else : is_dict = True gen = data . items ( ) # type : ignore result = None for k , v ...
def inverse_transform ( self , Y , columns = None ) : """Transform input data ` Y ` to ambient data space defined by ` self . data ` Takes data in the same reduced space as ` self . data _ nu ` and transforms it to be in the same ambient space as ` self . data ` . Parameters Y : array - like , shape = [ n _...
try : if not hasattr ( self , "data_pca" ) : # no pca performed try : if Y . shape [ 1 ] != self . data_nu . shape [ 1 ] : # shape is wrong raise ValueError except IndexError : # len ( Y . shape ) < 2 raise ValueError if columns is None : r...
def _do_code_blocks ( self , text ) : """Process Markdown ` < pre > < code > ` blocks ."""
code_block_re = re . compile ( r''' (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ )...
def build_vf_node ( vf ) : """Convert a VulnerabilityFunction object into a Node suitable for XML conversion ."""
nodes = [ Node ( 'imls' , { 'imt' : vf . imt } , vf . imls ) , Node ( 'meanLRs' , { } , vf . mean_loss_ratios ) , Node ( 'covLRs' , { } , vf . covs ) ] return Node ( 'vulnerabilityFunction' , { 'id' : vf . id , 'dist' : vf . distribution_name } , nodes = nodes )
async def unsubscribe ( self , topic ) : """Unsubscribe the socket from the specified topic . : param topic : The topic to unsubscribe from ."""
if self . socket_type not in { SUB , XSUB } : raise AssertionError ( "A %s socket cannot unsubscribe." % self . socket_type . decode ( ) , ) # Do this * * BEFORE * * awaiting so that new connections created during # the execution below honor the setting . self . _subscriptions . remove ( topic ) tasks = [ asyncio ....
def check_columns ( column , line , columns ) : """Make sure the column is the minimum between the largest column asked for and the max column available in the line ."""
return column <= min ( len ( line ) , max ( columns ) )
def to_feature_importances ( regressor_type , regressor_kwargs , trained_regressor ) : """Motivation : when the out - of - bag improvement heuristic is used , we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used . Th...
if is_oob_heuristic_supported ( regressor_type , regressor_kwargs ) : n_estimators = len ( trained_regressor . estimators_ ) denormalized_importances = trained_regressor . feature_importances_ * n_estimators return denormalized_importances else : return trained_regressor . feature_importances_
def faasport ( func : Faasport ) -> Faasport : """Decorator that registers the user ' s faasport function ."""
global user_faasport if user_faasport is not None : raise RuntimeError ( 'Multiple definitions of faasport.' ) user_faasport = func return func
def pressure_trend_text ( trend ) : """Convert pressure trend to a string , as used by the UK met office ."""
_ = pywws . localisation . translation . ugettext if trend > 6.0 : return _ ( u'rising very rapidly' ) elif trend > 3.5 : return _ ( u'rising quickly' ) elif trend > 1.5 : return _ ( u'rising' ) elif trend >= 0.1 : return _ ( u'rising slowly' ) elif trend < - 6.0 : return _ ( u'falling very rapidly'...
def registerApp ( self , itemId , appType , redirect_uris = None ) : """The register app operation registers an app item with the portal . App registration results in an APPID and APPSECRET ( also known as client _ id and client _ secret ( in OAuth speak respectively ) being generated for that application . U...
url = self . _url + "/registerApp" params = { "f" : "json" , "itemId" : itemId , "appType" : appType } if redirect_uris is None : params [ 'redirect_uris' ] = redirect_uris return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port ...
def apply_dependencies ( self ) : """Creates dependencies links between elements . : return : None"""
self . hosts . apply_dependencies ( ) self . services . apply_dependencies ( self . hosts )
def urlencode ( resource ) : """This implementation of urlencode supports all unicode characters : param : resource : Resource value to be url encoded ."""
if isinstance ( resource , str ) : return _urlencode ( resource . encode ( 'utf-8' ) ) return _urlencode ( resource )
def get_allure_suites ( longname ) : """> > > get _ allure _ suites ( ' Suite1 . Test ' ) [ Label ( name = ' suite ' , value = ' Suite1 ' ) ] > > > get _ allure _ suites ( ' Suite1 . Suite2 . Test ' ) # doctest : + NORMALIZE _ WHITESPACE [ Label ( name = ' suite ' , value = ' Suite1 ' ) , Label ( name = ' sub...
labels = [ ] suites = longname . split ( '.' ) if len ( suites ) > 3 : labels . append ( Label ( LabelType . PARENT_SUITE , suites . pop ( 0 ) ) ) labels . append ( Label ( LabelType . SUITE , suites . pop ( 0 ) ) ) if len ( suites ) > 1 : labels . append ( Label ( LabelType . SUB_SUITE , '.' . join ( suites [ ...
def chained ( wrapping_exc ) : # pylint : disable = W0212 """Embeds the current exception information into the given one ( which will replace the current one ) . For example : : try : except OSError as ex : raise chained ( MyError ( " database not found ! " ) )"""
t , v , tb = sys . exc_info ( ) if not t : return wrapping_exc wrapping_exc . _inner_exc = v lines = traceback . format_exception ( t , v , tb ) wrapping_exc . _inner_tb = "" . join ( lines [ 1 : ] ) return wrapping_exc
def area ( poly ) : """Area of a polygon poly"""
if len ( poly ) < 3 : # not a plane - no area return 0 total = [ 0 , 0 , 0 ] num = len ( poly ) for i in range ( num ) : vi1 = poly [ i ] vi2 = poly [ ( i + 1 ) % num ] prod = np . cross ( vi1 , vi2 ) total [ 0 ] += prod [ 0 ] total [ 1 ] += prod [ 1 ] total [ 2 ] += prod [ 2 ] if total == [...
def _func_filters ( self , filters ) : '''Build post query filters'''
if not isinstance ( filters , ( list , tuple ) ) : raise TypeError ( 'func_filters must be a <type list> or <type tuple>' ) for i , func in enumerate ( filters ) : if isinstance ( func , str ) and func == 'reverse' : filters [ i ] = 'reverse()' elif isinstance ( func , tuple ) and func [ 0 ] in YQL ...
def Add ( self , request , callback = None ) : """Add a new request . Args : request : A http _ wrapper . Request to add to the batch . callback : A callback to be called for this response , of the form callback ( response , exception ) . The first parameter is the deserialized response object . The secon...
handler = RequestResponseAndHandler ( request , None , callback ) self . __request_response_handlers [ self . _NewId ( ) ] = handler
def _request ( self , method , path = '/' , url = None , ignore_codes = [ ] , ** kwargs ) : """Performs HTTP request . : param str method : An HTTP method ( e . g . ' get ' , ' post ' , ' PUT ' , etc . . . ) : param str path : A path component of the target URL . This will be appended to the value of ` ` self...
_url = url if url else ( self . endpoint + path ) r = self . s . request ( method , _url , ** kwargs ) if not r . ok and r . status_code not in ignore_codes : r . raise_for_status ( ) return HTTPResponse ( r )
def licenses ( self ) : """Returns a string of the built - in licenses the J - Link has . Args : self ( JLink ) : the ` ` JLink ` ` instance Returns : String of the contents of the built - in licenses the J - Link has ."""
buf_size = self . MAX_BUF_SIZE buf = ( ctypes . c_char * buf_size ) ( ) res = self . _dll . JLINK_GetAvailableLicense ( buf , buf_size ) if res < 0 : raise errors . JLinkException ( res ) return ctypes . string_at ( buf ) . decode ( )
def record_set_get ( name , zone_name , resource_group , record_type , ** kwargs ) : '''. . versionadded : : Fluorine Get a dictionary representing a record set ' s properties . : param name : The name of the record set , relative to the name of the zone . : param zone _ name : The name of the DNS zone ( with...
dnsconn = __utils__ [ 'azurearm.get_client' ] ( 'dns' , ** kwargs ) try : record_set = dnsconn . record_sets . get ( relative_record_set_name = name , zone_name = zone_name , resource_group_name = resource_group , record_type = record_type ) result = record_set . as_dict ( ) except CloudError as exc : __uti...
def _exclude_region ( self , contig , start , end , fout ) : '''Writes reads not mapping to the given region of contig , start and end as per python convention'''
sam_reader = pysam . Samfile ( self . bam , "rb" ) exclude_interval = pyfastaq . intervals . Interval ( start , end - 1 ) for read in sam_reader . fetch ( contig ) : read_interval = pyfastaq . intervals . Interval ( read . pos , read . reference_end - 1 ) if not read_interval . intersects ( exclude_interval ) :...
def simple ( type , short , long = None , parent = None , buttons = gtk . BUTTONS_OK , default = None , ** kw ) : """A simple dialog : param type : The type of dialog : param short : The short description : param long : The long description : param parent : The parent Window to make this dialog transient to...
if buttons == gtk . BUTTONS_OK : default = gtk . RESPONSE_OK return _message_dialog ( type , short , long , parent = parent , buttons = buttons , default = default , ** kw )