signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def determine_bpi ( data , frames , EMPTY = b"\x00" * 10 ) :
"""Takes id3v2.4 frame data and determines if ints or bitpaddedints
should be used for parsing . Needed because iTunes used to write
normal ints for frame sizes .""" | # count number of tags found as BitPaddedInt and how far past
o = 0
asbpi = 0
while o < len ( data ) - 10 :
part = data [ o : o + 10 ]
if part == EMPTY :
bpioff = - ( ( len ( data ) - o ) % 10 )
break
name , size , flags = struct . unpack ( '>4sLH' , part )
size = BitPaddedInt ( size )
... |
async def joinTeleLayer ( self , url , indx = None ) :
'''Convenience function to join a remote telepath layer
into this cortex and default view .''' | info = { 'type' : 'remote' , 'owner' : 'root' , 'config' : { 'url' : url } }
layr = await self . addLayer ( ** info )
await self . view . addLayer ( layr , indx = indx )
return layr . iden |
def refresh ( self , only_closed = False ) :
"""refresh ports status
Args :
only _ closed - check status only for closed ports""" | if only_closed :
opened = filter ( self . __check_port , self . __closed )
self . __closed = self . __closed . difference ( opened )
self . __ports = self . __ports . union ( opened )
else :
ports = self . __closed . union ( self . __ports )
self . __ports = set ( filter ( self . __check_port , port... |
def _check_seed ( seed ) :
"""If possible , convert ` seed ` into a valid form for Stan ( an integer
between 0 and MAX _ UINT , inclusive ) . If not possible , use a random seed
instead and raise a warning if ` seed ` was not provided as ` None ` .""" | if isinstance ( seed , ( Number , string_types ) ) :
try :
seed = int ( seed )
except ValueError :
logger . warning ( "`seed` must be castable to an integer" )
seed = None
else :
if seed < 0 :
logger . warning ( "`seed` may not be negative" )
seed = No... |
def _autodiscover ( self ) :
"""Discovers panels to register from the current dashboard module .""" | if getattr ( self , "_autodiscover_complete" , False ) :
return
panels_to_discover = [ ]
panel_groups = [ ]
# If we have a flat iterable of panel names , wrap it again so
# we have a consistent structure for the next step .
if all ( [ isinstance ( i , six . string_types ) for i in self . panels ] ) :
self . pan... |
def _teardown ( self ) :
"Handles the restoration of any potential global state set ." | self . example . after ( self . context )
if self . is_root_runner :
run . after_all . execute ( self . context )
# self . context = self . context . _ parent
self . has_ran = True |
def send_confirmation_email ( self , confirmation_id , email_dict ) :
"""Sends an confirmation by email
If you want to send your email to more than one persons do :
' recipients ' : { ' to ' : [ ' bykof @ me . com ' , ' mbykovski @ seibert - media . net ' ] } }
: param confirmation _ id : the confirmation id ... | return self . _create_post_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , send_data = email_dict , command = EMAIL , ) |
def auth_keys ( user = None , config = '.ssh/authorized_keys' , fingerprint_hash_type = None ) :
'''Return the authorized keys for users
CLI Example :
. . code - block : : bash
salt ' * ' ssh . auth _ keys
salt ' * ' ssh . auth _ keys root
salt ' * ' ssh . auth _ keys user = root
salt ' * ' ssh . auth _... | if not user :
user = __salt__ [ 'user.list_users' ] ( )
old_output_when_one_user = False
if not isinstance ( user , list ) :
user = [ user ]
old_output_when_one_user = True
keys = { }
for u in user :
full = None
try :
full = _get_config_file ( u , config )
except CommandExecutionError :
... |
def log_exception ( self , typ : "Optional[Type[BaseException]]" , value : Optional [ BaseException ] , tb : Optional [ TracebackType ] , ) -> None :
"""Override to customize logging of uncaught exceptions .
By default logs instances of ` HTTPError ` as warnings without
stack traces ( on the ` ` tornado . gener... | if isinstance ( value , HTTPError ) :
if value . log_message :
format = "%d %s: " + value . log_message
args = [ value . status_code , self . _request_summary ( ) ] + list ( value . args )
gen_log . warning ( format , * args )
else :
app_log . error ( # type : ignore
"Uncaught except... |
def draw_line ( self , data , coordinates , style , label , mplobj = None ) :
"""Draw a line . By default , draw the line via the draw _ path ( ) command .
Some renderers might wish to override this and provide more
fine - grained behavior .
In matplotlib , lines are generally created via the plt . plot ( ) c... | pathcodes = [ 'M' ] + ( data . shape [ 0 ] - 1 ) * [ 'L' ]
pathstyle = dict ( facecolor = 'none' , ** style )
pathstyle [ 'edgecolor' ] = pathstyle . pop ( 'color' )
pathstyle [ 'edgewidth' ] = pathstyle . pop ( 'linewidth' )
self . draw_path ( data = data , coordinates = coordinates , pathcodes = pathcodes , style = p... |
def save ( self ) :
"""Save the state to the JSON file in the config dir .""" | logger . debug ( "Save the GUI state to `%s`." , self . path )
_save_json ( self . path , { k : v for k , v in self . items ( ) if k not in ( 'config_dir' , 'name' ) } ) |
async def clean_up_clients_async ( self ) :
"""Resets the pump swallows all exceptions .""" | if self . partition_receiver :
if self . eh_client :
await self . eh_client . stop_async ( )
self . partition_receiver = None
self . partition_receive_handler = None
self . eh_client = None |
def get_json_argument ( self , name , default = None ) :
"""Find and return the argument with key ' name '
from JSON request data . Similar to Tornado ' s get _ argument ( ) method .
: param str name : The name of the json key you want to get the value for
: param bool default : The default value if nothing i... | if default is None :
default = self . _ARG_DEFAULT
if not self . request . arguments :
self . load_json ( )
if name not in self . request . arguments :
if default is self . _ARG_DEFAULT :
msg = "Missing argument '%s'" % name
self . logger . debug ( msg )
self . raise_error ( 400 , ms... |
def moderate_view ( self , request , object_id , extra_context = None ) :
"""Handles moderate object tool through a somewhat hacky changelist view
whose queryset is altered via CommentAdmin . get _ changelist to only list
comments for the object under review .""" | opts = self . model . _meta
app_label = opts . app_label
view = CommentAdmin ( model = Comment , admin_site = self . admin_site )
view . list_filter = ( )
view . list_display = ( 'comment_text' , 'moderator_reply' , '_user' , 'submit_date' , )
model = self . model
obj = get_object_or_404 ( model , pk = unquote ( object... |
def add_timeline_callback ( self , timeline_events , callback ) :
"""Register a callback for a specific timeline event .""" | if not timeline_events :
return False
if not isinstance ( timeline_events , ( tuple , list ) ) :
timeline_events = [ timeline_events ]
for timeline_event in timeline_events :
if not isinstance ( timeline_event , dict ) :
raise AbodeException ( ( ERROR . EVENT_CODE_MISSING ) )
event_code = timeli... |
def get_nt_system_uid ( ) :
"""Get the MachineGuid from
HKEY _ LOCAL _ MACHINE \ Software \ Microsoft \ Cryptography \ MachineGuid""" | try :
import _winreg as winreg
except ImportError :
import winreg
lm = winreg . ConnectRegistry ( None , winreg . HKEY_LOCAL_MACHINE )
try :
key = winreg . OpenKey ( lm , r"Software\Microsoft\Cryptography" )
try :
return winreg . QueryValueEx ( key , "MachineGuid" ) [ 0 ]
finally :
k... |
def _g_2 ( self ) :
"""omega2 < omega < omega3""" | return 3 / ( self . _vertices_omegas [ 3 ] - self . _vertices_omegas [ 0 ] ) * ( self . _f ( 1 , 2 ) * self . _f ( 2 , 0 ) + self . _f ( 2 , 1 ) * self . _f ( 1 , 3 ) ) |
def r_oauth_authorized ( self ) :
"""Route for OAuth2 Authorization callback
: return : { " template " }""" | resp = self . authobj . authorized_response ( )
if resp is None :
return 'Access denied: reason=%s error=%s' % ( request . args [ 'error' ] , request . args [ 'error_description' ] )
session [ 'oauth_token' ] = ( resp [ 'access_token' ] , '' )
user = self . authobj . get ( 'user' )
# # TODO this is too specific to ... |
def get_cost_per_mol ( self , comp ) :
"""Get best estimate of minimum cost / mol based on known data
Args :
comp :
Composition as a pymatgen . core . structure . Composition
Returns :
float of cost / mol""" | comp = comp if isinstance ( comp , Composition ) else Composition ( comp )
decomp = self . get_lowest_decomposition ( comp )
return sum ( k . energy_per_atom * v * comp . num_atoms for k , v in decomp . items ( ) ) |
def build_db_cmd ( self , fname ) :
"""Return database format / build command""" | return self . funcs . db_func ( fname , self . outdir , self . exes . format_exe ) [ 0 ] |
def process_data ( self ) :
"""Attempt to extract a report from the current data stream contents
Returns :
bool : True if further processing is required and process _ data should be
called again .""" | further_processing = False
if self . state == self . WaitingForReportType and len ( self . raw_data ) > 0 :
self . current_type = self . raw_data [ 0 ]
try :
self . current_header_size = self . calculate_header_size ( self . current_type )
self . state = self . WaitingForReportHeader
fur... |
def _get_kind_and_names ( attributes ) :
"""Gets kind and possible names for : tl : ` DocumentAttribute ` .""" | kind = 'document'
possible_names = [ ]
for attr in attributes :
if isinstance ( attr , types . DocumentAttributeFilename ) :
possible_names . insert ( 0 , attr . file_name )
elif isinstance ( attr , types . DocumentAttributeAudio ) :
kind = 'audio'
if attr . performer and attr . title :
... |
def flip ( f ) :
"""Flip the order of positonal arguments of given function .""" | ensure_callable ( f )
result = lambda * args , ** kwargs : f ( * reversed ( args ) , ** kwargs )
functools . update_wrapper ( result , f , ( '__name__' , '__module__' ) )
return result |
def ticket_satisfaction_rating_create ( self , ticket_id , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / satisfaction _ ratings # create - a - satisfaction - rating" | api_path = "/api/v2/tickets/{ticket_id}/satisfaction_rating.json"
api_path = api_path . format ( ticket_id = ticket_id )
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def get_member_ideas ( self , * args , ** kwargs ) :
""": allowed _ param : ' memberId '
: pagination _ param : ' page _ number ' , ' page _ size '""" | return bind_api ( api = self , path = '/members/{memberId}/ideas' , payload_type = 'idea' , payload_list = True , allowed_param = [ 'memberId' ] , pagination_param = [ 'page_number' , 'page_size' ] ) ( * args , ** kwargs ) |
def IntegerSum ( input_vertex : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex :
"""Performs a sum across all dimensions
: param input _ vertex : the vertex to have its values summed""" | return Integer ( context . jvm_view ( ) . IntegerSumVertex , label , cast_to_integer_vertex ( input_vertex ) ) |
def get_nodes ( self , request ) :
"""Generates the nodelist
: param request :
: return : list of nodes""" | nodes = [ ]
language = get_language_from_request ( request , check_path = True )
current_site = get_current_site ( request )
page_site = self . instance . node . site
if self . instance and page_site != current_site :
return [ ]
categories_menu = False
posts_menu = False
config = False
if self . instance :
if n... |
def _format_base_path ( self , api_name ) :
"""Format the base path name .""" | name = self . app_name
if self . app_name != api_name :
name = '{0}-{1}' . format ( self . app_name , api_name )
return name |
def to_json ( self , value ) :
"""Subclasses should override this method for JSON encoding .""" | if not self . is_valid ( value ) :
raise ex . SerializeException ( 'Invalid value: {}' . format ( value ) )
return value |
def _to_dict ( self ) :
'''Returns a dictionary representation of this object''' | return dict ( minimum = self . minimum . _to_dict ( ) , maximum = self . maximum . _to_dict ( ) ) |
def __prepare_raw_data ( self ) :
"Format internal _ _ raw _ data storage according to usages setting" | # pre - parsed data should exist
if not self . __hid_object . ptr_preparsed_data :
raise HIDError ( "HID object close or unable to request pre parsed " "report data" )
# make sure pre - memory allocation already done
self . __alloc_raw_data ( )
try :
HidStatus ( hid_dll . HidP_InitializeReportForID ( self . __r... |
def _getOccurs ( self , e ) :
'''return a 3 item tuple''' | minOccurs = maxOccurs = '1'
nillable = True
return minOccurs , maxOccurs , nillable |
def compareTaggers ( model1 , model2 , string_list , module_name ) :
"""Compare two models . Given a list of strings , prints out tokens & tags
whenever the two taggers parse a string differently . This is for spot - checking models
: param tagger1 : a . crfsuite filename
: param tagger2 : another . crfsuite ... | module = __import__ ( module_name )
tagger1 = pycrfsuite . Tagger ( )
tagger1 . open ( module_name + '/' + model1 )
tagger2 = pycrfsuite . Tagger ( )
tagger2 . open ( module_name + '/' + model2 )
count_discrepancies = 0
for string in string_list :
tokens = module . tokenize ( string )
if tokens :
featur... |
def apply_mflist_budget_obs ( list_filename , flx_filename = "flux.dat" , vol_filename = "vol.dat" , start_datetime = "1-1-1970" ) :
"""process a MODFLOW list file to extract flux and volume water budget entries .
Parameters
list _ filename : str
the modflow list file
flx _ filename : str
the name of the ... | try :
import flopy
except Exception as e :
raise Exception ( "error import flopy: {0}" . format ( str ( e ) ) )
mlf = flopy . utils . MfListBudget ( list_filename )
flx , vol = mlf . get_dataframes ( start_datetime = start_datetime , diff = True )
flx . to_csv ( flx_filename , sep = ' ' , index_label = "datetim... |
def autoremove ( list_only = False , purge = False ) :
'''. . versionadded : : 2015.5.0
Remove packages not required by another package using ` ` apt - get
autoremove ` ` .
list _ only : False
Only retrieve the list of packages to be auto - removed , do not actually
perform the auto - removal .
purge : ... | cmd = [ ]
if list_only :
ret = [ ]
cmd . extend ( [ 'apt-get' , '--assume-no' ] )
if purge :
cmd . append ( '--purge' )
cmd . append ( 'autoremove' )
out = _call_apt ( cmd , ignore_retcode = True ) [ 'stdout' ]
found = False
for line in out . splitlines ( ) :
if found is True... |
def do_set_device ( self , args ) :
"""Set the PLM OS device .
Device defaults to / dev / ttyUSB0
Usage :
set _ device device
Arguments :
device : Required - INSTEON PLM device""" | params = args . split ( )
device = None
try :
device = params [ 0 ]
except IndexError :
_LOGGING . error ( 'Device name required.' )
self . do_help ( 'set_device' )
if device :
self . tools . device = device |
def until_synced ( self , timeout = None ) :
"""Return a tornado Future ; resolves when all subordinate clients are synced""" | futures = [ r . until_synced ( timeout ) for r in dict . values ( self . children ) ]
yield tornado . gen . multi ( futures , quiet_exceptions = tornado . gen . TimeoutError ) |
def sample_prob ( probs , rand ) :
"""Get samples from a tensor of probabilities .
: param probs : tensor of probabilities
: param rand : tensor ( of the same shape as probs ) of random values
: return : binary sample of probabilities""" | return tf . nn . relu ( tf . sign ( probs - rand ) ) |
def _create_hashes ( self , count ) :
"""Breaks up our hash into slots , so we can pull them out later .
Essentially , it splits our SHA / MD5 / etc into X parts .""" | for i in range ( 0 , count ) : # Get 1 / numblocks of the hash
blocksize = int ( len ( self . hexdigest ) / count )
currentstart = ( 1 + i ) * blocksize - blocksize
currentend = ( 1 + i ) * blocksize
self . hasharray . append ( int ( self . hexdigest [ currentstart : currentend ] , 16 ) )
# Workaround f... |
def image_from_name ( name , images ) :
"""Return an image from a list of images . If the name is an exact
match , return the last exactly matching image . Otherwise , sort
images by ' natural ' order , using decorate - sort - undecorate , and
return the largest .
see :
http : / / code . activestate . com... | prefixed_images = [ i for i in images if i . name . startswith ( name ) ]
if name in [ i . name for i in prefixed_images ] :
return [ i for i in prefixed_images if i . name == name ] [ - 1 ]
decorated = sorted ( [ ( int ( re . search ( '\d+' , i . name ) . group ( 0 ) ) , i ) for i in prefixed_images ] )
return [ i... |
def get_ytvideos ( query , ilogger ) :
"""Gets either a list of videos from a playlist or a single video , using the
first result of a YouTube search
Args :
query ( str ) : The YouTube search query
ilogger ( logging . logger ) : The logger to log API calls to
Returns :
queue ( list ) : The items obtaine... | queue = [ ]
# Search YouTube
search_result = ytdiscoveryapi . search ( ) . list ( q = query , part = "id,snippet" , maxResults = 1 , type = "video,playlist" ) . execute ( )
if not search_result [ "items" ] :
return [ ]
# Get video / playlist title
title = search_result [ "items" ] [ 0 ] [ "snippet" ] [ "title" ]
il... |
def contains ( self , key ) :
"Exact matching ." | index = self . follow_bytes ( key , self . ROOT )
if index is None :
return False
return self . has_value ( index ) |
def libs ( package , static = False ) :
"""Return the LDFLAGS string returned by pkg - config .
The static specifier will also include libraries for static linking ( i . e . ,
includes any private libraries ) .""" | _raise_if_not_exists ( package )
return _query ( package , * _build_options ( '--libs' , static = static ) ) |
def execute_by_options ( args ) :
"""execute by argument dictionary
Args :
args ( dict ) : command line argument dictionary""" | if args [ 'subcommand' ] == 'sphinx' :
s = Sphinx ( proj_info )
if args [ 'quickstart' ] :
s . quickstart ( )
elif args [ 'gen_code_api' ] :
s . gen_code_api ( )
elif args [ 'rst2html' ] :
s . rst2html ( )
pass
elif args [ 'subcommand' ] == 'offline_dist' :
pod = PyOfflin... |
def cudnnGetConvolutionForwardWorkspaceSize ( handle , srcDesc , wDesc , convDesc , destDesc , algo ) :
"""This function returns the amount of GPU memory workspace the user needs
to allocate to be able to call cudnnConvolutionForward with the specified algorithm .
Parameters
handle : cudnnHandle
Handle to a... | sizeInBytes = ctypes . c_size_t ( )
status = _libcudnn . cudnnGetConvolutionForwardWorkspaceSize ( handle , srcDesc , wDesc , convDesc , destDesc , algo , ctypes . byref ( sizeInBytes ) )
cudnnCheckStatus ( status )
return sizeInBytes |
def check_handle_syntax ( string ) :
'''Checks the syntax of a handle without an index ( are prefix
and suffix there , are there too many slashes ? ) .
: string : The handle without index , as string prefix / suffix .
: raise : : exc : ` ~ b2handle . handleexceptions . handleexceptions . HandleSyntaxError `
... | expected = 'prefix/suffix'
try :
arr = string . split ( '/' )
except AttributeError :
raise handleexceptions . HandleSyntaxError ( msg = 'The provided handle is None' , expected_syntax = expected )
if len ( arr ) < 2 :
msg = 'No slash'
raise handleexceptions . HandleSyntaxError ( msg = msg , handle = st... |
def _cut_hypernodes ( hypergraph ) :
"""Return the cut - nodes of the given hypergraph .
@ type hypergraph : hypergraph
@ param hypergraph : Hypergraph
@ rtype : list
@ return : List of cut - nodes .""" | nodes_ = cut_nodes ( hypergraph . graph )
nodes = [ ]
for each in nodes_ :
if ( each [ 1 ] == 'n' ) :
nodes . append ( each [ 0 ] )
return nodes |
def main ( ) :
"""Main entry point for the script . Create a parser , process the command line ,
and run it""" | parser = cli . Cli ( )
parser . parse ( sys . argv [ 1 : ] )
return parser . run ( ) |
def get ( self , key , lang = None ) :
"""Returns triple related to this node . Can filter on lang
: param key : Predicate of the triple
: param lang : Language of the triple if applicable
: rtype : Literal or BNode or URIRef""" | if lang is not None :
for o in self . graph . objects ( self . asNode ( ) , key ) :
if o . language == lang :
yield o
else :
for o in self . graph . objects ( self . asNode ( ) , key ) :
yield o |
def _make_request ( self , type , path , args , noRetry = False ) :
"""Make a request to Blot ' re .
Attempts to reply the request if it fails due to an expired
access token .""" | response = getattr ( requests , type ) ( path , headers = self . _add_auth_headers ( _JSON_HEADERS ) , ** args )
if response . status_code == 200 or response . status_code == 201 :
return response . json ( )
elif not noRetry and self . _is_expired_response ( response ) and 'refresh_token' in self . creds :
try ... |
def payload ( self ) :
"""Renders the resource payload .
: returns : a dict representing the object to be used as payload for a request""" | payload = { 'type' : self . resource_type ( ) , 'attributes' : self . attributes }
if self . id :
payload [ 'id' ] = self . id
return payload |
def putCtrlConf ( self , eleobj , ctrlkey , val , type = 'raw' ) :
"""put the value to control PV field
: param eleobj : element object in lattice
: param ctrlkey : element control property , PV name
: param val : new value for ctrlkey
: param type : set in ' raw ' or ' real ' mode , ' raw ' by default
' ... | if ctrlkey in eleobj . ctrlkeys :
if type == 'raw' :
newval = val
else : # val should be translated
newval = eleobj . unitTrans ( val , direction = '-' )
epics . caput ( eleobj . ctrlinfo [ ctrlkey ] [ 'pv' ] , newval )
return True
else :
return False |
def PDBasXMLwithSymwithPolarH ( self , id ) :
"""Adds Hydrogen Atoms to a Structure .""" | print _WARNING
# Protonated Structure in XML Format
h_s_xml = urllib . urlopen ( "http://www.cmbi.ru.nl/wiwsd/rest/PDBasXMLwithSymwithPolarH/id/" + id )
self . raw = h_s_xml
p = self . parser
h_s_smcra = p . read ( h_s_xml , 'WHATIF_Output' )
return h_s_smcra |
async def RelationById ( self , relation_ids ) :
'''relation _ ids : typing . Sequence [ int ]
Returns - > typing . Sequence [ ~ RelationResult ]''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'Uniter' , request = 'RelationById' , version = 5 , params = _params )
_params [ 'relation-ids' ] = relation_ids
reply = await self . rpc ( msg )
return reply |
def _load_words ( self ) :
"""Loads the list of profane words from file .""" | with open ( self . _words_file , 'r' ) as f :
self . _censor_list = [ line . strip ( ) for line in f . readlines ( ) ] |
def get ( self , keyword ) :
"""Return the element of the list after the given keyword .
Parameters
keyword : str
The keyword parameter to find in the list .
Putting a colon before the keyword is optional , if no colon is
given , it is added automatically ( e . g . " keyword " will be found as
" : keywo... | if not keyword . startswith ( ':' ) :
keyword = ':' + keyword
for i , s in enumerate ( self . data ) :
if s . to_string ( ) . upper ( ) == keyword . upper ( ) :
if i < len ( self . data ) - 1 :
return self . data [ i + 1 ]
else :
return None
return None |
def GetCacheSize ( self ) :
"""Determines the size of the uncompressed cached data .
Returns :
int : number of cached bytes .""" | if not self . _cache_start_offset or not self . _cache_end_offset :
return 0
return self . _cache_end_offset - self . _cache_start_offset |
def get_num_commenters ( self , item ) :
"""Get the number of unique people who commented on the issue / pr""" | commenters = [ comment [ 'user' ] [ 'login' ] for comment in item [ 'comments_data' ] ]
return len ( set ( commenters ) ) |
def __init ( self ) :
"""gets the properties for the site""" | url = "%s/%s.json" % ( self . _url , self . _itemId )
params = { "f" : "json" }
json_dict = self . _get ( url , params , securityHandler = self . _securityHandler , proxy_port = self . _proxy_port , proxy_url = self . _proxy_url )
self . _json_dict = json_dict
self . _json = json . dumps ( self . _json_dict )
setattr (... |
def _print_sql_with_error ( self , sql , error_line ) :
"""Writes a SQL statement with an syntax error to the output . The line where the error occurs is highlighted .
: param str sql : The SQL statement .
: param int error _ line : The line where the error occurs .""" | if os . linesep in sql :
lines = sql . split ( os . linesep )
digits = math . ceil ( math . log ( len ( lines ) + 1 , 10 ) )
i = 1
for line in lines :
if i == error_line :
self . _io . text ( '<error>{0:{width}} {1}</error>' . format ( i , line , width = digits , ) )
else :
... |
def create_equipamento_roteiro ( self ) :
"""Get an instance of equipamento _ roteiro services facade .""" | return EquipamentoRoteiro ( self . networkapi_url , self . user , self . password , self . user_ldap ) |
def tls_session_update ( self , msg_str ) :
"""Either for parsing or building , we store the client _ random
along with the raw string representing this handshake message .""" | super ( TLSClientHello , self ) . tls_session_update ( msg_str )
self . tls_session . advertised_tls_version = self . version
self . random_bytes = msg_str [ 10 : 38 ]
self . tls_session . client_random = ( struct . pack ( '!I' , self . gmt_unix_time ) + self . random_bytes )
if self . ext :
for e in self . ext :
... |
def create ( self ) :
"""Create item under file system with its path .
Returns :
True if its path does not exist , False otherwise .""" | if os . path . isfile ( self . path ) :
if not os . path . exists ( self . path ) :
with open ( self . path , 'w' ) as fileobj :
fileobj . write ( '' )
else :
os . makedirs ( self . path ) |
def delete_asset_content ( self , asset_content_id = None ) :
"""Deletes content from an ` ` Asset ` ` .
: param asset _ content _ id : the ` ` Id ` ` of the ` ` AssetContent ` `
: type asset _ content _ id : ` ` osid . id . Id ` `
: raise : ` ` NotFound ` ` - - ` ` asset _ content _ id ` ` is not found
: r... | if asset_content_id is None :
raise NullArgument ( )
asset = None
for a in AssetLookupSession ( self . _repository_id , proxy = self . _proxy , runtime = self . _runtime ) . get_assets ( ) :
i = 0
# might want to set plenary view
# to assure ordering ?
for ac in a . get_asset_contents ( ) :
... |
def partial_derivative_scalar ( self , U , V , y = 0 ) :
"""Compute partial derivative : math : ` C ( u | v ) ` of cumulative density of single values .""" | self . check_fit ( )
X = np . column_stack ( ( U , V ) )
return self . partial_derivative ( X , y ) |
def _view ( self , filepath , format ) :
"""Start the right viewer based on file format and platform .""" | methodnames = [ '_view_%s_%s' % ( format , backend . PLATFORM ) , '_view_%s' % backend . PLATFORM , ]
for name in methodnames :
view_method = getattr ( self , name , None )
if view_method is not None :
break
else :
raise RuntimeError ( '%r has no built-in viewer support for %r ' 'on %r platform' % (... |
def parse_failed_targets ( test_registry , junit_xml_path , error_handler ) :
"""Parses junit xml reports and maps targets to the set of individual tests that failed .
Targets with no failed tests are omitted from the returned mapping and failed tests with no
identifiable owning target are keyed under ` None ` ... | failed_targets = defaultdict ( set )
def parse_junit_xml_file ( path ) :
try :
xml = XmlParser . from_file ( path )
failures = int ( xml . get_attribute ( 'testsuite' , 'failures' ) )
errors = int ( xml . get_attribute ( 'testsuite' , 'errors' ) )
if failures or errors :
... |
def initialize_eigenanatomy ( initmat , mask = None , initlabels = None , nreps = 1 , smoothing = 0 ) :
"""InitializeEigenanatomy is a helper function to initialize sparseDecom
and sparseDecom2 . Can be used to estimate sparseness parameters per
eigenvector . The user then only chooses nvecs and optional
regu... | if isinstance ( initmat , iio . ANTsImage ) : # create initmat from each of the unique labels
if mask is not None :
selectvec = mask > 0
else :
selectvec = initmat > 0
initmatvec = initmat [ selectvec ]
if initlabels is None :
ulabs = np . sort ( np . unique ( initmatvec ) )
... |
def atlas_get_peer ( peer_hostport , peer_table = None ) :
"""Get the given peer ' s info""" | ret = None
with AtlasPeerTableLocked ( peer_table ) as ptbl :
ret = ptbl . get ( peer_hostport , None )
return ret |
async def request_offline_members ( self , * guilds ) :
r"""| coro |
Requests previously offline members from the guild to be filled up
into the : attr : ` . Guild . members ` cache . This function is usually not
called . It should only be used if you have the ` ` fetch _ offline _ members ` `
parameter set... | if any ( not g . large or g . unavailable for g in guilds ) :
raise InvalidArgument ( 'An unavailable or non-large guild was passed.' )
await self . _connection . request_offline_members ( guilds ) |
def geometry_linestring ( lat , lon , elev ) :
"""GeoJSON Linestring . Latitude and Longitude have 2 values each .
: param list lat : Latitude values
: param list lon : Longitude values
: return dict :""" | logger_excel . info ( "enter geometry_linestring" )
d = OrderedDict ( )
coordinates = [ ]
temp = [ "" , "" ]
# Point type , Matching pairs .
if lat [ 0 ] == lat [ 1 ] and lon [ 0 ] == lon [ 1 ] :
logger_excel . info ( "matching geo coordinate" )
lat . pop ( )
lon . pop ( )
d = geometry_point ( lat , lon... |
def AskFileForOpen ( message = None , typeList = None , version = None , defaultLocation = None , dialogOptionFlags = None , location = None , clientName = None , windowTitle = None , actionButtonLabel = None , cancelButtonLabel = None , preferenceKey = None , popupExtension = None , eventProc = None , previewProc = No... | return psidialogs . ask_file ( message = message ) |
def detag_string ( self , string ) :
"""Extracts tags from string .
returns ( string , list ) where
string : string has tags replaced by indices ( < BR > . . . = > < 0 > , < 1 > , < 2 > , etc . )
list : list of the removed tags ( ' < BR > ' , ' < I > ' , ' < / I > ' )""" | counter = itertools . count ( 0 )
count = lambda m : '<%s>' % next ( counter )
tags = self . tag_pattern . findall ( string )
tags = [ '' . join ( tag ) for tag in tags ]
( new , nfound ) = self . tag_pattern . subn ( count , string )
if len ( tags ) != nfound :
raise Exception ( 'tags dont match:' + string )
retur... |
def collides ( self , other ) :
"""Returns collision with axis aligned rect""" | angle = self . angle
width = self . width
height = self . height
if angle == 0 :
return other . collides ( Rect ( - 0.5 * width , - 0.5 * height , width , height ) )
# Phase 1
# * Form bounding box on tilted rectangle P .
# * Check whether bounding box and other intersect .
# * If not , then self and other do not i... |
def delete ( self , email_to_addresses = None , email_cc_addresses = None , email_insert = None ) :
"""Delete this storage volume on the HMC , and optionally send emails to
storage administrators requesting deletion of the storage volume on the
storage subsystem and cleanup of any resources related to the stora... | volreq_obj = { 'operation' : 'delete' , 'element-uri' : self . uri , }
body = { 'storage-volumes' : [ volreq_obj ] , }
if email_to_addresses :
body [ 'email-to-addresses' ] = email_to_addresses
if email_cc_addresses :
body [ 'email-cc-addresses' ] = email_cc_addresses
if email_insert :
body ... |
def make_gaussian_kernel ( sigma , npix = 501 , cdelt = 0.01 , xpix = None , ypix = None ) :
"""Make kernel for a 2D gaussian .
Parameters
sigma : float
Standard deviation in degrees .""" | sigma /= cdelt
def fn ( t , s ) :
return 1. / ( 2 * np . pi * s ** 2 ) * np . exp ( - t ** 2 / ( s ** 2 * 2.0 ) )
dxy = make_pixel_distance ( npix , xpix , ypix )
k = fn ( dxy , sigma )
k /= ( np . sum ( k ) * np . radians ( cdelt ) ** 2 )
return k |
def check_lock ( i ) :
"""Input : {
path - path to be locked
( unlock _ uid ) - UID of the lock to release it
Output : {
return - return code = 0 , if successful
= 32 , lock UID is not matching
> 0 , if error
( error ) - error text if return > 0""" | p = i [ 'path' ]
uuid = i . get ( 'unlock_uid' , '' )
pl = os . path . join ( p , cfg [ 'subdir_ck_ext' ] , cfg [ 'file_for_lock' ] )
luid = ''
if os . path . isfile ( pl ) :
import time
# Read lock file
try :
f = open ( pl )
luid = f . readline ( ) . strip ( )
exp = float ( f . read... |
def process ( self , context , internal_response ) :
"""Manage consent and attribute filtering
: type context : satosa . context . Context
: type internal _ response : satosa . internal . InternalData
: rtype : satosa . response . Response
: param context : response context
: param internal _ response : t... | consent_state = context . state [ STATE_KEY ]
internal_response . attributes = self . _filter_attributes ( internal_response . attributes , consent_state [ "filter" ] )
id_hash = self . _get_consent_id ( internal_response . requester , internal_response . subject_id , internal_response . attributes )
try : # Check if c... |
def reset ( self , label = None ) :
"""clears all measurements , allowing the object to be reused
Args :
label ( str , optional ) : optionally change the label
Example :
> > > from timerit import Timerit
> > > import math
> > > ti = Timerit ( num = 10 , unit = ' us ' , verbose = True )
> > > _ = ti . ... | if label :
self . label = label
self . times = [ ]
self . n_loops = None
self . total_time = None
return self |
def load ( handle ) :
"""Loads a module from a handle .
Currently this method only works with Tensorflow 2 . x and can only load modules
created by calling tensorflow . saved _ model . save ( ) . The method works in both
eager and graph modes .
Depending on the type of handle used , the call may involve dow... | if hasattr ( tf_v1 . saved_model , "load_v2" ) :
module_handle = resolve ( handle )
return tf_v1 . saved_model . load_v2 ( module_handle )
else :
raise NotImplementedError ( "hub.load() is not implemented for TF < 1.14.x, " "Current version: %s" , tf . __version__ ) |
def real_time_scheduling ( self , availability , oauth , event , target_calendars = ( ) ) :
"""Generates an real time scheduling link to start the OAuth process with
an event to be automatically upserted
: param dict availability : - A dict describing the availability details for the event :
: participants - ... | args = { 'oauth' : oauth , 'event' : event , 'target_calendars' : target_calendars }
if availability :
options = { }
options [ 'participants' ] = self . map_availability_participants ( availability . get ( 'participants' , None ) )
options [ 'required_duration' ] = self . map_availability_required_duration ... |
def to_scaled_dtype ( val ) :
"""Parse * val * to return a dtype .""" | res = [ ]
for i in val :
if i [ 1 ] . startswith ( "S" ) :
res . append ( ( i [ 0 ] , i [ 1 ] ) + i [ 2 : - 1 ] )
else :
try :
res . append ( ( i [ 0 ] , i [ - 1 ] . dtype ) + i [ 2 : - 1 ] )
except AttributeError :
res . append ( ( i [ 0 ] , type ( i [ - 1 ] ) ) ... |
def threshold_monitor_hidden_threshold_monitor_Cpu_limit ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
threshold_monitor_hidden = ET . SubElement ( config , "threshold-monitor-hidden" , xmlns = "urn:brocade.com:mgmt:brocade-threshold-monitor" )
threshold_monitor = ET . SubElement ( threshold_monitor_hidden , "threshold-monitor" )
Cpu = ET . SubElement ( threshold_monitor , "Cpu" )
limi... |
def GET_blockchain_num_names ( self , path_info , blockchain_name ) :
"""Handle GET / blockchains / : blockchainID / name _ count
Takes ` all = true ` to include expired names
Reply with the number of names on this blockchain""" | if blockchain_name != 'bitcoin' : # not supported
self . _reply_json ( { 'error' : 'Unsupported blockchain' } , status_code = 404 )
return
include_expired = False
qs_values = path_info [ 'qs_values' ]
if qs_values . get ( 'all' , '' ) . lower ( ) in [ '1' , 'true' ] :
include_expired = True
blockstackd_url ... |
def zen ( self ) :
"""Returns a quote from the Zen of GitHub . Yet another API Easter Egg
: returns : str""" | url = self . _build_url ( 'zen' )
resp = self . _get ( url )
return resp . content if resp . status_code == 200 else '' |
def set_terminal_title ( title , kernel32 = None ) :
"""Set the terminal title .
: param title : The title to set ( string , unicode , bytes accepted ) .
: param kernel32 : Optional mock kernel32 object . For testing .
: return : If title changed successfully ( Windows only , always True on Linux / OSX ) .
... | try :
title_bytes = title . encode ( 'utf-8' )
except AttributeError :
title_bytes = title
if IS_WINDOWS :
kernel32 = kernel32 or ctypes . windll . kernel32
try :
is_ascii = all ( ord ( c ) < 128 for c in title )
# str / unicode .
except TypeError :
is_ascii = all ( c < 128 f... |
def get_restart_freeze ( ) :
'''Displays whether ' restart on freeze ' is on or off if supported
: return : A string value representing the " restart on freeze " settings
: rtype : string
CLI Example :
. . code - block : : bash
salt ' * ' power . get _ restart _ freeze''' | ret = salt . utils . mac_utils . execute_return_result ( 'systemsetup -getrestartfreeze' )
return salt . utils . mac_utils . validate_enabled ( salt . utils . mac_utils . parse_return ( ret ) ) == 'on' |
def activate_axes ( self , axes ) :
'''Sets motors to a high current , for when they are moving
and / or must hold position
Activating XYZABC axes before both HOMING and MOVING
axes :
String containing the axes to set to high current ( eg : ' XYZABC ' )''' | axes = '' . join ( set ( axes ) & set ( AXES ) - set ( DISABLE_AXES ) )
active_currents = { ax : self . _active_current_settings [ 'now' ] [ ax ] for ax in axes if self . _active_axes [ ax ] is False }
if active_currents :
self . _save_current ( active_currents , axes_active = True ) |
def hover ( self , target = None ) :
"""Moves the cursor to the target location""" | if target is None :
target = self . _lastMatch or self
# Whichever one is not None
target_location = None
if isinstance ( target , Pattern ) :
target_location = self . find ( target ) . getTarget ( )
elif isinstance ( target , basestring ) :
target_location = self . find ( target ) . getTarget ( )
elif ... |
def packages ( self , name = None , memory = None , disk = None , swap = None , version = None , vcpus = None , group = None ) :
"""GET / : login / packages
: param name : the label associated with the resource package
: type name : : py : class : ` basestring `
: param memory : amount of RAM ( in MiB ) that ... | params = { }
if name :
params [ 'name' ] = name
if memory :
params [ 'memory' ] = memory
if disk :
params [ 'disk' ] = disk
if swap :
params [ 'swap' ] = swap
if version :
params [ 'version' ] = version
if vcpus :
params [ 'vcpus' ] = vcpus
if group :
params [ 'group' ] = group
j , _ = self ... |
def process_lipisha_payment ( request ) :
"""Handle payment received and respond with a dictionary""" | log . debug ( request . POST )
schema = LipishaInitiateSchema
api_type = request . POST . get ( 'api_type' )
if api_type == TYPE_ACKNOWLEDGE :
schema = LipishaAcknowledgeSchema
form = Form ( request , schema ( ) )
transaction_status_code = STATUS_SUCCESS
transaction_status = 'Processed'
transaction_status_descripti... |
def node_transmit ( node_id ) :
"""Transmit to another node .
The sender ' s node id must be specified in the url .
As with node . transmit ( ) the key parameters are what and to _ whom . However ,
the values these accept are more limited than for the back end due to the
necessity of serialization .
If wh... | exp = Experiment ( session )
what = request_parameter ( parameter = "what" , optional = True )
to_whom = request_parameter ( parameter = "to_whom" , optional = True )
# check the node exists
node = models . Node . query . get ( node_id )
if node is None :
return error_response ( error_type = "/node/transmit, node d... |
def enable_ap_port ( self , apid , port ) :
"""开启接入点端口
开启临时关闭的接入点端口 , 仅对公网域名 , 公网ip有效 。
Args :
- apid : 接入点ID
- port : 要设置的端口号
Returns :
返回一个tuple对象 , 其格式为 ( < result > , < ResponseInfo > )
- result 成功返回空dict { } , 失败返回 { " error " : " < errMsg string > " }
- ResponseInfo 请求的Response信息""" | url = '{0}/v3/aps/{1}/{2}/enable' . format ( self . host , apid , port )
return self . __post ( url ) |
def delete ( self , ** kwargs ) :
"""Deletes a member from an unmanaged license pool
You need to be careful with this method . When you use it , and it
succeeds on the remote BIG - IP , the configuration of the BIG - IP
will be reloaded . During this process , you will not be able to
access the REST interfa... | if 'uuid' not in kwargs :
kwargs [ 'uuid' ] = str ( self . uuid )
requests_params = self . _handle_requests_params ( kwargs )
kwargs = self . _check_for_python_keywords ( kwargs )
kwargs = self . _prepare_request_json ( kwargs )
delete_uri = self . _meta_data [ 'uri' ]
session = self . _meta_data [ 'bigip' ] . _met... |
def _font ( size ) :
"""Returns a PIL ImageFont instance .
: param size : size of the avatar , in pixels""" | # path = ' / usr / share / fonts / wenquanyi / wqy - microhei / wqy - microhei . ttc '
path = os . path . join ( os . path . dirname ( __file__ ) , 'data' , "wqy-microhei.ttc" )
return ImageFont . truetype ( path , size = int ( 0.65 * size ) , index = 0 ) |
def organization_create ( self , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / organizations # create - organization" | api_path = "/api/v2/organizations.json"
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def create ( model_config , model , source , storage , phases , callbacks = None , restart = True ) :
"""Vel factory function""" | return PhaseTrainCommand ( model_config = model_config , model_factory = model , source = source , storage = storage , phases = phases , callbacks = callbacks , restart = restart ) |
def get_resource_by_id ( resource_id , api_version , extract_value = None ) :
'''Get an AzureARM resource by id''' | ret = { }
try :
resconn = get_conn ( client_type = 'resource' )
resource_query = resconn . resources . get_by_id ( resource_id = resource_id , api_version = api_version )
resource_dict = resource_query . as_dict ( )
if extract_value is not None :
ret = resource_dict [ extract_value ]
else :
... |
def get_config ( self ) :
"""function to get current configuration""" | config = { 'location' : self . location , 'language' : self . language , 'topic' : self . topic , }
return config |
def set_logyticks_for_all ( self , row_column_list = None , logticks = None ) :
"""Manually specify the y - axis log tick values .
: param row _ column _ list : a list containing ( row , column ) tuples to
specify the subplots , or None to indicate * all * subplots .
: type row _ column _ list : list or None ... | if row_column_list is None :
self . ticks [ 'y' ] = [ '1e%d' % u for u in logticks ]
else :
for row , column in row_column_list :
self . set_logyticks ( row , column , logticks ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.