signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def main ( argv = None , directory = None ) :
"""Main entry point for the tool , used by setup . py
Returns a value that can be passed into exit ( ) specifying
the exit code .
1 is an error
0 is successful run""" | logging . basicConfig ( format = '%(message)s' )
argv = argv or sys . argv
arg_dict = parse_coverage_args ( argv [ 1 : ] )
GitPathTool . set_cwd ( directory )
fail_under = arg_dict . get ( 'fail_under' )
percent_covered = generate_coverage_report ( arg_dict [ 'coverage_xml' ] , arg_dict [ 'compare_branch' ] , html_repo... |
def yum_install ( packages , downloadonly = False , dest_dir = '/tmp' ) :
"""Installs ( or downloads ) a list of packages from yum
This public method installs a list of packages from yum or
downloads the packages to the specified destination directory using
the yum - downloadonly yum plugin .
: param downlo... | log = logging . getLogger ( mod_logger + '.yum_install' )
# Type checks on the args
if not isinstance ( dest_dir , basestring ) :
msg = 'dest_dir argument must be a string'
log . error ( msg )
raise CommandError ( msg )
if not isinstance ( packages , list ) :
msg = 'packages argument must be a list'
... |
def mark_all_as_unread ( self , recipient = None ) :
"""Mark as unread any read messages in the current queryset .
Optionally , filter these by recipient first .""" | qset = self . read ( True )
if recipient :
qset = qset . filter ( recipient = recipient )
return qset . update ( unread = True ) |
def ingredient_from_validated_dict ( ingr_dict , selectable ) :
"""Create an ingredient from an dictionary .
This object will be deserialized from yaml""" | validator = IngredientValidator ( schema = ingr_dict [ 'kind' ] )
if not validator . validate ( ingr_dict ) :
raise Exception ( validator . errors )
ingr_dict = validator . document
kind = ingr_dict . pop ( 'kind' , 'Metric' )
IngredientClass = ingredient_class_for_name ( kind )
if IngredientClass is None :
rai... |
def widgets ( self ) :
"""Get the Ext JS specific customization from the activity .
: return : The Ext JS specific customization in ` list ( dict ) ` form""" | customization = self . activity . _json_data . get ( 'customization' )
if customization and "ext" in customization . keys ( ) :
return customization [ 'ext' ] [ 'widgets' ]
else :
return [ ] |
def from_nodes ( cls , nodes , _copy = True ) :
"""Create a : class : ` . Surface ` from nodes .
Computes the ` ` degree ` ` based on the shape of ` ` nodes ` ` .
Args :
nodes ( numpy . ndarray ) : The nodes in the surface . The columns
represent each node while the rows are the dimension
of the ambient s... | _ , num_nodes = nodes . shape
degree = cls . _get_degree ( num_nodes )
return cls ( nodes , degree , _copy = _copy ) |
def get_type ( obj , ** kwargs ) :
"""Return the type of an object . Do some regex to remove the " < class . . . " bit .""" | t = type ( obj )
s = extract_type ( str ( t ) )
return 'Type: {}' . format ( s ) |
def current_extended ( self ) :
"""Returns a ` ` list ` ` of ` ` dictionaries ` ` of the most recent AP rankings .
The list is ordered in terms of the ranking so the # 1 team will be in
the first element and the # 25 team will be the last element . Each
dictionary has the following structure : :
' abbreviat... | latest_week = max ( self . _rankings . keys ( ) )
ordered_dict = sorted ( self . _rankings [ latest_week ] , key = lambda k : k [ 'rank' ] )
return ordered_dict |
async def receive ( self , timeout : float = None ) -> Union [ Message , None ] :
"""Receives a message for this behaviour .
If timeout is not None it returns the message or " None "
after timeout is done .
Args :
timeout ( float ) : number of seconds until return
Returns :
spade . message . Message : a... | if timeout :
coro = self . queue . get ( )
try :
msg = await asyncio . wait_for ( coro , timeout = timeout )
except asyncio . TimeoutError :
msg = None
else :
try :
msg = self . queue . get_nowait ( )
except asyncio . QueueEmpty :
msg = None
return msg |
def _update_config ( template_name , template_source = None , template_hash = None , template_hash_name = None , template_user = 'root' , template_group = 'root' , template_mode = '755' , template_attrs = '--------------e----' , saltenv = None , template_engine = 'jinja' , skip_verify = False , defaults = None , test =... | return __salt__ [ 'net.load_template' ] ( template_name , template_source = template_source , template_hash = template_hash , template_hash_name = template_hash_name , template_user = template_user , template_group = template_group , template_mode = template_mode , template_attrs = template_attrs , saltenv = saltenv , ... |
def get_backend ( self , backend = None ) :
"""Default crypto backend
: param backend :
: return :""" | from cryptography . hazmat . backends import default_backend
return default_backend ( ) if backend is None else backend |
def find_cell_end ( self , lines ) :
"""Return position of end of cell marker , and position
of first line after cell""" | if self . metadata and 'cell_type' in self . metadata :
self . cell_type = self . metadata . pop ( 'cell_type' )
else :
self . cell_type = 'code'
next_cell = len ( lines )
for i , line in enumerate ( lines ) :
if i > 0 and ( self . start_code_re . match ( line ) or self . alternative_start_code_re . match (... |
def grid ( self , EdgeAttribute = None , network = None , NodeAttribute = None , nodeHorizontalSpacing = None , nodeList = None , nodeVerticalSpacing = None , verbose = None ) :
"""Execute the Grid Layout on a network .
: param EdgeAttribute ( string , optional ) : The name of the edge column contai
ning numeri... | network = check_network ( self , network , verbose = verbose )
PARAMS = set_param ( [ 'EdgeAttribute' , 'network' , 'NodeAttribute' , 'nodeHorizontalSpacing' , 'nodeList' , 'nodeVerticalSpacing' ] , [ EdgeAttribute , network , NodeAttribute , nodeHorizontalSpacing , nodeList , nodeVerticalSpacing ] )
response = api ( u... |
def ParseVideoRow ( self , parser_mediator , query , row , ** unused_kwargs ) :
"""Parses a Video row .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
query ( str ) : query that created the row .
row ( sqlite3 . Row ) ... | query_hash = hash ( query )
event_data = KodiVideoEventData ( )
event_data . filename = self . _GetRowValue ( query_hash , row , 'strFilename' )
event_data . play_count = self . _GetRowValue ( query_hash , row , 'playCount' )
event_data . query = query
timestamp = self . _GetRowValue ( query_hash , row , 'lastPlayed' )... |
def is_in_virtualbox ( ) :
"""Is the current environment a virtualbox instance ?
Returns a boolean
Raises IOError if the necessary tooling isn ' t available""" | if not isfile ( __VIRT_WHAT ) or not access ( __VIRT_WHAT , X_OK ) :
raise IOError ( "virt-what not available" )
try :
return subprocess . check_output ( [ "sudo" , "-n" , __VIRT_WHAT ] ) . split ( '\n' ) [ 0 : 2 ] == __VIRT_WHAT_VIRTUALBOX_WITH_KVM
except subprocess . CalledProcessError as e :
raise IOErro... |
def list_all_free_shipping_promotions ( cls , ** kwargs ) :
"""List FreeShippingPromotions
Return a list of FreeShippingPromotions
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ free _ shipping _ pro... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_free_shipping_promotions_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_free_shipping_promotions_with_http_info ( ** kwargs )
return data |
def mutable_json_field ( # pylint : disable = keyword - arg - before - vararg
enforce_string = False , # type : bool
enforce_unicode = False , # type : bool
json = json , # type : typing . Union [ types . ModuleType , typing . Any ]
* args , # type : typing . Any
** kwargs # type : typing . Any
) : # type : ( . . . ) -... | return sqlalchemy . ext . mutable . MutableDict . as_mutable ( JSONField ( enforce_string = enforce_string , enforce_unicode = enforce_unicode , json = json , * args , ** kwargs ) ) |
def get_events_with_n_cluster ( event_number , condition = 'n_cluster==1' ) :
'''Selects the events with a certain number of cluster .
Parameters
event _ number : numpy . array
Returns
numpy . array''' | logging . debug ( "Calculate events with clusters where " + condition )
n_cluster_in_events = analysis_utils . get_n_cluster_in_events ( event_number )
n_cluster = n_cluster_in_events [ : , 1 ]
# return np . take ( n _ cluster _ in _ events , ne . evaluate ( condition ) , axis = 0 ) # does not return 1d , bug ?
return ... |
def published ( self , for_user = None , include_login_required = False ) :
"""Override ` ` DisplayableManager . published ` ` to exclude
pages with ` ` login _ required ` ` set to ` ` True ` ` . if the
user is unauthenticated and the setting
` ` PAGES _ PUBLISHED _ INCLUDE _ LOGIN _ REQUIRED ` ` is ` ` False... | published = super ( PageManager , self ) . published ( for_user = for_user )
unauthenticated = for_user and not for_user . is_authenticated ( )
if ( unauthenticated and not include_login_required and not settings . PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED ) :
published = published . exclude ( login_required = True )
... |
def setup_data ( ) :
"""Load and shape data for training with Keras + Pescador .
Returns
input _ shape : tuple , len = 3
Shape of each sample ; adapts to channel configuration of Keras .
X _ train , y _ train : np . ndarrays
Images and labels for training .
X _ test , y _ test : np . ndarrays
Images a... | # The data , shuffled and split between train and test sets
( x_train , y_train ) , ( x_test , y_test ) = mnist . load_data ( )
if K . image_data_format ( ) == 'channels_first' :
x_train = x_train . reshape ( x_train . shape [ 0 ] , 1 , img_rows , img_cols )
x_test = x_test . reshape ( x_test . shape [ 0 ] , 1 ... |
def addKey ( self , key , value ) :
'''Insert a attribute / element / key - value pair to all the dictionaries .
The same value is added to all of the dictionaries .
Of note : the current version of this routine cannot handle subtending
keys ( dictionaries in dictionaries ) .
Example of use :
> > > test =... | result = [ ]
for row in self . table :
try :
row [ key ] = value
except :
pass
result . append ( row )
self . table = result
return self |
def properties_for_args ( cls , arg_names = '_arg_names' ) :
"""For a class with an attribute ` arg _ names ` containing a list of names ,
add a property for every name in that list .
It is assumed that there is an instance attribute ` ` self . _ < arg _ name > ` ` ,
which is returned by the ` arg _ name ` pr... | from qnet . algebra . core . scalar_algebra import Scalar
scalar_args = False
if hasattr ( cls , '_scalar_args' ) :
scalar_args = cls . _scalar_args
for arg_name in getattr ( cls , arg_names ) :
def get_arg ( self , name ) :
val = getattr ( self , "_%s" % name )
if scalar_args :
asse... |
def database_forwards ( self , app_label , schema_editor , from_state , to_state ) :
"""Perform forward migration .""" | Process = from_state . apps . get_model ( 'flow' , 'Process' )
# pylint : disable = invalid - name
# Validate process types to ensure consistency .
errors = validate_process_types ( Process . objects . all ( ) )
if errors :
raise ValueError ( "Process type consistency check failed after migration: {}" . format ( er... |
def file_owner ( self , rev , filename , committer = True ) :
"""Returns the owner ( by majority blame ) of a given file in a given rev . Returns the committers ' name .
: param rev :
: param filename :
: param committer :""" | try :
if committer :
cm = 'committer'
else :
cm = 'author'
blame = self . repo . blame ( rev , os . path . join ( self . git_dir , filename ) )
blame = DataFrame ( [ [ x [ 0 ] . committer . name , len ( x [ 1 ] ) ] for x in blame ] , columns = [ cm , 'loc' ] ) . groupby ( cm ) . agg ( { ... |
def rotate_left ( self ) :
"""Left rotation""" | new_root = self . node . right . node
new_left_sub = new_root . left . node
old_root = self . node
self . node = new_root
old_root . right . node = new_left_sub
new_root . left . node = old_root |
def while_loop ( self , context , step_method ) :
"""Run step inside a while loop .
Args :
context : ( pypyr . context . Context ) The pypyr context . This arg will
mutate - after method execution will contain the new
updated context .
step _ method : ( method / function ) This is the method / function th... | logger . debug ( "starting" )
context [ 'whileCounter' ] = 0
if self . stop is None and self . max is None : # the ctor already does this check , but guess theoretically
# consumer could have messed with the props since ctor
logger . error ( f"while decorator missing both max and stop." )
raise PipelineDefiniti... |
def find_call ( self , path , method ) :
"""Find callable for the specified URL path and HTTP method .
Args :
path ( : obj : ` str ` ) : URL path to match
method ( : obj : ` str ` ) : HTTP method
Note :
A trailing ' / ' is always assumed in the path .""" | if not path . endswith ( '/' ) :
path += '/'
path = path . split ( '/' ) [ 1 : ]
return self . _recursive_route_match ( self . _routes , path , method , [ ] ) |
def form_invalid ( self , form , context = None , ** kwargs ) :
"""This will return the request with form errors as well as any
additional context .""" | if not context :
context = { }
context [ 'errors' ] = form . errors
return super ( ApiFormView , self ) . render_to_response ( context = context , status = 400 ) |
def get_pkg_version ( ) :
"""Get version string by parsing PKG - INFO .""" | try :
with open ( "PKG-INFO" , "r" ) as fp :
rgx = re . compile ( r"Version: (\d+)" )
for line in fp . readlines ( ) :
match = rgx . match ( line )
if match :
return match . group ( 1 )
except IOError :
return None |
def prompt_for_numbered_choice ( self , choices , title = None , prompt = ">" ) :
"""Displays a numbered vertical list of choices from the provided list of strings .
: param choices : list of choices to display
: param title : optional title to display above the numbered list
: param prompt : prompt string . ... | if choices is None or len ( choices ) < 1 :
raise Exception ( 'choices list must contain at least one element.' )
while True :
self . clear ( )
if title :
self . screen . println ( title + "\n" )
for i in range ( 0 , len ( choices ) ) :
print ( ' {:<4}{choice}' . format ( str ( i + 1 )... |
def headloss_exp ( FlowRate , Diam , KMinor ) :
"""Return the minor head loss ( due to expansions ) in a pipe .
This equation applies to both laminar and turbulent flows .""" | # Checking input validity
ut . check_range ( [ FlowRate , ">0" , "Flow rate" ] , [ Diam , ">0" , "Diameter" ] , [ KMinor , ">=0" , "K minor" ] )
return KMinor * 8 / ( gravity . magnitude * np . pi ** 2 ) * FlowRate ** 2 / Diam ** 4 |
def get_sudoers_entry ( username = None , sudoers_entries = None ) :
"""Find the sudoers entry in the sudoers file for the specified user .
args :
username ( str ) : username .
sudoers _ entries ( list ) : list of lines from the sudoers file .
returns : ` r
str : sudoers entry for the specified user .""" | for entry in sudoers_entries :
if entry . startswith ( username ) :
return entry . replace ( username , '' ) . strip ( ) |
def mkdir ( self , paths , create_parent = False , mode = 0o755 ) :
'''Create a directoryCount
: param paths : Paths to create
: type paths : list of strings
: param create _ parent : Also create the parent directories
: type create _ parent : boolean
: param mode : Mode the directory should be created wi... | if not isinstance ( paths , list ) :
raise InvalidInputException ( "Paths should be a list" )
if not paths :
raise InvalidInputException ( "mkdirs: no path given" )
for path in paths :
if not path . startswith ( "/" ) :
path = self . _join_user_path ( path )
fileinfo = self . _get_file_info ( pa... |
def request_file_upload ( owner , repo , filepath , md5_checksum = None ) :
"""Request a new package file upload ( for creating packages ) .""" | client = get_files_api ( )
md5_checksum = md5_checksum or calculate_file_md5 ( filepath )
with catch_raise_api_exception ( ) :
data , _ , headers = client . files_create_with_http_info ( owner = owner , repo = repo , data = { "filename" : os . path . basename ( filepath ) , "md5_checksum" : md5_checksum } , )
# pyl... |
def create_room ( self , room , service , nick , config = None , callback = None , errback = None , room_jid = None ) :
"""Prepares the creation of a room .
The callback is a method with two arguments :
- room : Bare JID of the room
- nick : Nick used to create the room
The errback is a method with 4 argume... | self . __logger . debug ( "Creating room: %s" , room )
with self . __lock :
if not room_jid : # Generate / Format the room JID if not given
room_jid = sleekxmpp . JID ( local = room , domain = service ) . bare
self . __logger . debug ( "... Room JID: %s" , room_jid )
if not self . __rooms : # First ... |
def update ( self , other = None , ** kwargs ) :
"""A special update method to handle merging of dict objects . For all
other iterable objects , we use the parent class update method . For
other objects , we simply make use of the internal merging logic .
: param other : An iterable object .
: type other : ... | if other is not None :
if isinstance ( other , dict ) :
for key in other :
self [ key ] = other [ key ]
else : # noinspection PyTypeChecker
super ( MergingDict , self ) . update ( other )
for key in kwargs :
self . _merge ( key , kwargs [ key ] ) |
def format_edges_section ( self ) :
"""format edges section .
assign _ vertexid ( ) should be called before this method , because
vertices reffered by blocks should have valid index .""" | buf = io . StringIO ( )
buf . write ( 'edges\n' )
buf . write ( '(\n' )
for e in self . edges . values ( ) :
buf . write ( ' ' + e . format ( self . vertices ) + '\n' )
buf . write ( ');' )
return buf . getvalue ( ) |
def retrieve_block_from_map ( source_path , include_path , block_name , leading_whitespace , block_map , link_stack ) :
"""Given a source directory , the path specified in an include tag , and the block name , retrieve
the corresponding Block from the block _ map ( adding it to the map if necessary ) .
The path... | # Check if the included file exists .
relative_to_source = os . path . join ( os . path . dirname ( source_path ) , include_path )
if os . path . isfile ( relative_to_source ) :
filename = relative_to_source
elif os . path . isfile ( include_path ) :
filename = include_path
else :
raise IncludeNonExistentBl... |
def config ( client , key , value ) :
"""Get and set Renku repository and global options .""" | if value is None :
cfg = client . repo . config_reader ( )
click . echo ( cfg . get_value ( * _split_section_and_key ( key ) ) )
else :
with client . repo . config_writer ( ) as cfg :
section , config_key = _split_section_and_key ( key )
cfg . set_value ( section , config_key , value )
... |
def plotPowers ( ax , params , popkeys , dataset , linestyles , linewidths , transient = 200 , SCALING_POSTFIX = '' , markerstyles = None ) :
'''plot power ( variance ) as function of depth for total and separate
contributors
Plot variance of sum signal''' | colors = phlp . get_colors ( len ( popkeys ) )
depth = params . electrodeParams [ 'z' ]
zpos = np . r_ [ params . layerBoundaries [ : , 0 ] , params . layerBoundaries [ - 1 , 1 ] ]
for i , layer in enumerate ( popkeys ) :
f = h5py . File ( os . path . join ( params . populations_path , '%s_population_%s' % ( layer ... |
def by_name ( self , country , language = "en" ) :
"""Fetch a country ' s ISO3166-1 two letter country code from its name .
An optional language parameter is also available .
Warning : This depends on the quality of the available translations .
If no match is found , returns an empty string .
. . warning : ... | with override ( language ) :
for code , name in self :
if name . lower ( ) == country . lower ( ) :
return code
if code in self . OLD_NAMES :
for old_name in self . OLD_NAMES [ code ] :
if old_name . lower ( ) == country . lower ( ) :
retur... |
def new ( self ) : # type : ( ) - > None
'''Create a new Rock Ridge Platform Dependent record .
Parameters :
None .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'PD record already initialized!' )
self . _initialized = True
self . padding = b'' |
def RemoveAndAddFeatures ( self , url , pathToFeatureClass , id_field , chunksize = 1000 ) :
"""Deletes all features in a feature service and uploads features from a feature class on disk .
Args :
url ( str ) : The URL of the feature service .
pathToFeatureClass ( str ) : The path of the feature class on disk... | fl = None
try :
if arcpyFound == False :
raise common . ArcRestHelperError ( { "function" : "RemoveAndAddFeatures" , "line" : inspect . currentframe ( ) . f_back . f_lineno , "filename" : 'featureservicetools' , "synerror" : "ArcPy required for this function" } )
arcpy . env . overwriteOutput = True
... |
def enable_proxy ( self , host , port ) :
"""Enable a default web proxy""" | self . proxy = [ host , _number ( port ) ]
self . proxy_enabled = True |
def sampled_softmax ( num_classes , num_samples , in_dim , inputs , weight , bias , sampled_values , remove_accidental_hits = True ) :
"""Sampled softmax via importance sampling .
This under - estimates the full softmax and is only used for training .""" | # inputs = ( n , in _ dim )
sample , prob_sample , prob_target = sampled_values
# ( num _ samples , )
sample = S . var ( 'sample' , shape = ( num_samples , ) , dtype = 'float32' )
label = S . var ( 'label' )
label = S . reshape ( label , shape = ( - 1 , ) , name = "label_reshape" )
# ( num _ samples + n , )
sample_labe... |
def vlan_classifier_rule_class_type_proto_proto_proto_val ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
vlan = ET . SubElement ( config , "vlan" , xmlns = "urn:brocade.com:mgmt:brocade-vlan" )
classifier = ET . SubElement ( vlan , "classifier" )
rule = ET . SubElement ( classifier , "rule" )
ruleid_key = ET . SubElement ( rule , "ruleid" )
ruleid_key . text = kwargs . pop ( 'ruleid' )
c... |
def device_event_retrieve ( self , device_event_id , ** kwargs ) : # noqa : E501
"""Retrieve a device event . # noqa : E501
Retrieve a specific device event . # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass asynchronous = True
> > > ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . device_event_retrieve_with_http_info ( device_event_id , ** kwargs )
# noqa : E501
else :
( data ) = self . device_event_retrieve_with_http_info ( device_event_id , ** kwargs )
# noqa : E501
return data |
def set_user_agent ( self , user_agent ) :
"""Replaces the current user agent in the requests session headers .""" | # set a default user _ agent if not specified
if user_agent is None :
requests_ua = requests . utils . default_user_agent ( )
user_agent = '%s (%s/%s)' % ( requests_ua , __title__ , __version__ )
# the requests module uses a case - insensitive dict for session headers
self . session . headers [ 'User-agent' ] =... |
def _parameter_sweep ( self , parameter_space , kernel_options , device_options , tuning_options ) :
"""Build a Noodles workflow by sweeping the parameter space""" | results = [ ]
# randomize parameter space to do pseudo load balancing
parameter_space = list ( parameter_space )
random . shuffle ( parameter_space )
# split parameter space into chunks
work_per_thread = int ( numpy . ceil ( len ( parameter_space ) / float ( self . max_threads ) ) )
chunks = _chunk_list ( parameter_spa... |
def _build_url ( self , path ) :
"""Returns the full url from path .
If path is already a url , return it unchanged . If it ' s a path , append
it to the stored url .
Returns :
str : The full URL""" | if path . startswith ( 'http://' ) or path . startswith ( 'https://' ) :
return path
else :
return '%s%s' % ( self . _url , path ) |
def bind_device_to_gateway ( self , parent , gateway_id , device_id , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Associates the device with the gateway .
Example :
> > > from google . cloud import iot _ v1
> > ... | # Wrap the transport method to add retry and timeout logic .
if "bind_device_to_gateway" not in self . _inner_api_calls :
self . _inner_api_calls [ "bind_device_to_gateway" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . bind_device_to_gateway , default_retry = self . _method_configs [ ... |
def load_utf_text_file ( file_ , default_encoding = 'UTF-8' , use_utf8_strings = True ) :
"""Loads the specified text file and tries to decode it using one of the UTF encodings .
: param file _ : The path to the loadable text file or a file - like object with a read ( ) method .
: param default _ encoding : The... | if isinstance ( file_ , my_basestring ) :
with open ( file_ , 'rb' ) as f :
buf = f . read ( )
else :
buf = file_ . read ( )
return decode_utf_text_buffer ( buf , default_encoding , use_utf8_strings ) |
def path ( self , path ) :
"""Path of the IOU executable .
: param path : path to the IOU image executable""" | self . _path = self . manager . get_abs_image_path ( path )
log . info ( 'IOU "{name}" [{id}]: IOU image updated to "{path}"' . format ( name = self . _name , id = self . _id , path = self . _path ) ) |
def _extract_modifier ( x , i , attrs ) :
"""Extracts the * / + / ! modifier in front of the Cite at index ' i ' of the
element list ' x ' . The modifier is stored in ' attrs ' . Returns the updated
index ' i ' .""" | global _cleveref_tex_flag
# pylint : disable = global - statement
assert x [ i ] [ 't' ] == 'Cite'
assert i > 0
# Check the previous element for a modifier in the last character
if x [ i - 1 ] [ 't' ] == 'Str' :
modifier = x [ i - 1 ] [ 'c' ] [ - 1 ]
if not _cleveref_tex_flag and modifier in [ '*' , '+' ] :
... |
def containing_triangle ( self , xi , yi ) :
"""Returns indices of the triangles containing xi yi
Parameters
xi : float / array of floats , shape ( l , )
Cartesian coordinates in the x direction
yi : float / array of floats , shape ( l , )
Cartesian coordinates in the y direction
Returns
tri _ indices... | p = self . _permutation
pts = np . column_stack ( [ xi , yi ] )
sorted_simplices = np . sort ( self . _simplices , axis = 1 )
triangles = [ ]
for pt in pts :
t = _tripack . trfind ( 3 , pt [ 0 ] , pt [ 1 ] , self . _x , self . _y , self . lst , self . lptr , self . lend )
tri = np . sort ( t ) - 1
triangles... |
def clear ( self , encoding = Constants . default_codec ) :
"""Clears the defined file content .
: param encoding : File encoding codec .
: type encoding : unicode
: return : Method success .
: rtype : bool""" | if foundations . strings . is_website ( self . __path ) :
raise foundations . exceptions . UrlWriteError ( "!> {0} | '{1}' url is not writable!" . format ( self . __class__ . __name__ , self . __path ) )
if self . uncache ( ) :
LOGGER . debug ( "> Clearing '{0}' file content." . format ( self . __path ) )
r... |
def get_measurements ( self , station_id , aggregated_on , from_timestamp , to_timestamp , limit = 100 ) :
"""Reads measurements of a specified station recorded in the specified time
window and aggregated on minute , hour or day . Optionally , the number of
resulting measurements can be limited .
: param stat... | assert station_id is not None
assert aggregated_on is not None
assert from_timestamp is not None
assert from_timestamp > 0
assert to_timestamp is not None
assert to_timestamp > 0
if to_timestamp < from_timestamp :
raise ValueError ( "End timestamp can't be earlier than begin timestamp" )
assert isinstance ( limit ,... |
def get_bugs_summaries ( self , bugids ) :
"""Get multiple bug objects ' summaries only ( faster ) .
param bugids : ` ` list ` ` of ` ` int ` ` , bug numbers .
returns : deferred that when fired returns a list of ` ` AttrDict ` ` s
representing these bugs .""" | payload = { 'ids' : bugids , 'include_fields' : [ 'id' , 'summary' ] }
d = self . call ( 'Bug.get' , payload )
d . addCallback ( self . _parse_bugs_callback )
return d |
def linked ( base_dir : str , rr_id : str ) -> str :
"""Get , from the specified directory , the path to the tails file associated with
the input revocation registry identifier , or None for no such file .
: param base _ dir : base directory for tails files , thereafter split by cred def id
: param rr _ id : ... | LOGGER . debug ( 'Tails.linked >>> base_dir: %s, rr_id: %s' , base_dir , rr_id )
if not ok_rev_reg_id ( rr_id ) :
LOGGER . debug ( 'Tails.linked <!< Bad rev reg id %s' , rr_id )
raise BadIdentifier ( 'Bad rev reg id {}' . format ( rr_id ) )
cd_id = rev_reg_id2cred_def_id ( rr_id )
link = join ( base_dir , cd_id... |
def open_magnet ( self ) :
"""Open magnet according to os .""" | if sys . platform . startswith ( 'linux' ) :
subprocess . Popen ( [ 'xdg-open' , self . magnet ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
elif sys . platform . startswith ( 'win32' ) :
os . startfile ( self . magnet )
elif sys . platform . startswith ( 'cygwin' ) :
os . startfile ( self .... |
def list_policy_versions ( policy_name , region = None , key = None , keyid = None , profile = None ) :
'''List versions of a policy .
CLI Example :
. . code - block : : bash
salt myminion boto _ iam . list _ policy _ versions mypolicy''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
policy_arn = _get_policy_arn ( policy_name , region , key , keyid , profile )
try :
ret = conn . list_policy_versions ( policy_arn )
return ret . get ( 'list_policy_versions_response' , { } ) . get ( 'list_policy_versions_resul... |
def plot_two_columns ( self , reset_xlimits = False , reset_ylimits = False ) :
"""Simple line plot for two selected columns .""" | self . clear_plot ( )
if self . tab is None : # No table data to plot
return
plt_kw = { 'lw' : self . settings . get ( 'linewidth' , 1 ) , 'ls' : self . settings . get ( 'linestyle' , '-' ) , 'color' : self . settings . get ( 'linecolor' , 'blue' ) , 'ms' : self . settings . get ( 'markersize' , 6 ) , 'mew' : self ... |
def create ( cidr_block , instance_tenancy = None , vpc_name = None , enable_dns_support = None , enable_dns_hostnames = None , tags = None , region = None , key = None , keyid = None , profile = None ) :
'''Given a valid CIDR block , create a VPC .
An optional instance _ tenancy argument can be provided . If pro... | try :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
vpc = conn . create_vpc ( cidr_block , instance_tenancy = instance_tenancy )
if vpc :
log . info ( 'The newly created VPC id is %s' , vpc . id )
_maybe_set_name_tag ( vpc_name , vpc )
_maybe_se... |
def get_node ( request ) :
"""MNCore . getCapabilities ( ) → Node .""" | api_major_int = 2 if d1_gmn . app . views . util . is_v2_api ( request ) else 1
node_pretty_xml = d1_gmn . app . node . get_pretty_xml ( api_major_int )
return django . http . HttpResponse ( node_pretty_xml , d1_common . const . CONTENT_TYPE_XML ) |
def __get_min_writes ( current_provisioning , min_provisioned_writes , log_tag ) :
"""Get the minimum number of writes to current _ provisioning
: type current _ provisioning : int
: param current _ provisioning : Current provisioned writes
: type min _ provisioned _ writes : int
: param min _ provisioned _... | # Fallback value to ensure that we always have at least 1 read
writes = 1
if min_provisioned_writes :
writes = int ( min_provisioned_writes )
if writes > int ( current_provisioning * 2 ) :
writes = int ( current_provisioning * 2 )
logger . debug ( '{0} - ' 'Cannot reach min-provisioned-writes as... |
def compute_internal ( self , sym_name , bucket_kwargs = None , ** arg_dict ) :
"""View the internal symbols using the forward function .
: param sym _ name :
: param bucket _ kwargs :
: param input _ dict :
: return :""" | data_shapes = { k : v . shape for k , v in arg_dict . items ( ) }
self . switch_bucket ( bucket_kwargs = bucket_kwargs , data_shapes = data_shapes )
internal_sym = self . sym . get_internals ( ) [ sym_name ]
data_inputs = { k : mx . nd . empty ( v , ctx = self . ctx ) for k , v in self . data_shapes . items ( ) if k in... |
def triplet_loss ( anchor , positive , negative , margin , extra = False , scope = "triplet_loss" ) :
r"""Loss for Triplet networks as described in the paper :
` FaceNet : A Unified Embedding for Face Recognition and Clustering
< https : / / arxiv . org / abs / 1503.03832 > ` _
by Schroff et al .
Learn embe... | with tf . name_scope ( scope ) :
d_pos = tf . reduce_sum ( tf . square ( anchor - positive ) , 1 )
d_neg = tf . reduce_sum ( tf . square ( anchor - negative ) , 1 )
loss = tf . reduce_mean ( tf . maximum ( 0. , margin + d_pos - d_neg ) )
if extra :
pos_dist = tf . reduce_mean ( tf . sqrt ( d_pos... |
def check_output_command ( file_path , head = None , tail = None ) :
'''call check _ output command to read content from a file''' | if os . path . exists ( file_path ) :
if sys . platform == 'win32' :
cmds = [ 'powershell.exe' , 'type' , file_path ]
if head :
cmds += [ '|' , 'select' , '-first' , str ( head ) ]
elif tail :
cmds += [ '|' , 'select' , '-last' , str ( tail ) ]
return check_ou... |
def get_unassigned_ports ( self ) :
"""Gets the collection ports from the member interconnects
which are eligible for assignment to an anlyzer port
Returns :
dict : Collection of ports""" | uri = "{}/unassignedPortsForPortMonitor" . format ( self . data [ "uri" ] )
response = self . _helper . do_get ( uri )
return self . _helper . get_members ( response ) |
def bigquery_type ( o , timestamp_parser = default_timestamp_parser ) :
"""Given a value , return the matching BigQuery type of that value . Must be
one of str / unicode / int / float / datetime / record , where record is a dict
containing value which have matching BigQuery types .
Parameters
o : object
A... | t = type ( o )
if t in six . integer_types :
return "integer"
elif ( t == six . binary_type and six . PY2 ) or t == six . text_type :
if timestamp_parser and timestamp_parser ( o ) :
return "timestamp"
else :
return "string"
elif t == float :
return "float"
elif t == bool :
return "b... |
def randomdate ( year : int ) -> datetime . date :
"""gives random date in year""" | if calendar . isleap ( year ) :
doy = random . randrange ( 366 )
else :
doy = random . randrange ( 365 )
return datetime . date ( year , 1 , 1 ) + datetime . timedelta ( days = doy ) |
def pdf ( self , data_predict = None ) :
r"""Evaluate the probability density function .
Parameters
data _ predict : array _ like , optional
Points to evaluate at . If unspecified , the training data is used .
Returns
pdf _ est : array _ like
Probability density function evaluated at ` data _ predict ` ... | if data_predict is None :
data_predict = self . data
else :
data_predict = _adjust_shape ( data_predict , self . k_vars )
pdf_est = [ ]
for i in range ( np . shape ( data_predict ) [ 0 ] ) :
pdf_est . append ( gpke ( self . bw , data = self . data , data_predict = data_predict [ i , : ] , var_type = self . ... |
def write_memory ( self , addr , value , transfer_size = 32 ) :
"""write a memory location .
By default the transfer size is a word""" | self . ap . write_memory ( addr , value , transfer_size ) |
def getAnalyses ( self , contentFilter = None , ** kwargs ) :
"""return list of all analyses against this sample""" | # contentFilter and kwargs are combined . They both exist for
# compatibility between the two signatures ; kwargs has been added
# to be compatible with how getAnalyses ( ) is used everywhere else .
cf = contentFilter if contentFilter else { }
cf . update ( kwargs )
analyses = [ ]
for ar in self . getAnalysisRequests (... |
def add ( self , resource , provider_uri_or_id , timeout = - 1 ) :
"""Adds a Device Manager under the specified provider .
Args :
resource ( dict ) : Object to add .
provider _ uri _ or _ id : ID or URI of provider .
timeout :
Timeout in seconds . Wait for task completion by default . The timeout does not... | uri = self . _provider_client . build_uri ( provider_uri_or_id ) + "/device-managers"
return self . _client . create ( resource = resource , uri = uri , timeout = timeout ) |
def skip_internal ( app , what , name , obj , skip , options ) :
"""Skip rendering autodoc when the docstring contains a line with
only the string ` : internal : ` .""" | docstring = inspect . getdoc ( obj ) or ""
if skip or re . search ( r"^\s*:internal:\s*$" , docstring , re . M ) is not None :
return True |
def emitCurrentRecordEdited ( self ) :
"""Emits the current record edited signal for this combobox , provided the
signals aren ' t blocked and the record has changed since the last time .""" | if self . _changedRecord == - 1 :
return
if self . signalsBlocked ( ) :
return
record = self . _changedRecord
self . _changedRecord = - 1
self . currentRecordEdited . emit ( record ) |
def read_qemu_img_stdout ( self ) :
"""Reads the standard output of the QEMU - IMG process .""" | output = ""
if self . _qemu_img_stdout_file :
try :
with open ( self . _qemu_img_stdout_file , "rb" ) as file :
output = file . read ( ) . decode ( "utf-8" , errors = "replace" )
except OSError as e :
log . warning ( "Could not read {}: {}" . format ( self . _qemu_img_stdout_file , e... |
def create ( self , group , grouptype ) :
"""Create an LDAP Group .
Raises :
ldap3 . core . exceptions . LDAPNoSuchObjectResult :
an object involved with the request is missing
ldap3 . core . exceptions . LDAPEntryAlreadyExistsResult :
the entity being created already exists""" | try :
self . client . add ( self . __distinguished_name ( group ) , API . __object_class ( ) , self . __ldap_attr ( group , grouptype ) )
except ldap3 . core . exceptions . LDAPNoSuchObjectResult : # pragma : no cover
print ( "Error creating LDAP Group.\nRequest: " , self . __ldap_attr ( group , grouptype ) , "... |
def connected ( self , ** kwargs ) :
"""triger the server _ ready event""" | self . bot . log . info ( 'Server config: %r' , self . bot . server_config )
# recompile when I ' m sure of my nickname
self . bot . config [ 'nick' ] = kwargs [ 'me' ]
self . bot . recompile ( )
# Let all plugins know that server can handle commands
self . bot . notify ( 'server_ready' )
# detach useless events
self .... |
def save_optimizer_states ( self , fname ) :
"""Saves optimizer ( updater ) state to a file .
Parameters
fname : str
Path to output states file .""" | assert self . optimizer_initialized
if self . _update_on_kvstore :
self . _kvstore . save_optimizer_states ( fname )
else :
with open ( fname , 'wb' ) as fout :
fout . write ( self . _updater . get_states ( ) ) |
def dump_data_peek ( data , base = 0 , separator = ' ' , width = 16 , bits = None ) :
"""Dump data from pointers guessed within the given binary data .
@ type data : str
@ param data : Dictionary mapping offsets to the data they point to .
@ type base : int
@ param base : Base offset .
@ type bits : int
... | if data is None :
return ''
pointers = compat . keys ( data )
pointers . sort ( )
result = ''
for offset in pointers :
dumped = HexDump . hexline ( data [ offset ] , separator , width )
address = HexDump . address ( base + offset , bits )
result += '%s -> %s\n' % ( address , dumped )
return result |
def mbcs_work_around ( ) :
'''work around for mbcs codec to make " bdist _ wininst " work
https : / / mail . python . org / pipermail / python - list / 2012 - February / 620326 . html''' | import codecs
try :
codecs . lookup ( 'mbcs' )
except LookupError :
ascii = codecs . lookup ( 'ascii' )
codecs . register ( lambda name : { True : ascii } . get ( name == 'mbcs' ) ) |
def _setup_logging ( cls , args ) :
'''Set up the root logger if needed .
The root logger is set the appropriate level so the file and WARC logs
work correctly .''' | assert ( logging . CRITICAL > logging . ERROR > logging . WARNING > logging . INFO > logging . DEBUG > logging . NOTSET )
assert ( LOG_VERY_QUIET > LOG_QUIET > LOG_NO_VERBOSE > LOG_VERBOSE > LOG_DEBUG )
assert args . verbosity
root_logger = logging . getLogger ( )
current_level = root_logger . getEffectiveLevel ( )
min... |
def read_g94 ( basis_lines , fname ) :
'''Reads G94 - formatted file data and converts it to a dictionary with the
usual BSE fields
Note that the gaussian format does not store all the fields we
have , so some fields are left blank''' | skipchars = '!'
basis_lines = [ l for l in basis_lines if l and not l [ 0 ] in skipchars ]
bs_data = create_skel ( 'component' )
i = 0
if basis_lines [ 0 ] == '****' :
i += 1
# skip initial * * * *
while i < len ( basis_lines ) :
line = basis_lines [ i ]
elementsym = line . split ( ) [ 0 ]
# Some gaussi... |
def _SetUnknownFlag ( self , name , value ) :
"""Returns value if setting flag | name | to | value | returned True .
Args :
name : Name of the flag to set .
value : Value to set .
Returns :
Flag value on successful call .
Raises :
UnrecognizedFlagError
IllegalFlagValueError""" | setter = self . __dict__ [ '__set_unknown' ]
if setter :
try :
setter ( name , value )
return value
except ( TypeError , ValueError ) : # Flag value is not valid .
raise exceptions . IllegalFlagValueError ( '"{1}" is not valid for --{0}' . format ( name , value ) )
except NameError :... |
def local_batch ( self , * args , ** kwargs ) :
'''Run : ref : ` execution modules < all - salt . modules > ` against batches of minions
. . versionadded : : 0.8.4
Wraps : py : meth : ` salt . client . LocalClient . cmd _ batch `
: return : Returns the result from the exeuction module for each batch of
retu... | local = salt . client . get_local_client ( mopts = self . opts )
return local . cmd_batch ( * args , ** kwargs ) |
def visitTerminal ( self , ctx ) :
"""Converts case insensitive keywords and identifiers to lowercase""" | text = ctx . getText ( )
return Terminal . from_text ( text , ctx ) |
def run_genesippr ( self ) :
"""Run GeneSippr on each of the samples""" | from pathlib import Path
home = str ( Path . home ( ) )
logging . info ( 'GeneSippr' )
# These unfortunate hard coded paths appear to be necessary
miniconda_path = os . path . join ( home , 'miniconda3' )
miniconda_path = miniconda_path if os . path . isdir ( miniconda_path ) else os . path . join ( home , 'miniconda' ... |
def load ( self , key ) :
"""Given a bucket key , load the corresponding bucket .
: param key : The bucket key . This may be either a string or a
BucketKey object .
: returns : A Bucket object .""" | # Turn the key into a BucketKey
if isinstance ( key , basestring ) :
key = BucketKey . decode ( key )
# Make sure the uuids match
if key . uuid != self . uuid :
raise ValueError ( "%s is not a bucket corresponding to this limit" % key )
# If the key is a version 1 key , load it straight from the
# database
if k... |
def delete_ip_scope ( network_address , auth , url ) :
"""Function to delete an entire IP segment from the IMC IP Address management under terminal access
: param network _ address
: param auth
: param url
> > > from pyhpeimc . auth import *
> > > from pyhpeimc . plat . termaccess import *
> > > auth = ... | scope_id = get_scope_id ( network_address , auth , url )
if scope_id == "Scope Doesn't Exist" :
return scope_id
f_url = url + '''/imcrs/res/access/assignedIpScope/''' + str ( scope_id )
response = requests . delete ( f_url , auth = auth , headers = HEADERS )
try :
if response . status_code == 204 : # print ( " ... |
def cmd_ssh ( options ) :
"""Connect to the specified instance via ssh .
Finds instances that match the user specified args that are also
in the ' running ' state . The target instance is determined , the
required connection information is retreived ( IP , key and ssh
user - name ) , then an ' ssh ' connect... | import os
import subprocess
from os . path import expanduser
options . inst_state = "running"
( i_info , param_str ) = gather_data ( options )
( tar_inst , tar_idx ) = determine_inst ( i_info , param_str , options . command )
home_dir = expanduser ( "~" )
if options . user is None :
tar_aminame = awsc . get_one_ami... |
def qmed_all_methods ( self ) :
"""Returns a dict of QMED methods using all available methods .
Available methods are defined in : attr : ` qmed _ methods ` . The returned dict keys contain the method name , e . g .
` amax _ record ` with value representing the corresponding QMED estimate in m3 / s .
: return... | result = { }
for method in self . methods :
try :
result [ method ] = getattr ( self , '_qmed_from_' + method ) ( )
except :
result [ method ] = None
return result |
def largestNativeClique ( self , max_chain_length = None ) :
"""Returns the largest native clique embedding we can find on the
processor , with the shortest chainlength possible ( for that clique
size ) . If possible , returns a uniform choice among all largest
cliques .
INPUTS :
max _ chain _ length ( in... | def f ( x ) :
return x . largestNativeClique ( max_chain_length = max_chain_length )
objective = self . _objective_bestscore
return self . _translate ( self . _map_to_processors ( f , objective ) ) |
def __placeSellOrder ( self , tick ) :
'''place sell order''' | if self . __position < 0 :
return
share = self . __position
order = Order ( accountId = self . __strategy . accountId , action = Action . SELL , is_market = True , symbol = self . __symbol , share = - share )
if self . __strategy . placeOrder ( order ) :
self . __position = 0
self . __buyPrice = 0 |
def reduce_fn ( x ) :
"""Aggregation function to get the first non - zero value .""" | values = x . values if pd and isinstance ( x , pd . Series ) else x
for v in values :
if not is_nan ( v ) :
return v
return np . NaN |
def main ( ) :
"""Entry point from command line""" | parser = get_parser ( )
args = parser . parse_args ( )
if args . debug :
logger . setLevel ( logging . NOTSET )
initialize_preferences ( )
if args . version :
print ( __version__ )
return
cmd = args . cmd or args . args
if args . no_browser and args . browser :
print ( "Cannot specify no-browser and bro... |
def get_file ( self ) :
"""SCP copy the file from the remote device to local system .""" | source_file = "{}" . format ( self . source_file )
self . scp_conn . scp_get_file ( source_file , self . dest_file )
self . scp_conn . close ( ) |
def create ( embedding_name , ** kwargs ) :
"""Creates an instance of token embedding .
Creates a token embedding instance by loading embedding vectors from an externally hosted
pre - trained token embedding file , such as those of GloVe and FastText . To get all the valid
` embedding _ name ` and ` source ` ... | create_text_embedding = registry . get_create_func ( TokenEmbedding , 'token embedding' )
return create_text_embedding ( embedding_name , ** kwargs ) |
def image_predict ( self , X ) :
"""Predicts class label for the entire image .
: param X : Array of images to be classified .
: type X : numpy array , shape = [ n _ images , n _ pixels _ y , n _ pixels _ x , n _ bands ]
: return : raster classification map
: rtype : numpy array , [ n _ samples , n _ pixels... | pixels = self . extract_pixels ( X )
predictions = self . classifier . predict ( pixels )
return predictions . reshape ( X . shape [ 0 ] , X . shape [ 1 ] , X . shape [ 2 ] ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.