signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def handle_error ( self , request , client_address ) :
"""Handle an error gracefully . May be overridden .
The default is to print a traceback and continue .""" | print '-' * 40
print 'Exception happened during processing of request from' ,
print client_address
import traceback
traceback . print_exc ( )
# XXX But this goes to stderr !
print '-' * 40 |
def from_pb ( cls , instance_pb , client ) :
"""Creates an instance from a protobuf .
: type instance _ pb :
: class : ` google . spanner . v2 . spanner _ instance _ admin _ pb2 . Instance `
: param instance _ pb : A instance protobuf object .
: type client : : class : ` ~ google . cloud . spanner _ v1 . cl... | match = _INSTANCE_NAME_RE . match ( instance_pb . name )
if match is None :
raise ValueError ( "Instance protobuf name was not in the " "expected format." , instance_pb . name , )
if match . group ( "project" ) != client . project :
raise ValueError ( "Project ID on instance does not match the " "project ID on ... |
def distance_to_furthest ( self , ps : Union [ "Units" , List [ "Point2" ] , Set [ "Point2" ] ] ) -> Union [ int , float ] :
"""This function assumes the 2d distance is meant""" | assert ps
furthest_distance_squared = - math . inf
for p2 in ps :
if not isinstance ( p2 , Point2 ) :
p2 = p2 . position
distance = ( self [ 0 ] - p2 [ 0 ] ) ** 2 + ( self [ 1 ] - p2 [ 1 ] ) ** 2
if furthest_distance_squared < distance :
furthest_distance_squared = distance
return furthest_d... |
def _summary ( self , name = None ) :
"""Return a summarized representation .
Parameters
name : str
name to use in the summary representation
Returns
String with a summarized representation of the index""" | formatter = self . _formatter_func
if len ( self ) > 0 :
index_summary = ', %s to %s' % ( formatter ( self [ 0 ] ) , formatter ( self [ - 1 ] ) )
else :
index_summary = ''
if name is None :
name = type ( self ) . __name__
result = '%s: %s entries%s' % ( printing . pprint_thing ( name ) , len ( self ) , inde... |
def _exec_cmd ( self , command , ** kwargs ) :
"""Create a new method as command has specific requirements .
There is a handful of the TMSH global commands supported ,
so this method requires them as a parameter .
: raises : InvalidCommand""" | kwargs [ 'command' ] = command
self . _check_exclusive_parameters ( ** kwargs )
requests_params = self . _handle_requests_params ( kwargs )
session = self . _meta_data [ 'bigip' ] . _meta_data [ 'icr_session' ]
response = session . post ( self . _meta_data [ 'uri' ] , json = kwargs , ** requests_params )
new_instance =... |
def delete ( self , p_todo ) :
"""Deletes a todo item from the list .""" | try :
number = self . _todos . index ( p_todo )
del self . _todos [ number ]
self . _update_todo_ids ( )
self . dirty = True
except ValueError : # todo item couldn ' t be found , ignore
pass |
async def verify ( self , message : bytes , signature : bytes , verkey : str = None ) -> bool :
"""Verify signature against input signer verification key ( default anchor ' s own ) .
Raise AbsentMessage for missing message or signature , or WalletState if wallet is closed .
: param message : Content to sign , a... | LOGGER . debug ( 'Wallet.verify >>> message: %s, signature: %s, verkey: %s' , message , signature , verkey )
if not message :
LOGGER . debug ( 'Wallet.verify <!< No message to verify' )
raise AbsentMessage ( 'No message to verify' )
if not signature :
LOGGER . debug ( 'Wallet.verify <!< No signature to veri... |
async def _send_markdown ( self , request : Request , stack : Stack ) :
"""Sends Markdown using ` _ send _ text ( ) `""" | await self . _send_text ( request , stack , 'Markdown' ) |
def set_options ( self , options ) :
"""Sets the given options as instance attributes ( only
if they are known ) .
: parameters :
options : Dict
All known instance attributes and more if the childclass
has defined them before this call .
: rtype : None""" | for key , val in options . items ( ) :
key = key . lstrip ( '_' )
if hasattr ( self , key ) :
setattr ( self , key , val ) |
def wait_travel ( self , character , thing , dest , cb = None ) :
"""Schedule a thing to travel someplace , then wait for it to finish , and call ` ` cb ` ` if provided
: param character : name of the character
: param thing : name of the thing
: param dest : name of the destination ( a place )
: param cb :... | self . wait_turns ( self . engine . character [ character ] . thing [ thing ] . travel_to ( dest ) , cb = cb ) |
def stringify_value ( value ) :
"""Convert any value to string .""" | if value is None :
return u''
isoformat = getattr ( value , 'isoformat' , None )
if isoformat is not None :
value = isoformat ( )
return type ( u'' ) ( value ) |
def run ( self , arguments = None , get_unknowns = False ) :
"""Init point to execute the script .
If ` arguments ` string is given , will evaluate the arguments , else
evaluates sys . argv . Any inheriting class should extend the run method
( but first calling BaseCmdLineTool . run ( self ) ) .""" | # redirect PIPE signal to quiet kill script , if not on Windows
if os . name != 'nt' :
signal . signal ( signal . SIGPIPE , signal . SIG_DFL )
if get_unknowns :
if arguments :
self . args , self . unknown_args = ( self . argparser . parse_known_args ( args = arguments . split ( ) ) )
else :
... |
def get_status ( self ) :
"""Returns the Partner status .""" | status = ctypes . c_int32 ( )
result = self . library . Par_GetStatus ( self . pointer , ctypes . byref ( status ) )
check_error ( result , "partner" )
return status |
def _create ( self , constraint , exists_main ) :
"""Create MongoDB query clause for a constraint .
: param constraint : The constraint
: type constraint : Constraint
: param exists _ main : Put exists into main clause
: type exists _ main : bool
: return : New clause
: rtype : MongoClause
: raise : V... | c = constraint
# alias
op = self . _reverse_operator ( c . op ) if self . _rev else c . op
mop = self . _mongo_op_str ( op )
# build the clause parts : location and expression
loc = MongoClause . LOC_MAIN
# default location
if op . is_exists ( ) :
loc = MongoClause . LOC_MAIN2 if exists_main else MongoClause . LOC_... |
def define ( rest ) :
"Define a word" | word = rest . strip ( )
res = util . lookup ( word )
fmt = ( '{lookup.provider} says: {res}' if res else "{lookup.provider} does not have a definition for that." )
return fmt . format ( ** dict ( locals ( ) , lookup = util . lookup ) ) |
def _generate_union_class ( self , ns , data_type ) : # type : ( ApiNamespace , Union ) - > None
"""Defines a Python class that represents a union in Stone .""" | self . emit ( self . _class_declaration_for_type ( ns , data_type ) )
with self . indent ( ) :
self . emit ( '"""' )
if data_type . doc :
self . emit_wrapped_text ( self . process_doc ( data_type . doc , self . _docf ) )
self . emit ( )
self . emit_wrapped_text ( 'This class acts as a tagged... |
def equation_of_time_spencer71 ( dayofyear ) :
"""Equation of time from Duffie & Beckman and attributed to Spencer
(1971 ) and Iqbal ( 1983 ) .
The coefficients correspond to the online copy of the ` Fourier
paper ` _ [ 1 ] _ in the Sundial Mailing list that was posted in 1998 by
Mac Oglesby from his corres... | day_angle = _calculate_simple_day_angle ( dayofyear )
# convert from radians to minutes per day = 24 [ h / day ] * 60 [ min / h ] / 2 / pi
eot = ( 1440.0 / 2 / np . pi ) * ( 0.0000075 + 0.001868 * np . cos ( day_angle ) - 0.032077 * np . sin ( day_angle ) - 0.014615 * np . cos ( 2.0 * day_angle ) - 0.040849 * np . sin ... |
def relpath_posix ( recwalk_result , pardir , fromwinpath = False ) :
'''Helper function to convert all paths to relative posix like paths ( to ease comparison )''' | return recwalk_result [ 0 ] , path2unix ( os . path . join ( os . path . relpath ( recwalk_result [ 0 ] , pardir ) , recwalk_result [ 1 ] ) , nojoin = True , fromwinpath = fromwinpath ) |
def serialize_arguments ( bound_args ) :
"""Generator that takes the bound _ args output of signature ( ) . bind and
iterates over all the arguments , returning reproducable addresses of each
argument .
An address is stored in an | ArgumentAddress | object ( a named tuple ) ,
containing the kind of argument... | for p in bound_args . signature . parameters . values ( ) :
if p . kind == Parameter . VAR_POSITIONAL :
for i , _ in enumerate ( bound_args . arguments [ p . name ] ) :
yield ArgumentAddress ( ArgumentKind . variadic , p . name , i )
continue
if p . kind == Parameter . VAR_KEYWORD :
... |
def load_model_class ( repo , content_type ) :
"""Return a model class for a content type in a repository .
: param Repo repo :
The git repository .
: param str content _ type :
The content type to list
: returns : class""" | schema = get_schema ( repo , content_type ) . to_json ( )
return deserialize ( schema , module_name = schema [ 'namespace' ] ) |
def audit_logs ( self , * , limit = 100 , before = None , after = None , oldest_first = None , user = None , action = None ) :
"""Return an : class : ` AsyncIterator ` that enables receiving the guild ' s audit logs .
You must have the : attr : ` ~ Permissions . view _ audit _ log ` permission to use this .
Exa... | if user :
user = user . id
if action :
action = action . value
return AuditLogIterator ( self , before = before , after = after , limit = limit , oldest_first = oldest_first , user_id = user , action_type = action ) |
def __get_condition ( self , url ) :
"""Gets the condition for a url and validates it .
: param str url : The url to get the condition for""" | if self . __heuristics_condition is not None :
return self . __heuristics_condition
if "pass_heuristics_condition" in self . __sites_object [ url ] :
condition = self . __sites_object [ url ] [ "pass_heuristics_condition" ]
else :
condition = self . cfg_heuristics [ "pass_heuristics_condition" ]
# Because t... |
def compare ( all_dict , others , names , module_name ) :
"""Return sets of objects only in _ _ all _ _ , refguide , or completely missing .""" | only_all = set ( )
for name in all_dict :
if name not in names :
only_all . add ( name )
only_ref = set ( )
missing = set ( )
for name in names :
if name not in all_dict :
for pat in REFGUIDE_ALL_SKIPLIST :
if re . match ( pat , module_name + '.' + name ) :
if name no... |
def _call ( self , x , out = None ) :
"""Project ` ` x ` ` onto the subspace .""" | if out is None :
out = x [ self . index ] . copy ( )
else :
out . assign ( x [ self . index ] )
return out |
def _set_range ( self , init ) :
"""Reset the view .""" | # PerspectiveCamera . _ set _ range ( self , init )
# Stop moving
self . _speed *= 0.0
# Get window size ( and store factor now to sync with resizing )
w , h = self . _viewbox . size
w , h = float ( w ) , float ( h )
# Get range and translation for x and y
x1 , y1 , z1 = self . _xlim [ 0 ] , self . _ylim [ 0 ] , self .... |
def sys_get_char_size ( ) -> Tuple [ int , int ] :
"""Return the current fonts character size as ( width , height )
Returns :
Tuple [ int , int ] : The current font glyph size in ( width , height )""" | w = ffi . new ( "int *" )
h = ffi . new ( "int *" )
lib . TCOD_sys_get_char_size ( w , h )
return w [ 0 ] , h [ 0 ] |
def get_density ( self , compound = '' , element = '' ) :
"""returns the list of isotopes for the element of the compound defined with their density
Parameters :
compound : string ( default is empty ) . If empty , all the stoichiometric will be displayed
element : string ( default is same as compound ) .
Ra... | _stack = self . stack
if compound == '' :
_list_compounds = _stack . keys ( )
list_all_dict = { }
for _compound in _list_compounds :
_list_element = _stack [ _compound ] [ 'elements' ]
list_all_dict [ _compound ] = { }
for _element in _list_element :
list_all_dict [ _comp... |
def get ( cls , expression ) :
"""Retrieve the model instance matching the given expression .
If the number of matching results is not equal to one , then
a ` ` ValueError ` ` will be raised .
: param expression : A boolean expression to filter by .
: returns : The matching : py : class : ` Model ` instance... | executor = Executor ( cls . __database__ )
result = executor . execute ( expression )
if len ( result ) != 1 :
raise ValueError ( 'Got %s results, expected 1.' % len ( result ) )
return cls . load ( result . _first_or_any ( ) , convert_key = False ) |
def reqs ( ctx , dataset , kwargs ) :
"Get the dataset ' s pip requirements" | kwargs = parse_kwargs ( kwargs )
( print ) ( data ( dataset , ** ctx . obj ) . reqs ( ** kwargs ) ) |
def _write ( self , * args , ** kwargs ) :
"""Writes to the consumer stream when * filter _ fn * evaluates to * True * , passing * args * and
* kwargs * .""" | if self . filter_fn ( * args , ** kwargs ) :
self . stream . write ( * args , ** kwargs ) |
def improvise ( oracle , seq_len , k = 1 , LRS = 0 , weight = None , continuity = 1 ) :
"""Given an oracle and length , generate an improvised sequence of the given length .
: param oracle : an indexed vmo object
: param seq _ len : the length of the returned improvisation sequence
: param k : the starting im... | s = [ ]
if k + continuity < oracle . n_states - 1 :
s . extend ( range ( k , k + continuity ) )
k = s [ - 1 ]
seq_len -= continuity
while seq_len > 0 :
s . append ( improvise_step ( oracle , k , LRS , weight ) )
k = s [ - 1 ]
if k + 1 < oracle . n_states - 1 :
k += 1
else :
k... |
def list_pods ( self , namespace = None ) :
"""List all available pods .
: param namespace : str , if not specified list pods for all namespaces
: return : collection of instances of : class : ` conu . backend . k8s . pod . Pod `""" | if namespace :
return [ Pod ( name = p . metadata . name , namespace = namespace , spec = p . spec ) for p in self . core_api . list_namespaced_pod ( namespace , watch = False ) . items ]
return [ Pod ( name = p . metadata . name , namespace = p . metadata . namespace , spec = p . spec ) for p in self . core_api . ... |
def to_ansi_24bit ( self ) :
"""Convert to ANSI 24 - bit color format
: return :""" | text = self . text . replace ( '\x1b' , '' )
if self . color and self . bg_color :
c = self . color . scale ( 255 )
bg_c = self . bg_color . scale ( 255 )
return ansicolor ( text , fg = ( c . r , c . g , c . b ) , bg = ( bg_c . r , bg_c . g , bg_c . b ) )
elif self . color :
c = self . color . scale ( 2... |
def get_mobilenet ( multiplier , pretrained = False , ctx = cpu ( ) , root = os . path . join ( base . data_dir ( ) , 'models' ) , ** kwargs ) :
r"""MobileNet model from the
` " MobileNets : Efficient Convolutional Neural Networks for Mobile Vision Applications "
< https : / / arxiv . org / abs / 1704.04861 > `... | net = MobileNet ( multiplier , ** kwargs )
if pretrained :
from . . model_store import get_model_file
version_suffix = '{0:.2f}' . format ( multiplier )
if version_suffix in ( '1.00' , '0.50' ) :
version_suffix = version_suffix [ : - 1 ]
net . load_parameters ( get_model_file ( 'mobilenet%s' % v... |
def get_polygons ( self , by_spec = False , depth = None ) :
"""Returns a list of polygons in this cell .
Parameters
by _ spec : bool
If ` ` True ` ` , the return value is a dictionary with the
polygons of each individual pair ( layer , datatype ) .
depth : integer or ` ` None ` `
If not ` ` None ` ` , ... | if depth is not None and depth < 0 :
bb = self . get_bounding_box ( )
if bb is None :
return { } if by_spec else [ ]
pts = [ numpy . array ( [ ( bb [ 0 , 0 ] , bb [ 0 , 1 ] ) , ( bb [ 0 , 0 ] , bb [ 1 , 1 ] ) , ( bb [ 1 , 0 ] , bb [ 1 , 1 ] ) , ( bb [ 1 , 0 ] , bb [ 0 , 1 ] ) ] ) ]
polygons = { ... |
def folderitem ( self , obj , item , index ) :
"""Prepare a data item for the listing .
: param obj : The catalog brain or content object
: param item : Listing item ( dictionary )
: param index : Index of the listing item
: returns : Augmented listing data item""" | item [ 'Service' ] = obj . Title
item [ 'class' ] [ 'service' ] = 'service_title'
item [ 'service_uid' ] = obj . getServiceUID
item [ 'Keyword' ] = obj . getKeyword
item [ 'Unit' ] = format_supsub ( obj . getUnit ) if obj . getUnit else ''
item [ 'retested' ] = obj . getRetestOfUID and True or False
item [ 'class' ] [ ... |
def get_bool_relative ( strings : Sequence [ str ] , prefix1 : str , delta : int , prefix2 : str , ignoreleadingcolon : bool = False ) -> Optional [ bool ] :
"""Fetches a boolean parameter via : func : ` get _ string _ relative ` .""" | return get_bool_raw ( get_string_relative ( strings , prefix1 , delta , prefix2 , ignoreleadingcolon = ignoreleadingcolon ) ) |
def parse_args ( self ) :
"""Called from ` ` gnotty . server . run ` ` and parses any CLI args
provided . Also handles loading settings from the Python
module specified with the ` ` - - conf - file ` ` arg . CLI args
take precedence over any settings defined in the Python
module defined by ` ` - - conf - fi... | options , _ = parser . parse_args ( )
file_settings = { }
if options . CONF_FILE :
execfile ( options . CONF_FILE , { } , file_settings )
for option in self . option_list :
if option . dest :
file_value = file_settings . get ( "GNOTTY_%s" % option . dest , None )
# optparse doesn ' t seem to pro... |
def initialize_app ( flask_app , args ) :
"""Initialize the App .""" | # Setup gourde with the args .
gourde . setup ( args )
# Register a custom health check .
gourde . is_healthy = is_healthy
# Add an optional API
initialize_api ( flask_app ) |
def write ( filename , mesh , write_binary = False ) :
"""Writes mdpa files , cf .
< https : / / github . com / KratosMultiphysics / Kratos / wiki / Input - data > .""" | assert not write_binary
if mesh . points . shape [ 1 ] == 2 :
logging . warning ( "mdpa requires 3D points, but 2D points given. " "Appending 0 third component." )
mesh . points = numpy . column_stack ( [ mesh . points [ : , 0 ] , mesh . points [ : , 1 ] , numpy . zeros ( mesh . points . shape [ 0 ] ) ] )
# Kra... |
def l2traceroute_input_protocolType_IP_l4_src_port ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
l2traceroute = ET . Element ( "l2traceroute" )
config = l2traceroute
input = ET . SubElement ( l2traceroute , "input" )
protocolType = ET . SubElement ( input , "protocolType" )
IP = ET . SubElement ( protocolType , "IP" )
l4_src_port = ET . SubElement ( IP , "l4-src-port" )
l4_src_po... |
def create ( self , data = { } , ** kwargs ) :
"""Create Virtual Account from given dict
Args :
Param for Creating Virtual Account
Returns :
Virtual Account dict""" | url = self . base_url
return self . post_url ( url , data , ** kwargs ) |
def decode ( self , initial_state : State , transition_function : TransitionFunction , supervision : SupervisionType ) -> Dict [ str , torch . Tensor ] :
"""Takes an initial state object , a means of transitioning from state to state , and a
supervision signal , and uses the supervision to train the transition fu... | raise NotImplementedError |
def _set_mpls_interface ( self , v , load = False ) :
"""Setter method for mpls _ interface , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / mpls _ interface ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ mpls _ interface is... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "interface_type interface_name" , mpls_interface . mpls_interface , yang_name = "mpls-interface" , rest_name = "mpls-interface" , parent = self , is_container = 'list' , user_ordered = False , path_helper = sel... |
def create ( cls , name , entries = None , comment = None , ** kw ) :
"""Create an Access List Entry .
Depending on the access list type you are creating ( IPAccessList ,
IPv6AccessList , IPPrefixList , IPv6PrefixList , CommunityAccessList ,
ExtendedCommunityAccessList ) , entries will define a dict of the
... | access_list_entry = [ ]
if entries :
for entry in entries :
access_list_entry . append ( { '{}_entry' . format ( cls . typeof ) : entry } )
json = { 'name' : name , 'entries' : access_list_entry , 'comment' : comment }
json . update ( kw )
return ElementCreator ( cls , json ) |
def sort_batch_by_length ( tensor : torch . Tensor , sequence_lengths : torch . Tensor ) :
"""Sort a batch first tensor by some specified lengths .
Parameters
tensor : torch . FloatTensor , required .
A batch first Pytorch tensor .
sequence _ lengths : torch . LongTensor , required .
A tensor representing... | if not isinstance ( tensor , torch . Tensor ) or not isinstance ( sequence_lengths , torch . Tensor ) :
raise ConfigurationError ( "Both the tensor and sequence lengths must be torch.Tensors." )
sorted_sequence_lengths , permutation_index = sequence_lengths . sort ( 0 , descending = True )
sorted_tensor = tensor . ... |
def predict ( self , p , x ) :
"""Parameters
p : ndarray
( Ns , d ) array of predictor variables ( Ns samples , d dimensions )
for regression
x : ndarray
ndarray of ( x , y ) points . Needs to be a ( Ns , 2 ) array
corresponding to the lon / lat , for example .
array of Points , ( x , y , z ) pairs of... | return self . krige_residual ( x ) + self . regression_model . predict ( p ) |
async def check_filters ( filters : typing . Iterable [ FilterObj ] , args ) :
"""Check list of filters
: param filters :
: param args :
: return :""" | data = { }
if filters is not None :
for filter_ in filters :
f = await execute_filter ( filter_ , args )
if not f :
raise FilterNotPassed ( )
elif isinstance ( f , dict ) :
data . update ( f )
return data |
def searchHierarchy ( self , fparent ) :
"""Core function to search directory structure for child files and folders of a parent""" | data = [ ]
returnData = [ ]
parentslashes = fparent . count ( '/' )
filecount = 0
foldercount = 0
# open files for folder searching
try :
dirFile = open ( self . dirIndex , 'rt' )
except IOError :
self . repo . printd ( "Error: Unable to read index file " + self . dirIndex )
return
# search for folders
for ... |
def _after_handler ( self , iid , callback , args ) :
"""Proxy to called by after ( ) in mainloop""" | self . _after_id = None
self . update_state ( iid , "normal" )
self . call_callbacks ( iid , callback , args ) |
def remove_element ( self , selector , by = By . CSS_SELECTOR ) :
"""Remove the first element on the page that matches the selector .""" | selector , by = self . __recalculate_selector ( selector , by )
selector = self . convert_to_css_selector ( selector , by = by )
selector = self . __make_css_match_first_element_only ( selector )
remove_script = """jQuery('%s').remove()""" % selector
self . safe_execute_script ( remove_script ) |
def HashIt ( self ) :
"""Finalizing function for the Fingerprint class .
This method applies all the different hash functions over the
previously specified different ranges of the input file , and
computes the resulting hashes .
After calling HashIt , the state of the object is reset to its
initial state ... | while True :
interval = self . _GetNextInterval ( )
if interval is None :
break
self . file . seek ( interval . start , os . SEEK_SET )
block = self . file . read ( interval . end - interval . start )
if len ( block ) != interval . end - interval . start :
raise RuntimeError ( 'Short... |
def accepted ( self ) :
"""Successfully close the widget and emit an export signal .
This method is also a ` SLOT ` .
The dialog will be closed , when the ` Export Data ` button is
pressed . If errors occur during the export , the status bar
will show the error message and the dialog will not be closed .""" | # return super ( DataFrameExportDialog , self ) . accepted
try :
self . _saveModel ( )
except Exception as err :
self . _statusBar . showMessage ( str ( err ) )
raise
else :
self . _resetWidgets ( )
self . exported . emit ( True )
self . accept ( ) |
def github_signature ( string , shared_secret , challenge_hmac ) :
'''Verify a challenging hmac signature against a string / shared - secret for
github webhooks .
. . versionadded : : 2017.7.0
Returns a boolean if the verification succeeded or failed .
CLI Example :
. . code - block : : bash
salt ' * ' ... | msg = string
key = shared_secret
hashtype , challenge = challenge_hmac . split ( '=' )
if six . text_type :
msg = salt . utils . stringutils . to_bytes ( msg )
key = salt . utils . stringutils . to_bytes ( key )
hmac_hash = hmac . new ( key , msg , getattr ( hashlib , hashtype ) )
return hmac_hash . hexdigest (... |
def nb_to_html ( nb_path ) :
"""convert notebook to html""" | exporter = html . HTMLExporter ( template_file = 'full' )
output , resources = exporter . from_filename ( nb_path )
header = output . split ( '<head>' , 1 ) [ 1 ] . split ( '</head>' , 1 ) [ 0 ]
body = output . split ( '<body>' , 1 ) [ 1 ] . split ( '</body>' , 1 ) [ 0 ]
# http : / / imgur . com / eR9bMRH
header = head... |
def zoom_in ( self , action = None , channel = 0 ) :
"""Params :
action - start or stop
channel - channel number
The magic of zoom in 1x , 2x etc . is the timer between the cmd
' start ' and cmd ' stop ' . My suggestion for start / stop cmd is 0.5 sec""" | ret = self . command ( 'ptz.cgi?action={0}&channel={1}&code=ZoomTele&arg1=0' '&arg2=0&arg3=0' . format ( action , channel ) )
return ret . content . decode ( 'utf-8' ) |
def _autozoom ( self ) :
"""Calculate zoom and location .""" | bounds = self . _autobounds ( )
attrs = { }
midpoint = lambda a , b : ( a + b ) / 2
attrs [ 'location' ] = ( midpoint ( bounds [ 'min_lat' ] , bounds [ 'max_lat' ] ) , midpoint ( bounds [ 'min_lon' ] , bounds [ 'max_lon' ] ) )
# self . _ folium _ map . fit _ bounds (
# [ bounds [ ' min _ long ' ] , bounds [ ' min _ lat... |
def find_hba ( self , all_atoms ) :
"""Find all possible hydrogen bond acceptors""" | data = namedtuple ( 'hbondacceptor' , 'a a_orig_atom a_orig_idx type' )
a_set = [ ]
for atom in filter ( lambda at : at . OBAtom . IsHbondAcceptor ( ) , all_atoms ) :
if atom . atomicnum not in [ 9 , 17 , 35 , 53 ] and atom . idx not in self . altconf : # Exclude halogen atoms
a_orig_idx = self . Mapper . m... |
def setCovariance ( self , cov ) :
"""set hyperparameters from given covariance""" | chol = LA . cholesky ( cov , lower = True )
params = chol [ sp . tril_indices ( self . dim ) ]
self . setParams ( params ) |
def readable_os_version ( ) :
"""Give a proper name for OS version
: return : Proper OS version
: rtype : str""" | if platform . system ( ) == 'Linux' :
return _linux_os_release ( )
elif platform . system ( ) == 'Darwin' :
return ' {version}' . format ( version = platform . mac_ver ( ) [ 0 ] )
elif platform . system ( ) == 'Windows' :
return platform . platform ( ) |
def _pad_sequence_fix ( attr , kernelDim = None ) :
"""Changing onnx ' s pads sequence to match with mxnet ' s pad _ width
mxnet : ( x1 _ begin , x1 _ end , . . . , xn _ begin , xn _ end )
onnx : ( x1 _ begin , x2 _ begin , . . . , xn _ end , xn _ end )""" | new_attr = ( )
if len ( attr ) % 2 == 0 :
for index in range ( int ( len ( attr ) / 2 ) ) :
new_attr = new_attr + attr [ index : : int ( len ( attr ) / 2 ) ]
# Making sure pad values are in the attr for all axes .
if kernelDim is not None :
while len ( new_attr ) < kernelDim * 2 :
... |
def create_execve ( original_name ) :
"""os . execve ( path , args , env )
os . execvpe ( file , args , env )""" | def new_execve ( path , args , env ) :
import os
send_process_created_message ( )
return getattr ( os , original_name ) ( path , patch_args ( args ) , env )
return new_execve |
def batch_reverse ( self , points , ** kwargs ) :
"""Method for identifying the addresses from a list of lat / lng tuples""" | fields = "," . join ( kwargs . pop ( "fields" , [ ] ) )
response = self . _req ( "post" , verb = "reverse" , params = { "fields" : fields } , data = json_points ( points ) )
if response . status_code != 200 :
return error_response ( response )
logger . debug ( response )
return LocationCollection ( response . json ... |
def _to_power_basis12 ( nodes1 , nodes2 ) :
r"""Compute the coefficients of an * * intersection polynomial * * .
Helper for : func : ` to _ power _ basis ` in the case that the first curve is
degree one and the second is degree two . In this case , B | eacute |
zout ' s ` theorem ` _ tells us that the * * int... | # We manually invert the Vandermonde matrix :
# [1 0 0 ] [ c0 ] = [ n0]
# [1 1/2 1/4 ] [ c1 ] [ n1]
# [1 1 1 ] [ c2 ] [ n2]
val0 = eval_intersection_polynomial ( nodes1 , nodes2 , 0.0 )
val1 = eval_intersection_polynomial ( nodes1 , nodes2 , 0.5 )
val2 = eval_intersection_polynomial ( nodes1 , nodes2 , 1.0 )
# [ c0 ] =... |
def get_control_mode ( self , ids ) :
"""Gets the mode ( ' joint ' or ' wheel ' ) for the specified motors .""" | to_get_ids = [ id for id in ids if id not in self . _known_mode ]
limits = self . get_angle_limit ( to_get_ids , convert = False )
modes = [ 'wheel' if limit == ( 0 , 0 ) else 'joint' for limit in limits ]
self . _known_mode . update ( zip ( to_get_ids , modes ) )
return tuple ( self . _known_mode [ id ] for id in ids ... |
def extract ( path_to_hex , output_path = None ) :
"""Given a path _ to _ hex file this function will attempt to extract the
embedded script from it and save it either to output _ path or stdout""" | with open ( path_to_hex , 'r' ) as hex_file :
python_script = extract_script ( hex_file . read ( ) )
if output_path :
with open ( output_path , 'w' ) as output_file :
output_file . write ( python_script )
else :
print ( python_script ) |
def controller ( self ) :
"""Check if multiple controllers are connected .
: returns : Return the controller _ id of the active controller .
: rtype : string""" | if hasattr ( self , 'controller_id' ) :
if len ( self . controller_info [ 'controllers' ] ) > 1 :
raise TypeError ( 'Only one controller per account is supported.' )
return self . controller_id
raise AttributeError ( 'No controllers assigned to this account.' ) |
def _compute_metadata_from_readers ( self ) :
"""Determine pieces of metadata from the readers loaded .""" | mda = { 'sensor' : self . _get_sensor_names ( ) }
# overwrite the request start / end times with actual loaded data limits
if self . readers :
mda [ 'start_time' ] = min ( x . start_time for x in self . readers . values ( ) )
mda [ 'end_time' ] = max ( x . end_time for x in self . readers . values ( ) )
return ... |
def job_step_error ( self , job_request_payload , message ) :
"""Send message that the job step failed using payload data .
: param job _ request _ payload : StageJobPayload | RunJobPayload | StoreJobOutputPayload payload from job with error
: param message : description of the error""" | payload = JobStepErrorPayload ( job_request_payload , message )
self . send ( job_request_payload . error_command , payload ) |
def update_group ( self , group , process_id , wit_ref_name , page_id , section_id , group_id ) :
"""UpdateGroup .
[ Preview API ] Updates a group in the work item form .
: param : class : ` < Group > < azure . devops . v5_0 . work _ item _ tracking _ process . models . Group > ` group : The updated group .
:... | route_values = { }
if process_id is not None :
route_values [ 'processId' ] = self . _serialize . url ( 'process_id' , process_id , 'str' )
if wit_ref_name is not None :
route_values [ 'witRefName' ] = self . _serialize . url ( 'wit_ref_name' , wit_ref_name , 'str' )
if page_id is not None :
route_values [ ... |
def includeme ( config ) :
"""this function adds some configuration for the application""" | config . add_route ( 'references' , '/references' )
_add_referencer ( config . registry )
config . add_view_deriver ( protected_resources . protected_view )
config . add_renderer ( 'json_item' , json_renderer )
config . scan ( ) |
def channel_is_settled ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID , ) -> bool :
"""Returns true if the channel is in a settled state , false otherwise .""" | try :
channel_state = self . _get_channel_state ( participant1 = participant1 , participant2 = participant2 , block_identifier = block_identifier , channel_identifier = channel_identifier , )
except RaidenRecoverableError :
return False
return channel_state >= ChannelState . SETTLED |
def _get_tuids_from_files_try_branch ( self , files , revision ) :
'''Gets files from a try revision . It abuses the idea that try pushes
will come from various , but stable points ( if people make many
pushes on that revision ) . Furthermore , updates are generally done
to a revision that should eventually h... | repo = 'try'
result = [ ]
log_existing_files = [ ]
files_to_update = [ ]
# Check if the files were already annotated .
for file in files :
with self . conn . transaction ( ) as t :
already_ann = self . _get_annotation ( revision , file , transaction = t )
if already_ann :
result . append ( ( fil... |
def perform ( self ) :
"""Performs all stored actions .""" | if self . _driver . w3c :
self . w3c_actions . perform ( )
else :
for action in self . _actions :
action ( ) |
def collect ( cls ) :
"""Load all constant generators from settings . WEBPACK _ CONSTANT _ PROCESSORS
and concat their values .""" | constants = { }
for method_path in WebpackConstants . get_constant_processors ( ) :
method = import_string ( method_path )
if not callable ( method ) :
raise ImproperlyConfigured ( 'Constant processor "%s" is not callable' % method_path )
result = method ( constants )
if isinstance ( result , di... |
def initialize_model ( self , root_node ) :
"""Initializes the Model using given root node .
: param root _ node : Graph root node .
: type root _ node : DefaultNode
: return : Method success
: rtype : bool""" | LOGGER . debug ( "> Initializing model with '{0}' root node." . format ( root_node ) )
self . beginResetModel ( )
self . root_node = root_node
self . enable_model_triggers ( True )
self . endResetModel ( )
return True |
def get_root_graph ( self , root ) :
"""Return back a graph containing just the root and children""" | children = self . get_children ( root )
g = Graph ( )
nodes = [ root ] + children
for node in nodes :
g . add_node ( node )
node_ids = [ x . id for x in nodes ]
edges = [ x for x in self . _edges . values ( ) if x . node1 . id in node_ids and x . node2 . id in node_ids ]
for e in edges :
g . add_edge ( e )
retu... |
def visit_Attribute ( self , node : AST , dfltChaining : bool = True ) -> str :
"""Return ` node ` s representation as attribute access .""" | return '.' . join ( ( self . visit ( node . value ) , node . attr ) ) |
def convert ( input_format , output_format , b64_data ) :
"""Convert ` b64 _ data ` fron ` input _ format ` to ` output _ format ` .
Args :
input _ format ( str ) : Specification of input format ( pdf / epub / whatever ) ,
see : attr : ` INPUT _ FORMATS ` for list .
output _ format ( str ) : Specification o... | # checks
assert input_format in INPUT_FORMATS , "Unsupported input format!"
assert output_format in OUTPUT_FORMATS , "Unsupported output format!"
with NTFile ( mode = "wb" , suffix = "." + input_format , dir = "/tmp" ) as ifile :
ofilename = ifile . name + "." + output_format
# save received data to the tempora... |
def textFile ( self , name , minPartitions = None , use_unicode = True ) :
"""Read a text file from HDFS , a local file system ( available on all
nodes ) , or any Hadoop - supported file system URI , and return it as an
RDD of Strings .
The text files must be encoded as UTF - 8.
If use _ unicode is False , ... | minPartitions = minPartitions or min ( self . defaultParallelism , 2 )
return RDD ( self . _jsc . textFile ( name , minPartitions ) , self , UTF8Deserializer ( use_unicode ) ) |
def _set_level_2 ( self , v , load = False ) :
"""Setter method for level _ 2 , mapped from YANG variable / routing _ system / router / isis / router _ isis _ cmds _ holder / address _ family / ipv6 / af _ ipv6 _ unicast / af _ ipv6 _ attributes / af _ common _ attributes / redistribute / isis / level _ 2 ( contain... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = level_2 . level_2 , is_container = 'container' , presence = False , yang_name = "level-2" , rest_name = "level-2" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,... |
def busses ( ) :
r"""Returns a tuple with the usb busses .""" | return ( Bus ( g ) for k , g in groupby ( sorted ( core . find ( find_all = True ) , key = lambda d : d . bus ) , lambda d : d . bus ) ) |
def check_port ( port , host , timeout = 10 ) :
"""connect to port on host and return True on success
: param port : int , port to check
: param host : string , host address
: param timeout : int , number of seconds spent trying
: return : bool""" | logger . info ( "trying to open connection to %s:%s" , host , port )
sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM )
try :
sock . settimeout ( timeout )
result = sock . connect_ex ( ( host , port ) )
logger . info ( "was connection successful? errno: %s" , result )
if result == 0 :
... |
def collect ( self ) :
"""Collect libvirt data""" | if libvirt is None :
self . log . error ( 'Unable to import either libvirt' )
return { }
# Open a restricted ( non - root ) connection to the hypervisor
conn = libvirt . openReadOnly ( None )
# Get hardware info
conninfo = conn . getInfo ( )
# Initialize variables
memallocated = 0
coresallocated = 0
totalcores ... |
def _get_initial_name ( self ) :
"""Determine the most suitable name of the function .
: return : The initial function name .
: rtype : string""" | name = None
addr = self . addr
# Try to get a name from existing labels
if self . _function_manager is not None :
if addr in self . _function_manager . _kb . labels :
name = self . _function_manager . _kb . labels [ addr ]
# try to get the name from a hook
if name is None and self . project is not None :
... |
def writeKerning ( self , location = None , masters = None ) :
"""Write kerning into the current instance .
Note : the masters attribute is ignored at the moment .""" | if self . currentInstance is None :
return
kerningElement = ET . Element ( "kerning" )
if location is not None :
locationElement = self . _makeLocationElement ( location )
kerningElement . append ( locationElement )
self . currentInstance . append ( kerningElement ) |
def marshall_key ( self , key ) :
"""Marshalls a Crash key to be used in the database .
@ see : L { _ _ init _ _ }
@ type key : L { Crash } key .
@ param key : Key to convert .
@ rtype : str or buffer
@ return : Converted key .""" | if key in self . __keys :
return self . __keys [ key ]
skey = pickle . dumps ( key , protocol = 0 )
if self . compressKeys :
skey = zlib . compress ( skey , zlib . Z_BEST_COMPRESSION )
if self . escapeKeys :
skey = skey . encode ( 'hex' )
if self . binaryKeys :
skey = buffer ( skey )
self . __keys [ key... |
def open_unknown ( self , fullurl , data = None ) :
"""Overridable interface to open unknown URL type .""" | type , url = splittype ( fullurl )
raise IOError ( 'url error' , 'unknown url type' , type ) |
def _classify ( self , X , tree , proba = False ) :
"""Private function that classify a dataset using tree .
Parameters
X : array - like of shape = [ n _ samples , n _ features ]
The input samples .
tree : object
proba : bool , optional ( default = False )
If True then return probabilities else return c... | n_samples , n_features = X . shape
predicted = np . ones ( n_samples )
# Check if final node
if tree [ 'split' ] == - 1 :
if not proba :
predicted = predicted * tree [ 'y_pred' ]
else :
predicted = predicted * tree [ 'y_prob' ]
else :
j , l = tree [ 'split' ]
filter_Xl = ( X [ : , j ] <=... |
def compare_hdf_files ( file1 , file2 ) :
"""Compare two hdf files .
: param file1 : First file to compare .
: param file2 : Second file to compare .
: returns True if they are the same .""" | data1 = FileToDict ( )
data2 = FileToDict ( )
scanner1 = data1 . scan
scanner2 = data2 . scan
with h5py . File ( file1 , 'r' ) as fh1 :
fh1 . visititems ( scanner1 )
with h5py . File ( file2 , 'r' ) as fh2 :
fh2 . visititems ( scanner2 )
return data1 . contents == data2 . contents |
def backward_tensor ( self , y ) :
"""Transforms a series of triangular matrices y to the packed representation x ( tf . tensors )
: param y : unpacked tensor with shape self . num _ matrices , self . N , self . N
: return : packed tensor with shape self . num _ matrices , ( self . N * * 2 + self . N ) / 2""" | if self . squeeze :
y = tf . expand_dims ( y , axis = 0 )
indices = np . vstack ( np . tril_indices ( self . N ) ) . T
indices = itertools . product ( np . arange ( self . num_matrices ) , indices )
indices = np . array ( [ np . hstack ( x ) for x in indices ] )
triangular = tf . gather_nd ( y , indices )
return tf... |
def build_reader ( validator , reader_namespace = config . DEFAULT ) :
"""A factory method for creating a custom config reader from a validation
function .
: param validator : a validation function which acceptance one argument ( the
configuration value ) , and returns that value casted to
the appropriate t... | def reader ( config_key , default = UndefToken , namespace = None ) :
config_namespace = config . get_namespace ( namespace or reader_namespace )
return validator ( _read_config ( config_key , config_namespace , default ) )
return reader |
def _svd ( cls , matrix , num_concepts = 5 ) :
"""Perform singular value decomposition for dimensionality reduction of the input matrix .""" | u , s , v = svds ( matrix , k = num_concepts )
return u , s , v |
def _cleave_interface ( self , bulk_silica , tile_x , tile_y , thickness ) :
"""Carve interface from bulk silica .
Also includes a buffer of O ' s above and below the surface to ensure the
interface is coated .""" | O_buffer = self . _O_buffer
tile_z = int ( math . ceil ( ( thickness + 2 * O_buffer ) / bulk_silica . periodicity [ 2 ] ) )
bulk = mb . recipes . TiledCompound ( bulk_silica , n_tiles = ( tile_x , tile_y , tile_z ) )
interface = mb . Compound ( periodicity = ( bulk . periodicity [ 0 ] , bulk . periodicity [ 1 ] , 0.0 )... |
def grab_token ( host , email , password ) :
"""Grab token from gateway . Press sync button before running .""" | urllib3 . disable_warnings ( )
url = ( 'https://' + host + '/gwr/gop.php?cmd=GWRLogin&data=<gip><version>1</version><email>' + str ( email ) + '</email><password>' + str ( password ) + '</password></gip>&fmt=xml' )
response = requests . get ( url , verify = False )
if '<rc>404</rc>' in response . text :
raise Permi... |
def _to_legacy_path ( dict_path ) :
"""Convert a tuple of ints and strings in a legacy " Path " .
. . note :
This assumes , but does not verify , that each entry in
` ` dict _ path ` ` is valid ( i . e . doesn ' t have more than one
key out of " name " / " id " ) .
: type dict _ path : lsit
: param dict... | elements = [ ]
for part in dict_path :
element_kwargs = { "type" : part [ "kind" ] }
if "id" in part :
element_kwargs [ "id" ] = part [ "id" ]
elif "name" in part :
element_kwargs [ "name" ] = part [ "name" ]
element = _app_engine_key_pb2 . Path . Element ( ** element_kwargs )
elemen... |
def creategroup ( name , primary_cluster_id , replication_group_description , wait = None , region = None , key = None , keyid = None , profile = None ) :
'''Ensure the a replication group is create .
name
Name of replication group
wait
Waits for the group to be available
primary _ cluster _ id
Name of ... | ret = { 'name' : name , 'result' : None , 'comment' : '' , 'changes' : { } }
is_present = __salt__ [ 'boto_elasticache.group_exists' ] ( name , region , key , keyid , profile )
if not is_present :
if __opts__ [ 'test' ] :
ret [ 'comment' ] = 'Replication {0} is set to be created.' . format ( name )
... |
def beacon ( config ) :
'''Scan for processes and fire events
Example Config
. . code - block : : yaml
beacons :
ps :
- processes :
salt - master : running
mysql : stopped
The config above sets up beacons to check that
processes are running or stopped .''' | ret = [ ]
procs = [ ]
for proc in psutil . process_iter ( ) :
_name = proc . name ( )
if _name not in procs :
procs . append ( _name )
_config = { }
list ( map ( _config . update , config ) )
for process in _config . get ( 'processes' , { } ) :
ret_dict = { }
if _config [ 'processes' ] [ process... |
def service_restart ( name ) :
'''Restart a " service " on the ssh server
. . versionadded : : 2015.8.2''' | cmd = 'restart ' + name
# Send the command to execute
out , err = DETAILS [ 'server' ] . sendline ( cmd )
# " scrape " the output and return the right fields as a dict
return parse ( out ) |
def main ( ) -> None :
"""Command - line processor . See ` ` - - help ` ` for details .""" | main_only_quicksetup_rootlogger ( level = logging . DEBUG )
parser = argparse . ArgumentParser ( formatter_class = argparse . ArgumentDefaultsHelpFormatter )
parser . add_argument ( "input_file" , help = "Input PDF (which is not modified by this program)" )
parser . add_argument ( "output_file" , help = "Output PDF" )
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.