signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def deprecated_function ( func , warning = DEPRECATED_FUNCTION_WARNING ) :
"""Adds a ` DeprecationWarning ` to a function
Parameters
func : ` callable `
the function to decorate with a ` DeprecationWarning `
warning : ` str ` , optional
the warning to present
Notes
The final warning message is formatt... | @ wraps ( func )
def wrapped_func ( * args , ** kwargs ) :
warnings . warn ( DEPRECATED_FUNCTION_WARNING . format ( func ) , category = DeprecationWarning , stacklevel = 2 , )
return func ( * args , ** kwargs )
return wrapped_func |
def get_web_auth_session_key ( self , url , token = "" ) :
"""Retrieves the session key of a web authorization process by its URL .""" | session_key , _username = self . get_web_auth_session_key_username ( url , token )
return session_key |
def is_amex ( n ) :
"""Checks if credit card number fits the american express format .""" | n , length = str ( n ) , len ( str ( n ) )
if length == 15 :
if n [ 0 ] == '3' and ( n [ 1 ] == '4' or n [ 1 ] == '7' ) :
return True
return False |
def disconnect ( self , code ) :
"""Called when WebSocket connection is closed .""" | Subscriber . objects . filter ( session_id = self . session_id ) . delete ( ) |
def date_this_month ( self , before_today = True , after_today = False ) :
"""Gets a Date object for the current month .
: param before _ today : include days in current month before today
: param after _ today : include days in current month after today
: param tzinfo : timezone , instance of datetime . tzin... | today = date . today ( )
this_month_start = today . replace ( day = 1 )
next_month_start = this_month_start + relativedelta . relativedelta ( months = 1 )
if before_today and after_today :
return self . date_between_dates ( this_month_start , next_month_start )
elif not before_today and after_today :
return sel... |
def format_expose ( expose ) :
"""Converts a port number or multiple port numbers , as used in the Dockerfile ` ` EXPOSE ` ` command , to a tuple .
: param : Port numbers , can be as integer , string , or a list / tuple of those .
: type expose : int | unicode | str | list | tuple
: return : A tuple , to be s... | if isinstance ( expose , six . string_types ) :
return expose ,
elif isinstance ( expose , collections . Iterable ) :
return map ( six . text_type , expose )
return six . text_type ( expose ) , |
def _on_decisions_event ( self , event = None , ** kwargs ) :
"""Called when an Event is received on the decisions channel . Saves
the value in group _ decisions . If num _ subperiods is None , immediately
broadcasts the event back out on the group _ decisions channel .""" | if not self . ran_ready_function :
logger . warning ( 'ignoring decision from {} before when_all_players_ready: {}' . format ( event . participant . code , event . value ) )
return
with track ( '_on_decisions_event' ) :
self . group_decisions [ event . participant . code ] = event . value
self . _group_... |
def get_excitation_spectrum ( self , width = 0.1 , npoints = 2000 ) :
"""Generate an excitation spectra from the singlet roots of TDDFT
calculations .
Args :
width ( float ) : Width for Gaussian smearing .
npoints ( int ) : Number of energy points . More points = > smoother
curve .
Returns :
( Excitat... | roots = self . parse_tddft ( )
data = roots [ "singlet" ]
en = np . array ( [ d [ "energy" ] for d in data ] )
osc = np . array ( [ d [ "osc_strength" ] for d in data ] )
epad = 20.0 * width
emin = en [ 0 ] - epad
emax = en [ - 1 ] + epad
de = ( emax - emin ) / npoints
# Use width of at least two grid points
if width <... |
def _on_action_triggered ( self ) :
"""Emits open _ requested when a recent file action has been triggered .""" | action = self . sender ( )
assert isinstance ( action , QtWidgets . QAction )
path = action . data ( )
self . open_requested . emit ( path )
self . update_actions ( ) |
def get_vlan_brief_output_provisioned_vlans_count ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vlan_brief = ET . Element ( "get_vlan_brief" )
config = get_vlan_brief
output = ET . SubElement ( get_vlan_brief , "output" )
provisioned_vlans_count = ET . SubElement ( output , "provisioned-vlans-count" )
provisioned_vlans_count . text = kwargs . pop ( 'provisioned_vlans_count' ... |
def main ( ) :
"""Main function of Lexicon .""" | # Dynamically determine all the providers available and gather command line arguments .
parsed_args = generate_cli_main_parser ( ) . parse_args ( )
log_level = logging . getLevelName ( parsed_args . log_level )
logging . basicConfig ( stream = sys . stdout , level = log_level , format = '%(message)s' )
logger . debug (... |
def merge_string_tuples ( tuple1 : tuple , tuple2 : tuple ) -> tuple :
"""Function to merge two string tuples by concatenation .
> > > merge _ string _ tuples ( ( ' Manjeet ' , ' Nikhil ' , ' Akshat ' ) , ( ' Singh ' , ' Meherwal ' , ' Garg ' ) )
( ' Manjeet Singh ' , ' Nikhil Meherwal ' , ' Akshat Garg ' )
>... | result = tuple ( ( str1 + str2 ) for ( str1 , str2 ) in zip ( tuple1 , tuple2 ) )
return result |
def _jobs_to_do ( self , restrictions ) :
""": return : the relation containing the keys to be computed ( derived from self . key _ source )""" | if self . restriction :
raise DataJointError ( 'Cannot call populate on a restricted table. ' 'Instead, pass conditions to populate() as arguments.' )
todo = self . key_source
if not isinstance ( todo , QueryExpression ) :
raise DataJointError ( 'Invalid key_source value' )
# check if target lacks any attribute... |
def load ( self , shapefile = None ) :
"""Opens a shapefile from a filename or file - like
object . Normally this method would be called by the
constructor with the file object or file name as an
argument .""" | if shapefile :
( shapeName , ext ) = os . path . splitext ( shapefile )
self . shapeName = shapeName
try :
self . shp = open ( "%s.shp" % shapeName , "rb" )
except IOError :
raise ShapefileException ( "Unable to open %s.shp" % shapeName )
try :
self . shx = open ( "%s.shx" % ... |
def standarize ( trainingset ) :
"""Morph the input signal to a mean of 0 and scale the signal strength by
dividing with the standard deviation ( rather that forcing a [ 0 , 1 ] range )""" | def encoder ( dataset ) :
for instance in dataset :
if np . any ( stds == 0 ) :
nonzero_indexes = np . where ( stds != 0 )
instance . features [ nonzero_indexes ] = ( instance . features [ nonzero_indexes ] - means [ nonzero_indexes ] ) / stds [ nonzero_indexes ]
else :
... |
def AAAA ( host , nameserver = None ) :
'''Return the AAAA record for ` ` host ` ` .
Always returns a list .
CLI Example :
. . code - block : : bash
salt ns1 dig . AAAA www . google . com''' | dig = [ 'dig' , '+short' , six . text_type ( host ) , 'AAAA' ]
if nameserver is not None :
dig . append ( '@{0}' . format ( nameserver ) )
cmd = __salt__ [ 'cmd.run_all' ] ( dig , python_shell = False )
# In this case , 0 is not the same as False
if cmd [ 'retcode' ] != 0 :
log . warning ( 'dig returned exit co... |
def getArrays ( self ) :
"""Return wavelength and flux arrays in user units .
Returns
wave : array _ like
Wavelength array in ` ` self . waveunits ` ` .
flux : array _ like
Flux array in ` ` self . fluxunits ` ` .
When necessary , ` ` self . primary _ area ` ` is used for unit conversion .""" | if hasattr ( self , 'primary_area' ) :
area = self . primary_area
else :
area = None
wave = self . GetWaveSet ( )
flux = self ( wave )
flux = units . Photlam ( ) . Convert ( wave , flux , self . fluxunits . name , area = area )
wave = units . Angstrom ( ) . Convert ( wave , self . waveunits . name )
return wave... |
def load_remote ( url , ** kwargs ) :
"""Load a mesh at a remote URL into a local trimesh object .
This must be called explicitly rather than automatically
from trimesh . load to ensure users don ' t accidentally make
network requests .
Parameters
url : string
URL containing mesh file
* * kwargs : pas... | # import here to keep requirement soft
import requests
# download the mesh
response = requests . get ( url )
# wrap as file object
file_obj = util . wrap_as_stream ( response . content )
# so loaders can access textures / etc
resolver = visual . resolvers . WebResolver ( url )
# actually load
loaded = load ( file_obj =... |
def competitions_data_download_file ( self , id , file_name , ** kwargs ) : # noqa : E501
"""Download competition data file # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . competitions _ data _ d... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . competitions_data_download_file_with_http_info ( id , file_name , ** kwargs )
# noqa : E501
else :
( data ) = self . competitions_data_download_file_with_http_info ( id , file_name , ** kwargs )
# noqa : E501
... |
def hexedit ( x ) :
"""Run external hex editor on a packet or bytes . Set editor in conf . prog . hexedit""" | x = bytes ( x )
fname = get_temp_file ( )
with open ( fname , "wb" ) as f :
f . write ( x )
subprocess . call ( [ conf . prog . hexedit , fname ] )
with open ( fname , "rb" ) as f :
x = f . read ( )
return x |
def celery_task_wrapper ( f ) :
"""Provides a task wrapper for celery that sets up cache and ensures
that the local store is cleared after completion""" | from celery . utils import fun_takes_kwargs
@ wraps ( f , assigned = available_attrs ( f ) )
def newf ( * args , ** kwargs ) :
backend = get_backend ( )
was_patched = backend . _patched
get_backend ( ) . patch ( )
# since this function takes all keyword arguments ,
# we will pass only the ones the f... |
def down_by_time ( * filters , remote_dir = DEFAULT_REMOTE_DIR , local_dir = "." , count = 1 ) :
"""Sync most recent file by date , time attribues""" | files = command . list_files ( * filters , remote_dir = remote_dir )
most_recent = sorted ( files , key = lambda f : f . datetime )
to_sync = most_recent [ - count : ]
_notify_sync ( Direction . down , to_sync )
down_by_files ( to_sync [ : : - 1 ] , local_dir = local_dir ) |
def plot_cells ( cell_1 , cell_2 , cell_3 ) :
"""Plots three cells""" | fig , ( ( ax1 , ax2 , ax3 ) ) = plt . subplots ( 1 , 3 , figsize = ( 12 , 5 ) )
for ax in [ ax1 , ax2 , ax3 ] :
ax . grid ( False )
ax . set_xticks ( [ ] )
ax . set_yticks ( [ ] )
ax1 . set_title ( "Type 1" )
ax1 . imshow ( cell_1 )
ax2 . set_title ( "Type 2" )
ax2 . imshow ( cell_2 )
ax3 . set_title ( "Typ... |
def extend ( self , * array_list ) :
"""Concatenate this array with the given arrays . This method doesn ' t modify current array . Instead ,
it creates new one , that have all of arrays . ( see : meth : ` . WBinArray . concat ` method )
: param array _ list : list of WBinArray
: return : newly created WBinAr... | result = WBinArray ( int ( self ) , len ( self ) )
for array in array_list :
result = result . concat ( array )
return result |
def training_job_summaries ( self , force_refresh = False ) :
"""A ( paginated ) list of everything from ` ` ListTrainingJobsForTuningJob ` ` .
Args :
force _ refresh ( bool ) : Set to True to fetch the latest data from SageMaker API .
Returns :
dict : The Amazon SageMaker response for ` ` ListTrainingJobsF... | if force_refresh :
self . clear_cache ( )
if self . _training_job_summaries is not None :
return self . _training_job_summaries
output = [ ]
next_args = { }
for count in range ( 100 ) :
logging . debug ( "Calling list_training_jobs_for_hyper_parameter_tuning_job %d" % count )
raw_result = self . _sage_c... |
def generate_phase_1 ( dim = 40 ) :
"""The first step in creating datapoints in the Poirazi & Mel model .
This returns a vector of dimension dim , with the last four values set to
1 and the rest drawn from a normal distribution .""" | phase_1 = numpy . random . normal ( 0 , 1 , dim )
for i in range ( dim - 4 , dim ) :
phase_1 [ i ] = 1.0
return phase_1 |
def paint ( self , iconic , painter , rect , mode , state , options ) :
"""Main paint method .""" | for opt in options :
self . _paint_icon ( iconic , painter , rect , mode , state , opt ) |
def decode ( data ) :
"""Decode the multibase decoded data
: param data : multibase encoded data
: type data : str or bytes
: return : decoded data
: rtype : str
: raises ValueError : if the data is not multibase encoded""" | data = ensure_bytes ( data , 'utf8' )
codec = get_codec ( data )
return codec . converter . decode ( data [ CODE_LENGTH : ] ) |
def get_security_group_id ( self , name ) :
"""Take name string , give back security group ID .
To get around VPC ' s API being stupid .""" | # Memoize entire list of groups
if not hasattr ( self , '_security_groups' ) :
self . _security_groups = { }
for group in self . get_all_security_groups ( ) :
self . _security_groups [ group . name ] = group . id
return self . _security_groups [ name ] |
def apply_injectables ( self , targets ) :
"""Given an iterable of ` Target ` instances , apply their transitive injectables .""" | target_types = { type ( t ) for t in targets }
target_subsystem_deps = { s for s in itertools . chain ( * ( t . subsystems ( ) for t in target_types ) ) }
for subsystem in target_subsystem_deps : # TODO : The is _ initialized ( ) check is primarily for tests and would be nice to do away with .
if issubclass ( subsy... |
def from_payload ( self , payload ) :
"""Init frame from binary data .""" | self . session_id = payload [ 0 ] * 256 + payload [ 1 ]
self . status = CommandSendConfirmationStatus ( payload [ 2 ] ) |
def connect ( self ) :
"""Initiate the channel we want to start streams from .""" | self . socketIO = SocketIO ( host = self . iosocket_server , port = 80 , resource = self . iosocket_resource , proxies = self . proxies , headers = self . headers , transports = [ "websocket" ] , Namespace = AtlasNamespace , )
self . socketIO . on ( self . EVENT_NAME_ERROR , self . handle_error ) |
def recv_match ( self , condition = None , type = None , blocking = False ) :
'''recv the next message that matches the given condition
type can be a string or a list of strings''' | if type is not None and not isinstance ( type , list ) :
type = [ type ]
while True :
m = self . recv_msg ( )
if m is None :
return None
if type is not None and not m . get_type ( ) in type :
continue
if not mavutil . evaluate_condition ( condition , self . messages ) :
conti... |
def missing_representative_sequence ( self ) :
"""list : List of genes with no mapping to a representative sequence .""" | return [ x . id for x in self . genes if not self . genes_with_a_representative_sequence . has_id ( x . id ) ] |
def center ( a : Union [ Set [ "Point2" ] , List [ "Point2" ] ] ) -> "Point2" :
"""Returns the central point for points in list""" | s = Point2 ( ( 0 , 0 ) )
for p in a :
s += p
return s / len ( a ) |
def skopeo_push ( self , repository = None , tag = None ) :
"""Push image from Docker daemon to Docker using skopeo
: param repository : repository to be pushed to
: param tag : tag
: return : pushed image""" | return self . copy ( repository , tag , SkopeoTransport . DOCKER_DAEMON , SkopeoTransport . DOCKER ) . using_transport ( SkopeoTransport . DOCKER ) |
def intersect ( self , other_seg , tol = 1e-12 ) :
"""Finds the intersections of two segments .
returns a list of tuples ( t1 , t2 ) such that
self . point ( t1 ) = = other _ seg . point ( t2 ) .
Note : This will fail if the two segments coincide for more than a
finite collection of points .""" | if isinstance ( other_seg , Line ) :
return bezier_by_line_intersections ( self , other_seg )
elif ( isinstance ( other_seg , QuadraticBezier ) or isinstance ( other_seg , CubicBezier ) ) :
assert self != other_seg
longer_length = max ( self . length ( ) , other_seg . length ( ) )
return bezier_intersec... |
def backwards ( apps , schema_editor ) :
"""Delete sample events , including derivative repeat and variation events .""" | titles = [ 'Daily Event' , 'Weekday Event' , 'Weekend Event' , 'Weekly Event' , 'Monthly Event' , 'Yearly Event' , ]
samples = EventBase . objects . filter ( title__in = titles )
samples . delete ( ) |
def read_tcp ( self , length ) :
"""Read Transmission Control Protocol ( TCP ) .
Structure of TCP header [ RFC 793 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Source Port | Destination Port |
| Sequence Number |
| Acknowledgement Number |
| Data | | U | A | P | R | S ... | if length is None :
length = len ( self )
_srcp = self . _read_unpack ( 2 )
_dstp = self . _read_unpack ( 2 )
_seqn = self . _read_unpack ( 4 )
_ackn = self . _read_unpack ( 4 )
_lenf = self . _read_binary ( 1 )
_flag = self . _read_binary ( 1 )
_wins = self . _read_unpack ( 2 )
_csum = self . _read_fileng ( 2 )
_u... |
def find_group ( self , star , starlist ) :
"""Find the ids of those stars in ` ` starlist ` ` which are at a
distance less than ` ` crit _ separation ` ` from ` ` star ` ` .
Parameters
star : ` ~ astropy . table . Row `
Star which will be either the head of a cluster or an
isolated one .
starlist : ` ~... | star_distance = np . hypot ( star [ 'x_0' ] - starlist [ 'x_0' ] , star [ 'y_0' ] - starlist [ 'y_0' ] )
distance_criteria = star_distance < self . crit_separation
return np . asarray ( starlist [ distance_criteria ] [ 'id' ] ) |
def restore ( self , path , configuration_type = "running" , restore_method = "override" , vrf_management_name = None ) :
"""Restore configuration on device from provided configuration file
Restore configuration from local file system or ftp / tftp server into ' running - config ' or ' startup - config ' .
: pa... | if hasattr ( self . resource_config , "vrf_management_name" ) :
vrf_management_name = vrf_management_name or self . resource_config . vrf_management_name
self . _validate_configuration_type ( configuration_type )
path = self . get_path ( path )
self . restore_flow . execute_flow ( path = path , configuration_type =... |
def docx_preprocess ( docx , batch = False ) :
"""Load docx files from local filepath if not already b64 encoded""" | if batch :
return [ docx_preprocess ( doc , batch = False ) for doc in docx ]
if os . path . isfile ( docx ) : # a filepath is provided , read and encode
return b64encode ( open ( docx , 'rb' ) . read ( ) )
else : # assume doc is already b64 encoded
return docx |
def _define_output_buffers ( self ) :
"""Prepare a dictionary so we know what buffers have to be update with the the output of every step .""" | # First define buffers that need input data
self . target_buffers = { None : [ ( step , self . buffers [ step ] ) for step in self . _get_input_steps ( ) ] }
# Go through all steps and append the buffers of their child nodes
for step in self . steps_sorted :
if step != self :
child_steps = [ edge [ 1 ] for ... |
def heatmap ( n_x = 5 , n_y = 10 ) :
"""Returns a DataFrame with the required format for
a heatmap plot
Parameters :
n _ x : int
Number of x categories
n _ y : int
Number of y categories""" | x = [ 'x_' + str ( _ ) for _ in range ( n_x ) ]
y = [ 'y_' + str ( _ ) for _ in range ( n_y ) ]
return pd . DataFrame ( surface ( n_x - 1 , n_y - 1 ) . values , index = x , columns = y ) |
def _do_logon ( self ) :
"""Log on , unconditionally . This can be used to re - logon .
This requires credentials to be provided .
Raises :
: exc : ` ~ zhmcclient . ClientAuthError `
: exc : ` ~ zhmcclient . ServerAuthError `
: exc : ` ~ zhmcclient . ConnectionError `
: exc : ` ~ zhmcclient . ParseError... | if self . _userid is None :
raise ClientAuthError ( "Userid is not provided." )
if self . _password is None :
if self . _get_password :
self . _password = self . _get_password ( self . _host , self . _userid )
else :
raise ClientAuthError ( "Password is not provided." )
logon_uri = '/api/ses... |
def parse_checksums ( checksums_string ) :
"""Parse a file containing checksums and filenames .""" | checksums_list = [ ]
for line in checksums_string . split ( '\n' ) :
try : # skip empty lines
if line == '' :
continue
checksum , filename = line . split ( )
# strip leading . /
if filename . startswith ( './' ) :
filename = filename [ 2 : ]
checksums_... |
def sync_remote_to_local ( force = "no" ) :
"""Sync your remote postgres database with local
Example :
fabrik prod sync _ remote _ to _ local""" | _check_requirements ( )
if force != "yes" :
message = "This will replace your local database '%s' with the " "remote '%s', are you sure [y/n]" % ( env . local_psql_db , env . psql_db )
answer = prompt ( message , "y" )
if answer != "y" :
logger . info ( "Sync stopped" )
return
init_tasks ( )... |
def shakeshake2_indiv_grad ( x1 , x2 , dy ) :
"""Overriding gradient for shake - shake of 2 tensors .""" | y = shakeshake2_py ( x1 , x2 , individual = True )
dx = tf . gradients ( ys = [ y ] , xs = [ x1 , x2 ] , grad_ys = [ dy ] )
return dx |
def convert ( self , * formats ) :
"""Return an Image instance with the first matching format .
For each format in ` ` * args ` ` : If the image ' s : attr : ` format ` attribute
is the same as the format , return self , otherwise try the next format .
If none of the formats match , return a new Image instanc... | for format in formats :
format = Image . image_format ( format )
if self . format == format :
return self
else :
return self . _convert ( format ) |
def get_root_path ( self , path ) :
"""See : py : meth : ` ~ stash . repository . Repository . get _ root _ path ` .""" | # Look at the directories present in the current working directory . In
# case a . svn directory is present , we know we are in the root directory
# of a Subversion repository ( for Subversion 1.7 . x ) . In case no
# repository specific folder is found , and the current directory has a
# parent directory , look if a r... |
def all ( self ) :
r"""Returns all content in this node , regardless of whitespace or
not . This includes all LaTeX needed to reconstruct the original source .
> > > from TexSoup import TexSoup
> > > soup = TexSoup ( r ' ' '
. . . \ newcommand { reverseconcat } [ 3 ] { # 3#2#1}
> > > list ( soup . all )
... | for child in self . expr . all :
if isinstance ( child , TexExpr ) :
node = TexNode ( child )
node . parent = self
yield node
else :
yield child |
def update ( self , byte_arr ) :
"""Read bytes and update the CRC computed .""" | if byte_arr :
self . value = self . calculate ( byte_arr , self . value ) |
def transform_from_chomsky_normal_form ( root ) : # type : ( Nonterminal ) - > Nonterminal
"""Transform the tree created by grammar in the Chomsky Normal Form to original rules .
: param root : Root of parsed tree .
: return : Modified tree .""" | # Transforms leaves
items = Traversing . post_order ( root )
items = filter ( lambda x : isinstance ( x , ( ChomskyTermRule , ChomskyTerminalReplaceRule ) ) , items )
de = deque ( items )
while de :
rule = de . popleft ( )
if isinstance ( rule , ChomskyTermRule ) :
upper_nonterm = rule . from_symbols [ ... |
def log_create ( self , instance , ** kwargs ) :
"""Helper method to create a new log entry . This method automatically populates some fields when no explicit value
is given .
: param instance : The model instance to log a change for .
: type instance : Model
: param kwargs : Field overrides for the : py : ... | changes = kwargs . get ( 'changes' , None )
pk = self . _get_pk_value ( instance )
if changes is not None :
kwargs . setdefault ( 'content_type' , ContentType . objects . get_for_model ( instance ) )
kwargs . setdefault ( 'object_pk' , pk )
kwargs . setdefault ( 'object_repr' , smart_text ( instance ) )
... |
def tempdeny ( ip = None , ttl = None , port = None , direction = None , comment = '' ) :
'''Add a rule to the temporary ip deny list .
See : func : ` _ access _ rule ` .
1 - Add an IP :
CLI Example :
. . code - block : : bash
salt ' * ' csf . tempdeny 127.0.0.1 300 port = 22 direction = ' in ' comment = ... | return _tmp_access_rule ( 'tempdeny' , ip , ttl , port , direction , comment ) |
def list_nodes ( call = None , ** kwargs ) :
'''Return a list of the VMs that in this location''' | if call == 'action' :
raise SaltCloudSystemExit ( 'The list_nodes function must be called with -f or --function.' )
ret = { }
conn = get_conn ( )
server_list = conn . server_list ( )
if not server_list :
return { }
for server in server_list :
server_tmp = conn . server_show ( server_list [ server ] [ 'id' ]... |
def obfuscate_unique ( tokens , index , replace , replacement , * args ) :
"""If the token string ( a unique value anywhere ) inside * tokens [ index ] *
matches * replace * , return * replacement * .
. . note : :
This function is only for replacing absolutely unique ocurrences of
* replace * ( where we don... | def return_replacement ( replacement ) :
UNIQUE_REPLACEMENTS [ replacement ] = replace
return replacement
tok = tokens [ index ]
token_type = tok [ 0 ]
token_string = tok [ 1 ]
if token_type != tokenize . NAME :
return None
# Skip this token
if token_string == replace :
return return_replacement ( r... |
def list ( self , order_id , ** params ) :
"""Retrieve order ' s line items
Returns all line items associated to order
: calls : ` ` get / orders / { order _ id } / line _ items ` `
: param int order _ id : Unique identifier of a Order .
: param dict params : ( optional ) Search options .
: return : List ... | _ , _ , line_items = self . http_client . get ( "/orders/{order_id}/line_items" . format ( order_id = order_id ) , params = params )
return line_items |
def zero_crossing_last ( frames ) :
"""Finds the last zero crossing in frames""" | frames = N . array ( frames )
crossings = N . where ( N . diff ( N . sign ( frames ) ) )
# crossings = N . where ( frames [ : n ] * frames [ 1 : n + 1 ] < 0)
if len ( crossings [ 0 ] ) == 0 :
print "No zero crossing"
return len ( frames ) - 1
return crossings [ 0 ] [ - 1 ] |
def unpack_attribute ( att ) :
"""Unpack an embedded attribute into a python or numpy object .""" | if att . unsigned :
log . warning ( 'Unsupported unsigned attribute!' )
# TDS 5.0 now has a dataType attribute that takes precedence
if att . len == 0 : # Empty
val = None
elif att . dataType == stream . STRING : # Then look for new datatype string
val = att . sdata
elif att . dataType : # Then a non - zero... |
def unsubscribe_user_from_discussion ( recID , uid ) :
"""Unsubscribe users from a discussion .
: param recID : record ID corresponding to the discussion we want to
unsubscribe the user
: param uid : user id
: return 1 if successful , 0 if not""" | query = """DELETE FROM "cmtSUBSCRIPTION"
WHERE id_bibrec=%s AND id_user=%s"""
params = ( recID , uid )
try :
res = run_sql ( query , params )
except :
return 0
if res > 0 :
return 1
return 0 |
def cleanup_interfaces ( self ) :
"""Removes all / sys / class / gpio / gpioN interfaces that this script created ,
and deletes callback bindings . Should be used after using interrupts .""" | debug ( "Cleaning up interfaces..." )
for gpio_id in self . _gpio_kernel_interfaces_created : # Close the value - file and remove interrupt bindings
self . del_interrupt_callback ( gpio_id )
# Remove the kernel GPIO interface
debug ( "- unexporting GPIO %s" % gpio_id )
with open ( _SYS_GPIO_ROOT + "unex... |
def filedet ( name , fobj = None , suffix = None ) :
"""Detect file type by filename .
: param name : file name
: param fobj : file object
: param suffix : file suffix like ` ` py ` ` , ` ` . py ` `
: return : file type full name , such as ` ` python ` ` , ` ` bash ` `""" | name = name or ( fobj and fobj . name ) or suffix
separated = name . split ( '.' )
if len ( separated ) == 1 :
raise FiledetException ( 'file name error.' )
key = '.' + separated [ - 1 ]
return _file_type_map . get ( key ) |
def multi_evaluate ( self , x , out = None ) :
"""Evaluate log of the density to propose ` ` x ` ` , namely log ( q ( x ) )
for each row in x .
: param x :
Matrix - like array ; the proposed points . Expect i - th accessible
as ` ` x [ i ] ` ` .
: param out :
Vector - like array , length = = ` ` len ( x... | if out is None :
out = _np . empty ( len ( x ) )
else :
assert len ( out ) == len ( x )
for i , point in enumerate ( x ) :
out [ i ] = self . evaluate ( point )
return out |
def handle_run_command ( parser , args ) :
"""Implement ` run ` sub - command .""" | MAX_LEVELS = 15
# - - - Look for ` pyftpsync . yaml ` in current folder and parents - - -
cur_level = 0
cur_folder = os . getcwd ( )
config_path = None
while cur_level < MAX_LEVELS :
path = os . path . join ( cur_folder , CONFIG_FILE_NAME )
# print ( " Searching for { } . . . " . format ( path ) )
if os . p... |
def convertbits ( data , frombits , tobits , pad = True ) :
"""General power - of - 2 base conversion .""" | acc = 0
bits = 0
ret = [ ]
maxv = ( 1 << tobits ) - 1
max_acc = ( 1 << ( frombits + tobits - 1 ) ) - 1
for value in data :
if value < 0 or ( value >> frombits ) :
return None
acc = ( ( acc << frombits ) | value ) & max_acc
bits += frombits
while bits >= tobits :
bits -= tobits
re... |
def write ( self , oprot ) :
'''Write this object to the given output protocol and return self .
: type oprot : thryft . protocol . _ output _ protocol . _ OutputProtocol
: rtype : pastpy . gen . database . impl . online . online _ database _ object _ detail _ image . OnlineDatabaseObjectDetailImage''' | oprot . write_struct_begin ( 'OnlineDatabaseObjectDetailImage' )
oprot . write_field_begin ( name = 'full_size_url' , type = 11 , id = None )
oprot . write_string ( self . full_size_url )
oprot . write_field_end ( )
oprot . write_field_begin ( name = 'mediaid' , type = 11 , id = None )
oprot . write_string ( self . med... |
def file_saved_in_editorstack ( self , editorstack_id_str , original_filename , filename ) :
"""A file was saved in editorstack , this notifies others""" | for editorstack in self . editorstacks :
if str ( id ( editorstack ) ) != editorstack_id_str :
editorstack . file_saved_in_other_editorstack ( original_filename , filename ) |
def Open ( self , filename , read_only = False ) :
"""Opens the database file .
Args :
filename ( str ) : filename of the database .
read _ only ( Optional [ bool ] ) : True if the database should be opened in
read - only mode . Since sqlite3 does not support a real read - only
mode we fake it by only per... | if self . _connection :
raise RuntimeError ( 'Cannot open database already opened.' )
self . filename = filename
self . read_only = read_only
try :
self . _connection = sqlite3 . connect ( filename )
except sqlite3 . OperationalError :
return False
if not self . _connection :
return False
self . _cursor... |
def merge ( self , other ) :
"""Merges two prefixes""" | other = PrefixCell . coerce ( other )
if self . is_equal ( other ) : # pick among dependencies
return self
elif other . is_entailed_by ( self ) :
return self
elif self . is_entailed_by ( other ) :
self . value = other . value
elif self . is_contradictory ( other ) :
raise Contradiction ( "Cannot merge p... |
def smart_open ( filename : str , mode : str = "rt" , ftype : str = "auto" , errors : str = 'replace' ) :
"""Returns a file descriptor for filename with UTF - 8 encoding .
If mode is " rt " , file is opened read - only .
If ftype is " auto " , uses gzip iff filename endswith . gz .
If ftype is { " gzip " , " ... | if ftype in ( 'gzip' , 'gz' ) or ( ftype == 'auto' and filename . endswith ( ".gz" ) ) or ( ftype == 'auto' and 'r' in mode and is_gzip_file ( filename ) ) :
return gzip . open ( filename , mode = mode , encoding = 'utf-8' , errors = errors )
else :
return open ( filename , mode = mode , encoding = 'utf-8' , er... |
def person_update ( self , people ) :
"""Update the status of people
: param people : All people of this sensor
: type people : list [ paps . person . Person ]
: rtype : None
: raises SensorUpdateException : Failed to update""" | packet = APPUpdateMessage ( device_id = Id . NOT_SET , people = people )
self . _send_packet ( self . _server_ip , self . _server_port , packet , acknowledge_packet = False ) |
def updateAccuracy ( self , * accuracy ) :
"""Updates current accuracy flag""" | for acc in accuracy :
if not isinstance ( acc , int ) :
acc = self . _ACCURACY_REVERSE_MAPPING [ acc ]
self . accuracy |= acc |
def image_path_from_index ( self , index ) :
"""given image index , find out full path
Parameters
index : int
index of a specific image
Returns
full path of this image""" | assert self . image_set_index is not None , "Dataset not initialized"
pos = self . image_set_index [ index ]
n_db , n_index = self . _locate_index ( index )
return self . imdbs [ n_db ] . image_path_from_index ( n_index ) |
def update_options ( cls , options , items ) :
"""Switch default options and backend if new backend is supplied in
items .""" | # Get new backend
backend_spec = items . get ( 'backend' , Store . current_backend )
split = backend_spec . split ( ':' )
backend , mode = split if len ( split ) == 2 else ( split [ 0 ] , 'default' )
if ':' not in backend_spec :
backend_spec += ':default'
if 'max_branches' in items :
print ( 'Warning: The max_b... |
def delete_mount_cache ( real_name ) :
'''. . versionadded : : 2018.3.0
Provide information if the path is mounted
CLI Example :
. . code - block : : bash
salt ' * ' mount . delete _ mount _ cache / mnt / share''' | cache = salt . utils . mount . read_cache ( __opts__ )
if cache :
if 'mounts' in cache :
if real_name in cache [ 'mounts' ] :
del cache [ 'mounts' ] [ real_name ]
cache_write = salt . utils . mount . write_cache ( cache , __opts__ )
if not cache_write :
ra... |
def _get_utc_sun_time_deg ( self , deg ) :
"""Return the times in minutes from 00:00 ( utc ) for a given sun altitude .
This is done for a given sun altitude in sunrise ` deg ` degrees
This function only works for altitudes sun really is .
If the sun never gets to this altitude , the returned sunset and sunri... | gama = 0
# location of sun in yearly cycle in radians
eqtime = 0
# difference betwen sun noon and clock noon
decl = 0
# sun declanation
hour_angle = 0
# solar hour angle
sunrise_angle = math . pi * deg / 180.0
# sun angle at sunrise / set
# get the day of year
day_of_year = self . gday_of_year ( )
# get radians of sun ... |
def _reset ( cls ) :
"""If we have forked since the watch dictionaries were initialized , all
that has is garbage , so clear it .""" | if os . getpid ( ) != cls . _cls_pid :
cls . _cls_pid = os . getpid ( )
cls . _cls_instances_by_target . clear ( )
cls . _cls_thread_by_target . clear ( ) |
def get_user_codeframe ( tb ) :
"""Modify traceback to only include the user code ' s execution frame
Always call in this fashion :
e = sys . exc _ info ( )
user _ tb = get _ user _ codeframe ( e [ 2 ] ) or e [ 2]
so that you can get the original frame back if you need to
( this is necessary because copyi... | while tb is not None :
f = tb . tb_frame
co = f . f_code
filename = co . co_filename
if filename [ 0 ] == '<' : # This is a meta - descriptor
# ( probably either " < unknown > " or " < string > " )
# and is likely the user ' s code we ' re executing
return tb
else :
tb = tb .... |
def _slice_area_from_bbox ( self , src_area , dst_area , ll_bbox = None , xy_bbox = None ) :
"""Slice the provided area using the bounds provided .""" | if ll_bbox is not None :
dst_area = AreaDefinition ( 'crop_area' , 'crop_area' , 'crop_latlong' , { 'proj' : 'latlong' } , 100 , 100 , ll_bbox )
elif xy_bbox is not None :
dst_area = AreaDefinition ( 'crop_area' , 'crop_area' , 'crop_xy' , src_area . proj_dict , src_area . x_size , src_area . y_size , xy_bbox )... |
def update_ticket ( self , ticket_id = None , body = None ) :
"""Update a ticket .
: param integer ticket _ id : the id of the ticket to update
: param string body : entry to update in the ticket""" | return self . ticket . addUpdate ( { 'entry' : body } , id = ticket_id ) |
def dumps ( cls , obj , protocol = 0 ) :
"""Equivalent to pickle . dumps except that the HoloViews option
tree is saved appropriately .""" | cls . save_option_state = True
val = pickle . dumps ( obj , protocol = protocol )
cls . save_option_state = False
return val |
def set_template ( self , id_environment , name , network ) :
"""Set template value . If id _ environment = 0 , set ' ' to all environments related with the template name .
: param id _ environment : Environment Identifier .
: param name : Template Name .
: param network : IPv4 or IPv6.
: return : None
: ... | url = 'environment/set_template/' + str ( id_environment ) + '/'
environment_map = dict ( )
environment_map [ 'name' ] = name
environment_map [ 'network' ] = network
code , xml = self . submit ( { 'environment' : environment_map } , 'POST' , url )
return self . response ( code , xml ) |
def stop_host ( self , config_file ) :
"""Stops a managed host specified by ` config _ file ` .""" | res = self . send_json_request ( 'host/stop' , data = { 'config' : config_file } )
if res . status_code != 200 :
raise UnexpectedResponse ( 'Attempted to stop a JSHost. Response: {res_code}: {res_text}' . format ( res_code = res . status_code , res_text = res . text , ) )
return res . json ( ) |
def isSquare ( matrix ) :
"""Check that ` ` matrix ` ` is square .
Returns
is _ square : bool
` ` True ` ` if ` ` matrix ` ` is square , ` ` False ` ` otherwise .""" | try :
try :
dim1 , dim2 = matrix . shape
except AttributeError :
dim1 , dim2 = _np . array ( matrix ) . shape
except ValueError :
return False
if dim1 == dim2 :
return True
return False |
def _memoize ( self , name , getter , * args , ** kwargs ) :
"""Cache a stable expensive - to - get item value for later ( optimized ) retrieval .""" | field = "custom_m_" + name
cached = self . fetch ( field )
if cached :
value = cached
else :
value = getter ( * args , ** kwargs )
self . _make_it_so ( "caching %s=%r for" % ( name , value , ) , [ "custom.set" ] , field [ 7 : ] , value )
self . _fields [ field ] = value
return value |
def top_right ( self ) :
'''Returns the axis instance at the top right of the page ,
where the postage stamp and aperture is displayed''' | res = self . body_top_right [ self . tcount ] ( )
self . tcount += 1
return res |
def do_get ( self , from_path , to_path ) :
"""Copy file from Ndrive to local file and print out out the metadata .
Examples :
Ndrive > get file . txt ~ / ndrive - file . txt""" | to_file = open ( os . path . expanduser ( to_path ) , "wb" )
self . n . downloadFile ( self . current_path + "/" + from_path , to_path ) |
def peek ( init , exposes , debug = False ) :
"""Default deserializer factory .
Arguments :
init ( callable ) : type constructor .
exposes ( iterable ) : attributes to be peeked and passed to ` init ` .
Returns :
callable : deserializer ( ` peek ` routine ) .""" | def _peek ( store , container , _stack = None ) :
args = [ store . peek ( objname , container , _stack = _stack ) for objname in exposes ]
if debug :
print ( args )
return init ( * args )
return _peek |
def create_pixeltypegrid ( grid_pars , grid_data ) :
"""Creates pixelgrid and arrays of axis values .
Starting from :
- grid _ pars : 2D numpy array , 1 column per parameter , unlimited number of
cols
- grid _ data : 2D numpy array , 1 column per variable , data corresponding
to the rows in grid _ pars
... | uniques = [ np . unique ( column , return_inverse = True ) for column in grid_pars ]
# [0 ] are the unique values , [ 1 ] the indices for these to recreate the original array
# we need to copy the values of the unique axes explicitly into new arrays
# otherwise we can get issues with the interpolator
axis_values = [ ]
... |
def _read_mode_unpack ( self , size , kind ) :
"""Read options request unpack process .
Positional arguments :
* size - int , length of option
* kind - int , option kind value
Returns :
* dict - - extracted option
Structure of IPv4 options :
Octets Bits Name Description
0 0 ip . opt . kind Kind
0 ... | if size < 3 :
raise ProtocolError ( f'{self.alias}: [Optno {kind}] invalid format' )
data = dict ( kind = kind , type = self . _read_opt_type ( kind ) , length = size , data = self . _read_unpack ( size ) , )
return data |
def get_linestyle ( self , increment = 1 ) :
"""Returns the current marker , then increments the marker by what ' s specified""" | i = self . linestyles_index
self . linestyles_index += increment
if self . linestyles_index >= len ( self . linestyles ) :
self . linestyles_index = self . linestyles_index - len ( self . linestyles )
if self . linestyles_index >= len ( self . linestyles ) :
self . linestyles_index = 0
# to be safe
retu... |
def auto_directory ( rel_name ) :
"""if you ' re using py . path you make do that as :
py . path . local ( full _ path ) . ensure _ dir ( )""" | dir_name = rel_path ( rel_name , check = False )
if not os . path . exists ( dir_name ) :
os . makedirs ( dir_name , exist_ok = True )
return dir_name |
def try_one_generator ( project , name , generator , target_type , properties , sources ) :
"""Checks if generator invocation can be pruned , because it ' s guaranteed
to fail . If so , quickly returns empty list . Otherwise , calls
try _ one _ generator _ really .""" | if __debug__ :
from . targets import ProjectTarget
assert isinstance ( project , ProjectTarget )
assert isinstance ( name , basestring ) or name is None
assert isinstance ( generator , Generator )
assert isinstance ( target_type , basestring )
assert isinstance ( properties , property_set . Prop... |
def grok_ttl ( secret ) :
"""Parses the TTL information""" | ttl_obj = { }
lease_msg = ''
if 'lease' in secret :
ttl_obj [ 'lease' ] = secret [ 'lease' ]
lease_msg = "lease:%s" % ( ttl_obj [ 'lease' ] )
if 'lease_max' in secret :
ttl_obj [ 'lease_max' ] = secret [ 'lease_max' ]
elif 'lease' in ttl_obj :
ttl_obj [ 'lease_max' ] = ttl_obj [ 'lease' ]
if 'lease_max'... |
def log_call ( call_name ) :
"""Log the API call to the logger .""" | def decorator ( f ) :
@ wraps ( f )
def wrapper ( * args , ** kw ) :
instance = args [ 0 ]
instance . logger . info ( call_name , { "content" : request . get_json ( ) } )
return f ( * args , ** kw )
return wrapper
return decorator |
def upload_entities_tsv ( namespace , workspace , entities_tsv ) :
"""Upload entities from a tsv loadfile .
File - based wrapper for api . upload _ entities ( ) .
A loadfile is a tab - separated text file with a header row
describing entity type and attribute names , followed by
rows of entities and their a... | if isinstance ( entities_tsv , string_types ) :
with open ( entities_tsv , "r" ) as tsv :
entity_data = tsv . read ( )
elif isinstance ( entities_tsv , io . StringIO ) :
entity_data = entities_tsv . getvalue ( )
else :
raise ValueError ( 'Unsupported input type.' )
return upload_entities ( namespace... |
def create_profile ( hostname , username , password , profile_type , name , ** kwargs ) :
r'''A function to connect to a bigip device and create a profile .
hostname
The host / address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile _ type
The type... | # build session
bigip_session = _build_session ( username , password )
# construct the payload
payload = { }
payload [ 'name' ] = name
# there ' s a ton of different profiles and a ton of options for each type of profile .
# this logic relies that the end user knows which options are meant for which profile types
for k... |
def create_dict_subelement ( root , subelement , content , ** kwargs ) :
"""Create a XML subelement from a Python dictionary .""" | attribs = kwargs . get ( 'attribs' , None )
namespace = kwargs . get ( 'namespace' , None )
key = subelement
# Add subelement ' s namespace and attributes .
if namespace and attribs :
subelement = SubElement ( root , namespace + subelement , attribs )
elif namespace :
subelement = SubElement ( root , namespace ... |
def register_instances ( self , load_balancer_name , instances ) :
"""Add new Instances to an existing Load Balancer .
: type load _ balancer _ name : string
: param load _ balancer _ name : The name of the Load Balancer
: type instances : List of strings
: param instances : The instance ID ' s of the EC2 i... | params = { 'LoadBalancerName' : load_balancer_name }
self . build_list_params ( params , instances , 'Instances.member.%d.InstanceId' )
return self . get_list ( 'RegisterInstancesWithLoadBalancer' , params , [ ( 'member' , InstanceInfo ) ] ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.