signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def help_center_article_translations ( self , article_id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / translations # list - translations"
api_path = "/api/v2/help_center/articles/{article_id}/translations.json" api_path = api_path . format ( article_id = article_id ) return self . call ( api_path , ** kwargs )
def K_butterfly_valve_Crane ( D , fd = None , style = 0 ) : r'''Returns the loss coefficient for a butterfly valve as shown in [1 ] _ . Three different types are supported ; Centric ( ` style ` = 0 ) , double offset ( ` style ` = 1 ) , and triple offset ( ` style ` = 2 ) . . . math : : K = N \ cdot f _ d ...
if fd is None : fd = ft_Crane ( D ) try : c1 , c2 , c3 = butterfly_valve_Crane_coeffs [ style ] except KeyError : raise KeyError ( 'Accepted valve styles are 0 (centric), 1 (double offset), or 2 (triple offset) only.' ) if D <= 0.2286 : # 2-8 inches , split at 9 inch return c1 * fd elif D <= 0.381 : # 1...
def get_preorder_burn_info ( outputs ) : """Given the set of outputs , find the fee sent to our burn address . This is always the third output . Return the fee and burn address on success as { ' op _ fee ' : . . . , ' burn _ address ' : . . . } Return None if not found"""
if len ( outputs ) != 3 : # not a well - formed preorder return None op_fee = outputs [ 2 ] [ 'value' ] burn_address = None try : burn_address = virtualchain . script_hex_to_address ( outputs [ 2 ] [ 'script' ] ) assert burn_address except : log . error ( "Not a well-formed preorder burn: {}" . format (...
def zk_client ( host , scheme , credential ) : """returns a connected ( and possibly authenticated ) ZK client"""
if not re . match ( r".*:\d+$" , host ) : host = "%s:%d" % ( host , DEFAULT_ZK_PORT ) client = KazooClient ( hosts = host ) client . start ( ) if scheme != "" : client . add_auth ( scheme , credential ) return client
def subCell2DCoords ( * args , ** kwargs ) : '''Same as subCell2DSlices but returning coordinates Example : g = subCell2DCoords ( arr , shape ) for x , y in g : plt . plot ( x , y )'''
for _ , _ , s0 , s1 in subCell2DSlices ( * args , ** kwargs ) : yield ( ( s1 . start , s1 . start , s1 . stop ) , ( s0 . start , s0 . stop , s0 . stop ) )
def get_best_match_zone ( all_zones , domain ) : """Return zone id which name is closer matched with domain name ."""
# Related : https : / / github . com / Miserlou / Zappa / issues / 459 public_zones = [ zone for zone in all_zones [ 'HostedZones' ] if not zone [ 'Config' ] [ 'PrivateZone' ] ] zones = { zone [ 'Name' ] [ : - 1 ] : zone [ 'Id' ] for zone in public_zones if zone [ 'Name' ] [ : - 1 ] in domain } if zones : keys = ma...
def execute ( self , transition ) : """Queue a transition for execution . : param transition : The transition"""
self . _transitions . append ( transition ) if self . _thread is None or not self . _thread . isAlive ( ) : self . _thread = threading . Thread ( target = self . _transition_loop ) self . _thread . setDaemon ( True ) self . _thread . start ( )
def drop_view ( self , viewname : str ) -> int : """Drops a view ."""
sql = "DROP VIEW IF EXISTS {}" . format ( viewname ) log . info ( "Dropping view " + viewname + " (ignore any warning here)" ) return self . db_exec_literal ( sql )
def fixtures ( ) : """Command for working with test data ."""
temp_path = os . path . join ( os . path . dirname ( __file__ ) , 'temp' ) demo_files_path = os . path . join ( os . path . dirname ( __file__ ) , 'demo_files' ) # Create location loc = Location ( name = 'local' , uri = temp_path , default = True ) db . session . add ( loc ) db . session . commit ( ) # Example files fr...
def rar ( rarfile , sources , template = None , cwd = None , runas = None ) : '''Uses ` rar for Linux ` _ to create rar files . . _ ` rar for Linux ` : http : / / www . rarlab . com / rarfile Path of rar file to be created sources Comma - separated list of sources to include in the rar file . Sources can ...
cmd = [ 'rar' , 'a' , '-idp' , '{0}' . format ( rarfile ) ] cmd . extend ( _expand_sources ( sources ) ) return __salt__ [ 'cmd.run' ] ( cmd , cwd = cwd , template = template , runas = runas , python_shell = False ) . splitlines ( )
def _pathway_side_information ( pathway_positive_series , pathway_negative_series , index ) : """Create the pandas . Series containing the side labels that correspond to each pathway , based on the user - specified gene signature definition ."""
positive_series_label = pd . Series ( [ "pos" ] * len ( pathway_positive_series ) ) negative_series_label = pd . Series ( [ "neg" ] * len ( pathway_negative_series ) ) side_information = positive_series_label . append ( negative_series_label ) side_information . index = index side_information . name = "side" return sid...
def list_experiments ( self , collection_name ) : """List all experiments that belong to a collection . Args : collection _ name ( string ) : Name of the parent collection . Returns : ( list ) Raises : requests . HTTPError on failure ."""
exp = ExperimentResource ( name = '' , collection_name = collection_name , coord_frame = 'foo' ) return self . _list_resource ( exp )
def is_null_like ( x ) : """Determine whether an object is effectively null . : param object x : Object for which null likeness is to be determined . : return bool : Whether given object is effectively " null . " """
return x in [ None , "" ] or ( coll_like ( x ) and isinstance ( x , Sized ) and 0 == len ( x ) )
def setup_logging ( name ) : """Setup logging according to environment variables ."""
logger = logging . getLogger ( __name__ ) if 'NVIM_PYTHON_LOG_FILE' in os . environ : prefix = os . environ [ 'NVIM_PYTHON_LOG_FILE' ] . strip ( ) major_version = sys . version_info [ 0 ] logfile = '{}_py{}_{}' . format ( prefix , major_version , name ) handler = logging . FileHandler ( logfile , 'w' , ...
def remove_entry ( self , pathname_name , recursive = True ) : """Removes the specified child file or directory . Args : pathname _ name : Basename of the child object to remove . recursive : If True ( default ) , the entries in contained directories are deleted first . Used to propagate removal errors ( ...
pathname_name = self . _normalized_entryname ( pathname_name ) entry = self . get_entry ( pathname_name ) if self . filesystem . is_windows_fs : if entry . st_mode & PERM_WRITE == 0 : self . filesystem . raise_os_error ( errno . EACCES , pathname_name ) if self . filesystem . has_open_file ( entry ) : ...
def _exec_cleanup ( self , cursor , fd ) : """Close the cursor , remove any references to the fd in internal state and remove the fd from the ioloop . : param psycopg2 . extensions . cursor cursor : The cursor to close : param int fd : The connection file descriptor"""
LOGGER . debug ( 'Closing cursor and cleaning %s' , fd ) try : cursor . close ( ) except ( psycopg2 . Error , psycopg2 . Warning ) as error : LOGGER . debug ( 'Error closing the cursor: %s' , error ) self . _cleanup_fd ( fd ) # If the cleanup callback exists , remove it if self . _cleanup_callback : self . ...
def transformer_tall_pretrain_lm_tpu_adafactor ( ) : """Hparams for transformer on LM pretraining ( with 64k vocab ) on TPU ."""
hparams = transformer_tall_pretrain_lm ( ) update_hparams_for_tpu ( hparams ) hparams . max_length = 1024 # For multi - problem on TPU we need it in absolute examples . hparams . batch_size = 8 hparams . multiproblem_vocab_size = 2 ** 16 return hparams
def _verify_client_authentication ( self , request_body , http_headers = None ) : # type ( str , Optional [ Mapping [ str , str ] ] - > Mapping [ str , str ] """Verifies the client authentication . : param request _ body : urlencoded token request : param http _ headers : : return : The parsed request body ."...
if http_headers is None : http_headers = { } token_request = dict ( parse_qsl ( request_body ) ) token_request [ 'client_id' ] = verify_client_authentication ( self . clients , token_request , http_headers . get ( 'Authorization' ) ) return token_request
def tama_read ( self , filename ) : """Parse the science segments from a tama list of locked segments contained in file . @ param filename : input text file containing a list of tama segments ."""
self . __filename = filename for line in open ( filename ) : columns = line . split ( ) id = int ( columns [ 0 ] ) start = int ( math . ceil ( float ( columns [ 3 ] ) ) ) end = int ( math . floor ( float ( columns [ 4 ] ) ) ) dur = end - start x = ScienceSegment ( tuple ( [ id , start , end , du...
def _create_morlet ( options , s_freq ) : """Create morlet wavelets , with scipy . signal doing the actual computation . Parameters foi : ndarray or list or tuple vector with frequency of interest s _ freq : int or float sampling frequency of the data options : dict with ' M _ in _ s ' ( duration of t...
wavelets = [ ] foi = options . pop ( 'foi' ) for f in foi : wavelets . append ( morlet ( f , s_freq , ** options ) ) return wavelets
def set_default_viewport ( self ) : """Calculates the viewport based on the configured aspect ratio . Will add black borders and center the viewport if the window do not match the configured viewport . If aspect ratio is None the viewport will be scaled to the entire window size regardless of size ."""
if self . aspect_ratio : expected_width = int ( self . buffer_height * self . aspect_ratio ) expected_height = int ( expected_width / self . aspect_ratio ) if expected_width > self . buffer_width : expected_width = self . buffer_width expected_height = int ( expected_width / self . aspect_ra...
def spectral_entropy ( X , Band , Fs , Power_Ratio = None ) : """Compute spectral entropy of a time series from either two cases below : 1 . X , the time series ( default ) 2 . Power _ Ratio , a list of normalized signal power in a set of frequency bins defined in Band ( if Power _ Ratio is provided , recomme...
if Power_Ratio is None : Power , Power_Ratio = bin_power ( X , Band , Fs ) Spectral_Entropy = 0 for i in range ( 0 , len ( Power_Ratio ) - 1 ) : Spectral_Entropy += Power_Ratio [ i ] * numpy . log ( Power_Ratio [ i ] ) Spectral_Entropy /= numpy . log ( len ( Power_Ratio ) ) # to save time , minus one is omitted...
def print_variant ( variant_line , outfile = None , silent = False ) : """Print a variant . If a result file is provided the variante will be appended to the file , otherwise they are printed to stdout . Args : variants _ file ( str ) : A string with the path to a file outfile ( FileHandle ) : An opened f...
variant_line = variant_line . rstrip ( ) if not variant_line . startswith ( '#' ) : if outfile : outfile . write ( variant_line + '\n' ) else : if not silent : print ( variant_line ) return
def _options ( self , ** kwargs ) : """Formats search parameters / values for use with API : param \ * \ * kwargs : search parameters / values"""
def _format_fq ( d ) : for k , v in d . items ( ) : if isinstance ( v , list ) : d [ k ] = ' ' . join ( map ( lambda x : '"' + x + '"' , v ) ) else : d [ k ] = '"' + v + '"' values = [ ] for k , v in d . items ( ) : value = '%s:(%s)' % ( k , v ) values...
def get_hypervisors ( self ) : """Initialize the internal list containing each template available for each hypervisor . : return : [ bool ] True in case of success , otherwise False"""
json_scheme = self . gen_def_json_scheme ( 'GetHypervisors' ) json_obj = self . call_method_post ( method = 'GetHypervisors' , json_scheme = json_scheme ) self . json_templates = json_obj d = dict ( json_obj ) for elem in d [ 'Value' ] : hv = self . hypervisors [ elem [ 'HypervisorType' ] ] for inner_elem in el...
def loads ( string , filename = None , includedir = '' ) : '''Load the contents of ` ` string ` ` to a Python object The returned object is a subclass of ` ` dict ` ` that exposes string keys as attributes as well . Example : > > > config = libconf . loads ( ' window : { title : " libconfig example " ; } ; ...
try : f = io . StringIO ( string ) except TypeError : raise TypeError ( "libconf.loads() input string must by unicode" ) return load ( f , filename = filename , includedir = includedir )
def before_request ( self , fn ) : """Registers a function to run before each request . For example , this can be used to open a database connection , or to load the logged in user from the session . The function will be called without any arguments . If it returns a non - None value , the value is handled ...
self . _defer ( lambda app : app . before_request ( fn ) ) return fn
def put ( self , request , bot_id , hook_id , id , format = None ) : """Update existing telegram recipient serializer : TelegramRecipientSerializer responseMessages : - code : 401 message : Not authenticated - code : 400 message : Not valid request"""
bot = self . get_bot ( bot_id , request . user ) hook = self . get_hook ( hook_id , bot , request . user ) recipient = self . get_recipient ( id , hook , request . user ) serializer = self . serializer ( recipient , data = request . data ) if serializer . is_valid ( ) : serializer . save ( ) return Response ( s...
def from_unknown ( cls , value , xx = False , xxx = False , locale = False , name = False ) : """Try to create a Language instance having only some limited data about the Language . If no corresponding Language is found , a NotALanguageException is thrown . : param value : data known about the language as strin...
# Use 2 lists instead of dict = = > order known keys = [ 'ISO639' , 'LanguageID' , 'locale' , 'LanguageName' ] truefalses = [ xx , xxx , locale , name ] value = value . lower ( ) for key , doKey in zip ( keys , truefalses ) : if doKey : try : return cls . _from_xyz ( key , value ) except...
def run_matrix ( self , matrix_definition , document ) : """Running pipeline via a matrix . Args : matrix _ definition ( dict ) : one concrete matrix item . document ( dict ) : spline document ( complete ) as loaded from yaml file ."""
matrix = Matrix ( matrix_definition , 'matrix(parallel)' in document ) process_data = MatrixProcessData ( ) process_data . options = self . options process_data . pipeline = document [ 'pipeline' ] process_data . model = { } if 'model' not in document else document [ 'model' ] process_data . hooks = Hooks ( document ) ...
def _convert_to_example ( filename , image_buffer , label , synset , human , bbox , height , width ) : """Build an Example proto for an example . Args : filename : string , path to an image file , e . g . , ' / path / to / example . JPG ' image _ buffer : string , JPEG encoding of RGB image label : integer ...
xmin = [ ] ymin = [ ] xmax = [ ] ymax = [ ] for b in bbox : assert len ( b ) == 4 # pylint : disable = expression - not - assigned [ l . append ( point ) for l , point in zip ( [ xmin , ymin , xmax , ymax ] , b ) ] # pylint : enable = expression - not - assigned colorspace = 'RGB' channels = 3 image_for...
def add_states ( self , * states ) : '''Add @ states .'''
for state in states : self . states [ state ] = EventManagerPlus ( self )
def on_successful_login ( self , subject , authc_token , account_id ) : """Reacts to the successful login attempt by first always forgetting any previously stored identity . Then if the authc _ token is a ` ` RememberMe ` ` type of token , the associated identity will be remembered for later retrieval during ...
# always clear any previous identity : self . forget_identity ( subject ) # now save the new identity : if authc_token . is_remember_me : self . remember_identity ( subject , authc_token , account_id ) else : msg = ( "AuthenticationToken did not indicate that RememberMe is " "requested. RememberMe functionalit...
def convert ( self , value , _type ) : """Convert instances of textx types and match rules to python types ."""
return self . type_convertors . get ( _type , lambda x : x ) ( value )
def _find_workflows ( mcs , attrs ) : """Find workflow definition ( s ) in a WorkflowEnabled definition . This method overrides the default behavior from xworkflows in order to use our custom StateField objects ."""
workflows = { } for k , v in attrs . items ( ) : if isinstance ( v , StateField ) : workflows [ k ] = v return workflows
def get_cameras_properties ( self ) : """Return camera properties ."""
resource = "cameras" resource_event = self . publish_and_get_event ( resource ) if resource_event : self . _last_refresh = int ( time . time ( ) ) self . _camera_properties = resource_event . get ( 'properties' )
def memory ( self ) : """Memory information in bytes Example : > > > print ( ctx . device ( 0 ) . memory ( ) ) { ' total ' : 4238016512L , ' used ' : 434831360L , ' free ' : 3803185152L } Returns : total / used / free memory in bytes"""
class GpuMemoryInfo ( Structure ) : _fields_ = [ ( 'total' , c_ulonglong ) , ( 'free' , c_ulonglong ) , ( 'used' , c_ulonglong ) , ] c_memory = GpuMemoryInfo ( ) _check_return ( _NVML . get_function ( "nvmlDeviceGetMemoryInfo" ) ( self . hnd , byref ( c_memory ) ) ) return { 'total' : c_memory . total , 'free' : c_...
def get_idx ( self , arr : Collection , is_item : bool = True ) : "Fetch item or user ( based on ` is _ item ` ) for all in ` arr ` . ( Set model to ` cpu ` and no grad . )"
m = self . model . eval ( ) . cpu ( ) requires_grad ( m , False ) u_class , i_class = self . data . train_ds . x . classes . values ( ) classes = i_class if is_item else u_class c2i = { v : k for k , v in enumerate ( classes ) } try : return tensor ( [ c2i [ o ] for o in arr ] ) except Exception as e : print ( ...
def _box_points ( values , mode = 'extremes' ) : """Default mode : ( mode = ' extremes ' or unset ) Return a 7 - tuple of 2x minimum , Q1 , Median , Q3, and 2x maximum for a list of numeric values . 1.5IQR mode : ( mode = ' 1.5IQR ' ) Return a 7 - tuple of min , Q1 - 1.5 * IQR , Q1 , Median , Q3, Q3 + 1.5...
def median ( seq ) : n = len ( seq ) if n % 2 == 0 : # seq has an even length return ( seq [ n // 2 ] + seq [ n // 2 - 1 ] ) / 2 else : # seq has an odd length return seq [ n // 2 ] def mean ( seq ) : return sum ( seq ) / len ( seq ) def stdev ( seq ) : m = mean ( seq ) l = len (...
def get_rt_ticker ( self , code , num = 500 ) : """获取指定股票的实时逐笔 。 取最近num个逐笔 : param code : 股票代码 : param num : 最近ticker个数 ( 有最大个数限制 , 最近1000个 ) : return : ( ret , data ) ret = = RET _ OK 返回pd dataframe数据 , 数据列格式如下 ret ! = RET _ OK 返回错误字符串 参数 类型 说明 stock _ code str 股票代码 sequence int 逐笔序号 time str 成交时...
if code is None or is_str ( code ) is False : error_str = ERROR_STR_PREFIX + "the type of code param is wrong" return RET_ERROR , error_str if num is None or isinstance ( num , int ) is False : error_str = ERROR_STR_PREFIX + "the type of num param is wrong" return RET_ERROR , error_str query_processor =...
def patches ( self , dwn , install , comp_sum , uncomp_sum ) : """Seperates packages from patches / directory"""
dwnp , installp , comp_sump , uncomp_sump = ( [ ] for i in range ( 4 ) ) for d , i , c , u in zip ( dwn , install , comp_sum , uncomp_sum ) : if "_slack" + slack_ver ( ) in i : dwnp . append ( d ) dwn . remove ( d ) installp . append ( i ) install . remove ( i ) comp_sump . a...
def parse ( self , m , prefix = None ) : """Parse branch notification messages sent by Launchpad ."""
subject = m [ "subject" ] match = re . search ( r"^\s*\[Branch\s+([^]]+)\]" , subject ) if match : repository = match . group ( 1 ) else : repository = None # Put these into a dictionary , otherwise we cannot assign them # from nested function definitions . d = { 'files' : [ ] , 'comments' : "" } gobbler = None...
def dpu ( self , hash = None , historics_id = None ) : """Calculate the DPU cost of consuming a stream . Uses API documented at http : / / dev . datasift . com / docs / api / rest - api / endpoints / dpu : param hash : target CSDL filter hash : type hash : str : returns : dict with extra response data : r...
if hash : return self . request . get ( 'dpu' , params = dict ( hash = hash ) ) if historics_id : return self . request . get ( 'dpu' , params = dict ( historics_id = historics_id ) )
def public_ip_address_delete ( name , resource_group , ** kwargs ) : '''. . versionadded : : 2019.2.0 Delete a public IP address . : param name : The name of the public IP address to delete . : param resource _ group : The resource group name assigned to the public IP address . CLI Example : . . code - ...
result = False netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs ) try : pub_ip = netconn . public_ip_addresses . delete ( public_ip_address_name = name , resource_group_name = resource_group ) pub_ip . wait ( ) result = True except CloudError as exc : __utils__ [ 'azurearm.log_cloud...
def get_version_url ( self , full_name , packaging , version , descriptor = None ) : """Get the URL to a specific version of the given project , optionally using a descriptor to get a particular variant of the version ( sources , javadocs , etc . ) . The name of the artifact should be composed of the group ID a...
group , artifact = _parse_full_name ( full_name ) return self . _urls . get_url ( group , artifact , packaging , version , descriptor )
def inFootprint ( footprint , ra , dec ) : """Check if set of ra , dec combinations are in footprint . Careful , input files must be in celestial coordinates . filename : Either healpix map or mangle polygon file ra , dec : Celestial coordinates Returns : inside : boolean array of coordinates in footprint...
if footprint is None : return np . ones ( len ( ra ) , dtype = bool ) try : if isinstance ( footprint , str ) and os . path . exists ( footprint ) : filename = footprint # footprint = hp . read _ map ( filename , verbose = False ) # footprint = fitsio . read ( filename ) [ ' I ' ] . rave...
def filter ( self , search ) : '''Perform filtering instead of default post - filtering .'''
if not self . _filters : return search filters = Q ( 'match_all' ) for f in self . _filters . values ( ) : filters &= f return search . filter ( filters )
def filter_falsey ( data , recurse_depth = None , ignore_types = ( ) ) : '''Helper function to remove items from an iterable with falsey value . Removes ` ` None ` ` , ` ` { } ` ` and ` ` [ ] ` ` , 0 , ' ' ( but does not remove ` ` False ` ` ) . Recurses into sub - iterables if ` ` recurse ` ` is set to ` ` Tru...
filter_element = ( functools . partial ( filter_falsey , recurse_depth = recurse_depth - 1 , ignore_types = ignore_types ) if recurse_depth else lambda x : x ) if isinstance ( data , dict ) : processed_elements = [ ( key , filter_element ( value ) ) for key , value in six . iteritems ( data ) ] return type ( da...
def get_class ( self ) : """Return a Code class based on current ErrorType value . Returns : enum . IntEnum : class referenced by current error type ."""
classes = { 'OFPET_HELLO_FAILED' : HelloFailedCode , 'OFPET_BAD_REQUEST' : BadRequestCode , 'OFPET_BAD_ACTION' : BadActionCode , 'OFPET_FLOW_MOD_FAILED' : FlowModFailedCode , 'OFPET_PORT_MOD_FAILED' : PortModFailedCode , 'OFPET_QUEUE_OP_FAILED' : QueueOpFailedCode } return classes . get ( self . name , GenericFailedCod...
def createReport ( tm , options , sequenceString , numSegments , numSynapses ) : """Create CSV file with detailed trace of predictions , missed predictions , accuracy , segment / synapse growth , etc ."""
pac = tm . mmGetTracePredictedActiveColumns ( ) pic = tm . mmGetTracePredictedInactiveColumns ( ) upac = tm . mmGetTraceUnpredictedActiveColumns ( ) resultsFilename = os . path . join ( "results" , options . name + "_" + str ( int ( 100 * options . noise ) ) + ".csv" ) with open ( resultsFilename , "wb" ) as resultsFil...
def handle_parent ( repo , ** kwargs ) : """: return : repo . parent ( )"""
log . info ( 'parent: %s %s' % ( repo , kwargs ) ) _parent = repo . parent ( ) if _parent : return [ _parent . serialize ( ) ]
def context_lookup ( self , vars ) : """Lookup the variables in the provided dictionary , resolve with entries in the context"""
while isinstance ( vars , IscmExpr ) : vars = vars . resolve ( self . context ) for ( k , v ) in vars . items ( ) : if isinstance ( v , IscmExpr ) : vars [ k ] = v . resolve ( self . context ) return vars
def get_label_idx ( self , label ) : """Returns the index of a label . Returns None if not found ."""
for i in range ( len ( self ) ) : if self . mem [ i ] . is_label and self . mem [ i ] . inst == label : return i return None
def feedforward ( inputs , num_units , scope = "multihead_attention" ) : '''Point - wise feed forward net . Args : inputs : A 3d tensor with shape of [ N , T , C ] . num _ units : A list of two integers . scope : Optional scope for ` variable _ scope ` . reuse : Boolean , whether to reuse the weights of a...
with tf . variable_scope ( scope ) : # Inner layer params = { "inputs" : inputs , "filters" : num_units [ 0 ] , "kernel_size" : 1 , "activation" : tf . nn . relu , "use_bias" : True } outputs = tf . layers . conv1d ( ** params ) # Readout layer params = { "inputs" : outputs , "filters" : num_units [ 1 ]...
def from_tags ( cls , tags_file : str , tags_folder : str ) -> 'TrainData' : """Load a set of data from a text file with tags in the following format : < file _ id > ( tab ) < tag > < file _ id > ( tab ) < tag > file _ id : identifier of file such that the following file exists : { tags _ folder } / { data ...
if not tags_file : num_ignored_wavs = len ( glob ( join ( tags_folder , '*.wav' ) ) ) if num_ignored_wavs > 10 : print ( 'WARNING: Found {} wavs but no tags file specified!' . format ( num_ignored_wavs ) ) return cls ( ( [ ] , [ ] ) , ( [ ] , [ ] ) ) if not isfile ( tags_file ) : raise RuntimeEr...
def start ( self , on_done ) : """Starts the genesis block creation process . Will call the given ` on _ done ` callback on successful completion . Args : on _ done ( function ) : a function called on completion Raises : InvalidGenesisStateError : raises this error if a genesis block is unable to be pro...
genesis_file = os . path . join ( self . _data_dir , 'genesis.batch' ) try : with open ( genesis_file , 'rb' ) as batch_file : genesis_data = genesis_pb2 . GenesisData ( ) genesis_data . ParseFromString ( batch_file . read ( ) ) LOGGER . info ( 'Producing genesis block from %s' , genesis_file ) ...
def tf_pathname ( self ) : """Method used for defining full path name for particular tensor at build time . For example , ` tf . get _ variable ` creates variable w / o taking into account name scopes and ` tf _ pathname ` consists of all parts of scope names which were used up to that point - ` tf . get _ va...
if self . parent is self : return self . tf_name_scope tail = self . pathname . split ( '/' , 1 ) [ - 1 ] leader = self . root . tf_name_scope return "{leader_name}/{tail_name}" . format ( leader_name = leader , tail_name = tail )
def search ( cls , search_string , values_of = '' , group = whoosh . qparser . OrGroup , match_substrings = True , limit = None ) : """Searches the fields for given search _ string . Returns the found records if ' values _ of ' is left empty , else the values of the given columns . : param search _ string : T...
index = Whooshee . get_or_create_index ( _get_app ( cls ) , cls ) prepped_string = cls . prep_search_string ( search_string , match_substrings ) with index . searcher ( ) as searcher : parser = whoosh . qparser . MultifieldParser ( cls . schema . names ( ) , index . schema , group = group ) query = parser . par...
def _CreateRequest ( self , url , data = None ) : """Creates a new urllib request ."""
logging . debug ( "Creating request for: '%s' with payload:\n%s" , url , data ) req = urllib2 . Request ( url , data = data ) if self . host_override : req . add_header ( "Host" , self . host_override ) for key , value in self . extra_headers . iteritems ( ) : req . add_header ( key , value ) return req
def __del_running_bp_from_all_threads ( self , bp ) : "Auxiliary method ."
for ( tid , bpset ) in compat . iteritems ( self . __runningBP ) : if bp in bpset : bpset . remove ( bp ) self . system . get_thread ( tid ) . clear_tf ( )
def expand_relative_uri ( self , context , uri ) : """If uri is relative then expand in context . Prints warning if expansion happens ."""
full_uri = urljoin ( context , uri ) if ( full_uri != uri ) : print ( " WARNING - expanded relative URI to %s" % ( full_uri ) ) uri = full_uri return ( uri )
def get_context_menu ( self , qpoint ) : """override this method to customize the context menu"""
menu = QMenu ( self ) index = self . view . indexAt ( qpoint ) def add_action ( menu , text , handler , icon = None ) : a = None if icon is None : a = QAction ( text , self ) else : a = QAction ( icon , text , self ) a . triggered . connect ( handler ) menu . addAction ( a ) add_acti...
def stop ( name ) : """Stop project ' s container ."""
container_name = get_container_name ( name ) client = docker . Client ( ) try : client . stop ( container_name ) except docker . errors . NotFound : pass except docker . errors . APIError as error : die ( error . explanation . decode ( ) )
def get_capabilities_by_ext ( self , strict_type_matching : bool = False ) -> Dict [ str , Dict [ Type , Dict [ str , Parser ] ] ] : """For all extensions that are supported , lists all types that can be parsed from this extension . For each type , provide the list of parsers supported . The order is " most per...
check_var ( strict_type_matching , var_types = bool , var_name = 'strict_matching' ) res = dict ( ) # For all extensions that are supported , for ext in self . get_all_supported_exts_for_type ( type_to_match = JOKER , strict = strict_type_matching ) : res [ ext ] = self . get_capabilities_for_ext ( ext , strict_typ...
def gen_reference_primitive ( polypeptide , start , end ) : """Generates a reference Primitive for a Polypeptide given start and end coordinates . Notes Uses the rise _ per _ residue of the Polypeptide primitive to define the separation of points on the line joining start and end . Parameters polypeptide ...
prim = polypeptide . primitive q = find_foot ( a = start , b = end , p = prim . coordinates [ 0 ] ) ax = Axis ( start = q , end = end ) # flip axis if antiparallel to polypeptide _ vector if not is_acute ( polypeptide_vector ( polypeptide ) , ax . unit_tangent ) : ax = Axis ( start = end , end = q ) arc_length = 0 ...
def rename_tabs_after_change ( self , given_name ) : """Rename tabs after a change in name ."""
client = self . get_current_client ( ) # Prevent renames that want to assign the same name of # a previous tab repeated = False for cl in self . get_clients ( ) : if id ( client ) != id ( cl ) and given_name == cl . given_name : repeated = True break # Rename current client tab to add str _ id if cl...
async def on_raw ( self , message ) : """Handle a single message ."""
self . logger . debug ( '<< %s' , message . _raw ) if not message . _valid : self . logger . warning ( 'Encountered strictly invalid IRC message from server: %s' , message . _raw ) if isinstance ( message . command , int ) : cmd = str ( message . command ) . zfill ( 3 ) else : cmd = message . command # Invo...
def get_fields_dict ( self ) : """Return a list of ` label ` / ` value ` dictionaries to represent the fiels named by the model _ admin class ' s ` get _ inspect _ view _ fields ` method"""
fields = [ ] for field_name in self . model_admin . get_inspect_view_fields ( ) : fields . append ( self . get_dict_for_field ( field_name ) ) return fields
def segment ( self , source , language = None ) : """Returns a chunk list from the given sentence . Args : source ( str ) : Source string to segment . language ( : obj : ` str ` , optional ) : A language code . Returns : A chunk list . ( : obj : ` budou . chunk . ChunkList ` ) Raises : ValueError : If...
if language and not language in self . supported_languages : raise ValueError ( 'Language {} is not supported by NLAPI segmenter' . format ( language ) ) chunks = ChunkList ( ) results = tinysegmenter . tokenize ( source ) seek = 0 for word in results : word = word . strip ( ) if not word : continue...
def bin2str ( b ) : """Binary to string ."""
ret = [ ] for pos in range ( 0 , len ( b ) , 8 ) : ret . append ( chr ( int ( b [ pos : pos + 8 ] , 2 ) ) ) return '' . join ( ret )
def _collapse_to_cwl_record ( samples , want_attrs , input_files ) : """Convert nested samples from batches into a CWL record , based on input keys ."""
input_keys = sorted ( list ( set ( ) . union ( * [ d [ "cwl_keys" ] for d in samples ] ) ) , key = lambda x : ( - len ( x ) , tuple ( x ) ) ) out = { } for key in input_keys : if key in want_attrs : key_parts = key . split ( "__" ) vals = [ ] cur = [ ] for d in samples : ...
def combine_initial_dims ( tensor : torch . Tensor ) -> torch . Tensor : """Given a ( possibly higher order ) tensor of ids with shape ( d1 , . . . , dn , sequence _ length ) Return a view that ' s ( d1 * . . . * dn , sequence _ length ) . If original tensor is 1 - d or 2 - d , return it as is ."""
if tensor . dim ( ) <= 2 : return tensor else : return tensor . view ( - 1 , tensor . size ( - 1 ) )
def query ( self , sql , ** kwargs ) : """Shortcut for GET / v1 / query , except with argument format = ' dataframe ' ( the default ) , in which case it will simply wrap the result of the GET query to / v1 / query ( with format = ' table ' ) in a ` pandas . DataFrame ` ."""
if 'format' not in kwargs or kwargs [ 'format' ] == 'dataframe' : resp = self . get ( '/v1/query' , data = { 'q' : sql , 'format' : 'table' } ) . json ( ) if len ( resp ) == 0 : return pd . DataFrame ( ) else : return pd . DataFrame . from_records ( resp [ 1 : ] , columns = resp [ 0 ] , inde...
def path ( self , which = None ) : """Extend ` ` nailgun . entity _ mixins . Entity . path ` ` . The format of the returned path depends on the value of ` ` which ` ` : smart _ class _ parameters / api / environments / : environment _ id / smart _ class _ parameters Otherwise , call ` ` super ` ` ."""
if which in ( 'smart_class_parameters' , ) : return '{0}/{1}' . format ( super ( Environment , self ) . path ( which = 'self' ) , which ) return super ( Environment , self ) . path ( which )
def add_phase ( self , name , done , score , summary , steps , report_every = None , log_every = None , checkpoint_every = None , feed = None ) : """Add a phase to the loop protocol . If the model breaks long computation into multiple steps , the done tensor indicates whether the current score should be added t...
done = tf . convert_to_tensor ( done , tf . bool ) score = tf . convert_to_tensor ( score , tf . float32 ) summary = tf . convert_to_tensor ( summary , tf . string ) feed = feed or { } if done . shape . ndims is None or score . shape . ndims is None : raise ValueError ( "Rank of 'done' and 'score' tensors must be k...
def getReferenceByName ( self , name ) : """Returns the reference with the specified name ."""
if name not in self . _referenceNameMap : raise exceptions . ReferenceNameNotFoundException ( name ) return self . _referenceNameMap [ name ]
def libvlc_video_set_spu ( p_mi , i_spu ) : '''Set new video subtitle . @ param p _ mi : the media player . @ param i _ spu : video subtitle track to select ( i _ id from track description ) . @ return : 0 on success , - 1 if out of range .'''
f = _Cfunctions . get ( 'libvlc_video_set_spu' , None ) or _Cfunction ( 'libvlc_video_set_spu' , ( ( 1 , ) , ( 1 , ) , ) , None , ctypes . c_int , MediaPlayer , ctypes . c_int ) return f ( p_mi , i_spu )
def between ( y , z ) : """Greater than or equal to y and less than z ."""
return _combinable ( lambda x : ( y <= x < z ) or _equal_or_float_equal ( x , y ) )
def raw_encode ( data ) : """Special case serializer ."""
content_type = 'application/data' payload = data if isinstance ( payload , unicode ) : content_encoding = 'utf-8' payload = payload . encode ( content_encoding ) else : content_encoding = 'binary' return content_type , content_encoding , payload
def _should_retry ( resp ) : """Given a urlfetch response , decide whether to retry that request ."""
return ( resp . status_code == httplib . REQUEST_TIMEOUT or ( resp . status_code >= 500 and resp . status_code < 600 ) )
def fill_urls ( self ) : """This assigns the URL ' s based on the protocol ."""
protocol = self . dcnm_protocol self . _org_url = '%s://%s/rest/auto-config/organizations' % ( ( protocol , self . _ip ) ) self . _create_network_url = ( '%s://%s/' % ( protocol , self . _ip ) + 'rest/auto-config/organizations' '/%s/partitions/%s/networks' ) self . host_protocol_url = '%s://%s/' % ( protocol , self . _...
def param_set ( self , param_name , _value = None , ** kwargs ) : """Setting parameter . if _ value , we inject it directly . if not , we use all extra kwargs : param topic _ name : name of the topic : param _ value : optional value : param kwargs : each extra kwarg will be put in the value if structure match...
# changing unicode to string ( testing stability of multiprocess debugging ) if isinstance ( param_name , unicode ) : param_name = unicodedata . normalize ( 'NFKD' , param_name ) . encode ( 'ascii' , 'ignore' ) _value = _value or { } if kwargs : res = self . param_svc . call ( args = ( param_name , kwargs , ) )...
def GetFileSystem ( self , path_spec ) : """Retrieves a file system object defined by path specification . Args : path _ spec ( PathSpec ) : path specification . Returns : FileSystem : a file system object or None if not cached ."""
identifier = self . _GetFileSystemCacheIdentifier ( path_spec ) return self . _file_system_cache . GetObject ( identifier )
def build_relational_field ( self , field_name , relation_info ) : """Create fields for forward and reverse relationships ."""
field_class = self . serializer_related_field field_kwargs = get_relation_kwargs ( field_name , relation_info ) to_field = field_kwargs . pop ( 'to_field' , None ) if to_field and not relation_info . related_model . _meta . get_field ( to_field ) . primary_key : field_kwargs [ 'slug_field' ] = to_field field_cl...
def get_fastq_2 ( job , patient_id , sample_type , fastq_1 ) : """For a path to a fastq _ 1 file , return a fastq _ 2 file with the same prefix and naming scheme . : param str patient _ id : The patient _ id : param str sample _ type : The sample type of the file : param str fastq _ 1 : The path to the fastq ...
prefix , extn = fastq_1 , 'temp' final_extn = '' while extn : prefix , extn = os . path . splitext ( prefix ) final_extn = extn + final_extn if prefix . endswith ( '1' ) : prefix = prefix [ : - 1 ] job . fileStore . logToMaster ( '"%s" prefix for "%s" determined to be %s' % ( sample_type , p...
def kinks ( path , tol = 1e-8 ) : """returns indices of segments that start on a non - differentiable joint ."""
kink_list = [ ] for idx in range ( len ( path ) ) : if idx == 0 and not path . isclosed ( ) : continue try : u = path [ ( idx - 1 ) % len ( path ) ] . unit_tangent ( 1 ) v = path [ idx ] . unit_tangent ( 0 ) u_dot_v = u . real * v . real + u . imag * v . imag flag = False...
def computeEntropyAndEnthalpy ( self , uncertainty_method = None , verbose = False , warning_cutoff = 1.0e-10 ) : """Decompose free energy differences into enthalpy and entropy differences . Compute the decomposition of the free energy difference between states 1 and N into reduced free energy differences , red...
if verbose : print ( "Computing average energy and entropy by MBAR." ) # Retrieve N and K for convenience . N = self . N K = self . K # Augment W _ nk , N _ k , and c _ k for q _ A ( x ) for the potential energies , # with one extra row / column for each state . # weight matrix Log_W_nk = np . zeros ( [ N , K * 2 ]...
def approxQuantile ( self , col , probabilities , relativeError ) : """Calculates the approximate quantiles of numerical columns of a DataFrame . The result of this algorithm has the following deterministic bound : If the DataFrame has N elements and if we request the quantile at probability ` p ` up to err...
if not isinstance ( col , ( basestring , list , tuple ) ) : raise ValueError ( "col should be a string, list or tuple, but got %r" % type ( col ) ) isStr = isinstance ( col , basestring ) if isinstance ( col , tuple ) : col = list ( col ) elif isStr : col = [ col ] for c in col : if not isinstance ( c ,...
def substitute ( ctx , text , old_text , new_text , instance_num = - 1 ) : """Substitutes new _ text for old _ text in a text string"""
text = conversions . to_string ( text , ctx ) old_text = conversions . to_string ( old_text , ctx ) new_text = conversions . to_string ( new_text , ctx ) if instance_num < 0 : return text . replace ( old_text , new_text ) else : splits = text . split ( old_text ) output = splits [ 0 ] instance = 1 f...
def get_doc_lengths ( self ) : '''Returns a list of document lengths in words Returns np . array'''
idx_to_delete_list = self . _build_term_index_list ( True , self . _get_non_unigrams ( ) ) unigram_X , _ = self . _get_X_after_delete_terms ( idx_to_delete_list ) return unigram_X . sum ( axis = 1 ) . A1
def parse_args ( arguments , apply_config = False ) : """Parse command - line options ."""
parser = create_parser ( ) args = parser . parse_args ( arguments ) if not args . files and not args . list_fixes : parser . error ( 'incorrect number of arguments' ) args . files = [ decode_filename ( name ) for name in args . files ] if apply_config : parser = read_config ( args , parser ) args = parser ....
def add ( name , ** kwargs ) : """add a new configuration with the name specified and all of the keywords as attributes of that configuration ."""
_CONFIG . add_section ( name ) for ( key , value ) in kwargs . items ( ) : _CONFIG . set ( name , key , value ) with open ( _CONFIG_FILEPATH , 'w' ) as configfile : _CONFIG . write ( configfile ) info ( 'Configuration updated at %s' % _JUT_HOME )
def get_log_id ( cls , id ) : """Fetches log for the command represented by this id Args : ` id ` : command id"""
conn = Qubole . agent ( ) r = conn . get_raw ( cls . element_path ( id ) + "/logs" ) return r . text
def get_row_dict ( self , row_idx ) : """Return a dictionary representation for a matrix row : param row _ idx : which row : return : a dict of feature keys / values , not including ones which are the default value"""
try : row = self . _rows [ row_idx ] except TypeError : row = self . _rows [ self . _row_name_idx [ row_idx ] ] if isinstance ( row , dict ) : return row else : if row_idx not in self . _row_memo : self . _row_memo [ row_idx ] = dict ( ( self . _column_name_list [ idx ] , v ) for idx , v in enum...
def load_file_config ( path = None , section = None ) : """Loads configuration from file with following content : : [ default ] interface = socketcan channel = can0 : param path : path to config file . If not specified , several sensible default locations are tried depending on platform . : param sect...
config = ConfigParser ( ) if path is None : config . read ( [ os . path . expanduser ( path ) for path in CONFIG_FILES ] ) else : config . read ( path ) _config = { } section = section if section is not None else 'default' if config . has_section ( section ) : if config . has_section ( 'default' ) : ...
def lu_companion ( top_row , value ) : r"""Compute an LU - factored : math : ` C - t I ` and its 1 - norm . . . _ dgecon : http : / / www . netlib . org / lapack / explore - html / dd / d9a / group _ _ double _ g _ ecomputational _ ga188b8d30443d14b1a3f7f8331d87ae60 . html # ga188b8d30443d14b1a3f7f8331d87ae60 ...
degree , = top_row . shape lu_mat = np . zeros ( ( degree , degree ) , order = "F" ) if degree == 1 : lu_mat [ 0 , 0 ] = top_row [ 0 ] - value return lu_mat , abs ( lu_mat [ 0 , 0 ] ) # Column 0 : Special case since it doesn ' t have ` ` - t ` ` above the diagonal . horner_curr = top_row [ 0 ] - value one_norm ...
def clicks ( self , tag = None , fromdate = None , todate = None ) : """Gets total counts of unique links that were clicked ."""
return self . call ( "GET" , "/stats/outbound/clicks" , tag = tag , fromdate = fromdate , todate = todate )
def get_minimum_needs ( self ) : """Get the minimum needed information about the minimum needs . That is the resource and the amount . : returns : minimum needs : rtype : OrderedDict"""
minimum_needs = OrderedDict ( ) for resource in self . minimum_needs [ 'resources' ] : if resource [ 'Unit abbreviation' ] : name = '%s [%s]' % ( tr ( resource [ 'Resource name' ] ) , resource [ 'Unit abbreviation' ] ) else : name = tr ( resource [ 'Resource name' ] ) amount = resource [ 'De...
def create_mackup_home ( self ) : """If the Mackup home folder does not exist , create it ."""
if not os . path . isdir ( self . mackup_folder ) : if utils . confirm ( "Mackup needs a directory to store your" " configuration files\n" "Do you want to create it now? <{}>" . format ( self . mackup_folder ) ) : os . makedirs ( self . mackup_folder ) else : utils . error ( "Mackup can't do any...
def is_previous_task_processing ( self , * args , ** kwargs ) : """Return True if exist task that is equal to current and is uncompleted"""
app = self . _get_app ( ) inspect = app . control . inspect ( ) active = inspect . active ( ) or { } scheduled = inspect . scheduled ( ) or { } reserved = inspect . reserved ( ) or { } uncompleted = sum ( list ( active . values ( ) ) + list ( scheduled . values ( ) ) + reserved . values ( ) , [ ] ) return any ( self . ...