signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def stopService ( self ) :
"""Stop calling persistent timed events .""" | super ( _SiteScheduler , self ) . stopService ( )
if self . timer is not None :
self . timer . cancel ( )
self . timer = None |
def n1qlQueryEx ( self , cls , * args , ** kwargs ) :
"""Execute a N1QL statement providing a custom handler for rows .
This method allows you to define your own subclass ( of
: class : ` ~ AsyncN1QLRequest ` ) which can handle rows as they are
received from the network .
: param cls : The subclass ( not in... | kwargs [ 'itercls' ] = cls
o = super ( AsyncBucket , self ) . n1ql_query ( * args , ** kwargs )
if not self . connected :
self . connect ( ) . addCallback ( lambda x : o . start ( ) )
else :
o . start ( )
return o |
def pull ( self , key , default = None ) :
"""Pulls an item from the collection .
: param key : The key
: type key : mixed
: param default : The default value
: type default : mixed
: rtype : mixed""" | val = self . get ( key , default )
self . forget ( key )
return val |
async def wait ( self , need_pts = False ) -> dict :
"""Send long poll request
: param need _ pts : need return the pts field""" | if not self . base_url :
await self . _get_long_poll_server ( need_pts )
params = { 'ts' : self . ts , 'key' : self . key , }
params . update ( self . base_params )
# invalid mimetype from server
code , response = await self . api . _session . driver . get_text ( self . base_url , params , timeout = 2 * self . base... |
def split_ls ( func ) :
"""Decorator to split files into manageable chunks as not to exceed the windows cmd limit
: param func : Function to call for each chunk
: type func : : py : class : Function""" | @ wraps ( func )
def wrapper ( self , files , silent = True , exclude_deleted = False ) :
if not isinstance ( files , ( tuple , list ) ) :
files = [ files ]
counter = 0
index = 0
results = [ ]
while files :
if index >= len ( files ) :
results += func ( self , files , sile... |
def yaml_to_file ( data : Mapping , output_dir : str , name : str ) -> str :
"""Save the given object to the given path in YAML .
: param data : dict / list to be dumped
: param output _ dir : target output directory
: param name : target filename
: return : target path""" | dumped_config_f = path . join ( output_dir , name )
with open ( dumped_config_f , 'w' ) as file :
yaml . dump ( data , file , Dumper = ruamel . yaml . RoundTripDumper )
return dumped_config_f |
def update ( self , query , payload ) :
"""Updates a record
: param query : Dictionary , string or : class : ` QueryBuilder ` object
: param payload : Dictionary payload
: return :
- Dictionary of the updated record""" | if not isinstance ( payload , dict ) :
raise InvalidUsage ( "Update payload must be of type dict" )
record = self . get ( query ) . one ( )
self . _url = self . _url_builder . get_appended_custom ( "/{0}" . format ( record [ 'sys_id' ] ) )
return self . _get_response ( 'PUT' , data = json . dumps ( payload ) ) |
def evaluate ( self , reference_scene_list , estimated_scene_list = None , estimated_scene_probabilities = None ) :
"""Evaluate file pair ( reference and estimated )
Parameters
reference _ scene _ list : list of dict or dcase _ util . containers . MetaDataContainer
Reference scene list .
Default value None ... | if estimated_scene_list is None and estimated_scene_probabilities is None :
raise ValueError ( "Nothing to evaluate, give at least estimated_scene_list or estimated_scene_probabilities" )
# Make sure reference _ scene _ list is dcase _ util . containers . MetaDataContainer
if not isinstance ( estimated_scene_list ,... |
def plot_gaussian_2D ( mu , lmbda , color = 'b' , centermarker = True , label = '' , alpha = 1. , ax = None , artists = None ) :
'''Plots mean and cov ellipsoid into current axes . Must be 2D . lmbda is a covariance matrix .''' | assert len ( mu ) == 2
ax = ax if ax else plt . gca ( )
# TODO use artists !
t = np . hstack ( [ np . arange ( 0 , 2 * np . pi , 0.01 ) , 0 ] )
circle = np . vstack ( [ np . sin ( t ) , np . cos ( t ) ] )
ellipse = np . dot ( np . linalg . cholesky ( lmbda ) , circle )
if artists is None :
point = ax . scatter ( [ ... |
def set_deployment_id ( self ) :
"""Sets the deployment ID from deployment properties
: return : None""" | log = logging . getLogger ( self . cls_logger + '.set_deployment_id' )
deployment_id_val = self . get_value ( 'cons3rt.deployment.id' )
if not deployment_id_val :
log . debug ( 'Deployment ID not found in deployment properties' )
return
try :
deployment_id = int ( deployment_id_val )
except ValueError :
... |
def _getUE4BuildInterrogator ( self ) :
"""Uses UE4BuildInterrogator to interrogate UnrealBuildTool about third - party library details""" | ubtLambda = lambda target , platform , config , args : self . _runUnrealBuildTool ( target , platform , config , args , True )
interrogator = UE4BuildInterrogator ( self . getEngineRoot ( ) , self . _getEngineVersionDetails ( ) , self . _getEngineVersionHash ( ) , ubtLambda )
return interrogator |
def ac_factory ( path = "" ) :
"""Attribute Converter factory
: param path : The path to a directory where the attribute maps are expected
to reside .
: return : A AttributeConverter instance""" | acs = [ ]
if path :
if path not in sys . path :
sys . path . insert ( 0 , path )
for fil in os . listdir ( path ) :
if fil . endswith ( ".py" ) :
mod = import_module ( fil [ : - 3 ] )
for key , item in mod . __dict__ . items ( ) :
if key . startswith ( "__... |
def call_inputhook ( self , input_is_ready_func ) :
"""Call the inputhook . ( Called by a prompt - toolkit eventloop . )""" | self . _input_is_ready = input_is_ready_func
# Start thread that activates this pipe when there is input to process .
def thread ( ) :
input_is_ready_func ( wait = True )
os . write ( self . _w , b'x' )
threading . Thread ( target = thread ) . start ( )
# Call inputhook .
self . inputhook ( self )
# Flush the r... |
def get_document ( self , collection_id , ref = None , mimetype = "application/tei+xml, application/xml" ) :
"""Make a navigation request on the DTS API
: param collection _ id : Id of the collection
: param ref : If ref is a tuple , it is treated as a range . String or int are treated as single ref
: param m... | parameters = { "id" : collection_id }
_parse_ref_parameters ( parameters , ref )
return self . call ( "documents" , parameters , mimetype = mimetype ) |
def imsave ( filename , image , normalize = False , format = None , quality = - 1 ) :
"""Convenience function that uses QImage . save to save an image to the
given file . This is intentionally similar to scipy . misc . imsave .
However , it supports different optional arguments :
: param normalize : see : fun... | qImage = array2qimage ( image , normalize = normalize )
return qImage . save ( filename , format , quality ) |
def on_key_event ( self , event ) :
'''handle key events''' | keycode = event . GetKeyCode ( )
if keycode == wx . WXK_HOME :
self . zoom = 1.0
self . dragpos = wx . Point ( 0 , 0 )
self . need_redraw = True |
def limit_author_choices ( ) :
"""Limit choices in blog author field based on config settings""" | LIMIT_AUTHOR_CHOICES = getattr ( settings , 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP' , None )
if LIMIT_AUTHOR_CHOICES :
if isinstance ( LIMIT_AUTHOR_CHOICES , str ) :
limit = Q ( groups__name = LIMIT_AUTHOR_CHOICES )
else :
limit = Q ( )
for s in LIMIT_AUTHOR_CHOICES :
limit = limit... |
def _escapeText ( text ) :
"""Adds backslash - escapes to property value characters that need them .""" | output = ""
index = 0
match = reCharsToEscape . search ( text , index )
while match :
output = output + text [ index : match . start ( ) ] + '\\' + text [ match . start ( ) ]
index = match . end ( )
match = reCharsToEscape . search ( text , index )
output = output + text [ index : ]
return output |
def load_pa11y_ignore_rules ( file = None , url = None ) : # pylint : disable = redefined - builtin
"""Load the pa11y ignore rules from the given file or URL .""" | if not file and not url :
return None
if file :
file = Path ( file )
if not file . isfile ( ) :
msg = ( u"pa11y_ignore_rules_file specified, but file does not exist! {file}" ) . format ( file = file )
raise ValueError ( msg )
return yaml . safe_load ( file . text ( ) )
# must be URL
resp... |
def cli ( self , * args , ** kwargs ) :
"""Defines a CLI function that should be routed by this API""" | kwargs [ 'api' ] = self . api
return cli ( * args , ** kwargs ) |
def _set_interface_reliable_messaging ( self , v , load = False ) :
"""Setter method for interface _ reliable _ messaging , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / mpls _ interface / rsvp / interface _ reliable _ messaging ( container )
If this variable is read - only ( ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = interface_reliable_messaging . interface_reliable_messaging , is_container = 'container' , presence = True , yang_name = "interface-reliable-messaging" , rest_name = "reliable-messaging" , parent = self , path_helper = self .... |
def trunc_neg_eigs ( self , particle ) :
"""Given a state represented as a model parameter vector ,
returns a model parameter vector representing the same
state with any negative eigenvalues set to zero .
: param np . ndarray particle : Vector of length ` ` ( dim * * 2 , ) ` `
representing a state .
: ret... | arr = np . tensordot ( particle , self . _basis . data . conj ( ) , 1 )
w , v = np . linalg . eig ( arr )
if np . all ( w >= 0 ) :
return particle
else :
w [ w < 0 ] = 0
new_arr = np . dot ( v * w , v . conj ( ) . T )
new_particle = np . real ( np . dot ( self . _basis . flat ( ) , new_arr . flatten ( )... |
def loadalldatas ( ) :
"""Loads all demo fixtures .""" | dependency_order = [ 'common' , 'profiles' , 'blog' , 'democomments' ]
for app in dependency_order :
project . recursive_load ( os . path . join ( paths . project_paths . manage_root , app ) ) |
def get_version_details ( path ) :
"""Parses version file
: param path : path to version file
: return : version details""" | with open ( path , "r" ) as reader :
lines = reader . readlines ( )
data = { line . split ( " = " ) [ 0 ] . replace ( "__" , "" ) : line . split ( " = " ) [ 1 ] . strip ( ) . replace ( "'" , "" ) for line in lines }
return data |
def minimize ( self , * args , ** kwargs ) :
'''Optimize our loss exhaustively .
This method is a thin wrapper over the : func : ` iterate ` method . It simply
exhausts the iterative optimization process and returns the final
monitor values .
Returns
train _ monitors : dict
A dictionary mapping monitor ... | monitors = None
for monitors in self . iterate ( * args , ** kwargs ) :
pass
return monitors |
def targets ( self , tgt , tgt_type ) :
'''Return a dict of { ' id ' : { ' ipv4 ' : < ipaddr > } } data sets to be used as
targets given the passed tgt and tgt _ type''' | targets = { }
for back in self . _gen_back ( ) :
f_str = '{0}.targets' . format ( back )
if f_str not in self . rosters :
continue
try :
targets . update ( self . rosters [ f_str ] ( tgt , tgt_type ) )
except salt . exceptions . SaltRenderError as exc :
log . error ( 'Unable to r... |
def insert_tag ( tag , before , root ) :
"""Insert ` tag ` before ` before ` tag if present . If not , insert it into ` root ` .
Args :
tag ( obj ) : HTMLElement instance .
before ( obj ) : HTMLElement instance .
root ( obj ) : HTMLElement instance .""" | if not before :
root . childs . append ( tag )
tag . parent = root
return
if type ( before ) in [ tuple , list ] :
before = first ( before )
# check that ` before ` is double linked
if not hasattr ( before , "parent" ) :
raise ValueError ( "Input must be double-linked!" )
# put it before first exist... |
def try_log_part ( self , context = None , with_start_message = True ) :
"""Залогировать , если пришло время из part _ log _ time _ minutes
: return : boolean Возвращает True если лог был записан""" | if context is None :
context = { }
self . __counter += 1
if time . time ( ) - self . __begin_time > self . __part_log_time_seconds :
self . __begin_time = time . time ( )
context [ 'count' ] = self . __counter
if self . __total :
self . __percent_done = int ( self . __counter * 100 / self . __to... |
def I_minus_R ( self , singular_value ) :
"""get I - R at singular value
Parameters
singular _ value : int
singular value to calc R at
Returns
I - R : pyemu . Matrix
identity matrix minus resolution matrix at singular _ value""" | if self . __I_R is not None and singular_value == self . __I_R_sv :
return self . __I_R
else :
if singular_value > self . jco . ncol :
return self . parcov . zero
else : # v2 = self . qhalfx . v [ : , singular _ value : ]
v2 = self . xtqx . v [ : , singular_value : ]
self . __I_R = v... |
def pre_release ( version ) :
"""Generates new docs , release announcements and creates a local tag .""" | announce ( version )
regen ( )
changelog ( version , write_out = True )
fix_formatting ( )
msg = "Preparing release version {}" . format ( version )
check_call ( [ "git" , "commit" , "-a" , "-m" , msg ] )
print ( )
print ( f"{Fore.CYAN}[generate.pre_release] {Fore.GREEN}All done!" )
print ( )
print ( f"Please push your... |
def forward ( self , images , targets = None ) :
"""Arguments :
images ( list [ Tensor ] or ImageList ) : images to be processed
targets ( list [ BoxList ] ) : ground - truth boxes present in the image ( optional )
Returns :
result ( list [ BoxList ] or dict [ Tensor ] ) : the output from the model .
Duri... | if self . training and targets is None :
raise ValueError ( "In training mode, targets should be passed" )
images = to_image_list ( images )
features = self . backbone ( images . tensors )
proposals , proposal_losses = self . rpn ( images , features , targets )
if self . roi_heads :
x , result , detector_losses... |
def start ( self ) :
"""Starts the upload .
: raises SbgError : If upload is not in PREPARING state .""" | if self . _status == TransferState . PREPARING :
super ( Upload , self ) . start ( )
else :
raise SbgError ( 'Unable to start. Upload not in PREPARING state.' ) |
def get_scss_files ( self , skip_partials = True , with_source_path = False ) :
"""Gets all SCSS files in the source directory .
: param bool skip _ partials : If True , partials will be ignored . Otherwise ,
all SCSS files , including ones that begin
with ' _ ' will be returned .
: param boom with _ source... | scss_files = [ ]
for root , dirs , files in os . walk ( self . _source_path ) :
for filename in fnmatch . filter ( files , "*.scss" ) :
if filename . startswith ( "_" ) and skip_partials :
continue
full_path = os . path . join ( root , filename )
if not with_source_path :
... |
def get_lrc ( self , playingsong ) :
"""获取歌词
如果测试频繁会发如下信息 :
{ ' msg ' : ' You API access rate limit has been exceeded .
Contact api - master @ douban . com if you want higher limit . ' ,
' code ' : 1998,
' request ' : ' GET / j / v2 / lyric ' }""" | try :
url = "https://douban.fm/j/v2/lyric"
postdata = { 'sid' : playingsong [ 'sid' ] , 'ssid' : playingsong [ 'ssid' ] , }
s = requests . session ( )
response = s . get ( url , params = postdata , headers = HEADERS )
# 把歌词解析成字典
lyric = json . loads ( response . text , object_hook = decode_dict ... |
def _project_TH2 ( self , hist : Hist ) -> Any :
"""Perform the actual TH2 - > TH1 projection .
This projection can only be to 1D .
Args :
hist ( ROOT . TH2 ) : Histogram from which the projections should be performed .
Returns :
ROOT . TH1 : The projected histogram .""" | if len ( self . projection_axes ) != 1 :
raise ValueError ( len ( self . projection_axes ) , "Invalid number of axes" )
# logger . debug ( f " self . projection _ axes [ 0 ] . axis : { self . projection _ axes [ 0 ] . axis } , axis range name : { self . projection _ axes [ 0 ] . name } , axis _ type : { self . proj... |
def treebeard_js ( ) :
"""Template tag to print out the proper < script / > tag to include a custom . js""" | path = get_static_url ( )
js_file = urljoin ( path , 'treebeard/treebeard-admin.js' )
jquery_ui = urljoin ( path , 'treebeard/jquery-ui-1.8.5.custom.min.js' )
# Jquery UI is needed to call disableSelection ( ) on drag and drop so
# text selections arent marked while dragging a table row
# http : / / www . lokkju . com ... |
def parse_stream ( response ) :
"""take stream from docker - py lib and display it to the user .
this also builds a stream list and returns it .""" | stream_data = [ ]
stream = stdout
for data in response :
if data :
try :
data = data . decode ( 'utf-8' )
except AttributeError as e :
logger . exception ( "Unable to parse stream, Attribute Error Raised: {0}" . format ( e ) )
stream . write ( data )
c... |
def get_fit_failed_candidate_model ( model_type , formula ) :
"""Return a Candidate model that indicates the fitting routine failed .
Parameters
model _ type : : any : ` str `
Model type ( e . g . , ` ` ' cdd _ hdd ' ` ` ) .
formula : : any : ` float `
The candidate model formula .
Returns
candidate _... | warnings = [ EEMeterWarning ( qualified_name = "eemeter.caltrack_daily.{}.model_results" . format ( model_type ) , description = ( "Error encountered in statsmodels.formula.api.ols method. (Empty data?)" ) , data = { "traceback" : traceback . format_exc ( ) } , ) ]
return CalTRACKUsagePerDayCandidateModel ( model_type ... |
def linkify ( self ) :
"""The realms linkify is done during the default realms / satellites initialization in the
Config class .
This functione only finishes the process by setting the realm level property according
to the realm position in the hierarchy .
All ` level ` 0 realms are main realms that have th... | logger . info ( "Known realms:" )
for realm in self :
for tmp_realm in self : # Ignore if it is me . . .
if tmp_realm == realm :
continue
# Ignore if I am a sub realm of another realm
if realm . get_name ( ) in tmp_realm . realm_members :
break
else : # This realm... |
def p_if_statement_woelse ( self , p ) :
'if _ statement : IF LPAREN cond RPAREN true _ statement' | p [ 0 ] = IfStatement ( p [ 3 ] , p [ 5 ] , None , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def authenticate ( self , end_user_ip , personal_number = None , requirement = None , ** kwargs ) :
"""Request an authentication order . The : py : meth : ` collect ` method
is used to query the status of the order .
Note that personal number is not needed when authentication is to
be done on the same device ... | data = { "endUserIp" : end_user_ip }
if personal_number :
data [ "personalNumber" ] = personal_number
if requirement and isinstance ( requirement , dict ) :
data [ "requirement" ] = requirement
# Handling potentially changed optional in - parameters .
data . update ( kwargs )
response = self . client . post ( s... |
def from_json ( cls , data ) :
"""Create STAT from json dictionary .
Args :
data : {
' location ' : { } , / / ladybug location schema
' ashrae _ climate _ zone ' : str ,
' koppen _ climate _ zone ' : str ,
' extreme _ cold _ week ' : { } , / / ladybug analysis period schema
' extreme _ hot _ week ' : ... | # Initialize the class with all data missing
stat_ob = cls ( None )
# Check required and optional keys
option_keys_none = ( 'ashrae_climate_zone' , 'koppen_climate_zone' , 'extreme_cold_week' , 'extreme_hot_week' , 'standard_pressure_at_elev' )
option_keys_list = ( 'monthly_db_50' , 'monthly_wb_50' , 'monthly_db_range_... |
def showExports ( peInstance ) :
"""Show exports information""" | exports = peInstance . ntHeaders . optionalHeader . dataDirectory [ consts . EXPORT_DIRECTORY ] . info
if exports :
exp_fields = exports . getFields ( )
for field in exp_fields :
print "%s -> %x" % ( field , exp_fields [ field ] . value )
for entry in exports . exportTable :
entry_fields = e... |
def getLeapSecondLastUpdated ( ) : # @ NoSelf
"""Shows the latest date a leap second was added to the leap second table .""" | print ( 'Leap second last updated:' , str ( CDFepoch . LTS [ - 1 ] [ 0 ] ) + '-' + str ( CDFepoch . LTS [ - 1 ] [ 1 ] ) + '-' + str ( CDFepoch . LTS [ - 1 ] [ 2 ] ) ) |
def append ( self , node ) :
"""Append ( set ) the document root .
@ param node : A root L { Element } or name used to build
the document root element .
@ type node : ( L { Element } | str | None )""" | if isinstance ( node , basestring ) :
self . __root = Element ( node )
return
if isinstance ( node , Element ) :
self . __root = node
return |
def update_ontology ( ont_url , rdf_path ) :
"""Load an ontology formatted like Eidos ' from github .""" | yaml_root = load_yaml_from_url ( ont_url )
G = rdf_graph_from_yaml ( yaml_root )
save_hierarchy ( G , rdf_path ) |
def get_pid ( rundir , process_type = PROCESS_TYPE , name = None ) :
"""Get the pid from the pid file in the run directory , using the given
process type and process name for the filename .
@ returns : pid of the process , or None if not running or file not found .""" | pidPath = get_pidpath ( rundir , process_type , name )
log . log ( 'run' , 'pidfile for %s %s is %s' % ( process_type , name , pidPath ) )
if not os . path . exists ( pidPath ) :
return
pidFile = open ( pidPath , 'r' )
pid = pidFile . readline ( )
pidFile . close ( )
if not pid or int ( pid ) == 0 :
return
retu... |
def connection ( self , name = None ) :
"""return a named connection .
This function will return a named connection by either finding one
in its pool by the name or creating a new one . If no name is given ,
it will use the name of the current executing thread as the name of
the connection .
parameters : ... | if not name :
name = self . _get_default_connection_name ( )
if name in self . pool :
return self . pool [ name ]
self . pool [ name ] = psycopg2 . connect ( self . dsn )
return self . pool [ name ] |
def update ( self , request , * args , ** kwargs ) :
"""Update the ` ` Relation ` ` object .
Reject the update if user doesn ' t have ` ` EDIT ` ` permission on
the collection referenced in the ` ` Relation ` ` .""" | instance = self . get_object ( )
if ( not request . user . has_perm ( 'edit_collection' , instance . collection ) and not request . user . is_superuser ) :
return Response ( status = status . HTTP_401_UNAUTHORIZED )
return super ( ) . update ( request , * args , ** kwargs ) |
def clean_email ( self ) :
"""Ensure the email address is not already registered .""" | email = self . cleaned_data . get ( "email" )
qs = User . objects . exclude ( id = self . instance . id ) . filter ( email = email )
if len ( qs ) == 0 :
return email
raise forms . ValidationError ( ugettext ( "This email is already registered" ) ) |
def align ( s1 , s2 , gap = ' ' , eq = operator . eq ) :
'''aligns two strings
> > > print ( * align ( ' pharmacy ' , ' farmácia ' , gap = ' _ ' ) , sep = ' \\ n ' )
pharmac _ y
_ farmácia
> > > print ( * align ( ' advantage ' , ' vantagem ' , gap = ' _ ' ) , sep = ' \\ n ' )
advantage _
_ _ vantagem'... | # first we compute the dynamic programming table
m , n = len ( s1 ) , len ( s2 )
table = [ ]
# the table is extended lazily , one row at a time
row = list ( range ( n + 1 ) )
# the first row is 0 , 1 , 2 , . . . , n
table . append ( list ( row ) )
# copy row and insert into table
for i in range ( m ) :
p = i
ro... |
def buttons ( self ) :
"""Returns a matrix ( list of lists ) containing all buttons of the message
as ` MessageButton < telethon . tl . custom . messagebutton . MessageButton > `
instances .""" | if self . _buttons is None and self . reply_markup :
if not self . input_chat :
return
try :
bot = self . _needed_markup_bot ( )
except ValueError :
return
else :
self . _set_buttons ( self . _input_chat , bot )
return self . _buttons |
def _get_controllers ( self ) :
"""Iterate through the installed controller entry points and import
the module and assign the handle to the CLI . _ controllers dict .
: return : dict""" | controllers = dict ( )
for pkg in pkg_resources . iter_entry_points ( group = self . CONTROLLERS ) :
LOGGER . debug ( 'Loading %s controller' , pkg . name )
controllers [ pkg . name ] = importlib . import_module ( pkg . module_name )
return controllers |
def _MultiStream ( cls , fds ) :
"""Effectively streams data from multiple opened AFF4ImageBase objects .
Args :
fds : A list of opened AFF4Stream ( or AFF4Stream descendants ) objects .
Yields :
Tuples ( chunk , fd , exception ) where chunk is a binary blob of data and fd
is an object from the fds argume... | missing_chunks_by_fd = { }
for chunk_fd_pairs in collection . Batch ( cls . _GenerateChunkPaths ( fds ) , cls . MULTI_STREAM_CHUNKS_READ_AHEAD ) :
chunks_map = dict ( chunk_fd_pairs )
contents_map = { }
for chunk_fd in FACTORY . MultiOpen ( chunks_map , mode = "r" , token = fds [ 0 ] . token ) :
if ... |
def parse_value ( self , sn : "DataNode" ) -> ScalarValue :
"""Let schema node ' s type parse the receiver ' s value .""" | res = sn . type . parse_value ( self . value )
if res is None :
raise InvalidKeyValue ( self . value )
return res |
def load_member ( fqn ) :
"""Loads and returns a class for a given fully qualified name .""" | modulename , member_name = split_fqn ( fqn )
module = __import__ ( modulename , globals ( ) , locals ( ) , member_name )
return getattr ( module , member_name ) |
def sentence_matches ( self , sentence_text ) :
"""Returns true iff the sentence contains this mention ' s upstream
and downstream participants , and if one of the stemmed verbs in
the sentence is the same as the stemmed action type .""" | has_upstream = False
has_downstream = False
has_verb = False
# Get the first word of the action type and assume this is the verb
# ( Ex . get depends for depends on )
actiontype_words = word_tokenize ( self . mention . actiontype )
actiontype_verb_stemmed = stem ( actiontype_words [ 0 ] )
words = word_tokenize ( senten... |
def sscan ( self , name , cursor = 0 , match = None , count = None ) :
"""Incrementally return lists of elements in a set . Also return a cursor
indicating the scan position .
` ` match ` ` allows for filtering the keys by pattern
` ` count ` ` allows for hint the minimum number of returns""" | pieces = [ name , cursor ]
if match is not None :
pieces . extend ( [ Token . get_token ( 'MATCH' ) , match ] )
if count is not None :
pieces . extend ( [ Token . get_token ( 'COUNT' ) , count ] )
return self . execute_command ( 'SSCAN' , * pieces ) |
def overlays_at ( self , key ) :
"""Key may be a slice or a point .""" | if isinstance ( key , slice ) :
s , e , _ = key . indices ( len ( self . text ) )
else :
s = e = key
return [ o for o in self . overlays if o . start in Rng ( s , e ) ] |
def get_object ( self , resource_url ) :
"""Get remote resource information . Creates a local directory for the
resource if this is the first access to the resource . Downloads the
resource Json representation and writes it into a . json file in the
cache directory .
Raises ValueError if resource is not cac... | # Check if resource is in local cache . If not , create a new cache
# identifier and set is _ cached flag to false
if resource_url in self . cache :
cache_id = self . cache [ resource_url ]
else :
cache_id = str ( uuid . uuid4 ( ) )
# The local cahce directory for resource is given by cache identifier
obj_dir =... |
def eeg_microstates_plot ( method , path = "" , extension = ".png" , show_sensors_position = False , show_sensors_name = False , plot = True , save = True , dpi = 150 , contours = 0 , colorbar = False , separate = False ) :
"""Plot the microstates .""" | # Generate and store figures
figures = [ ]
names = [ ]
# Check if microstates metrics available
try :
microstates = method [ "microstates_good_fit" ]
except KeyError :
microstates = method [ "microstates" ]
# Create individual plot for each microstate
for microstate in set ( microstates ) :
if microstate !=... |
def delete_polygon ( self , polygon ) :
"""Deletes on the Agro API the Polygon identified by the ID of the provided polygon object .
: param polygon : the ` pyowm . agro10 . polygon . Polygon ` object to be deleted
: type polygon : ` pyowm . agro10 . polygon . Polygon ` instance
: returns : ` None ` if deleti... | assert polygon . id is not None
status , _ = self . http_client . delete ( NAMED_POLYGON_URI % str ( polygon . id ) , params = { 'appid' : self . API_key } , headers = { 'Content-Type' : 'application/json' } ) |
def _prepare_deprecation_data ( self ) :
"""Cycles through the list of AppSettingDeprecation instances set on
` ` self . deprecations ` ` and prepulates two new dictionary attributes :
` ` self . _ deprecated _ settings ` ` :
Uses the deprecated setting names themselves as the keys . Used to
check whether a... | if not isinstance ( self . deprecations , ( list , tuple ) ) :
raise IncorrectDeprecationsValueType ( "'deprecations' must be a list or tuple, not a {}." . format ( type ( self . deprecations ) . __name__ ) )
self . _deprecated_settings = { }
self . _replacement_settings = defaultdict ( list )
for item in self . de... |
def create_multicast_socket ( address , port ) :
"""Creates a multicast socket according to the given address and port .
Handles both IPv4 and IPv6 addresses .
: param address : Multicast address / group
: param port : Socket port
: return : A tuple ( socket , listening address )
: raise ValueError : Inva... | # Get the information about a datagram ( UDP ) socket , of any family
try :
addrs_info = socket . getaddrinfo ( address , port , socket . AF_UNSPEC , socket . SOCK_DGRAM )
except socket . gaierror :
raise ValueError ( "Error retrieving address informations ({0}, {1})" . format ( address , port ) )
if len ( addr... |
def stop_and_reset_thread ( self , ignore_results = False ) :
"""Stop current search thread and clean - up""" | if self . search_thread is not None :
if self . search_thread . isRunning ( ) :
if ignore_results :
self . search_thread . sig_finished . disconnect ( self . search_complete )
self . search_thread . stop ( )
self . search_thread . wait ( )
self . search_thread . setParent ( N... |
def create ( self , project_id = None ) :
"""Creates the bucket .
Args :
project _ id : the project in which to create the bucket .
Returns :
The bucket .
Raises :
Exception if there was an error creating the bucket .""" | if not self . exists ( ) :
if project_id is None :
project_id = self . _api . project_id
try :
self . _info = self . _api . buckets_insert ( self . _name , project_id = project_id )
except Exception as e :
raise e
return self |
def find_write_predecessors ( self , address ) :
"""Returns all predecessor transaction ids for a write of the provided
address .
Arguments :
address ( str ) : the radix address
Returns : a set of transaction ids""" | # A write operation must be preceded by :
# - The " enclosing writer " , which is the writer at the address or
# the nearest writer higher ( closer to the root ) in the tree .
# - The " enclosing readers " , which are the readers at the address
# or higher in the tree .
# - The " children writers " , which include all ... |
def comunicar_certificado_icpbrasil ( self , certificado ) :
"""Função ` ` ComunicarCertificadoICPBRASIL ` ` conforme ER SAT , item 6.1.2.
Envio do certificado criado pela ICP - Brasil .
: param str certificado : Conteúdo do certificado digital criado pela
autoridade certificadora ICP - Brasil .
: return... | return self . invocar__ComunicarCertificadoICPBRASIL ( self . gerar_numero_sessao ( ) , self . _codigo_ativacao , certificado ) |
def get_alignments ( attention_matrix : np . ndarray , threshold : float = .9 ) -> Iterator [ Tuple [ int , int ] ] :
"""Yields hard alignments from an attention _ matrix ( target _ length , source _ length )
given a threshold .
: param attention _ matrix : The attention matrix .
: param threshold : The thres... | for src_idx in range ( attention_matrix . shape [ 1 ] ) :
for trg_idx in range ( attention_matrix . shape [ 0 ] ) :
if attention_matrix [ trg_idx , src_idx ] > threshold :
yield ( src_idx , trg_idx ) |
def __recv_cb ( self , msg ) :
"""Calls user - provided callback and marks message for Ack regardless of success""" | try :
self . __msg_callback ( msg )
except :
logger . exception ( "AmqpLink.__recv_cb exception calling msg_callback" )
finally : # only works if all messages handled in series
self . __last_id = msg . delivery_tag
self . __unacked += 1 |
def map ( self , arg , na_action = None ) :
"""Map values of Series according to input correspondence .
Used for substituting each value in a Series with another value ,
that may be derived from a function , a ` ` dict ` ` or
a : class : ` Series ` .
Parameters
arg : function , dict , or Series
Mapping ... | new_values = super ( ) . _map_values ( arg , na_action = na_action )
return self . _constructor ( new_values , index = self . index ) . __finalize__ ( self ) |
def write_bibtex_dict ( stream , entries ) :
"""bibtexparser . write converts the entire database to one big string and
writes it out in one go . I ' m sure it will always all fit in RAM but some
things just will not stand .""" | from bibtexparser . bwriter import BibTexWriter
writer = BibTexWriter ( )
writer . indent = ' '
writer . entry_separator = ''
first = True
for rec in entries :
if first :
first = False
else :
stream . write ( b'\n' )
stream . write ( writer . _entry_to_bibtex ( rec ) . encode ( 'utf8' ) ) |
def disassemble ( self , * , transforms = None ) -> Iterator [ Instruction ] :
"""Disassembles this method , yielding an iterable of
: class : ` ~ jawa . util . bytecode . Instruction ` objects .""" | if transforms is None :
if self . cf . classloader :
transforms = self . cf . classloader . bytecode_transforms
else :
transforms = [ ]
transforms = [ self . _bind_transform ( t ) for t in transforms ]
with io . BytesIO ( self . _code ) as code :
ins_iter = iter ( lambda : read_instruction (... |
def main ( conf_file , overwrite , logger ) :
"""Create configuration and log file . Restart the daemon when configuration
is done .
Args :
conf _ file ( str ) : Path to the configuration file .
overwrite ( bool ) : Overwrite the configuration file with ` clean ` config ?""" | uid = pwd . getpwnam ( get_username ( ) ) . pw_uid
# stop the daemon
logger . info ( "Stopping the daemon." )
sh . service ( get_service_name ( ) , "stop" )
# create files
logger . info ( "Creating config file." )
create_config ( cnf_file = conf_file , uid = uid , overwrite = overwrite )
logger . info ( "Creating log f... |
def handle_import ( self , options ) :
"""Gets posts from Blogger .""" | blog_id = options . get ( "blog_id" )
if blog_id is None :
raise CommandError ( "Usage is import_blogger %s" % self . args )
try :
from gdata import service
except ImportError :
raise CommandError ( "Could not import the gdata library." )
blogger = service . GDataService ( )
blogger . service = "blogger"
bl... |
def set_write_bit ( fn ) : # type : ( str ) - > None
"""Set read - write permissions for the current user on the target path . Fail silently
if the path doesn ' t exist .
: param str fn : The target filename or path
: return : None""" | fn = fs_encode ( fn )
if not os . path . exists ( fn ) :
return
file_stat = os . stat ( fn ) . st_mode
os . chmod ( fn , file_stat | stat . S_IRWXU | stat . S_IRWXG | stat . S_IRWXO )
if not os . path . isdir ( fn ) :
for path in [ fn , os . path . dirname ( fn ) ] :
try :
os . chflags ( pat... |
def update_balances ( self , recursive = True ) :
"""Calculate tree balance factor""" | if self . node :
if recursive :
if self . node . left :
self . node . left . update_balances ( )
if self . node . right :
self . node . right . update_balances ( )
self . balance = self . node . left . height - self . node . right . height
else :
self . balance = 0 |
def schemaNewValidCtxt ( self ) :
"""Create an XML Schemas validation context based on the given
schema .""" | ret = libxml2mod . xmlSchemaNewValidCtxt ( self . _o )
if ret is None :
raise treeError ( 'xmlSchemaNewValidCtxt() failed' )
__tmp = SchemaValidCtxt ( _obj = ret )
__tmp . schema = self
return __tmp |
def sigma_operator_indices ( A ) :
r"""If A is an outer - product type operator | a > < b | return a , b .
> > > sig = ket ( 2 , 3 ) * bra ( 1 , 3)
> > > sigma _ operator _ indices ( sig )
(1 , 0)
> > > sigma _ operator _ indices ( sig + sig . adjoint ( ) )
( None , None )""" | Ne = A . shape [ 0 ]
band = True
if sum ( A ) != 1 :
band = False
a = None ;
b = None
for i in range ( Ne ) :
for j in range ( Ne ) :
if A [ i , j ] == 1 :
a = i ;
b = j
elif A [ i , j ] != 0 :
band = False
if band :
return a , b
else :
return None , N... |
def cms_check ( migrate_cmd = False ) :
"""Runs the django CMS ` ` cms check ` ` command""" | from django . core . management import call_command
try :
import cms
# NOQA # nopyflakes
_create_db ( migrate_cmd )
call_command ( 'cms' , 'check' )
except ImportError :
print ( 'cms_check available only if django CMS is installed' ) |
def ensure_provisioning ( table_name , key_name , num_consec_read_checks , num_consec_write_checks ) :
"""Ensure that provisioning is correct
: type table _ name : str
: param table _ name : Name of the DynamoDB table
: type key _ name : str
: param key _ name : Configuration option key name
: type num _ ... | if get_global_option ( 'circuit_breaker_url' ) or get_table_option ( key_name , 'circuit_breaker_url' ) :
if circuit_breaker . is_open ( table_name , key_name ) :
logger . warning ( 'Circuit breaker is OPEN!' )
return ( 0 , 0 )
# Handle throughput alarm checks
__ensure_provisioning_alarm ( table_nam... |
def _delete_record ( self , identifier = None , rtype = None , name = None , content = None ) :
"""Connects to Hetzner account , removes an existing record from the zone and returns a
boolean , if deletion was successful or not . Uses identifier or rtype , name & content to
lookup over all records of the zone f... | with self . _session ( self . domain , self . domain_id ) as ddata : # Validate method parameters
if identifier :
rtype , name , content = self . _parse_identifier ( identifier , ddata [ 'zone' ] [ 'data' ] )
if rtype is None or name is None or content is None :
LOGGER . info ( 'Hetzner ... |
def validate_password_strength ( value ) :
"""Validates that a password is as least 7 characters long and has at least
1 digit and 1 letter .""" | min_length = 7
if len ( value ) < min_length :
raise ValidationError ( _ ( 'Password must be at least {0} characters ' 'long.' ) . format ( min_length ) )
# check for digit
if not any ( char . isdigit ( ) for char in value ) :
raise ValidationError ( _ ( 'Password must contain at least 1 digit.' ) )
# check for... |
def check_info ( info ) :
"""Validate info dict .
Raise ValueError if validation fails .""" | if not isinstance ( info , dict ) :
raise ValueError ( "bad metainfo - not a dictionary" )
pieces = info . get ( "pieces" )
if not isinstance ( pieces , basestring ) or len ( pieces ) % 20 != 0 :
raise ValueError ( "bad metainfo - bad pieces key" )
piece_size = info . get ( "piece length" )
if not isinstance ( ... |
def get_pubkey ( self ) :
'''Return the key string for the SSH public key''' | if '__master_opts__' in self . opts and self . opts [ '__master_opts__' ] . get ( 'ssh_use_home_key' ) and os . path . isfile ( os . path . expanduser ( '~/.ssh/id_rsa' ) ) :
priv = os . path . expanduser ( '~/.ssh/id_rsa' )
else :
priv = self . opts . get ( 'ssh_priv' , os . path . join ( self . opts [ 'pki_di... |
def _conf ( cls , opts ) :
"""Setup logging via ini - file from logging _ conf _ file option .""" | if not opts . logging_conf_file :
return False
if not os . path . exists ( opts . logging_conf_file ) : # FileNotFoundError added only in Python 3.3
# https : / / docs . python . org / 3 / whatsnew / 3.3 . html # pep - 3151 - reworking - the - os - and - io - exception - hierarchy
raise OSError ( "Error: Unable... |
def error ( self , i : int = None ) -> str :
"""Returns an error message""" | head = "[" + colors . red ( "error" ) + "]"
if i is not None :
head = str ( i ) + " " + head
return head |
def load ( self , rule_type , quiet = False ) :
"""Open a JSON file definiting a ruleset and load it into a Ruleset object
: param quiet :
: return :""" | if self . filename and os . path . exists ( self . filename ) :
try :
with open ( self . filename , 'rt' ) as f :
ruleset = json . load ( f )
self . about = ruleset [ 'about' ] if 'about' in ruleset else ''
self . rules = { }
for filename in ruleset [ 'rules' ... |
def get_created_date_metadata ( self ) :
"""Gets the metadata for the asset creation date .
return : ( osid . Metadata ) - metadata for the created date
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template
metadata = dict ( self . _mdata [ 'created_date' ] )
metadata . update ( { 'existing_date_time_values' : self . _my_map [ 'createdDate' ] } )
return Metadata ( ** metadata ) |
def get_sequences ( input_seqs ) :
"""Returns a list of Sequences
Parameters
input _ seqs : iterable of ( str , str )
The list of input sequences in ( label , sequence ) format
Returns
list of Sequence
Raises
ValueError
If no sequences where found in ` input _ seqs `
If all the sequences do not ha... | try :
seqs = [ Sequence ( id , seq ) for id , seq in input_seqs ]
except Exception :
seqs = [ ]
if len ( seqs ) == 0 :
logger = logging . getLogger ( __name__ )
logger . warn ( 'No sequences found in fasta file!' )
return None
# Check that all the sequence lengths ( aligned and unaligned are the sam... |
def filter_noexpand_columns ( columns ) :
"""Return columns not containing and containing the noexpand prefix .
Parameters
columns : sequence of str
A sequence of strings to be split
Returns
Two lists , the first containing strings without the noexpand prefix , the
second containing those that do with t... | prefix_len = len ( NOEXPAND_PREFIX )
noexpand = [ c [ prefix_len : ] for c in columns if c . startswith ( NOEXPAND_PREFIX ) ]
other = [ c for c in columns if not c . startswith ( NOEXPAND_PREFIX ) ]
return other , noexpand |
def _get_action_urls ( self ) :
"""Get the url patterns that route each action to a view .""" | actions = { }
model_name = self . model . _meta . model_name
# e . g . : polls _ poll
base_url_name = '%s_%s' % ( self . model . _meta . app_label , model_name )
# e . g . : polls _ poll _ actions
model_actions_url_name = '%s_actions' % base_url_name
self . tools_view_name = 'admin:' + model_actions_url_name
# WISHLIST... |
def stream ( self , name ) :
"""Stream can be used to record different time series :
run . history . stream ( " batch " ) . add ( { " gradients " : 1 } )""" | if self . stream_name != "default" :
raise ValueError ( "Nested streams aren't supported" )
if self . _streams . get ( name ) == None :
self . _streams [ name ] = History ( self . fname , out_dir = self . out_dir , add_callback = self . _add_callback , stream_name = name )
return self . _streams [ name ] |
def validate ( self , value ) :
"""Check if ` ` value ` ` is valid .
: returns : [ errors ] If ` ` value ` ` is invalid , otherwise [ ] .""" | errors = [ ]
# Make sure the type validates first .
valid = self . _is_valid ( value )
if not valid :
errors . append ( self . fail ( value ) )
return errors
# Then validate all the constraints second .
for constraint in self . _constraints_inst :
error = constraint . is_valid ( value )
if error :
... |
def get_text_position ( fig , ax , ha = 'left' , va = 'top' , pad_scale = 1.0 ) :
"""Return text position inside of the given axis""" | # # Check and preprocess input arguments
try :
pad_scale = float ( pad_scale )
except :
raise TypeError ( "'pad_scale should be of type 'float'" )
for arg in [ va , ha ] :
assert type ( arg ) is str
arg = arg . lower ( )
# Make it lowercase to prevent case problem .
# # Get axis size in inches
ax_height... |
def messages ( count , size ) :
'''Generator for count messages of the provided size''' | import string
# Make sure we have at least ' size ' letters
letters = islice ( cycle ( chain ( string . lowercase , string . uppercase ) ) , size )
return islice ( cycle ( '' . join ( l ) for l in permutations ( letters , size ) ) , count ) |
def find_any_valid_version ( self ) : # type : ( ) - > str
"""Find version candidates , return first ( or any , since they aren ' t ordered )
Blow up if versions are not homogeneous
: return :""" | versions = self . all_current_versions ( )
if not versions and not self . force_init :
raise JiggleVersionException ( "Have no versions to work with, failed to find any. Include --init to start out at 0.1.0" )
if not versions and self . force_init :
versions = { "force_init" : "0.1.0" }
if len ( versions ) > 1 ... |
def _kill_cursors ( self , cursor_ids , address , topology , session ) :
"""Send a kill cursors message with the given ids .""" | listeners = self . _event_listeners
publish = listeners . enabled_for_commands
if address : # address could be a tuple or _ CursorAddress , but
# select _ server _ by _ address needs ( host , port ) .
server = topology . select_server_by_address ( tuple ( address ) )
else : # Application called close _ cursor ( ) w... |
def get ( cls , name , service = Service ( ) ) :
'''fetch given bin from the service''' | path = pathjoin ( cls . path , name )
response = service . send ( SRequest ( 'GET' , path ) )
return cls . from_response ( response , service = service ) |
async def _send_rtcp_pli ( self , media_ssrc ) :
"""Send an RTCP packet to report picture loss .""" | if self . __rtcp_ssrc is not None :
packet = RtcpPsfbPacket ( fmt = RTCP_PSFB_PLI , ssrc = self . __rtcp_ssrc , media_ssrc = media_ssrc )
await self . _send_rtcp ( packet ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.