signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _shrink_list ( self , shrink ) :
"""Shrink list down to essentials
: param shrink : List to shrink
: type shrink : list
: return : Shrunk list
: rtype : list""" | res = [ ]
if len ( shrink ) == 1 :
return self . shrink ( shrink [ 0 ] )
else :
for a in shrink :
temp = self . shrink ( a )
if temp :
res . append ( temp )
return res |
def _connected ( self , link_uri ) :
"""This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded .""" | print ( 'Connected to %s' % link_uri )
# The definition of the logconfig can be made before connecting
self . _lg_stab = LogConfig ( name = 'Stabilizer' , period_in_ms = 10 )
self . _lg_stab . add_variable ( 'stabilizer.roll' , 'float' )
self . _lg_stab . add_variable ( 'stabilizer.pitch' , 'float' )
self . _lg_stab . ... |
def get_order ( self , codes ) :
"""Return evidence codes in order shown in code2name .""" | return sorted ( codes , key = lambda e : [ self . ev2idx . get ( e ) ] ) |
def copy_config ( self , original , new ) :
'''Copies collection configs into a new folder . Can be used to create new collections based on existing configs .
Basically , copies all nodes under / configs / original to / configs / new .
: param original str : ZK name of original config
: param new str : New na... | if not self . kz . exists ( '/configs/{}' . format ( original ) ) :
raise ZookeeperError ( "Collection doesn't exist in Zookeeper. Current Collections are: {}" . format ( self . kz . get_children ( '/configs' ) ) )
base = '/configs/{}' . format ( original )
nbase = '/configs/{}' . format ( new )
self . _copy_dir ( ... |
def submit ( self , txn , timeout = None ) :
"""Submit a transaction .
Processes multiple requests in a single transaction .
A transaction increments the revision of the key - value store
and generates events with the same revision for every
completed request .
It is not allowed to modify the same key sev... | def run ( pg_txn ) :
val = Json ( txn . _marshal ( ) )
pg_txn . execute ( "SELECT pgetcd.submit(%s,%s)" , ( val , 10 ) )
rows = pg_txn . fetchall ( )
res = "{0}" . format ( rows [ 0 ] [ 0 ] )
return res
return self . _pool . runInteraction ( run ) |
def insert_colorpoint ( self , position = 0.5 , color1 = [ 1.0 , 1.0 , 0.0 ] , color2 = [ 1.0 , 1.0 , 0.0 ] ) :
"""Inserts the specified color into the list .""" | L = self . _colorpoint_list
# if position = 0 or 1 , push the end points inward
if position <= 0.0 :
L . insert ( 0 , [ 0.0 , color1 , color2 ] )
elif position >= 1.0 :
L . append ( [ 1.0 , color1 , color2 ] )
# otherwise , find the position where it belongs
else : # loop over all the points
for n in range ... |
def pixels_to_tiles ( self , coords , clamp = True ) :
"""Convert pixel coordinates into tile coordinates .
clamp determines if we should clamp the tiles to ones only on the tilemap .""" | tile_coords = Vector2 ( )
tile_coords . X = int ( coords [ 0 ] ) / self . spritesheet [ 0 ] . width
tile_coords . Y = int ( coords [ 1 ] ) / self . spritesheet [ 0 ] . height
if clamp :
tile_coords . X , tile_coords . Y = self . clamp_within_range ( tile_coords . X , tile_coords . Y )
return tile_coords |
def post_data ( self , job_id , body , params = None ) :
"""` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / ml - post - data . html > ` _
: arg job _ id : The name of the job receiving the data
: arg body : The data to process
: arg reset _ end : Optional parameter to sp... | for param in ( job_id , body ) :
if param in SKIP_IN_PATH :
raise ValueError ( "Empty value passed for a required argument." )
return self . transport . perform_request ( "POST" , _make_path ( "_ml" , "anomaly_detectors" , job_id , "_data" ) , params = params , body = self . _bulk_body ( body ) , ) |
def move ( self , path , raise_if_exists = False ) :
"""Alias for ` ` rename ( ) ` `""" | self . rename ( path , raise_if_exists = raise_if_exists ) |
def aromatize ( molecule , usedPyroles = None ) :
"""( molecule , usedPyroles = None ) - > aromatize a molecular graph
usedPyroles is a dictionary that holds the pyrole like
atoms that are used in the conversion process .
The following valence checker may need this information""" | pyroleLike = getPyroleLikeAtoms ( molecule )
if usedPyroles is None :
usedPyroles = { }
cyclesToCheck = [ ]
# determine which cycles came in marked as aromatic
# and which need to be checked form the kekular form
# if a cycle came in as aromatic , convert it
# before going on .
for cycle in molecule . cycles :
... |
def scale ( table ) :
"""scale table based on the column with the largest sum""" | t = [ ]
columns = [ [ ] for i in table [ 0 ] ]
for row in table :
for i , v in enumerate ( row ) :
columns [ i ] . append ( v )
sums = [ float ( sum ( i ) ) for i in columns ]
scale_to = float ( max ( sums ) )
scale_factor = [ scale_to / i for i in sums if i != 0 ]
for row in table :
t . append ( [ a * ... |
def cache_file ( source ) :
'''Wrapper for cp . cache _ file which raises an error if the file was unable to
be cached .
CLI Example :
. . code - block : : bash
salt myminion container _ resource . cache _ file salt : / / foo / bar / baz . txt''' | try : # Don ' t just use cp . cache _ file for this . Docker has its own code to
# pull down images from the web .
if source . startswith ( 'salt://' ) :
cached_source = __salt__ [ 'cp.cache_file' ] ( source )
if not cached_source :
raise CommandExecutionError ( 'Unable to cache {0}' . f... |
def get_as_datetime ( self , key ) :
"""Converts map element into a Date or returns the current date if conversion is not possible .
: param key : an index of element to get .
: return : Date value ot the element or the current date if conversion is not supported .""" | value = self . get ( key )
return DateTimeConverter . to_datetime ( value ) |
def addJunctionPos ( shape , fromPos , toPos ) :
"""Extends shape with the given positions in case they differ from the
existing endpoints . assumes that shape and positions have the same dimensionality""" | result = list ( shape )
if fromPos != shape [ 0 ] :
result = [ fromPos ] + result
if toPos != shape [ - 1 ] :
result . append ( toPos )
return result |
def save_xml ( self , doc , element ) :
'''Save this component into an xml . dom . Element object .''' | element . setAttributeNS ( XSI_NS , XSI_NS_S + 'type' , 'rtsExt:component_ext' )
element . setAttributeNS ( RTS_NS , RTS_NS_S + 'id' , self . id )
element . setAttributeNS ( RTS_NS , RTS_NS_S + 'pathUri' , self . path_uri )
if self . active_configuration_set :
element . setAttributeNS ( RTS_NS , RTS_NS_S + 'activeC... |
def find_line ( scihdu , refhdu ) :
"""Obtain bin factors and corner location to extract
and bin the appropriate subset of a reference image to
match a science image .
If the science image has zero offset and is the same size and
binning as the reference image , ` ` same _ size ` ` will be set to
` True `... | sci_bin , sci_corner = get_corner ( scihdu . header )
ref_bin , ref_corner = get_corner ( refhdu . header )
# We can use the reference image directly , without binning
# and without extracting a subset .
if ( sci_corner [ 0 ] == ref_corner [ 0 ] and sci_corner [ 1 ] == ref_corner [ 1 ] and sci_bin [ 0 ] == ref_bin [ 0 ... |
def show_code ( co , version , file = None ) :
"""Print details of methods , functions , or code to * file * .
If * file * is not provided , the output is printed on stdout .""" | if file is None :
print ( code_info ( co , version ) )
else :
file . write ( code_info ( co , version ) + '\n' ) |
def run ( self ) :
"""Main thread function .""" | if not hasattr ( self , 'queue' ) :
raise RuntimeError ( "Audio queue is not intialized." )
chunk = None
channel = None
self . keep_listening = True
while self . keep_listening :
if chunk is None :
try :
frame = self . queue . get ( timeout = queue_timeout )
chunk = pygame . snda... |
def _load_plugin_class ( menu , name ) :
"""Load Custodia plugin
Entry points are preferred over dotted import path .""" | group = 'custodia.{}' . format ( menu )
eps = list ( pkg_resources . iter_entry_points ( group , name ) )
if len ( eps ) > 1 :
raise ValueError ( "Multiple entry points for {} {}: {}" . format ( menu , name , eps ) )
elif len ( eps ) == 1 : # backwards compatibility with old setuptools
ep = eps [ 0 ]
if has... |
def assert_is_lat ( val ) :
"""Checks it the given value is a feasible decimal latitude
: param val : value to be checked
: type val : int of float
: returns : ` None `
: raises : * ValueError * if value is out of latitude boundaries , * AssertionError * if type is wrong""" | assert type ( val ) is float or type ( val ) is int , "Value must be a number"
if val < - 90.0 or val > 90.0 :
raise ValueError ( "Latitude value must be between -90 and 90" ) |
def set_connection ( self , url ) :
"""Sets the connection URL to the address a Neo4j server is set up at""" | u = urlparse ( url )
if u . netloc . find ( '@' ) > - 1 and ( u . scheme == 'bolt' or u . scheme == 'bolt+routing' ) :
credentials , hostname = u . netloc . rsplit ( '@' , 1 )
username , password , = credentials . split ( ':' )
else :
raise ValueError ( "Expecting url format: bolt://user:password@localhost:... |
def get_data_for_sensors ( macs = [ ] , search_duratio_sec = 5 , bt_device = '' ) :
"""Get lates data for sensors in the MAC ' s list .
Args :
macs ( array ) : MAC addresses
search _ duratio _ sec ( int ) : Search duration in seconds . Default 5
bt _ device ( string ) : Bluetooth device id
Returns :
dic... | log . info ( 'Get latest data for sensors. Stop with Ctrl+C.' )
log . info ( 'Stops automatically in %ss' , search_duratio_sec )
log . info ( 'MACs: %s' , macs )
datas = dict ( )
for new_data in RuuviTagSensor . _get_ruuvitag_datas ( macs , search_duratio_sec , bt_device = bt_device ) :
datas [ new_data [ 0 ] ] = n... |
async def import_wallet ( config : str , credentials : str , import_config_json : str ) -> None :
"""Creates a new secure wallet with the given unique name and then imports its content
according to fields provided in import _ config
This can be seen as an indy _ create _ wallet call with additional content impo... | logger = logging . getLogger ( __name__ )
logger . debug ( "import_wallet: >>> config: %r, credentials: %r, import_config_json: %r" , config , credentials , import_config_json )
if not hasattr ( import_wallet , "cb" ) :
logger . debug ( "import_wallet: Creating callback" )
import_wallet . cb = create_cb ( CFUNC... |
def PortPathMatcher ( cls , port_path ) :
"""Returns a device matcher for the given port path .""" | if isinstance ( port_path , str ) : # Convert from sysfs path to port _ path .
port_path = [ int ( part ) for part in SYSFS_PORT_SPLIT_RE . split ( port_path ) ]
return lambda device : device . port_path == port_path |
def apply_calibration ( df , calibration_df , calibration ) :
'''Apply calibration values from ` fit _ fb _ calibration ` result to ` calibration `
object .''' | from dmf_control_board_firmware import FeedbackResults
for i , ( fb_resistor , R_fb , C_fb ) in calibration_df [ [ 'fb_resistor' , 'R_fb' , 'C_fb' ] ] . iterrows ( ) :
calibration . R_fb [ int ( fb_resistor ) ] = R_fb
calibration . C_fb [ int ( fb_resistor ) ] = C_fb
cleaned_df = df . dropna ( )
grouped = clean... |
def index ( self , sub , start = None , end = None ) :
"""Like S . find ( ) but raise ValueError when the substring is not found .
: param str sub : Substring to search .
: param int start : Beginning position .
: param int end : Stop comparison at this position .""" | return self . value_no_colors . index ( sub , start , end ) |
def crude_stretch ( self , min_stretch = None , max_stretch = None ) :
"""Perform simple linear stretching .
This is done without any cutoff on the current image and normalizes to
the [ 0,1 ] range .""" | if min_stretch is None :
non_band_dims = tuple ( x for x in self . data . dims if x != 'bands' )
min_stretch = self . data . min ( dim = non_band_dims )
if max_stretch is None :
non_band_dims = tuple ( x for x in self . data . dims if x != 'bands' )
max_stretch = self . data . max ( dim = non_band_dims ... |
def GetCoinAssets ( self ) :
"""Get asset ids of all coins present in the wallet .
Returns :
list : of UInt256 asset id ' s .""" | assets = set ( )
for coin in self . GetCoins ( ) :
assets . add ( coin . Output . AssetId )
return list ( assets ) |
def datetime2literal_rnc ( d : datetime . datetime , c : Optional [ Dict ] ) -> str :
"""Format a DateTime object as something MySQL will actually accept .""" | # dt = d . strftime ( " % Y - % m - % d % H : % M : % S " )
# . . . can fail with e . g .
# ValueError : year = 1850 is before 1900 ; the datetime strftime ( ) methods
# require year > = 1900
# http : / / stackoverflow . com / questions / 10263956
dt = d . isoformat ( " " )
# noinspection PyArgumentList
return _mysql .... |
def make_auto_deployable ( self , stage , swagger = None ) :
"""Sets up the resource such that it will triggers a re - deployment when Swagger changes
: param swagger : Dictionary containing the Swagger definition of the API""" | if not swagger :
return
# CloudFormation does NOT redeploy the API unless it has a new deployment resource
# that points to latest RestApi resource . Append a hash of Swagger Body location to
# redeploy only when the API data changes . First 10 characters of hash is good enough
# to prevent redeployment when API ha... |
def angle ( self , other ) :
"""Return the angle to the vector other""" | return math . acos ( self . dot ( other ) / ( self . magnitude ( ) * other . magnitude ( ) ) ) |
def finalize ( self , album_cache , image_cache , warn_node ) :
"""Update attributes after Sphinx cache is updated .
: param dict album _ cache : Cache of Imgur albums to read . Keys are Imgur IDs , values are Album instances .
: param dict image _ cache : Cache of Imgur images to read . Keys are Imgur IDs , va... | album = album_cache [ self . imgur_id ] if self . album else None
image = image_cache [ album . cover_id ] if self . album else image_cache [ self . imgur_id ]
options = self . options
# Determine target . Code in directives . py handles defaults and unsets target _ * if : target : is set .
if options [ 'target_gallery... |
def import_generated_autoboto_module ( self , name ) :
"""Imports a module from the generated autoboto package in the build directory ( not target _ dir ) .
For example , to import autoboto . services . s3 . shapes , call :
botogen . import _ generated _ autoboto _ module ( " services . s3 . shapes " )""" | if str ( self . config . build_dir ) not in sys . path :
sys . path . append ( str ( self . config . build_dir ) )
return importlib . import_module ( f"{self.config.target_package}.{name}" ) |
def _GetStat ( self ) :
"""Retrieves information about the file entry .
Returns :
VFSStat : a stat object .""" | stat_object = super ( APFSFileEntry , self ) . _GetStat ( )
# File data stat information .
stat_object . size = self . _fsapfs_file_entry . size
# Ownership and permissions stat information .
stat_object . mode = self . _fsapfs_file_entry . file_mode & 0x0fff
stat_object . uid = self . _fsapfs_file_entry . owner_identi... |
def setKUS ( self , K , U , S ) :
"""setKUS ( CLMM self , MatrixXd const & K , MatrixXd const & U , VectorXd const & S )
Parameters
K : MatrixXd const &
U : MatrixXd const &
S : VectorXd const &""" | return _core . CLMM_setKUS ( self , K , U , S ) |
def get_multiplicon_segments ( self , value ) :
"""Return a dictionary describing the genome segments that
contribute to the named multiplicon , keyed by genome , with
( start feature , end feature ) tuples .""" | sql = '''SELECT genome, first, last FROM segments
WHERE multiplicon=:mp'''
cur = self . _dbconn . cursor ( )
cur . execute ( sql , { 'mp' : str ( value ) } )
result = cur . fetchall ( )
cur . close ( )
segdict = collections . defaultdict ( tuple )
for genome , start , end in result :
segdict [ ge... |
def write_recording ( recording , save_path ) :
'''Save recording extractor to MEArec format .
Parameters
recording : RecordingExtractor
Recording extractor object to be saved
save _ path : str
. h5 or . hdf5 path''' | assert HAVE_MREX , "To use the MEArec extractors, install MEArec: \n\n pip install MEArec\n\n"
save_path = Path ( save_path )
if save_path . is_dir ( ) :
print ( "The file will be saved as recording.h5 in the provided folder" )
save_path = save_path / 'recording.h5'
if save_path . suffix == '.h5' or save_path .... |
def _safe_issue_checkout ( repo , issue = None ) :
"""Safely checkout branch for the issue .""" | branch_name = str ( issue ) if issue else 'master'
if branch_name not in repo . heads :
branch = repo . create_head ( branch_name )
else :
branch = repo . heads [ branch_name ]
branch . checkout ( ) |
def _write_conf_file ( ) :
"""Write configuration file as it is defined in settings .""" | with open ( CONF_FILE , "w" ) as f :
f . write ( DEFAULT_PROFTPD_CONF )
logger . debug ( "'%s' created." , CONF_FILE ) |
def _get_obs_array ( self , k , use_raw = False , layer = 'X' ) :
"""Get an array from the layer ( default layer = ' X ' ) along the observation dimension by first looking up
obs . keys and then var . index .""" | in_raw_var_names = k in self . raw . var_names if self . raw is not None else False
if use_raw and self . raw is None :
raise ValueError ( '.raw doesn\'t exist' )
if k in self . obs . keys ( ) :
x = self . _obs [ k ]
elif in_raw_var_names and use_raw and layer == 'X' :
x = self . raw [ : , k ] . X
elif k in... |
def _repr_pretty_ ( self , p , cycle ) :
"""Derived from IPython ' s dict and sequence pretty printer functions ,
https : / / github . com / ipython / ipython / blob / master / IPython / lib / pretty . py""" | if cycle :
p . text ( '{...}' )
else :
keys = self . keys ( )
if keys :
delim_start = '[{'
delim_end = '}]'
wid_max_max = self . _repr_max_width
wid_max = max ( [ len ( k ) for k in keys ] )
wid_max = min ( [ wid_max , wid_max_max ] )
key_template = '{{:{:d}s}... |
def make ( parser ) :
"""Prepare a data disk on remote host .""" | sub_command_help = dedent ( """
Create OSDs from a data disk on a remote host:
ceph-deploy osd create {node} --data /path/to/device
For bluestore, optional devices can be used::
ceph-deploy osd create {node} --data /path/to/data --block-db /path/to/db-device
ceph-deploy osd create {no... |
def getextensibleindex ( bunchdt , data , commdct , key , objname ) :
"""get the index of the first extensible item""" | theobject = getobject ( bunchdt , key , objname )
if theobject == None :
return None
theidd = iddofobject ( data , commdct , key )
extensible_i = [ i for i in range ( len ( theidd ) ) if 'begin-extensible' in theidd [ i ] ]
try :
extensible_i = extensible_i [ 0 ]
except IndexError :
return theobject |
def _check_disabled ( self ) :
"""Check if health check is disabled .
It logs a message if health check is disabled and it also adds an item
to the action queue based on ' on _ disabled ' setting .
Returns :
True if check is disabled otherwise False .""" | if self . config [ 'check_disabled' ] :
if self . config [ 'on_disabled' ] == 'withdraw' :
self . log . info ( "Check is disabled and ip_prefix will be " "withdrawn" )
self . log . info ( "adding %s in the queue" , self . ip_with_prefixlen )
self . action . put ( self . del_operation )
... |
def protected_operation ( fn ) :
"""Use this decorator to prevent an operation from being executed
when the related uri resource is still in use .
The parent _ object must contain :
* a request
* with a registry . queryUtility ( IReferencer )
: raises pyramid . httpexceptions . HTTPConflict : Signals that... | @ functools . wraps ( fn )
def advice ( parent_object , * args , ** kw ) :
response = _advice ( parent_object . request )
if response is not None :
return response
else :
return fn ( parent_object , * args , ** kw )
return advice |
def phoncontent ( self , cls = 'current' , correctionhandling = CorrectionHandling . CURRENT ) :
"""Get the phonetic content explicitly associated with this element ( of the specified class ) .
Unlike : meth : ` phon ` , this method does not recurse into child elements ( with the sole exception of the Correction ... | if not self . SPEAKABLE : # only printable elements can hold text
raise NoSuchPhon
# Find explicit text content ( same class )
for e in self :
if isinstance ( e , PhonContent ) :
if cls is None or e . cls == cls :
return e
elif isinstance ( e , Correction ) :
try :
re... |
def verify_create_instance ( self , ** kwargs ) :
"""Verifies an instance creation command .
Without actually placing an order .
See : func : ` create _ instance ` for a list of available options .
Example : :
new _ vsi = {
' domain ' : u ' test01 . labs . sftlyr . ws ' ,
' hostname ' : u ' minion05 ' ,... | kwargs . pop ( 'tags' , None )
create_options = self . _generate_create_dict ( ** kwargs )
return self . guest . generateOrderTemplate ( create_options ) |
def _set_limit ( self , v , load = False ) :
"""Setter method for limit , mapped from YANG variable / hardware / profile / tcam / limit ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ limit is considered as a private
method . Backends looking to populate... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = limit . limit , is_container = 'container' , presence = False , yang_name = "limit" , rest_name = "limit" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensi... |
def distance_to_contact ( D , alpha = 1 ) :
"""Compute contact matrix from input distance matrix . Distance values of
zeroes are given the largest contact count otherwise inferred non - zero
distance values .""" | if callable ( alpha ) :
distance_function = alpha
else :
try :
a = np . float64 ( alpha )
def distance_function ( x ) :
return 1 / ( x ** ( 1 / a ) )
except TypeError :
print ( "Alpha parameter must be callable or an array-like" )
raise
except ZeroDivisionErro... |
def load ( cls , path ) :
"""Create a new MLPipeline from a JSON specification .
The JSON file format is the same as the one created by the ` to _ dict ` method .
Args :
path ( str ) : Path of the JSON file to load .
Returns :
MLPipeline :
A new MLPipeline instance with the specification found
in the ... | with open ( path , 'r' ) as in_file :
metadata = json . load ( in_file )
return cls . from_dict ( metadata ) |
def get_results ( self , stream , time_interval ) :
"""Get the results for a given stream
: param time _ interval : The time interval
: param stream : The stream object
: return : A generator over stream instances""" | query = stream . stream_id . as_raw ( )
query [ 'datetime' ] = { '$gt' : time_interval . start , '$lte' : time_interval . end }
with switch_db ( StreamInstanceModel , 'hyperstream' ) :
for instance in StreamInstanceModel . objects ( __raw__ = query ) :
yield StreamInstance ( timestamp = instance . datetime ... |
def plot_fit ( self , ** kwargs ) :
"""Plots the fit of the model against the data""" | import matplotlib . pyplot as plt
import seaborn as sns
figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) )
plt . figure ( figsize = figsize )
date_index = self . index [ self . ar : self . data . shape [ 0 ] ]
mu , Y = self . _model ( self . latent_variables . get_z_values ( ) )
plt . plot ( date_index , Y , label = 'Da... |
def plotAccuracy ( suite , name ) :
"""Plots classification accuracy""" | path = suite . cfgparser . get ( name , "path" )
path = os . path . join ( path , name )
accuracy = defaultdict ( list )
sensations = defaultdict ( list )
for exp in suite . get_exps ( path = path ) :
params = suite . get_params ( exp )
maxTouches = params [ "num_sensations" ]
cells = params [ "cells_per_ax... |
def exclusive ( via = threading . Lock ) :
"""Mark a callable as exclusive
: param via : factory for a Lock to guard the callable
Guards the callable against being entered again before completion .
Explicitly raises a : py : exc : ` RuntimeError ` on violation .
: note : If applied to a method , it is exclu... | def make_exclusive ( fnc ) :
fnc_guard = via ( )
@ functools . wraps ( fnc )
def exclusive_call ( * args , ** kwargs ) :
if fnc_guard . acquire ( blocking = False ) :
try :
return fnc ( * args , ** kwargs )
finally :
fnc_guard . release ( )
... |
def _SetSshHostKeys ( self , host_key_types = None ) :
"""Regenerates SSH host keys when the VM is restarted with a new IP address .
Booting a VM from an image with a known SSH key allows a number of attacks .
This function will regenerating the host key whenever the IP address
changes . This applies the firs... | section = 'Instance'
instance_id = self . _GetInstanceId ( )
if instance_id != self . instance_config . GetOptionString ( section , 'instance_id' ) :
self . logger . info ( 'Generating SSH host keys for instance %s.' , instance_id )
file_regex = re . compile ( r'ssh_host_(?P<type>[a-z0-9]*)_key\Z' )
key_dir... |
def ugettext ( self , text ) :
"""Translates message / text and returns it in a unicode string .
Using runtime to get i18n service .""" | runtime_service = self . runtime . service ( self , "i18n" )
runtime_ugettext = runtime_service . ugettext
return runtime_ugettext ( text ) |
def _extract_jar ( self , coordinate , jar_path ) :
"""Extracts the jar to a subfolder of workdir / extracted and returns the path to it .""" | with open ( jar_path , 'rb' ) as f :
sha = sha1 ( f . read ( ) ) . hexdigest ( )
outdir = os . path . join ( self . workdir , 'extracted' , sha )
if not os . path . exists ( outdir ) :
ZIP . extract ( jar_path , outdir )
self . context . log . debug ( 'Extracting jar {jar} at {jar_path}.' . format ( jar... |
def requires_product_environment ( func , * args , ** kws ) :
"""task decorator that makes sure that the product environment
of django _ productline is activated :
- context is bound
- features have been composed""" | from django_productline import startup
startup . select_product ( )
return func ( * args , ** kws ) |
def poll_for_response ( self ) :
"""Polls the device for user input
If there is a keymapping for the device , the key map is applied
to the key reported from the device .
If a response is waiting to be processed , the response is appended
to the internal response _ queue""" | key_state = self . con . check_for_keypress ( )
if key_state != NO_KEY_DETECTED :
response = self . con . get_current_response ( )
if self . keymap is not None :
response [ 'key' ] = self . keymap [ response [ 'key' ] ]
else :
response [ 'key' ] -= 1
self . response_queue . append ( resp... |
def _apply ( self , plan ) :
'''Required function of manager . py to actually apply a record change .
: param plan : Contains the zones and changes to be made
: type plan : octodns . provider . base . Plan
: type return : void''' | desired = plan . desired
changes = plan . changes
self . log . debug ( '_apply: zone=%s, len(changes)=%d' , desired . name , len ( changes ) )
azure_zone_name = desired . name [ : len ( desired . name ) - 1 ]
self . _check_zone ( azure_zone_name , create = True )
for change in changes :
class_name = change . __clas... |
def parent_folder ( path , base = None ) :
""": param str | None path : Path to file or folder
: param str | None base : Base folder to use for relative paths ( default : current working dir )
: return str : Absolute path of parent folder of ' path '""" | return path and os . path . dirname ( resolved_path ( path , base = base ) ) |
def _handle_func_def ( self , node , scope , ctxt , stream ) :
"""Handle FuncDef nodes
: node : TODO
: scope : TODO
: ctxt : TODO
: stream : TODO
: returns : TODO""" | self . _dlog ( "handling function definition" )
func = self . _handle_node ( node . decl , scope , ctxt , stream )
func . body = node . body |
def remove_profile ( self , profile ) :
"""Remove a profile .
: param profile : The profile to be removed .
: type profile : basestring , str""" | self . remove_file ( os . path . join ( self . root_directory , 'minimum_needs' , profile + '.json' ) ) |
def _check_max_running ( self , func , data , opts , now ) :
'''Return the schedule data structure''' | # Check to see if there are other jobs with this
# signature running . If there are more than maxrunning
# jobs present then don ' t start another .
# If jid _ include is False for this job we can ignore all this
# NOTE - - jid _ include defaults to True , thus if it is missing from the data
# dict we treat it like it ... |
def setMaxSpeed ( self , laneID , speed ) :
"""setMaxSpeed ( string , double ) - > None
Sets a new maximum allowed speed on the lane in m / s .""" | self . _connection . _sendDoubleCmd ( tc . CMD_SET_LANE_VARIABLE , tc . VAR_MAXSPEED , laneID , speed ) |
def sign ( self , consumer_secret , access_token_secret , method , url , oauth_params , req_kwargs ) :
'''Sign request using PLAINTEXT method .
: param consumer _ secret : Consumer secret .
: type consumer _ secret : str
: param access _ token _ secret : Access token secret ( optional ) .
: type access _ to... | key = self . _escape ( consumer_secret ) + b'&'
if access_token_secret :
key += self . _escape ( access_token_secret )
return key . decode ( ) |
def _instantiate ( cls , params ) :
"""Helper to instantiate Attention classes from parameters . Warns in log if parameter is not supported
by class constructor .
: param cls : Attention class .
: param params : configuration parameters .
: return : instance of ` cls ` type .""" | sig_params = inspect . signature ( cls . __init__ ) . parameters
valid_params = dict ( )
for key , value in params . items ( ) :
if key in sig_params :
valid_params [ key ] = value
else :
logger . debug ( 'Type %s does not support parameter \'%s\'' % ( cls . __name__ , key ) )
return cls ( ** va... |
def get_embedded_items ( result_collection ) :
"""Given a result _ collection ( returned by a previous API call that
returns a collection , like get _ bundle _ list ( ) or search ( ) ) , return a
list of embedded items with each item in the returned list
considered a result object .
' result _ collection ' ... | # Argument error checking .
assert result_collection is not None
result = [ ]
embedded_objects = result_collection . get ( '_embedded' )
if embedded_objects is not None : # Handle being passed a non - collection gracefully .
result = embedded_objects . get ( 'items' , result )
return result |
def formatmonthname ( self , theyear , themonth , withyear = True ) :
"""Return a month name translated as a table row .""" | monthname = '%s %s' % ( MONTHS [ themonth ] . title ( ) , theyear )
return '<caption>%s</caption>' % monthname |
def _get_all_eip_addresses ( addresses = None , allocation_ids = None , region = None , key = None , keyid = None , profile = None ) :
'''Get all EIP ' s associated with the current credentials .
addresses
( list ) - Optional list of addresses . If provided , only those those in the
list will be returned .
... | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
return conn . get_all_addresses ( addresses = addresses , allocation_ids = allocation_ids )
except boto . exception . BotoServerError as e :
log . error ( e )
return [ ] |
def to_list ( self , n = None ) :
"""Converts sequence to list of elements .
> > > type ( seq ( [ ] ) . to _ list ( ) )
list
> > > type ( seq ( [ ] ) )
functional . pipeline . Sequence
> > > seq ( [ 1 , 2 , 3 ] ) . to _ list ( )
[1 , 2 , 3]
: param n : Take n elements of sequence if not None
: retur... | if n is None :
self . cache ( )
return self . _base_sequence
else :
return self . cache ( ) . take ( n ) . list ( ) |
def begin ( self ) :
"""Called once before using the session to check global step .""" | self . _global_step_tensor = tf . train . get_global_step ( )
if self . _global_step_tensor is None :
raise RuntimeError ( 'Global step should be created to use StepCounterHook.' ) |
def _patch_for_tf1_12 ( tf ) :
"""Monkey patch tf 1.12 so tfds can use it .""" | tf . io . gfile = tf . gfile
tf . io . gfile . copy = tf . gfile . Copy
tf . io . gfile . exists = tf . gfile . Exists
tf . io . gfile . glob = tf . gfile . Glob
tf . io . gfile . isdir = tf . gfile . IsDirectory
tf . io . gfile . listdir = tf . gfile . ListDirectory
tf . io . gfile . makedirs = tf . gfile . MakeDirs
t... |
def simxGetCollectionHandle ( clientID , collectionName , operationMode ) :
'''Please have a look at the function description / documentation in the V - REP user manual''' | handle = ct . c_int ( )
if ( sys . version_info [ 0 ] == 3 ) and ( type ( collectionName ) is str ) :
collectionName = collectionName . encode ( 'utf-8' )
return c_GetCollectionHandle ( clientID , collectionName , ct . byref ( handle ) , operationMode ) , handle . value |
def OpenDialog ( self , Name , * Params ) :
"""Open dialog . Use this method to open dialogs added in newer Skype versions if there is no
dedicated method in Skype4Py .
: Parameters :
Name : str
Dialog name .
Params : unicode
One or more optional parameters .""" | self . _Skype . _Api . allow_focus ( self . _Skype . Timeout )
params = filter ( None , ( str ( Name ) , ) + Params )
self . _Skype . _DoCommand ( 'OPEN %s' % tounicode ( ' ' . join ( params ) ) ) |
def find_matching_middleware ( self , method , path ) :
"""Iterator handling the matching of middleware against a method + path
pair . Yields the middleware , and the""" | for mw in self . mw_list :
if not mw . matches_method ( method ) :
continue
# get the path matching this middleware and the ' rest ' of the url
# ( i . e . the part that comes AFTER the match ) to be potentially
# matched later by a subchain
path_match , rest_url = mw . path_split ( path )
... |
def _adaptSynapses ( self , inputVector , activeColumns , predictedActiveCells ) :
"""This is the primary learning method . It updates synapses ' permanence based
on the bottom - up input to the TP and the TP ' s active cells .
For each active cell , its synapses ' permanences are updated as follows :
1 . if ... | inputIndices = numpy . where ( inputVector > 0 ) [ 0 ]
predictedIndices = numpy . where ( predictedActiveCells > 0 ) [ 0 ]
permChanges = numpy . zeros ( self . _numInputs )
# Decrement inactive TM cell - > active TP cell connections
permChanges . fill ( - 1 * self . _synPermInactiveDec )
# Increment active TM cell - > ... |
def create_adv_by_name ( model , x , attack_type , sess , dataset , y = None , ** kwargs ) :
"""Creates the symbolic graph of an adversarial example given the name of
an attack . Simplifies creating the symbolic graph of an attack by defining
dataset - specific parameters .
Dataset - specific default paramete... | # TODO : black box attacks
attack_names = { 'FGSM' : FastGradientMethod , 'MadryEtAl' : MadryEtAl , 'MadryEtAl_y' : MadryEtAl , 'MadryEtAl_multigpu' : MadryEtAlMultiGPU , 'MadryEtAl_y_multigpu' : MadryEtAlMultiGPU }
if attack_type not in attack_names :
raise Exception ( 'Attack %s not defined.' % attack_type )
atta... |
def solution_path ( self , min_lambda , max_lambda , lambda_bins , verbose = 0 ) :
'''Follows the solution path to find the best lambda value .''' | lambda_grid = np . exp ( np . linspace ( np . log ( max_lambda ) , np . log ( min_lambda ) , lambda_bins ) )
aic_trace = np . zeros ( lambda_grid . shape )
# The AIC score for each lambda value
aicc_trace = np . zeros ( lambda_grid . shape )
# The AICc score for each lambda value ( correcting for finite sample size )
b... |
def logical_or ( self , other ) :
"""logical _ or ( t ) = self ( t ) or other ( t ) .""" | return self . operation ( other , lambda x , y : int ( x or y ) ) |
def add_context ( request ) :
"""Add variables to all dictionaries passed to templates .""" | # Whether the user has president privileges
try :
PRESIDENT = Manager . objects . filter ( incumbent__user = request . user , president = True , ) . count ( ) > 0
except TypeError :
PRESIDENT = False
# If the user is logged in as an anymous user
if request . user . username == ANONYMOUS_USERNAME :
request .... |
def vertices_per_edge ( self ) :
"""Returns an Ex2 array of adjacencies between vertices , where
each element in the array is a vertex index . Each edge is included
only once . Edges that are not shared by 2 faces are not included .""" | import numpy as np
return np . asarray ( [ vertices_in_common ( e [ 0 ] , e [ 1 ] ) for e in self . f [ self . faces_per_edge ] ] ) |
def days_since_last_snowfall ( self , value = 99 ) :
"""Corresponds to IDD Field ` days _ since _ last _ snowfall `
Args :
value ( int ) : value for IDD Field ` days _ since _ last _ snowfall `
Missing value : 99
if ` value ` is None it will not be checked against the
specification and is assumed to be a ... | if value is not None :
try :
value = int ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type int ' 'for field `days_since_last_snowfall`' . format ( value ) )
self . _days_since_last_snowfall = value |
def dict_minus ( d , * keys ) :
"""Delete key ( s ) from dict if exists , returning resulting dict""" | # make shallow copy
d = dict ( d )
for key in keys :
try :
del d [ key ]
except :
pass
return d |
def writeIslandBoxes ( filename , catalog , fmt ) :
"""Write an output file in ds9 . reg , or kvis . ann format that contains bounding boxes for all the islands .
Parameters
filename : str
Filename to write .
catalog : list
List of sources . Only those of type : class : ` AegeanTools . models . IslandSour... | if fmt not in [ 'reg' , 'ann' ] :
log . warning ( "Format not supported for island boxes{0}" . format ( fmt ) )
return
# fmt not supported
out = open ( filename , 'w' )
print ( "#Aegean Islands" , file = out )
print ( "#Aegean version {0}-({1})" . format ( __version__ , __date__ ) , file = out )
if fmt == 'reg'... |
def _simulated_chain_result ( self , potential_chain , already_used_bonus ) :
"""Simulate any chain reactions .
Arguments :
potential _ chain : a state to be tested for chain reactions
already _ used _ bonus : boolean indicating whether a bonus turn was already
applied during this action
Return : final re... | while potential_chain : # hook for capture game optimizations . no effect in base
# warning : only do this ONCE for any given state or it will
# always filter the second time
if self . _disallow_state ( potential_chain ) :
potential_chain . graft_child ( Filtered ( ) )
return None
# no more ... |
def sort_canonical ( keyword , stmts ) :
"""Sort all ` stmts ` in the canonical order defined by ` keyword ` .
Return the sorted list . The ` stmt ` list is not modified .
If ` keyword ` does not have a canonical order , the list is returned
as is .""" | try :
( _arg_type , subspec ) = stmt_map [ keyword ]
except KeyError :
return stmts
res = [ ]
# keep the order of data definition statements and case
keep = [ s [ 0 ] for s in data_def_stmts ] + [ 'case' ]
for ( kw , _spec ) in flatten_spec ( subspec ) : # keep comments before a statement together with that sta... |
def _normalize_slice ( self , key , clamp = False ) :
"""Return a slice equivalent to the input * key * , standardized .""" | if key . start is None :
start = 0
else :
start = ( len ( self ) + key . start ) if key . start < 0 else key . start
if key . stop is None or key . stop == maxsize :
stop = len ( self ) if clamp else None
else :
stop = ( len ( self ) + key . stop ) if key . stop < 0 else key . stop
return slice ( start ... |
def get_config ( ) :
"""Read the configfile and return config dict .
Returns
dict
Dictionary with the content of the configpath file .""" | configpath = get_configpath ( )
if not configpath . exists ( ) :
raise IOError ( "Config file {} not found." . format ( str ( configpath ) ) )
else :
config = configparser . ConfigParser ( )
config . read ( str ( configpath ) )
return config |
def p_word_list ( p ) :
'''word _ list : WORD
| word _ list WORD''' | parserobj = p . context
if len ( p ) == 2 :
p [ 0 ] = [ _expandword ( parserobj , p . slice [ 1 ] ) ]
else :
p [ 0 ] = p [ 1 ]
p [ 0 ] . append ( _expandword ( parserobj , p . slice [ 2 ] ) ) |
def auto ( self , enabled = True , ** kwargs ) :
"""Method to enable or disable automatic capture , allowing you to
simultaneously set the instance parameters .""" | self . namespace = self . get_namespace ( )
self . notebook_name = "{notebook}"
self . _timestamp = tuple ( time . localtime ( ) )
kernel = r'var kernel = IPython.notebook.kernel; '
nbname = r"var nbname = IPython.notebook.get_notebook_name(); "
nbcmd = ( r"var name_cmd = '%s.notebook_name = \"' + nbname + '\"'; " % se... |
def eta_mass1_to_mass2 ( eta , mass1 , return_mass_heavier = False , force_real = True ) :
"""This function takes values for eta and one component mass and returns the
second component mass . Similar to mchirp _ mass1 _ to _ mass2 this requires
finding the roots of a quadratic equation . Basically :
eta m2 ^ ... | return conversions . mass_from_knownmass_eta ( mass1 , eta , known_is_secondary = return_mass_heavier , force_real = force_real ) |
def transform ( self , X ) :
"""Add the features calculated using the timeseries _ container and add them to the corresponding rows in the input
pandas . DataFrame X .
To save some computing time , you should only include those time serieses in the container , that you
need . You can set the timeseries contai... | if self . timeseries_container is None :
raise RuntimeError ( "You have to provide a time series using the set_timeseries_container function before." )
# Extract only features for the IDs in X . index
timeseries_container_X = restrict_input_to_index ( self . timeseries_container , self . column_id , X . index )
ext... |
def _encode_char ( char , charmap , defaultchar ) :
"""Encode a single character with the given encoding map
: param char : char to encode
: param charmap : dictionary for mapping characters in this code page""" | if ord ( char ) < 128 :
return ord ( char )
if char in charmap :
return charmap [ char ]
return ord ( defaultchar ) |
def cv_precompute ( self , mask , b ) :
'''Pre - compute the matrices : py : obj : ` A ` and : py : obj : ` B `
( cross - validation step only )
for chunk : py : obj : ` b ` .''' | # Get current chunk and mask outliers
m1 = self . get_masked_chunk ( b )
flux = self . fraw [ m1 ]
K = GetCovariance ( self . kernel , self . kernel_params , self . time [ m1 ] , self . fraw_err [ m1 ] )
med = np . nanmedian ( flux )
# Now mask the validation set
M = lambda x , axis = 0 : np . delete ( x , mask , axis ... |
def remove_from_products ( self , products = None , all_products = False ) :
"""Remove user group from some product license configuration groups ( PLCs ) , or all of them .
: param products : list of product names the user group should be removed from
: param all _ products : a boolean meaning remove from all (... | if all_products :
if products :
raise ArgumentError ( "When removing from all products, do not specify specific products" )
plist = "all"
else :
if not products :
raise ArgumentError ( "You must specify products from which to remove the user group" )
plist = { GroupTypes . productConfigu... |
def mysql_to_dict ( data , key ) :
'''Convert MySQL - style output to a python dictionary''' | ret = { }
headers = [ '' ]
for line in data :
if not line :
continue
if line . startswith ( '+' ) :
continue
comps = line . split ( '|' )
for comp in range ( len ( comps ) ) :
comps [ comp ] = comps [ comp ] . strip ( )
if len ( headers ) > 1 :
index = len ( headers )... |
def simple_cmd ( ) :
"""` ` Deprecated ` ` : Not better than ` ` fire ` ` - > pip install fire""" | parser = argparse . ArgumentParser ( prog = "Simple command-line function toolkit." , description = """Input function name and args and kwargs.
python xxx.py main -a 1 2 3 -k a=1,b=2,c=3""" , )
parser . add_argument ( "-f" , "--func_name" , default = "main" )
parser . add_argument ( "-a" , "--args" , dest = "ar... |
def update_subscription ( request , ident ) :
"Shows subscriptions options for a verified subscriber ." | try :
subscription = Subscription . objects . get ( ident = ident )
except Subscription . DoesNotExist :
return respond ( 'overseer/invalid_subscription_token.html' , { } , request )
if request . POST :
form = UpdateSubscriptionForm ( request . POST , instance = subscription )
if form . is_valid ( ) :
... |
def _dump_model ( model , attrs = None ) :
"""Dump the model fields for debugging .""" | fields = [ ]
for field in model . _meta . fields :
fields . append ( ( field . name , str ( getattr ( model , field . name ) ) ) )
if attrs is not None :
for attr in attrs :
fields . append ( ( attr , str ( getattr ( model , attr ) ) ) )
for field in model . _meta . many_to_many :
vals = getattr ( m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.