signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def announced_networks ( self ) :
"""Show all announced networks for the BGP configuration .
Returns tuple of advertised network , routemap . Route
map may be None .
for advertised in engine . bgp . advertisements :
net , route _ map = advertised
: return : list of tuples ( advertised _ network , route _ ... | return [ ( Element . from_href ( ne . get ( 'announced_ne_ref' ) ) , Element . from_href ( ne . get ( 'announced_rm_ref' ) ) ) for ne in self . data . get ( 'announced_ne_setting' ) ] |
def make_objs ( names , out_dir = '' ) :
"""Make object file names for cl . exe and link . exe .""" | objs = [ replace_ext ( name , '.obj' ) for name in names ]
if out_dir :
objs = [ os . path . join ( out_dir , obj ) for obj in objs ]
return objs |
async def release_forks ( self , philosopher ) :
'''The ` ` philosopher ` ` has just eaten and is ready to release both
forks .
This method releases them , one by one , by sending the ` ` put _ down ` `
action to the monitor .''' | forks = self . forks
self . forks = [ ]
self . started_waiting = 0
for fork in forks :
philosopher . logger . debug ( 'Putting down fork %s' , fork )
await philosopher . send ( 'monitor' , 'putdown_fork' , fork )
await sleep ( self . cfg . waiting_period ) |
def append ( self , page , content , ** options ) :
"""Appends * content * text to * page * .
Valid * options * are :
* * sum * : ( str ) change summary
* * minor * : ( bool ) whether this is a minor change""" | return self . _dokuwiki . send ( 'dokuwiki.appendPage' , page , content , options ) |
def patch_namespaced_persistent_volume_claim_status ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""patch _ namespaced _ persistent _ volume _ claim _ status # noqa : E501
partially update status of the specified PersistentVolumeClaim # noqa : E501
This method makes a synchronous HTTP request ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . patch_namespaced_persistent_volume_claim_status_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . patch_namespaced_persistent_volume_claim_status_with_http_info ( name , nam... |
def evaluate ( self , dataset , metric = "auto" , missing_value_action = 'auto' , with_predictions = False , options = { } , ** kwargs ) :
"""Evaluate the model by making predictions of target values and comparing
these to actual values .
Parameters
dataset : SFrame
Dataset in the same format used for train... | if missing_value_action == 'auto' :
missing_value_action = select_default_missing_value_policy ( self , 'evaluate' )
_raise_error_if_not_sframe ( dataset , "dataset" )
results = self . __proxy__ . evaluate ( dataset , missing_value_action , metric , with_predictions = with_predictions ) ;
return results |
def polynet ( num_classes = 1000 , pretrained = 'imagenet' ) :
"""PolyNet architecture from the paper
' PolyNet : A Pursuit of Structural Diversity in Very Deep Networks '
https : / / arxiv . org / abs / 1611.05725""" | if pretrained :
settings = pretrained_settings [ 'polynet' ] [ pretrained ]
assert num_classes == settings [ 'num_classes' ] , 'num_classes should be {}, but is {}' . format ( settings [ 'num_classes' ] , num_classes )
model = PolyNet ( num_classes = num_classes )
model . load_state_dict ( model_zoo . l... |
def create_page_move ( self , page_move_parameters , project , wiki_identifier , comment = None ) :
"""CreatePageMove .
Creates a page move operation that updates the path and order of the page as provided in the parameters .
: param : class : ` < WikiPageMoveParameters > < azure . devops . v5_0 . wiki . models... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if wiki_identifier is not None :
route_values [ 'wikiIdentifier' ] = self . _serialize . url ( 'wiki_identifier' , wiki_identifier , 'str' )
query_parameters = { }
if comment is not N... |
def release ( self , force = False ) :
"""Release lock .
To release a lock , we must already own the lock .
Arguments :
force ( bool , optional ) : If true , ignore any existing lock owner .
Raises :
UnableToReleaseLockError : If the lock is claimed by another
process ( not raised if force option is use... | # There ' s no lock , so do nothing .
if not self . islocked :
return
if self . owned_by_self or force :
os . remove ( self . path )
else :
raise UnableToReleaseLockError ( self ) |
def do_organization_info ( ava ) :
"""Description of an organization in the configuration is
a dictionary of keys and values , where the values might be tuples : :
" organization " : {
" name " : ( " AB Exempel " , " se " ) ,
" display _ name " : ( " AB Exempel " , " se " ) ,
" url " : " http : / / www . ... | if ava is None :
return None
org = md . Organization ( )
for dkey , ( ckey , klass ) in ORG_ATTR_TRANSL . items ( ) :
if ckey not in ava :
continue
if isinstance ( ava [ ckey ] , six . string_types ) :
setattr ( org , dkey , [ _localized_name ( ava [ ckey ] , klass ) ] )
elif isinstance ... |
def split ( self ) :
"""Split the leaf node .""" | if self . split_mode == 'random' : # Split randomly between min and max of node ' s points on split dimension
split_dim_data = self . get_data_x ( ) [ self . idxs , self . split_dim ]
# data on split dim
split_min = min ( split_dim_data )
split_max = max ( split_dim_data )
split_value = split_min + ... |
def get_form_layout ( self , process_id , wit_ref_name ) :
"""GetFormLayout .
[ Preview API ] Gets the form layout .
: param str process _ id : The ID of the process .
: param str wit _ ref _ name : The reference name of the work item type .
: rtype : : class : ` < FormLayout > < azure . devops . v5_0 . wor... | route_values = { }
if process_id is not None :
route_values [ 'processId' ] = self . _serialize . url ( 'process_id' , process_id , 'str' )
if wit_ref_name is not None :
route_values [ 'witRefName' ] = self . _serialize . url ( 'wit_ref_name' , wit_ref_name , 'str' )
response = self . _send ( http_method = 'GET... |
def function_dict ( self ) :
"""Equivalent to ` ` self . model _ dict ` ` , but with all variables replaced by
functions if applicable . Sorted by the evaluation order according to
` ` self . ordered _ symbols ` ` , not alphabetical like ` ` self . model _ dict ` ` !""" | func_dict = OrderedDict ( )
for var , func in self . vars_as_functions . items ( ) :
expr = self . model_dict [ var ] . xreplace ( self . vars_as_functions )
func_dict [ func ] = expr
return func_dict |
def put ( self , context ) :
"""Return a reference , making it eligable for recycling once its reference
count reaches zero .""" | LOG . debug ( '%r.put(%r)' , self , context )
self . _lock . acquire ( )
try :
if self . _refs_by_context . get ( context , 0 ) == 0 :
LOG . warning ( '%r.put(%r): refcount was 0. shutdown_all called?' , self , context )
return
self . _refs_by_context [ context ] -= 1
finally :
self . _lock ... |
def authenticate ( self , request ) :
"""Returns a ` User ` if a correct access token has been supplied
in the Authorization header . Otherwise returns ` None ` .""" | auth = get_authorization_header ( request ) . split ( )
if not auth or auth [ 0 ] . lower ( ) != b'bearer' :
return None
if len ( auth ) == 1 :
msg = 'Invalid authorization header. No credentials provided.'
raise exceptions . AuthenticationFailed ( msg )
elif len ( auth ) > 2 :
msg = 'Invalid authorizat... |
def _split_after_delimiter ( self , item , indent_amt ) :
"""Split the line only after a delimiter .""" | self . _delete_whitespace ( )
if self . fits_on_current_line ( item . size ) :
return
last_space = None
for item in reversed ( self . _lines ) :
if ( last_space and ( not isinstance ( item , Atom ) or not item . is_colon ) ) :
break
else :
last_space = None
if isinstance ( item , self . ... |
def debug ( func ) :
"""Print the function name and arguments for debugging .""" | @ wraps ( func )
def wrapper ( * args , ** kwargs ) :
print ( "{} args: {} kwargs: {}" . format ( func . __name__ , args , kwargs ) )
return func ( * args , ** kwargs )
return wrapper |
def formatted_ghost_file ( self ) :
"""Returns a properly formatted ghost file name .
: returns : formatted ghost _ file name ( string )""" | # replace specials characters in ' drive : \ filename ' in Linux and Dynamips in MS Windows or viceversa .
ghost_file = "{}-{}.ghost" . format ( os . path . basename ( self . _image ) , self . _ram )
ghost_file = ghost_file . replace ( '\\' , '-' ) . replace ( '/' , '-' ) . replace ( ':' , '-' )
return ghost_file |
def optional ( self ) :
"""Flag indicating an optional property .""" | value = self . _schema . get ( "optional" , False )
if value is not False and value is not True :
raise SchemaError ( "optional value {0!r} is not a boolean" . format ( value ) )
return value |
def positional ( max_pos_args ) :
"""A decorator to declare that only the first N arguments may be positional .
Note that for methods , n includes ' self ' .""" | __ndb_debug__ = 'SKIP'
def positional_decorator ( wrapped ) :
if not DEBUG :
return wrapped
__ndb_debug__ = 'SKIP'
@ wrapping ( wrapped )
def positional_wrapper ( * args , ** kwds ) :
__ndb_debug__ = 'SKIP'
if len ( args ) > max_pos_args :
plural_s = ''
if... |
def validate_commit_range ( repo_dir , old_commit , new_commit ) :
"""Check if commit range is valid . Flip it if needed .""" | # Are there any commits between the two commits that were provided ?
try :
commits = get_commits ( repo_dir , old_commit , new_commit )
except Exception :
commits = [ ]
if len ( commits ) == 0 : # The user might have gotten their commits out of order . Let ' s flip
# the order of the commits and try again .
... |
def get_logs_multipart ( w3 , startBlock , stopBlock , address , topics , max_blocks ) :
"""Used to break up requests to ` ` eth _ getLogs ` `
The getLog request is partitioned into multiple calls of the max number of blocks
` ` max _ blocks ` ` .""" | _block_ranges = block_ranges ( startBlock , stopBlock , max_blocks )
for from_block , to_block in _block_ranges :
params = { 'fromBlock' : from_block , 'toBlock' : to_block , 'address' : address , 'topics' : topics }
yield w3 . eth . getLogs ( drop_items_with_none_value ( params ) ) |
async def async_delete_device ( self , device_id : int ) -> None :
"""Delete an enrolled device .
: param device _ id : unique identifier for the device to be deleted""" | # Lookup device using zone to obtain an accurate index , which is
# needed to perform the delete command
device = self . _devices [ device_id ]
response = await self . _protocol . async_execute ( GetDeviceCommand ( device . category , device . group_number , device . unit_number ) )
if isinstance ( response , DeviceInf... |
async def _get_descriptions ( self ) :
"""Read a column descriptor packet for each column in the result .""" | self . fields = [ ]
self . converters = [ ]
use_unicode = self . connection . use_unicode
conn_encoding = self . connection . encoding
description = [ ]
for i in range ( self . field_count ) :
field = await self . connection . _read_packet ( FieldDescriptorPacket )
self . fields . append ( field )
descripti... |
def access_token_handler ( self , ** args ) :
"""Get access token based on cookie sent with this request .
This handler deals with two cases :
1 ) Non - browser client ( indicated by no messageId set in request )
where the response is a simple JSON response .
2 ) Browser client ( indicate by messageId setin... | message_id = request . args . get ( 'messageId' , default = None )
origin = request . args . get ( 'origin' , default = 'unknown_origin' )
self . logger . info ( "access_token_handler: origin = " + origin )
account = request . cookies . get ( self . account_cookie_name , default = '' )
token = self . access_token ( acc... |
def _get_unknown_error_response ( self , request , exc ) :
"""Generate HttpResponse for unknown exceptions .
todo : this should be more informative . .""" | logging . getLogger ( 'devil' ) . error ( 'while doing %s on %s with [%s], devil caught: %s' % ( request . method , request . path_info , str ( request . GET ) , str ( exc ) ) , exc_info = True )
if settings . DEBUG :
raise
else :
return HttpResponse ( status = codes . INTERNAL_SERVER_ERROR [ 1 ] ) |
def wkb ( self ) :
"""Get the geometry as an ( E ) WKB .""" | return self . _to_wkb ( use_srid = True , dimz = self . dimz , dimm = self . dimm ) |
def rpole_to_pot_aligned ( rpole , sma , q , F , d , component = 1 ) :
"""Transforms polar radius to surface potential""" | q = q_for_component ( q , component = component )
rpole_ = np . array ( [ 0 , 0 , rpole / sma ] )
logger . debug ( "libphoebe.roche_Omega(q={}, F={}, d={}, rpole={})" . format ( q , F , d , rpole_ ) )
pot = libphoebe . roche_Omega ( q , F , d , rpole_ )
return pot_for_component ( pot , component , reverse = True ) |
def count_tf ( tokens_stream ) :
"""Count term frequencies for a single file .""" | tf = defaultdict ( int )
for tokens in tokens_stream :
for token in tokens :
tf [ token ] += 1
return tf |
def do_visualize ( model , model_path , nr_visualize = 100 , output_dir = 'output' ) :
"""Visualize some intermediate results ( proposals , raw predictions ) inside the pipeline .""" | df = get_train_dataflow ( )
# we don ' t visualize mask stuff
df . reset_state ( )
pred = OfflinePredictor ( PredictConfig ( model = model , session_init = get_model_loader ( model_path ) , input_names = [ 'image' , 'gt_boxes' , 'gt_labels' ] , output_names = [ 'generate_{}_proposals/boxes' . format ( 'fpn' if cfg . MO... |
def fill_from_allwise ( self , ident , catalog_ident = 'II/328/allwise' ) :
"""Fill in astrometric information from the AllWISE catalog using Astroquery .
This uses the : mod : ` astroquery ` module to query the AllWISE
(2013wise . rept . . . . 1C ) source catalog through the Vizier
(2000A & AS . . 143 . . . ... | from astroquery . vizier import Vizier
import numpy . ma . core as ma_core
# We should match exactly one table and one row within that table , but
# for robustness we ignore additional results if they happen to
# appear . Strangely , querying for an invalid identifier yields a table
# with two rows that are filled with... |
def splitarg ( args ) :
'''This function will split arguments separated by spaces or commas
to be backwards compatible with the original ArcGet command line tool''' | if not args :
return args
split = list ( )
for arg in args :
if ',' in arg :
split . extend ( [ x for x in arg . split ( ',' ) if x ] )
elif arg :
split . append ( arg )
return split |
def remove_asset ( self , asset_id , composition_id ) :
"""Removes an ` ` Asset ` ` from a ` ` Composition ` ` .
arg : asset _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` Asset ` `
arg : composition _ id ( osid . id . Id ) : ` ` Id ` ` of the
` ` Composition ` `
raise : NotFound - ` ` asset _ id ` ` ` ` n... | if ( not isinstance ( composition_id , ABCId ) and composition_id . get_identifier_namespace ( ) != 'repository.Composition' ) :
raise errors . InvalidArgument ( 'the argument is not a valid OSID Id' )
composition_map , collection = self . _get_composition_collection ( composition_id )
try :
composition_map [ '... |
def update ( self ) :
"""Determines in how many segments the whole reach needs to be
divided to approximate the desired lag time via integer rounding .
Adjusts the shape of sequence | QJoints | additionally .
Required control parameters :
| Lag |
Calculated derived parameters :
| NmbSegments |
Prepare... | pars = self . subpars . pars
self ( int ( round ( pars . control . lag ) ) )
pars . model . sequences . states . qjoints . shape = self + 1 |
def remove_server_data ( server_id ) :
"""Remove a server from the server data
Args :
server _ id ( int ) : The server to remove from the server data""" | logger . debug ( "Removing server from serverdata" )
# Remove the server from data
data = datatools . get_data ( )
if server_id in data [ "discord" ] [ "servers" ] :
data [ "discord" ] [ "servers" ] . pop ( server_id )
datatools . write_data ( data ) |
def tle ( self , url , reload = False , filename = None ) :
"""Load and parse a satellite TLE file .
Given a URL or a local path , this loads a file of three - line records in
the common Celestrak file format , or two - line records like those from
space - track . org . For a three - line element set , each f... | d = { }
with self . open ( url , reload = reload , filename = filename ) as f :
for names , sat in parse_tle ( f ) :
d [ sat . model . satnum ] = sat
for name in names :
d [ name ] = sat
return d |
def seg ( reference_intervals , estimated_intervals ) :
"""Compute the MIREX ' MeanSeg ' score .
Examples
> > > ( ref _ intervals ,
. . . ref _ labels ) = mir _ eval . io . load _ labeled _ intervals ( ' ref . lab ' )
> > > ( est _ intervals ,
. . . est _ labels ) = mir _ eval . io . load _ labeled _ inte... | return min ( underseg ( reference_intervals , estimated_intervals ) , overseg ( reference_intervals , estimated_intervals ) ) |
def league_scores ( self , total_data , time , show_datetime , use_12_hour_format ) :
"""Prints the data in a pretty format""" | for match in total_data [ 'matches' ] :
self . scores ( self . parse_result ( match ) , add_new_line = not show_datetime )
if show_datetime :
click . secho ( ' %s' % Stdout . utc_to_local ( match [ "utcDate" ] , use_12_hour_format , show_datetime ) , fg = self . colors . TIME )
click . echo ( ) |
def main ( ) :
"""Main function for command line usage""" | usage = "usage: %(prog)s [options] "
description = "Merge a set of Fermi-LAT files."
parser = argparse . ArgumentParser ( usage = usage , description = description )
parser . add_argument ( '-o' , '--output' , default = None , type = str , help = 'Output file.' )
parser . add_argument ( '--clobber' , default = False , ... |
def add_catalogue ( self , catalogue , overlay = False ) :
''': param catalogue :
Earthquake catalogue as instance of
: class : ` openquake . hmtk . seismicity . catalogue . Catalogue `
: param dict config :
Configuration parameters of the algorithm , containing the
following information :
' min _ lat '... | # Magnitudes bins and minimum marrker size
# min _ mag = np . min ( catalogue . data [ ' magnitude ' ] )
# max _ mag = np . max ( catalogue . data [ ' magnitude ' ] )
con_min = np . where ( np . array ( [ symb [ 0 ] for symb in DEFAULT_SYMBOLOGY ] ) < np . min ( catalogue . data [ 'magnitude' ] ) ) [ 0 ]
con_max = np .... |
def tablib_export_action ( modeladmin , request , queryset , file_type = "xls" ) :
"""Allow the user to download the current filtered list of items
: param file _ type :
One of the formats supported by tablib ( e . g . " xls " , " csv " , " html " ,
etc . )""" | dataset = SimpleDataset ( queryset , headers = None )
filename = '{0}.{1}' . format ( smart_str ( modeladmin . model . _meta . verbose_name_plural ) , file_type )
response_kwargs = { 'content_type' : get_content_type ( file_type ) }
response = HttpResponse ( getattr ( dataset , file_type ) , ** response_kwargs )
respon... |
def view_pdf ( name = None ) :
"""Render a pdf file based on the given page .
. . note : : this is a bottle view
Keyword Arguments :
: name : ( str ) - - name of the rest file ( without the . rst extension )
MANDATORY""" | if name is None :
return view_meta_index ( )
files = glob . glob ( "{0}.rst" . format ( name ) )
if len ( files ) > 0 :
file_handle = open ( files [ 0 ] , 'r' )
dest_filename = name + '.pdf'
doctree = publish_doctree ( file_handle . read ( ) )
try :
produce_pdf ( doctree_content = doctree , ... |
def signalflow ( self , token , endpoint = None , timeout = None , compress = None ) :
"""Obtain a SignalFlow API client .""" | from . import signalflow
compress = compress if compress is not None else self . _compress
return signalflow . SignalFlowClient ( token = token , endpoint = endpoint or self . _stream_endpoint , timeout = timeout or self . _timeout , compress = compress ) |
def _overlap_slices ( self , shape ) :
"""Calculate the slices for the overlapping part of the bounding
box and an array of the given shape .
Parameters
shape : tuple of int
The ` ` ( ny , nx ) ` ` shape of array where the slices are to be
applied .
Returns
slices _ large : tuple of slices
A tuple o... | if len ( shape ) != 2 :
raise ValueError ( 'input shape must have 2 elements.' )
xmin = self . bbox . ixmin
xmax = self . bbox . ixmax
ymin = self . bbox . iymin
ymax = self . bbox . iymax
if xmin >= shape [ 1 ] or ymin >= shape [ 0 ] or xmax <= 0 or ymax <= 0 : # no overlap of the aperture with the data
return... |
def get_dataset_url ( self , tournament = 1 ) :
"""Fetch url of the current dataset .
Args :
tournament ( int , optional ) : ID of the tournament , defaults to 1
Returns :
str : url of the current dataset
Example :
> > > NumerAPI ( ) . get _ dataset _ url ( )
https : / / numerai - datasets . s3 . amaz... | query = """
query($tournament: Int!) {
dataset(tournament: $tournament)
}"""
arguments = { 'tournament' : tournament }
url = self . raw_query ( query , arguments ) [ 'data' ] [ 'dataset' ]
return url |
def withdraw ( self , currency , amount , address , paymentId = None ) :
"""Immediately places a withdrawal for a given currency , with no email
confirmation . In order to use this method , the withdrawal privilege
must be enabled for your API key . Required POST parameters are
" currency " , " amount " , and... | return self . _private ( 'withdraw' , currency = currency , amount = amount , address = address , paymentId = paymentId ) |
def get_localontologies ( pattern = "" ) :
"returns a list of file names in the ontologies folder ( not the full path )" | res = [ ]
ONTOSPY_LOCAL_MODELS = get_home_location ( )
if not os . path . exists ( ONTOSPY_LOCAL_MODELS ) :
get_or_create_home_repo ( )
for f in os . listdir ( ONTOSPY_LOCAL_MODELS ) :
if os . path . isfile ( os . path . join ( ONTOSPY_LOCAL_MODELS , f ) ) :
if not f . startswith ( "." ) and not f . end... |
def search_tag ( self , tag , symbols = True , feeds = False ) :
"""Get a list of Symbols by searching a tag or partial tag .
Parameters
tag : str
The tag to search . Appending ' % ' will use SQL ' s " LIKE "
functionality .
symbols : bool , optional
Search for Symbol ' s based on their tags .
feeds :... | syms = [ ]
if isinstance ( tag , ( str , unicode ) ) :
tags = [ tag ]
else :
tags = tag
if symbols :
crits = [ ]
for tag in tags :
if "%" in tag :
crit = SymbolTag . tag . like ( tag )
else :
crit = SymbolTag . tag == tag
crits . append ( crit )
qry = ... |
def _onShortcutPrint ( self ) :
"""Ctrl + P handler .
Show dialog , print file""" | dialog = QPrintDialog ( self )
if dialog . exec_ ( ) == QDialog . Accepted :
printer = dialog . printer ( )
self . print_ ( printer ) |
def init_arg_names ( obj ) :
"""Names of arguments to _ _ init _ _ method of this object ' s class .""" | # doing something wildly hacky by pulling out the arguments to
# _ _ init _ _ or _ _ new _ _ and hoping that they match fields defined on the
# object
try :
init_code = obj . __init__ . __func__ . __code__
except AttributeError :
try :
init_code = obj . __new__ . __func__ . __code__
except Attribute... |
def fetch_plaintext_by_subject ( self , email_name ) :
"""Get the plain text of an email , searching by subject .
@ Params
email _ name - the subject to search for
@ Returns
Plaintext content of the matched email""" | if not email_name :
raise EmailException ( "Subject cannot be null" )
results = self . __imap_search ( SUBJECT = email_name )
sources = self . fetch_plaintext ( results )
return sources |
def pssm_array2pwm_array ( arr , background_probs = DEFAULT_BASE_BACKGROUND ) :
"""Convert pssm array to pwm array""" | b = background_probs2array ( background_probs )
b = b . reshape ( [ 1 , 4 , 1 ] )
return ( np . exp ( arr ) * b ) . astype ( arr . dtype ) |
def _load_edflib ( filename ) :
"""load a multi - channel Timeseries from an EDF ( European Data Format ) file
or EDF + file , using edflib .
Args :
filename : EDF + file
Returns :
Timeseries""" | import edflib
e = edflib . EdfReader ( filename , annotations_mode = 'all' )
if np . ptp ( e . get_samples_per_signal ( ) ) != 0 :
raise Error ( 'channels have differing numbers of samples' )
if np . ptp ( e . get_signal_freqs ( ) ) != 0 :
raise Error ( 'channels have differing sample rates' )
n = e . samples_i... |
def trends_available ( self ) :
"""Returns a list of regions for which Twitter tracks trends .""" | url = 'https://api.twitter.com/1.1/trends/available.json'
try :
resp = self . get ( url )
except requests . exceptions . HTTPError as e :
raise e
return resp . json ( ) |
def post_resource ( collection ) :
"""Return the appropriate * Response * based on adding a new resource to
* collection * .
: param string collection : a : class : ` sandman . model . Model ` endpoint
: rtype : : class : ` flask . Response `""" | cls = endpoint_class ( collection )
resource = cls ( )
resource . from_dict ( get_resource_data ( request ) )
_validate ( cls , request . method , resource )
_perform_database_action ( 'add' , resource )
return resource_created_response ( resource ) |
def class_wise_accuracy ( self , scene_label ) :
"""Class - wise accuracy
Returns
dict
results in a dictionary format""" | if len ( self . accuracies_per_class . shape ) == 2 :
return { 'accuracy' : float ( numpy . mean ( self . accuracies_per_class [ : , self . scene_label_list . index ( scene_label ) ] ) ) }
else :
return { 'accuracy' : float ( numpy . mean ( self . accuracies_per_class [ self . scene_label_list . index ( scene_l... |
def get_api_resources ( self , ** kwargs ) :
"""get available resources
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . get _ api _ resources ( async _ req = True )
> > > result = thread . get ( )
: param ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_api_resources_with_http_info ( ** kwargs )
else :
( data ) = self . get_api_resources_with_http_info ( ** kwargs )
return data |
def dataSetElementType ( h5Dataset ) :
"""Returns a string describing the element type of the dataset""" | dtype = h5Dataset . dtype
if dtype . names :
return '<structured>'
else :
if dtype . metadata and 'vlen' in dtype . metadata :
vlen_type = dtype . metadata [ 'vlen' ]
try :
return "<vlen {}>" . format ( vlen_type . __name__ )
# when vlen _ type is a type
except At... |
def generate_base_points ( num_points , domain_size , density_map = None , reflect = True ) :
r"""Generates a set of base points for passing into the Tessellation - based
Network classes . The points can be distributed in spherical , cylindrical ,
or rectilinear patterns , as well as 2D and 3D ( disks and squar... | def _try_points ( num_points , prob ) :
prob = sp . atleast_3d ( prob )
prob = sp . array ( prob ) / sp . amax ( prob )
# Ensure prob is normalized
base_pts = [ ]
N = 0
while N < num_points :
pt = sp . random . rand ( 3 )
# Generate a point
# Test whether to keep it or no... |
def classify_segmented_recording ( recording , result_format = None ) :
"""Use this function if you are sure you have a single symbol .
Parameters
recording : string
The recording in JSON format
Returns
list of dictionaries
Each dictionary contains the keys ' symbol ' and ' probability ' . The list
is... | global single_symbol_classifier
if single_symbol_classifier is None :
single_symbol_classifier = SingleClassificer ( )
return single_symbol_classifier . predict ( recording , result_format ) |
def get_occurrence ( exchange_id , instance_index , format = u"Default" ) :
"""Requests one or more calendar items from the store matching the master & index .
exchange _ id is the id for the master event in the Exchange store .
format controls how much data you get back from Exchange . Full docs are here , but... | root = M . GetItem ( M . ItemShape ( T . BaseShape ( format ) ) , M . ItemIds ( ) )
items_node = root . xpath ( "//m:ItemIds" , namespaces = NAMESPACES ) [ 0 ]
for index in instance_index :
items_node . append ( T . OccurrenceItemId ( RecurringMasterId = exchange_id , InstanceIndex = str ( index ) ) )
return root |
def __gen_random_values ( self ) :
'''Generate random values based on supplied value ranges
Returns :
list : random values , one per tunable variable''' | values = [ ]
if self . _value_ranges is None :
self . _logger . log ( 'crit' , 'Must set the type/range of possible values' )
raise RuntimeError ( "Must set the type/range of possible values" )
else :
for t in self . _value_ranges :
if t [ 0 ] == 'int' :
values . append ( randint ( t [ 1... |
def _read_join_synack ( self , bits , size , kind ) :
"""Read Join Connection option for Responding SYN / ACK .
Positional arguments :
* bits - str , 4 - bit data
* size - int , length of option
* kind - int , 30 ( Multipath TCP )
Returns :
* dict - - extracted Join Connection ( MP _ JOIN - SYN / ACK ) ... | adid = self . _read_unpack ( 1 )
hmac = self . _read_fileng ( 8 )
srno = self . _read_unpack ( 4 )
data = dict ( kind = kind , length = size + 1 , subtype = 'MP_JOIN-SYN/ACK' , join = dict ( synack = dict ( backup = True if int ( bits [ 3 ] ) else False , addrid = adid , hmac = hmac , randnum = srno , ) , ) , )
return ... |
def distance ( p0 , p1 , deg = True , r = r_earth_mean ) :
"""Return the distance between two points on the surface of the Earth .
Parameters
p0 : point - like ( or array of point - like ) [ longitude , latitude ] objects
p1 : point - like ( or array of point - like ) [ longitude , latitude ] objects
deg : ... | single , ( p0 , p1 ) = _to_arrays ( ( p0 , 2 ) , ( p1 , 2 ) )
if deg :
p0 = np . radians ( p0 )
p1 = np . radians ( p1 )
lon0 , lat0 = p0 [ : , 0 ] , p0 [ : , 1 ]
lon1 , lat1 = p1 [ : , 0 ] , p1 [ : , 1 ]
# h _ x used to denote haversine ( x ) : sin ^ 2 ( x / 2)
h_dlat = sin ( ( lat1 - lat0 ) / 2.0 ) ** 2
h_dlo... |
def parse_samtools_idxstats ( self ) :
"""Find Samtools idxstats logs and parse their data""" | self . samtools_idxstats = dict ( )
for f in self . find_log_files ( 'samtools/idxstats' ) :
parsed_data = parse_single_report ( f [ 'f' ] )
if len ( parsed_data ) > 0 :
if f [ 's_name' ] in self . samtools_idxstats :
log . debug ( "Duplicate sample name found! Overwriting: {}" . format ( f ... |
def trace_integration ( tracer = None ) :
"""Integrate with pymongo to trace it using event listener .""" | log . info ( 'Integrated module: {}' . format ( MODULE_NAME ) )
monitoring . register ( MongoCommandListener ( tracer = tracer ) ) |
def _set_pb_meaning_from_entity ( entity , name , value , value_pb , is_list = False ) :
"""Add meaning information ( from an entity ) to a protobuf .
: type entity : : class : ` google . cloud . datastore . entity . Entity `
: param entity : The entity to be turned into a protobuf .
: type name : str
: par... | if name not in entity . _meanings :
return
meaning , orig_value = entity . _meanings [ name ]
# Only add the meaning back to the protobuf if the value is
# unchanged from when it was originally read from the API .
if orig_value is not value :
return
# For lists , we set meaning on each sub - element .
if is_lis... |
def temp_output_dir ( prefix = "tmp" , suffix = "" , dir = None , make_parents = False , always_clean = False ) :
"""A context manager for convenience in creating a temporary directory ,
which is deleted when exiting the context .
Usage :
with temp _ output _ dir ( ) as dirname :""" | return _temp_output ( True , prefix = prefix , suffix = suffix , dir = dir , make_parents = make_parents , always_clean = always_clean ) |
def amen_mv ( A , x , tol , y = None , z = None , nswp = 20 , kickrank = 4 , kickrank2 = 0 , verb = True , init_qr = True , renorm = 'direct' , fkick = False ) :
'''Approximate the matrix - by - vector via the AMEn iteration
[ y , z ] = amen _ mv ( A , x , tol , varargin )
Attempts to approximate the y = A * x ... | if renorm is 'gram' :
print ( "Not implemented yet. Renorm is switched to 'direct'" )
renorm = 'direct'
if isinstance ( x , _tt . vector ) :
d = x . d
m = x . n
rx = x . r
x = _tt . vector . to_list ( x )
vectype = 1
# tt _ tensor
elif isinstance ( x , list ) :
d = len ( x )
m = ... |
def get_beamarea_deg2 ( self , ra , dec ) :
"""Calculate the area of the beam in square degrees .
Parameters
ra , dec : float
The sky position ( degrees ) .
Returns
area : float
The area of the beam in square degrees .""" | beam = self . get_beam ( ra , dec )
if beam is None :
return 0
return beam . a * beam . b * np . pi |
def set_parent ( self , parent ) :
"""Set the parent of the treeitem
: param parent : parent treeitem
: type parent : : class : ` TreeItem ` | None
: returns : None
: rtype : None
: raises : None""" | if self . _parent == parent :
return
if self . _parent :
self . _parent . remove_child ( self )
self . _parent = parent
if parent :
parent . add_child ( self ) |
def coherence ( freq , power , cross ) :
"""Calculate frequency resolved coherence for given power - and crossspectra .
Parameters
freq : numpy . ndarray
Frequencies , 1 dim array .
power : numpy . ndarray
Power spectra , 1st axis units , 2nd axis frequencies .
cross : numpy . ndarray ,
Cross spectra ... | N = len ( power )
coh = np . zeros ( np . shape ( cross ) )
for i in range ( N ) :
for j in range ( N ) :
coh [ i , j ] = cross [ i , j ] / np . sqrt ( power [ i ] * power [ j ] )
assert ( len ( freq ) == len ( coh [ 0 , 0 ] ) )
return freq , coh |
def gates_close ( gate0 : Gate , gate1 : Gate , tolerance : float = TOLERANCE ) -> bool :
"""Returns : True if gates are almost identical .
Closeness is measured with the gate angle .""" | return vectors_close ( gate0 . vec , gate1 . vec , tolerance ) |
def rmtree_p ( self ) :
"""Like : meth : ` rmtree ` , but does not raise an exception if the
directory does not exist .""" | try :
self . rmtree ( )
except OSError :
_ , e , _ = sys . exc_info ( )
if e . errno != errno . ENOENT :
raise
return self |
def _build_wells ( self ) -> List [ Well ] :
"""This function is used to create one instance of wells to be used by all
accessor functions . It is only called again if a new offset needs
to be applied .""" | return [ Well ( self . _well_definition [ well ] , Location ( self . _calibrated_offset , self ) , "{} of {}" . format ( well , self . _display_name ) , self . is_tiprack ) for well in self . _ordering ] |
async def reply_sticker ( self , sticker : typing . Union [ base . InputFile , base . String ] , disable_notification : typing . Union [ base . Boolean , None ] = None , reply_markup = None , reply = True ) -> Message :
"""Use this method to send . webp stickers .
Source : https : / / core . telegram . org / bots... | return await self . bot . send_sticker ( chat_id = self . chat . id , sticker = sticker , disable_notification = disable_notification , reply_to_message_id = self . message_id if reply else None , reply_markup = reply_markup ) |
def positive_int ( val ) :
"""Parse ` val ` into a positive integer .""" | if isinstance ( val , float ) :
raise ValueError ( '"{}" must not be a float' . format ( val ) )
val = int ( val )
if val >= 0 :
return val
raise ValueError ( '"{}" must be positive' . format ( val ) ) |
def not_right ( self , num ) :
"""WITH SLICES BEING FLAT , WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [ : - num : ]""" | if num == None :
return FlatList ( [ _get_list ( self ) [ : - 1 : ] ] )
if num <= 0 :
return FlatList . EMPTY
return FlatList ( _get_list ( self ) [ : - num : ] ) |
def info ( ) :
"""Generate information for a bug report .
Based on the requests package help utility module .""" | try :
platform_info = { "system" : platform . system ( ) , "release" : platform . release ( ) }
except IOError :
platform_info = { "system" : "Unknown" , "release" : "Unknown" }
implementation = platform . python_implementation ( )
if implementation == "CPython" :
implementation_version = platform . python_... |
def qsat ( self , temp , pres , parameter ) :
"""Calculate ( qsat _ lst ) vector of saturation humidity from :
temp = vector of element layer temperatures
pres = pressure ( at current timestep ) .""" | gamw = ( parameter . cl - parameter . cpv ) / parameter . rv
betaw = ( parameter . lvtt / parameter . rv ) + ( gamw * parameter . tt )
alpw = math . log ( parameter . estt ) + ( betaw / parameter . tt ) + ( gamw * math . log ( parameter . tt ) )
work2 = parameter . r / parameter . rv
foes_lst = [ 0 for i in range ( len... |
def get_repository_with_parent ( self , repository_id , include_parent , project = None ) :
"""GetRepositoryWithParent .
Retrieve a git repository .
: param str repository _ id : The name or ID of the repository .
: param bool include _ parent : True to include parent repository . Only available in authentica... | 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' )
query_parameters = { }
if include_parent is not No... |
def add_widget ( self , wclass ) :
"""Adds a new item to the treeview .""" | tree = self . treeview
# get the selected item :
selected_item = ''
tsel = tree . selection ( )
if tsel :
selected_item = tsel [ 0 ]
# Need to remove filter if set
self . filter_remove ( )
root = selected_item
# check if the widget can be added at selected point
if not self . _validate_add ( root , wclass , False )... |
def is_entailed_by ( self , other ) :
"""Given two beliefstates , returns True iff the calling instance
implies the other beliefstate , meaning it contains at least the same
structure ( for all structures ) and all values ( for all defined values ) .
Inverse of ` entails ` .
Note : this only compares the it... | for ( s_key , s_val ) in self :
if s_key in other :
if not hasattr ( other [ s_key ] , 'implies' ) :
raise Exception ( "Cell for %s is missing implies()" % s_key )
if not other [ s_key ] . implies ( s_val ) :
return False
else :
return False
return True |
def dp2hx ( number , lenout = _default_len_out ) :
"""Convert a double precision number to an equivalent character
string using base 16 " scientific notation . "
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / dp2hx _ c . html
: param number : D . p . number to be converted .
... | number = ctypes . c_double ( number )
lenout = ctypes . c_int ( lenout )
string = stypes . stringToCharP ( lenout )
length = ctypes . c_int ( )
libspice . dp2hx_c ( number , lenout , string , ctypes . byref ( length ) )
return stypes . toPythonString ( string ) |
def main ( ) :
"""Keywords generator command line""" | parser = argparse . ArgumentParser ( description = __doc__ )
parser . add_argument ( 'learn' , help = "learning source codes directory" )
parser . add_argument ( 'keywords' , help = "output keywords file, JSON" )
parser . add_argument ( '-n' , '--nbkeywords' , type = int , default = 10000 , help = "the number of keywor... |
def createalphabet ( alphabetinput = None ) :
"""Creates a sample alphabet containing printable ASCII characters""" | if alphabetinput and os . path . isfile ( alphabetinput ) :
return _load_alphabet ( alphabetinput )
elif alphabetinput :
alpha = [ ]
setlist = alphabetinput . split ( ',' )
for alphaset in setlist :
a = int ( alphaset . split ( '-' ) [ 0 ] )
b = int ( alphaset . split ( '-' ) [ 1 ] )
... |
def create_node ( self , network , participant ) :
"""Make a new node for participants .""" | return self . models . RogersAgent ( network = network , participant = participant ) |
def on_step_end ( self , step , logs = { } ) :
"""Save weights at interval steps during training""" | self . total_steps += 1
if self . total_steps % self . interval != 0 : # Nothing to do .
return
filepath = self . filepath . format ( step = self . total_steps , ** logs )
if self . verbose > 0 :
print ( 'Step {}: saving model to {}' . format ( self . total_steps , filepath ) )
self . model . save_weights ( fil... |
def put_record ( self , data , partition_key = None ) :
"""Add data to the record queue in the proper format .
Parameters
data : str
Data to send .
partition _ key : str
Hash that determines which shard a given data record belongs to .""" | # Byte encode the data
data = encode_data ( data )
# Create a random partition key if not provided
if not partition_key :
partition_key = uuid . uuid4 ( ) . hex
# Build the record
record = { 'Data' : data , 'PartitionKey' : partition_key }
# Flush the queue if it reaches the batch size
if self . queue . qsize ( ) >... |
def _extrac_qtl ( peak , block , headers ) :
"""Given a row containing the peak of the QTL and all the rows of
the linkage group of the said QTL ( splitted per trait ) , determine
the QTL interval and find the start and stop marker of the said
interval .
The interval is a LOD 2 interval .
The approach is ... | qtls = [ ]
if not peak :
return qtls
threshold = 2
for trait in peak :
blockcnt = headers . index ( trait )
local_block = block [ blockcnt ]
lod2_threshold = float ( peak [ trait ] [ - 1 ] ) - float ( threshold )
# Search QTL start
cnt = local_block . index ( peak [ trait ] )
start = local_b... |
def extrapolate_error ( self ) :
"""Estimate the numerical error to be expected when applying all
methods available based on the results of the current and the
last method .
Note that this expolation strategy cannot be applied on the first
method . If the current method is the first one , ` - 999.9 ` is ret... | if self . numvars . idx_method > 2 :
self . numvars . extrapolated_error = modelutils . exp ( modelutils . log ( self . numvars . error ) + ( modelutils . log ( self . numvars . error ) - modelutils . log ( self . numvars . last_error ) ) * ( self . numconsts . nmb_methods - self . numvars . idx_method ) )
else :
... |
def dump ( self , f , name ) :
"""Write the attribute to a file - like object""" | array = self . get ( )
# print the header line
print ( "% 40s kind=%s shape=(%s)" % ( name , array . dtype . kind , "," . join ( [ str ( int ( size_axis ) ) for size_axis in array . shape ] ) , ) , file = f )
# print the numbers
counter = 0
for value in array . flat :
counter += 1
print ( "% 20s" % value , en... |
def _disable_access_key ( self , force_disable_self = False ) :
"""This function first checks to see if the key is already disabled
if not then it goes to disabling""" | client = self . client
if self . validate is True :
return
else :
try :
client . update_access_key ( UserName = self . _search_user_for_key ( ) , AccessKeyId = self . access_key_id , Status = 'Inactive' )
logger . info ( "Access key {id} has " "been disabled." . format ( id = self . access_key_i... |
def entity_delete ( args ) :
"""Delete entity in a workspace .""" | msg = "WARNING: this will delete {0} {1} in {2}/{3}" . format ( args . entity_type , args . entity , args . project , args . workspace )
if not ( args . yes or _confirm_prompt ( msg ) ) :
return
json_body = [ { "entityType" : args . entity_type , "entityName" : args . entity } ]
r = fapi . delete_entities ( args . ... |
def merge ( a , b , op = None , recurse_list = False , max_depth = None ) :
"""Immutable merge ` ` a ` ` structure with ` ` b ` ` using binary operator ` ` op ` `
on leaf nodes . All nodes at , or below , ` ` max _ depth ` ` are considered to be
leaf nodes .
Merged structure is returned , input data structure... | if op is None :
op = operator . add
if max_depth is not None :
if max_depth < 1 :
return op ( a , b )
else :
max_depth -= 1
if isinstance ( a , dict ) and isinstance ( b , dict ) :
result = { }
for key in set ( chain ( a . keys ( ) , b . keys ( ) ) ) :
if key in a and key in ... |
def _inputrc_enables_vi_mode ( ) :
'''Emulate a small bit of readline behavior .
Returns :
( bool ) True if current user enabled vi mode ( " set editing - mode vi " ) in . inputrc''' | for filepath in ( os . path . expanduser ( '~/.inputrc' ) , '/etc/inputrc' ) :
try :
with open ( filepath ) as f :
for line in f :
if _setre . fullmatch ( line ) :
return True
except IOError :
continue
return False |
def as_labeller ( x , default = label_value , multi_line = True ) :
"""Coerse to labeller function
Parameters
x : function | dict
Object to coerce
default : function | str
Default labeller . If it is a string ,
it should be the name of one the labelling
functions provided by plotnine .
multi _ line ... | if x is None :
x = default
# One of the labelling functions as string
with suppress ( KeyError , TypeError ) :
x = LABELLERS [ x ]
# x is a labeller
with suppress ( AttributeError ) :
if x . __name__ == '_labeller' :
return x
def _labeller ( label_info ) :
label_info = pd . Series ( label_info )... |
def delete_api_integration_response ( restApiId , resourcePath , httpMethod , statusCode , region = None , key = None , keyid = None , profile = None ) :
'''Deletes an integration response for a given method in a given API
CLI Example :
. . code - block : : bash
salt myminion boto _ apigateway . delete _ api ... | try :
resource = describe_api_resource ( restApiId , resourcePath , region = region , key = key , keyid = keyid , profile = profile ) . get ( 'resource' )
if resource :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
conn . delete_integration_response ( restA... |
def get_response ( self , path , ** params ) :
"""Giving a service path and optional specific arguments , returns
the response string .""" | url = "%s%s" % ( self . base_url , path )
return self . _get_response ( url , ** params ) |
def reload ( ) :
'''Remove all stopped VMs and reload configuration from the default configuration file .
CLI Example :
. . code - block : : bash
salt ' * ' vmctl . reload''' | ret = False
cmd = 'vmctl reload'
result = __salt__ [ 'cmd.run_all' ] ( cmd , output_loglevel = 'trace' , python_shell = False )
if result [ 'retcode' ] == 0 :
ret = True
else :
raise CommandExecutionError ( 'Problem encountered running vmctl' , info = { 'errors' : [ result [ 'stderr' ] ] , 'changes' : ret } )
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.