signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def init_nn_params ( scale , layer_sizes , rs = npr . RandomState ( 0 ) ) : """Build a list of ( weights , biases ) tuples , one for each layer ."""
return [ ( rs . randn ( insize , outsize ) * scale , # weight matrix rs . randn ( outsize ) * scale ) # bias vector for insize , outsize in zip ( layer_sizes [ : - 1 ] , layer_sizes [ 1 : ] ) ]
def depth_september_average_ground_temperature ( self , value = None ) : """Corresponds to IDD Field ` depth _ september _ average _ ground _ temperature ` Args : value ( float ) : value for IDD Field ` depth _ september _ average _ ground _ temperature ` Unit : C if ` value ` is None it will not be check...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `depth_september_average_ground_temperature`' . format ( value ) ) self . _depth_september_average_ground_temperature = value
def _get_programs_dict ( ) : """Builds and returns programs dictionary This will have to import the packages in COLLABORATORS _ S in order to get their absolute path . Returns : dictionary : { " packagename " : [ ExeInfo0 , . . . ] , . . . } " packagename " examples : " f311 . explorer " , " numpy " """
global __programs_dict if __programs_dict is not None : return __programs_dict d = __programs_dict = OrderedDict ( ) for pkgname in COLLABORATORS_S : try : package = importlib . import_module ( pkgname ) except ImportError : # I think it is better to be silent when a collaborator package is not inst...
def create_attachment ( cls , session , attachment ) : """Create an attachment . An attachment must be sent to the API before it can be used in a thread . Use this method to create the attachment , then use the resulting hash when creating a thread . Note that HelpScout only supports attachments of 10MB or ...
return super ( Conversations , cls ) . create ( session , attachment , endpoint_override = '/attachments.json' , out_type = Attachment , )
def copy ( self , ** kwargs ) : """Copy a message , optionally replace attributes with kwargs ."""
msg = Message ( self . encode ( ) , self . gateway ) for key , val in kwargs . items ( ) : setattr ( msg , key , val ) return msg
def _set_Memory ( self , v , load = False ) : """Setter method for Memory , mapped from YANG variable / rbridge _ id / threshold _ monitor / Memory ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ Memory is considered as a private method . Backends lookin...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = Memory . Memory , is_container = 'container' , presence = False , yang_name = "Memory" , rest_name = "Memory" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , ext...
def simxSetUIButtonProperty ( clientID , uiHandle , uiButtonID , prop , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
return c_SetUIButtonProperty ( clientID , uiHandle , uiButtonID , prop , operationMode )
def add_signal ( self , signal ) : """Adds " input " signal to connected signals . Internally connects the signal to a control slot ."""
self . __signals . append ( signal ) if self . __connected : # Connects signal if the current state is " connected " self . __connect_signal ( signal )
def expand ( self , other ) : """Add all elements from an other result to the list of elements of this result object . It is used by the auto resolve feature . : param other : Expand the result with the elements from this result . : type other : overpy . Result : raises ValueError : If provided parameter is...
if not isinstance ( other , Result ) : raise ValueError ( "Provided argument has to be instance of overpy:Result()" ) other_collection_map = { Node : other . nodes , Way : other . ways , Relation : other . relations , Area : other . areas } for element_type , own_collection in self . _class_collection_map . items (...
def ModulePath ( module_name ) : """Computes a path to the specified module . Args : module _ name : A name of the module to get the path for . Returns : A path to the specified module . Raises : ImportError : If specified module cannot be imported ."""
module = importlib . import_module ( module_name ) path = inspect . getfile ( module ) # TODO : In Python 2 ` inspect . getfile ` returns a byte string , so # we have to decode that in order to be consistent with Python 3. if compatibility . PY2 : path = path . decode ( "utf-8" ) # In case of modules with want a pa...
def download ( self , link_item_dict : Dict [ str , LinkItem ] , folder : Path , desc : str , unit : str , delay : float = 0 ) -> List [ str ] : """. . warning : : The parameters may change in future versions . ( e . g . change order and accept another host ) Download the given LinkItem dict from the plugins ho...
if 'delay' in self . _options : delay = self . _options [ 'delay' ] # TODO : add other optional host ? if not link_item_dict : return [ ] job_list = [ ] with ThreadPoolExecutor ( max_workers = self . _simul_downloads ) as executor : for link , item in link_item_dict . items ( ) : job = executor . su...
def pdmerge_respeta_tz ( func_merge , tz_ant = None , * args , ** kwargs ) : """Programación defensiva por issue : pandas BUG ( a veces , el index pierde el tz ) : - issue # 7795 : concat of objects with the same timezone get reset to UTC ; - issue # 10567 : DataFrame combine _ first ( ) loses timezone informa...
df_merged = func_merge ( * args , ** kwargs ) if tz_ant is not None and tz_ant != df_merged . index . tz : # print _ warn ( ' Error pandas : join prevProg + demandaGeneracion pierde timezone ( % s - > % s ) ' # % ( data _ import [ KEYS _ DATA [ 0 ] ] . index . tz , tz _ ant ) ) df_merged . index = df_merged . index...
def dict_to_pendulum ( d : Dict [ str , Any ] , pendulum_class : ClassType ) -> DateTime : """Converts a ` ` dict ` ` object back to a ` ` Pendulum ` ` ."""
return pendulum . parse ( d [ 'iso' ] )
def get ( self , key ) : """Get cache entry for key , or return None ."""
query = self . _conn . execute ( "SELECT * FROM cache WHERE key=?" , ( key , ) ) rec = query . fetchone ( ) if rec is None : return None rec = dict ( zip ( self . _columns , rec ) ) if self . check_last_modified : if rec [ 'modified' ] is None : return None # no last modified header present , so red...
def cache_generator ( self , key , generator ) : """Cache result of generator into dictionary Used to cache inference results"""
results = [ ] for result in generator : results . append ( result ) yield result self . inferred [ key ] = tuple ( results )
def _read_py ( self , fin_py , get_goids_only , exclude_ungrouped ) : """Read Python sections file . Store : section2goids sections _ seen . Return goids _ fin ."""
goids_sec = [ ] with open ( fin_py ) as istrm : section_name = None for line in istrm : mgo = self . srch_py_goids . search ( line ) # Matches GO IDs in sections if mgo : goids_sec . append ( mgo . group ( 2 ) ) elif not get_goids_only and "[" in line : ms...
def fail_stop ( self ) : """Explicit stop - the - build failure . This sets failure status on the target nodes and all of their dependent parent nodes . Note : Although this function is normally invoked on nodes in the executing state , it might also be invoked on up - to - date nodes when using Configure...
T = self . tm . trace if T : T . write ( self . trace_message ( 'Task.failed_stop()' , self . node ) ) # Invoke will _ not _ build ( ) to clean - up the pending children # list . self . tm . will_not_build ( self . targets , lambda n : n . set_state ( NODE_FAILED ) ) # Tell the taskmaster to not start any new tasks...
def get_namespace_preorder ( self , namespace_id_hash ) : """Given the hash ( namesapce _ id , sender _ script _ pubkey , reveal _ addr ) for a namespace that is being imported , get its associated NAMESPACE _ PREORDER record . Return the namespace preorder record on success . Return None if not found , if ...
namespace_preorder = namedb_get_namespace_preorder ( self . db , namespace_id_hash , self . lastblock ) return namespace_preorder
def derivative ( self , x ) : """Return the derivative at ` ` x ` ` . Left scalar multiplication and derivative are commutative : ` ` FunctionalLeftVectorMult ( op , y ) . derivative ( z ) = = FunctionalLeftVectorMult ( op . derivative ( z ) , y ) ` ` Returns derivative : ` FunctionalLeftVectorMult `"""
if self . is_linear : return self else : return FunctionalLeftVectorMult ( self . functional . derivative ( x ) , self . vector )
def _build_youtube_dl_coprocessor ( cls , session : AppSession , proxy_port : int ) : '''Build youtube - dl coprocessor .'''
# Test early for executable wpull . processor . coprocessor . youtubedl . get_version ( session . args . youtube_dl_exe ) coprocessor = session . factory . new ( 'YoutubeDlCoprocessor' , session . args . youtube_dl_exe , ( session . args . proxy_server_address , proxy_port ) , root_path = session . args . directory_pre...
def diginorm ( args ) : """% prog diginorm fastqfile Run K - mer based normalization . Based on tutorial : < http : / / ged . msu . edu / angus / diginorm - 2012 / tutorial . html > Assume input is either an interleaved pairs file , or two separate files . To set up khmer : $ git clone git : / / github . ...
from jcvi . formats . fastq import shuffle , pairinplace , split from jcvi . apps . base import getfilesize p = OptionParser ( diginorm . __doc__ ) p . add_option ( "--single" , default = False , action = "store_true" , help = "Single end reads" ) p . add_option ( "--tablesize" , help = "Memory size" ) p . add_option (...
def _set_yarn_metrics_from_json ( self , tags , metrics_json , yarn_metrics ) : """Parse the JSON response and set the metrics"""
for dict_path , metric in iteritems ( yarn_metrics ) : metric_name , metric_type = metric metric_value = self . _get_value_from_json ( dict_path , metrics_json ) if metric_value is not None : self . _set_metric ( metric_name , metric_type , metric_value , tags )
def expected_number_of_transactions_in_first_n_periods ( self , n ) : r"""Return expected number of transactions in first n n _ periods . Expected number of transactions occurring across first n transaction opportunities . Used by Fader and Hardie to assess in - sample fit . . . math : : Pr ( X ( n ) = x | ...
params = self . _unload_params ( "alpha" , "beta" , "gamma" , "delta" ) alpha , beta , gamma , delta = params x_counts = self . data . groupby ( "frequency" ) [ "weights" ] . sum ( ) x = np . asarray ( x_counts . index ) p1 = binom ( n , x ) * exp ( betaln ( alpha + x , beta + n - x ) - betaln ( alpha , beta ) + betaln...
def _watchdog_time ( self ) : """标题时间显示"""
while not self . quit : self . data . time = self . player . time_pos self . view . display ( ) time . sleep ( 1 )
def _create_hexdump ( src , start_offset = 0 , length = 16 ) : """Prepares an hexadecimal dump string : param src : A string containing binary data : param start _ offset : The start offset of the source : param length : Length of a dump line : return : A dump string"""
FILTER = "" . join ( ( len ( repr ( chr ( x ) ) ) == 3 ) and chr ( x ) or "." for x in range ( 256 ) ) pattern = "{{0:04X}} {{1:<{0}}} {{2}}\n" . format ( length * 3 ) # Convert raw data to str ( Python 3 compatibility ) src = to_str ( src , "latin-1" ) result = [ ] for i in range ( 0 , len ( src ) , length ) : ...
def nonstoichiometric_symmetrized_slab ( self , init_slab , tol = 1e-3 ) : """This method checks whether or not the two surfaces of the slab are equivalent . If the point group of the slab has an inversion symmetry ( ie . belong to one of the Laue groups ) , then it is assumed that the surfaces should be equi...
sg = SpacegroupAnalyzer ( init_slab , symprec = tol ) if sg . is_laue ( ) : return [ init_slab ] nonstoich_slabs = [ ] # Build an equivalent surface slab for each of the different surfaces for top in [ True , False ] : asym = True slab = init_slab . copy ( ) slab . energy = init_slab . energy while ...
def unique_identities ( cls , sh_db ) : """List the unique identities available in SortingHat . : param sh _ db : SortingHat database"""
try : for unique_identity in api . unique_identities ( sh_db ) : yield unique_identity except Exception as e : logger . debug ( "Unique identities not returned from SortingHat due to %s" , str ( e ) )
def load_extra_yaml ( self , env , silent , key ) : """This is deprecated , kept for compat . . deprecated : : 1.0.0 Use multiple settings or INCLUDES _ FOR _ DYNACONF files instead ."""
if self . get ( "YAML" ) is not None : self . logger . warning ( "The use of YAML var is deprecated, please define multiple " "filepaths instead: " "e.g: SETTINGS_FILE_FOR_DYNACONF = " "'settings.py,settings.yaml,settings.toml' or " "INCLUDES_FOR_DYNACONF=['path.toml', 'folder/*']" ) yaml_loader . load ( self ,...
def manages ( self , cfg_part ) : """Tell if the satellite is managing this configuration part The managed configuration is formed as a dictionary indexed on the link instance _ id : u ' SchedulerLink _ 1 ' : { u ' hash ' : u ' 4d08630a3483e1eac7898e7a721bd5d7768c8320 ' , u ' push _ flavor ' : u ' 4d08630a3...
logger . debug ( "Do I (%s/%s) manage: %s, my managed configuration(s): %s" , self . type , self . name , cfg_part , self . cfg_managed ) # If we do not yet manage a configuration if not self . cfg_managed : logger . info ( "I (%s/%s) do not manage (yet) any configuration!" , self . type , self . name ) return ...
def read_time ( self , content ) : """Core function used to generate the read _ time for content . Parameters : : param content : Instance of pelican . content . Content Returns : None"""
if get_class_name ( content ) in self . content_type_supported : # Exit if readtime is already set if hasattr ( content , 'readtime' ) : return None default_lang_conf = self . lang_settings [ 'default' ] lang_conf = self . lang_settings . get ( content . lang , default_lang_conf ) avg_reading_wp...
def _save_active_file ( self ) : """Saves current task information to active file . Example format : : active _ task { name " task name " ; start _ time " 2012-04-23 15:18:22 " ;"""
_parser = parser . SettingParser ( ) # add name _parser . add_option ( None , 'name' , common . to_utf8 ( self . _name ) ) # add start time start_time = self . _start_time . strftime ( '%Y-%m-%d %H:%M:%S.%f' ) _parser . add_option ( None , 'start_time' , start_time ) # write it to file return _parser . write ( self . _...
def copy_data_in_redis ( self , redis_prefix , redis_instance ) : """Copy the complete lookup data into redis . Old data will be overwritten . Args : redis _ prefix ( str ) : Prefix to distinguish the data in redis for the different looktypes redis _ instance ( str ) : an Instance of Redis Returns : bool ...
if redis_instance is not None : self . _redis = redis_instance if self . _redis is None : raise AttributeError ( "redis_instance is missing" ) if redis_prefix is None : raise KeyError ( "redis_prefix is missing" ) if self . _lookuptype == "clublogxml" or self . _lookuptype == "countryfile" : self . _pus...
def character_copy ( self , char ) : """Return a dictionary describing character ` ` char ` ` ."""
ret = self . character_stat_copy ( char ) chara = self . _real . character [ char ] nv = self . character_nodes_stat_copy ( char ) if nv : ret [ 'node_val' ] = nv ev = self . character_portals_stat_copy ( char ) if ev : ret [ 'edge_val' ] = ev avs = self . character_avatars_copy ( char ) if avs : ret [ 'ava...
def _get_current_output ( self ) : """Get child modules output ."""
output = [ ] for item in self . items : out = self . py3 . get_output ( item ) if out and "separator" not in out [ - 1 ] : out [ - 1 ] [ "separator" ] = True output += out return output
def FindClassIdInMoMetaIgnoreCase ( classId ) : """Methods whether classId is valid or not . Given class is case insensitive ."""
if not classId : return None if classId in _ManagedObjectMeta : return classId lClassId = classId . lower ( ) for key in _ManagedObjectMeta . keys ( ) : if ( key . lower ( ) == lClassId ) : return key return None
def wr_header_file ( self , write_fields , write_dir ) : """Write a header file using the specified fields"""
# Create record specification line record_line = '' # Traverse the ordered dictionary for field in RECORD_SPECS . index : # If the field is being used , add it with its delimiter if field in write_fields : record_line += RECORD_SPECS . loc [ field , 'delimiter' ] + str ( getattr ( self , field ) ) header_li...
def run ( self , data_service , project_file ) : """Attach a remote file to activity with used relationship . : param data _ service : DataServiceApi : service used to attach relationship : param project _ file : ProjectFile : contains details about a file we will attach"""
remote_path = project_file . path file_dict = data_service . get_file ( project_file . id ) . json ( ) file_version_id = file_dict [ 'current_version' ] [ 'id' ] data_service . create_used_relation ( self . activity . id , KindType . file_str , file_version_id ) self . activity . remote_path_to_file_version_id [ remote...
def matches_truth ( call_alleles , truth_alleles , data ) : """Flexibly check if truth and call alleles match , using p - groups ."""
if not truth_alleles : return "" else : def _remove_p ( x ) : return x [ : - 1 ] if x . endswith ( "P" ) else x t_cmp = set ( [ _remove_p ( hla_groups . hla_protein ( x , data ) ) for x in truth_alleles ] ) c_cmp = set ( [ _remove_p ( hla_groups . hla_protein ( x , data ) ) for x in call_alleles...
def enclosing_frame ( frame = None , level = 2 ) : """Get an enclosing frame that skips decorator code"""
frame = frame or sys . _getframe ( level ) while frame . f_globals . get ( '__name__' ) == __name__ : frame = frame . f_back return frame
def read ( self , config_dir = None , config_name = None , clear = False ) : """read config from config _ dir if config _ dir is None , clear to default config clear will clear to default before reading new file"""
# TODO should probably allow config _ dir to be a list as well # get name of config directory if not config_dir : config_dir = self . _defaults . get ( 'config_dir' , None ) if not config_dir : raise KeyError ( 'config_dir not set' ) # get name of config file if not config_name : config_name = self . _defau...
def get ( self , index , feature = None , params = None ) : """The get index API allows to retrieve information about one or more indexes . ` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / indices - get - index . html > ` _ : arg index : A comma - separated list of index na...
if index in SKIP_IN_PATH : raise ValueError ( "Empty value passed for a required argument 'index'." ) return self . transport . perform_request ( "GET" , _make_path ( index , feature ) , params = params )
def get_hook_model ( ) : """Returns the Custom Hook model if defined in settings , otherwise the default Hook model ."""
from rest_hooks . models import Hook HookModel = Hook if getattr ( settings , 'HOOK_CUSTOM_MODEL' , None ) : HookModel = get_module ( settings . HOOK_CUSTOM_MODEL ) return HookModel
def draw_rect ( self , x : int , y : int , width : int , height : int , ch : int , fg : Optional [ Tuple [ int , int , int ] ] = None , bg : Optional [ Tuple [ int , int , int ] ] = None , bg_blend : int = tcod . constants . BKGND_SET , ) -> None : """Draw characters and colors over a rectangular region . ` x ` a...
x , y = self . _pythonic_index ( x , y ) lib . draw_rect ( self . console_c , x , y , width , height , ch , ( fg , ) if fg is not None else ffi . NULL , ( bg , ) if bg is not None else ffi . NULL , bg_blend , )
def dataverse_download_doi ( doi , local_fname = None , file_requirements = { } , clobber = False ) : """Downloads a file from the Dataverse , using a DOI and set of metadata parameters to locate the file . Args : doi ( str ) : Digital Object Identifier ( DOI ) containing the file . local _ fname ( Optional...
metadata = dataverse_search_doi ( doi ) def requirements_match ( metadata ) : for key in file_requirements . keys ( ) : if metadata [ 'dataFile' ] . get ( key , None ) != file_requirements [ key ] : return False return True for file_metadata in metadata [ 'data' ] [ 'latestVersion' ] [ 'file...
def images ( self ) : """Return a list of MediaImage objects for this media ."""
return [ MediaImage ( item . get ( 'url' ) , item . get ( 'height' ) , item . get ( 'width' ) ) for item in self . media_metadata . get ( 'images' , [ ] ) ]
def parse ( payload , candidate_classes ) : """Parse a json response into an intent . : param payload : a JSON object representing an intent . : param candidate _ classes : a list of classes representing various intents , each having their own ` parse ` method to attempt parsing the JSON object into the g...
for cls in candidate_classes : intent = cls . parse ( payload ) if intent : return intent return None
def display ( self , cutout , use_pixel_coords = False ) : """: param cutout : source cutout object to be display : type cutout : source . SourceCutout"""
logging . debug ( "Current display list contains: {}" . format ( self . _displayables_by_cutout . keys ( ) ) ) logging . debug ( "Looking for {}" . format ( cutout ) ) assert isinstance ( cutout , SourceCutout ) if cutout in self . _displayables_by_cutout : displayable = self . _displayables_by_cutout [ cutout ] el...
def encrypt_ascii ( self , data , key = None , v = None , extra_bytes = 0 , digest = "hex" ) : """Encrypt data and return as ascii string . Hexadecimal digest as default . Avaiable digests : hex : Hexadecimal base64 : Base 64 hqx : hexbin4"""
digests = { "hex" : binascii . b2a_hex , "base64" : binascii . b2a_base64 , "hqx" : binascii . b2a_hqx } digestor = digests . get ( digest ) if not digestor : TripleSecError ( u"Digestor not supported." ) binary_result = self . encrypt ( data , key , v , extra_bytes ) result = digestor ( binary_result ) return resu...
def _threeDdot_simple ( M , a ) : "Return Ma , where M is a 3x3 transformation matrix , for each pixel"
result = np . empty ( a . shape , dtype = a . dtype ) for i in range ( a . shape [ 0 ] ) : for j in range ( a . shape [ 1 ] ) : A = np . array ( [ a [ i , j , 0 ] , a [ i , j , 1 ] , a [ i , j , 2 ] ] ) . reshape ( ( 3 , 1 ) ) L = np . dot ( M , A ) result [ i , j , 0 ] = L [ 0 ] res...
def fishqq ( lon = None , lat = None , di_block = None ) : """Test whether a distribution is Fisherian and make a corresponding Q - Q plot . The Q - Q plot shows the data plotted against the value expected from a Fisher distribution . The first plot is the uniform plot which is the Fisher model distribution i...
if di_block is None : all_dirs = make_di_block ( lon , lat ) else : all_dirs = di_block ppars = pmag . doprinc ( all_dirs ) # get principal directions rDIs = [ ] nDIs = [ ] QQ_dict1 = { } QQ_dict2 = { } for rec in all_dirs : angle = pmag . angle ( [ rec [ 0 ] , rec [ 1 ] ] , [ ppars [ 'dec' ] , ppars [ 'inc...
def displayplot ( data , plinds , plottype , scaling , fileroot , url_path = 'http://www.aoc.nrao.edu/~claw/plots' ) : """Generate interactive plot"""
plotdict = { 'dmt' : plotdmt , 'norm' : plotnorm , 'loc' : plotloc , 'stat' : plotstat , 'all' : plotall } sizedict = { 'dmt' : [ 900 , 500 ] , 'norm' : [ 700 , 700 ] , 'loc' : [ 700 , 700 ] , 'stat' : [ 700 , 700 ] } sortinds = sorted ( set ( plinds [ 'cir' ] + plinds [ 'cro' ] + plinds [ 'edg' ] ) ) sizesrc , plaw = ...
def describe_availability_zones ( self , xml_bytes ) : """Parse the XML returned by the C { DescribeAvailibilityZones } function . @ param xml _ bytes : XML bytes with a C { DescribeAvailibilityZonesResponse } root element . @ return : a C { list } of L { AvailabilityZone } . TODO : regionName , messageSet"...
results = [ ] root = XML ( xml_bytes ) for zone_data in root . find ( "availabilityZoneInfo" ) : zone_name = zone_data . findtext ( "zoneName" ) zone_state = zone_data . findtext ( "zoneState" ) results . append ( model . AvailabilityZone ( zone_name , zone_state ) ) return results
def browse ( self , endpoint = "hot" , category_path = "" , seed = "" , q = "" , timerange = "24hr" , tag = "" , offset = 0 , limit = 10 ) : """Fetch deviations from public endpoints : param endpoint : The endpoint from which the deviations will be fetched ( hot / morelikethis / newest / undiscovered / popular / ...
if endpoint == "hot" : response = self . _req ( '/browse/hot' , { "category_path" : category_path , "offset" : offset , "limit" : limit } ) elif endpoint == "morelikethis" : if seed : response = self . _req ( '/browse/morelikethis' , { "seed" : seed , "category_path" : category_path , "offset" : offset ...
def convert ( self , value ) : """Convert self value ."""
try : return convert_to_format ( value , self . _format ) except ( ValueError , TypeError ) : return value
def read_calibration ( detx = None , det_id = None , from_file = False , det_id_table = None ) : """Retrive calibration from file , the DB ."""
from km3pipe . calib import Calibration # noqa if not ( detx or det_id or from_file ) : return None if detx is not None : return Calibration ( filename = detx ) if from_file : det_ids = np . unique ( det_id_table ) if len ( det_ids ) > 1 : log . critical ( "Multiple detector IDs found in events....
def create_strategy ( name = None ) : """Create a strategy , or just returns it if it ' s already one . : param name : : return : Strategy"""
import logging from bonobo . execution . strategies . base import Strategy if isinstance ( name , Strategy ) : return name if name is None : name = DEFAULT_STRATEGY logging . debug ( "Creating execution strategy {!r}..." . format ( name ) ) try : factory = STRATEGIES [ name ] except KeyError as exc : ra...
def _select_helper ( args , kwargs ) : """Allow flexible selector syntax . Returns : dict"""
if len ( args ) > 1 : raise TypeError ( "select accepts at most ONE positional argument." ) if len ( args ) > 0 and len ( kwargs ) > 0 : raise TypeError ( "select accepts EITHER a positional argument, OR keyword arguments (not both)." ) if len ( args ) == 0 and len ( kwargs ) == 0 : raise TypeError ( "selec...
def all ( self ) : """Return a dictionary containing all preferences by section Loaded from cache or from db in case of cold cache"""
if not preferences_settings . ENABLE_CACHE : return self . load_from_db ( ) preferences = self . registry . preferences ( ) # first we hit the cache once for all existing preferences a = self . many_from_cache ( preferences ) if len ( a ) == len ( preferences ) : return a # avoid database hit if not necessary #...
def login ( self , username , password = None , blob = None , zeroconf = None ) : """Authenticate to Spotify ' s servers . You can login with one of three combinations : - ` ` username ` ` and ` ` password ` ` - ` ` username ` ` and ` ` blob ` ` - ` ` username ` ` and ` ` zeroconf ` ` To get the ` ` blob ...
username = utils . to_char ( username ) if password is not None : password = utils . to_char ( password ) spotifyconnect . Error . maybe_raise ( lib . SpConnectionLoginPassword ( username , password ) ) elif blob is not None : blob = utils . to_char ( blob ) spotifyconnect . Error . maybe_raise ( lib . ...
def set_url ( self , url ) : """Sets the url . arg : url ( string ) : the new copyright raise : InvalidArgument - ` ` url ` ` is invalid raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` raise : NullArgument - ` ` url ` ` is ` ` null ` ` * compliance : mandatory - - This method must be ...
# Implemented from template for osid . repository . AssetContentForm . set _ url _ template if self . get_url_metadata ( ) . is_read_only ( ) : raise errors . NoAccess ( ) if not self . _is_valid_string ( url , self . get_url_metadata ( ) ) : raise errors . InvalidArgument ( ) self . _my_map [ 'url' ] = url
def in_memory ( self ) : """: return : True if self is in a global memory of annotations ."""
self_class = self . __class__ # check if self class is in global memory memory = Annotation . __ANNOTATIONS_IN_MEMORY__ . get ( self_class , ( ) ) # check if self is in memory result = self in memory return result
def map_get ( self , key , mapkey ) : """Retrieve a value from a map . : param str key : The document ID : param str mapkey : Key within the map to retrieve : return : : class : ` ~ . ValueResult ` : raise : : exc : ` IndexError ` if the mapkey does not exist : raise : : cb _ exc : ` NotFoundError ` if th...
op = SD . get ( mapkey ) sdres = self . lookup_in ( key , op ) return self . _wrap_dsop ( sdres , True )
def parametererror ( self ) : """Return the first parameter error , or False if there is none"""
for parametergroup , parameters in self . parameters : # pylint : disable = unused - variable for parameter in parameters : if parameter . error : return parameter . error return False
def write_hash_file_for_path ( path , recompute = False ) : r"""Creates a hash file for each file in a path CommandLine : python - m utool . util _ hash - - test - write _ hash _ file _ for _ path Example : > > > # DISABLE _ DOCTEST > > > import os > > > import utool as ut > > > from utool . util _ ha...
hash_fpath_list = [ ] for root , dname_list , fname_list in os . walk ( path ) : for fname in sorted ( fname_list ) : # fpath = os . path . join ( path , fname ) fpath = os . path . join ( root , fname ) hash_fpath = write_hash_file ( fpath , recompute = recompute ) if hash_fpath is not None...
def set ( self , keyword , default , from_env = True ) : """Set value on self if not already set . If unset , attempt to retrieve from environment variable of same name ( unless disabled via ' from _ env ' ) . If ' default ' value is not a string , evaluate environment variable as a Python type . If no env va...
env_key = '{}{}' . format ( self . ENV_PREFIX , keyword . upper ( ) ) if hasattr ( self , keyword ) : return getattr ( self , keyword ) value = default if from_env and ( env_key in env ) : env_val = env . get ( env_key ) should_eval = not isinstance ( default , str ) try : value = literal_eval (...
def parse_ids ( self , skiprecover ) : '''IDS file has a list of contigs that need to be ordered . ' recover ' , keyword , if available in the third column , is less confident . tig00015093 46912 tig00035238 46779 recover tig00030900 119291'''
idsfile = self . idsfile logging . debug ( "Parse idsfile `{}`" . format ( idsfile ) ) fp = open ( idsfile ) tigs = [ ] for row in fp : if row [ 0 ] == '#' : # Header continue atoms = row . split ( ) tig , size = atoms [ : 2 ] size = int ( size ) if skiprecover and len ( atoms ) == 3 and ato...
def sweepCrossValidation ( self ) : """sweepCrossValidation ( ) will go through each of the crossvalidation input / targets . The crossValidationCorpus is a list of dictionaries of input / targets referenced by layername . Example : ( { " input " : [ 0.0 , 0.1 ] , " output " : [ 1.0 ] } , { " input " : [ 0.5 ...
# get learning value and then turn it off oldLearning = self . learning self . learning = 0 tssError = 0.0 ; totalCorrect = 0 ; totalCount = 0 ; totalPCorrect = { } self . _cv = True # in cross validation if self . autoCrossValidation : for i in range ( len ( self . inputs ) ) : set = self . getDataCrossVal...
def gload ( smatch , gpaths = None , glabels = None , filt = None , reducel = False , remove_underscore = True , clear = True , single = True , reshape = RESHAPE_DEFAULT , idxlower = True , returnfirst = False , lowercase = True , lamb = None , verbose = True , idval = None ) : """Loads into global namespace the sy...
# Normalize the match string for symbols if smatch [ 0 ] == '@' : returnfirst = True smatch = smatch [ 1 : ] smatch = expandmatch ( smatch ) # Build gdxobj list and if isinstance ( gpaths , list ) and isinstance ( gpaths [ 0 ] , GdxFile ) : gpaths = [ g . internal_filename for g in gpaths ] gdxobjs = gp...
def latlon ( location , throttle = 0.5 , center = True , round_digits = 2 ) : '''Look up the latitude / longitude coordinates of a given location using the Google Maps API . The result is cached to avoid redundant API requests . throttle : send at most one request in this many seconds center : return the cent...
global last_read if isinstance ( location , list ) : return map ( lambda x : latlon ( x , throttle = throttle , center = center , round_digits = round_digits ) , location ) if location in _latlons : result = _latlons [ location ] if center : lat1 , lon1 , lat2 , lon2 = result result = ( lat1...
def add_log_type ( self , logType , name = None , level = 0 , stdoutFlag = None , fileFlag = None , color = None , highlight = None , attributes = None ) : """Add a new logtype . : Parameters : # . logType ( string ) : The logtype . # . name ( None , string ) : The logtype name . If None , name will be set to...
# check logType assert logType not in self . __logTypeStdoutFlags . keys ( ) , "logType '%s' already defined" % logType assert isinstance ( logType , basestring ) , "logType must be a string" logType = str ( logType ) # set log type self . __set_log_type ( logType = logType , name = name , level = level , stdoutFlag = ...
def record2marcxml ( record ) : """Convert a JSON record to a MARCXML string . Deduces which set of rules to use by parsing the ` ` $ schema ` ` key , as it unequivocally determines which kind of record we have . Args : record ( dict ) : a JSON record . Returns : str : a MARCXML string converted from th...
schema_name = _get_schema_name ( record ) if schema_name == 'hep' : marcjson = hep2marc . do ( record ) elif schema_name == 'authors' : marcjson = hepnames2marc . do ( record ) else : raise NotImplementedError ( u'JSON -> MARC rules missing for "{}"' . format ( schema_name ) ) record = RECORD ( ) for key , ...
def events_view ( request ) : """Events homepage . Shows a list of events occurring in the next week , month , and future ."""
is_events_admin = request . user . has_admin_permission ( 'events' ) if request . method == "POST" : if "approve" in request . POST and is_events_admin : event_id = request . POST . get ( 'approve' ) event = get_object_or_404 ( Event , id = event_id ) event . rejected = False event ....
def selected_value ( self , layer_purpose_key ) : """Obtain selected hazard or exposure . : param layer _ purpose _ key : A layer purpose key , can be hazard or exposure . : type layer _ purpose _ key : str : returns : A selected hazard or exposure definition . : rtype : dict"""
if layer_purpose_key == layer_purpose_exposure [ 'key' ] : role = RoleExposureConstraint elif layer_purpose_key == layer_purpose_hazard [ 'key' ] : role = RoleHazardConstraint else : return None selected = self . tblFunctions2 . selectedItems ( ) if len ( selected ) != 1 : return None try : return s...
def remove_description_by_type ( self , type_p ) : """Delete all records which are equal to the passed type from the list in type _ p of type : class : ` VirtualSystemDescriptionType `"""
if not isinstance ( type_p , VirtualSystemDescriptionType ) : raise TypeError ( "type_p can only be an instance of type VirtualSystemDescriptionType" ) self . _call ( "removeDescriptionByType" , in_p = [ type_p ] )
def lasso_regression ( self ) : """Lasso Regression . This function runs lasso regression and stores the , 1 . Model 2 . Model name 3 . Max score 4 . Metrics"""
score_list = [ ] max_score = float ( '-inf' ) best_alpha = None for alpha in self . alphas : # model = Lasso ( normalize = True , alpha = alpha , max _ iter = 5000) model = Lasso ( alpha = alpha , max_iter = 5000 ) model . fit ( self . baseline_in , self . baseline_out . values . ravel ( ) ) scores = [ ] ...
def get_devices ( self ) : """Get the list of all known devices ."""
devices = [ ] for element in self . get_device_elements ( ) : device = FritzhomeDevice ( self , node = element ) devices . append ( device ) return devices
def find_all_headers ( pipeline_files = [ ] , label_rules = None ) : """find _ all _ headers : param pipeline _ files : files to process : param label _ rules : labeling rules"""
log . info ( "find_all_headers - START" ) headers = [ "src_file" ] headers_dict = { "src_file" : None } if label_rules : headers = [ "src_file" , "label_value" , "label_name" ] headers_dict = { "src_file" : None , "label_value" : None , "label_name" : None } for c in pipeline_files : df = pd . read_csv ( c ...
def _len_list ( obj ) : '''Length of list ( estimate ) .'''
n = len ( obj ) # estimate over - allocation if n > 8 : n += 6 + ( n >> 3 ) elif n : n += 4 return n
def _key ( self , block , name ) : """Resolves ` name ` to a key , in the following form : KeyValueStore . Key ( scope = field . scope , user _ id = student _ id , block _ scope _ id = block _ id , field _ name = name , block _ family = block . entry _ point ,"""
field = self . _getfield ( block , name ) if field . scope in ( Scope . children , Scope . parent ) : block_id = block . scope_ids . usage_id user_id = None else : block_scope = field . scope . block if block_scope == BlockScope . ALL : block_id = None elif block_scope == BlockScope . USAGE ...
def read_tracers_h5 ( xdmf_file , infoname , snapshot , position ) : """Extract tracers data from hdf5 files . Args : xdmf _ file ( : class : ` pathlib . Path ` ) : path of the xdmf file . infoname ( str ) : name of information to extract . snapshot ( int ) : snapshot number . position ( bool ) : whether ...
xdmf_root = xmlET . parse ( str ( xdmf_file ) ) . getroot ( ) tra = { } tra [ infoname ] = [ { } , { } ] # two blocks , ordered by cores if position : for axis in 'xyz' : tra [ axis ] = [ { } , { } ] for elt_subdomain in xdmf_root [ 0 ] [ 0 ] [ snapshot ] . findall ( 'Grid' ) : ibk = int ( elt_subdomain...
def _is_request_in_exclude_path ( self , request ) : """Check if the request path is in the ` _ exclude _ paths ` list"""
if self . _exclude_paths : for path in self . _exclude_paths : if request . path . startswith ( path ) : return True return False else : return False
def add ( self , properties ) : """Add a faked Virtual Function resource . Parameters : properties ( dict ) : Resource properties . Special handling and requirements for certain properties : * ' element - id ' will be auto - generated with a unique value across all instances of this resource type , if n...
new_vf = super ( FakedVirtualFunctionManager , self ) . add ( properties ) partition = self . parent assert 'virtual-function-uris' in partition . properties partition . properties [ 'virtual-function-uris' ] . append ( new_vf . uri ) if 'device-number' not in new_vf . properties : devno = partition . devno_alloc (...
def all ( self , sort = None , ** kwargs ) : """Returns a list of media from this library section . Parameters : sort ( string ) : The sort string"""
sortStr = '' if sort is not None : sortStr = '?sort=' + sort key = '/library/sections/%s/all%s' % ( self . key , sortStr ) return self . fetchItems ( key , ** kwargs )
def _evaluate_tempyREPR ( self , child , repr_cls ) : """Assign a score ito a TempyRepr class . The scores depends on the current scope and position of the object in which the TempyREPR is found ."""
score = 0 if repr_cls . __name__ == self . __class__ . __name__ : # One point if the REPR have the same name of the container score += 1 elif repr_cls . __name__ == self . root . __class__ . __name__ : # One point if the REPR have the same name of the Tempy tree root score += 1 # Add points defined in scorers m...
def setup_tables ( create = True , drop = False ) : """Binds the model classes to registered metadata and engine and ( potentially ) creates the db tables . This function expects that you have bound the L { meta . metadata } and L { meta . engine } . @ param create : Whether to create the tables ( if they do ...
global frames_table frames_table = Table ( 'frames' , meta . metadata , Column ( 'message_id' , String ( 255 ) , primary_key = True ) , Column ( 'sequence' , BigInteger , primary_key = False , autoincrement = True ) , Column ( 'destination' , String ( 255 ) , index = True ) , Column ( 'frame' , PickleType ) , Column ( ...
def create_dataset_file ( root_dir , data ) : """Create a new dataset from a template ."""
file_path = os . path . join ( root_dir , '{dataset_type}' , '{dataset_name}.py' ) context = ( _HEADER + _DATASET_DEFAULT_IMPORTS + _CITATION + _DESCRIPTION + _DATASET_DEFAULTS ) with gfile . GFile ( file_path . format ( ** data ) , 'w' ) as f : f . write ( context . format ( ** data ) )
def socket_read ( fp ) : """Buffered read from socket . Reads all data available from socket . @ fp : File pointer for socket . @ return : String of characters read from buffer ."""
response = '' oldlen = 0 newlen = 0 while True : response += fp . read ( buffSize ) newlen = len ( response ) if newlen - oldlen == 0 : break else : oldlen = newlen return response
def calculateLocalElasticity ( self , bp , frames = None , helical = False , unit = 'kT' ) : r"""Calculate local elastic matrix or stiffness matrix for local DNA segment . . note : : Here local DNA segment referred to less than 5 base - pair long . In case of : ref : ` base - step - image ` : Shift ( : math : `...
acceptedUnit = [ 'kT' , 'kJ/mol' , 'kcal/mol' ] if unit not in acceptedUnit : raise ValueError ( " {0} not accepted. Use any of the following: {1} " . format ( unit , acceptedUnit ) ) frames = self . _validateFrames ( frames ) name = '{0}-{1}-{2}-{3}-local-{4}' . format ( bp [ 0 ] , bp [ 1 ] , frames [ 0 ] , frames...
def hscan ( self , name , key_start , key_end , limit = 10 ) : """Return a dict mapping key / value in the top ` ` limit ` ` keys between ` ` key _ start ` ` and ` ` key _ end ` ` within hash ` ` name ` ` in ascending order Similiar with * * Redis . HSCAN * * . . note : : The range is ( ` ` key _ start ` ` , ...
limit = get_positive_integer ( 'limit' , limit ) return self . execute_command ( 'hscan' , name , key_start , key_end , limit )
def new_media_status ( self , media_status ) : """Handle reception of a new MediaStatus ."""
casts = self . _casts group_members = self . _mz . members for member_uuid in group_members : if member_uuid not in casts : continue for listener in list ( casts [ member_uuid ] [ 'listeners' ] ) : listener . multizone_new_media_status ( self . _group_uuid , media_status )
def do_ls ( self , subcmd , opts , folder = "" ) : """$ { cmd _ name } : list messages in the specified folder $ { cmd _ usage } $ { cmd _ option _ list } SINCE can be used with epoch times , for example : md ls - s $ ( date ' + % s ' )"""
client = MdClient ( self . maildir , filesystem = self . filesystem ) client . ls ( foldername = folder , stream = self . stdout , reverse = getattr ( opts , "reverse" , False ) , grep = getattr ( opts , "grep" , None ) , field = getattr ( opts , "field" , None ) , since = float ( getattr ( opts , "since" , - 1 ) ) )
def _change ( self , changes ) : """Apply the given changes to the board . changes : sequence of ( position , new tile ) pairs or None"""
if changes is None : return for position , new_tile in changes : self . _array [ position ] = new_tile
def _globals ( self ) : """Returns the globals needed for eval ( ) statements ."""
# start with numpy globbies = dict ( _n . __dict__ ) globbies . update ( _special . __dict__ ) # update with required stuff globbies . update ( { 'h' : self . h , 'c' : self . c , 'd' : self , 'self' : self } ) # update with user stuff globbies . update ( self . extra_globals ) return globbies
def create ( cls , object_version , key , value ) : """Create a new tag for a given object version ."""
assert len ( key ) < 256 assert len ( value ) < 256 with db . session . begin_nested ( ) : obj = cls ( version_id = as_object_version_id ( object_version ) , key = key , value = value ) db . session . add ( obj ) return obj
def find_card_bundles ( provider : Provider , deck : Deck ) -> Optional [ Iterator ] : '''each blockchain transaction can contain multiple cards , wrapped in bundles . This method finds and returns those bundles .'''
if isinstance ( provider , RpcNode ) : if deck . id is None : raise Exception ( "deck.id required to listtransactions" ) p2th_account = provider . getaccount ( deck . p2th_address ) batch_data = [ ( 'getrawtransaction' , [ i [ "txid" ] , 1 ] ) for i in provider . listtransactions ( p2th_account ) ] ...
def add_folder ( self , folder ) : """Add a folder scan images there"""
if folder in self . folders : return self . folders . add ( folder ) for subfolder , junk , filenames in os . walk ( folder ) : for filename in filenames : name , ext = os . path . splitext ( filename ) if ext in self . exts : self . images . append ( os . path . join ( subfolder , f...
def km3h5concat ( input_files , output_file , n_events = None , ** kwargs ) : """Concatenate KM3HDF5 files via pipeline ."""
from km3pipe import Pipeline # noqa from km3pipe . io import HDF5Pump , HDF5Sink # noqa pipe = Pipeline ( ) pipe . attach ( HDF5Pump , filenames = input_files , ** kwargs ) pipe . attach ( StatusBar , every = 250 ) pipe . attach ( HDF5Sink , filename = output_file , ** kwargs ) pipe . drain ( n_events )
def decompress ( f ) : """Decompress a Plan 9 image file . Assumes f is already cued past the initial ' compressed \n ' string ."""
r = meta ( f . read ( 60 ) ) return r , decomprest ( f , r [ 4 ] )
def attachment_md5 ( self ) : '''Calculate the checksum of the file upload . For binary files ( e . g . PDFs ) , the MD5 of the file itself is used . Archives are unpacked and the MD5 is generated from the sanitized textfiles in the archive . This is done with some smartness : - Whitespace and tabs are remo...
MAX_MD5_FILE_SIZE = 10000 md5_set = [ ] def md5_add_text ( text ) : try : text = str ( text , errors = 'ignore' ) text = text . replace ( ' ' , '' ) . replace ( '\n' , '' ) . replace ( '\t' , '' ) hexvalues = hashlib . md5 ( text . encode ( 'utf-8' ) ) . hexdigest ( ) md5_set . appen...
def delete_job ( self , job_id ) : """Delete the given job id . The job must have been previously reserved by this connection"""
if hasattr ( job_id , 'job_id' ) : job_id = job_id . job_id with self . _sock_ctx ( ) as socket : self . _send_message ( 'delete {0}' . format ( job_id ) , socket ) self . _receive_word ( socket , b'DELETED' )