signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def dense ( * elements ) :
"""Create a dense vector of 64 - bit floats from a Python list or numbers .
> > > Vectors . dense ( [ 1 , 2 , 3 ] )
DenseVector ( [ 1.0 , 2.0 , 3.0 ] )
> > > Vectors . dense ( 1.0 , 2.0)
DenseVector ( [ 1.0 , 2.0 ] )""" | if len ( elements ) == 1 and not isinstance ( elements [ 0 ] , ( float , int , long ) ) : # it ' s list , numpy . array or other iterable object .
elements = elements [ 0 ]
return DenseVector ( elements ) |
def do_break ( self , arg , temporary = 0 ) :
"""b ( reak ) [ ( [ filename : ] lineno | function ) [ , condition ] ]
Without argument , list all breaks .
With a line number argument , set a break at this line in the
current file . With a function name , set a break at the first
executable line of that funct... | if not arg :
all_breaks = '\n' . join ( bp . bpformat ( ) for bp in bdb . Breakpoint . bpbynumber if bp )
if all_breaks :
self . message ( "Num Type Disp Enb Where" )
self . message ( all_breaks )
return
# Parse arguments , comma has lowest precedence and cannot occur in
# filename... |
def MessageToRepr ( msg , multiline = False , ** kwargs ) :
"""Return a repr - style string for a protorpc message .
protorpc . Message . _ _ repr _ _ does not return anything that could be considered
python code . Adding this function lets us print a protorpc message in such
a way that it could be pasted int... | # TODO ( jasmuth ) : craigcitro suggests a pretty - printer from apitools / gen .
indent = kwargs . get ( 'indent' , 0 )
def IndentKwargs ( kwargs ) :
kwargs = dict ( kwargs )
kwargs [ 'indent' ] = kwargs . get ( 'indent' , 0 ) + 4
return kwargs
if isinstance ( msg , list ) :
s = '['
for item in msg... |
def parse_stats ( self , soup ) :
"""Given :
soup : a bs4 element containing the current media list ' s stats
Return a dict of this media list ' s stats .""" | stats = { }
for row in soup . children :
try :
key = row . name . replace ( u'user_' , u'' )
if key == u'id' :
stats [ key ] = int ( row . text )
elif key == u'name' :
stats [ key ] = row . text
elif key == self . verb + u'ing' :
try :
... |
def features ( self ) :
"""List of features .""" | r = [ ]
for _ , inter in self . props . items ( ) :
if isinstance ( inter , tuple ) :
if ( inter [ 0 ] and inter [ 1 ] and inter [ 0 ] . getValue ( ) == inter [ 1 ] . getValue ( ) and inter [ 0 ] . operator == "=" and inter [ 1 ] . operator == "=" ) :
r . append ( inter [ 0 ] )
else :
... |
async def grant ( self , username , acl = 'login' ) :
"""Grant access level of the given user on the controller .
Note that if the user already has higher permissions than the
provided ACL , this will do nothing ( see revoke for a way to
remove permissions ) .
: param str username : Username
: param str a... | controller_facade = client . ControllerFacade . from_connection ( self . connection ( ) )
user = tag . user ( username )
changes = client . ModifyControllerAccess ( acl , 'grant' , user )
try :
await controller_facade . ModifyControllerAccess ( [ changes ] )
return True
except errors . JujuError as e :
if '... |
def render ( self , trajectories : Tuple [ NonFluents , Fluents , Fluents , Fluents , np . array ] , batch : Optional [ int ] = None ) -> None :
'''Renders the simulated ` trajectories ` for the given ` batch ` .
Args :
trajectories : NonFluents , states , actions , interms and rewards .
batch : Number of bat... | raise NotImplementedError |
def set_access_port ( self , port_number , vlan_id ) :
"""Sets the specified port as an ACCESS port .
: param port _ number : allocated port number
: param vlan _ id : VLAN number membership""" | if port_number not in self . _nios :
raise DynamipsError ( "Port {} is not allocated" . format ( port_number ) )
nio = self . _nios [ port_number ]
yield from self . _hypervisor . send ( 'ethsw set_access_port "{name}" {nio} {vlan_id}' . format ( name = self . _name , nio = nio , vlan_id = vlan_id ) )
log . info ( ... |
def thumbnail ( parser , token ) :
"""Creates a thumbnail of for an ImageField .
To just output the absolute url to the thumbnail : :
{ % thumbnail image 80x80 % }
After the image path and dimensions , you can put any options : :
{ % thumbnail image 80x80 force _ ssl = True % }
To put the thumbnail URL on... | args = token . split_contents ( )
tag = args [ 0 ]
# Check to see if we ' re setting to a context variable .
if len ( args ) > 4 and args [ - 2 ] == 'as' :
context_name = args [ - 1 ]
args = args [ : - 2 ]
else :
context_name = None
if len ( args ) < 3 :
raise TemplateSyntaxError ( "Invalid syntax. Expe... |
def create_summary_tear_sheet ( factor_data , long_short = True , group_neutral = False ) :
"""Creates a small summary tear sheet with returns , information , and turnover
analysis .
Parameters
factor _ data : pd . DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date ( level 0 ) and asset ( level 1... | # Returns Analysis
mean_quant_ret , std_quantile = perf . mean_return_by_quantile ( factor_data , by_group = False , demeaned = long_short , group_adjust = group_neutral )
mean_quant_rateret = mean_quant_ret . apply ( utils . rate_of_return , axis = 0 , base_period = mean_quant_ret . columns [ 0 ] )
mean_quant_ret_byda... |
def _read_s3_config ( self ) :
"""Read in the value of the configuration file in Amazon S3.
: rtype : str
: raises : ValueError""" | try :
import boto3
import botocore . exceptions
except ImportError :
boto3 , botocore = None , None
if not boto3 :
raise ValueError ( 's3 URL specified for configuration but boto3 not installed' )
parsed = parse . urlparse ( self . _file_path )
try :
response = boto3 . client ( 's3' , endpoint_url =... |
def delete_data_source ( self , data_source ) :
"""Delete data source with it ' s name or ID .
data _ source = { ' imap ' : { ' name ' : ' data - source - name ' } }
or
data _ source = { ' pop3 ' : { ' id ' : ' data - source - id ' } }""" | source_type = [ k for k in data_source . keys ( ) ] [ 0 ]
complete_source = self . get_data_sources ( source_id = data_source [ source_type ] [ 'id' ] )
folder_id = complete_source [ source_type ] [ 0 ] [ 'l' ]
self . delete_folders ( folder_ids = [ folder_id ] )
return self . request ( 'DeleteDataSource' , data_source... |
def step ( self , ** args ) :
"""Network . step ( )
Does a single step . Calls propagate ( ) , backprop ( ) , and
change _ weights ( ) if learning is set .
Format for parameters : < layer name > = < activation / target list >""" | if self . verbosity > 0 :
print ( "Network.step() called with:" , args )
# First , copy the values into either activations or targets :
retargs = self . preStep ( ** args )
if retargs :
args = retargs
# replace the args
# Propagate activation through network :
self . propagate ( ** args )
retargs = self . p... |
def ignore_proxy_host ( self ) :
"""Check if self . host is in the $ no _ proxy ignore list .""" | if urllib . proxy_bypass ( self . host ) :
return True
no_proxy = os . environ . get ( "no_proxy" )
if no_proxy :
entries = [ parse_host_port ( x ) for x in no_proxy . split ( "," ) ]
for host , port in entries :
if host . lower ( ) == self . host and port == self . port :
return True
re... |
def update_user ( self , user_name , new_user_name = None , new_path = None ) :
"""Updates name and / or path of the specified user .
: type user _ name : string
: param user _ name : The name of the user
: type new _ user _ name : string
: param new _ user _ name : If provided , the username of the user wi... | params = { 'UserName' : user_name }
if new_user_name :
params [ 'NewUserName' ] = new_user_name
if new_path :
params [ 'NewPath' ] = new_path
return self . get_response ( 'UpdateUser' , params ) |
def compileInterpolatableTTFsFromDS ( designSpaceDoc , preProcessorClass = TTFInterpolatablePreProcessor , outlineCompilerClass = OutlineTTFCompiler , featureCompilerClass = None , featureWriters = None , glyphOrder = None , useProductionNames = None , cubicConversionError = None , reverseDirection = True , inplace = F... | ufos , layerNames = [ ] , [ ]
for source in designSpaceDoc . sources :
if source . font is None :
raise AttributeError ( "designspace source '%s' is missing required 'font' attribute" % getattr ( source , "name" , "<Unknown>" ) )
ufos . append ( source . font )
# ' layerName ' is None for the defaul... |
def syllable_split ( string ) :
'''Split ' string ' into ( stressed ) syllables and punctuation / whitespace .''' | p = r'\'[%s]+|`[%s]+|[%s]+|[^%s\'`\.]+|[^\.]{1}' % ( A , A , A , A )
return re . findall ( p , string , flags = FLAGS ) |
def get_current_url ( environ , root_only = False , strip_querystring = False , host_only = False ) :
"""A handy helper function that recreates the full URL for the current
request or parts of it . Here an example :
> > > from werkzeug import create _ environ
> > > env = create _ environ ( " / ? param = foo "... | tmp = [ environ [ "wsgi.url_scheme" ] , "://" , get_host ( environ ) ]
cat = tmp . append
if host_only :
return "" . join ( tmp ) + "/"
cat ( quote ( environ . get ( "SCRIPT_NAME" , "" ) . rstrip ( "/" ) ) )
if root_only :
cat ( "/" )
else :
cat ( quote ( "/" + environ . get ( "PATH_INFO" , "" ) . lstrip ( ... |
def confirmation_pdf ( self , confirmation_id ) :
"""Opens a pdf of a confirmation
: param confirmation _ id : the confirmation id
: return : dict""" | return self . _create_get_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , command = PDF ) |
def render_source ( self , source , variables = None ) :
"""Render a source with the passed variables .""" | if variables is None :
variables = { }
template = self . _engine . from_string ( source )
return template . render ( ** variables ) |
def install_optimal_reactor ( verbose = False ) :
"""Try to install the optimal Twisted reactor for platform .
: param verbose : If ` ` True ` ` , print what happens .
: type verbose : bool""" | import sys
from twisted . python import reflect
# # determine currently installed reactor , if any
if 'twisted.internet.reactor' in sys . modules :
current_reactor = reflect . qual ( sys . modules [ 'twisted.internet.reactor' ] . __class__ ) . split ( '.' ) [ - 1 ]
else :
current_reactor = None
# # depending on... |
def _get_client ( ) :
'''Return a cloud client''' | client = salt . cloud . CloudClient ( os . path . join ( os . path . dirname ( __opts__ [ 'conf_file' ] ) , 'cloud' ) , pillars = copy . deepcopy ( __pillar__ . get ( 'cloud' , { } ) ) )
return client |
def build_pages ( self ) :
"""Iterate over the pages _ dir and build the pages""" | for root , _ , files in os . walk ( self . pages_dir ) :
base_dir = root . replace ( self . pages_dir , "" ) . lstrip ( "/" )
if not base_dir . startswith ( "_" ) :
for f in files :
src_file = os . path . join ( base_dir , f )
self . _build_page ( src_file ) |
def read ( self ) :
"""Read the target value
Use $ project aggregate operator in order to support nested objects""" | result = self . get_collection ( ) . aggregate ( [ { '$match' : { '_id' : self . _document_id } } , { '$project' : { '_value' : '$' + self . _path , '_id' : False } } ] )
for doc in result :
if '_value' not in doc :
break
return doc [ '_value' ] |
def add_scan_host_detail ( self , scan_id , host = '' , name = '' , value = '' ) :
"""Adds a host detail result to scan _ id scan .""" | self . scan_collection . add_result ( scan_id , ResultType . HOST_DETAIL , host , name , value ) |
def search_url ( self , var = DEFAULT_SEARCH_ENV , default = NOTSET , engine = None ) :
"""Returns a config dictionary , defaulting to SEARCH _ URL .
: rtype : dict""" | return self . search_url_config ( self . url ( var , default = default ) , engine = engine ) |
def stop ( self ) :
"""Stop the client . This sends a signal to the clients main task which
makes it terminate .
It may take some cycles through the event loop to stop the client
task . To check whether the task has actually stopped , query
: attr : ` running ` .""" | if not self . running :
return
self . logger . debug ( "stopping main task of %r" , self , stack_info = True )
self . _main_task . cancel ( ) |
def diff_table ( self , table1 , table2 ) :
"""Returns the difference between the tables table1 and table2.
: type table1 : Table
: type table2 : Table
: rtype : TableDiff""" | changes = 0
table_differences = TableDiff ( table1 . get_name ( ) )
table_differences . from_table = table1
table1_columns = table1 . get_columns ( )
table2_columns = table2 . get_columns ( )
# See if all the fields in table1 exist in table2
for column_name , column in table2_columns . items ( ) :
if not table1 . h... |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for spec of input and result values .""" | # extracting dictionary of coefficients specific to required
# intensity measure type .
C = self . COEFFS [ imt ]
C_PGA = self . COEFFS [ PGA ( ) ]
imt_per = 0 if imt . name == 'PGV' else imt . period
pga_rock = self . _get_pga_on_rock ( C_PGA , rup , dists )
mean = ( self . _get_magnitude_scaling_term ( C , rup ) + se... |
def _GetAPFSVolumeIdentifiers ( self , scan_node ) :
"""Determines the APFS volume identifiers .
Args :
scan _ node ( SourceScanNode ) : scan node .
Returns :
list [ str ] : APFS volume identifiers .
Raises :
ScannerError : if the format of or within the source is not supported
or the the scan node is... | if not scan_node or not scan_node . path_spec :
raise errors . ScannerError ( 'Invalid scan node.' )
volume_system = apfs_volume_system . APFSVolumeSystem ( )
volume_system . Open ( scan_node . path_spec )
volume_identifiers = self . _source_scanner . GetVolumeIdentifiers ( volume_system )
if not volume_identifiers... |
def import_from_path ( path ) :
"""Import a class dynamically , given it ' s dotted path .
: param path : the path of the module
: type path : string
: return : Return the value of the named attribute of object .
: rtype : object""" | module_name , class_name = path . rsplit ( '.' , 1 )
try :
return getattr ( __import__ ( module_name , fromlist = [ class_name ] ) , class_name )
except AttributeError :
raise ImportError ( 'Unable to import %s' % path ) |
def from_otgformat ( self , otgOrder ) :
"""[ summary ]
Arguments :
otgOrder { [ type ] } - - [ description ]
{ ' seqno ' : 6,
' user _ id ' : ' 106184 ' ,
' order _ id ' : ' WDRB _ QA01 _ FtNlyBem ' ,
' exchange _ id ' : ' SHFE ' ,
' instrument _ id ' : ' rb1905 ' ,
' direction ' : ' SELL ' ,
' o... | self . order_id = otgOrder . get ( 'order_id' )
self . account_cookie = otgOrder . get ( 'user_id' )
self . exchange_id = otgOrder . get ( 'exchange_id' )
self . code = str ( otgOrder . get ( 'instrument_id' ) ) . upper ( )
self . offset = otgOrder . get ( 'offset' )
self . direction = otgOrder . get ( 'direction' )
se... |
def v1_tag_suggest ( request , tags , prefix , parent = '' ) :
'''Provide fast suggestions for tag components .
This yields suggestions for * components * of a tag and a given
prefix . For example , given the tags ` ` foo / bar / baz ` ` and
` ` fob / bob ` ` , here are some example completions ( ordering may... | prefix = prefix . decode ( 'utf-8' ) . strip ( )
parent = parent . decode ( 'utf-8' ) . strip ( )
limit = min ( 10000 , int ( request . params . get ( 'limit' , 100 ) ) )
return { 'suggestions' : tags . suggest ( parent , prefix , limit = limit ) } |
def on_lstCategories_itemSelectionChanged ( self ) :
"""Update purpose description label .
. . note : : This is an automatic Qt slot
executed when the purpose selection changes .""" | self . clear_further_steps ( )
# Set widgets
purpose = self . selected_purpose ( )
# Exit if no selection
if not purpose :
return
# Set description label
self . lblDescribeCategory . setText ( purpose [ "description" ] )
self . lblIconCategory . setPixmap ( QPixmap ( resources_path ( 'img' , 'wizard' , 'keyword-cat... |
def python_value ( self , dtype , dvalue ) :
"""Convert a CLIPS type into Python .""" | try :
return CONVERTERS [ dtype ] ( dvalue )
except KeyError :
if dtype == clips . common . CLIPSType . MULTIFIELD :
return self . multifield_to_list ( )
if dtype == clips . common . CLIPSType . FACT_ADDRESS :
return clips . facts . new_fact ( self . _env , lib . to_pointer ( dvalue ) )
... |
def payload_unregister ( klass , pid ) :
"""is used while a hook is running to let Juju know
that a payload has been manually stopped . The < class > and < id > provided
must match a payload that has been previously registered with juju using
payload - register .""" | cmd = [ 'payload-unregister' ]
for x in [ klass , pid ] :
cmd . append ( x )
subprocess . check_call ( cmd ) |
def fallback ( message : str , ex : Exception ) -> None :
"""Fallback procedure when a cli command fails .
: param message : message to be logged
: param ex : Exception which caused the failure""" | logging . error ( '%s' , message )
logging . exception ( '%s' , ex )
sys . exit ( 1 ) |
def appliance_node_information ( self ) :
"""Gets the ApplianceNodeInformation API client .
Returns :
ApplianceNodeInformation :""" | if not self . __appliance_node_information :
self . __appliance_node_information = ApplianceNodeInformation ( self . __connection )
return self . __appliance_node_information |
def encoding ( encoding = True ) :
"""DEPRECATED : use pynvim . decode ( ) .""" | if isinstance ( encoding , str ) :
encoding = True
def dec ( f ) :
f . _nvim_decode = encoding
return f
return dec |
def from_api_repr ( cls , resource , config ) :
"""Factory : construct a Variable given its API representation
: type resource : dict
: param resource : change set representation returned from the API .
: type config : : class : ` google . cloud . runtimeconfig . config . Config `
: param config : The confi... | name = variable_name_from_full_name ( resource . get ( "name" ) )
variable = cls ( name = name , config = config )
variable . _set_properties ( resource = resource )
return variable |
def get_geometry ( self , geo_level , geo_code ) :
"""Get the geometry description for a geography . This is a dict
with two keys , ' properties ' which is a dict of properties ,
and ' shape ' which is a shapely shape ( may be None ) .""" | mapit_level = SETTINGS [ 'level_codes' ] [ geo_level ]
url = SETTINGS [ 'url' ] + '/area/MDB:%s/feature.geojson?type=%s' % ( geo_code , mapit_level )
url = url + '&generation=%s' % SETTINGS [ 'generation' ]
simplify = SETTINGS [ 'level_simplify' ] . get ( mapit_level )
if simplify :
url = url + '&simplification_lev... |
def expr_to_tree ( ind , pset ) :
"""Convert the unstructured DEAP pipeline into a tree data - structure .
Parameters
ind : deap . creator . Individual
The pipeline that is being exported
Returns
pipeline _ tree : list
List of operators in the current optimized pipeline
EXAMPLE :
pipeline :
" Deci... | def prim_to_list ( prim , args ) :
if isinstance ( prim , deap . gp . Terminal ) :
if prim . name in pset . context :
return pset . context [ prim . name ]
else :
return prim . value
return [ prim . name ] + args
tree = [ ]
stack = [ ]
for node in ind :
stack . append... |
def find_mrms_tracks ( self ) :
"""Identify objects from MRMS timesteps and link them together with object matching .
Returns :
List of STObjects containing MESH track information .""" | obs_objects = [ ]
tracked_obs_objects = [ ]
if self . mrms_ew is not None :
self . mrms_grid . load_data ( )
if len ( self . mrms_grid . data ) != len ( self . hours ) :
print ( 'Less than 24 hours of observation data found' )
return tracked_obs_objects
for h , hour in enumerate ( self . hou... |
def sharey ( axes ) :
"""Shared axes limits without shared locators , ticks , etc .
By Joe Kington""" | linker = Linker ( axes )
for ax in axes :
ax . _linker = linker |
def _mems_updated_cb ( self ) :
"""Called when the memories have been identified""" | logger . info ( 'Memories finished updating' )
self . param . refresh_toc ( self . _param_toc_updated_cb , self . _toc_cache ) |
def get_readme ( ) :
"""Get the contents of the ` ` README . rst ` ` file as a Unicode string .""" | try :
import pypandoc
description = pypandoc . convert ( 'README.md' , 'rst' )
except ( IOError , ImportError ) :
description = open ( 'README.md' ) . read ( )
return description |
def kill ( self , sig = signal . SIGTERM ) :
"""Terminate the test job .
Kill the subprocess if it was spawned , abort the spawning
process otherwise . This information can be collected afterwards
by reading the self . killed and self . spawned flags .
Also join the 3 related threads to the caller thread . ... | while self . is_alive ( ) :
self . killed = True
time . sleep ( POLLING_DELAY )
# " Was a process spawned ? " polling
if not self . spawned :
continue
# Either self . run returns or runner yields
if self . process . poll ( ) is None : # It ' s running
self . process . send_si... |
def clean ( self ) :
"""Checks that there is almost one field to select""" | if any ( self . errors ) : # Don ' t bother validating the formset unless each form is valid on
# its own
return
( selects , aliases , froms , wheres , sorts , groups_by , params ) = self . get_query_parts ( )
if not selects :
validation_message = _ ( u"At least you must check a row to get." )
raise forms .... |
def reflectance ( self , band ) :
"""Calculate top of atmosphere reflectance of Landsat 8
as outlined here : http : / / landsat . usgs . gov / Landsat8 _ Using _ Product . php
R _ raw = MR * Q + AR
R = R _ raw / cos ( Z ) = R _ raw / sin ( E )
Z = 90 - E ( in degrees )
where :
R _ raw = TOA planetary re... | if band not in self . oli_bands :
raise ValueError ( 'Landsat 8 reflectance should OLI band (i.e. bands 1-8)' )
elev = getattr ( self , 'sun_elevation' )
dn = self . _get_band ( 'b{}' . format ( band ) )
mr = getattr ( self , 'reflectance_mult_band_{}' . format ( band ) )
ar = getattr ( self , 'reflectance_add_band... |
def main ( ) :
'''Main routine .''' | # validate command line arguments
arg_parser = argparse . ArgumentParser ( )
arg_parser . add_argument ( '--vmssname' , '-n' , required = True , action = 'store' , help = 'Scale set name' )
arg_parser . add_argument ( '--rgname' , '-g' , required = True , action = 'store' , help = 'Resource Group Name' )
arg_parser . a... |
def set_bsd_socket_params ( self , port_reuse = None ) :
"""Sets BSD - sockets related params .
: param bool port _ reuse : Enable REUSE _ PORT flag on socket to allow multiple
instances binding on the same address ( BSD only ) .""" | self . _set ( 'reuse-port' , port_reuse , cast = bool )
return self . _section |
def newFromSites ( self , sites , exclude = False ) :
"""Create a new read from self , with only certain sites .
@ param sites : A set of C { int } 0 - based sites ( i . e . , indices ) in
sequences that should be kept . If C { None } ( the default ) , all sites
are kept .
@ param exclude : If C { True } th... | if exclude :
sites = set ( range ( len ( self ) ) ) - sites
newSequence = [ ]
newStructure = [ ]
for index , ( base , structure ) in enumerate ( zip ( self . sequence , self . structure ) ) :
if index in sites :
newSequence . append ( base )
newStructure . append ( structure )
read = self . __cl... |
def patch_file ( patch_stream : TextIO , fromcsv_stream : TextIO , tocsv_stream : TextIO , strict : bool = True , sep : str = ',' ) :
"""Apply the patch to the source CSV file , and save the result to the target
file .""" | diff = patch . load ( patch_stream )
from_records = records . load ( fromcsv_stream , sep = sep )
to_records = patch . apply ( diff , from_records , strict = strict )
# what order should the columns be in ?
if to_records : # have data , use a nice ordering
all_columns = to_records [ 0 ] . keys ( )
index_columns... |
def find_state ( self , container , start = None , end = None , avoid = None , initial_state = None , final_state = None ) :
"""Execute instructions .""" | self . __set_cpu_state ( initial_state )
# Convert input native addresses to reil addresses .
start = to_reil_address ( start ) if start else None
end = to_reil_address ( end ) if end else None
avoid = [ to_reil_address ( addr ) for addr in avoid ] if avoid else [ ]
# Load instruction pointer .
ip = start if start else... |
def renew ( cls , fqdn , duration , background ) :
"""Renew a domain .""" | fqdn = fqdn . lower ( )
if not background and not cls . intty ( ) :
background = True
domain_info = cls . info ( fqdn )
current_year = domain_info [ 'date_registry_end' ] . year
domain_params = { 'duration' : duration , 'current_year' : current_year , }
result = cls . call ( 'domain.renew' , fqdn , domain_params )
... |
def process_match ( match , fixed_text , cur , cur_end ) :
"""Processes a single match in rules""" | # Set our tools
# - - Initial / default value for replace
replace = True
# - - Set check cursor depending on match [ ' type ' ]
if match [ 'type' ] == 'prefix' :
chk = cur - 1
else : # suffix
chk = cur_end
# - - Set scope based on whether scope is negative
if match [ 'scope' ] . startswith ( '!' ) :
scope =... |
def get_jwt_key_data ( ) :
"""Returns the data for the JWT private key used for encrypting the user login token as a string object
Returns :
` str `""" | global __jwt_data
if __jwt_data :
return __jwt_data
from cloud_inquisitor import config_path
from cloud_inquisitor . config import dbconfig
jwt_key_file = dbconfig . get ( 'jwt_key_file_path' , default = 'ssl/private.key' )
if not os . path . isabs ( jwt_key_file ) :
jwt_key_file = os . path . join ( config_pat... |
def P ( value , bits = None , endian = None , target = None ) :
"""Pack an unsigned pointer for a given target .
Args :
value ( int ) : The value to pack .
bits ( : class : ` ~ pwnypack . target . Target . Bits ` ) : Override the default
word size . If ` ` None ` ` it will look at the word size of
` ` tar... | return globals ( ) [ 'P%d' % _get_bits ( bits , target ) ] ( value , endian = endian , target = target ) |
def simxGetObjectIntParameter ( clientID , objectHandle , parameterID , operationMode ) :
'''Please have a look at the function description / documentation in the V - REP user manual''' | parameterValue = ct . c_int ( )
return c_GetObjectIntParameter ( clientID , objectHandle , parameterID , ct . byref ( parameterValue ) , operationMode ) , parameterValue . value |
def get_source_data_items ( self , data_item : DataItem ) -> typing . List [ DataItem ] :
"""Return the list of data items that are data sources for the data item .
: return : The list of : py : class : ` nion . swift . Facade . DataItem ` objects .
. . versionadded : : 1.0
Scriptable : Yes""" | return [ DataItem ( data_item ) for data_item in self . _document_model . get_source_data_items ( data_item . _data_item ) ] if data_item else None |
def _master_tops ( self , load ) :
'''Return the results from an external node classifier if one is
specified
: param dict load : A payload received from a minion
: return : The results from an external node classifier''' | load = self . __verify_load ( load , ( 'id' , 'tok' ) )
if load is False :
return { }
return self . masterapi . _master_tops ( load , skip_verify = True ) |
def list_ ( device , unit = None ) :
'''Prints partition information of given < device >
CLI Examples :
. . code - block : : bash
salt ' * ' partition . list / dev / sda
salt ' * ' partition . list / dev / sda unit = s
salt ' * ' partition . list / dev / sda unit = kB''' | _validate_device ( device )
if unit :
if unit not in VALID_UNITS :
raise CommandExecutionError ( 'Invalid unit passed to partition.part_list' )
cmd = 'parted -m -s {0} unit {1} print' . format ( device , unit )
else :
cmd = 'parted -m -s {0} print' . format ( device )
out = __salt__ [ 'cmd.run_stdou... |
def specbits ( self ) :
"""Returns the array of arguments that would be given to
iptables for the current Extension .""" | bits = [ ]
for opt in sorted ( self . __options ) : # handle the case where this is a negated option
m = re . match ( r'^! (.*)' , opt )
if m :
bits . extend ( [ '!' , "--%s" % m . group ( 1 ) ] )
else :
bits . append ( "--%s" % opt )
optval = self . __options [ opt ]
if isinstance (... |
def create_name_id_mapping_response ( self , name_id = None , encrypted_id = None , in_response_to = None , issuer = None , sign_response = False , status = None , sign_alg = None , digest_alg = None , ** kwargs ) :
"""protocol for mapping a principal ' s name identifier into a
different name identifier for the s... | # Done over SOAP
ms_args = self . message_args ( )
_resp = NameIDMappingResponse ( name_id , encrypted_id , in_response_to = in_response_to , ** ms_args )
if sign_response :
return self . sign ( _resp , sign_alg = sign_alg , digest_alg = digest_alg )
else :
logger . info ( "Message: %s" , _resp )
return _re... |
def search_results_info ( self ) :
"""Returns the search results info for this command invocation or None .
The search results info object is created from the search results info
file associated with the command invocation . Splunk does not pass the
location of this file by default . You must request it by sp... | if self . _search_results_info is not None :
return self . _search_results_info
try :
info_path = self . input_header [ 'infoPath' ]
except KeyError :
return None
def convert_field ( field ) :
return ( field [ 1 : ] if field [ 0 ] == '_' else field ) . replace ( '.' , '_' )
def convert_value ( field , v... |
def pipe_xpathfetchpage ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""A source that fetches the content of a given website as DOM nodes or a
string . Loopable .
context : pipe2py . Context object
_ INPUT : pipeforever pipe or an iterable of items or fields
conf : dict
URL - - url objec... | conf = DotDict ( conf )
urls = utils . listize ( conf [ 'URL' ] )
for item in _INPUT :
for item_url in urls :
url = utils . get_value ( DotDict ( item_url ) , DotDict ( item ) , ** kwargs )
url = utils . get_abspath ( url )
f = urlopen ( url )
# TODO : it seems that Yahoo ! converts ... |
def _input_as_list ( self , data ) :
'''Takes the positional arguments as input in a list .
The list input here should be [ query _ file _ path , database _ file _ path ,
output _ file _ path ]''' | query , database , output = data
if ( not isabs ( database ) ) or ( not isabs ( query ) ) or ( not isabs ( output ) ) :
raise ApplicationError ( "Only absolute paths allowed.\n%s" % ', ' . join ( data ) )
self . _database = FilePath ( database )
self . _query = FilePath ( query )
self . _output = ResultPath ( outpu... |
def process_iter ( proc , cmd = "" ) :
"""helper function to iterate over a process stdout
and report error messages when done""" | try :
for l in proc . stdout :
yield l
finally :
if proc . poll ( ) is None : # there was an exception
return
else :
proc . wait ( )
if proc . returncode not in ( 0 , None , signal . SIGPIPE , signal . SIGPIPE + 128 ) :
sys . stderr . write ( "cmd was:%s\n" % cmd ... |
def write_project_summary ( samples , qsign_info = None ) :
"""Write project summary information on the provided samples .
write out dirs , genome resources ,""" | work_dir = samples [ 0 ] [ 0 ] [ "dirs" ] [ "work" ]
out_file = os . path . join ( work_dir , "project-summary.yaml" )
upload_dir = ( os . path . join ( work_dir , samples [ 0 ] [ 0 ] [ "upload" ] [ "dir" ] ) if "dir" in samples [ 0 ] [ 0 ] [ "upload" ] else "" )
date = str ( datetime . now ( ) )
prev_samples = _other_... |
def __analyses_match ( self , analysisA , analysisB ) :
"""Leiame , kas tegu on duplikaatidega ehk täpselt üht ja sama
morfoloogilist infot sisaldavate analüüsidega .""" | return POSTAG in analysisA and POSTAG in analysisB and analysisA [ POSTAG ] == analysisB [ POSTAG ] and ROOT in analysisA and ROOT in analysisB and analysisA [ ROOT ] == analysisB [ ROOT ] and FORM in analysisA and FORM in analysisB and analysisA [ FORM ] == analysisB [ FORM ] and CLITIC in analysisA and CLITIC in anal... |
def put ( self , key , value , ttl = - 1 ) :
"""Transactional implementation of : func : ` Map . put ( key , value , ttl ) < hazelcast . proxy . map . Map . put > `
The object to be put will be accessible only in the current transaction context till the transaction is
committed .
: param key : ( object ) , th... | check_not_none ( key , "key can't be none" )
check_not_none ( value , "value can't be none" )
return self . _encode_invoke ( transactional_map_put_codec , key = self . _to_data ( key ) , value = self . _to_data ( value ) , ttl = to_millis ( ttl ) ) |
def get_cmdline_options ( self ) :
"""Return a ' { cmd : { opt : val } } ' map of all command - line options
Option names are all long , but do not include the leading ' - - ' , and
contain dashes rather than underscores . If the option doesn ' t take
an argument ( e . g . ' - - quiet ' ) , the ' val ' is ' N... | d = { }
for cmd , opts in self . command_options . items ( ) :
for opt , ( src , val ) in opts . items ( ) :
if src != "command line" :
continue
opt = opt . replace ( '_' , '-' )
if val == 0 :
cmdobj = self . get_command_obj ( cmd )
neg_opt = self . negati... |
def consume ( self ) : # pragma : no cover
"""start consuming rabbitmq messages""" | print ( ' [*] Waiting for logs. To exit press CTRL+C' )
self . channel . basic_consume ( self . queue_name , self . callback )
self . channel . start_consuming ( ) |
def execute_input_middleware_stream ( self , request , controller ) :
"""Request comes from the controller . Returned is a request .
controller arg is the name of the controller .""" | start_request = request
# either ' http ' or ' cmd ' or ' irc '
controller_name = "" . join ( controller . get_controller_name ( ) . split ( '-' ) [ : 1 ] )
middlewares = list ( self . pre_input_middleware ) + list ( self . input_middleware )
for m in middlewares :
to_execute = getattr ( m ( controller ) , controll... |
def TaskAttemptInput ( input , task_attempt ) :
"""Returns the correct Input class for a given
data type and gather mode""" | ( data_type , mode ) = _get_input_info ( input )
if data_type != 'file' :
return NoOpInput ( None , task_attempt )
if mode == 'no_gather' :
return FileInput ( input [ 'data' ] [ 'contents' ] , task_attempt )
else :
assert mode . startswith ( 'gather' )
return FileListInput ( input [ 'data' ] [ 'contents... |
def OnSecondaryCheckbox ( self , event ) :
"""Top Checkbox event handler""" | self . attrs [ "top" ] = event . IsChecked ( )
self . attrs [ "right" ] = event . IsChecked ( )
post_command_event ( self , self . DrawChartMsg ) |
def save ( self ) :
"""Save profile settings into user profile directory""" | config = self . profiledir + '/config'
if not isdir ( self . profiledir ) :
makedirs ( self . profiledir )
cp = SafeConfigParser ( )
cp . add_section ( 'ssh' )
cp . set ( 'ssh' , 'private_key' , self . ssh_private_key )
cp . set ( 'ssh' , 'public_key' , self . ssh_public_key )
with open ( config , 'w' ) as cfile :
... |
def get_ndv_b ( b ) :
"""Get NoData value for GDAL band .
If NoDataValue is not set in the band ,
extract upper left and lower right pixel values .
Otherwise assume NoDataValue is 0.
Parameters
b : GDALRasterBand object
This is the input band .
Returns
b _ ndv : float
NoData value""" | b_ndv = b . GetNoDataValue ( )
if b_ndv is None : # Check ul pixel for ndv
ns = b . XSize
nl = b . YSize
ul = float ( b . ReadAsArray ( 0 , 0 , 1 , 1 ) )
# ur = float ( b . ReadAsArray ( ns - 1 , 0 , 1 , 1 ) )
lr = float ( b . ReadAsArray ( ns - 1 , nl - 1 , 1 , 1 ) )
# ll = float ( b . ReadAsAr... |
def write ( self ) :
"""Set the output pins of the port to the correct state .""" | mask = 0
for pin in self . pins :
if pin . mode == OUTPUT :
if pin . value == 1 :
pin_nr = pin . pin_number - self . port_number * 8
mask |= 1 << int ( pin_nr )
# print ( " type mask " , type ( mask ) )
# print ( " type self . portnumber " , type ( self . port _ number ) )
# print ( ... |
def _get_xmlparser ( xmlclass = XmlObject , validate = False , resolver = None ) :
"""Initialize an instance of : class : ` lxml . etree . XMLParser ` with appropriate
settings for validation . If validation is requested and the specified
instance of : class : ` XmlObject ` has an XSD _ SCHEMA defined , that wi... | if validate :
if hasattr ( xmlclass , 'XSD_SCHEMA' ) and xmlclass . XSD_SCHEMA is not None : # If the schema has already been loaded , use that .
# ( since we accessing the * class * , accessing ' xmlschema ' returns a property ,
# not the initialized schema object we actually want ) .
xmlschema = g... |
def log_pipeline ( self , pl ) :
"""Write a report of the pipeline out to a file""" | from datetime import datetime
from ambry . etl . pipeline import CastColumns
self . build_fs . makedir ( 'pipeline' , allow_recreate = True )
try :
ccp = pl [ CastColumns ]
caster_code = ccp . pretty_code
except Exception as e :
caster_code = str ( e )
templ = u ( """
Pipeline : {}
run time : {}
pha... |
def dendrogram ( df , method = 'average' , filter = None , n = 0 , p = 0 , sort = None , orientation = None , figsize = None , fontsize = 16 , inline = False ) :
"""Fits a ` scipy ` hierarchical clustering algorithm to the given DataFrame ' s variables and visualizes the results as
a ` scipy ` dendrogram .
The ... | if not figsize :
if len ( df . columns ) <= 50 or orientation == 'top' or orientation == 'bottom' :
figsize = ( 25 , 10 )
else :
figsize = ( 25 , ( 25 + len ( df . columns ) - 50 ) * 0.5 )
plt . figure ( figsize = figsize )
gs = gridspec . GridSpec ( 1 , 1 )
ax0 = plt . subplot ( gs [ 0 ] )
df =... |
def update_states_geo_zone_by_id ( cls , states_geo_zone_id , states_geo_zone , ** kwargs ) :
"""Update StatesGeoZone
Update attributes of StatesGeoZone
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . update _ sta... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _update_states_geo_zone_by_id_with_http_info ( states_geo_zone_id , states_geo_zone , ** kwargs )
else :
( data ) = cls . _update_states_geo_zone_by_id_with_http_info ( states_geo_zone_id , states_geo_zone , ** kwargs )
re... |
def delete ( self , id ) :
"""Delete a component by id""" | id = self . as_id ( id )
response = self . http . delete ( '%s/%s' % ( self . api_url , id ) , auth = self . auth )
response . raise_for_status ( ) |
def to_json ( graph : BELGraph ) -> Mapping [ str , Any ] :
"""Convert this graph to a Node - Link JSON object .""" | graph_json_dict = node_link_data ( graph )
# Convert annotation list definitions ( which are sets ) to canonicalized / sorted lists
graph_json_dict [ 'graph' ] [ GRAPH_ANNOTATION_LIST ] = { keyword : list ( sorted ( values ) ) for keyword , values in graph_json_dict [ 'graph' ] . get ( GRAPH_ANNOTATION_LIST , { } ) . i... |
def next_k_array ( a ) :
"""Given an array ` a ` of k distinct nonnegative integers , sorted in
ascending order , return the next k - array in the lexicographic
ordering of the descending sequences of the elements [ 1 ] _ . ` a ` is
modified in place .
Parameters
a : ndarray ( int , ndim = 1)
Array of l... | # Logic taken from Algotirhm T in D . Knuth , The Art of Computer
# Programming , Section 7.2.1.3 " Generating All Combinations " .
k = len ( a )
if k == 1 or a [ 0 ] + 1 < a [ 1 ] :
a [ 0 ] += 1
return a
a [ 0 ] = 0
i = 1
x = a [ i ] + 1
while i < k - 1 and x == a [ i + 1 ] :
i += 1
a [ i - 1 ] = i - 1... |
def text ( self , selector ) :
"""Return text result that executed by given css selector
: param selector : ` str ` css selector
: return : ` list ` or ` None `""" | result = self . __bs4 . select ( selector )
return [ r . get_text ( ) for r in result ] if result . __len__ ( ) > 1 else result [ 0 ] . get_text ( ) if result . __len__ ( ) > 0 else None |
def get_media_detail_output_interface_interface_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_media_detail = ET . Element ( "get_media_detail" )
config = get_media_detail
output = ET . SubElement ( get_media_detail , "output" )
interface = ET . SubElement ( output , "interface" )
interface_name_key = ET . SubElement ( interface , "interface-name" )
interface_name_key . tex... |
def values ( self , * args : str , ** kwargs : str ) -> "ValuesQuery" :
"""Make QuerySet return dicts instead of objects .""" | fields_for_select = { }
# type : Dict [ str , str ]
for field in args :
if field in fields_for_select :
raise FieldError ( "Duplicate key {}" . format ( field ) )
fields_for_select [ field ] = field
for return_as , field in kwargs . items ( ) :
if return_as in fields_for_select :
raise Field... |
def show_vcs_output_vcs_nodes_vcs_node_info_node_vcs_mode ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_vcs = ET . Element ( "show_vcs" )
config = show_vcs
output = ET . SubElement ( show_vcs , "output" )
vcs_nodes = ET . SubElement ( output , "vcs-nodes" )
vcs_node_info = ET . SubElement ( vcs_nodes , "vcs-node-info" )
node_vcs_mode = ET . SubElement ( vcs_node_info , "node-vcs-mo... |
def request ( self , path , args = None , post_args = None , files = None , method = None ) :
"""Fetches the given path in the Graph API .
We translate args to a valid query string . If post _ args is
given , we send a POST request to the given path with the given
arguments .""" | if args is None :
args = dict ( )
if post_args is not None :
method = "POST"
# Add ` access _ token ` to post _ args or args if it has not already been
# included .
if self . access_token : # If post _ args exists , we assume that args either does not exists
# or it does not need ` access _ token ` .
if pos... |
def vertical_line ( self , x : Union [ int , float ] , y1 : Union [ int , float ] , y2 : Union [ int , float ] , emphasize : bool = False ) -> None :
"""Adds a line from ( x , y1 ) to ( x , y2 ) .""" | y1 , y2 = sorted ( [ y1 , y2 ] )
self . vertical_lines . append ( _VerticalLine ( x , y1 , y2 , emphasize ) ) |
def get_unit_hostnames ( self , units ) :
"""Return a dict of juju unit names to hostnames .""" | host_names = { }
for unit in units :
host_names [ unit . info [ 'unit_name' ] ] = str ( unit . file_contents ( '/etc/hostname' ) . strip ( ) )
self . log . debug ( 'Unit host names: {}' . format ( host_names ) )
return host_names |
def compile_rules ( environment ) :
"""Compiles all the rules from the environment into a list of rules .""" | e = re . escape
rules = [ ( len ( environment . comment_start_string ) , 'comment' , e ( environment . comment_start_string ) ) , ( len ( environment . block_start_string ) , 'block' , e ( environment . block_start_string ) ) , ( len ( environment . variable_start_string ) , 'variable' , e ( environment . variable_star... |
def _get_tracker ( self , resource ) :
"""Return the resource tracker that is tracking ` ` resource ` ` .
: param resource : A resource .
: return : A resource tracker .
: rtype : : class : ` _ ResourceTracker `""" | with self . _lock :
for rt in self . _reference_queue :
if rt is not None and resource is rt . resource :
return rt
raise UnknownResourceError ( 'Resource not created by pool' ) |
def close ( self , signalnum = None , frame = None ) :
self . _running = False
"""Closes all currently open Tail objects""" | self . _log_debug ( "Closing all tail objects" )
self . _active = False
for fid in self . _tails :
self . _tails [ fid ] . close ( )
for n in range ( 0 , self . _number_of_consumer_processes ) :
if self . _proc [ n ] is not None and self . _proc [ n ] . is_alive ( ) :
self . _logger . debug ( "Terminate... |
def get_corrector_f ( rinput , meta , ins , datamodel ) :
"""Corrector for intensity flat""" | from emirdrp . processing . flatfield import FlatFieldCorrector
flat_info = meta [ 'master_flat' ]
with rinput . master_flat . open ( ) as hdul :
_logger . info ( 'loading intensity flat' )
_logger . debug ( 'flat info: %s' , flat_info )
mflat = hdul [ 0 ] . data
# Check NaN and Ceros
mask1 = mflat ... |
def write_header ( self , out_strm , delim , f1_num_fields , f2_num_fields , f1_header = None , f2_header = None , missing_val = None ) :
"""Write the header for a joined file . If headers are provided for one or more
of the input files , then a header is generated for the output file .
Otherwise , this does no... | mm = f1_header != f2_header
one_none = f1_header is None or f2_header is None
if mm and one_none and missing_val is None :
raise InvalidHeaderError ( "Cannot generate output header when one " + "input file is missing a header and no " + "missing value was provided to replace " + "unknown entries." )
if f1_header is... |
def getEyeOutputViewport ( self , eEye ) :
"""Gets the viewport in the frame buffer to draw the output of the distortion into""" | fn = self . function_table . getEyeOutputViewport
pnX = c_uint32 ( )
pnY = c_uint32 ( )
pnWidth = c_uint32 ( )
pnHeight = c_uint32 ( )
fn ( eEye , byref ( pnX ) , byref ( pnY ) , byref ( pnWidth ) , byref ( pnHeight ) )
return pnX . value , pnY . value , pnWidth . value , pnHeight . value |
def get_map_values ( self , lons , lats , ibin = None ) :
"""Return the indices in the flat array corresponding to a set of coordinates
Parameters
lons : array - like
' Longitudes ' ( RA or GLON )
lats : array - like
' Latitidues ' ( DEC or GLAT )
ibin : int or array - like
Extract data only for a giv... | theta = np . pi / 2. - np . radians ( lats )
phi = np . radians ( lons )
pix = hp . ang2pix ( self . hpx . nside , theta , phi , nest = self . hpx . nest )
if self . data . ndim == 2 :
return self . data [ : , pix ] if ibin is None else self . data [ ibin , pix ]
else :
return self . data [ pix ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.