signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_assessment_taken_query_session_for_bank ( self , bank_id ) :
"""Gets the ` ` OsidSession ` ` associated with the assessment taken query service for the given bank .
arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the bank
return : ( osid . assessment . AssessmentTakenQuerySession ) - an
` ` Ass... | if not self . supports_assessment_taken_query ( ) :
raise errors . Unimplemented ( )
# Also include check to see if the catalog Id is found otherwise raise errors . NotFound
# pylint : disable = no - member
return sessions . AssessmentTakenQuerySession ( bank_id , runtime = self . _runtime ) |
def check_if_username_exists ( self , username ) :
'''Check if the username handles exists .
: param username : The username , in the form index : prefix / suffix
: raises : : exc : ` ~ b2handle . handleexceptions . HandleNotFoundException `
: raises : : exc : ` ~ b2handle . handleexceptions . GenericHandleEr... | LOGGER . debug ( 'check_if_username_exists...' )
_ , handle = b2handle . utilhandle . remove_index_from_handle ( username )
resp = self . send_handle_get_request ( handle )
resp_content = decoded_response ( resp )
if b2handle . hsresponses . does_handle_exist ( resp ) :
handlerecord_json = json . loads ( resp_conte... |
def compute ( self , x , yerr ) :
"""Compute and factorize the covariance matrix .
Args :
x ( ndarray [ nsamples , ndim ] ) : The independent coordinates of the
data points .
yerr ( ndarray [ nsamples ] or float ) : The Gaussian uncertainties on
the data points at coordinates ` ` x ` ` . These values will... | # Compute the kernel matrix .
K = self . kernel . get_value ( x )
K [ np . diag_indices_from ( K ) ] += yerr ** 2
# Factor the matrix and compute the log - determinant .
self . _factor = ( cholesky ( K , overwrite_a = True , lower = False ) , False )
self . log_determinant = 2 * np . sum ( np . log ( np . diag ( self .... |
def tracked_model_history ( self ) :
"""Returns history of a tracked object""" | from tracked_model . models import History
return History . objects . filter ( table_name = self . _meta . db_table , table_id = self . pk ) |
def parseColors ( colors , defaultColor ) :
"""Parse command line color information .
@ param colors : A C { list } of space separated " value color " strings , such as
[ " 0.9 red " , " 0.75 rgb ( 23 , 190 , 207 ) " , " 0.1 # CF3CF3 " ] .
@ param defaultColor : The C { str } color to use for cells that do no... | result = [ ]
if colors :
for colorInfo in colors :
fields = colorInfo . split ( maxsplit = 1 )
if len ( fields ) == 2 :
threshold , color = fields
try :
threshold = float ( threshold )
except ValueError :
print ( '--color arguments ... |
def asML ( self ) :
"""Convert this matrix to the new mllib - local representation .
This does NOT copy the data ; it copies references .
: return : : py : class : ` pyspark . ml . linalg . DenseMatrix `
. . versionadded : : 2.0.0""" | return newlinalg . DenseMatrix ( self . numRows , self . numCols , self . values , self . isTransposed ) |
def get_central_coors ( self , row , col ) :
"""Get the coordinates of central grid .
Args :
row : row number , range from 0 to ( nRows - 1 ) .
col : col number , range from 0 to ( nCols - 1 ) .
Returns :
XY coordinates . If the row or col are invalid , raise ValueError .""" | if row < 0 or row >= self . nRows or col < 0 or col >= self . nCols :
raise ValueError ( "The row (%d) or col (%d) must be >=0 and less than " "nRows (%d) or nCols (%d)!" % ( row , col , self . nRows , self . nCols ) )
else :
tmpx = self . xMin + ( col + 0.5 ) * self . dx
tmpy = self . yMax - ( row + 0.5 ) ... |
def references_json ( references ) :
'''Given a list of all models in a graph , return JSON representing
them and their properties .
Args :
references ( seq [ Model ] ) :
A list of models to convert to JSON
Returns :
list''' | references_json = [ ]
for r in references :
ref = r . ref
ref [ 'attributes' ] = r . _to_json_like ( include_defaults = False )
references_json . append ( ref )
return references_json |
def open_connection ( self , verbose = False ) :
"""Initializes a new IMAP4 _ SSL connection to an email server .""" | # Connect to server
hostname = self . configs . get ( 'IMAP' , 'hostname' )
if verbose :
print ( 'Connecting to ' + hostname )
connection = imaplib . IMAP4_SSL ( hostname )
# Authenticate
username = self . configs . get ( 'IMAP' , 'username' )
password = self . configs . get ( 'IMAP' , 'password' )
if verbose :
... |
async def requirements ( client : Client , search : str ) -> dict :
"""GET list of requirements for a given UID / Public key
: param client : Client to connect to the api
: param search : UID or public key
: return :""" | return await client . get ( MODULE + '/requirements/%s' % search , schema = REQUIREMENTS_SCHEMA ) |
def hello_world ( test , example , prompts ) :
"""A hello world test phase .""" | test . logger . info ( 'Hello World!' )
test . measurements . widget_type = prompts . prompt ( 'What\'s the widget type? (Hint: try `MyWidget` to PASS)' , text_input = True )
if test . measurements . widget_type == 'raise' :
raise Exception ( )
test . measurements . widget_color = 'Black'
test . measurements . widg... |
def mri_head_reco_op_32_channel ( ) :
"""Reconstruction operator for 32 channel MRI of a head .
This is a T2 weighted TSE scan of a healthy volunteer .
The reconstruction operator is the sum of the modulus of each channel .
See the data source with DOI ` 10.5281 / zenodo . 800527 ` _ or the
` project webpag... | # To get the same rotation as in the reference article
space = odl . uniform_discr ( min_pt = [ - 115.2 , - 115.2 ] , max_pt = [ 115.2 , 115.2 ] , shape = [ 256 , 256 ] , dtype = complex )
trafo = odl . trafos . FourierTransform ( space )
return odl . ReductionOperator ( odl . ComplexModulus ( space ) * trafo . inverse... |
def set_color_mask ( self , red , green , blue , alpha ) :
"""Toggle writing of frame buffer color components
Parameters
red : bool
Red toggle .
green : bool
Green toggle .
blue : bool
Blue toggle .
alpha : bool
Alpha toggle .""" | self . glir . command ( 'FUNC' , 'glColorMask' , bool ( red ) , bool ( green ) , bool ( blue ) , bool ( alpha ) ) |
def tilecache ( self , event , * args , ** kwargs ) :
"""Checks and caches a requested tile to disk , then delivers it to
client""" | request , response = event . args [ : 2 ]
self . log ( request . path , lvl = verbose )
try :
filename , url = self . _split_cache_url ( request . path , 'tilecache' )
except UrlError :
return
# self . log ( ' CACHE QUERY : ' , filename , url )
# Do we have the tile already ?
if os . path . isfile ( filename ) ... |
def get_report ( self ) :
"""Return a string containing a report of the result .
This can used to print or save to a text file .
Returns :
str : String containing infos about the result""" | lines = [ super ( InvalidUtterancesResult , self ) . get_report ( ) ]
if len ( self . invalid_utterances ) > 0 :
lines . append ( '\nInvalid utterances:' )
sorted_items = sorted ( self . invalid_utterances . items ( ) , key = lambda x : x [ 0 ] )
lines . extend ( [ ' * {} ({})' . format ( x , y ) for x ,... |
def patch ( self , patch ) :
"""Given a ParsedNodePatch , add the new information to the node .""" | # explicitly pick out the parts to update so we don ' t inadvertently
# step on the model name or anything
self . _contents . update ( { 'patch_path' : patch . original_file_path , 'description' : patch . description , 'columns' : patch . columns , 'docrefs' : patch . docrefs , } )
# patches always trigger re - validat... |
def getvariable ( name ) :
"""Get the value of a local variable somewhere in the call stack .""" | import inspect
fr = inspect . currentframe ( )
try :
while fr :
fr = fr . f_back
vars = fr . f_locals
if name in vars :
return vars [ name ]
except :
pass
return None |
def extend ( self , iter , parent = None ) :
"""Add a sequence of items to the end of the list
: param iter : The iterable of items to add .
: param parent : The node to add the items as a child of , or None for
top - level nodes .""" | for item in iter :
self . append ( item , parent ) |
def get_relavent_flags ( self ) :
'''Retrieves the relevant flags for this data block .
Returns :
All flags related to this block .''' | relavent_flags = { }
for code , flags_list in self . flags . items ( ) :
relavent_flags [ code ] = [ ]
for flag in flags_list :
if self . flag_is_related ( flag ) :
relavent_flags [ code ] . append ( flag )
# Remove that flag level if no error exists
if not relavent_flags [ code ] :
... |
def pairs ( args ) :
"""See _ _ doc _ _ for OptionParser . set _ pairs ( ) .""" | import jcvi . formats . bed
p = OptionParser ( pairs . __doc__ )
p . set_pairs ( )
opts , targs = p . parse_args ( args )
if len ( targs ) != 1 :
sys . exit ( not p . print_help ( ) )
samfile , = targs
bedfile = samfile . rsplit ( "." , 1 ) [ 0 ] + ".bed"
if need_update ( samfile , bedfile ) :
cmd = "bamToBed -... |
def get_permissions_app_name ( ) :
"""Gets the app after which smartmin permissions should be installed . This can be specified by PERMISSIONS _ APP in the
Django settings or defaults to the last app with models""" | global permissions_app_name
if not permissions_app_name :
permissions_app_name = getattr ( settings , 'PERMISSIONS_APP' , None )
if not permissions_app_name :
app_names_with_models = [ a . name for a in apps . get_app_configs ( ) if a . models_module is not None ]
if app_names_with_models :
... |
def to_css ( self ) :
'''Generate the CSS representation of this HSL color .
Returns :
str , ` ` " hsl ( . . . ) " ` ` or ` ` " hsla ( . . . ) " ` `''' | if self . a == 1.0 :
return "hsl(%d, %s%%, %s%%)" % ( self . h , self . s * 100 , self . l * 100 )
else :
return "hsla(%d, %s%%, %s%%, %s)" % ( self . h , self . s * 100 , self . l * 100 , self . a ) |
def _buildItem ( self , elem , cls = None , initpath = None ) :
"""Factory function to build objects based on registered PLEXOBJECTS .""" | # cls is specified , build the object and return
initpath = initpath or self . _initpath
if cls is not None :
return cls ( self . _server , elem , initpath )
# cls is not specified , try looking it up in PLEXOBJECTS
etype = elem . attrib . get ( 'type' , elem . attrib . get ( 'streamType' ) )
ehash = '%s.%s' % ( el... |
def delete_state ( key , namespace = None , table_name = None , environment = None , layer = None , stage = None , shard_id = None , consistent = True , wait_exponential_multiplier = 500 , wait_exponential_max = 5000 , stop_max_delay = 10000 ) :
"""Delete Lambda state value .""" | if table_name is None :
table_name = _state_table_name ( environment = environment , layer = layer , stage = stage )
if not table_name :
msg = ( "Can't produce state table name: unable to set state " "item '{}'" . format ( key ) )
logger . error ( msg )
raise StateTableError ( msg )
return
dynamodb ... |
def _create_token_set ( self ) :
"""Creates a token set of all tokens in the index using ` lunr . TokenSet `""" | self . token_set = TokenSet . from_list ( sorted ( list ( self . inverted_index . keys ( ) ) ) ) |
def pckw02 ( handle , classid , frname , first , last , segid , intlen , n , polydg , cdata , btime ) :
"""Write a type 2 segment to a PCK binary file given the file handle ,
frame class ID , base frame , time range covered by the segment , and
the Chebyshev polynomial coefficients .
https : / / naif . jpl . ... | handle = ctypes . c_int ( handle )
classid = ctypes . c_int ( classid )
frame = stypes . stringToCharP ( frname )
first = ctypes . c_double ( first )
last = ctypes . c_double ( last )
segid = stypes . stringToCharP ( segid )
intlen = ctypes . c_double ( intlen )
n = ctypes . c_int ( n )
polydg = ctypes . c_int ( polydg... |
def modprobe ( module , persist = True ) :
"""Load a kernel module and configure for auto - load on reboot .""" | cmd = [ 'modprobe' , module ]
log ( 'Loading kernel module %s' % module , level = INFO )
subprocess . check_call ( cmd )
if persist :
persistent_modprobe ( module ) |
def n_jobs ( self ) :
"""Returns number of jobs / threads to use during assignment of data .
Returns
If None it will return the setting of ' PYEMMA _ NJOBS ' or
' SLURM _ CPUS _ ON _ NODE ' environment variable . If none of these environment variables exist ,
the number of processors / or cores is returned ... | if not hasattr ( self , '_n_jobs' ) :
self . _n_jobs = get_n_jobs ( logger = getattr ( self , 'logger' ) )
return self . _n_jobs |
def saveHdlFiles ( self , srcDir ) :
""": param srcDir : dir name where dir with HDL files should be stored""" | path = os . path . join ( srcDir , self . name )
try :
os . makedirs ( path )
except OSError : # wipe if exists
shutil . rmtree ( path )
os . makedirs ( path )
files = self . hdlFiles
self . hdlFiles = self . toHdlConversion ( self . top , self . name , path )
for srcF in files :
dst = os . path . join ... |
def nonlinear_odr ( x , y , dx , dy , func , params_init , ** kwargs ) :
"""Perform a non - linear orthogonal distance regression , return the results as
ErrorValue ( ) instances .
Inputs :
x : one - dimensional numpy array of the independent variable
y : one - dimensional numpy array of the dependent varia... | odrmodel = odr . Model ( lambda pars , x : func ( x , * pars ) )
if dx is not None : # treat non - finite values as fixed
xfixed = np . isfinite ( dx )
else :
xfixed = None
odrdata = odr . RealData ( x , y , sx = dx , sy = dy , fix = xfixed )
odrodr = odr . ODR ( odrdata , odrmodel , params_init , ifixb = [ not... |
def get_team_scores ( self , team , time , show_upcoming , use_12_hour_format ) :
"""Queries the API and gets the particular team scores""" | team_id = self . team_names . get ( team , None )
time_frame = 'n' if show_upcoming else 'p'
if team_id :
try :
req = self . _get ( 'teams/{team_id}/matches?timeFrame={time_frame}{time}' . format ( team_id = team_id , time_frame = time_frame , time = time ) )
team_scores = req . json ( )
if ... |
def eventFilter ( self , widget , event ) :
"""Event filter for search _ text widget .
Emits signals when presing Enter and Shift + Enter .
This signals are used for search forward and backward .
Also , a crude hack to get tab working in the Find / Replace boxes .""" | if event . type ( ) == QEvent . KeyPress :
key = event . key ( )
shift = event . modifiers ( ) & Qt . ShiftModifier
if key == Qt . Key_Return :
if shift :
self . return_shift_pressed . emit ( )
else :
self . return_pressed . emit ( )
if key == Qt . Key_Tab :
... |
def _check_load_paths ( load_path ) :
'''Checks the validity of the load _ path , returns a sanitized version
with invalid paths removed .''' | if load_path is None or not isinstance ( load_path , six . string_types ) :
return None
_paths = [ ]
for _path in load_path . split ( ':' ) :
if os . path . isabs ( _path ) and os . path . isdir ( _path ) :
_paths . append ( _path )
else :
log . info ( 'Invalid augeas_cfg load_path entry: %s... |
def _build_replay_buffer ( self , use_staging ) :
"""Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer .""" | replay_buffer_kwargs = dict ( observation_shape = dqn_agent . NATURE_DQN_OBSERVATION_SHAPE , stack_size = dqn_agent . NATURE_DQN_STACK_SIZE , replay_capacity = self . _replay_capacity , batch_size = self . _buffer_batch_size , update_horizon = self . update_horizon , gamma = self . gamma , extra_storage_types = None , ... |
def place ( self , reverse_pipe , seqs_list , resolve_placements , files , args , slash_endings , tax_descr , clusterer ) :
'''placement - This is the placement pipeline in GraftM , in aligned reads
are placed into phylogenetic trees , and the results interpreted .
If reverse reads are used , this is where the ... | trusted_placements = { }
files_to_delete = [ ]
# Merge the alignments so they can all be placed at once .
alias_hash = self . alignment_merger ( seqs_list , files . comb_aln_fa ( ) )
files_to_delete += seqs_list
files_to_delete . append ( files . comb_aln_fa ( ) )
if os . path . getsize ( files . comb_aln_fa ( ) ) == 0... |
def deepest_node ( ( subj , pred , obj ) , graph ) :
"""recurse down the tree and return a list of the most deeply nested
child nodes of the given triple""" | # i don ' t fully accept the premise that this docstring presents
# i ' m not a docstring literalist
to_return = [ ]
def _deepest_node ( ( subj , pred , obj ) , graph ) :
children = [ ]
if isinstance ( obj , rt . BNode ) :
for s , p , o in graph :
if str ( s ) == str ( obj ) :
... |
def compute_full_connections ( self , config , direct ) :
"""Compute connections for a fully - connected feed - forward genome - - each
input connected to all hidden nodes
( and output nodes if ` ` direct ` ` is set or there are no hidden nodes ) ,
each hidden node connected to all output nodes .
( Recurren... | hidden = [ i for i in iterkeys ( self . nodes ) if i not in config . output_keys ]
output = [ i for i in iterkeys ( self . nodes ) if i in config . output_keys ]
connections = [ ]
if hidden :
for input_id in config . input_keys :
for h in hidden :
connections . append ( ( input_id , h ) )
fo... |
def get_all_permissions ( self ) :
"""Returns a set of tuples with the perm name and view menu name""" | perms = set ( )
for role in self . get_user_roles ( ) :
for perm_view in role . permissions :
t = ( perm_view . permission . name , perm_view . view_menu . name )
perms . add ( t )
return perms |
def ensure_lockfile ( keep_outdated = False , pypi_mirror = None ) :
"""Ensures that the lockfile is up - to - date .""" | if not keep_outdated :
keep_outdated = project . settings . get ( "keep_outdated" )
# Write out the lockfile if it doesn ' t exist , but not if the Pipfile is being ignored
if project . lockfile_exists :
old_hash = project . get_lockfile_hash ( )
new_hash = project . calculate_pipfile_hash ( )
if new_ha... |
def _replace_placeholder ( sql_statement , variable ) :
"""Return the string obtained by replacing the specified placeholders by
its corresponding value .
@ param sql _ statement : the string expression of a SQL statement to
replace placeholders with their corresponding values .
@ param variable : the varia... | ( variable_name , variable_type , variable_value ) = variable
sql_value = RdbmsConnection . _expand_placeholder_value ( variable_value ) if variable_type == PlaceholderType . simple_list else ',' . join ( [ '(%s)' % RdbmsConnection . _expand_placeholder_value ( v ) for v in variable_value ] )
return re . sub ( PATTERN_... |
def assign_to ( self , obj ) :
"""Assign ` x ` and ` y ` to an object that has properties ` x ` and ` y ` .""" | obj . x = self . x
obj . y = self . y |
def hist_frame ( data , column = None , by = None , grid = True , xlabelsize = None , xrot = None , ylabelsize = None , yrot = None , ax = None , sharex = False , sharey = False , figsize = None , layout = None , bins = 10 , ** kwds ) :
"""Make a histogram of the DataFrame ' s .
A ` histogram ` _ is a representat... | _raise_if_no_mpl ( )
_converter . _WARN = False
if by is not None :
axes = grouped_hist ( data , column = column , by = by , ax = ax , grid = grid , figsize = figsize , sharex = sharex , sharey = sharey , layout = layout , bins = bins , xlabelsize = xlabelsize , xrot = xrot , ylabelsize = ylabelsize , yrot = yrot ,... |
def get_file_extension ( filepath ) :
"""Copy if anyconfig . utils . get _ file _ extension is not available .
> > > get _ file _ extension ( " / a / b / c " )
> > > get _ file _ extension ( " / a / b . txt " )
' txt '
> > > get _ file _ extension ( " / a / b / c . tar . xz " )
' xz '""" | _ext = os . path . splitext ( filepath ) [ - 1 ]
if _ext :
return _ext [ 1 : ] if _ext . startswith ( '.' ) else _ext
return '' |
def coordinate ( self ) :
"""Returns the maven coordinate of this jar .
: rtype : : class : ` pants . java . jar . M2Coordinate `""" | return M2Coordinate ( org = self . org , name = self . name , rev = self . rev , classifier = self . classifier , ext = self . ext ) |
def color_percentages ( file_list , n_tasks = 9 , file_name = "color_percent.png" , intensification_factor = 1.2 ) :
"""Creates an image in which each cell in the avida grid is represented as
a square of 9 sub - cells . Each of these 9 sub - cells represents a different
task , and is colored such that cooler co... | # Load data
data = task_percentages ( load_grid_data ( file_list ) )
# Initialize grid
grid = [ [ ] ] * len ( data ) * 3
for i in range ( len ( grid ) ) :
grid [ i ] = [ [ ] ] * len ( data [ 0 ] ) * 3
# Color grid
for i in range ( len ( data ) ) :
for j in range ( len ( data [ i ] ) ) :
for k in range (... |
def get_parent_catalog_ids ( self , catalog_id ) :
"""Gets the parent ` ` Ids ` ` of the given catalog .
arg : catalog _ id ( osid . id . Id ) : a catalog ` ` Id ` `
return : ( osid . id . IdList ) - the parent ` ` Ids ` ` of the catalog
raise : NotFound - ` ` catalog _ id ` ` is not found
raise : NullArgum... | # Implemented from template for
# osid . resource . BinHierarchySession . get _ parent _ bin _ ids
if self . _catalog_session is not None :
return self . _catalog_session . get_parent_catalog_ids ( catalog_id = catalog_id )
return self . _hierarchy_session . get_parents ( id_ = catalog_id ) |
def setup ( config_root = '' ) :
"""Service configuration and logging setup .
Configuration defined in ` ` gordon - janitor - user . toml ` ` will overwrite
` ` gordon - janitor . toml ` ` .
Args :
config _ root ( str ) : where configuration should load from ,
defaults to current working directory .
Ret... | config = _load_config ( root = config_root )
logging_config = config . get ( 'core' , { } ) . get ( 'logging' , { } )
log_level = logging_config . get ( 'level' , 'INFO' ) . upper ( )
log_handlers = logging_config . get ( 'handlers' ) or [ 'syslog' ]
ulogger . setup_logging ( progname = 'gordon-janitor' , level = log_l... |
def get_charset ( message , default = "utf-8" ) :
"""Get the message charset""" | if message . get_content_charset ( ) :
return message . get_content_charset ( )
if message . get_charset ( ) :
return message . get_charset ( )
return default |
def convert_serializer_field ( field , is_input = True ) :
"""Converts a django rest frameworks field to a graphql field
and marks the field as required if we are creating an input type
and the field itself is required""" | graphql_type = get_graphene_type_from_serializer_field ( field )
args = [ ]
kwargs = { "description" : field . help_text , "required" : is_input and field . required }
# if it is a tuple or a list it means that we are returning
# the graphql type and the child type
if isinstance ( graphql_type , ( list , tuple ) ) :
... |
def getSKOSDirectSubs ( self , aURI ) :
"""2015-08-19 : currenlty not used , inferred from above""" | aURI = aURI
qres = self . rdflib_graph . query ( """SELECT DISTINCT ?x
WHERE {
{
{ ?x skos:broader <%s> }
UNION
{ <%s> skos:narrower ?s }
}
FILTE... |
def CreateMuskingumXFileFromDranageLine ( in_drainage_line , x_id , out_x_file , file_geodatabase = None ) :
"""Create muskingum X file from drainage line .
Parameters
in _ drainage _ line : str
Path to the stream network ( i . e . Drainage Line ) shapefile .
x _ id : str
The name of the muksingum X field... | ogr_drainage_line_shapefile_lyr , ogr_drainage_line_shapefile = open_shapefile ( in_drainage_line , file_geodatabase )
with open_csv ( out_x_file , 'w' ) as kfile :
x_writer = csv_writer ( kfile )
for drainage_line_feature in ogr_drainage_line_shapefile_lyr :
x_writer . writerow ( [ drainage_line_featur... |
def new ( cls , pic_id , filename , rId , cx , cy ) :
"""Return a new ` ` < pic : pic > ` ` element populated with the minimal
contents required to define a viable picture element , based on the
values passed as parameters .""" | pic = parse_xml ( cls . _pic_xml ( ) )
pic . nvPicPr . cNvPr . id = pic_id
pic . nvPicPr . cNvPr . name = filename
pic . blipFill . blip . embed = rId
pic . spPr . cx = cx
pic . spPr . cy = cy
return pic |
def get_user_profile_photos ( user_id , offset = None , limit = None , ** kwargs ) :
"""Use this method to get a list of profile pictures for a user . Returns a UserProfilePhotos object .
: param user _ id : Unique identifier of the target user
: param offset : Sequential number of the first photo to be returne... | # required args
params = dict ( user_id = user_id )
# optional args
params . update ( _clean_params ( offset = offset , limit = limit ) )
return TelegramBotRPCRequest ( 'getUserProfilePhotos' , params = params , on_result = UserProfilePhotos . from_result , ** kwargs ) |
def merge_dict ( a , b , path = None ) :
"""Merge dict b into a""" | if not path :
path = [ ]
for key in b :
if key in a :
if isinstance ( a [ key ] , dict ) and isinstance ( b [ key ] , dict ) :
merge_dict ( a [ key ] , b [ key ] , path + [ str ( key ) ] )
else :
continue
else :
a [ key ] = b [ key ]
return a |
def cpustats ( ) :
'''Return information about the CPU .
Returns
dict : A dictionary containing information about the CPU stats
CLI Example :
. . code - block : : bash
salt * status . cpustats''' | # Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there ' s a lot of overhead
# Time related info
user , system , idle , interrupt , dpc = psutil . cpu_times ( )
cpu = { 'user' : user , 'system' : system , 'idle' : idle , 'irq' : interrupt , 'dpc' : dpc }
# Count related inf... |
def get_plugins ( cls ) :
"""Returns all plugin instances of plugin point , passing all args and
kwargs to plugin constructor .""" | # Django > = 1.9 changed something with the migration logic causing
# plugins to be executed before the corresponding database tables
# exist . This method will only return something if the database
# tables have already been created .
# XXX : I don ' t fully understand the issue and there should be
# another way but t... |
def seconds2str ( seconds ) :
"""Returns string such as 1h 05m 55s .""" | if seconds < 0 :
return "{0:.3g}s" . format ( seconds )
elif math . isnan ( seconds ) :
return "NaN"
elif math . isinf ( seconds ) :
return "Inf"
m , s = divmod ( seconds , 60 )
h , m = divmod ( m , 60 )
if h >= 1 :
return "{0:g}h {1:02g}m {2:.3g}s" . format ( h , m , s )
elif m >= 1 :
return "{0:02... |
def play_mode ( self , playmode ) :
"""Set the speaker ' s mode .""" | playmode = playmode . upper ( )
if playmode not in PLAY_MODES . keys ( ) :
raise KeyError ( "'%s' is not a valid play mode" % playmode )
self . avTransport . SetPlayMode ( [ ( 'InstanceID' , 0 ) , ( 'NewPlayMode' , playmode ) ] ) |
def tag ( self , repository , tag = None , ** kwargs ) :
"""Tag this image into a repository . Similar to the ` ` docker tag ` `
command .
Args :
repository ( str ) : The repository to set for the tag
tag ( str ) : The tag name
force ( bool ) : Force
Raises :
: py : class : ` docker . errors . APIErro... | return self . client . api . tag ( self . id , repository , tag = tag , ** kwargs ) |
def gen_binary_files_from_urls ( urls : Iterable [ str ] , on_disk : bool = False , show_info : bool = True ) -> Generator [ BinaryIO , None , None ] :
"""Generate binary files from a series of URLs ( one per URL ) .
Args :
urls : iterable of URLs
on _ disk : if ` ` True ` ` , yields files that are on disk ( ... | for url in urls :
if on_disk : # Necessary for e . g . zip processing ( random access )
with tempfile . TemporaryDirectory ( ) as tmpdir :
filename = os . path . join ( tmpdir , "tempfile" )
download ( url = url , filename = filename )
with open ( filename , 'rb' ) as f :... |
def from_hdf5 ( cls , f ) :
"""Load an object from an HDF5 file .
Requires ` ` h5py ` ` .
Parameters
f : str , : class : ` h5py . File `
Either the filename or an open HDF5 file .""" | # TODO : this is duplicated code from PhaseSpacePosition
if isinstance ( f , str ) :
import h5py
f = h5py . File ( f )
pos = quantity_from_hdf5 ( f [ 'pos' ] )
vel = quantity_from_hdf5 ( f [ 'vel' ] )
time = None
if 'time' in f :
time = quantity_from_hdf5 ( f [ 'time' ] )
frame = None
if 'frame' in f :
... |
def _map_table_name ( self , model_names ) :
"""Pre foregin _ keys potrbejeme pre z nazvu tabulky zistit class ,
tak si to namapujme""" | for model in model_names :
if isinstance ( model , tuple ) :
model = model [ 0 ]
try :
model_cls = getattr ( self . models , model )
self . table_to_class [ class_mapper ( model_cls ) . tables [ 0 ] . name ] = model
except AttributeError :
pass |
def verify_weave_options ( opt , parser ) :
"""Parses the CLI options , verifies that they are consistent and
reasonable , and acts on them if they are
Parameters
opt : object
Result of parsing the CLI with OptionParser , or any object with the
required attributes
parser : object
OptionParser instance... | # PYTHONCOMPILED is initially set in pycbc . _ _ init _ _
cache_dir = os . environ [ 'PYTHONCOMPILED' ]
# Check whether to use a fixed directory for weave
if opt . fixed_weave_cache :
if os . environ . get ( "FIXED_WEAVE_CACHE" , None ) :
cache_dir = os . environ [ "FIXED_WEAVE_CACHE" ]
elif getattr ( s... |
def _wait_if_required ( self , container_state , next_child_state_to_execute , woke_up_from_pause_or_step_mode ) :
"""Calls a blocking wait for the calling thread , depending on the execution mode .
: param container _ state : the current hierarhcy state to handle the execution mode for
: param next _ child _ s... | wait = True
# if there is a state in self . run _ to _ states then RAFCON was commanded
# a ) a step _ over
# b ) a step _ out
# c ) a run _ until
for state_path in copy . deepcopy ( self . run_to_states ) :
next_child_state_path = None
# can be None in case of no transition given
if next_child_state_to_exe... |
def scale ( self , image , size , crop , options ) :
"""Wrapper for ` ` engine _ scale ` ` , checks if the scaling factor is below one or that scale _ up
option is set to True before calling ` ` engine _ scale ` ` .
: param image :
: param size :
: param crop :
: param options :
: return :""" | original_size = self . get_image_size ( image )
factor = self . _calculate_scaling_factor ( original_size , size , crop is not None )
if factor < 1 or options [ 'scale_up' ] :
width = int ( original_size [ 0 ] * factor )
height = int ( original_size [ 1 ] * factor )
image = self . engine_scale ( image , wid... |
def violations ( self , src_path ) :
"""Return a list of Violations recorded in ` src _ path ` .""" | if not any ( src_path . endswith ( ext ) for ext in self . driver . supported_extensions ) :
return [ ]
if src_path not in self . violations_dict :
if self . reports :
self . violations_dict = self . driver . parse_reports ( self . reports )
else :
if self . driver_tool_installed is None :
... |
def effects ( self , cursor = None , order = 'asc' , limit = 10 , sse = False ) :
"""This endpoint represents all effects .
` GET / effects { ? cursor , limit , order }
< https : / / www . stellar . org / developers / horizon / reference / endpoints / effects - all . html > ` _
: param cursor : A paging token... | endpoint = '/effects'
params = self . __query_params ( cursor = cursor , order = order , limit = limit )
return self . query ( endpoint , params , sse ) |
def set_custom_predict_fn ( self , predict_fn ) :
"""Sets a custom function for inference .
Instead of using TF Serving to host a model for WIT to query , WIT can
directly use a custom function as the model to query . In this case , the
provided function should accept example protos and return :
- For class... | # If estimator is set , remove it before setting predict _ fn
self . delete ( 'estimator_and_spec' )
self . store ( 'custom_predict_fn' , predict_fn )
self . set_inference_address ( 'custom_predict_fn' )
# If no model name has been set , give a default
if not self . has_model_name ( ) :
self . set_model_name ( '1' ... |
def assertFileSizeEqual ( self , filename , size , msg = None ) :
'''Fail if ` ` filename ` ` does not have the given ` ` size ` ` as
determined by the ' = = ' operator .
Parameters
filename : str , bytes , file - like
size : int , float
msg : str
If not provided , the : mod : ` marbles . mixins ` or
... | fsize = self . _get_file_size ( filename )
self . assertEqual ( fsize , size , msg = msg ) |
def pseudo_peripheral_node ( A ) :
"""Find a pseudo peripheral node .
Parameters
A : sparse matrix
Sparse matrix
Returns
x : int
Locaiton of the node
order : array
BFS ordering
level : array
BFS levels
Notes
Algorithm in Saad""" | from pyamg . graph import breadth_first_search
n = A . shape [ 0 ]
valence = np . diff ( A . indptr )
# select an initial node x , set delta = 0
x = int ( np . random . rand ( ) * n )
delta = 0
while True : # do a level - set traversal from x
order , level = breadth_first_search ( A , x )
# select a node y in t... |
def _get_block_storage ( kwargs ) :
'''Construct a block storage instance from passed arguments''' | if kwargs is None :
kwargs = { }
block_storage_name = kwargs . get ( 'name' , None )
block_storage_size = kwargs . get ( 'size' , None )
block_storage_description = kwargs . get ( 'description' , None )
datacenter_id = kwargs . get ( 'datacenter_id' , None )
server_id = kwargs . get ( 'server_id' , None )
block_sto... |
def get_quota_history ( self , ** kwargs ) :
"""Get quota usage history""" | kwargs = self . _verify_sort_options ( kwargs )
kwargs = self . _verify_filters ( kwargs , ServicePackage )
api = self . _get_api ( billing . DefaultApi )
return PaginatedResponse ( api . get_service_package_quota_history , lwrap_type = QuotaHistory , ** kwargs ) |
def get_user ( self , key = None ) :
'''Get user information from the server and update the attribute
Args :
keyuser key ( default : me )
return ( status code for the get request , dict user data )''' | if key :
uri = self . api_uri + "/users/" + key
else :
uri = self . api_uri + "/users/me"
return self . _req ( 'get' , uri ) |
def histogram2d ( data1 , data2 , bins = 10 , * args , ** kwargs ) :
"""Facade function to create 2D histograms .
For implementation and parameters , see histogramdd .
This function is also aliased as " h2 " .
Returns
physt . histogram _ nd . Histogram2D
See Also
numpy . histogram2d
histogramdd""" | import numpy as np
# guess axis names
if "axis_names" not in kwargs :
if hasattr ( data1 , "name" ) and hasattr ( data2 , "name" ) :
kwargs [ "axis_names" ] = [ data1 . name , data2 . name ]
if data1 is not None and data2 is not None :
data1 = np . asarray ( data1 )
data2 = np . asarray ( data2 )
... |
def indent ( text , n = 2 , ch = " " ) :
'''Indent all the lines in a given block of text by a specified amount .
Args :
text ( str ) :
The text to indent
n ( int , optional ) :
The amount to indent each line by ( default : 2)
ch ( char , optional ) :
What character to fill the indentation with ( defa... | padding = ch * n
return "\n" . join ( padding + line for line in text . split ( "\n" ) ) |
def bestscore ( self , seq , fwd = '' ) :
"""m . bestscore ( seq , fwd = ' ' ) - - Returns the score of the best matching subsequence in seq .""" | matches , endpoints , scores = self . _scan ( seq , threshold = - 100000 , forw_only = fwd )
if scores :
return max ( scores )
else :
return - 1000 |
def _qr_factor_packed ( a , enorm , finfo ) :
"""Compute the packed pivoting Q - R factorization of a matrix .
Parameters :
a - An n - by - m matrix , m > = n . This will be * overwritten *
by this function as described below !
enorm - A Euclidian - norm - computing function .
finfo - A Numpy finfo object... | machep = finfo . eps
n , m = a . shape
if m < n :
raise ValueError ( '"a" must be at least as tall as it is wide' )
acnorm = np . empty ( n , finfo . dtype )
for j in range ( n ) :
acnorm [ j ] = enorm ( a [ j ] , finfo )
rdiag = acnorm . copy ( )
wa = acnorm . copy ( )
pmut = np . arange ( n )
for i in range (... |
def _set_system_config ( self , v , load = False ) :
"""Setter method for system _ config , mapped from YANG variable / system _ config ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ system _ config is considered as a private
method . Backends looking t... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = system_config . system_config , is_container = 'container' , presence = False , yang_name = "system-config" , rest_name = "system" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , regist... |
def mask_to_n_loudest_clustered_events ( self , n_loudest = 10 , ranking_statistic = "newsnr" , cluster_window = 10 ) :
"""Edits the mask property of the class to point to the N loudest
single detector events as ranked by ranking statistic . Events are
clustered so that no more than 1 event within + / - cluster... | # If this becomes memory intensive we can optimize
stat_instance = sngl_statistic_dict [ ranking_statistic ] ( [ ] )
stat = stat_instance . single ( self . trigs ) [ self . mask ]
# Used for naming in plots . . . Seems an odd place for this to live !
if ranking_statistic == "newsnr" :
self . stat_name = "Reweighted... |
def check_entitlement ( doi ) :
"""Check whether IP and credentials enable access to content for a doi .
This function uses the entitlement endpoint of the Elsevier API to check
whether an article is available to a given institution . Note that this
feature of the API is itself not available for all instituti... | if doi . lower ( ) . startswith ( 'doi:' ) :
doi = doi [ 4 : ]
url = '%s/%s' % ( elsevier_entitlement_url , doi )
params = { 'httpAccept' : 'text/xml' }
res = requests . get ( url , params , headers = ELSEVIER_KEYS )
if not res . status_code == 200 :
logger . error ( 'Could not check entitlements for article %s... |
def query_by_bucket ( cls , bucket ) :
"""Query all uncompleted multipart uploads .""" | return cls . query . filter ( cls . bucket_id == as_bucket_id ( bucket ) ) |
def cli ( ctx , board , fpga , pack , type , size , project_dir , verbose , verbose_yosys , verbose_arachne ) :
"""Bitstream timing analysis .""" | # Run scons
exit_code = SCons ( project_dir ) . time ( { 'board' : board , 'fpga' : fpga , 'size' : size , 'type' : type , 'pack' : pack , 'verbose' : { 'all' : verbose , 'yosys' : verbose_yosys , 'arachne' : verbose_arachne } } )
ctx . exit ( exit_code ) |
def sap_sid_nr ( broker ) :
"""Get the SID and Instance Number
Typical output of saphostctrl _ listinstances : :
# / usr / sap / hostctrl / exe / saphostctrl - function ListInstances
Inst Info : SR1 - 01 - liuxc - rhel7 - hana - ent - 749 , patch 418 , changelist 1816226
Returns :
( list ) : List of tuple... | insts = broker [ DefaultSpecs . saphostctrl_listinstances ] . content
hn = broker [ DefaultSpecs . hostname ] . content [ 0 ] . split ( '.' ) [ 0 ] . strip ( )
results = set ( )
for ins in insts :
ins_splits = ins . split ( ' - ' )
# Local Instance
if ins_splits [ 2 ] . strip ( ) == hn : # ( sid , nr )
... |
def _update_text_record ( self , witness , text_id ) :
"""Updates the record with ` text _ id ` with ` witness ` \' s checksum and
token count .
: param withness : witness to update from
: type witness : ` WitnessText `
: param text _ id : database ID of Text record
: type text _ id : ` int `""" | checksum = witness . get_checksum ( )
token_count = len ( witness . get_tokens ( ) )
with self . _conn :
self . _conn . execute ( constants . UPDATE_TEXT_SQL , [ checksum , token_count , text_id ] ) |
def render ( value , ** kwargs ) :
"""Use Jinja2 rendering for given text an key key / values .
Args :
value ( str ) : the template to be rendered .
kwargs ( dict ) : named parameters representing available variables
inside the template .
> > > model = { " message " : " hello world 1 ! " }
> > > rendere... | try :
environment = Environment ( autoescape = False )
# nosec
environment . filters [ 'render' ] = render
environment . filters [ 'docker_environment' ] = docker_environment
environment . filters [ 'find_matrix' ] = find_matrix
environment . filters [ 'find_stages' ] = find_stages
template ... |
def __get_lookup ( in_fn , selected_type = None ) :
"""Determine which lookup func to use based on inpt files and type option .""" | lookup_func = None
if selected_type is not None :
lookup_func = get_lookup_by_filetype ( selected_type )
else :
extension = os . path . splitext ( in_fn ) [ 1 ]
lookup_func = get_lookup_by_file_extension ( extension )
assert ( lookup_func is not None )
return lookup_func |
def filter_and_save ( raw , symbol_ids , destination_path ) :
"""Parameters
raw : dict
with key ' handwriting _ datasets '
symbol _ ids : dict
Maps LaTeX to write - math . com id
destination _ path : str
Path where the filtered dict ' raw ' will be saved""" | logging . info ( 'Start filtering...' )
new_hw_ds = [ ]
for el in raw [ 'handwriting_datasets' ] :
if el [ 'formula_id' ] in symbol_ids :
el [ 'formula_id' ] = symbol_ids [ el [ 'formula_id' ] ]
el [ 'handwriting' ] . formula_id = symbol_ids [ el [ 'formula_id' ] ]
new_hw_ds . append ( el )
... |
def get_kb_mappings_json ( kb_name = "" , key = "" , value = "" , match_type = "s" , limit = None ) :
"""Get leftside / rightside mappings from kb kb _ name formatted as json dict .
If key given , give only those with left side ( mapFrom ) = key .
If value given , give only those with right side ( mapTo ) = val... | mappings = get_kb_mappings ( kb_name , key , value , match_type )
ret = [ ]
if limit is None :
limit = len ( mappings )
for m in mappings [ : limit ] :
label = m [ 'value' ] or m [ 'key' ]
value = m [ 'key' ] or m [ 'value' ]
ret . append ( { 'label' : label , 'value' : value } )
return json . dumps ( r... |
def GetDefaultAgency ( self ) :
"""Return the default Agency . If no default Agency has been set select the
default depending on how many Agency objects are in the Schedule . If there
are 0 make a new Agency the default , if there is 1 it becomes the default ,
if there is more than 1 then return None .""" | if not self . _default_agency :
if len ( self . _agencies ) == 0 :
self . NewDefaultAgency ( )
elif len ( self . _agencies ) == 1 :
self . _default_agency = self . _agencies . values ( ) [ 0 ]
return self . _default_agency |
def walk ( self , node : dict ) :
"""Walk thru schema and dereferencing ` ` id ` ` and ` ` $ ref ` ` instances""" | if isinstance ( node , bool ) :
pass
elif '$ref' in node and isinstance ( node [ '$ref' ] , str ) :
ref = node [ '$ref' ]
node [ '$ref' ] = urlparse . urljoin ( self . resolution_scope , ref )
elif 'id' in node and isinstance ( node [ 'id' ] , str ) :
with self . in_scope ( node [ 'id' ] ) :
sel... |
def binary_operation_comparison ( self , rule , left , right , ** kwargs ) :
"""Callback method for rule tree traversing . Will be called at proper time
from : py : class : ` pynspect . rules . ComparisonBinOpRule . traverse ` method .
: param pynspect . rules . Rule rule : Reference to rule .
: param left : ... | return '<div class="pynspect-rule-operation pynspect-rule-operation-comparison"><h3 class="pynspect-rule-operation-name">{}</h3><ul class="pynspect-rule-operation-arguments"><li class="pynspect-rule-operation-argument-left">{}</li><li class="pynspect-rule-operation-argument-right">{}</li></ul></div>' . format ( rule . ... |
def _repr_pretty_ ( self , builder , cycle ) :
"""Custom pretty output for the IPython console""" | builder . text ( self . __class__ . __name__ + "(" )
if cycle :
builder . text ( "<cycle>" )
else :
builder . pretty ( self . __dict__ )
builder . text ( ")" ) |
def format_op_hdr ( ) :
"""Build the header""" | txt = 'Base Filename' . ljust ( 36 ) + ' '
txt += 'Lines' . rjust ( 7 ) + ' '
txt += 'Words' . rjust ( 7 ) + ' '
txt += 'Unique' . ljust ( 8 ) + ''
return txt |
def get_solution ( self , parameters = None ) :
"""stub""" | if not self . has_solution ( ) :
raise IllegalState ( )
return DisplayText ( self . my_osid_object . _my_map [ 'solution' ] ) |
def chunk ( self , size ) :
"""Chunk the underlying collection .
: param size : The chunk size
: type size : int
: rtype : Collection""" | chunks = self . _chunk ( size )
return self . __class__ ( list ( map ( self . __class__ , chunks ) ) ) |
def create_gre_tunnel_mode ( cls , name , local_endpoint , remote_endpoint , policy_vpn , mtu = 0 , pmtu_discovery = True , ttl = 0 , enabled = True , comment = None ) :
"""Create a GRE based tunnel mode route VPN . Tunnel mode GRE wraps the
GRE tunnel in an IPSEC tunnel to provide encrypted end - to - end
secu... | json = { 'name' : name , 'ttl' : ttl , 'mtu' : mtu , 'pmtu_discovery' : pmtu_discovery , 'tunnel_encryption' : 'tunnel_mode' , 'tunnel_mode' : 'gre' , 'enabled' : enabled , 'comment' : comment , 'rbvpn_tunnel_side_a' : local_endpoint . data , 'rbvpn_tunnel_side_b' : remote_endpoint . data }
if policy_vpn is None :
... |
def nmf_init ( data , clusters , k , init = 'enhanced' ) :
"""Generates initial M and W given a data set and an array of cluster labels .
There are 3 options for init :
enhanced - uses EIn - NMF from Gong 2013
basic - uses means for M , assigns W such that the chosen cluster for a given cell has value 0.75 an... | init_m = np . zeros ( ( data . shape [ 0 ] , k ) )
if sparse . issparse ( data ) :
for i in range ( k ) :
if data [ : , clusters == i ] . shape [ 1 ] == 0 :
point = np . random . randint ( 0 , data . shape [ 1 ] )
init_m [ : , i ] = data [ : , point ] . toarray ( ) . flatten ( )
... |
def collection_composition ( collection , raw = False ) :
"""This method retrieve the total of documents , articles ( citable documents ) ,
issues and bibliografic references of a journal
arguments
collection : SciELO 3 letters Acronym
issn : Journal ISSN
return for journal context
" citable " : 12140, ... | tc = ThriftClient ( )
body = { "query" : { "filtered" : { } } }
fltr = { }
query = { "query" : { "bool" : { "must" : [ { "match" : { "collection" : collection } } ] } } }
body [ 'query' ] [ 'filtered' ] . update ( fltr )
body [ 'query' ] [ 'filtered' ] . update ( query )
query_parameters = [ ( 'size' , '0' ) , ( 'searc... |
def _process_hints ( self , analyzed_addrs ) :
"""Process function hints in the binary .
: return : None""" | # Function hints !
# Now let ' s see how many new functions we can get here . . .
while self . _pending_function_hints :
f = self . _pending_function_hints . pop ( )
if f not in analyzed_addrs :
new_state = self . project . factory . entry_state ( mode = 'fastpath' )
new_state . ip = new_state .... |
def random_id ( length = 16 , charset = alphanum_chars , first_charset = alpha_chars , sep = '' , group = 0 ) :
"""Creates a random id with the given length and charset .
# # Parameters
* length the number of characters in the id
* charset what character set to use ( a list of characters )
* first _ charset... | t = [ ]
first_chars = list ( set ( charset ) . intersection ( first_charset ) )
if len ( first_chars ) == 0 :
first_chars = charset
t . append ( first_chars [ random . randrange ( len ( first_chars ) ) ] )
for i in range ( len ( t ) , length ) :
if ( group > 0 ) and ( i % group == 0 ) and ( i < length ) :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.