signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_sender ( * sender_params , ** kwargs ) : """Utility function acting as a Sender factory - ensures senders don ' t get created twice of more for the same target server"""
notify_func = kwargs [ 'notify_func' ] with _sender_instances_lock : existing_sender = _sender_instances . get ( sender_params , None ) if existing_sender : sender = existing_sender sender . _notify = notify_func else : sender = _Sender ( * sender_params , notify = notify_func ) ...
def get_cell ( self , index , column ) : """For a single index and column value return the value of the cell : param index : index value : param column : column name : return : value"""
i = sorted_index ( self . _index , index ) if self . _sort else self . _index . index ( index ) c = self . _columns . index ( column ) return self . _data [ c ] [ i ]
def taper_shift ( waveform , output ) : """Add waveform to output with waveform shifted accordingly ( for tapering multi - mode ringdowns )"""
if len ( waveform ) == len ( output ) : output . data += waveform . data else : output . data [ len ( output ) - len ( waveform ) : ] += waveform . data return output
def get_config_directory ( appname ) : """Get OS - specific configuration directory . : type appname : str : arg appname : capitalized name of the application"""
if platform . system ( ) . lower ( ) == 'windows' : path = os . path . join ( os . getenv ( 'APPDATA' ) or '~' , appname , appname ) elif platform . system ( ) . lower ( ) == 'darwin' : path = os . path . join ( '~' , 'Library' , 'Application Support' , appname ) else : path = os . path . join ( os . getenv...
def gatk_haplotype_caller ( job , bam , bai , ref , fai , ref_dict , annotations = None , emit_threshold = 10.0 , call_threshold = 30.0 , unsafe_mode = False , hc_output = None ) : """Uses GATK HaplotypeCaller to identify SNPs and INDELs . Outputs variants in a Genomic VCF file . : param JobFunctionWrappingJob jo...
job . fileStore . logToMaster ( 'Running GATK HaplotypeCaller' ) inputs = { 'genome.fa' : ref , 'genome.fa.fai' : fai , 'genome.dict' : ref_dict , 'input.bam' : bam , 'input.bam.bai' : bai } work_dir = job . fileStore . getLocalTempDir ( ) for name , file_store_id in inputs . iteritems ( ) : job . fileStore . readG...
def _rm_gos_edges ( rm_goids , edges_all ) : """Remove any is _ a edges that contain user - specified edges ."""
edges_reduced = [ ] for goid_child , goid_parent in sorted ( edges_all , key = lambda t : t [ 1 ] ) : if goid_child not in rm_goids and goid_parent not in rm_goids : edges_reduced . append ( ( goid_child , goid_parent ) ) return edges_reduced
def cmap_center_point_adjust ( cmap , range , center ) : """Converts center to a ratio between 0 and 1 of the range given and calls cmap _ center _ adjust ( ) . returns a new adjusted colormap accordingly : param cmap : colormap instance : param range : Tuple of ( min , max ) : param center : New cmap cen...
if not ( ( range [ 0 ] < center ) and ( center < range [ 1 ] ) ) : return cmap return cmap_center_adjust ( cmap , abs ( center - range [ 0 ] ) / abs ( range [ 1 ] - range [ 0 ] ) )
def _uniform_sample ( self ) : """Sampling method . First uniformly sample a demonstration from the set of demonstrations . Then uniformly sample a state from the selected demonstration ."""
# get a random episode index ep_ind = random . choice ( self . demo_list ) # select a flattened mujoco state uniformly from this episode states = self . demo_file [ "data/{}/states" . format ( ep_ind ) ] . value state = random . choice ( states ) if self . need_xml : model_xml = self . _xml_for_episode_index ( ep_i...
def logit ( x , a = 0. , b = 1. ) : r"""Computes the logit function with domain : math : ` x \ in ( a , b ) ` . This is given by : . . math : : \ mathrm { logit } ( x ; a , b ) = \ log \ left ( \ frac { x - a } { b - x } \ right ) . Note that this is also the inverse of the logistic function with range : ...
return numpy . log ( x - a ) - numpy . log ( b - x )
def _getPercentile ( points , n , interpolate = False ) : """Percentile is calculated using the method outlined in the NIST Engineering Statistics Handbook : http : / / www . itl . nist . gov / div898 / handbook / prc / section2 / prc252 . htm"""
sortedPoints = sorted ( not_none ( points ) ) if len ( sortedPoints ) == 0 : return None fractionalRank = ( n / 100.0 ) * ( len ( sortedPoints ) + 1 ) rank = int ( fractionalRank ) rankFraction = fractionalRank - rank if not interpolate : rank += int ( math . ceil ( rankFraction ) ) if rank == 0 : percentil...
def segment_centre_of_mass ( seg ) : '''Calculate and return centre of mass of a segment . C , seg _ volalculated as centre of mass of conical frustum'''
h = mm . segment_length ( seg ) r0 = seg [ 0 ] [ COLS . R ] r1 = seg [ 1 ] [ COLS . R ] num = r0 * r0 + 2 * r0 * r1 + 3 * r1 * r1 denom = 4 * ( r0 * r0 + r0 * r1 + r1 * r1 ) centre_of_mass_z_loc = num / denom return seg [ 0 ] [ COLS . XYZ ] + ( centre_of_mass_z_loc / h ) * ( seg [ 1 ] [ COLS . XYZ ] - seg [ 0 ] [ COLS ...
def get_outlier_info ( pronac ) : """Return if a project with the given pronac is an outlier based on raised funds ."""
df = data . planilha_captacao raised_funds_averages = data . segment_raised_funds_average . to_dict ( 'index' ) segment_id = df [ df [ 'Pronac' ] == pronac ] [ 'Segmento' ] . iloc [ 0 ] mean = raised_funds_averages [ segment_id ] [ 'mean' ] std = raised_funds_averages [ segment_id ] [ 'std' ] project_raised_funds = get...
def apply_transform ( self , matrix ) : """Apply a transform to the sphere primitive Parameters matrix : ( 4,4 ) float , homogenous transformation"""
matrix = np . asanyarray ( matrix , dtype = np . float64 ) if matrix . shape != ( 4 , 4 ) : raise ValueError ( 'shape must be 4,4' ) center = np . dot ( matrix , np . append ( self . primitive . center , 1.0 ) ) [ : 3 ] self . primitive . center = center
def get_orders ( self , instrument = None , count = 50 ) : """See more : http : / / developer . oanda . com / rest - live / orders / # getOrdersForAnAccount"""
url = "{0}/{1}/accounts/{2}/orders" . format ( self . domain , self . API_VERSION , self . account_id ) params = { "instrument" : instrument , "count" : count } try : return self . _Client__call ( uri = url , params = params , method = "get" ) except RequestException : return False except AssertionError : r...
def main ( sniffer_instance = None , test_args = ( ) , progname = sys . argv [ 0 ] , args = sys . argv [ 1 : ] ) : """Runs the program . This is used when you want to run this program standalone . ` ` sniffer _ instance ` ` A class ( usually subclassed of Sniffer ) that hooks into the scanner and handles runnin...
parser = OptionParser ( version = "%prog " + __version__ ) parser . add_option ( '-w' , '--wait' , dest = "wait_time" , metavar = "TIME" , default = 0.5 , type = "float" , help = "Wait time, in seconds, before possibly rerunning" "tests. (default: %default)" ) parser . add_option ( '--no-clear' , dest = "clear_on_run" ...
def available_migrations ( ) : '''List available migrations for udata and enabled plugins Each row is tuple with following signature : ( plugin , package , filename )'''
migrations = [ ] for filename in resource_listdir ( 'udata' , 'migrations' ) : if filename . endswith ( '.js' ) : migrations . append ( ( 'udata' , 'udata' , filename ) ) plugins = entrypoints . get_enabled ( 'udata.models' , current_app ) for plugin , module in plugins . items ( ) : if resource_isdir (...
def filter_by_status ( weather_list , status , weather_code_registry ) : """Filters out from the provided list of * Weather * objects a sublist of items having a status corresponding to the provided one . The lookup is performed against the provided * WeatherCodeRegistry * object . : param weathers : a list o...
result = [ ] for weather in weather_list : if status_is ( weather , status , weather_code_registry ) : result . append ( weather ) return result
def get_status_badge ( self , project , definition , branch_name = None , stage_name = None , job_name = None , configuration = None , label = None ) : """GetStatusBadge . [ Preview API ] < p > Gets the build status for a definition , optionally scoped to a specific branch , stage , job , and configuration . < / ...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if definition is not None : route_values [ 'definition' ] = self . _serialize . url ( 'definition' , definition , 'str' ) query_parameters = { } if branch_name is not None : query...
def _urlparse ( path ) : """Like urlparse except it assumes ' file : / / ' if no scheme is specified"""
url = urlparse . urlparse ( path ) _validate_url ( url ) if not url . scheme or url . scheme == 'file://' : # Normalize path , and set scheme to " file " if missing path = os . path . abspath ( os . path . expanduser ( path ) ) url = urlparse . urlparse ( 'file://' + path ) return url
def read ( self , numberOfBytes ) : """Read from a port on dummy _ serial . The response is dependent on what was written last to the port on dummy _ serial , and what is defined in the : data : ` RESPONSES ` dictionary . Args : numberOfBytes ( int ) : For compability with the real function . Returns a * ...
if VERBOSE : _print_out ( '\nDummy_serial: Reading from port (max length {!r} bytes)' . format ( numberOfBytes ) ) if numberOfBytes < 0 : raise IOError ( 'Dummy_serial: The numberOfBytes to read must not be negative. Given: {!r}' . format ( numberOfBytes ) ) if not self . _isOpen : raise IOError ( 'Dummy_se...
def squareform_isfc ( isfcs , iscs = None ) : """Converts square ISFCs to condensed ISFCs ( and ISCs ) , and vice - versa If input is a 2 - or 3 - dimensional array of square ISFC matrices , converts this to the condensed off - diagonal ISFC values ( i . e . , the vectorized triangle ) and the diagonal ISC va...
# Check if incoming ISFCs are square ( redundant ) if not type ( iscs ) == np . ndarray and isfcs . shape [ - 2 ] == isfcs . shape [ - 1 ] : if isfcs . ndim == 2 : isfcs = isfcs [ np . newaxis , ... ] if isfcs . ndim == 3 : iscs = np . diagonal ( isfcs , axis1 = 1 , axis2 = 2 ) isfcs = n...
def get_git_refs ( self ) : """: calls : ` GET / repos / : owner / : repo / git / refs < http : / / developer . github . com / v3 / git / refs > ` _ : rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . GitRef . GitRef `"""
return github . PaginatedList . PaginatedList ( github . GitRef . GitRef , self . _requester , self . url + "/git/refs" , None )
def close_debt_position ( self , symbol , account = None ) : """Close a debt position and reclaim the collateral : param str symbol : Symbol to close debt position for : raises ValueError : if symbol has no open call position"""
if not account : if "default_account" in self . blockchain . config : account = self . blockchain . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , full = True , blockchain_instance = self . blockchain ) debts = self . lis...
def get ( self , section , option , raw = False , vars = None ) : """Get an option value for a given section . If ` vars ' is provided , it must be a dictionary . The option is looked up in ` vars ' ( if provided ) , ` section ' , and in ` defaults ' in that order . All % interpolations are expanded in the re...
sectiondict = { } try : sectiondict = self . _sections [ section ] except KeyError : if section != DEFAULTSECT : raise NoSectionError ( section ) # Update with the entry specific variables vardict = { } if vars : for key , value in vars . items ( ) : vardict [ self . optionxform ( key ) ] = ...
def find_endurance_tier_iops_per_gb ( volume ) : """Find the tier for the given endurance volume ( IOPS per GB ) : param volume : The volume for which the tier level is desired : return : Returns a float value indicating the IOPS per GB for the volume"""
tier = volume [ 'storageTierLevel' ] iops_per_gb = 0.25 if tier == "LOW_INTENSITY_TIER" : iops_per_gb = 0.25 elif tier == "READHEAVY_TIER" : iops_per_gb = 2 elif tier == "WRITEHEAVY_TIER" : iops_per_gb = 4 elif tier == "10_IOPS_PER_GB" : iops_per_gb = 10 else : raise ValueError ( "Could not find tie...
async def main ( ) : """Load devices and scenes , run first scene ."""
pyvlx = PyVLX ( 'pyvlx.yaml' ) # Alternative : # pyvlx = PyVLX ( host = " 192.168.2.127 " , password = " velux123 " , timeout = 60) await pyvlx . load_devices ( ) print ( pyvlx . devices [ 1 ] ) print ( pyvlx . devices [ 'Fenster 4' ] ) await pyvlx . load_scenes ( ) print ( pyvlx . scenes [ 0 ] ) print ( pyvlx . scenes...
def displayValue ( self , vocab , value , widget ) : """Overwrite the Script ( Python ) ` displayValue . py ` located at ` Products . Archetypes . skins . archetypes ` to handle the references of our Picklist Widget ( Methods ) gracefully . This method gets called by the ` picklist . pt ` template like this :...
# Taken from the Script ( Python ) t = self . restrictedTraverse ( '@@at_utils' ) . translate # ensure we have strings , otherwise the ` getValue ` method of # Products . Archetypes . utils will raise a TypeError def to_string ( v ) : if isinstance ( v , basestring ) : return v return api . get_title ( ...
def copy_file_clipboard ( self , fnames = None ) : """Copy file ( s ) / folders ( s ) to clipboard ."""
if fnames is None : fnames = self . get_selected_filenames ( ) if not isinstance ( fnames , ( tuple , list ) ) : fnames = [ fnames ] try : file_content = QMimeData ( ) file_content . setUrls ( [ QUrl . fromLocalFile ( _fn ) for _fn in fnames ] ) cb = QApplication . clipboard ( ) cb . setMimeData...
def load_mod ( module , package ) : """Load a module named ` ` module ` ` from given search ` ` path ` ` The module path prefix is set according to the ` ` prefix ` ` argument . By defualt the module is loaded as if it comes from a global ' db _ migrations ' package . As such , it may conflict with any ' db _...
name = '%s.%s' % ( package . __name__ , module ) if name in sys . modules : return sys . modules [ name ] return importlib . import_module ( name , package = package . __name__ )
def podcast_episode ( self , podcast_episode_id ) : """Get information about a podcast _ episode . Parameters : podcast _ episode _ id ( str ) : A podcast episode ID . Returns : dict : Podcast episode information ."""
response = self . _call ( mc_calls . PodcastFetchEpisode , podcast_episode_id ) podcast_episode_info = [ podcast_episode for podcast_episode in response . body if not podcast_episode [ 'deleted' ] ] return podcast_episode_info
def SetCTypesForLibrary ( libname , fn_table ) : """Set function argument types and return types for an ObjC library . Args : libname : Library name string fn _ table : List of ( function , [ arg types ] , return types ) tuples Returns : ctypes . CDLL with types set according to fn _ table Raises : Er...
libpath = ctypes . util . find_library ( libname ) if not libpath : raise ErrorLibNotFound ( 'Library %s not found' % libname ) lib = ctypes . cdll . LoadLibrary ( libpath ) # We need to define input / output parameters for all functions we use for ( function , args , result ) in fn_table : f = getattr ( lib , ...
def _to_bel_lines_body ( graph ) -> Iterable [ str ] : """Iterate the lines of a BEL graph ' s corresponding BEL script ' s body . : param pybel . BELGraph graph : A BEL graph"""
qualified_edges = sort_qualified_edges ( graph ) for citation , citation_edges in group_citation_edges ( qualified_edges ) : yield 'SET Citation = {{{}}}\n' . format ( citation ) for evidence , evidence_edges in group_evidence_edges ( citation_edges ) : yield 'SET SupportingText = "{}"' . format ( evide...
def __calculate_boltzmann_factor ( self , state_key , next_action_list ) : '''Calculate boltzmann factor . Args : state _ key : The key of state . next _ action _ list : The possible action in ` self . t + 1 ` . If the length of this list is 0 , all action should be possible . Returns : [ ( ` The key of...
sigmoid = self . __calculate_sigmoid ( ) q_df = self . q_df [ self . q_df . state_key == state_key ] q_df = q_df [ q_df . isin ( next_action_list ) ] q_df [ "boltzmann_factor" ] = q_df [ "q_value" ] / sigmoid q_df [ "boltzmann_factor" ] = q_df [ "boltzmann_factor" ] . apply ( np . exp ) q_df [ "boltzmann_factor" ] = q_...
def vxvyvz_to_galcencyl ( vx , vy , vz , X , Y , Z , vsun = [ 0. , 1. , 0. ] , Xsun = 1. , Zsun = 0. , galcen = False , _extra_rot = True ) : """NAME : vxvyvz _ to _ galcencyl PURPOSE : transform velocities in XYZ coordinates ( wrt Sun ) to cylindrical Galactocentric coordinates for velocities INPUT : vx ...
vxyz = vxvyvz_to_galcenrect ( vx , vy , vz , vsun = vsun , Xsun = Xsun , Zsun = Zsun , _extra_rot = _extra_rot ) return nu . array ( rect_to_cyl_vec ( vxyz [ : , 0 ] , vxyz [ : , 1 ] , vxyz [ : , 2 ] , X , Y , Z , cyl = galcen ) ) . T
def type_str ( self , short = False ) : """Returns the type of the attribute as string . : return : the type : rtype : str"""
if short : return javabridge . static_call ( "weka/core/Attribute" , "typeToStringShort" , "(Lweka/core/Attribute;)Ljava/lang/String;" , self . jobject ) else : return javabridge . static_call ( "weka/core/Attribute" , "typeToString" , "(Lweka/core/Attribute;)Ljava/lang/String;" , self . jobject )
def parse_volumes_output ( out ) : """Parses the output of the Docker CLI ' docker volume ls ' and returns it in the format similar to the Docker API . : param out : CLI output . : type out : unicode | str : return : Parsed result . : rtype : list [ dict ]"""
if not out : return [ ] line_iter = islice ( out . splitlines ( ) , 1 , None ) # Skip header return list ( map ( _volume_info , line_iter ) )
def get_filepaths_with_extension ( extname , root_dir = '.' ) : """Get relative filepaths of files in a directory , and sub - directories , with the given extension . Parameters extname : ` str ` Extension name ( e . g . ' txt ' , ' rst ' ) . Extension comparison is case - insensitive . root _ dir : ` s...
# needed for comparison with os . path . splitext if not extname . startswith ( '.' ) : extname = '.' + extname # for case - insensitivity extname = extname . lower ( ) root_dir = os . path . abspath ( root_dir ) selected_filenames = [ ] for dirname , sub_dirnames , filenames in os . walk ( root_dir ) : for fil...
def _read_file ( folder , filename ) : '''Reads and returns the contents of a file'''
path = os . path . join ( folder , filename ) try : with salt . utils . files . fopen ( path , 'rb' ) as contents : return salt . utils . data . decode ( contents . readlines ( ) ) except ( OSError , IOError ) : return ''
def migrate ( gandi , resource , force , background ) : """Migrate a disk to another datacenter ."""
# check it ' s not attached source_info = gandi . disk . info ( resource ) if source_info [ 'vms_id' ] : click . echo ( 'Cannot start the migration: disk %s is attached. ' 'Please detach the disk before starting the migration.' % resource ) return disk_datacenter = source_info [ 'datacenter_id' ] dc_choices = g...
def get_fpath ( self , cachedir = None , cfgstr = None , ext = None ) : """Ignore : fname = _ fname cfgstr = _ cfgstr"""
_dpath = self . get_cachedir ( cachedir ) _fname = self . get_prefix ( ) _cfgstr = self . get_cfgstr ( ) if cfgstr is None else cfgstr _ext = self . ext if ext is None else ext fpath = _args2_fpath ( _dpath , _fname , _cfgstr , _ext ) return fpath
def __parse_identities ( self , json ) : """Parse identities using Stackalytics format . The Stackalytics identities format is a JSON document under the " users " key . The document should follow the next schema : " users " : [ " launchpad _ id " : " 0 - jsmith " , " gerrit _ id " : " jsmith " , " compa...
try : for user in json [ 'users' ] : name = self . __encode ( user [ 'user_name' ] ) uuid = name uid = UniqueIdentity ( uuid = uuid ) identity = Identity ( name = name , email = None , username = None , source = self . source , uuid = uuid ) uid . identities . append ( identi...
def save_json_metadata ( self , package_info : Dict ) -> bool : """Take the JSON metadata we just fetched and save to disk"""
try : with utils . rewrite ( self . json_file ) as jf : dump ( package_info , jf , indent = 4 , sort_keys = True ) except Exception as e : logger . error ( "Unable to write json to {}: {}" . format ( self . json_file , str ( e ) ) ) return False symlink_dir = self . json_pypi_symlink . parent if not...
def _valid_comparison ( time_a , time_b , event_a , event_b ) : """True if times can be compared ."""
if time_a == time_b : # Ties are only informative if exactly one event happened return event_a != event_b if event_a and event_b : return True if event_a and time_a < time_b : return True if event_b and time_b < time_a : return True return False
def get_path ( self , path = '' ) : """Validate incoming path , if path is empty , build it from resource attributes , If path is invalid - raise exception : param path : path to remote file storage : return : valid path or : raise Exception :"""
if not path : host = self . resource_config . backup_location if ':' not in host : scheme = self . resource_config . backup_type if not scheme or scheme . lower ( ) == self . DEFAULT_FILE_SYSTEM . lower ( ) : scheme = self . file_system scheme = re . sub ( '(:|/+).*$' , '' , ...
def create_transaction ( self , outputs , fee = None , leftover = None , combine = True , message = None , unspents = None , custom_pushdata = False ) : # pragma : no cover """Creates a signed P2PKH transaction . : param outputs : A sequence of outputs you wish to send in the form ` ` ( destination , amount , c...
unspents , outputs = sanitize_tx_data ( unspents or self . unspents , outputs , fee or get_fee ( ) , leftover or self . address , combine = combine , message = message , compressed = self . is_compressed ( ) , custom_pushdata = custom_pushdata ) return create_p2pkh_transaction ( self , unspents , outputs , custom_pushd...
def set_input_container ( _container , cfg ) : """Save the input for the container in the configurations ."""
if not _container : return False if _container . exists ( ) : cfg [ "container" ] [ "input" ] = str ( _container ) return True return False
def main ( ) : """Generate a PDF using the async method ."""
docraptor = DocRaptor ( ) print ( "Create PDF" ) resp = docraptor . create ( { "document_content" : "<h1>python-docraptor</h1><p>Async Test</p>" , "test" : True , "async" : True , } ) print ( "Status ID: {status_id}" . format ( status_id = resp [ "status_id" ] ) ) status_id = resp [ "status_id" ] resp = docraptor . sta...
def advanced_wrap ( f , wrapper ) : """Wrap a decorated function while keeping the same keyword arguments"""
f_sig = list ( inspect . getargspec ( f ) ) wrap_sig = list ( inspect . getargspec ( wrapper ) ) # Update the keyword arguments of the wrapper if f_sig [ 3 ] is None or f_sig [ 3 ] == [ ] : f_sig [ 3 ] , f_kwargs = [ ] , [ ] else : f_kwargs = f_sig [ 0 ] [ - len ( f_sig [ 3 ] ) : ] for key , default in zip ( f_...
def resolved_packages ( self ) : """Return a list of PackageVariant objects , or None if the resolve did not complete or was unsuccessful ."""
if ( self . status != SolverStatus . solved ) : return None final_phase = self . phase_stack [ - 1 ] return final_phase . _get_solved_variants ( )
def _to_roman ( num ) : """Convert integer to roman numerals ."""
roman_numeral_map = ( ( 'M' , 1000 ) , ( 'CM' , 900 ) , ( 'D' , 500 ) , ( 'CD' , 400 ) , ( 'C' , 100 ) , ( 'XC' , 90 ) , ( 'L' , 50 ) , ( 'XL' , 40 ) , ( 'X' , 10 ) , ( 'IX' , 9 ) , ( 'V' , 5 ) , ( 'IV' , 4 ) , ( 'I' , 1 ) ) if not ( 0 < num < 5000 ) : log ( WARN , 'Number out of range for roman (must be 1..4999)' ...
def _conn_string_odbc ( self , db_key , instance = None , conn_key = None , db_name = None ) : '''Return a connection string to use with odbc'''
if instance : dsn , host , username , password , database , driver = self . _get_access_info ( instance , db_key , db_name ) elif conn_key : dsn , host , username , password , database , driver = conn_key . split ( ":" ) conn_str = '' if dsn : conn_str = 'DSN={};' . format ( dsn ) if driver : conn_str +...
def dispatch_job ( jobname , exe , args , opts , batch_opts , dry_run = True ) : """Dispatch an LSF job . Parameters exe : str Execution string . args : list Positional arguments . opts : dict Dictionary of command - line options ."""
batch_opts . setdefault ( 'W' , 300 ) batch_opts . setdefault ( 'R' , 'rhel60 && scratch > 10' ) cmd_opts = '' for k , v in opts . items ( ) : if isinstance ( v , list ) : cmd_opts += ' ' . join ( [ '--%s=%s' % ( k , t ) for t in v ] ) elif isinstance ( v , bool ) and v : cmd_opts += ' --%s ' % ...
def setup_signals ( ) : """Set up the signal handlers ."""
signal . signal ( signal . SIGINT , shutit_util . ctrl_c_signal_handler ) signal . signal ( signal . SIGQUIT , shutit_util . ctrl_quit_signal_handler )
def canonicalize ( ctx , statement , namespace_targets , version , api , config_fn ) : """Canonicalize statement Target namespaces can be provided in the following manner : bel stmt canonicalize " < BELStmt > " - - namespace _ targets ' { " HGNC " : [ " EG " , " SP " ] , " CHEMBL " : [ " CHEBI " ] } ' the val...
if config_fn : config = bel . db . Config . merge_config ( ctx . config , override_config_fn = config_fn ) else : config = ctx . config # Configuration - will return the first truthy result in list else the default option if namespace_targets : namespace_targets = json . loads ( namespace_targets ) namespac...
def give_repr ( cls ) : # pragma : no cover r"""Patch a class to give it a generic _ _ repr _ _ method that works by inspecting the instance dictionary . Parameters cls : type The class to add a generic _ _ repr _ _ to . Returns cls : type The passed class is returned"""
def reprer ( self ) : attribs = ', ' . join ( [ "%s=%r" % ( k , v ) for k , v in self . __dict__ . items ( ) if not k . startswith ( "_" ) ] ) wrap = "{self.__class__.__name__}({attribs})" . format ( self = self , attribs = attribs ) return wrap cls . __repr__ = reprer return cls
def writesgf ( self , sgffilename ) : "Write the game to an SGF file after a game"
size = self . size outfile = open ( sgffilename , "w" ) if not outfile : print "Couldn't create " + sgffilename return black_name = self . blackplayer . get_program_name ( ) white_name = self . whiteplayer . get_program_name ( ) black_seed = self . blackplayer . get_random_seed ( ) white_seed = self . whiteplay...
async def load ( self , file_path , locale = None , key : int = 0 , pos : int = 1 , neg : Optional [ ColRanges ] = None ) : """Start the loading / watching process"""
if neg is None : neg : ColRanges = [ ( 2 , None ) ] await self . start ( file_path , locale , kwargs = { 'key' : key , 'pos' : pos , 'neg' : neg , } )
def dom_table ( self ) : """A ` Table ` containing DOM attributes"""
if self . _dom_table is None : data = defaultdict ( list ) for dom_id , ( du , floor , _ ) in self . doms . items ( ) : data [ 'dom_id' ] . append ( dom_id ) data [ 'du' ] . append ( du ) data [ 'floor' ] . append ( floor ) dom_position = self . dom_positions [ dom_id ] d...
def ae ( actual , predicted ) : """Computes the absolute error . This function computes the absolute error between two numbers , or for element between a pair of lists or numpy arrays . Parameters actual : int , float , list of numbers , numpy array The ground truth value predicted : same type as actual...
return np . abs ( np . array ( actual ) - np . array ( predicted ) )
def sargasso_stats_table ( self ) : """Take the parsed stats from the sargasso report and add them to the basic stats table at the top of the report"""
headers = OrderedDict ( ) headers [ 'sargasso_percent_assigned' ] = { 'title' : '% Assigned' , 'description' : 'Sargasso % Assigned reads' , 'max' : 100 , 'min' : 0 , 'suffix' : '%' , 'scale' : 'RdYlGn' } headers [ 'Assigned-Reads' ] = { 'title' : '{} Assigned' . format ( config . read_count_prefix ) , 'description' : ...
def elapse_time ( start , end = None , precision = 3 ) : """Simple time calculation utility . Given a start time , it will provide an elapse time ."""
if end is None : end = time_module . time ( ) return round ( end - start , precision )
def get_chacra_repo ( shaman_url ) : """From a Shaman URL , get the chacra url for a repository , read the contents that point to the repo and return it as a string ."""
shaman_response = get_request ( shaman_url ) chacra_url = shaman_response . geturl ( ) chacra_response = get_request ( chacra_url ) return chacra_response . read ( )
def _pseudo_parse_arglist ( signode , arglist ) : """Parse list of comma separated arguments . Arguments can have optional types ."""
paramlist = addnodes . desc_parameterlist ( ) stack = [ paramlist ] try : for argument in arglist . split ( ',' ) : argument = argument . strip ( ) ends_open = 0 ends_close = 0 while argument . startswith ( '[' ) : stack . append ( addnodes . desc_optional ( ) ) ...
def sync_state ( self ) : """Syncs the internal Pybullet robot state to the joint positions of the robot being controlled ."""
# sync IK robot state to the current robot joint positions self . sync_ik_robot ( self . robot_jpos_getter ( ) ) # make sure target pose is up to date pos_r , orn_r , pos_l , orn_l = self . ik_robot_eef_joint_cartesian_pose ( ) self . ik_robot_target_pos_right = pos_r self . ik_robot_target_orn_right = orn_r self . ik_...
def _get_library_os_path_from_library_dict_tree ( self , library_path , library_name ) : """Hand verified library os path from libraries dictionary tree ."""
if library_path is None or library_name is None : return None path_list = library_path . split ( os . sep ) target_lib_dict = self . libraries # go down the path to the correct library for path_element in path_list : if path_element not in target_lib_dict : # Library cannot be found target_lib_dict = No...
def logReload ( options ) : """encompasses all the logic for reloading observer ."""
event_handler = Reload ( options ) observer = Observer ( ) observer . schedule ( event_handler , path = '.' , recursive = True ) observer . start ( ) try : while True : time . sleep ( 1 ) except KeyboardInterrupt : observer . stop ( ) pid = os . getpid ( ) chalk . eraser ( ) chalk . green ( ...
def get_edge_citation ( self , u : BaseEntity , v : BaseEntity , key : str ) -> Optional [ CitationDict ] : """Get the citation for a given edge ."""
return self . _get_edge_attr ( u , v , key , CITATION )
def get_payload ( self ) : """Return Payload ."""
ret = bytes ( [ len ( self . scenes ) ] ) for number , name in self . scenes : ret += bytes ( [ number ] ) ret += string_to_bytes ( name , 64 ) ret += bytes ( [ self . remaining_scenes ] ) return ret
def JMS_to_FormFlavor_lep ( C , dd ) : """From JMS to semileptonic Fierz basis for Classes V . C should be the JMS basis and ` ddll ` should be of the form ' sbl _ eni _ tau ' , ' dbl _ munu _ e ' etc ."""
b = dflav [ dd [ 0 ] ] s = dflav [ dd [ 1 ] ] return { 'CVLL_' + dd + 'mm' : C [ "VedLL" ] [ 1 , 1 , s , b ] , 'CVRR_' + dd + 'mm' : C [ "VedRR" ] [ 1 , 1 , s , b ] , 'CVLR_' + dd + 'mm' : C [ "VdeLR" ] [ s , b , 1 , 1 ] , 'CVRL_' + dd + 'mm' : C [ "VedLR" ] [ 1 , 1 , s , b ] , 'CSLL_' + dd + 'mm' : C [ "SedRR" ] [ 1 ,...
def nla_put_nested ( msg , attrtype , nested ) : """Add nested attributes to Netlink message . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / attr . c # L772 Takes the attributes found in the ` nested ` message and appends them to the message ` msg ` nested in a container of the type ...
_LOGGER . debug ( 'msg 0x%x: attr <> %d: adding msg 0x%x as nested attribute' , id ( msg ) , attrtype , id ( nested ) ) return nla_put ( msg , attrtype , nlmsg_datalen ( nested . nm_nlh ) , nlmsg_data ( nested . nm_nlh ) )
def cdl_addmon ( self , source_url , save_path = '/' , timeout = 3600 ) : '''Usage : cdl _ addmon < source _ url > [ save _ path ] [ timeout ] - add an offline ( cloud ) download task and monitor the download progress source _ url - the URL to download file from . save _ path - path on PCS to save file to . def...
rpath = self . __get_cdl_dest ( source_url , save_path ) return self . __cdl_addmon ( source_url , rpath , timeout )
def tensor_dim_to_mesh_dim_size ( layout , mesh_shape , tensor_dim ) : """How many ways does a tensor dimension get split . This is used to " cheat " when building the mtf graph and peek at how a tensor dimension will be split . Returns 1 if the tensor dimension is not split . Args : layout : an input to ...
layout_rules = convert_to_layout_rules ( layout ) mesh_shape = convert_to_shape ( mesh_shape ) mesh_axis = layout_rules . tensor_dimension_to_mesh_axis ( tensor_dim , mesh_shape ) if mesh_axis is None : return 1 else : return mesh_shape . dims [ mesh_axis ] . size
def handle ( send , msg , args ) : """Implements several XKCD comics ."""
output = textutils . gen_xkcd_sub ( msg , True ) if output is None : return if args [ 'type' ] == 'action' : send ( "correction: * %s %s" % ( args [ 'nick' ] , output ) ) else : send ( "%s actually meant: %s" % ( args [ 'nick' ] , output ) )
def main ( ) : """Main script function ."""
args = get_args ( ) process_args ( args ) if not args . no_display : disp = display . init ( args . size ) client = song . init ( args . port , args . server ) while True : song . get_art ( args . cache_dir , args . size , client ) if not args . no_display : display . launch ( disp , args . cache_di...
def extend_instance ( instance , * bases , ** kwargs ) : """Apply subclass ( mixin ) to a class object or its instance By default , the mixin is placed at the start of bases to ensure its called first as per MRO . If you wish to have it injected last , which is useful for monkeypatching , then you can speci...
last = kwargs . get ( 'last' , False ) bases = tuple ( bases ) for base in bases : assert inspect . isclass ( base ) , "bases must be classes" assert not inspect . isclass ( instance ) base_cls = instance . __class__ base_cls_name = instance . __class__ . __name__ new_bases = ( base_cls , ) + bases if last else bas...
def _check ( self ) : """Checks if the message parameters are valid . Assumes that the types are already correct . : raises ValueError : iff one or more attributes are invalid"""
if self . timestamp < 0.0 : raise ValueError ( "the timestamp may not be negative" ) if isinf ( self . timestamp ) : raise ValueError ( "the timestamp may not be infinite" ) if isnan ( self . timestamp ) : raise ValueError ( "the timestamp may not be NaN" ) if self . is_remote_frame and self . is_error_fram...
def Descargar ( self , url = URL , filename = "padron.txt" , proxy = None ) : "Descarga el archivo de AFIP , devuelve 200 o 304 si no fue modificado"
proxies = { } if proxy : proxies [ 'http' ] = proxy proxies [ 'https' ] = proxy proxy_handler = urllib2 . ProxyHandler ( proxies ) print "Abriendo URL %s ..." % url req = urllib2 . Request ( url ) if os . path . exists ( filename ) : http_date = formatdate ( timeval = os . path . getmtime ( filename ) ,...
def _generate_list_heading ( self ) : """Generate the list of heading links of page ."""
local = self . parser . find ( 'body' ) . first_result ( ) id_container_heading_before = ( AccessibleNavigationImplementation . ID_CONTAINER_HEADING_BEFORE ) id_container_heading_after = ( AccessibleNavigationImplementation . ID_CONTAINER_HEADING_AFTER ) if local is not None : container_before = self . parser . fin...
def to_dataframe ( self , stimuli = None , inhibitors = None , prepend = "" ) : """Converts the list of clampigns to a ` pandas . DataFrame ` _ object instance Parameters stimuli : Optional [ list [ str ] ] List of stimuli names . If given , stimuli are converted to { 0,1 } instead of { - 1,1 } . inhibitors...
stimuli , inhibitors = stimuli or [ ] , inhibitors or [ ] cues = stimuli + inhibitors nc = len ( cues ) ns = len ( stimuli ) variables = cues or np . array ( list ( set ( ( v for ( v , s ) in it . chain . from_iterable ( self ) ) ) ) ) matrix = np . array ( [ ] ) for clamping in self : arr = clamping . to_array ( v...
def _build_object_type ( var , property_path = None ) : """Builds schema definitions for object type values . : param var : The object type value : param List [ str ] property _ path : The property path of the current type , defaults to None , optional : param property _ path : [ type ] , optional : retur...
if not property_path : property_path = [ ] schema = { "type" : "object" } if is_builtin_type ( var ) : return schema entry = var . metadata [ CONFIG_KEY ] if isinstance ( entry . min , int ) : schema [ "minProperties" ] = entry . min if isinstance ( entry . max , int ) : schema [ "maxProperties" ] = ent...
def rethreshold ( self , new_threshold , new_threshold_type = 'MAD' ) : """Remove detections from the Party that are below a new threshold . . . Note : : threshold can only be set higher . . . Warning : : Works in place on Party . : type new _ threshold : float : param new _ threshold : New threshold leve...
for family in self . families : rethresh_detections = [ ] for d in family . detections : if new_threshold_type == 'MAD' and d . threshold_type == 'MAD' : new_thresh = ( d . threshold / d . threshold_input ) * new_threshold elif new_threshold_type == 'MAD' and d . threshold_type != 'M...
def get_ec2_role ( self , role , mount_point = 'aws-ec2' ) : """GET / auth / < mount _ point > / role / < role > : param role : : type role : : param mount _ point : : type mount _ point : : return : : rtype :"""
return self . _adapter . get ( '/v1/auth/{0}/role/{1}' . format ( mount_point , role ) ) . json ( )
def remove_subscriber ( self , message ) : """Remove a subscriber based on token . : param message : the message"""
logger . debug ( "Remove Subcriber" ) host , port = message . destination key_token = hash ( str ( host ) + str ( port ) + str ( message . token ) ) try : self . _relations [ key_token ] . transaction . completed = True del self . _relations [ key_token ] except KeyError : logger . warning ( "No Subscriber"...
def load_class_by_path ( taskpath ) : """Given a taskpath , returns the main task class ."""
return getattr ( importlib . import_module ( re . sub ( r"\.[^.]+$" , "" , taskpath ) ) , re . sub ( r"^.*\." , "" , taskpath ) )
def list_data ( self , previous_data = False , prompt = False , console_row = False , console_row_to_cursor = False , console_row_from_cursor = False ) : """Return list of strings . Where each string is fitted to windows width . Parameters are the same as they are in : meth : ` . WConsoleWindow . data ` method ...
return self . split ( self . data ( previous_data , prompt , console_row , console_row_to_cursor , console_row_from_cursor ) )
def type ( self ) : """Read - only . A member of : ref : ` MsoColorType ` , one of RGB , THEME , or AUTO , corresponding to the way this color is defined . Its value is | None | if no color is applied at this level , which causes the effective color to be inherited from the style hierarchy ."""
color = self . _color if color is None : return None if color . themeColor is not None : return MSO_COLOR_TYPE . THEME if color . val == ST_HexColorAuto . AUTO : return MSO_COLOR_TYPE . AUTO return MSO_COLOR_TYPE . RGB
def _PrintDatabaseTable ( self , tableName , rowSelect = None ) : """Prints contents of database table . An optional argument ( rowSelect ) can be given which contains a list of column names and values against which to search , allowing a subset of the table to be printed . Gets database column headings using...
goodlogging . Log . Info ( "DB" , "{0}" . format ( tableName ) ) goodlogging . Log . IncreaseIndent ( ) tableInfo = self . _ActionDatabase ( "PRAGMA table_info({0})" . format ( tableName ) ) dbQuery = "SELECT * FROM {0}" . format ( tableName ) dbQueryParams = [ ] if rowSelect is not None : dbQuery = dbQuery + " WHE...
def split_overlaps ( self ) : """Finds all intervals with overlapping ranges and splits them along the range boundaries . Completes in worst - case O ( n ^ 2 * log n ) time ( many interval boundaries are inside many intervals ) , best - case O ( n * log n ) time ( small number of overlaps < < n per interval...
if not self : return if len ( self . boundary_table ) == 2 : return bounds = sorted ( self . boundary_table ) # get bound locations new_ivs = set ( ) for lbound , ubound in zip ( bounds [ : - 1 ] , bounds [ 1 : ] ) : for iv in self [ lbound ] : new_ivs . add ( Interval ( lbound , ubound , iv . data ...
def _aggop ( self , query ) : """SINGLE ROW RETURNED WITH AGGREGATES"""
if isinstance ( query . select , list ) : # RETURN SINGLE OBJECT WITH AGGREGATES for s in query . select : if s . aggregate not in aggregates : Log . error ( "Expecting all columns to have an aggregate: {{select}}" , select = s ) selects = FlatList ( ) for s in query . select : s...
def _LinearFoldByteStream ( self , mapped_value , ** unused_kwargs ) : """Folds the data type into a byte stream . Args : mapped _ value ( object ) : mapped value . Returns : bytes : byte stream . Raises : FoldingError : if the data type definition cannot be folded into the byte stream ."""
try : attribute_values = [ getattr ( mapped_value , attribute_name , None ) for attribute_name in self . _attribute_names ] attribute_values = [ value for value in attribute_values if value is not None ] return self . _operation . WriteTo ( tuple ( attribute_values ) ) except Exception as exception : er...
def get_ligand_ring_selection ( self , ring ) : """MDAnalysis atom selections of aromatic rings present in the ligand molecule . Takes : * ring * - index in self . ligrings dictionary Output : * ring _ selection * - MDAnalysis Atom group"""
ring_names = "" for atom in self . ligrings [ ring ] : ring_names = ring_names + " " + str ( atom ) ring_selection = self . topology_data . universe . ligand . select_atoms ( "name " + ring_names ) return ring_selection
def provider ( container , cache , name = None ) : """A decorator to register a provider on a container . For more information see : meth : ` Container . add _ provider ` ."""
def register ( provider ) : container . add_provider ( provider , cache , name ) return provider return register
def hash_function ( self ) : """Returns the hash function proper . Ensures that ` self ` is not bound to the returned closure ."""
assert hasattr ( self , 'f1' ) and hasattr ( self , 'f2' ) # These are not just convenient aliases for the given # attributes ; if ` self ` would creep into the returned closure , # that would ensure that a reference to this big , fat object # would be kept alive ; hence , any hash function would carry # around all of ...
def intersection ( self , * others ) : """Return the intersection of two or more sets as a new set . > > > from ngram import NGram > > > a = NGram ( [ ' spam ' , ' eggs ' ] ) > > > b = NGram ( [ ' spam ' , ' ham ' ] ) > > > list ( a . intersection ( b ) ) [ ' spam ' ]"""
return self . copy ( super ( NGram , self ) . intersection ( * others ) )
def attr ( aid ) : '''Action function generator to retrieve an attribute from the current link'''
def _attr ( ctx ) : return ctx . current_link [ ATTRIBUTES ] . get ( aid ) return _attr
def k2a ( a , x ) : """Rescale data from a K object x to array a ."""
func , scale = None , 1 t = abs ( x . _t ) # timestamp ( 12 ) , month ( 13 ) , date ( 14 ) or datetime ( 15) if 12 <= t <= 15 : unit = get_unit ( a ) attr , shift , func , scale = _UNIT [ unit ] a [ : ] = getattr ( x , attr ) . data a += shift # timespan ( 16 ) , minute ( 17 ) , second ( 18 ) or time ( ...
def run_checks ( self , b , compute , times = [ ] , ** kwargs ) : """run any sanity checks to make sure the parameters and options are legal for this backend . If they are not , raise an error here to avoid errors within the workers . Any physics - checks that are backend - independent should be in Bundle ....
raise NotImplementedError ( "run_checks is not implemented by the {} backend" . format ( self . __class__ . __name__ ) )
def rotx ( t ) : """Rotation about the x - axis ."""
c = np . cos ( t ) s = np . sin ( t ) return np . array ( [ [ 1 , 0 , 0 ] , [ 0 , c , - s ] , [ 0 , s , c ] ] )
def fts_count ( self , fts , inv ) : """Return the count of segments in an inventory matching a given feature mask . Args : fts ( set ) : feature mask given as a set of ( value , feature ) tuples inv ( set ) : inventory of segments ( as Unicode IPA strings ) Returns : int : number of segments in ` inv `...
return len ( list ( filter ( lambda s : self . fts_match ( fts , s ) , inv ) ) )
def smacof_p ( similarities , n_uq , metric = True , n_components = 2 , init = None , n_init = 8 , n_jobs = 1 , max_iter = 300 , verbose = 0 , eps = 1e-3 , random_state = None , return_n_iter = False ) : """Computes multidimensional scaling using SMACOF ( Scaling by Majorizing a Complicated Function ) algorithm ...
similarities = check_array ( similarities ) random_state = check_random_state ( random_state ) if hasattr ( init , '__array__' ) : init = np . asarray ( init ) . copy ( ) if not n_init == 1 : warnings . warn ( 'Explicit initial positions passed: ' 'performing only one init of the MDS instead of %d' % n_...