signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def to_address ( name ) : """Convert a reverse map domain name into textual address form . @ param name : an IPv4 or IPv6 address in reverse - map form . @ type name : dns . name . Name object @ rtype : str"""
if name . is_subdomain ( ipv4_reverse_domain ) : name = name . relativize ( ipv4_reverse_domain ) labels = list ( name . labels ) labels . reverse ( ) text = '.' . join ( labels ) # run through inet _ aton ( ) to check syntax and make pretty . return dns . ipv4 . inet_ntoa ( dns . ipv4 . inet_at...
def get_entries ( self , start = 0 , end = 0 , data_request = None , steam_ids = None ) : """Get leaderboard entries . : param start : start entry , not index ( e . g . rank 1 is ` ` start = 1 ` ` ) : type start : : class : ` int ` : param end : end entry , not index ( e . g . only one entry then ` ` start = ...
message = MsgProto ( EMsg . ClientLBSGetLBEntries ) message . body . app_id = self . app_id message . body . leaderboard_id = self . id message . body . range_start = start message . body . range_end = end message . body . leaderboard_data_request = self . data_request if data_request is None else data_request if steam...
def export_repos ( self , envs = [ ] ) : """Dump JuicerRepo ( ) objects for all repos in all environments . Note that this has undefined results should a repo exist with different configurations in different environments ."""
all_envs = envs juicer . utils . Log . log_notice ( "Only exporting repos in environment(s): %s" , ", " . join ( all_envs ) ) all_pulp_repo_names = self . list_repos ( envs = all_envs ) all_pulp_repo_names_uniqued = set ( ) num_repos = 0 # Track name of all processed repos . Update when we ' ve found # all environments...
def create ( self , relpath , langs , category ) : """Return a source root at the given ` relpath ` for the given ` langs ` and ` category ` . : returns : : class : ` SourceRoot ` ."""
return SourceRoot ( relpath , tuple ( self . _canonicalize_langs ( langs ) ) , category )
def _it_sol ( s_data , g_hat , d_hat , g_bar , t2 , a , b , conv = 0.0001 ) -> Tuple [ float , float ] : """Iteratively compute the conditional posterior means for gamma and delta . gamma is an estimator for the additive batch effect , deltat is an estimator for the multiplicative batch effect . We use an EB fr...
n = ( 1 - np . isnan ( s_data ) ) . sum ( axis = 1 ) g_old = g_hat . copy ( ) d_old = d_hat . copy ( ) change = 1 count = 0 # we place a normally distributed prior on gamma and and inverse gamma prior on delta # in the loop , gamma and delta are updated together . they depend on each other . we iterate until convergenc...
def close ( self ) : '''Closes the Redis Monitor and plugins'''
for plugin_key in self . plugins_dict : obj = self . plugins_dict [ plugin_key ] instance = obj [ 'instance' ] instance . close ( )
def reset ( self , total_size = None ) : """Remove all file system contents and reset the root ."""
self . root = FakeDirectory ( self . path_separator , filesystem = self ) self . cwd = self . root . name self . open_files = [ ] self . _free_fd_heap = [ ] self . _last_ino = 0 self . _last_dev = 0 self . mount_points = { } self . add_mount_point ( self . root . name , total_size ) self . _add_standard_streams ( )
def render_crispy_form ( form , helper = None , context = None ) : """Renders a form and returns its HTML output . This function wraps the template logic in a function easy to use in a Django view ."""
from crispy_forms . templatetags . crispy_forms_tags import CrispyFormNode if helper is not None : node = CrispyFormNode ( 'form' , 'helper' ) else : node = CrispyFormNode ( 'form' , None ) node_context = Context ( context ) node_context . update ( { 'form' : form , 'helper' : helper } ) return node . render ( ...
def _OnNodeInfo ( self , node_id ) : """Sets the node info based on its attributes ."""
handler , value , attrs = self . _get_handling_triplet ( node_id ) frame_color = handler . on_frame_color ( value , attrs ) node_info = idaapi . node_info_t ( ) if frame_color is not None : node_info . frame_color = frame_color flags = node_info . get_flags_for_valid ( ) self . SetNodeInfo ( node_id , node_info , f...
def is_rate_matrix ( K , tol = 1e-10 ) : """True if K is a rate matrix Parameters K : numpy . ndarray matrix Matrix to check tol : float tolerance to check with Returns Truth value : bool True , if K negated diagonal is positive and row sums up to zero . False , otherwise"""
R = K - K . diagonal ( ) off_diagonal_positive = np . allclose ( R , abs ( R ) , 0.0 , atol = tol ) row_sum = K . sum ( axis = 1 ) row_sum_eq_0 = np . allclose ( row_sum , 0.0 , atol = tol ) return off_diagonal_positive and row_sum_eq_0
def get_wrapping_class ( node ) : """Get the class that wraps the given node . We consider that a class wraps a node if the class is a parent for the said node . : returns : The class that wraps the given node : rtype : ClassDef or None"""
klass = node . frame ( ) while klass is not None and not isinstance ( klass , ClassDef ) : if klass . parent is None : klass = None else : klass = klass . parent . frame ( ) return klass
def parse_datetime ( record : str ) -> Optional [ datetime ] : """Parse a datetime string into a python datetime object"""
# NEM defines Date8 , DateTime12 and DateTime14 format_strings = { 8 : '%Y%m%d' , 12 : '%Y%m%d%H%M' , 14 : '%Y%m%d%H%M%S' } if record == '' : return None return datetime . strptime ( record . strip ( ) , format_strings [ len ( record . strip ( ) ) ] )
def from_parts ( cls , parts ) : """Return content types XML mapping each part in * parts * to the appropriate content type and suitable for storage as ` ` [ Content _ Types ] . xml ` ` in an OPC package ."""
cti = cls ( ) cti . _defaults [ 'rels' ] = CT . OPC_RELATIONSHIPS cti . _defaults [ 'xml' ] = CT . XML for part in parts : cti . _add_content_type ( part . partname , part . content_type ) return cti
def format_date ( ctx , text ) : """Takes a single parameter ( date as string ) and returns it in the format defined by the org"""
dt = conversions . to_datetime ( text , ctx ) return dt . astimezone ( ctx . timezone ) . strftime ( ctx . get_date_format ( True ) )
def _expectation ( p , mean , none1 , none2 , none3 , nghp = None ) : """Compute the expectation : < m ( X ) > _ p ( X ) - m ( x ) : : Linear , Identity or Constant mean function : return : NxQ"""
return mean ( p . mu )
def parse ( self , response ) : """Passes the response to the pipeline . : param obj response : The scrapy response"""
if not self . helper . parse_crawler . content_type ( response ) : return yield self . helper . parse_crawler . pass_to_pipeline ( response , self . helper . url_extractor . get_allowed_domain ( response . url ) )
def spkez ( targ , et , ref , abcorr , obs ) : """Return the state ( position and velocity ) of a target body relative to an observing body , optionally corrected for light time ( planetary aberration ) and stellar aberration . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / sp...
targ = ctypes . c_int ( targ ) et = ctypes . c_double ( et ) ref = stypes . stringToCharP ( ref ) abcorr = stypes . stringToCharP ( abcorr ) obs = ctypes . c_int ( obs ) starg = stypes . emptyDoubleVector ( 6 ) lt = ctypes . c_double ( ) libspice . spkez_c ( targ , et , ref , abcorr , obs , starg , ctypes . byref ( lt ...
def OpenFile ( self , filename ) : """Try to open filename in the static files directory of this server . Return a tuple ( file object , string mime _ type ) or raise an exception ."""
( mime_type , encoding ) = mimetypes . guess_type ( filename ) assert mime_type # A crude guess of when we should use binary mode . Without it non - unix # platforms may corrupt binary files . if mime_type . startswith ( 'text/' ) : mode = 'r' else : mode = 'rb' return open ( os . path . join ( self . server . ...
def parallel ( self , width , routing = Routing . ROUND_ROBIN , func = None , name = None ) : """Split stream into channels and start a parallel region . Returns a new stream that will contain the contents of this stream with tuples distributed across its channels . The returned stream starts a parallel regio...
_name = name if _name is None : _name = self . name + '_parallel' _name = self . topology . graph . _requested_name ( _name , action = 'parallel' , func = func ) if routing is None or routing == Routing . ROUND_ROBIN or routing == Routing . BROADCAST : op2 = self . topology . graph . addOperator ( "$Parallel$" ...
def obfuscate_variable ( tokens , index , replace , replacement , right_of_equal , inside_parens , inside_function ) : """If the token string inside * tokens [ index ] * matches * replace * , return * replacement * . * right _ of _ equal * , and * inside _ parens * are used to determine whether or not this toke...
def return_replacement ( replacement ) : VAR_REPLACEMENTS [ replacement ] = replace return replacement tok = tokens [ index ] token_type = tok [ 0 ] token_string = tok [ 1 ] if index > 0 : prev_tok = tokens [ index - 1 ] else : # Pretend it ' s a newline ( for simplicity ) prev_tok = ( 54 , '\n' , ( 1 ,...
async def get_gender ( self ) -> User . Gender : """Get the gender from Facebook ."""
u = await self . _get_user ( ) try : return User . Gender ( u . get ( 'gender' ) ) except ValueError : return User . Gender . unknown
def is_mac_address ( value , ** kwargs ) : """Indicate whether ` ` value ` ` is a valid MAC address . : param value : The value to evaluate . : returns : ` ` True ` ` if ` ` value ` ` is valid , ` ` False ` ` if it is not . : rtype : : class : ` bool < python : bool > ` : raises SyntaxError : if ` ` kwargs ...
try : value = validators . mac_address ( value , ** kwargs ) except SyntaxError as error : raise error except Exception : return False return True
def stop ( self ) : """Stop Modis and log it out of Discord ."""
self . button_toggle_text . set ( "Start Modis" ) self . state = "off" logger . info ( "Stopping Discord Modis" ) from . _client import client asyncio . run_coroutine_threadsafe ( client . logout ( ) , client . loop ) self . status_bar . set_status ( 0 )
def from_dict ( cls , d ) : """Construct a MSONable AdfKey object from the JSON dict . Parameters d : dict A dict of saved attributes . Returns adfkey : AdfKey An AdfKey object recovered from the JSON dict ` ` d ` ` ."""
key = d . get ( "name" ) options = d . get ( "options" , None ) subkey_list = d . get ( "subkeys" , [ ] ) if len ( subkey_list ) > 0 : subkeys = list ( map ( lambda k : AdfKey . from_dict ( k ) , subkey_list ) ) else : subkeys = None return cls ( key , options , subkeys )
def get_decoded_jwt ( request ) : """Grab jwt from jwt cookie in request if possible . Returns a decoded jwt dict if it can be found . Returns None if the jwt is not found ."""
jwt_cookie = request . COOKIES . get ( jwt_cookie_name ( ) , None ) if not jwt_cookie : return None return jwt_decode_handler ( jwt_cookie )
def re_match ( self , pattern , haystack , ** kwargs ) : """re . match py3 compat : param pattern : : param haystack : : return :"""
try : return re . match ( pattern , haystack . decode ( 'utf8' ) , ** kwargs ) except Exception as e : logger . debug ( 're.match exception: %s' % e ) self . trace_logger . log ( e )
def _create_penwidth_combo ( self ) : """Create pen width combo box"""
choices = map ( unicode , xrange ( 12 ) ) self . pen_width_combo = _widgets . PenWidthComboBox ( self , choices = choices , style = wx . CB_READONLY , size = ( 50 , - 1 ) ) self . pen_width_combo . SetToolTipString ( _ ( u"Border width" ) ) self . AddControl ( self . pen_width_combo ) self . Bind ( wx . EVT_COMBOBOX , ...
def _set_if_type ( self , v , load = False ) : """Setter method for if _ type , mapped from YANG variable / mpls _ state / dynamic _ bypass / dynamic _ bypass _ interface / if _ type ( mpls - if - type ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ if _ type is consi...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'loopback-interface' : { 'value' : 7 } , u'ethernet-interface' : { 'value' : 2 } , u'port-channel-interface' : { 'value' : 5 } ,...
def ner ( sentence , format = None ) : """Location and classify named entities in text Parameters sentence : { unicode , str } raw sentence Returns tokens : list of tuple with word , pos tag , chunking tag , ner tag tagged sentence Examples > > > # - * - coding : utf - 8 - * - > > > from underthes...
sentence = chunk ( sentence ) crf_model = CRFNERPredictor . Instance ( ) result = crf_model . predict ( sentence , format ) return result
def strduration ( duration ) : """Turn a time value in seconds into hh : mm : ss or mm : ss ."""
if duration < 0 : duration = abs ( duration ) prefix = "-" else : prefix = "" duration = math . ceil ( duration ) if duration >= SECONDS_PER_HOUR : # 1 hour # time , in hours : minutes : seconds return "%s%02d:%02d:%02d" % ( prefix , duration // SECONDS_PER_HOUR , ( duration % SECONDS_PER_HOUR ) // SECO...
def reject ( self , func ) : """: param func : : type func : ( K , T ) - > bool : rtype : TList [ T ] Usage : > > > TDict ( k1 = 1 , k2 = 2 , k3 = 3 ) . reject ( lambda k , v : v < 3)"""
return TList ( [ v for k , v in self . items ( ) if not func ( k , v ) ] )
def enqueue_command ( self , command_name , args , options ) : """Enqueue a new command into this pipeline ."""
assert_open ( self ) promise = Promise ( ) self . commands . append ( ( command_name , args , options , promise ) ) return promise
def to_capitalized_camel_case ( snake_case_string ) : """Convert a string from snake case to camel case with the first letter capitalized . For example , " some _ var " would become " SomeVar " . : param snake _ case _ string : Snake - cased string to convert to camel case . : returns : Camel - cased version ...
parts = snake_case_string . split ( '_' ) return '' . join ( [ i . title ( ) for i in parts ] )
def collapse_address_list ( addresses ) : """Collapse a list of IP objects . Example : collapse _ address _ list ( [ IPv4 ( ' 1.1.0.0/24 ' ) , IPv4 ( ' 1.1.1.0/24 ' ) ] ) - > [ IPv4 ( ' 1.1.0.0/23 ' ) ] Args : addresses : A list of IPv4Network or IPv6Network objects . Returns : A list of IPv4Network o...
i = 0 addrs = [ ] ips = [ ] nets = [ ] # split IP addresses and networks for ip in addresses : if isinstance ( ip , _BaseIP ) : if ips and ips [ - 1 ] . _version != ip . _version : raise TypeError ( "%s and %s are not of the same version" % ( str ( ip ) , str ( ips [ - 1 ] ) ) ) ips . ap...
def delete_deployment_group ( self , project , deployment_group_id ) : """DeleteDeploymentGroup . [ Preview API ] Delete a deployment group . : param str project : Project ID or project name : param int deployment _ group _ id : ID of the deployment group to be deleted ."""
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if deployment_group_id is not None : route_values [ 'deploymentGroupId' ] = self . _serialize . url ( 'deployment_group_id' , deployment_group_id , 'int' ) self . _send ( http_method ...
def _propertiesOrClustersForSequence ( sequence , propertyNames , propertyValues , missingAAValue ) : """Extract amino acid property values or cluster numbers for a sequence . @ param sequence : An C { AARead } ( or a subclass ) instance . @ param propertyNames : An iterable of C { str } property names ( each o...
propertyNames = sorted ( map ( str . lower , set ( propertyNames ) ) ) # Make sure all mentioned property names exist for at least one AA . knownProperties = set ( ) for names in propertyValues . values ( ) : knownProperties . update ( names ) unknown = set ( propertyNames ) - knownProperties if unknown : raise...
def has_fingerprint_dlog ( self , modulus ) : """Exact fingerprint using mathematical structure of the primes : param modulus : : return :"""
if not self . is_acceptable_modulus ( modulus ) : return False self . tested += 1 positive = self . dlog_fprinter . fprint ( modulus ) if positive : self . found += 1 return positive
def get_document_type ( self , ehr_username , doc_type ) : """invokes TouchWorksMagicConstants . ACTION _ GET _ DOCUMENT _ TYPE action : return : JSON response"""
magic = self . _magic_json ( action = TouchWorksMagicConstants . ACTION_GET_DOCUMENT_TYPE , app_name = self . _app_name , user_id = ehr_username , token = self . _token . token , parameter1 = doc_type ) response = self . _http_request ( TouchWorksEndPoints . MAGIC_JSON , data = magic ) result = self . _get_results_or_r...
def fit ( self , x0 = None , distribution = 'lognormal' , n = None , ** kwargs ) : '''Incomplete method to fit experimental values to a curve . It is very hard to get good initial guesses , which are really required for this . Differential evolution is promissing . This API is likely to change in the future ....
dist = { 'lognormal' : PSDLognormal , 'GGS' : PSDGatesGaudinSchuhman , 'RR' : PSDRosinRammler } [ distribution ] if distribution == 'lognormal' : if x0 is None : d_characteristic = sum ( [ fi * di for fi , di in zip ( self . fractions , self . Dis ) ] ) s = 0.4 x0 = [ d_characteristic , s ] ...
def _retrieve_assets ( self , sids , asset_tbl , asset_type ) : """Internal function for loading assets from a table . This should be the only method of ` AssetFinder ` that writes Assets into self . _ asset _ cache . Parameters sids : iterable of int Asset ids to look up . asset _ tbl : sqlalchemy . Ta...
# Fastpath for empty request . if not sids : return { } cache = self . _asset_cache hits = { } querying_equities = issubclass ( asset_type , Equity ) filter_kwargs = ( _filter_equity_kwargs if querying_equities else _filter_future_kwargs ) rows = self . _retrieve_asset_dicts ( sids , asset_tbl , querying_equities )...
def validated_url ( url ) : """Return url if valid , raise URLError otherwise"""
try : u = urlparse ( url ) u . port # Trigger ' invalid port ' exception except Exception : raise error . URLError ( url ) else : if not u . scheme or not u . netloc : raise error . URLError ( url ) return url
def _finish_task_processing ( self , queue , task , success ) : """After a task is executed , this method is called and ensures that the task gets properly removed from the ACTIVE queue and , in case of an error , retried or marked as failed ."""
log = self . log . bind ( queue = queue , task_id = task . id ) def _mark_done ( ) : # Remove the task from active queue task . _move ( from_state = ACTIVE ) log . info ( 'done' ) if success : _mark_done ( ) else : should_retry = False should_log_error = True # Get execution info ( for logging a...
def _get_versions ( config = None ) : """Retrieve details on all programs available on the system ."""
try : from bcbio . pipeline import version if hasattr ( version , "__version__" ) : bcbio_version = ( "%s-%s" % ( version . __version__ , version . __git_revision__ ) if version . __git_revision__ else version . __version__ ) else : bcbio_version = "" except ImportError : bcbio_version =...
def optical_flow_rad_send ( self , time_usec , sensor_id , integration_time_us , integrated_x , integrated_y , integrated_xgyro , integrated_ygyro , integrated_zgyro , temperature , quality , time_delta_distance_us , distance , force_mavlink1 = False ) : '''Optical flow from an angular rate flow sensor ( e . g . PX...
return self . send ( self . optical_flow_rad_encode ( time_usec , sensor_id , integration_time_us , integrated_x , integrated_y , integrated_xgyro , integrated_ygyro , integrated_zgyro , temperature , quality , time_delta_distance_us , distance ) , force_mavlink1 = force_mavlink1 )
def detectType ( option , urlOrPaths , serverEndpoint = ServerEndpoint , verbose = Verbose , tikaServerJar = TikaServerJar , responseMimeType = 'text/plain' , services = { 'type' : '/detect/stream' } ) : '''Detect the MIME / media type of the stream and return it in text / plain . : param option : : param urlOr...
paths = getPaths ( urlOrPaths ) return [ detectType1 ( option , path , serverEndpoint , verbose , tikaServerJar , responseMimeType , services ) for path in paths ]
def get_strain_state_dict ( strains , stresses , eq_stress = None , tol = 1e-10 , add_eq = True , sort = True ) : """Creates a dictionary of voigt - notation stress - strain sets keyed by " strain state " , i . e . a tuple corresponding to the non - zero entries in ratios to the lowest nonzero value , e . g ....
# Recast stress / strains vstrains = np . array ( [ Strain ( s ) . zeroed ( tol ) . voigt for s in strains ] ) vstresses = np . array ( [ Stress ( s ) . zeroed ( tol ) . voigt for s in stresses ] ) # Collect independent strain states : independent = set ( [ tuple ( np . nonzero ( vstrain ) [ 0 ] . tolist ( ) ) for vstr...
def tobytes ( self , prim , skipprepack = False ) : '''Compatible to Parser . tobytes ( )'''
stream = BytesIO ( ) self . tostream ( prim , stream , skipprepack = skipprepack ) return stream . getvalue ( )
def iter_get ( self , name = None , group = None , index = None , raster = None , samples_only = False , raw = False , ) : """iterator over a channel This is usefull in case of large files with a small number of channels . If the * raster * keyword argument is not * None * the output is interpolated according...
gp_nr , ch_nr = self . _validate_channel_selection ( name , group , index ) grp = self . groups [ gp_nr ] data = self . _load_data ( grp ) for fragment in data : yield self . get ( group = gp_nr , index = ch_nr , raster = raster , samples_only = samples_only , data = fragment , raw = raw , )
def weekdays ( self ) : """Returns the number of weekdays this item has . : return < int >"""
if self . itemStyle ( ) == self . ItemStyle . Group : out = 0 for i in range ( self . childCount ( ) ) : out += self . child ( i ) . weekdays ( ) return out else : dstart = self . dateStart ( ) . toPyDate ( ) dend = self . dateEnd ( ) . toPyDate ( ) return projex . dates . weekdays ( dst...
def lat_lon_grid_deltas ( longitude , latitude , ** kwargs ) : r"""Calculate the delta between grid points that are in a latitude / longitude format . Calculate the signed delta distance between grid points when the grid spacing is defined by delta lat / lon rather than delta x / y Parameters longitude : ar...
from pyproj import Geod # Inputs must be the same number of dimensions if latitude . ndim != longitude . ndim : raise ValueError ( 'Latitude and longitude must have the same number of dimensions.' ) # If we were given 1D arrays , make a mesh grid if latitude . ndim < 2 : longitude , latitude = np . meshgrid ( l...
def completer_tokenize ( cls , value , min_length = 3 ) : '''Quick and dirty tokenizer for completion suggester'''
tokens = list ( itertools . chain ( * [ [ m for m in n . split ( "'" ) if len ( m ) > min_length ] for n in value . split ( ' ' ) ] ) ) return list ( set ( [ value ] + tokens + [ ' ' . join ( tokens ) ] ) )
def count_hom ( self , allele = None , axis = None ) : """Count homozygous genotypes . Parameters allele : int , optional Allele index . axis : int , optional Axis over which to count , or None to perform overall count ."""
b = self . is_hom ( allele = allele ) return np . sum ( b , axis = axis )
def keep_high_angle ( vertices , min_angle_deg ) : """Keep vertices with angles higher then given minimum ."""
accepted = [ ] v = vertices v1 = v [ 1 ] - v [ 0 ] accepted . append ( ( v [ 0 ] [ 0 ] , v [ 0 ] [ 1 ] ) ) for i in range ( 1 , len ( v ) - 2 ) : v2 = v [ i + 1 ] - v [ i - 1 ] diff_angle = np . fabs ( angle ( v1 , v2 ) * 180.0 / np . pi ) if diff_angle > min_angle_deg : accepted . append ( ( v [ i ...
def _list_superclasses ( class_def ) : """Return a list of the superclasses of the given class"""
superclasses = class_def . get ( 'superClasses' , [ ] ) if superclasses : # Make sure to duplicate the list return list ( superclasses ) sup = class_def . get ( 'superClass' , None ) if sup : return [ sup ] else : return [ ]
def genes_with_structures ( self ) : """DictList : All genes with any mapped protein structures ."""
return DictList ( x for x in self . genes if x . protein . num_structures > 0 )
def SDAVG ( self , days = 45 ) : """the last 45 days average . 計算 days 日內之平均數 , 預設 45 日"""
if len ( self . raw_data ) >= days : data = self . raw_data [ - days : ] data_avg = float ( sum ( data ) / days ) return data_avg else : return 0
def share ( self , project , to_user , force_send , auth_role , user_message ) : """Send mail and give user specified access to the project . : param project : RemoteProject project to share : param to _ user : RemoteUser user to receive email / access : param auth _ role : str project role eg ' project _ adm...
if self . _is_current_user ( to_user ) : raise ShareWithSelfError ( SHARE_WITH_SELF_MESSAGE . format ( "share" ) ) if not to_user . email : self . _raise_user_missing_email_exception ( "share" ) self . set_user_project_permission ( project , to_user , auth_role ) return self . _share_project ( D4S2Api . SHARE_D...
def set_combiner ( value , mutator , * args , ** kwargs ) : """Expects the output of the source to be a set to which the result of each mutator is added ."""
value . add ( mutator ( * args , ** kwargs ) ) return value
def makeMany2ManyRelatedManager ( formodel , name_relmodel , name_formodel ) : '''formodel is the model which the manager .'''
class _Many2ManyRelatedManager ( Many2ManyRelatedManager ) : pass _Many2ManyRelatedManager . formodel = formodel _Many2ManyRelatedManager . name_relmodel = name_relmodel _Many2ManyRelatedManager . name_formodel = name_formodel return _Many2ManyRelatedManager
def render ( self , fname = '' ) : """Render the circuit expression and store the result in a file Args : fname ( str ) : Path to an image file to store the result in . Returns : str : The path to the image file"""
import qnet . visualization . circuit_pyx as circuit_visualization from tempfile import gettempdir from time import time , sleep if not fname : tmp_dir = gettempdir ( ) fname = os . path . join ( tmp_dir , "tmp_{}.png" . format ( hash ( time ) ) ) if circuit_visualization . draw_circuit ( self , fname ) : d...
def get_all_dict ( module ) : """Return a copy of the _ _ all _ _ dict with irrelevant items removed ."""
if hasattr ( module , "__all__" ) : all_dict = copy . deepcopy ( module . __all__ ) else : all_dict = copy . deepcopy ( dir ( module ) ) all_dict = [ name for name in all_dict if not name . startswith ( "_" ) ] for name in [ 'absolute_import' , 'division' , 'print_function' ] : try : all_dict . ...
def host_resolution_order ( ifo , env = 'NDSSERVER' , epoch = 'now' , lookback = 14 * 86400 ) : """Generate a logical ordering of NDS ( host , port ) tuples for this IFO Parameters ifo : ` str ` prefix for IFO of interest env : ` str ` , optional environment variable name to use for server order , defau...
hosts = [ ] # if given environment variable exists , it will contain a # comma - separated list of host : port strings giving the logical ordering if env and os . getenv ( env ) : hosts = parse_nds_env ( env ) # If that host fails , return the server for this IFO and the backup at CIT if to_gps ( 'now' ) - to_gps (...
def expand ( self , process , child_nodes ) : """this expands a current node by defining ALL the children for that process TODO = processes need to be recalculated"""
# print ( ' TODO : process check = ' , process ) # print ( self . name , ' expanded to - > ' , child _ nodes ) self . child_nodes = [ ] for n in child_nodes : self . child_nodes . append ( CoreData ( n , parent = self ) )
def stringIndex ( self , string ) : """Returns the index in the table of the provided string . Adds the string to the table if it ' s not there . : param string : the input string ."""
if string in self . table : return self . table [ string ] else : result = self . current_index self . table [ string ] = result self . current_index += self . c_strlen ( string ) return result
def restrict_to_version ( self , version ) : """Restricts the generated SVG file to : obj : ` version ` . See : meth : ` get _ versions ` for a list of available version values that can be used here . This method should only be called before any drawing operations have been performed on the given surface . ...
cairo . cairo_svg_surface_restrict_to_version ( self . _pointer , version ) self . _check_status ( )
def cleave_sequence ( input_layer , unroll = None ) : """Cleaves a tensor into a sequence , this is the inverse of squash . Recurrent methods unroll across an array of Tensors with each one being a timestep . This cleaves the first dim so that each it is an array of Tensors . It is the inverse of squash _ seq...
if unroll is None : raise ValueError ( 'You must set unroll either here or in the defaults.' ) shape = input_layer . shape if shape [ 0 ] is not None and shape [ 0 ] % unroll != 0 : raise ValueError ( 'Must divide the split dimension evenly: %d mod %d != 0' % ( shape [ 0 ] , unroll ) ) if unroll <= 0 : rais...
def dotperu_exclude_case_insensitive_git_globs ( ) : """These use the glob syntax accepted by ` git ls - files ` ( NOT our own glob . py ) . Note that * * must match at least one path component , so we have to use separate globs for matches at the root and matches below ."""
globs = [ ] for capitalization in DOTPERU_CAPITALIZATIONS : globs . append ( capitalization + '/**' ) globs . append ( '**/' + capitalization + '/**' ) return globs
def print ( self , txt : str , hold : bool = False ) -> None : """Conditionally print txt : param txt : text to print : param hold : If true , hang on to the text until another print comes through : param hold : If true , drop both print statements if another hasn ' t intervened : return :"""
if hold : self . held_prints [ self . trace_depth ] = txt elif self . held_prints [ self . trace_depth ] : if self . max_print_depth > self . trace_depth : print ( self . held_prints [ self . trace_depth ] ) print ( txt ) self . max_print_depth = self . trace_depth del self . held_pr...
def get_repo ( self , cached = True ) : """Get a git repository object for this instance ."""
module = sys . modules [ self . __module__ ] # We use module . _ _ file _ _ instead of module . _ _ path _ _ [ 0] # to include modules without a _ _ path _ _ attribute . if hasattr ( self . __class__ , '_repo' ) and cached : repo = self . __class__ . _repo elif hasattr ( module , '__file__' ) : path = os . path...
def send_offset_commit_request ( self , group , payloads = None , fail_on_error = True , callback = None , group_generation_id = - 1 , consumer_id = '' ) : """Send a list of OffsetCommitRequests to the Kafka broker for the given consumer group . Args : group ( str ) : The consumer group to which to commit the...
group = _coerce_consumer_group ( group ) encoder = partial ( KafkaCodec . encode_offset_commit_request , group = group , group_generation_id = group_generation_id , consumer_id = consumer_id ) decoder = KafkaCodec . decode_offset_commit_response resps = yield self . _send_broker_aware_request ( payloads , encoder , dec...
def chapman_profile ( Z0 : float , zKM : np . ndarray , H : float ) : """Z0 : altitude [ km ] of intensity peak zKM : altitude grid [ km ] H : scale height [ km ] example : pz = chapman _ profile ( 110 , np . arange ( 90,200,1 ) , 20)"""
return np . exp ( .5 * ( 1 - ( zKM - Z0 ) / H - np . exp ( ( Z0 - zKM ) / H ) ) )
def run ( self ) : """Run flux analysis command ."""
# Load compound information def compound_name ( id ) : if id not in self . _model . compounds : return id return self . _model . compounds [ id ] . properties . get ( 'name' , id ) # Reaction genes information def reaction_genes_string ( id ) : if id not in self . _model . reactions : return...
def add_health_monitor ( self , type , delay = 10 , timeout = 10 , attemptsBeforeDeactivation = 3 , path = "/" , statusRegex = None , bodyRegex = None , hostHeader = None ) : """Adds a health monitor to the load balancer . If a monitor already exists , it is updated with the supplied settings ."""
abd = attemptsBeforeDeactivation return self . manager . add_health_monitor ( self , type = type , delay = delay , timeout = timeout , attemptsBeforeDeactivation = abd , path = path , statusRegex = statusRegex , bodyRegex = bodyRegex , hostHeader = hostHeader )
def add_condition ( self , conkey , cond ) : """Add a condition , one of the addable ones . conkey : str One of ' cond ' , startcond ' or ' stopcond ' . ' start ' or ' stop ' is accepted as shorts for ' startcond ' or ' stopcond ' . If the conkey is given with an explicit number ( like ' stopcond3 ' ) and...
# Audit : if conkey == 'start' or conkey == 'stop' : conkey += 'cond' if not any ( conkey . startswith ( addable ) for addable in _ADDABLES ) : raise KeyError ( conkey ) if not self . conconf . valid_conkey ( conkey ) : raise KeyError ( conkey ) self . _parse_cond ( cond ) # Checking conkey = self . conconf...
def get_config ( self ) : """Returns pickle - serializable configuration struct for storage ."""
# Fill this dict with config data return { 'hash_name' : self . hash_name , 'dim' : self . dim , 'bin_width' : self . bin_width , 'projection_count' : self . projection_count , 'normals' : self . normals }
def fetchone ( self ) : """Fetches next row , or ` ` None ` ` if there are no more rows"""
row = self . _session . fetchone ( ) if row : return self . _row_factory ( row )
def split_sequence_file_on_sample_ids_to_files ( seqs , outdir ) : """Split FASTA file on sample IDs . Parameters seqs : file handler file handler to demultiplexed FASTA file outdir : string dirpath to output split FASTA files"""
logger = logging . getLogger ( __name__ ) logger . info ( 'split_sequence_file_on_sample_ids_to_files' ' for file %s into dir %s' % ( seqs , outdir ) ) outputs = { } for bits in sequence_generator ( seqs ) : sample = sample_id_from_read_id ( bits [ 0 ] ) if sample not in outputs : outputs [ sample ] = o...
def str_slice_replace ( arr , start = None , stop = None , repl = None ) : """Replace a positional slice of a string with another value . Parameters start : int , optional Left index position to use for the slice . If not specified ( None ) , the slice is unbounded on the left , i . e . slice from the start...
if repl is None : repl = '' def f ( x ) : if x [ start : stop ] == '' : local_stop = start else : local_stop = stop y = '' if start is not None : y += x [ : start ] y += repl if stop is not None : y += x [ local_stop : ] return y return _na_map ( f , arr )
def draw_rect ( self , bbox , cell_val ) : """Fills the bbox with the content values Float bbox values are normalized to have non - zero area"""
new_x0 = int ( bbox [ x0 ] ) new_y0 = int ( bbox [ y0 ] ) new_x1 = max ( new_x0 + 1 , int ( bbox [ x1 ] ) ) new_y1 = max ( new_y0 + 1 , int ( bbox [ y1 ] ) ) self . grid [ new_x0 : new_x1 , new_y0 : new_y1 ] = cell_val
def delete_renditions_if_master_has_changed ( sender , instance , ** kwargs ) : '''if master file as changed delete all renditions'''
try : obj = sender . objects . get ( pk = instance . pk ) except sender . DoesNotExist : pass # Object is new , so field hasn ' t technically changed . else : if not obj . master == instance . master : # Field has changed obj . master . delete ( save = False ) instance . delete_all_rendi...
def insert ( self , fields , values ) : '''insert new db entry : param fields : list of fields to insert : param values : list of values to insert : return : row id of the new row'''
if fields : _fields = ' (%s) ' % ',' . join ( fields ) else : _fields = '' _values = ',' . join ( '?' * len ( values ) ) query = ''' INSERT INTO %s %s VALUES (%s) ''' % ( self . _name , _fields , _values ) self . _cursor . execute ( query , tuple ( values ) ) self . _connection . commit ( ) retu...
def to_source ( node , indentation = ' ' * 4 ) : """Return source code of a given AST ."""
if isinstance ( node , gast . AST ) : node = gast . gast_to_ast ( node ) generator = SourceWithCommentGenerator ( indentation , False , astor . string_repr . pretty_string ) generator . visit ( node ) generator . result . append ( '\n' ) return astor . source_repr . pretty_source ( generator . result ) . lstrip ( )
def selection ( x_bounds , x_types , clusteringmodel_gmm_good , clusteringmodel_gmm_bad , minimize_starting_points , minimize_constraints_fun = None ) : '''Select the lowest mu value'''
results = lib_acquisition_function . next_hyperparameter_lowest_mu ( _ratio_scores , [ clusteringmodel_gmm_good , clusteringmodel_gmm_bad ] , x_bounds , x_types , minimize_starting_points , minimize_constraints_fun = minimize_constraints_fun ) return results
def proof_req_briefs2req_creds ( proof_req : dict , briefs : Union [ dict , Sequence [ dict ] ] ) -> dict : """Given a proof request and cred - brief ( s ) , return a requested - creds structure . The proof request must have cred def id restrictions on all requested attribute specifications . : param proof _ re...
rv = { 'self_attested_attributes' : { } , 'requested_attributes' : { } , 'requested_predicates' : { } } attr_refts = proof_req_attr_referents ( proof_req ) pred_refts = proof_req_pred_referents ( proof_req ) for brief in iter_briefs ( briefs ) : cred_info = brief [ 'cred_info' ] timestamp = ( brief [ 'interval'...
def gen_anytext ( * args ) : """Convenience function to create bag of words for anytext property"""
bag = [ ] for term in args : if term is not None : if isinstance ( term , list ) : for term2 in term : if term2 is not None : bag . append ( term2 ) else : bag . append ( term ) return ' ' . join ( bag )
def __generate ( self ) : """Generate a new value for this ObjectId ."""
# 4 bytes current time oid = struct . pack ( ">i" , int ( time . time ( ) ) ) # 3 bytes machine oid += ObjectId . _machine_bytes # 2 bytes pid oid += struct . pack ( ">H" , os . getpid ( ) % 0xFFFF ) # 3 bytes inc with ObjectId . _inc_lock : oid += struct . pack ( ">i" , ObjectId . _inc ) [ 1 : 4 ] ObjectId . _...
def _complete_exit ( self , cmd , args , text ) : """Find candidates for the ' exit ' command ."""
if args : return return [ x for x in { 'root' , 'all' , } if x . startswith ( text ) ]
def parse_list ( lexer : Lexer , is_const : bool ) -> ListValueNode : """ListValue [ Const ]"""
start = lexer . token item = parse_const_value if is_const else parse_value_value return ListValueNode ( values = any_nodes ( lexer , TokenKind . BRACKET_L , item , TokenKind . BRACKET_R ) , loc = loc ( lexer , start ) , )
def show_bare_metal_state_output_bare_metal_state ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_bare_metal_state = ET . Element ( "show_bare_metal_state" ) config = show_bare_metal_state output = ET . SubElement ( show_bare_metal_state , "output" ) bare_metal_state = ET . SubElement ( output , "bare-metal-state" ) bare_metal_state . text = kwargs . pop ( 'bare_metal_state' ...
def ip_cmd ( self , name ) : """Print ip of given container"""
if not self . container_exists ( name = name ) : exit ( 'Unknown container {0}' . format ( name ) ) ip = self . get_container_ip ( name ) if not ip : exit ( "Failed to get network address for" " container {0}" . format ( name ) ) else : echo ( ip )
def get_subreddit ( self , subreddit_name , * args , ** kwargs ) : """Return a Subreddit object for the subreddit _ name specified . The additional parameters are passed directly into the : class : ` . Subreddit ` constructor ."""
sr_name_lower = subreddit_name . lower ( ) if sr_name_lower == 'random' : return self . get_random_subreddit ( ) elif sr_name_lower == 'randnsfw' : return self . get_random_subreddit ( nsfw = True ) return objects . Subreddit ( self , subreddit_name , * args , ** kwargs )
def RIBSystemRouteLimitExceeded_originator_switch_info_switchIpV4Address ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) RIBSystemRouteLimitExceeded = ET . SubElement ( config , "RIBSystemRouteLimitExceeded" , xmlns = "http://brocade.com/ns/brocade-notification-stream" ) originator_switch_info = ET . SubElement ( RIBSystemRouteLimitExceeded , "originator-switch-info" ) switchIpV4Address = ET . SubElemen...
def handle ( self , * args , ** options ) : """Run the specified Selenium test ( s ) the indicated number of times in the specified browser ."""
browser_name = options [ 'browser_name' ] count = options [ 'count' ] if len ( args ) > 0 : tests = list ( args ) else : tests = settings . SELENIUM_DEFAULT_TESTS # Kill any orphaned chromedriver processes process = Popen ( [ 'killall' , 'chromedriver' ] , stderr = open ( os . devnull , 'w' ) ) process . wait (...
def _prep_cmd ( cmd , tx_out_file ) : """Wrap CNVkit commands ensuring we use local temporary directories ."""
cmd = " " . join ( cmd ) if isinstance ( cmd , ( list , tuple ) ) else cmd return "export TMPDIR=%s && %s" % ( os . path . dirname ( tx_out_file ) , cmd )
def get_op_traceback ( self , op_name ) : """Get the traceback of an op in the latest version of the TF graph . Args : op _ name : Name of the op . Returns : Creation traceback of the op , in the form of a list of 2 - tuples : ( file _ path , lineno ) Raises : ValueError : If the op with the given nam...
if not self . _graph_traceback : raise ValueError ( 'No graph traceback has been received yet.' ) for op_log_entry in self . _graph_traceback . log_entries : if op_log_entry . name == op_name : return self . _code_def_to_traceback_list ( op_log_entry . code_def ) raise ValueError ( 'No op named "%s" can...
def _console ( console : Any ) -> Any : """Return a cffi console ."""
try : return console . console_c except AttributeError : warnings . warn ( ( "Falsy console parameters are deprecated, " "always use the root console instance returned by " "console_init_root." ) , DeprecationWarning , stacklevel = 3 , ) return ffi . NULL
def fetch ( bank , key ) : '''Fetch a key value .'''
_init_client ( ) etcd_key = '{0}/{1}/{2}' . format ( path_prefix , bank , key ) try : value = client . read ( etcd_key ) . value return __context__ [ 'serial' ] . loads ( base64 . b64decode ( value ) ) except etcd . EtcdKeyNotFound : return { } except Exception as exc : raise SaltCacheError ( 'There was...
def contraction_round_Miller ( Di1 , Di2 , rc ) : r'''Returns loss coefficient for any round edged pipe contraction using the method of Miller [ 1 ] _ . This method uses a spline fit to a graph with area ratios 0 to 1 , and radius ratios ( rc / Di2 ) from 0.1 to 0. Parameters Di1 : float Inside diameter o...
A_ratio = Di2 * Di2 / ( Di1 * Di1 ) radius_ratio = rc / Di2 if radius_ratio > 0.1 : radius_ratio = 0.1 Ks = float ( bisplev ( A_ratio , radius_ratio , tck_contraction_abrupt_Miller ) ) # For some near - 1 ratios , can get negative Ks due to the spline . if Ks < 0.0 : Ks = 0.0 return Ks
def add_file ( self , fileGrp , mimetype = None , url = None , ID = None , pageId = None , force = False , local_filename = None , ** kwargs ) : """Add a ` OcrdFile < / . . / . . / ocrd _ models / ocrd _ models . ocrd _ file . html > ` _ . Arguments : fileGrp ( string ) : Add file to ` ` mets : fileGrp ` ` with...
if not ID : raise Exception ( "Must set ID of the mets:file" ) el_fileGrp = self . _tree . getroot ( ) . find ( ".//mets:fileGrp[@USE='%s']" % ( fileGrp ) , NS ) if el_fileGrp is None : el_fileGrp = self . add_file_group ( fileGrp ) if ID is not None and self . find_files ( ID = ID ) != [ ] : if not force :...
def namedb_get_preorder ( cur , preorder_hash , current_block_number , include_expired = False , expiry_time = None ) : """Get a preorder record by hash . If include _ expired is set , then so must expiry _ time Return None if not found ."""
select_query = None args = None if include_expired : select_query = "SELECT * FROM preorders WHERE preorder_hash = ?;" args = ( preorder_hash , ) else : assert expiry_time is not None , "expiry_time is required with include_expired" select_query = "SELECT * FROM preorders WHERE preorder_hash = ? AND blo...