signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def set_max_connections_per_host ( self , host_distance , max_connections ) : """Sets the maximum number of connections per Session that will be opened for each host with : class : ` ~ . HostDistance ` equal to ` host _ distance ` . The default is 2 for : attr : ` ~ HostDistance . LOCAL ` and 1 for : attr : `...
if self . protocol_version >= 3 : raise UnsupportedOperation ( "Cluster.set_max_connections_per_host() only has an effect " "when using protocol_version 1 or 2." ) self . _max_connections_per_host [ host_distance ] = max_connections
def add_notes ( self , note , duration = None ) : """Add a Note , note as string or NoteContainer to the last Bar . If the Bar is full , a new one will automatically be created . If the Bar is not full but the note can ' t fit in , this method will return False . True otherwise . An InstrumentRangeError exc...
if self . instrument != None : if not self . instrument . can_play_notes ( note ) : raise InstrumentRangeError , "Note '%s' is not in range of the instrument (%s)" % ( note , self . instrument ) if duration == None : duration = 4 # Check whether the last bar is full , if so create a new bar and add the ...
def get_client ( self ) : """Retrieves or creates a client instance from this configuration object . If instantiated from this configuration , the resulting object is also cached in the property ` ` client ` ` and a reference to this configuration is stored on the client object . : return : Client object inst...
client = self . _client if not client : self . _client = client = self . client_constructor ( ** self . get_init_kwargs ( ) ) client . client_configuration = self # Client might update the version number after construction . updated_version = getattr ( client , 'api_version' , None ) if updated_vers...
def trim_nearby_peaks ( peaks , dt ) : r"""Finds pairs of peaks that are nearer to each other than to the solid phase , and removes the peak that is closer to the solid . Parameters peaks : ND - array A boolean image containing True values to mark peaks in the distance transform ( ` ` dt ` ` ) dt : ND -...
peaks = sp . copy ( peaks ) if dt . ndim == 2 : from skimage . morphology import square as cube else : from skimage . morphology import cube peaks , N = spim . label ( peaks , structure = cube ( 3 ) ) crds = spim . measurements . center_of_mass ( peaks , labels = peaks , index = sp . arange ( 1 , N + 1 ) ) crds...
def _add_timedelta ( self , delta ) : """Add timedelta duration to the instance . : param delta : The timedelta instance : type delta : pendulum . Duration or datetime . timedelta : rtype : Date"""
if isinstance ( delta , pendulum . Duration ) : return self . add ( years = delta . years , months = delta . months , weeks = delta . weeks , days = delta . remaining_days , ) return self . add ( days = delta . days )
def get ( self ) : """Get the script content from the URL using the decided downloader ."""
method_name = "_download_" + self . name method = getattr ( self , method_name ) return method ( )
def create_user ( self , projects = None , tasks = None ) : """Create and return a new user : param projects : the projects for the user : type projects : list of : class : ` jukeboxcore . djadapter . models . Project ` : param tasks : the tasks for the user : type tasks : list of : class : ` jukeboxcore . ...
projects = projects or [ ] tasks = tasks or [ ] dialog = UserCreatorDialog ( projects = projects , tasks = tasks , parent = self ) dialog . exec_ ( ) user = dialog . user if user : userdata = djitemdata . UserItemData ( user ) treemodel . TreeItem ( userdata , self . users_model . root ) return user
def decorators ( self , relation ) : """Return prefixes for tuple . : param int relation : relation of string value to actual value"""
if self . CONFIG . show_approx_str : approx_str = Decorators . relation_to_symbol ( relation ) else : approx_str = '' return _Decorators ( approx_str = approx_str )
def _normalize_window ( window , nfft , library , dtype ) : """Normalise a window specification for a PSD calculation Parameters window : ` str ` , ` numpy . ndarray ` , ` None ` the input window specification nfft : ` int ` the length of the Fourier transform , in samples library : ` str ` the name o...
if library == '_lal' and isinstance ( window , numpy . ndarray ) : from . _lal import window_from_array return window_from_array ( window ) if library == '_lal' : from . _lal import generate_window return generate_window ( nfft , window = window , dtype = dtype ) if isinstance ( window , string_types ) ...
def avgwave ( self , wavelengths = None ) : """Calculate the : ref : ` average wavelength < synphot - formula - avgwv > ` . Parameters wavelengths : array - like , ` ~ astropy . units . quantity . Quantity ` , or ` None ` Wavelength values for sampling . If not a Quantity , assumed to be in Angstrom . If ...
x = self . _validate_wavelengths ( wavelengths ) . value y = self ( x ) . value num = np . trapz ( y * x , x = x ) den = np . trapz ( y , x = x ) if den == 0 : # pragma : no cover avg_wave = 0.0 else : avg_wave = abs ( num / den ) return avg_wave * self . _internal_wave_unit
def change_authentication ( self , client_id = None , client_secret = None , access_token = None , refresh_token = None ) : """Change the current authentication ."""
# TODO : Add error checking so you cannot change client _ id and retain # access _ token . Because that doesn ' t make sense . self . client_id = client_id or self . client_id self . client_secret = client_secret or self . client_secret self . access_token = access_token or self . access_token self . refresh_token = re...
def warnconfig ( action = 'default' ) : """Configure the Python warnings . : type action : string : param action : The configuration to set . Options are : ' default ' , ' error ' , ' ignore ' , ' always ' , ' module ' and ' once ' ."""
# If action is ' default ' if action . lower ( ) == 'default' : # Change warning settings warnings . filterwarnings ( 'default' ) # If action is ' error ' elif action . lower ( ) == 'error' : # Change warning settings warnings . filterwarnings ( 'error' ) # If action is ' ignore ' elif action . lower ( ) == 'ig...
def make_es_id ( uri ) : """Creates the id based off of the uri value Args : uri : the uri to conver to an elasticsearch id"""
try : uri = uri . clean_uri except AttributeError : pass return sha1 ( uri . encode ( ) ) . hexdigest ( )
def next_prime ( starting_value ) : "Return the smallest prime larger than the starting value ."
if starting_value < 2 : return 2 result = ( starting_value + 1 ) | 1 while not is_prime ( result ) : result = result + 2 return result
def merge ( files , out_file , config ) : """merge smartly fastq files . It recognizes paired fastq files ."""
pair1 = [ fastq_file [ 0 ] for fastq_file in files ] if len ( files [ 0 ] ) > 1 : path = splitext_plus ( out_file ) pair1_out_file = path [ 0 ] + "_R1" + path [ 1 ] pair2 = [ fastq_file [ 1 ] for fastq_file in files ] pair2_out_file = path [ 0 ] + "_R2" + path [ 1 ] _merge_list_fastqs ( pair1 , pair...
def delete_many ( self , uris ) : """Remove many nodes from cache . No return ."""
cache_keys = ( self . _build_cache_key ( uri ) for uri in uris ) self . _delete_many ( cache_keys )
def _padleft ( width , s , has_invisible = True ) : """Flush right . > > > _ padleft ( 6 , ' \u044f \u0439 \u0446 \u0430 ' ) = = ' \u044f \u0439 \u0446 \u0430 ' True"""
def impl ( val ) : iwidth = width + len ( val ) - len ( _strip_invisible ( val ) ) if has_invisible else width fmt = "{0:>%ds}" % iwidth return fmt . format ( val ) num_lines = s . splitlines ( ) return len ( num_lines ) > 1 and '\n' . join ( map ( impl , num_lines ) ) or impl ( s )
def finalize ( self ) : """Output the number of instances that contained dead code ."""
if self . total_instances > 1 : print ( '{} of {} instances contained dead code.' . format ( self . dead_code_instances , self . total_instances ) )
def parse_token ( self , token , tags = [ WORD , POS , CHUNK , PNP , REL , ANCHOR , LEMMA ] ) : """Returns the arguments for Sentence . append ( ) from a tagged token representation . The order in which token tags appear can be specified . The default order is ( separated by slashes ) : - word , - part - of...
p = { WORD : "" , POS : None , IOB : None , CHUNK : None , PNP : None , REL : None , ROLE : None , ANCHOR : None , LEMMA : None } # Split the slash - formatted token into separate tags in the given order . # Decode & slash ; characters ( usually in words and lemmata ) . # Assume None for missing tags ( except the word ...
def fix_coordinate_decimal ( d ) : """Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal . Round them down to 5 decimals : param dict d : Metadata : return dict d : Metadata"""
try : for idx , n in enumerate ( d [ "geo" ] [ "geometry" ] [ "coordinates" ] ) : d [ "geo" ] [ "geometry" ] [ "coordinates" ] [ idx ] = round ( n , 5 ) except Exception as e : logger_misc . error ( "fix_coordinate_decimal: {}" . format ( e ) ) return d
def fn_check_full ( fn ) : """Check for file existence Avoids race condition , but slower than os . path . exists . Parameters fn : str Input filename string . Returns status True if file exists , False otherwise ."""
status = True if not os . path . isfile ( fn ) : status = False else : try : open ( fn ) except IOError : status = False return status
def delete_Variable ( self , name ) : '''pops a variable from class and delete it from parameter list : parameter name : name of the parameter to delete'''
self . message ( 1 , 'Deleting variable {0}' . format ( name ) ) self . par_list = self . par_list [ self . par_list != name ] return self . __dict__ . pop ( name )
def inject ( self , span_context , format , carrier ) : """Injects ` span _ context ` into ` carrier ` . The type of ` carrier ` is determined by ` format ` . See the : class : ` Format ` class / namespace for the built - in OpenTracing formats . Implementations * must * raise : exc : ` UnsupportedFormatExcep...
if format in Tracer . _supported_formats : return raise UnsupportedFormatException ( format )
def upload_backup_bundle_from_file ( self , file_path , deployment_groups_id_or_uri ) : """Restore an Artifact Bundle from a backup file . Args : file _ path ( str ) : The File Path to restore the Artifact Bundle . deployment _ groups _ id _ or _ uri : ID or URI of the Deployment Groups . Returns : dict :...
deployment_groups_uri = deployment_groups_id_or_uri if self . DEPLOYMENT_GROUPS_URI not in deployment_groups_id_or_uri : deployment_groups_uri = self . DEPLOYMENT_GROUPS_URI + deployment_groups_id_or_uri uri = self . BACKUP_ARCHIVE_PATH + "?deploymentGrpUri=" + deployment_groups_uri return self . _client . upload (...
def add_vbar_widget ( self , ref , x = 1 , y = 1 , length = 10 ) : """Add Vertical Bar Widget"""
if ref not in self . widgets : widget = widgets . VBarWidget ( screen = self , ref = ref , x = x , y = y , length = length ) self . widgets [ ref ] = widget return self . widgets [ ref ]
def unlist ( list_thing , complain = True ) : """transforms [ Something ] - > Something . By default , raises a ValueError for any other list values ."""
if complain and len ( list_thing ) > 1 : raise ValueError ( "More than one element in {}" . format ( list_thing ) ) elif len ( list_thing ) == 1 : return list_thing [ 0 ] if complain : raise ValueError ( "Nothing in {}" . format ( list_thing ) ) return None
def function_exists ( self , fun ) : """get function ' s existense"""
res = fun in self . _rule_functions self . say ( 'function exists:' + str ( fun ) + ':' + str ( res ) , verbosity = 10 ) return res
def _use_datastore ( self , key , options = None ) : """Return whether to use the datastore for this key . Args : key : Key instance . options : ContextOptions instance , or None . Returns : True if the datastore should be used , False otherwise ."""
flag = ContextOptions . use_datastore ( options ) if flag is None : flag = self . _datastore_policy ( key ) if flag is None : flag = ContextOptions . use_datastore ( self . _conn . config ) if flag is None : flag = True return flag
def unique_size ( self ) : """Size of ONLY this particular layer : return : int or None"""
self . _virtual_size = self . _virtual_size or graceful_chain_get ( self . data , "VirtualSize" , default = 0 ) try : return self . _virtual_size - self . _shared_size except TypeError : return 0
def vlans ( self ) : """list [ dict ] : A list of dictionary items describing the details of vlan interfaces . This method fetches the VLAN interfaces Examples : > > > import pynos . device > > > switch = ' 10.24.39.202' > > > auth = ( ' admin ' , ' password ' ) > > > conn = ( switch , ' 22 ' ) > > ...
urn = "{urn:brocade.com:mgmt:brocade-interface-ext}" result = [ ] has_more = '' last_vlan_id = '' while ( has_more == '' ) or ( has_more == 'true' ) : request_interface = self . get_vlan_brief_request ( last_vlan_id ) interface_result = self . _callback ( request_interface , 'get' ) has_more = self . get_no...
def headers ( self ) : """Return the headers for the resource . Returns the AltName , if specified ; if not , then the Name , and if that is empty , a name based on the column position . These headers are specifically applicable to the output table , and may not apply to the resource source . FOr those headers ...
t = self . schema_term if t : return [ self . _name_for_col_term ( c , i ) for i , c in enumerate ( t . children , 1 ) if c . term_is ( "Table.Column" ) ] else : return None
def add ( self , * args ) : """Add object ( s ) to the Container . : param * args : Any objects to add to the Container . : returns : full list of Container ' s child objects"""
self . children . extend ( args ) bump_child_depth ( self , self . _depth ) return self . children
def get_pkg_names ( pkgs ) : """Get PyPI package names from a list of imports . Args : pkgs ( List [ str ] ) : List of import names . Returns : List [ str ] : The corresponding PyPI package names ."""
result = set ( ) with open ( join ( "mapping" ) , "r" ) as f : data = dict ( x . strip ( ) . split ( ":" ) for x in f ) for pkg in pkgs : # Look up the mapped requirement . If a mapping isn ' t found , # simply use the package name . result . add ( data . get ( pkg , pkg ) ) # Return a sorted list for backward ...
def add_final_training_ops ( self , embeddings , all_labels_count , bottleneck_tensor_size , hidden_layer_size = BOTTLENECK_TENSOR_SIZE / 4 , dropout_keep_prob = None ) : """Adds a new softmax and fully - connected layer for training . The set up for the softmax and fully - connected layers is based on : https ...
with tf . name_scope ( 'input' ) : bottleneck_input = tf . placeholder_with_default ( embeddings , shape = [ None , bottleneck_tensor_size ] , name = 'ReshapeSqueezed' ) bottleneck_with_no_gradient = tf . stop_gradient ( bottleneck_input ) with tf . name_scope ( 'Wx_plus_b' ) : hidden = layers . ful...
def symget ( self , name ) : """: param name : name of the macro varable to set : - name is a character"""
ll = self . submit ( "%put " + name + "=&" + name + ";\n" ) l2 = ll [ 'LOG' ] . rpartition ( name + "=" ) l2 = l2 [ 2 ] . partition ( "\n" ) try : var = int ( l2 [ 0 ] ) except : try : var = float ( l2 [ 0 ] ) except : var = l2 [ 0 ] return var
def list_jobs ( config , * , status = JobStatus . Active , filter_by_type = None , filter_by_worker = None ) : """Return a list of Celery jobs . Args : config ( Config ) : Reference to the configuration object from which the settings are retrieved . status ( JobStatus ) : The status of the jobs that should ...
celery_app = create_app ( config ) # option to filter by the worker ( improves performance ) if filter_by_worker is not None : inspect = celery_app . control . inspect ( destination = filter_by_worker if isinstance ( filter_by_worker , list ) else [ filter_by_worker ] ) else : inspect = celery_app . control . i...
def transpose ( self , name = None , output_channels = None , kernel_shapes = None , strides = None , paddings = None , activation = None , activate_final = None , normalization_ctor = None , normalization_kwargs = None , normalize_final = None , initializers = None , partitioners = None , regularizers = None , use_bat...
for rate in self . _rates : if rate != 1 : raise NotImplementedError ( "Transpose dilated convolutions " "are not supported" ) output_shapes = [ ] if data_format is None : data_format = self . _data_format if data_format == DATA_FORMAT_NHWC : start_dim , end_dim = 1 , - 1 elif data_format == DATA_FO...
def OnUpdate ( self , event ) : """Updates the toolbar states"""
attributes = event . attr self . _update_font ( attributes [ "textfont" ] ) self . _update_pointsize ( attributes [ "pointsize" ] ) self . _update_font_weight ( attributes [ "fontweight" ] ) self . _update_font_style ( attributes [ "fontstyle" ] ) self . _update_frozencell ( attributes [ "frozen" ] ) self . _update_loc...
def lookup_string ( conn , kstr ) : """Finds the keycode associated with a string representation of a keysym . : param kstr : English representation of a keysym . : return : Keycode , if one exists . : rtype : int"""
if kstr in keysyms : return get_keycode ( conn , keysyms [ kstr ] ) elif len ( kstr ) > 1 and kstr . capitalize ( ) in keysyms : return get_keycode ( conn , keysyms [ kstr . capitalize ( ) ] ) return None
def cmd ( send , * _ ) : """Returns the Discordian date . Syntax : { command }"""
try : output = subprocess . check_output ( [ 'ddate' ] , universal_newlines = True ) except subprocess . CalledProcessError : output = 'Today is the day you install ddate!' for line in output . splitlines ( ) : send ( line )
def _dumpArrayToFile ( filelike , array ) : """Serializes a 1 - dimensional ` ` numpy . array ` ` to bytes , writes the bytes to the filelike object and returns a dictionary with metadata , necessary to restore the ` ` numpy . array ` ` from the file . : param filelike : can be a file or a file - like object ...
bytedata = array . tobytes ( 'C' ) start = filelike . tell ( ) end = start + len ( bytedata ) metadata = { 'start' : start , 'end' : end , 'size' : array . size , 'dtype' : array . dtype . name } filelike . write ( bytedata ) return metadata
def scatter ( adata , x = None , y = None , color = None , use_raw = None , layers = 'X' , sort_order = True , alpha = None , basis = None , groups = None , components = None , projection = '2d' , legend_loc = 'right margin' , legend_fontsize = None , legend_fontweight = None , color_map = None , palette = None , frame...
if basis is not None : axs = _scatter_obs ( adata = adata , x = x , y = y , color = color , use_raw = use_raw , layers = layers , sort_order = sort_order , alpha = alpha , basis = basis , groups = groups , components = components , projection = projection , legend_loc = legend_loc , legend_fontsize = legend_fontsiz...
def get_group_by_id ( self , group_id ) -> typing . Optional [ 'Group' ] : """Args : group _ id : group ID Returns : Group"""
VALID_POSITIVE_INT . validate ( group_id , 'get_group_by_id' ) for group in self . groups : if group . group_id == group_id : return group return None
def download_items ( self , items , file_path , file_format = 'zip' ) : """Retrieve a file from the server containing the metadata and documents for the speficied items : type items : List or ItemGroup : param items : List of the the URLs of the items to download , or an ItemGroup object : type file _ pat...
download_url = '/catalog/download_items' download_url += '?' + urlencode ( ( ( 'format' , file_format ) , ) ) item_data = { 'items' : list ( items ) } data = self . api_request ( download_url , method = 'POST' , data = json . dumps ( item_data ) , raw = True ) with open ( file_path , 'w' ) as f : f . write ( data )...
async def synchronize ( self , pid , vendor_specific = None ) : """Send an object synchronization request to the CN ."""
return await self . _request_pyxb ( "post" , [ "synchronize" , pid ] , { } , mmp_dict = { "pid" : pid } , vendor_specific = vendor_specific , )
def create_diff_storage ( self , target , variant ) : """Starts creating an empty differencing storage unit based on this medium in the format and at the location defined by the @ a target argument . The target medium must be in : py : attr : ` MediumState . not _ created ` state ( i . e . must not have an ...
if not isinstance ( target , IMedium ) : raise TypeError ( "target can only be an instance of type IMedium" ) if not isinstance ( variant , list ) : raise TypeError ( "variant can only be an instance of type list" ) for a in variant [ : 10 ] : if not isinstance ( a , MediumVariant ) : raise TypeErro...
def cli ( ctx ) : """Check the latest Apio version ."""
current_version = get_distribution ( 'apio' ) . version latest_version = get_pypi_latest_version ( ) if latest_version is None : ctx . exit ( 1 ) if latest_version == current_version : click . secho ( 'You\'re up-to-date!\nApio {} is currently the ' 'newest version available.' . format ( latest_version ) , fg =...
def highlight_block ( self , text ) : """Implement highlight specific for C / C + + ."""
text = to_text_string ( text ) inside_comment = tbh . get_state ( self . currentBlock ( ) . previous ( ) ) == self . INSIDE_COMMENT self . setFormat ( 0 , len ( text ) , self . formats [ "comment" if inside_comment else "normal" ] ) match = self . PROG . search ( text ) index = 0 while match : for key , value in li...
def read_clusters ( self , min_cluster_size ) : """Read and parse OSLOM clusters output file ."""
num_found = 0 clusters = [ ] with open ( self . get_path ( OslomRunner . OUTPUT_FILE ) , "r" ) as reader : # Read the output file every two lines for line1 , line2 in itertools . izip_longest ( * [ reader ] * 2 ) : info = OslomRunner . RE_INFOLINE . match ( line1 . strip ( ) ) . groups ( ) nodes = l...
def list_subscriptions ( self , target_id = None , ids = None , query_flags = None ) : """ListSubscriptions . [ Preview API ] : param str target _ id : : param [ str ] ids : : param str query _ flags : : rtype : [ NotificationSubscription ]"""
query_parameters = { } if target_id is not None : query_parameters [ 'targetId' ] = self . _serialize . query ( 'target_id' , target_id , 'str' ) if ids is not None : ids = "," . join ( ids ) query_parameters [ 'ids' ] = self . _serialize . query ( 'ids' , ids , 'str' ) if query_flags is not None : quer...
def segment_file ( self , value ) : """Setter for _ segment _ file attribute"""
assert os . path . isfile ( value ) , "%s is not a valid file" % value self . _segment_file = value
def load_country_map_data ( ) : """Loading data for map with country map"""
csv_bytes = get_example_data ( 'birth_france_data_for_country_map.csv' , is_gzip = False , make_bytes = True ) data = pd . read_csv ( csv_bytes , encoding = 'utf-8' ) data [ 'dttm' ] = datetime . datetime . now ( ) . date ( ) data . to_sql ( # pylint : disable = no - member 'birth_france_by_region' , db . engine , if_e...
def _get_ghp_command ( self ) -> str : '''Generate ` ` mkdocs gh - deploy ` ` command to deploy the site to GitHub Pages .'''
components = [ self . _mkdocs_config . get ( 'mkdocs_path' , 'mkdocs' ) ] components . append ( 'gh-deploy' ) command = ' ' . join ( components ) self . logger . debug ( f'GHP upload command: {command}' ) return command
def psicomputations ( variance , Z , variational_posterior , return_psi2_n = False ) : """Compute psi - statistics for ss - linear kernel"""
# here are the " statistics " for psi0 , psi1 and psi2 # Produced intermediate results : # psi0 N # psi1 NxM # psi2 MxM mu = variational_posterior . mean S = variational_posterior . variance psi0 = ( variance * ( np . square ( mu ) + S ) ) . sum ( axis = 1 ) Zv = variance * Z psi1 = np . dot ( mu , Zv . T ) if return_p...
def pomegranate ( args ) : """% prog cotton seqids karyotype . layout mcscan . out all . bed synteny . layout Build a figure that calls graphics . karyotype to illustrate the high ploidy of WGD history of pineapple genome . The script calls both graphics . karyotype and graphic . synteny ."""
p = OptionParser ( pomegranate . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "9x7" ) if len ( args ) != 5 : sys . exit ( not p . print_help ( ) ) seqidsfile , klayout , datafile , bedfile , slayout = args fig = plt . figure ( 1 , ( iopts . w , iopts . h ) ) root = fig . add_axes ( [ 0 ,...
def _update_secret ( namespace , name , data , apiserver_url ) : '''Replace secrets data by a new one'''
# Prepare URL url = "{0}/api/v1/namespaces/{1}/secrets/{2}" . format ( apiserver_url , namespace , name ) # Prepare data data = [ { "op" : "replace" , "path" : "/data" , "value" : data } ] # Make request ret = _kpatch ( url , data ) if ret . get ( "status" ) == 404 : return "Node {0} doesn't exist" . format ( url )...
def get ( self , status_code ) : """Returns the requested status . : param int status _ code : the status code to return : queryparam str reason : optional reason phrase"""
status_code = int ( status_code ) if status_code >= 400 : kwargs = { 'status_code' : status_code } if self . get_query_argument ( 'reason' , None ) : kwargs [ 'reason' ] = self . get_query_argument ( 'reason' ) if self . get_query_argument ( 'log_message' , None ) : kwargs [ 'log_message' ] ...
def results ( self , project_key = None , plan_key = None , job_key = None , build_number = None , expand = None , favourite = False , clover_enabled = False , issue_key = None , start_index = 0 , max_results = 25 ) : """Get results as generic method : param project _ key : : param plan _ key : : param job _ ...
resource = "result" if project_key and plan_key and job_key and build_number : resource += "/{}-{}-{}/{}" . format ( project_key , plan_key , job_key , build_number ) elif project_key and plan_key and build_number : resource += "/{}-{}/{}" . format ( project_key , plan_key , build_number ) elif project_key and ...
def extract ( self , file_path , is_drum = False ) : '''Extract MIDI file . Args : file _ path : File path of MIDI . is _ drum : Extract drum data or not . Returns : pd . DataFrame ( columns = [ " program " , " start " , " end " , " pitch " , " velocity " , " duration " ] )'''
midi_data = pretty_midi . PrettyMIDI ( file_path ) note_tuple_list = [ ] for instrument in midi_data . instruments : if ( is_drum is False and instrument . is_drum is False ) or ( is_drum is True and instrument . is_drum is True ) : for note in instrument . notes : note_tuple_list . append ( ( i...
def _ts_parse ( ts ) : """Parse alert timestamp , return UTC datetime object to maintain Python 2 compatibility ."""
dt = datetime . strptime ( ts [ : 19 ] , "%Y-%m-%dT%H:%M:%S" ) if ts [ 19 ] == '+' : dt -= timedelta ( hours = int ( ts [ 20 : 22 ] ) , minutes = int ( ts [ 23 : ] ) ) elif ts [ 19 ] == '-' : dt += timedelta ( hours = int ( ts [ 20 : 22 ] ) , minutes = int ( ts [ 23 : ] ) ) return dt . replace ( tzinfo = pytz ....
def listen ( self , * , host , port , override = False , forever = False , ** kwargs ) : """Listen on TCP / IP socket . Parameters host : str Host like ' 127.0.0.1' port : Port like 80."""
if override : argv = dict ( enumerate ( sys . argv ) ) host = argv . get ( 1 , host ) port = int ( argv . get ( 2 , port ) ) server = self . loop . create_server ( self . __handler . fork , host , port , ** kwargs ) server = self . loop . run_until_complete ( server ) self . log ( 'info' , 'Start listening ...
def decorate_with_metadata ( obj , result ) : """Return obj decorated with es _ meta object"""
# Create es _ meta object with Elasticsearch metadata about this # search result obj . es_meta = Metadata ( # Elasticsearch id id = result . get ( '_id' , 0 ) , # Source data source = result . get ( '_source' , { } ) , # The search result score score = result . get ( '_score' , None ) , # The document type type = resul...
def duplicate_lines ( self ) : """Duplicates the document lines under cursor . : return : Method success . : rtype : bool"""
cursor = self . textCursor ( ) self . __select_text_under_cursor_blocks ( cursor ) text = cursor . selectedText ( ) cursor . setPosition ( cursor . block ( ) . next ( ) . position ( ) ) cursor . position ( ) == cursor . document ( ) . firstBlock ( ) . position ( ) and cursor . setPosition ( cursor . document ( ) . last...
def _get_url_doc ( self ) : """Return a list of URLs that map to this resource ."""
resolver = get_resolver ( None ) possibilities = resolver . reverse_dict . getlist ( self ) urls = [ possibility [ 0 ] for possibility in possibilities ] return urls
def make_path_relative ( path ) : """makes an absolute path name to a relative pathname ."""
if os . path . isabs ( path ) : drive_s , path = os . path . splitdrive ( path ) import re if not drive_s : path = re . compile ( "/*(.*)" ) . findall ( path ) [ 0 ] else : path = path [ 1 : ] assert ( not os . path . isabs ( path ) ) , path return path
def send_update_port_statuses ( self , context , port_ids , status ) : """Call the pluging to update the port status which updates the DB . : param context : contains user information : param port _ ids : list of ids of the ports associated with the status : param status : value of the status for the given po...
cctxt = self . client . prepare ( version = '1.1' ) return cctxt . call ( context , 'update_port_statuses_cfg' , port_ids = port_ids , status = status )
def train_model_from_args ( args : argparse . Namespace ) : """Just converts from an ` ` argparse . Namespace ` ` object to string paths ."""
train_model_from_file ( args . param_path , args . serialization_dir , args . overrides , args . file_friendly_logging , args . recover , args . force , args . cache_directory , args . cache_prefix )
def PMISc ( S , method = 'JP' ) : """C / F splitting using Parallel Modified Independent Set ( in color ) . PMIS - c , or PMIS in color , improves PMIS by perturbing the initial random weights with weights determined by a vertex coloring . Parameters S : csr _ matrix Strength of connection matrix indicati...
S = remove_diagonal ( S ) weights , G , S , T = preprocess ( S , coloring_method = method ) return MIS ( G , weights )
def logger_has_handlers ( logger ) : """Check if given logger has at least 1 handler associated , return a boolean value . Since Python 2 doesn ' t provide Logger . hasHandlers ( ) , we have to perform the lookup by ourself ."""
if six . PY3 : return logger . hasHandlers ( ) else : c = logger rv = False while c : if c . handlers : rv = True break if not c . propagate : break else : c = c . parent return rv
def schema_org ( builder ) : # pylint : disable = line - too - long """Builds schema . org microdata for DatasetSearch from DatasetBuilder . Markup spec : https : / / developers . google . com / search / docs / data - types / dataset # dataset Testing tool : https : / / search . google . com / structured - data...
# pylint : enable = line - too - long properties = [ ( lambda x : x . name , SCHEMA_ORG_NAME ) , ( lambda x : x . description , SCHEMA_ORG_DESC ) , ( lambda x : x . name , SCHEMA_ORG_URL ) , ( lambda x : ( x . urls and x . urls [ 0 ] ) or "" , SCHEMA_ORG_SAMEAS ) ] info = builder . info out_str = SCHEMA_ORG_PRE for ext...
def update_info ( self , info ) : """set / update the info for this indexable with the key / value if there is a conflict raise / warn as needed"""
for key in self . _info_fields : value = getattr ( self , key , None ) idx = _get_info ( info , self . name ) existing_value = idx . get ( key ) if key in idx and value is not None and existing_value != value : # frequency / name just warn if key in [ 'freq' , 'index_name' ] : ws = a...
def logout ( request , redirect_url = settings . LOGOUT_REDIRECT_URL ) : """Nothing hilariously hidden here , logs a user out . Strip this out if your application already has hooks to handle this ."""
django_logout ( request ) return HttpResponseRedirect ( request . build_absolute_uri ( redirect_url ) )
def reverse ( self ) : """Generate the reverse of a directed graph , returns an identical graph if not directed . Attributes & weights are preserved . @ rtype : digraph @ return : The directed graph that should be reversed ."""
assert self . DIRECTED , "Undirected graph types such as %s cannot be reversed" % self . __class__ . __name__ N = self . __class__ ( ) # - Add the nodes N . add_nodes ( n for n in self . nodes ( ) ) # - Add the reversed edges for ( u , v ) in self . edges ( ) : wt = self . edge_weight ( ( u , v ) ) label = self...
def remote ( self , name = 'origin' ) : """: return : Remote with the specified name : raise ValueError : if no remote with such a name exists"""
r = Remote ( self , name ) if not r . exists ( ) : raise ValueError ( "Remote named '%s' didn't exist" % name ) return r
def _fire_master ( self , data = None , tag = None , events = None , pretag = None , timeout = 60 , sync = True , timeout_handler = None ) : '''Fire an event on the master , or drop message if unable to send .'''
load = { 'id' : self . opts [ 'id' ] , 'cmd' : '_minion_event' , 'pretag' : pretag , 'tok' : self . tok } if events : load [ 'events' ] = events elif data and tag : load [ 'data' ] = data load [ 'tag' ] = tag elif not data and tag : load [ 'data' ] = { } load [ 'tag' ] = tag else : return if syn...
def get_create_parameter ( model , param ) : """Return parameter with given name , creating it if needed . If unique is false and the parameter exists , the value is not changed ; if it does not exist , it will be created . If unique is true then upon conflict a number is added to the end of the parameter nam...
norm_name = _n ( param . name ) parameter = model . parameters . get ( norm_name ) if not param . unique and parameter is not None : return parameter if param . unique : pnum = 1 while True : pname = norm_name + '_%d' % pnum if model . parameters . get ( pname ) is None : break ...
def getReadAlignments ( self , reference , start = None , end = None ) : """Returns an iterator over the specified reads"""
return self . _getReadAlignments ( reference , start , end , self , None )
def add_to_matching_blacklist ( session , term ) : """Add term to the matching blacklist . This function adds a ` term ` to the matching blacklist . The term to add cannot have a ` None ` or empty value , on this case an ` ValueError ` will be raised . : param session : database session : param term : ter...
if term is None : raise ValueError ( "'term' to blacklist cannot be None" ) if term == '' : raise ValueError ( "'term' to blacklist cannot be an empty string" ) mb = MatchingBlacklist ( excluded = term ) session . add ( mb ) return mb
def is_available ( self ) -> bool : """Indicate if this Monitor is currently available ."""
status_response = self . _client . get_state ( 'api/monitors/daemonStatus/id:{}/daemon:zmc.json' . format ( self . _monitor_id ) ) if not status_response : _LOGGER . warning ( 'Could not get availability for monitor {}' . format ( self . _monitor_id ) ) return False # Monitor _ Status was only added in ZM 1.32....
def docker ( gandi , vm , args ) : """Manage docker instance"""
if not [ basedir for basedir in os . getenv ( 'PATH' , '.:/usr/bin' ) . split ( ':' ) if os . path . exists ( '%s/docker' % basedir ) ] : gandi . echo ( """'docker' not found in $PATH, required for this command \ to work See https://docs.docker.com/installation/#installation to install, or use: # curl https://g...
def _validate_version ( self ) : """If the version starts with a digit , it must be a sematic - versioning style string ."""
self . _assert_type ( "version" , list ( six . string_types ) ) self . _assert_matches_re ( "version" , [ RELEASE_VERSION_RE ] )
def _variable_elimination ( self , variables , operation , evidence = None , elimination_order = None , joint = True ) : """Implementation of a generalized variable elimination . Parameters variables : list , array - like variables that are not to be eliminated . operation : str ( ' marginalize ' | ' maximi...
if isinstance ( variables , string_types ) : raise TypeError ( "variables must be a list of strings" ) if isinstance ( evidence , string_types ) : raise TypeError ( "evidence must be a list of strings" ) # Dealing with the case when variables is not provided . if not variables : all_factors = [ ] for fa...
def get_file_descriptor ( self ) : """Return the file descriptor for the given websocket"""
try : return uwsgi . connection_fd ( ) except IOError as e : self . close ( ) raise WebSocketError ( e )
def wait_for_service ( host , port , timeout = DEFAULT_TIMEOUT ) : """Return True if connection to the host and port is successful within the timeout . @ param host : str : hostname of the server @ param port : int : TCP port to which to connect @ param timeout : int : length of time in seconds to try to conn...
service = ServiceURL ( 'tcp://{}:{}' . format ( host , port ) , timeout ) return service . wait ( )
def action ( arguments ) : """Trim the alignment as specified"""
# Determine file format for input and output source_format = ( arguments . source_format or fileformat . from_handle ( arguments . source_file ) ) output_format = ( arguments . output_format or fileformat . from_handle ( arguments . output_file ) ) # Load the alignment with arguments . source_file : sequences = Seq...
def _set_country ( self , c ) : """callback if we used Tor ' s GETINFO ip - to - country"""
self . location . countrycode = c . split ( ) [ 0 ] . split ( '=' ) [ 1 ] . strip ( ) . upper ( )
def copy_modified_gene ( self , modified_gene , ignore_model_attributes = True ) : """Copy attributes of a Gene object over to this Gene , given that the modified gene has the same ID . Args : modified _ gene ( Gene , GenePro ) : Gene with modified attributes that you want to copy over . ignore _ model _ attr...
ignore = [ '_model' , '_reaction' , '_functional' , 'model' , 'reaction' , 'functional' ] for attr in filter ( lambda a : not a . startswith ( '__' ) and not isinstance ( getattr ( type ( self ) , a , None ) , property ) and not callable ( getattr ( self , a ) ) , dir ( modified_gene ) ) : if attr not in ignore and...
def decrypt ( self , data ) : """DES decrypts the data based on the key it was initialised with . : param data : The encrypted bytes string to decrypt : return : The decrypted bytes string"""
decrypted_data = b"" for i in range ( 0 , len ( data ) , 8 ) : block = data [ i : i + 8 ] block_length = len ( block ) if block_length != 8 : raise ValueError ( "DES decryption must be a multiple of 8 " "bytes" ) decrypted_data += self . _decode_block ( block ) return decrypted_data
def filter_accept_reftrack ( self , reftrack ) : """Return True , if the filter accepts the given reftrack : param reftrack : the reftrack to filter : type reftrack : : class : ` jukeboxcore . reftrack . Reftrack ` : returns : True , if the filter accepts the reftrack : rtype : : class : ` bool ` : raises...
if reftrack . status ( ) in self . _forbidden_status : return False if reftrack . get_typ ( ) in self . _forbidden_types : return False if reftrack . uptodate ( ) in self . _forbidden_uptodate : return False if reftrack . alien ( ) in self . _forbidden_alien : return False return True
def mavlink_packet ( self , m ) : '''handle an incoming mavlink packet'''
if m . get_type ( ) == 'PPP' and self . ppp_fd != - 1 : print ( "got ppp mavlink pkt len=%u" % m . length ) os . write ( self . ppp_fd , m . data [ : m . length ] )
def preprocess_text ( text , language ) : """This function applies pre - processing steps that convert forms of words considered equivalent into one standardized form . As one straightforward step , it case - folds the text . For the purposes of wordfreq and related tools , a capitalized word shouldn ' t have...
# NFC or NFKC normalization , as needed for the language info = get_language_info ( language ) text = unicodedata . normalize ( info [ 'normal_form' ] , text ) # Transliteration of multi - script languages if info [ 'transliteration' ] is not None : text = transliterate ( info [ 'transliteration' ] , text ) # Abjad...
def safety_set_allowed_area_send ( self , target_system , target_component , frame , p1x , p1y , p1z , p2x , p2y , p2z , force_mavlink1 = False ) : '''Set a safety zone ( volume ) , which is defined by two corners of a cube . This message can be used to tell the MAV which setpoints / MISSIONs to accept and whic...
return self . send ( self . safety_set_allowed_area_encode ( target_system , target_component , frame , p1x , p1y , p1z , p2x , p2y , p2z ) , force_mavlink1 = force_mavlink1 )
def setCmd ( self , cmd ) : """Check the cmd is valid , FrameError will be raised if its not ."""
cmd = cmd . upper ( ) if cmd not in VALID_COMMANDS : raise FrameError ( "The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % ( cmd , VALID_COMMANDS , STOMP_VERSION ) ) else : self . _cmd = cmd
def get_turn_delta ( self , branch = None , turn = None , tick = None , start_tick = 0 ) : """Get a dictionary describing changes to the world within a given turn Defaults to the present turn , and stops at the present tick unless specified . See the documentation for ` ` get _ delta ` ` for a detailed descript...
branch = branch or self . branch turn = turn or self . turn tick = tick or self . tick delta = super ( ) . get_turn_delta ( branch , turn , start_tick , tick ) if branch in self . _avatarness_cache . settings and turn in self . _avatarness_cache . settings [ branch ] : for chara , graph , node , is_av in self . _av...
def _apply_outputter ( self , func , mod ) : '''Apply the _ _ outputter _ _ variable to the functions'''
if hasattr ( mod , '__outputter__' ) : outp = mod . __outputter__ if func . __name__ in outp : func . __outputter__ = outp [ func . __name__ ]
def _get_msupdate_status ( ) : '''Check to see if Microsoft Update is Enabled Return Boolean'''
# To get the status of Microsoft Update we actually have to check the # Microsoft Update Service Manager # Initialize the PyCom system with salt . utils . winapi . Com ( ) : # Create a ServiceManager Object obj_sm = win32com . client . Dispatch ( 'Microsoft.Update.ServiceManager' ) # Return a collection of loaded S...
def warn_explicit ( message , category , filename , lineno , module = None , registry = None , module_globals = None , emit_module = None ) : """Low level implementation of the warning functionality . Duplicate of the standard library ` warnings . warn _ explicit ` , except it accepts the following arguments : ...
lineno = int ( lineno ) if module is None : module = filename or "<unknown>" if module [ - 3 : ] . lower ( ) == ".py" : module = module [ : - 3 ] # XXX What about leading pathname ? if registry is None : registry = { } if registry . get ( 'version' , 0 ) != warnings . _filters_version : ...
def read_annotations ( path_or_file , separator = '\t' , reset = True ) : """Read all annotations from the specified file . > > > annotations = read _ annotations ( path _ or _ file , separator ) > > > colnames = annotations [ ' Column Name ' ] > > > types = annotations [ ' Type ' ] > > > annot _ row = anno...
annotations = OrderedDict ( { } ) with PathOrFile ( path_or_file , 'r' , reset = reset ) as f : annotations [ 'Column Name' ] = f . readline ( ) . strip ( ) . split ( separator ) for line in f : if line . startswith ( '#!{' ) : tokens = line . strip ( ) . split ( separator ) _nam...
def rescale_pixel_values ( images , order = "C" ) : """Rescale the range of values in images to be between [ 0 , 1]"""
images = np . asarray ( images , order = order ) . astype ( "float32" ) images -= images . min ( ) images /= images . max ( ) return images
def run ( self , * args ) : """Get and set configuration parameters . This command gets or sets parameter values from the user configuration file . On Linux systems , configuration will be stored in the file ' ~ / . sortinghat ' ."""
params = self . parser . parse_args ( args ) config_file = os . path . expanduser ( '~/.sortinghat' ) if params . action == 'get' : code = self . get ( params . parameter , config_file ) elif params . action == 'set' : code = self . set ( params . parameter , params . value , config_file ) else : raise Runt...