signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def parse ( cls , detail_string ) : """Parse a string represention of Credentials ."""
split = detail_string . split ( ':' ) if len ( split ) != 4 : raise Exception ( 'invalid credentials' ) # TODO : other exception ltpk = binascii . unhexlify ( split [ 0 ] ) ltsk = binascii . unhexlify ( split [ 1 ] ) atv_id = binascii . unhexlify ( split [ 2 ] ) client_id = binascii . unhexlify ( split [ 3 ] ) retu...
def _updateKW ( image , filename , exten , skyKW , Value ) : """update the header with the kw , value"""
# Update the value in memory image . header [ skyKW ] = Value # Now update the value on disk if isinstance ( exten , tuple ) : strexten = '[%s,%s]' % ( exten [ 0 ] , str ( exten [ 1 ] ) ) else : strexten = '[%s]' % ( exten ) log . info ( 'Updating keyword %s in %s' % ( skyKW , filename + strexten ) ) fobj = fil...
def step ( self ) : """Do a single iteration over all cbpdn and ccmod steps . Those that are not coupled on the K axis are performed in parallel ."""
# If the nproc parameter of _ _ init _ _ is zero , just iterate # over the K consensus instances instead of using # multiprocessing to do the computations in parallel . This is # useful for debugging and timing comparisons . if self . nproc == 0 : for k in range ( self . xstep . cri . K ) : step_group ( k )...
def average_percentile ( values ) : """Get the average , min percentile ( 5 % ) and max percentile ( 95 % ) of a list of values . : param values : list of value to compute : type values : list : return : tuple containing average , min and max value : rtype : tuple"""
if not values : return None , None , None value_avg = round ( float ( sum ( values ) ) / len ( values ) , 2 ) value_max = round ( percentile ( values , 95 ) , 2 ) value_min = round ( percentile ( values , 5 ) , 2 ) return value_avg , value_min , value_max
def _construct_url ( self , endpoint ) : """Return the full URL to the specified endpoint"""
parsed_url = urlparse ( self . host ) scheme = parsed_url [ 0 ] host = parsed_url [ 1 ] # Handle host without a scheme specified ( eg . www . example . com ) if scheme == "" : scheme = "http" host = self . host if not endpoint . startswith ( "/" ) : endpoint = "/" + endpoint if self . config [ "api_version"...
def on_resize ( self , width , height ) : """Handle resized windows ."""
width , height = self . _update_perspective ( width , height ) self . scene . camera . resolution = ( width , height ) self . view [ 'ball' ] . resize ( self . scene . camera . resolution ) self . scene . camera . transform = self . view [ 'ball' ] . pose
def list_csv ( self , filter = None , type = None , sort = None , limit = None , page = None ) : # pylint : disable = redefined - builtin """Get a list of results as CSV . : param filter : ( optional ) Filters to apply as a string list . : param type : ( optional ) ` union ` or ` inter ` as string . : param s...
return self . service . list ( self . base , filter , type , sort , limit , page , format = 'csv' ) . text
def process_timer ( self , key , fields ) : """Process a received timer event : param key : Key of timer : param fields : Received fields"""
try : if key not in self . timers : self . timers [ key ] = [ ] self . timers [ key ] . append ( float ( fields [ 0 ] ) ) if self . stats_seen >= maxint : self . logger . info ( "hit maxint, reset seen counter" ) self . stats_seen = 0 self . stats_seen += 1 except Exception as er...
def maybe_new ( cls , values , use_comma = True ) : """If ` values ` contains only one item , return that item . Otherwise , return a List as normal ."""
if len ( values ) == 1 : return values [ 0 ] else : return cls ( values , use_comma = use_comma )
def plot_surface ( x , y , z , color = default_color , wrapx = False , wrapy = False ) : """Draws a 2d surface in 3d , defined by the 2d ordered arrays x , y , z . : param x : { x2d } : param y : { y2d } : param z : { z2d } : param color : { color2d } : param bool wrapx : when True , the x direction is as...
return plot_mesh ( x , y , z , color = color , wrapx = wrapx , wrapy = wrapy , wireframe = False )
def set_ram ( self , ram ) : """Set the amount of RAM allocated to this VirtualBox VM . : param ram : amount RAM in MB ( integer )"""
if ram == 0 : return yield from self . _modify_vm ( '--memory {}' . format ( ram ) ) log . info ( "VirtualBox VM '{name}' [{id}] has set amount of RAM to {ram}" . format ( name = self . name , id = self . id , ram = ram ) ) self . _ram = ram
def _headline ( self , error , i : int ) -> str : """Format the error message ' s headline"""
msgs = Msg ( ) # get the error title if error . errclass == "fatal" : msg = msgs . fatal ( i ) elif error . errclass == "warning" : msg = msgs . warning ( i ) elif error . errclass == "info" : msg = msgs . info ( i ) elif error . errclass == "debug" : msg = msgs . debug ( i ) elif error . errclass == "v...
def export_osm_file ( self ) : """Generate OpenStreetMap element tree from ` ` Osm ` ` ."""
osm = create_elem ( 'osm' , { 'generator' : self . generator , 'version' : self . version } ) osm . extend ( obj . toosm ( ) for obj in self ) return etree . ElementTree ( osm )
def derive_link_fields ( self , context ) : """Used to derive which fields should be linked . This should return a set ( ) containing the names of those fields which should be linkable ."""
if self . link_fields is not None : return self . link_fields else : link_fields = set ( ) if self . fields : for field in self . fields : if field != 'is_active' : link_fields . add ( field ) break return link_fields
def restore_review_history_for ( brain_or_object ) : """Restores the review history for the given brain or object"""
# Get the review history . Note this comes sorted from oldest to newest review_history = get_purged_review_history_for ( brain_or_object ) obj = api . get_object ( brain_or_object ) wf_tool = api . get_tool ( "portal_workflow" ) wf_ids = get_workflow_ids_for ( brain_or_object ) wfs = map ( lambda wf_id : wf_tool . getW...
def settings ( self , height = None , url_params = { } , render = None ) : """Specify iframe height and add URL parameter dictionary . The library takes care of URI component encoding for the dictionary . : param height : Height in pixels . : type height : Integer . : param url _ params : Dictionary of quer...
res = copy . copy ( self ) res . _height = height or self . _height res . _url_params = dict ( self . _url_params , ** url_params ) res . _render = self . _render if render == None else render return res
def visit_Dict ( self , node ) : '''A dict is abstracted as an unordered container of its values > > > from pythran import passmanager > > > pm = passmanager . PassManager ( ' demo ' ) > > > module = ast . parse ( ' def foo ( a , b ) : return { 0 : a , 1 : b } ' ) > > > result = pm . gather ( Aliases , modu...
if node . keys : elts_aliases = set ( ) for key , val in zip ( node . keys , node . values ) : self . visit ( key ) # res ignored , just to fill self . aliases elt_aliases = self . visit ( val ) elts_aliases . update ( map ( ContainerOf , elt_aliases ) ) else : elts_aliases =...
def p_iteration_statement_3 ( self , p ) : """iteration _ statement : FOR LPAREN expr _ noin _ opt SEMI expr _ opt SEMI expr _ opt RPAREN statement | FOR LPAREN VAR variable _ declaration _ list _ noin SEMI expr _ opt SEMI expr _ opt RPAREN statement"""
if len ( p ) == 10 : p [ 0 ] = ast . For ( init = p [ 3 ] , cond = p [ 5 ] , count = p [ 7 ] , statement = p [ 9 ] ) else : init = ast . VarStatement ( p [ 4 ] ) p [ 0 ] = ast . For ( init = init , cond = p [ 6 ] , count = p [ 8 ] , statement = p [ 10 ] )
def isAlmostEqual ( self , tag_name , params = None , fn = None , case_sensitive = False ) : """Compare element with given ` tag _ name ` , ` params ` and / or by lambda function ` fn ` . Lambda function is same as in : meth : ` find ` . Args : tag _ name ( str ) : Compare just name of the element . param...
if isinstance ( tag_name , self . __class__ ) : return self . isAlmostEqual ( tag_name . getTagName ( ) , tag_name . params if tag_name . params else None ) # search by lambda function if fn and not fn ( self ) : return False # compare case sensitive ? comparator = self . _tagname # we need to make self . _ tag...
def inplace_delete_message_queue ( chain_state : ChainState , state_change : Union [ ReceiveDelivered , ReceiveProcessed ] , queueid : QueueIdentifier , ) -> None : """Filter messages from queue , if the queue becomes empty , cleanup the queue itself ."""
queue = chain_state . queueids_to_queues . get ( queueid ) if not queue : return inplace_delete_message ( message_queue = queue , state_change = state_change , ) if len ( queue ) == 0 : del chain_state . queueids_to_queues [ queueid ] else : chain_state . queueids_to_queues [ queueid ] = queue
def get_live_url ( con_pool , method , host , url , headers , retries = 1 , redirect = True , body = None , service_name = None ) : """Return a connection from the pool and perform an HTTP request . : param con _ pool : is the http connection pool associated with the service : param method : HTTP request me...
timeout = con_pool . timeout . read_timeout start_time = time . time ( ) response = con_pool . urlopen ( method , url , body = body , headers = headers , redirect = redirect , retries = retries , timeout = timeout ) request_time = time . time ( ) - start_time rest_request . send ( sender = 'restclients' , url = url , r...
def find ( self , key ) : "Exact matching ( returns value )"
index = self . follow_bytes ( key , self . ROOT ) if index is None : return - 1 if not self . has_value ( index ) : return - 1 return self . value ( index )
def search ( self , id_key = None , ** parameters ) : """Searches TMDb for movie metadata"""
id_tmdb = parameters . get ( "id_tmdb" ) or id_key id_imdb = parameters . get ( "id_imdb" ) title = parameters . get ( "title" ) year = parameters . get ( "year" ) if id_tmdb : yield self . _search_id_tmdb ( id_tmdb ) elif id_imdb : yield self . _search_id_imdb ( id_imdb ) elif title : for result in self . ...
def __get_translation ( self , surah , ayah , lang ) : """Perform http request to get translation from given surah , ayah and language . Parameter : : surah - - Surah index from API pages . : ayat - - Ayat key . : lang - - Language code . Return : : string - - Translation from given surah and ayat .""...
# Construct url to fetch translation data . url = '{base}/translations/{lang}/{lang}_translation_{surah}.json' . format ( base = self . BASE_API , lang = lang , surah = int ( surah ) ) try : response = urlopen ( url ) # Fetch data from give url . data = json . loads ( response . read ( ) . decode ( 'utf-8' ...
def downgrade ( ) : """Downgrade database ."""
op . drop_table ( 'files_multipartobject_part' ) op . drop_index ( op . f ( 'ix_files_object__mimetype' ) , table_name = 'files_object' ) op . drop_table ( 'files_object' ) op . drop_table ( 'files_multipartobject' ) op . drop_table ( 'files_buckettags' ) op . drop_table ( 'files_bucket' ) op . drop_table ( 'files_loca...
def sign_create_cancellation ( cancellation_params , private_key ) : """Function to sign the parameters required to create a cancellation request from the Switcheo Exchange . Execution of this function is as follows : : sign _ create _ cancellation ( cancellation _ params = signable _ params , private _ key = e...
hash_message = defunct_hash_message ( text = stringify_message ( cancellation_params ) ) hex_message = binascii . hexlify ( hash_message ) . decode ( ) signed_message = binascii . hexlify ( Account . signHash ( hex_message , private_key = private_key ) [ 'signature' ] ) . decode ( ) create_params = cancellation_params ...
def align_yaxis_np ( axes ) : """Align zeros of the two axes , zooming them out by same ratio"""
axes = np . array ( axes ) extrema = np . array ( [ ax . get_ylim ( ) for ax in axes ] ) # reset for divide by zero issues for i in range ( len ( extrema ) ) : if np . isclose ( extrema [ i , 0 ] , 0.0 ) : extrema [ i , 0 ] = - 1 if np . isclose ( extrema [ i , 1 ] , 0.0 ) : extrema [ i , 1 ] = ...
def install ( self , io_handler , module_name ) : """Installs the bundle with the given module name"""
bundle = self . _context . install_bundle ( module_name ) io_handler . write_line ( "Bundle ID: {0}" , bundle . get_bundle_id ( ) ) return bundle . get_bundle_id ( )
def validate_cmd_response_str ( name , got , expected , hex_encode = True ) : """Check that some value returned in the response to a command matches what we put in the request ( the command ) ."""
if got != expected : if hex_encode : got_s = got . encode ( 'hex' ) exp_s = expected . encode ( 'hex' ) else : got_s = got exp_s = expected raise ( pyhsm . exception . YHSM_Error ( "Bad %s in response (got %s, expected %s)" % ( name , got_s , exp_s ) ) ) return got
def isin ( self , test_elements ) : """Tests each value in the array for whether it is in test elements . Parameters test _ elements : array _ like The values against which to test each value of ` element ` . This argument is flattened if an array or array _ like . See numpy notes for behavior with non - ...
from . computation import apply_ufunc from . dataset import Dataset from . dataarray import DataArray from . variable import Variable if isinstance ( test_elements , Dataset ) : raise TypeError ( 'isin() argument must be convertible to an array: {}' . format ( test_elements ) ) elif isinstance ( test_elements , ( V...
def SignalAbort ( self ) : """Signals the process to abort ."""
self . _abort = True if self . _extraction_worker : self . _extraction_worker . SignalAbort ( ) if self . _parser_mediator : self . _parser_mediator . SignalAbort ( )
def list ( self , ** filters ) : """Returns a queryset filtering object by user permission . If you want , you can specify filter arguments . See https : / / docs . djangoproject . com / en / dev / ref / models / querysets / # filter for more details"""
LOG . debug ( u'Querying %s by filters=%s' , self . model_class . __name__ , filters ) query = self . __queryset__ ( ) perm = build_permission_name ( self . model_class , 'view' ) LOG . debug ( u"Checking if user %s has_perm %s" % ( self . user , perm ) ) query_with_permission = filter ( lambda o : self . user . has_pe...
def all_independent_generators ( self ) : """Return all generators in this namespace which are not clones ."""
return { g : name for g , name in self . _ns . items ( ) if not is_clone ( g ) }
def restore_repository_from_recycle_bin ( self , repository_details , project , repository_id ) : """RestoreRepositoryFromRecycleBin . [ Preview API ] Recover a soft - deleted Git repository . Recently deleted repositories go into a soft - delete state for a period of time before they are hard deleted and become ...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) content = self . _serialize . body ( repository_de...
def upload_file ( self , source , dest_uri ) : """Upload file to MediaFire . source - - path to the file or a file - like object ( e . g . io . BytesIO ) dest _ uri - - MediaFire Resource URI"""
folder_key , name = self . _prepare_upload_info ( source , dest_uri ) is_fh = hasattr ( source , 'read' ) fd = None try : if is_fh : # Re - using filehandle fd = source else : # Handling fs open / close fd = open ( source , 'rb' ) return MediaFireUploader ( self . api ) . upload ( fd , name ...
def choose ( self , n ) : """Return all unique combinations ( up to permutation ) of n elements , taken without replacement from the contents of the jagged dimension . Combinations are ordered such that those of the first elements precede later ones , e . g . for n = 2 : ( 0,1 ) , ( 0,2 ) , ( 1,2 ) , ( 0,3 ) ...
args = self . _argchoose ( n , absolute = True ) columns = ( self . content [ args . content [ c ] ] for c in args . columns ) out = self . JaggedArray . fromoffsets ( args . offsets , self . Table . named ( "tuple" , * columns ) . flattentuple ( ) ) return out
def get_realms_and_credentials ( self , uri , http_method = 'GET' , body = None , headers = None ) : """Fetch realms and credentials for the presented request token . : param uri : The full URI of the token request . : param http _ method : A valid HTTP verb , i . e . GET , POST , PUT , HEAD , etc . : param b...
request = self . _create_request ( uri , http_method = http_method , body = body , headers = headers ) if not self . request_validator . verify_request_token ( request . resource_owner_key , request ) : raise errors . InvalidClientError ( ) realms = self . request_validator . get_realms ( request . resource_owner_k...
def export_saved_model ( sess , export_dir , tag_set , signatures ) : """Convenience function to export a saved _ model using provided arguments The caller specifies the saved _ model signatures in a simplified python dictionary form , as follows : : signatures = { ' signature _ def _ key ' : { ' inputs ' :...
import tensorflow as tf g = sess . graph g . _unsafe_unfinalize ( ) # https : / / github . com / tensorflow / serving / issues / 363 builder = tf . saved_model . builder . SavedModelBuilder ( export_dir ) logging . info ( "===== signatures: {}" . format ( signatures ) ) signature_def_map = { } for key , sig in signatur...
def _set_increment ( self , statement ) : """Set the increment statement for this loop ( e . g . in a ` for ` ) ."""
assert isinstance ( statement , CodeStatement ) self . increment = statement statement . scope = self . body
def oval ( self , x1 , y1 , x2 , y2 , color = "black" , outline = False , outline_color = "black" ) : """Draws an oval between 2 points : param int x1: The x position of the starting point . : param int y1: The y position of the starting point . : param int x2: The x position of the end point . : para...
return self . tk . create_oval ( x1 , y1 , x2 , y2 , outline = utils . convert_color ( outline_color ) if outline else "" , width = int ( outline ) , fill = "" if color is None else utils . convert_color ( color ) )
def log ( self , entry , * args ) : """Append the string supplied to the log ( a list of strings ) . If additional arguments are supplied , then first string is assumed to be a format string and the other args are used for string interpolation . For instance ` backup . log ( " % d + % d = = % d " , 1 , 1 , 2 ...
if args : entry = entry % args self . backup_log . append ( entry )
def parse_partial ( self , text ) : '''Parse the longest possible prefix of a given string . Return a tuple of the result value and the rest of the string . If failed , raise a ParseError .'''
if not isinstance ( text , str ) : raise TypeError ( 'Can only parsing string but got {!r}' . format ( text ) ) res = self ( text , 0 ) if res . status : return ( res . value , text [ res . index : ] ) else : raise ParseError ( res . expected , text , res . index )
def cli ( env ) : """List IPSec VPN tunnel contexts"""
manager = SoftLayer . IPSECManager ( env . client ) contexts = manager . get_tunnel_contexts ( ) table = formatting . Table ( [ 'id' , 'name' , 'friendly name' , 'internal peer IP address' , 'remote peer IP address' , 'created' ] ) for context in contexts : table . add_row ( [ context . get ( 'id' , '' ) , context ...
def run_wait ( name , location = '\\' ) : r'''Run a scheduled task and return when the task finishes : param str name : The name of the task to run . : param str location : A string value representing the location of the task . Default is ' \ \ ' which is the root for the task scheduler ( C : \ Windows \ Sy...
# Check for existing folder if name not in list_tasks ( location ) : return '{0} not found in {1}' . format ( name , location ) # connect to the task scheduler with salt . utils . winapi . Com ( ) : task_service = win32com . client . Dispatch ( "Schedule.Service" ) task_service . Connect ( ) # get the folder to...
def debugger ( ) : """Return the current debugger instance , or create if none ."""
sdb = _current [ 0 ] if sdb is None or not sdb . active : sdb = _current [ 0 ] = Sdb ( ) return sdb
def import_doc ( self , file_uris , docsearch , current_doc = None ) : """Import the specified PDF file"""
doc = None docs = [ ] pages = [ ] file_uris = [ self . fs . safe ( uri ) for uri in file_uris ] imported = [ ] for file_uri in file_uris : if docsearch . is_hash_in_index ( PdfDoc . hash_file ( self . fs , file_uri ) ) : logger . info ( "Document %s already found in the index. Skipped" % ( file_uri ) ) ...
def libraries ( ) : """return installed library names ."""
ls = libraries_dir ( ) . dirs ( ) ls = [ str ( x . name ) for x in ls ] ls . sort ( ) return ls
def add_edges ( self , from_idx , to_idx , weight = 1 , symmetric = False , copy = False ) : '''Adds all from - > to edges . weight may be a scalar or 1d array . If symmetric = True , also adds to - > from edges with the same weights .'''
raise NotImplementedError ( )
def tab ( self , netloc = None , url = None , extra_id = None , use_tid = False ) : '''Get a chromium tab from the pool , optionally one that has an association with a specific netloc / URL . If no url or netloc is specified , the per - thread identifier will be used . If ` extra _ id ` is specified , it ' s st...
assert self . alive , "Chrome has been shut down! Cannot continue!" if not netloc and url : netloc = urllib . parse . urlparse ( url ) . netloc self . log . debug ( "Getting tab for netloc: %s (url: %s)" , netloc , url ) # Coerce to string type so even if it ' s none , it doesn ' t hurt anything . key = str ( n...
def language_model ( self , verbose = True ) : """builds a Tamil bigram letter model"""
# use a generator in corpus prev = None for next_letter in self . corpus . next_tamil_letter ( ) : # update frequency from corpus if prev : self . letter2 [ prev ] [ next_letter ] += 1 if ( verbose ) : print ( prev ) print ( next_letter ) print ( self . letter2 [ ...
def listen_tta ( self , target , timeout ) : """Listen * timeout * seconds for a Type A activation at 106 kbps . The ` ` sens _ res ` ` , ` ` sdd _ res ` ` , and ` ` sel _ res ` ` response data must be provided and ` ` sdd _ res ` ` must be a 4 byte UID that starts with ` ` 08h ` ` . Depending on ` ` sel _ re...
if target . sel_res and target . sel_res [ 0 ] & 0x20 : info = "{device} does not support listen as Type 4A Target" raise nfc . clf . UnsupportedTargetError ( info . format ( device = self ) ) return super ( Device , self ) . listen_tta ( target , timeout )
def user_path ( self , team , user ) : """Returns the path to directory with the user ' s package repositories ."""
return os . path . join ( self . team_path ( team ) , user )
def managed ( name , ** kwargs ) : '''Manage user account login : string login name password : string password password _ hashed : boolean set if password is a nt hash instead of plain text domain : string users domain profile : string profile path script : string logon script drive : stri...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } # save state saved = __salt__ [ 'pdbedit.list' ] ( hashes = True ) saved = saved [ name ] if name in saved else { } # call pdbedit . modify kwargs [ 'login' ] = name res = __salt__ [ 'pdbedit.modify' ] ( ** kwargs ) # calculate changes if res ...
def render_map ( self ) : """Renders a container and JSON that is picked up by ` static / icekit / js / google _ map . js ` which mounts a responsive static map with overlays and links"""
return ( '<div id="{container_id}" class="google-map"></div>' '<script>' ' gkGoogleMaps = window.gkGoogleMaps || [];' ' gkGoogleMaps.push({data});' '</script>' ) . format ( container_id = self . get_map_element_id ( ) , data = json . dumps ( self . get_map_data ( ) ) , )
def aws ( self ) : """Access the aws : returns : twilio . rest . accounts . v1 . credential . aws . AwsList : rtype : twilio . rest . accounts . v1 . credential . aws . AwsList"""
if self . _aws is None : self . _aws = AwsList ( self . _version , ) return self . _aws
def create_cube ( ) : """Generate vertices & indices for a filled and outlined cube Returns vertices : array Array of vertices suitable for use as a VertexBuffer . filled : array Indices to use to produce a filled cube . outline : array Indices to use to produce an outline of the cube ."""
vtype = [ ( 'position' , np . float32 , 3 ) , ( 'texcoord' , np . float32 , 2 ) , ( 'normal' , np . float32 , 3 ) , ( 'color' , np . float32 , 4 ) ] itype = np . uint32 # Vertices positions p = np . array ( [ [ 1 , 1 , 1 ] , [ - 1 , 1 , 1 ] , [ - 1 , - 1 , 1 ] , [ 1 , - 1 , 1 ] , [ 1 , - 1 , - 1 ] , [ 1 , 1 , - 1 ] , [...
def convert_to_crash_data ( raw_crash , processed_crash ) : """Takes a raw crash and a processed crash ( these are Socorro - centric data structures ) and converts them to a crash data structure used by signature generation . : arg raw _ crash : raw crash data from Socorro : arg processed _ crash : processe...
# We want to generate fresh signatures , so we remove the " normalized " field # from stack frames from the processed crash because this is essentially # cached data from previous processing for thread in glom ( processed_crash , 'json_dump.threads' , default = [ ] ) : for frame in thread . get ( 'frames' , [ ] ) :...
def _read_input_csv ( in_file ) : """Parse useful details from SampleSheet CSV file ."""
with io . open ( in_file , newline = None ) as in_handle : reader = csv . reader ( in_handle ) next ( reader ) # header for line in reader : if line : # empty lines ( fc_id , lane , sample_id , genome , barcode ) = line [ : 5 ] yield fc_id , lane , sample_id , genome , ba...
def passthrough_proc ( self , inputstring , ** kwargs ) : """Process python passthroughs ."""
out = [ ] found = None # store of characters that might be the start of a passthrough hold = None # the contents of the passthrough so far count = None # current parenthetical level ( num closes - num opens ) multiline = None # if in a passthrough , is it a multiline passthrough skips = self . copy_skips ( ) for i , c ...
def _tempDirectories ( self ) : """: rtype : an iterator to the temporary directories containing jobs / stats files in the hierarchy of directories in self . tempFilesDir"""
def _dirs ( path , levels ) : if levels > 0 : for subPath in os . listdir ( path ) : for i in _dirs ( os . path . join ( path , subPath ) , levels - 1 ) : yield i else : yield path for tempDir in _dirs ( self . tempFilesDir , self . levels ) : yield tempDir
def _read_n ( self , l , ret ) : """Reads ' N ' mask from 1 bit file to convert bases to ' N ' . In the 2 bit file , ' N ' or any other invalid base is written as ' A ' . Therefore the ' N ' mask file is required to correctly identify where invalid bases are . Parameters l : tuple location ret : list ...
file = os . path . join ( self . dir , l . chr + ".n.1bit" ) if not os . path . exists ( file ) : return data = DNA2Bit . _read_1bit_file ( file , l ) d = DNA2Bit . _read1bit ( data , l ) for i in range ( 0 , len ( ret ) ) : if d [ i ] == 1 : ret [ i ] = DNA_N_UC
def run ( data ) : """Quantitaive isoforms expression by eXpress"""
name = dd . get_sample_name ( data ) in_bam = dd . get_transcriptome_bam ( data ) config = data [ 'config' ] if not in_bam : logger . info ( "Transcriptome-mapped BAM file not found, skipping eXpress." ) return data out_dir = os . path . join ( dd . get_work_dir ( data ) , "express" , name ) out_file = os . pat...
def _calc_direction ( data , mag , direction , ang , d1 , d2 , theta , slc0 , slc1 , slc2 ) : """This function gives the magnitude and direction of the slope based on Tarboton ' s D _ \ infty method . This is a helper - function to _ tarboton _ slopes _ directions"""
data0 = data [ slc0 ] data1 = data [ slc1 ] data2 = data [ slc2 ] s1 = ( data0 - data1 ) / d1 s2 = ( data1 - data2 ) / d2 s1_2 = s1 ** 2 sd = ( data0 - data2 ) / np . sqrt ( d1 ** 2 + d2 ** 2 ) r = np . arctan2 ( s2 , s1 ) rad2 = s1_2 + s2 ** 2 # Handle special cases # should be on diagonal b_s1_lte0 = s1 <= 0 b_s2_lte...
def to_web ( self , host = None , user = None , password = None ) : """Send the model to BEL Commons by wrapping : py : func : ` pybel . to _ web ` The parameters ` ` host ` ` , ` ` user ` ` , and ` ` password ` ` all check the PyBEL configuration , which is located at ` ` ~ / . config / pybel / config . json...
response = pybel . to_web ( self . model , host = host , user = user , password = password ) return response
def get_url ( self , resource , params = None ) : """Generate url for request"""
# replace placeholders pattern = r'\{(.+?)\}' resource = re . sub ( pattern , lambda t : str ( params . get ( t . group ( 1 ) , '' ) ) , resource ) # build url parts = ( self . endpoint , '/api/' , resource ) return '/' . join ( map ( lambda x : str ( x ) . strip ( '/' ) , parts ) )
def _apply_properties ( widget , properties = { } ) : """Applies the specified properties to the widget . ` properties ` is a dictionary with key value pairs corresponding to the properties to be applied to the widget ."""
with widget . hold_sync ( ) : for key , value in properties . items ( ) : setattr ( widget , key , value )
def get_relation_type ( self , relation_type ) : """Get all the items of the given relationship type related to this item ."""
qs = self . get_queryset ( ) return qs . filter ( relation_type = relation_type )
def set_column_flat ( self , field , value , components = None , computed_type = None ) : """TODO : add documentation TODO : needs testing"""
value_dict = self . unpack_column_flat ( value , components , computed_type = computed_type ) self . update_columns ( field , value_dict , computed_type = computed_type )
def insertElementTable ( self , token ) : """Create an element and insert it into the tree"""
element = self . createElement ( token ) if self . openElements [ - 1 ] . name not in tableInsertModeElements : return self . insertElementNormal ( token ) else : # We should be in the InTable mode . This means we want to do # special magic element rearranging parent , insertBefore = self . getTableMisnestedNod...
def to_simple ( self , request , data , many = False , ** kwargs ) : """Serialize response to simple object ( list , dict ) ."""
schema = self . get_schema ( request , ** kwargs ) return schema . dump ( data , many = many ) . data if schema else data
def mesh ( self , mesh_size = 1 , extra_height = 0.1 , edge = True , attach = True ) : """Generates a set of points distributed in a mesh that covers the whole Place and computes their height . Generates a xy mesh with a given mesh _ size in the Place . surface ' s domain and computes the Surface ' s height f...
# Mesh a , b = self . get_domain ( ) a -= 2 * mesh_size # extra bound b += 2 * mesh_size x_mesh = np . arange ( a [ 0 ] , b [ 0 ] , mesh_size ) y_mesh = np . arange ( a [ 1 ] , b [ 1 ] , mesh_size ) x , y = np . meshgrid ( x_mesh , y_mesh ) xy = np . array ( [ x . ravel ( ) , y . ravel ( ) ] ) . T # Compute and store x...
def _init_vocab_from_file ( self , filename ) : """Load vocab from a file . Args : filename : The file to load vocabulary from ."""
with tf . gfile . Open ( filename ) as f : tokens = [ token . strip ( ) for token in f . readlines ( ) ] def token_gen ( ) : for token in tokens : yield token self . _init_vocab ( token_gen ( ) , add_reserved_tokens = False )
async def get_tournament ( self , t_id : int = None , url : str = None , subdomain : str = None , force_update = False ) -> Tournament : """gets a tournament with its id or url or url + subdomain Note : from the API , it can ' t be known if the retrieved tournament was made from this user . Thus , any tournamen...
assert_or_raise ( ( t_id is None ) ^ ( url is None ) , ValueError , 'One of t_id or url must not be None' ) found_t = self . _find_tournament_by_id ( t_id ) if t_id is not None else self . _find_tournament_by_url ( url , subdomain ) if force_update or found_t is None : param = t_id if param is None : if...
def compress_repr ( self ) -> str : """Works as | Parameter . compress _ repr | , but returns a string with constant names instead of constant values . See the main documentation on class | NameParameter | for further information ."""
string = super ( ) . compress_repr ( ) if string in ( '?' , '[]' ) : return string if string is None : values = self . values else : values = [ int ( string ) ] invmap = { value : key for key , value in self . CONSTANTS . items ( ) } result = ', ' . join ( invmap . get ( value , repr ( value ) ) for value i...
def _as_in_context ( data , ctx ) : """Move data into new context ."""
if isinstance ( data , nd . NDArray ) : return data . as_in_context ( ctx ) elif isinstance ( data , ( list , tuple ) ) : return [ _as_in_context ( d , ctx ) for d in data ] return data
def killCells ( self , percent = 0.05 ) : """Changes the percentage of cells that are now considered dead . The first time you call this method a permutation list is set up . Calls change the number of cells considered dead ."""
numColumns = numpy . prod ( self . getColumnDimensions ( ) ) if self . zombiePermutation is None : self . zombiePermutation = numpy . random . permutation ( numColumns ) self . numDead = int ( round ( percent * numColumns ) ) if self . numDead > 0 : self . deadCols = self . zombiePermutation [ 0 : self . numDea...
def boardToString ( self , margins = None ) : """return a string representation of the current board ."""
if margins is None : margins = { } b = self . board rg = range ( b . size ( ) ) left = ' ' * margins . get ( 'left' , 0 ) s = '\n' . join ( [ left + ' ' . join ( [ self . getCellStr ( x , y ) for x in rg ] ) for y in rg ] ) return s
def _Backward2a_T_Ps ( P , s ) : """Backward equation for region 2a , T = f ( P , s ) Parameters P : float Pressure , [ MPa ] s : float Specific entropy , [ kJ / kgK ] Returns T : float Temperature , [ K ] References IAPWS , Revised Release on the IAPWS Industrial Formulation 1997 for the Ther...
I = [ - 1.5 , - 1.5 , - 1.5 , - 1.5 , - 1.5 , - 1.5 , - 1.25 , - 1.25 , - 1.25 , - 1.0 , - 1.0 , - 1.0 , - 1.0 , - 1.0 , - 1.0 , - 0.75 , - 0.75 , - 0.5 , - 0.5 , - 0.5 , - 0.5 , - 0.25 , - 0.25 , - 0.25 , - 0.25 , 0.25 , 0.25 , 0.25 , 0.25 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.75 , 0.75 , 0.75 , 0.75 , 1.0 , 1...
def getNamespaces ( self ) : """Get the I { unique } set of namespaces referenced in the branch . @ return : A set of namespaces . @ rtype : set"""
s = set ( ) for n in self . branch + self . node . ancestors ( ) : if self . permit ( n . expns ) : s . add ( n . expns ) s = s . union ( self . pset ( n ) ) return s
def size ( self ) : """The number of instances in the data . If the underlying data source changes , it may be outdated ."""
import tensorflow as tf if self . _size is None : self . _size = 0 options = tf . python_io . TFRecordOptions ( tf . python_io . TFRecordCompressionType . GZIP ) for tfexample_file in self . files : self . _size += sum ( 1 for x in tf . python_io . tf_record_iterator ( tfexample_file , options = opt...
def qrange ( self , name , offset , limit ) : """Return a ` ` limit ` ` slice of the list ` ` name ` ` at position ` ` offset ` ` ` ` offset ` ` can be negative numbers just like Python slicing notation Similiar with * * Redis . LRANGE * * : param string name : the queue name : param int offset : the return...
offset = get_integer ( 'offset' , offset ) limit = get_positive_integer ( 'limit' , limit ) return self . execute_command ( 'qrange' , name , offset , limit )
def read_file ( filename ) : """Read a file into a string"""
p = path . abspath ( path . dirname ( __file__ ) ) filepath = path . join ( p , filename ) try : return open ( filepath ) . read ( ) except IOError : return ''
def _starttls ( self ) : """Exchange a STARTTLS message with Riak to initiate secure communications return True is Riak responds with a STARTTLS response , False otherwise"""
resp_code , _ = self . _non_connect_send_recv ( riak . pb . messages . MSG_CODE_START_TLS ) if resp_code == riak . pb . messages . MSG_CODE_START_TLS : return True else : return False
def validate ( self , value ) : """Applies the validation criteria . Returns value , new value , or None if invalid ."""
try : coord . Angle ( value , unit = self . unit ) return value except ValueError : return None
def filter_user_term_matrix ( user_term_matrix , annotated_nodes , label_to_topic , max_number_of_labels = None ) : """Filters out labels that are either too rare , or have very few representatives . Inputs : - user _ term _ matrix : A user - to - term matrix in scipy sparse matrix format . - annotated _ nodes ...
# Aggregate edges and eliminate zeros . user_term_matrix = user_term_matrix . tocsr ( ) user_term_matrix . eliminate_zeros ( ) # Enforce max number of labels if required . # Form matrix that indicates which user - label pairs are nonzero . temp_matrix = copy . copy ( user_term_matrix ) temp_matrix . data = np . ones_li...
def apply ( self , strain , detector_name , f_lower = None , distance_scale = 1 , simulation_ids = None , inj_filter_rejector = None ) : """Add injections ( as seen by a particular detector ) to a time series . Parameters strain : TimeSeries Time series to inject signals into , of type float32 or float64. d...
if strain . dtype not in ( float32 , float64 ) : raise TypeError ( "Strain dtype must be float32 or float64, not " + str ( strain . dtype ) ) lalstrain = strain . lal ( ) earth_travel_time = lal . REARTH_SI / lal . C_SI t0 = float ( strain . start_time ) - earth_travel_time t1 = float ( strain . end_time ) + earth_...
def _verify_client ( self , low ) : '''Verify that the client is in fact one we have'''
if 'client' not in low or low . get ( 'client' ) not in self . saltclients : self . set_status ( 400 ) self . write ( "400 Invalid Client: Client not found in salt clients" ) self . finish ( ) return False return True
def QA_fetch_get_future_transaction_realtime ( code , ip = None , port = None ) : '期货历史成交分笔'
ip , port = get_extensionmarket_ip ( ip , port ) apix = TdxExHq_API ( ) global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list ( ) if extension_market_list is None else extension_market_list code_market = extension_market_list . query ( 'code=="{}"' . format ( code ) ) . iloc [ 0 ] with ...
def sell_close ( id_or_ins , amount , price = None , style = None , close_today = False ) : """平买仓 : param id _ or _ ins : 下单标的物 : type id _ or _ ins : : class : ` ~ Instrument ` object | ` str ` | List [ : class : ` ~ Instrument ` ] | List [ ` str ` ] : param int amount : 下单手数 : param float price : 下单价格 , ...
position_effect = POSITION_EFFECT . CLOSE_TODAY if close_today else POSITION_EFFECT . CLOSE return order ( id_or_ins , amount , SIDE . SELL , position_effect , cal_style ( price , style ) )
def _loop_once ( self , timeout = None ) : """Execute a single : class : ` Poller ` wait , dispatching any IO events that caused the wait to complete . : param float timeout : If not : data : ` None ` , maximum time in seconds to wait for events ."""
_vv and IOLOG . debug ( '%r._loop_once(%r, %r)' , self , timeout , self . poller ) # IOLOG . debug ( ' readers = \ n % s ' , pformat ( self . poller . readers ) ) # IOLOG . debug ( ' writers = \ n % s ' , pformat ( self . poller . writers ) ) for side , func in self . poller . poll ( timeout ) : self . _call ( side...
def attemptToAddJob ( self , jobShape , nodeShape , targetTime ) : """Attempt to pack a job into this reservation timeslice and / or the reservations after it . jobShape is the Shape of the job requirements , nodeShape is the Shape of the node this is a reservation for , and targetTime is the maximum time to wa...
# starting slice of time that we can fit in so far startingReservation = self # current end of the slices we can fit in so far endingReservation = startingReservation # the amount of runtime of the job currently covered by slices availableTime = 0 # total time from when the instance started up to startingReservation st...
def render_arrow ( self , label , start , end , direction , i ) : """Render individual arrow . label ( unicode ) : Dependency label . start ( int ) : Index of start word . end ( int ) : Index of end word . direction ( unicode ) : Arrow direction , ' left ' or ' right ' . i ( int ) : Unique ID , typically ...
level = self . levels . index ( end - start ) + 1 x_start = self . offset_x + start * self . distance + self . arrow_spacing if self . direction == "rtl" : x_start = self . width - x_start y = self . offset_y x_end = ( self . offset_x + ( end - start ) * self . distance + start * self . distance - self . arrow_spac...
def _get_exec_driver ( ) : '''Get the method to be used in shell commands'''
contextkey = 'docker.exec_driver' if contextkey not in __context__ : from_config = __salt__ [ 'config.get' ] ( contextkey , None ) # This if block can be removed once we make docker - exec a default # option , as it is part of the logic in the commented block above . if from_config is not None : ...
def next_doc_with_tag ( self , doc_tag ) : """Returns the next document with the specified tag . Empty string is no doc is found ."""
while True : try : doc = next ( self ) if doc . tag == doc_tag : return doc except StopIteration : raise
def p_variable ( p ) : '''variable : base _ variable _ with _ function _ calls OBJECT _ OPERATOR object _ property method _ or _ not variable _ properties | base _ variable _ with _ function _ calls'''
if len ( p ) == 6 : name , dims = p [ 3 ] params = p [ 4 ] if params is not None : p [ 0 ] = ast . MethodCall ( p [ 1 ] , name , params , lineno = p . lineno ( 2 ) ) else : p [ 0 ] = ast . ObjectProperty ( p [ 1 ] , name , lineno = p . lineno ( 2 ) ) for class_ , dim , lineno in dims...
def pause ( self , lastGoodStep = 0 ) : # type : ( ALastGoodStep ) - > None """Pause a run ( ) so that resume ( ) can be called later , or seek within an Armed or Paused state . The original call to run ( ) will not be interrupted by pause ( ) , it will wait until the scan completes or is aborted . Normally...
current_state = self . state . value if lastGoodStep <= 0 : last_good_step = self . completed_steps . value else : last_good_step = lastGoodStep if current_state == ss . RUNNING : next_state = ss . PAUSED else : next_state = current_state assert last_good_step < self . total_steps . value , "Cannot seek...
def validate_aead_otp ( self , public_id , otp , key_handle , aead ) : """Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key _ handle to decrypt the AEAD . @ param public _ id : The six bytes public id of the YubiKey @ param otp : The one time password ( OTP ) to validate @ param key _ handle : T...
if type ( public_id ) is not str : assert ( ) if type ( otp ) is not str : assert ( ) if type ( key_handle ) is not int : assert ( ) if type ( aead ) is not str : assert ( ) return pyhsm . validate_cmd . YHSM_Cmd_AEAD_Validate_OTP ( self . stick , public_id , otp , key_handle , aead ) . execute ( )
def send_workflow ( self ) : """With the workflow instance and the task invitation is assigned a role ."""
task_invitation = TaskInvitation . objects . get ( self . task_invitation_key ) wfi = task_invitation . instance select_role = self . input [ 'form' ] [ 'select_role' ] if wfi . current_actor == self . current . role : task_invitation . role = RoleModel . objects . get ( select_role ) wfi . current_actor = Role...
def read ( self , files ) : """Read settings from given config files . @ raises : LinkCheckerError on syntax errors in the config file ( s )"""
assert isinstance ( files , list ) , "Invalid file list %r" % files try : self . read_ok = super ( LCConfigParser , self ) . read ( files ) if len ( self . read_ok ) < len ( files ) : failed_files = set ( files ) - set ( self . read_ok ) log . warn ( LOG_CHECK , "Could not read configuration fil...
def QA_SU_save_future_min ( client = DATABASE , ui_log = None , ui_progress = None ) : """save future _ min Keyword Arguments : client { [ type ] } - - [ description ] ( default : { DATABASE } )"""
future_list = [ item for item in QA_fetch_get_future_list ( ) . code . unique ( ) . tolist ( ) if str ( item ) [ - 2 : ] in [ 'L8' , 'L9' ] ] coll = client . future_min coll . create_index ( [ ( 'code' , pymongo . ASCENDING ) , ( 'time_stamp' , pymongo . ASCENDING ) , ( 'date_stamp' , pymongo . ASCENDING ) ] ) err = [ ...