signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def export_widgets ( self_or_cls , obj , filename , fmt = None , template = None , json = False , json_path = '' , ** kwargs ) : """Render and export object as a widget to a static HTML file . Allows supplying a custom template formatting string with fields to interpolate ' js ' , ' css ' and the main ' html ' ...
if fmt not in list ( self_or_cls . widgets . keys ( ) ) + [ 'auto' , None ] : raise ValueError ( "Renderer.export_widget may only export " "registered widget types." ) if not isinstance ( obj , NdWidget ) : if not isinstance ( filename , ( BytesIO , StringIO ) ) : filedir = os . path . dirname ( filenam...
def _load_meta ( path ) : """Load meta data about this package from file pypi . json . : param path : The path to pypi . json : return : Dictionary of key value pairs ."""
with open ( path ) as f : meta = load ( f , encoding = 'utf-8' ) meta = { k : v . decode ( 'utf-8' ) if isinstance ( v , bytes ) else v for k , v in meta . items ( ) } src_dir = abspath ( dirname ( path ) ) if 'requirements' in meta and str ( meta [ 'requirements' ] ) . startswith ( 'file://' ) : ...
def ReadDirectory ( self , path , extension = 'yaml' ) : """Reads artifact definitions from a directory . This function does not recurse sub directories . Args : path ( str ) : path of the directory to read from . extension ( Optional [ str ] ) : extension of the filenames to read . Yields : ArtifactDef...
if extension : glob_spec = os . path . join ( path , '*.{0:s}' . format ( extension ) ) else : glob_spec = os . path . join ( path , '*' ) for artifact_file in glob . glob ( glob_spec ) : for artifact_definition in self . ReadFile ( artifact_file ) : yield artifact_definition
def build_quantity ( orig_text , text , item , values , unit , surface , span , uncert ) : """Build a Quantity object out of extracted information ."""
# Discard irrelevant txt2float extractions , cardinal numbers , codes etc . if surface . lower ( ) in [ 'a' , 'an' , 'one' ] or re . search ( r'1st|2nd|3rd|[04-9]th' , surface ) or re . search ( r'\d+[A-Z]+\d+' , surface ) or re . search ( r'\ba second\b' , surface , re . IGNORECASE ) : logging . debug ( u'\tMeanin...
def SLIT_GAUSSIAN ( x , g ) : """Instrumental ( slit ) function . B ( x ) = sqrt ( ln ( 2 ) / pi ) / Ξ³ * exp ( - ln ( 2 ) * ( x / Ξ³ ) * * 2 ) , where Ξ³ / 2 is a gaussian half - width at half - maximum ."""
g /= 2 return sqrt ( log ( 2 ) ) / ( sqrt ( pi ) * g ) * exp ( - log ( 2 ) * ( x / g ) ** 2 )
def templates_for_host ( templates ) : """Given a template name ( or list of them ) , returns the template names as a list , with each name prefixed with the device directory inserted into the front of the list ."""
if not isinstance ( templates , ( list , tuple ) ) : templates = [ templates ] theme_dir = host_theme_path ( ) host_templates = [ ] if theme_dir : for template in templates : host_templates . append ( "%s/templates/%s" % ( theme_dir , template ) ) host_templates . append ( template ) return ...
def _append_request_ids ( self , resp ) : """Add request _ ids as an attribute to the object : param resp : Response object or list of Response objects"""
if isinstance ( resp , list ) : # Add list of request _ ids if response is of type list . for resp_obj in resp : self . _append_request_id ( resp_obj ) elif resp is not None : # Add request _ ids if response contains single object . self . _append_request_id ( resp )
def _parse_sod_segment ( self , fptr ) : """Parse the SOD ( start - of - data ) segment . Parameters fptr : file Open file object . Returns SODSegment The current SOD segment ."""
offset = fptr . tell ( ) - 2 length = 0 return SODsegment ( length , offset )
def docker_windows_path_adjust ( path ) : # type : ( Text ) - > Text r"""Changes only windows paths so that the can be appropriately passed to the docker run command as as docker treats them as unix paths . Example : ' C : \ Users \ foo to / C / Users / foo ( Docker for Windows ) or / c / Users / foo ( Docker...
if onWindows ( ) : split = path . split ( ':' ) if len ( split ) == 2 : if platform . win32_ver ( ) [ 0 ] in ( '7' , '8' ) : # type : ignore split [ 0 ] = split [ 0 ] . lower ( ) # Docker toolbox uses lowecase windows Drive letters else : split [ 0 ] = split [...
def Miller_bend_unimpeded_correction ( Kb , Di , L_unimpeded ) : '''Limitations as follows : * Ratio not over 30 * If ratio under 0.01 , tabulated values are used near the limits ( discontinuity in graph anyway ) * If ratio for a tried curve larger than max value , max value is used instead of calculating...
if Kb < 0.1 : Kb_C_o = 0.1 elif Kb > 1 : Kb_C_o = 1.0 else : Kb_C_o = Kb L_unimpeded_ratio = L_unimpeded / Di if L_unimpeded_ratio > 30 : L_unimpeded_ratio = 30.0 for i in range ( len ( bend_rounded_Miller_C_o_Kbs ) ) : Kb_low , Kb_high = bend_rounded_Miller_C_o_Kbs [ i ] , bend_rounded_Miller_C_o_K...
def parse ( self ) -> InstanceRoute : """Parse resource identifier ."""
res = InstanceRoute ( ) if self . at_end ( ) : return res if self . peek ( ) == "/" : self . offset += 1 if self . at_end ( ) : return res sn = self . schema_node while True : name , ns = self . prefixed_name ( ) cn = sn . get_data_child ( name , ns ) if cn is None : for cn in sn . child...
def compile_temp ( d , key , value ) : """Compiles temporary dictionaries for metadata . Adds a new entry to an existing dictionary . : param dict d : : param str key : : param any value : : return dict :"""
if not value : d [ key ] = None elif len ( value ) == 1 : d [ key ] = value [ 0 ] else : d [ key ] = value return d
def get_cloudwatch_event_rule ( app_name , account , region ) : """Get CloudWatch Event rule names ."""
session = boto3 . Session ( profile_name = account , region_name = region ) cloudwatch_client = session . client ( 'events' ) lambda_alias_arn = get_lambda_alias_arn ( app = app_name , account = account , region = region ) rule_names = cloudwatch_client . list_rule_names_by_target ( TargetArn = lambda_alias_arn ) if ru...
def nand_synth ( net ) : """Synthesizes an Post - Synthesis block into one consisting of nands and inverters in place : param block : The block to synthesize ."""
if net . op in '~nrwcsm@' : return True def arg ( num ) : return net . args [ num ] dest = net . dests [ 0 ] if net . op == '&' : dest <<= ~ ( arg ( 0 ) . nand ( arg ( 1 ) ) ) elif net . op == '|' : dest <<= ( ~ arg ( 0 ) ) . nand ( ~ arg ( 1 ) ) elif net . op == '^' : temp_0 = arg ( 0 ) . nand ( ar...
def package_version ( filename , varname ) : """Return package version string by reading ` filename ` and retrieving its module - global variable ` varnam ` ."""
_locals = { } with open ( filename ) as fp : exec ( fp . read ( ) , None , _locals ) return _locals [ varname ]
def fill_concentric_circles ( size , center , radius ) : """Returns a path that fills a concentric circle with the given radius and center . : param radius : : param center : : param size : The size of the image , used to skip points that are out of bounds . : return : Yields iterators , where each iterator...
for r in range ( radius ) : yield concentric_circle ( center , r , size = size )
def build_journals_kb ( knowledgebase ) : """Given the path to a knowledge base file , read in the contents of that file into a dictionary of search - > replace word phrases . The search phrases are compiled into a regex pattern object . The knowledge base file should consist only of lines that take the fol...
# Initialise vars : # dictionary of search and replace phrases from KB : kb = { } standardised_titles = { } seek_phrases = [ ] # A dictionary of " replacement terms " ( RHS ) to be inserted into KB as # " seek terms " later , if they were not already explicitly added # by the KB : repl_terms = { } for seek_phrase , rep...
def _fetch_objects ( self , key , value ) : """Fetch Multiple linked objects"""
return self . to_cls . query . filter ( ** { key : value } )
def _get_result ( self ) -> float : """Return current measurement result in lx ."""
try : data = self . _bus . read_word_data ( self . _i2c_add , self . _mode ) self . _ok = True except OSError as exc : self . log_error ( "Bad reading in bus: %s" , exc ) self . _ok = False return - 1 count = data >> 8 | ( data & 0xff ) << 8 mode2coeff = 2 if self . _high_res else 1 ratio = 1 / ( 1....
async def index ( request ) : """This is the view handler for the " / " url . * * Note : returning html without a template engine like jinja2 is ugly , no way around that . * * : param request : the request object see http : / / aiohttp . readthedocs . io / en / stable / web _ reference . html # request : ret...
# { % if database . is _ none and example . is _ message _ board % } # app . router allows us to generate urls based on their names , # see http : / / aiohttp . readthedocs . io / en / stable / web . html # reverse - url - constructing - using - named - resources message_url = request . app . router [ 'messages' ] . ur...
def get_users ( self , id , status = 0 , fetch_child = 0 , simple = True ) : """θŽ·ε–ιƒ¨ι—¨ζˆε‘˜ : https : / / work . weixin . qq . com / api / doc # 90000/90135/90200 θŽ·ε–ιƒ¨ι—¨ζˆε‘˜θ―¦ζƒ… : https : / / work . weixin . qq . com / api / doc # 90000/90135/90201 : param id : 部门 id : param status : 0 θŽ·ε–ε…¨ιƒ¨ε‘˜ε·₯ , 1 θŽ·ε–ε·²ε…³ζ³¨ζˆε‘˜εˆ—θ‘¨ , 2 θŽ·ε–η¦η”¨ζˆε‘˜εˆ—...
url = 'user/simplelist' if simple else 'user/list' res = self . _get ( url , params = { 'department_id' : id , 'status' : status , 'fetch_child' : 1 if fetch_child else 0 } ) return res [ 'userlist' ]
def load_permission_mappings ( apilevel ) : """Load the API / Permission mapping for the requested API level . If the requetsed level was not found , None is returned . : param apilevel : integer value of the API level , i . e . 24 for Android 7.0 : return : a dictionary of { MethodSignature : [ List of Permi...
root = os . path . dirname ( os . path . realpath ( __file__ ) ) permissions_file = os . path . join ( root , "api_permission_mappings" , "permissions_{}.json" . format ( apilevel ) ) if not os . path . isfile ( permissions_file ) : return { } with open ( permissions_file , "r" ) as fp : return json . load ( fp...
def is_circumpolar ( self , var ) : """Test if a variable is on a circumpolar grid Parameters % ( CFDecoder . is _ triangular . parameters ) s Returns % ( CFDecoder . is _ triangular . returns ) s"""
xcoord = self . get_x ( var ) return xcoord is not None and xcoord . ndim == 2
def getProxyForObject ( self , obj ) : """Returns the proxied version of C { obj } as stored in the context , or creates a new proxied object and returns that . @ see : L { pyamf . flex . proxy _ object } @ since : 0.6"""
proxied = self . proxied_objects . get ( id ( obj ) ) if proxied is None : from pyamf import flex proxied = flex . proxy_object ( obj ) self . addProxyObject ( obj , proxied ) return proxied
def remote_get ( cwd , remote = 'origin' , user = None , password = None , redact_auth = True , ignore_retcode = False , output_encoding = None ) : '''Get the fetch and push URL for a specific remote cwd The path to the git checkout remote : origin Name of the remote to query user User under which to ru...
cwd = _expand_path ( cwd , user ) all_remotes = remotes ( cwd , user = user , password = password , redact_auth = redact_auth , ignore_retcode = ignore_retcode , output_encoding = output_encoding ) if remote not in all_remotes : raise CommandExecutionError ( 'Remote \'{0}\' not present in git checkout located at {1...
def schema ( self , sources = None , tables = None , clean = False , force = False , use_pipeline = False ) : """Generate destination schemas . : param sources : If specified , build only destination tables for these sources : param tables : If specified , build only these tables : param clean : Delete tables...
from itertools import groupby from operator import attrgetter from ambry . etl import Collect , Head from ambry . orm . exc import NotFoundError self . dstate = self . STATES . BUILDING self . commit ( ) # Workaround for https : / / github . com / CivicKnowledge / ambry / issues / 171 self . log ( '---- Schema ----' ) ...
def plot_winds ( self , ws , wd , wsmax , plot_range = None ) : """Required input : ws : Wind speeds ( knots ) wd : Wind direction ( degrees ) wsmax : Wind gust ( knots ) Optional Input : plot _ range : Data range for making figure ( list of ( min , max , step ) )"""
# PLOT WIND SPEED AND WIND DIRECTION self . ax1 = fig . add_subplot ( 4 , 1 , 1 ) ln1 = self . ax1 . plot ( self . dates , ws , label = 'Wind Speed' ) self . ax1 . fill_between ( self . dates , ws , 0 ) self . ax1 . set_xlim ( self . start , self . end ) if not plot_range : plot_range = [ 0 , 20 , 1 ] self . ax1 . ...
def get_client_for_file ( self , filename ) : """Get client associated with a given file ."""
client = None for idx , cl in enumerate ( self . get_clients ( ) ) : if self . filenames [ idx ] == filename : self . tabwidget . setCurrentIndex ( idx ) client = cl break return client
def is_storage ( self ) : """Return true if the variable is located in storage See https : / / solidity . readthedocs . io / en / v0.4.24 / types . html ? highlight = storage % 20location # data - location Returns : ( bool )"""
if self . location == 'memory' : return False # Use by slithIR SSA if self . location == 'reference_to_storage' : return False if self . location == 'storage' : return True if isinstance ( self . type , ( ArrayType , MappingType ) ) : return True if isinstance ( self . type , UserDefinedType ) : ret...
def to_source ( self , classname ) : """Returns the model as Java source code if the classifier implements weka . classifiers . Sourcable . : param classname : the classname for the generated Java code : type classname : str : return : the model as source code string : rtype : str"""
if not self . check_type ( self . jobject , "weka.classifiers.Sourcable" ) : return None return javabridge . call ( self . jobject , "toSource" , "(Ljava/lang/String;)Ljava/lang/String;" , classname )
def upgrade ( check_only , yes ) : '''Upgrade libreant database . This command can be used after an update of libreant in order to upgrade the database and make it aligned with the new version .'''
from utils . es import Elasticsearch from libreantdb import DB , migration from libreantdb . exceptions import MappingsException try : db = DB ( Elasticsearch ( hosts = conf [ 'ES_HOSTS' ] ) , index_name = conf [ 'ES_INDEXNAME' ] ) if not db . es . indices . exists ( db . index_name ) : die ( "The speci...
def get ( self ) : """Copies file from local filesystem to self . save _ dir . Returns : Full path of the copied file . Raises : EnvironmentError if the file can ' t be found or the save _ dir is not writable ."""
if self . local_file . endswith ( '.whl' ) : self . temp_dir = tempfile . mkdtemp ( ) save_dir = self . temp_dir else : save_dir = self . save_dir save_file = '{0}/{1}' . format ( save_dir , os . path . basename ( self . local_file ) ) if not os . path . exists ( save_file ) or not os . path . samefile ( se...
def is_email_verified ( self , request , email ) : """Checks whether or not the email address is already verified beyond allauth scope , for example , by having accepted an invitation before signing up ."""
ret = False verified_email = request . session . get ( 'account_verified_email' ) if verified_email : ret = verified_email . lower ( ) == email . lower ( ) return ret
def backfill ( self , data , resolution , start , end = None ) : """Backfills missing historical data : Optional : data : pd . DataFrame Minimum required bars for backfill attempt resolution : str Algo resolution start : datetime Backfill start date ( YYYY - MM - DD [ HH : MM : SS [ . MS ] ) . end :...
data . sort_index ( inplace = True ) # currenly only supporting minute - data if resolution [ - 1 ] in ( "K" , "V" ) : self . backfilled = True return None # missing history ? start_date = parse_date ( start ) end_date = parse_date ( end ) if end else datetime . utcnow ( ) if data . empty : first_date = dat...
def set_position ( cls , resource_id , to_position , db_session = None , * args , ** kwargs ) : """Sets node position for new node in the tree : param resource _ id : resource to move : param to _ position : new position : param db _ session : : return : def count _ children ( cls , resource _ id , db _ ses...
db_session = get_db_session ( db_session ) # lets lock rows to prevent bad tree states resource = ResourceService . lock_resource_for_update ( resource_id = resource_id , db_session = db_session ) cls . check_node_position ( resource . parent_id , to_position , on_same_branch = True , db_session = db_session ) cls . sh...
def match ( self , request , * , root = None , path = None , methods = None ) : """Return match or None for the request / constraints pair . Parameters request : : class : ` . http . Request ` Request instance . root : str HTTP path root . path : str HTTP path . methods : list HTTP methods . Ret...
match = Match ( ) if path is not None : pattern = self . __get_pattern ( path ) match = pattern . match ( request . path ) elif root is not None : pattern = self . __get_pattern ( root ) match = pattern . match ( request . path , left = True ) if not match : return None if methods : methods = ma...
async def msetup ( self , text_channel ) : """Creates the gui Args : text _ channel ( discord . Channel ) : The channel for the embed ui to run in"""
if self . mready : logger . warning ( "Attempt to init music when already initialised" ) return if self . state != 'starting' : logger . error ( "Attempt to init from wrong state ('{}'), must be 'starting'." . format ( self . state ) ) return self . logger . debug ( "Setting up gui" ) # Create gui self ...
def add_missing_model ( self , model_list_or_dict , core_elements_dict , model_name , model_class , model_key ) : """Adds one missing model The method will search for the first core - object out of core _ object _ dict not represented in the list or dict of models handed by model _ list _ or _ dict , adds it an...
def core_element_has_model ( core_object ) : for model_or_key in model_list_or_dict : model = model_or_key if model_key is None else model_list_or_dict [ model_or_key ] if core_object is getattr ( model , model_name ) : return True return False if model_name == "income" : self . ...
def enter_new_scope ( ctx ) : """we inside new scope with it onw : param ctx : : return :"""
ctx = ctx . clone ( ) ctx . waiting_for = ctx . compiled_story ( ) . children_matcher ( ) return ctx
def from_gpx ( gpx_segment ) : """Creates a segment from a GPX format . No preprocessing is done . Arguments : gpx _ segment ( : obj : ` gpxpy . GPXTrackSegment ` ) Return : : obj : ` Segment `"""
points = [ ] for point in gpx_segment . points : points . append ( Point . from_gpx ( point ) ) return Segment ( points )
def create_cells ( self , blocks ) : """Turn the list of blocks into a list of notebook cells ."""
cells = [ ] for block in blocks : if ( block [ 'type' ] == self . code ) and ( block [ 'IO' ] == 'input' ) : code_cell = self . create_code_cell ( block ) cells . append ( code_cell ) elif ( block [ 'type' ] == self . code and block [ 'IO' ] == 'output' and cells [ - 1 ] . cell_type == 'code' ) ...
def post ( self , text , attachments = None ) : """Post a message as the bot . : param str text : the text of the message : param attachments : a list of attachments : type attachments : : class : ` list ` : return : ` ` True ` ` if successful : rtype : bool"""
return self . manager . post ( self . bot_id , text , attachments )
def read_FITS_cols ( infile , cols = None ) : # noqa : N802 """Read columns from FITS table"""
with fits . open ( infile , memmap = False ) as ftab : extnum = 0 extfound = False for extn in ftab : if 'tfields' in extn . header : extfound = True break extnum += 1 if not extfound : print ( 'ERROR: No catalog table found in ' , infile ) raise V...
def _switch ( self , future ) : """Switch greenlet ."""
scoop . _control . current = self assert self . greenlet is not None , ( "No greenlet to switch to:" "\n{0}" . format ( self . __dict__ ) ) return self . greenlet . switch ( future )
def _uploadFile ( self , directory , fn , dentry , db , service ) : """Uploads file and changes status to ' S ' . Looks up service name with service string"""
# Create a hash of the file if fn not in db : print ( "%s - Not in DB, must run 'add' first!" % ( fn ) ) else : # If already added , see if it ' s modified , only then # do another upload if db [ fn ] [ 'services' ] [ service ] [ 'status' ] == self . ST_UPTODATE : if not dentry [ 'status' ] == self . ST...
def offline ( f ) : """This decorator allows you to access ` ` ctx . bitshares ` ` which is an instance of BitShares with ` ` offline = True ` ` ."""
@ click . pass_context @ verbose def new_func ( ctx , * args , ** kwargs ) : ctx . obj [ "offline" ] = True ctx . bitshares = BitShares ( ** ctx . obj ) ctx . blockchain = ctx . bitshares ctx . bitshares . set_shared_instance ( ) return ctx . invoke ( f , * args , ** kwargs ) return update_wrapper (...
def list_get ( l , idx , default = None ) : """Get from a list with an optional default value ."""
try : if l [ idx ] : return l [ idx ] else : return default except IndexError : return default
def alignment ( layer , decay_ratio = 2 ) : """Encourage neighboring images to be similar . When visualizing the interpolation between two objectives , it ' s often desireable to encourage analagous boejcts to be drawn in the same position , to make them more comparable . This term penalizes L2 distance bet...
def inner ( T ) : batch_n = T ( layer ) . get_shape ( ) . as_list ( ) [ 0 ] arr = T ( layer ) accum = 0 for d in [ 1 , 2 , 3 , 4 ] : for i in range ( batch_n - d ) : a , b = i , i + d arr1 , arr2 = arr [ a ] , arr [ b ] accum += tf . reduce_mean ( ( arr1 - arr...
def _repo_is_preset ( repo ) : """Evaluate whether GitHub repository is a be package Arguments : gist ( str ) : username / id pair e . g . mottosso / be - ad"""
package_template = "https://raw.githubusercontent.com" package_template += "/{repo}/master/package.json" package_path = package_template . format ( repo = repo ) response = get ( package_path ) if response . status_code == 404 : return False try : data = response . json ( ) except : return False if not data...
def jsonmget ( self , path , * args ) : """Gets the objects stored as a JSON values under ` ` path ` ` from keys ` ` args ` `"""
pieces = [ ] pieces . extend ( args ) pieces . append ( str_path ( path ) ) return self . execute_command ( 'JSON.MGET' , * pieces )
def _peg_pose_in_hole_frame ( self ) : """A helper function that takes in a named data field and returns the pose of that object in the base frame ."""
# World frame peg_pos_in_world = self . sim . data . get_body_xpos ( "cylinder" ) peg_rot_in_world = self . sim . data . get_body_xmat ( "cylinder" ) . reshape ( ( 3 , 3 ) ) peg_pose_in_world = T . make_pose ( peg_pos_in_world , peg_rot_in_world ) # World frame hole_pos_in_world = self . sim . data . get_body_xpos ( "h...
def load_commands ( self , parser ) : """Load commands of this profile . : param parser : argparse parser on which to add commands"""
entrypoints = self . _get_entrypoints ( ) already_loaded = set ( ) for entrypoint in entrypoints : if entrypoint . name not in already_loaded : command_class = entrypoint . load ( ) command_class ( entrypoint . name , self , parser ) . prepare ( ) already_loaded . add ( entrypoint . name )
def has_contents_for ( self , package ) : """Return true if ' exclude _ package ( package ) ' would do something"""
pfx = package + '.' for p in self . iter_distribution_names ( ) : if p == package or p . startswith ( pfx ) : return True
def find_revision_id ( self , revision = None ) : """Find the global revision id of the given revision ."""
# Make sure the local repository exists . self . create ( ) # Try to find the revision id of the specified revision . revision = self . expand_branch_name ( revision ) output = self . context . capture ( 'git' , 'rev-parse' , revision ) # Validate the ` git rev - parse ' output . return self . ensure_hexadecimal_string...
def user_config ( ** kwargs ) : """Initialize Git user config file . : param kwargs : key / value pairs are stored in the git user config file ."""
for kw in kwargs : git ( 'config --global user.%s "%s"' % ( kw , kwargs . get ( kw ) ) ) . wait ( )
def recover ( data : bytes , signature : Signature , hasher : Callable [ [ bytes ] , bytes ] = eth_sign_sha3 , ) -> Address : """eth _ recover address from data hash and signature"""
_hash = hasher ( data ) # ecdsa _ recover accepts only standard [ 0,1 ] v ' s so we add support also for [ 27,28 ] here # anything else will raise BadSignature if signature [ - 1 ] >= 27 : # support ( 0,1,27,28 ) v values signature = Signature ( signature [ : - 1 ] + bytes ( [ signature [ - 1 ] - 27 ] ) ) try : ...
def stateDict ( self ) : """Saves internal values to be loaded later : returns : dict - - { ' parametername ' : value , . . . }"""
state = { 'duration' : self . _duration , 'intensity' : self . _intensity , 'risefall' : self . _risefall , 'stim_type' : self . name } return state
def get_url_directory_string ( url ) : """Determines the url ' s directory string . : param str url : the url to extract the directory string from : return str : the directory string on the server"""
domain = UrlExtractor . get_allowed_domain ( url ) splitted_url = url . split ( '/' ) # the following commented list comprehension could replace # the following for , if not and break statement # index = [ index for index in range ( len ( splitted _ url ) ) # if not re . search ( domain , splitted _ url [ index ] ) is ...
def login ( ) : """Log in a registered user by adding the user id to the session ."""
if request . method == "POST" : username = request . form [ "username" ] password = request . form [ "password" ] error = None user = User . query . filter_by ( username = username ) . first ( ) if user is None : error = "Incorrect username." elif not user . check_password ( password ) :...
def deduplicate_taxa ( records ) : """Remove any duplicate records with identical IDs , keep the first instance seen and discard additional occurences ."""
logging . info ( 'Applying _deduplicate_taxa generator: ' + 'removing any duplicate records with identical IDs.' ) taxa = set ( ) for record in records : # Default to full ID , split if | is found . taxid = record . id if '|' in record . id : try : taxid = int ( record . id . split ( "|" ) [...
def guess_encoding ( request ) : """Try to guess the encoding of a request without going through the slow chardet process"""
ctype = request . headers . get ( 'content-type' ) if not ctype : # we don ' t have a content - type , somehow , so . . . LOGGER . warning ( "%s: no content-type; headers are %s" , request . url , request . headers ) return 'utf-8' # explicit declaration match = re . search ( r'charset=([^ ;]*)(;| |$)' , ctype ...
def convert_to_gt ( text , layer_name = GT_WORDS ) : '''Converts all words in a morphologically analysed Text from FS format to giellatekno ( GT ) format , and stores in a new layer named GT _ WORDS . If the keyword argument * layer _ name = = ' words ' * , overwrites the old ' words ' layer with the new laye...
assert WORDS in text , '(!) The input text should contain "' + str ( WORDS ) + '" layer.' assert len ( text [ WORDS ] ) == 0 or ( len ( text [ WORDS ] ) > 0 and ANALYSIS in text [ WORDS ] [ 0 ] ) , '(!) Words in the input text should contain "' + str ( ANALYSIS ) + '" layer.' new_words_layer = [ ] # 1 ) Perform the con...
def get_derived_from ( self , address ) : """Get the target the specified target was derived from . If a Target was injected programmatically , e . g . from codegen , this allows us to trace its ancestry . If a Target is not derived , default to returning itself . : API : public"""
parent_address = self . _derived_from_by_derivative . get ( address , address ) return self . get_target ( parent_address )
def register_route ( self , name , route ) : """Register a route handler : param name : Name of the route : param route : Route handler"""
try : self . routes [ name ] = route . handle except Exception as e : print ( 'could not import handle, maybe something wrong ' , 'with your code?' ) print ( e )
def create_label ( self , name , justify = Gtk . Justification . CENTER , wrap_mode = True , tooltip = None ) : """The function is used for creating lable with HTML text"""
label = Gtk . Label ( ) name = name . replace ( '|' , '\n' ) label . set_markup ( name ) label . set_justify ( justify ) label . set_line_wrap ( wrap_mode ) if tooltip is not None : label . set_has_tooltip ( True ) label . connect ( "query-tooltip" , self . parent . tooltip_queries , tooltip ) return label
def map_sprinkler ( self , sx , sy , watered_crop = '^' , watered_field = '_' , dry_field = ' ' , dry_crop = 'x' ) : """Return a version of the ASCII map showing reached crop cells ."""
# convert strings ( rows ) to lists of characters for easier map editing maplist = [ list ( s ) for s in self . maplist ] for y , row in enumerate ( maplist ) : for x , cell in enumerate ( row ) : if sprinkler_reaches_cell ( x , y , sx , sy , self . r ) : if cell == 'x' : cell = ...
def adjust_for_scratch ( self ) : """Remove certain plugins in order to handle the " scratch build " scenario . Scratch builds must not affect subsequent builds , and should not be imported into Koji ."""
if self . user_params . scratch . value : remove_plugins = [ ( "prebuild_plugins" , "koji_parent" ) , ( "postbuild_plugins" , "compress" ) , # required only to make an archive for Koji ( "postbuild_plugins" , "pulp_pull" ) , # required only to make an archive for Koji ( "postbuild_plugins" , "compare_compon...
def on_publish ( self ) : # type : ( ) - > Callable """Decorator . Decorator to handle all messages that have been published by the client . * * Example Usage : * * : : @ mqtt . on _ publish ( ) def handle _ publish ( client , userdata , mid ) : print ( ' Published message with mid { } . ' . format ( ...
def decorator ( handler ) : # type : ( Callable ) - > Callable self . client . on_publish = handler return handler return decorator
def create_serving_logger ( ) -> Logger : """Create a logger for serving . This creates a logger named quart . serving ."""
logger = getLogger ( 'quart.serving' ) if logger . level == NOTSET : logger . setLevel ( INFO ) logger . addHandler ( serving_handler ) return logger
def createMask ( input = None , static_sig = 4.0 , group = None , editpars = False , configObj = None , ** inputDict ) : """The user can input a list of images if they like to create static masks as well as optional values for static _ sig and inputDict . The configObj . cfg file will set the defaults and then ...
if input is not None : inputDict [ "static_sig" ] = static_sig inputDict [ "group" ] = group inputDict [ "updatewcs" ] = False inputDict [ "input" ] = input else : print >> sys . stderr , "Please supply an input image\n" raise ValueError # this accounts for a user - called init where config is n...
def execute ( self , input_data ) : '''Execute the PEIndicators worker'''
raw_bytes = input_data [ 'sample' ] [ 'raw_bytes' ] # Analyze the output of pefile for any anomalous conditions . # Have the PE File module process the file try : self . pefile_handle = pefile . PE ( data = raw_bytes , fast_load = False ) except ( AttributeError , pefile . PEFormatError ) , error : return { 'er...
def done ( self , key ) : '''return True iff key is marked done . : param key : a json - serializable object .'''
# key is not done b / c the file does not even exist yet if not os . path . exists ( self . path ) : return False is_done = False done_line = self . _done_line ( key ) undone_line = self . _undone_line ( key ) with open ( self . path ) as fh : for line in fh : if line == done_line : is_done ...
def deInactivateCells ( self , l6Input ) : """Activate trnCells according to the l6Input . These in turn will impact bursting mode in relay cells that are connected to these trnCells . Given the feedForwardInput , compute which cells will be silent , tonic , or bursting . : param l6Input : : return : noth...
# Figure out which TRN cells recognize the L6 pattern . self . trnOverlaps = self . trnConnections . computeActivity ( l6Input , 0.5 ) self . activeTRNSegments = np . flatnonzero ( self . trnOverlaps >= self . trnActivationThreshold ) self . activeTRNCellIndices = self . trnConnections . mapSegmentsToCells ( self . act...
def send ( self , recipients , subject , text_body , html_body = None , sender = None , ** kwargs ) : # type : ( List [ str ] , str , str , Optional [ str ] , Optional [ str ] , Any ) - > None """Send email Args : recipients ( List [ str ] ) : Email recipient subject ( str ) : Email subject text _ body ( st...
if sender is None : sender = self . sender v = validate_email ( sender , check_deliverability = False ) # validate and get info sender = v [ 'email' ] # replace with normalized form normalised_recipients = list ( ) for recipient in recipients : v = validate_email ( recipient , check_deliverability = True ) ...
def handleServerEvents ( self , msg ) : """dispatch msg to the right handler"""
self . log . debug ( 'MSG %s' , msg ) self . handleConnectionState ( msg ) if msg . typeName == "error" : self . handleErrorEvents ( msg ) elif msg . typeName == dataTypes [ "MSG_CURRENT_TIME" ] : if self . time < msg . time : self . time = msg . time elif ( msg . typeName == dataTypes [ "MSG_TYPE_MKT_D...
def unpack_messages ( msgs ) : import msgpack """Deserialize a message to python structures"""
for key , msg in msgs : record = msgpack . unpackb ( msg ) record [ '_key' ] = key yield record
def write_wrapped ( self , s , extra_room = 0 ) : """Add a soft line break if needed , then write s ."""
if self . room < len ( s ) + extra_room : self . write_soft_break ( ) self . write_str ( s )
def is_blocked ( self ) : """: class : ` bool ` : Checks if the user is blocked . . . note : : This only applies to non - bot accounts ."""
r = self . relationship if r is None : return False return r . type is RelationshipType . blocked
def get_xml_child ( source , path ) : """Get the first descendant of source identified by path . Path must be either a an xpath string , or a 2 - tuple of ( xpath , namespace _ dict ) ."""
if isinstance ( path , ( tuple , list ) ) : return source . find ( * path ) else : return source . find ( path )
def DbGetDeviceAliasList ( self , argin ) : """Get device alias name with a specific filter : param argin : The filter : type : tango . DevString : return : Device alias list : rtype : tango . DevVarStringArray"""
self . _log . debug ( "In DbGetDeviceAliasList()" ) if not argin : argin = "%" else : argin = replace_wildcard ( argin ) return self . db . get_device_alias_list ( argin )
def qhalf ( self ) : """get the square root of the cofactor matrix attribute . Create the attribute if it has not yet been created Returns qhalf : pyemu . Matrix"""
if self . __qhalf != None : return self . __qhalf self . log ( "qhalf" ) self . __qhalf = self . obscov ** ( - 0.5 ) self . log ( "qhalf" ) return self . __qhalf
def set ( self , element_to_set , value ) : """( Helper ) Set thermostat"""
self . _elk . send ( ts_encode ( self . index , value , element_to_set ) )
def _get_fout_go ( self ) : """Get the name of an output file based on the top GO term ."""
assert self . goids , "NO VALID GO IDs WERE PROVIDED AS STARTING POINTS FOR HIERARCHY REPORT" base = next ( iter ( self . goids ) ) . replace ( ':' , '' ) upstr = '_up' if 'up' in self . kws else '' return "hier_{BASE}{UP}.{EXT}" . format ( BASE = base , UP = upstr , EXT = 'txt' )
async def substr ( self , name , start , end = - 1 ) : """Return a substring of the string at key ` ` name ` ` . ` ` start ` ` and ` ` end ` ` are 0 - based integers specifying the portion of the string to return ."""
return await self . execute_command ( 'SUBSTR' , name , start , end )
def bounds ( self ) : """The axis aligned bounds of the faces of the mesh . Returns bounds : ( 2 , 3 ) float Bounding box with [ min , max ] coordinates"""
# return bounds including ONLY referenced vertices in_mesh = self . vertices [ self . referenced_vertices ] # get mesh bounds with min and max mesh_bounds = np . array ( [ in_mesh . min ( axis = 0 ) , in_mesh . max ( axis = 0 ) ] ) # should not be mutable mesh_bounds . flags . writeable = False return mesh_bounds
def create ( self , name , description , ** attrs ) : """Create a new : class : ` Project ` : param name : name of the : class : ` Project ` : param description : description of the : class : ` Project ` : param attrs : optional attributes for : class : ` Project `"""
attrs . update ( { 'name' : name , 'description' : description } ) return self . _new_resource ( payload = attrs )
def import_module ( module_fqname , superclasses = None ) : """Imports the module module _ fqname and returns a list of defined classes from that module . If superclasses is defined then the classes returned will be subclasses of the specified superclass or superclasses . If superclasses is plural it must be ...
module_name = module_fqname . rpartition ( "." ) [ - 1 ] module = __import__ ( module_fqname , globals ( ) , locals ( ) , [ module_name ] ) modules = [ class_ for cname , class_ in inspect . getmembers ( module , inspect . isclass ) if class_ . __module__ == module_fqname ] if superclasses : modules = [ m for m in ...
def get ( key , profile = None ) : '''Get a value from the Redis SDB .'''
if not profile : return False redis_kwargs = profile . copy ( ) redis_kwargs . pop ( 'driver' ) redis_conn = redis . StrictRedis ( ** redis_kwargs ) return redis_conn . get ( key )
def process_item ( self , item , spider ) : """Store item data in DB . First determine if a version of the article already exists , if so then ' migrate ' the older version to the archive table . Second store the new article in the current version table"""
# Set defaults version = 1 ancestor = 0 # Search the CurrentVersion table for an old version of the article try : self . cursor . execute ( self . compare_versions , ( item [ 'url' ] , ) ) except ( pymysql . err . OperationalError , pymysql . ProgrammingError , pymysql . InternalError , pymysql . IntegrityError , T...
def enable ( self , timeout = 0 ) : """Enable the plugin . Args : timeout ( int ) : Timeout in seconds . Default : 0 Raises : : py : class : ` docker . errors . APIError ` If the server returns an error ."""
self . client . api . enable_plugin ( self . name , timeout ) self . reload ( )
def _prepare_imports ( self , dicts ) : """filters the import stream to remove duplicates also serves as a good place to override if anything special has to be done to the order of the import stream ( see OrganizationImporter )"""
# hash ( json ) : id seen_hashes = { } for data in dicts : json_id = data . pop ( '_id' ) # map duplicates ( using omnihash to tell if json dicts are identical - ish ) objhash = omnihash ( data ) if objhash not in seen_hashes : seen_hashes [ objhash ] = json_id yield json_id , data e...
def update ( self , value , timestamp = None ) : """Add a value to the reservoir . : param value : the value to be added : param timestamp : the epoch timestamp of the value in seconds , defaults to the current timestamp if not specified ."""
if timestamp is None : timestamp = self . current_time_in_fractional_seconds ( ) self . rescale_if_needed ( ) priority = self . weight ( timestamp - self . start_time ) / random . random ( ) self . values [ priority ] = value if len ( self . values ) > self . size : self . values . remove_min ( )
def find_closing_parenthesis ( sql , startpos ) : """Find the pair of opening and closing parentheses . Starts search at the position startpos . Returns tuple of positions ( opening , closing ) if search succeeds , otherwise None ."""
pattern = re . compile ( r'[()]' ) level = 0 opening = [ ] for match in pattern . finditer ( sql , startpos ) : par = match . group ( ) if par == '(' : if level == 0 : opening = match . start ( ) level += 1 if par == ')' : assert level > 0 , "missing '(' before ')'" ...
def add_input ( self , input ) : '''Add a single build XML output file to our data .'''
events = xml . dom . pulldom . parse ( input ) context = [ ] for ( event , node ) in events : if event == xml . dom . pulldom . START_ELEMENT : context . append ( node ) if node . nodeType == xml . dom . Node . ELEMENT_NODE : x_f = self . x_name_ ( * context ) if x_f : ...
def _add_attr_property ( self ) : """Add a read / write ` ` { prop _ name } ` ` property to the element class that returns the interpreted value of this attribute on access and changes the attribute value to its ST _ * counterpart on assignment ."""
property_ = property ( self . _getter , self . _setter , None ) # assign unconditionally to overwrite element name definition setattr ( self . _element_cls , self . _prop_name , property_ )
def newline ( self ) : """Advances the cursor position ot the left hand side , and to the next line . If the cursor is on the lowest line , the displayed contents are scrolled , causing the top line to be lost ."""
self . carriage_return ( ) if self . _cy + ( 2 * self . _ch ) >= self . _device . height : # Simulate a vertical scroll copy = self . _backing_image . crop ( ( 0 , self . _ch , self . _device . width , self . _device . height ) ) self . _backing_image . paste ( copy , ( 0 , 0 ) ) self . _canvas . rectangle ...
def encode_priority ( self , facility , priority ) : """Encode the facility and priority . You can pass in strings or integers - if strings are passed , the facility _ names and priority _ names mapping dictionaries are used to convert them to integers ."""
return ( facility << 3 ) | self . priority_map . get ( priority , self . LOG_WARNING )
def __validate_and_fix_spark_args ( spark_args ) : """Prepares spark arguments . In the command - line script , they are passed as for example ` - s master = local [ 4 ] deploy - mode = client verbose ` , which would be passed to spark - submit as ` - - master local [ 4 ] - - deploy - mode client - - verbose ` ...
pattern = re . compile ( r'[\w\-_]+=.+' ) fixed_args = [ ] for arg in spark_args : if arg not in SPARK_SUBMIT_FLAGS : if not pattern . match ( arg ) : raise SystemExit ( 'Spark argument `%s` does not seem to be in the correct format ' '`ARG_NAME=ARG_VAL`, and is also not recognized to be one of ...
def securitygroupid ( vm_ ) : '''Returns the SecurityGroupId'''
securitygroupid_set = set ( ) securitygroupid_list = config . get_cloud_config_value ( 'securitygroupid' , vm_ , __opts__ , search_global = False ) # If the list is None , then the set will remain empty # If the list is already a set then calling ' set ' on it is a no - op # If the list is a string , then calling ' set...
def read ( self , addr , size ) : '''Read access . : param addr : i2c slave address : type addr : char : param size : size of transfer : type size : int : returns : data byte array : rtype : array . array ( ' B ' )'''
self . set_addr ( addr | 0x01 ) self . set_size ( size ) self . start ( ) while not self . is_ready : pass return self . get_data ( size )