signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def record_header ( self ) :
"""Read global header .
- Extract global header .
- Make Info object out of header properties .
- Append Info .
- Write plist file .""" | self . _gbhdr = Header ( self . _ifile )
self . _vinfo = self . _gbhdr . version
self . _dlink = self . _gbhdr . protocol
self . _nnsec = self . _gbhdr . nanosecond
if self . _trace is not NotImplemented :
self . _trace . _endian = self . _gbhdr . byteorder
self . _trace . _nnsecd = self . _gbhdr . nanosecond
i... |
def word ( cap = False ) :
"""This function generates a fake word by creating between two and three
random syllables and then joining them together .""" | syllables = [ ]
for x in range ( random . randint ( 2 , 3 ) ) :
syllables . append ( _syllable ( ) )
word = "" . join ( syllables )
if cap :
word = word [ 0 ] . upper ( ) + word [ 1 : ]
return word |
def get_certificate_request ( json_encode = True ) :
"""Generate a certificatee requests based on the network confioguration""" | req = CertRequest ( json_encode = json_encode )
req . add_hostname_cn ( )
# Add os - hostname entries
for net_type in [ INTERNAL , ADMIN , PUBLIC ] :
net_config = config ( ADDRESS_MAP [ net_type ] [ 'override' ] )
try :
net_addr = resolve_address ( endpoint_type = net_type )
ip = network_get_pri... |
def overlay_add ( self , overlay_id , x , y , file_or_fd , offset , fmt , w , h , stride ) :
"""Mapped mpv overlay _ add command , see man mpv ( 1 ) .""" | self . command ( 'overlay_add' , overlay_id , x , y , file_or_fd , offset , fmt , w , h , stride ) |
def _create_labels_for_features ( self , X ) :
"""Create labels for the features
NOTE : this code is duplicated from MultiFeatureVisualizer""" | if self . labels is None : # Use column names if a dataframe
if is_dataframe ( X ) :
self . features_ = np . array ( X . columns )
# Otherwise use the column index as the labels
else :
_ , ncols = X . shape
self . features_ = np . arange ( 0 , ncols )
else :
self . features_ = np... |
def put_file ( self ) :
"""SCP copy the file from the local system to the remote device .""" | destination = "{}/{}" . format ( self . file_system , self . dest_file )
self . scp_conn . scp_transfer_file ( self . source_file , destination )
# Must close the SCP connection to get the file written ( flush )
self . scp_conn . close ( ) |
def update ( self , ** kwargs ) :
"""Explicitly reload context with DB usage to get access
to complete DB object .""" | self . reload_context ( es_based = False , ** kwargs )
return super ( ESCollectionView , self ) . update ( ** kwargs ) |
def fix_examples_dir ( lib_dir ) :
"""rename examples dir to ` ` examples ` `""" | for x in lib_dir . dirs ( ) :
if x . name . lower ( ) == EXAMPLES :
return
for x in lib_dir . dirs ( ) :
if x . name . lower ( ) == EXAMPLES :
_fix_dir ( x )
return
for x in lib_dir . dirs ( ) :
if 'example' in x . name . lower ( ) :
_fix_dir ( x )
return
for x in lib... |
def library_sequencing_results ( self ) :
"""Generates a dict . where each key is a Library ID on the SequencingRequest and each value
is the associated SequencingResult . Libraries that aren ' t yet with a SequencingResult are
not inlcuded in the dict .""" | sres_ids = self . sequencing_result_ids
res = { }
for i in sres_ids :
sres = SequencingResult ( i )
res [ sres . library_id ] = sres
return res |
def output_to_file ( filename , tracklisting , action ) :
"""Produce requested output ; either output text file , tag audio file or do
both .
filename : a string of path + filename without file extension
tracklisting : a string containing a tracklisting
action : ' tag ' , ' text ' or ' both ' , from command... | if action in ( 'tag' , 'both' ) :
audio_tagged = tag_audio ( filename , tracklisting )
if action == 'both' and audio_tagged :
write_text ( filename , tracklisting )
elif action == 'text' :
write_text ( filename , tracklisting ) |
def append_process ( xmldoc , program = None , version = None , cvs_repository = None , cvs_entry_time = None , comment = None , is_online = False , jobid = 0 , domain = None , ifos = None ) :
"""Add an entry to the process table in xmldoc . program , version ,
cvs _ repository , comment , and domain should all b... | try :
proctable = lsctables . ProcessTable . get_table ( xmldoc )
except ValueError :
proctable = lsctables . New ( lsctables . ProcessTable )
xmldoc . childNodes [ 0 ] . appendChild ( proctable )
proctable . sync_next_id ( )
process = proctable . RowType ( )
process . program = program
process . version = ... |
def get_generic_rcp_name ( inname ) :
"""Convert an RCP name into the generic Pymagicc RCP name
The conversion is case insensitive .
Parameters
inname : str
The name for which to get the generic Pymagicc RCP name
Returns
str
The generic Pymagicc RCP name
Examples
> > > get _ generic _ rcp _ name (... | # TODO : move into OpenSCM
mapping = { "rcp26" : "rcp26" , "rcp3pd" : "rcp26" , "rcp45" : "rcp45" , "rcp6" : "rcp60" , "rcp60" : "rcp60" , "rcp85" : "rcp85" , }
try :
return mapping [ inname . lower ( ) ]
except KeyError :
error_msg = "No generic name for input: {}" . format ( inname )
raise ValueError ( er... |
def prepare_data ( fm , max_back , dur_cap = 700 ) :
'''Computes angle and length differences up to given order and deletes
suspiciously long fixations .
Input
fm : Fixmat
Fixmat for which to comput angle and length differences
max _ back : Int
Computes delta angle and amplitude up to order max _ back .... | durations = np . roll ( fm . end - fm . start , 1 ) . astype ( float )
angles , lengths , ads , lds = anglendiff ( fm , roll = max_back , return_abs = True )
# durations and ads are aligned in a way that an entry in ads
# encodes the angle of the saccade away from a fixation in
# durations
forward_angle = abs ( reshift... |
def get_pid ( self , unique_id , configs = None ) :
"""Gets the pid of the process with ` unique _ id ` . If the deployer does not know of a process
with ` unique _ id ` then it should return a value of constants . PROCESS _ NOT _ RUNNING _ PID""" | RECV_BLOCK_SIZE = 16
# the following is necessay to set the configs for this function as the combination of the
# default configurations and the parameter with the parameter superceding the defaults but
# not modifying the defaults
if configs is None :
configs = { }
tmp = self . default_configs . copy ( )
tmp . upd... |
def room_members ( self , stream_id ) :
'''get list of room members''' | req_hook = 'pod/v2/room/' + str ( stream_id ) + '/membership/list'
req_args = None
status_code , response = self . __rest__ . GET_query ( req_hook , req_args )
self . logger . debug ( '%s: %s' % ( status_code , response ) )
return status_code , response |
def find_files ( self ) :
"""Find all file paths for publishing , yield ( urlname , kwargs )""" | # yield blueprint paths first
if getattr ( self , 'blueprint_name' , None ) :
for path in walk_directory ( os . path . join ( self . path , self . blueprint_name ) , ignore = self . project . EXCLUDES ) :
yield 'preview' , { 'path' : path }
# then yield project paths
for path in walk_directory ( self . path... |
def new_reservoir ( reservoir_type = 'uniform' , * reservoir_args , ** reservoir_kwargs ) :
"""Build a new reservoir""" | try :
reservoir_cls = RESERVOIR_TYPES [ reservoir_type ]
except KeyError :
raise InvalidMetricError ( "Unknown reservoir type: {}" . format ( reservoir_type ) )
return reservoir_cls ( * reservoir_args , ** reservoir_kwargs ) |
def _any_pandas_objects ( terms ) :
"""Check a sequence of terms for instances of PandasObject .""" | return any ( isinstance ( term . value , pd . core . generic . PandasObject ) for term in terms ) |
def sort ( self , * sorting , ** kwargs ) :
"""Sort resources .""" | sorting_ = [ ]
for name , desc in sorting :
field = self . meta . model . _meta . fields . get ( name )
if field is None :
continue
if desc :
field = field . desc ( )
sorting_ . append ( field )
if sorting_ :
return self . collection . order_by ( * sorting_ )
return self . collection |
def set_truetype_font ( path : str , tile_width : int , tile_height : int ) -> None :
"""Set the default tileset from a ` . ttf ` or ` . otf ` file .
` path ` is the file path for the font file .
` tile _ width ` and ` tile _ height ` are the desired size of the tiles in the new
tileset . The font will be sca... | if not os . path . exists ( path ) :
raise RuntimeError ( "File not found:\n\t%s" % ( os . path . realpath ( path ) , ) )
lib . TCOD_tileset_load_truetype_ ( path . encode ( ) , tile_width , tile_height ) |
def launchTemplateApplication ( self , pchTemplateAppKey , pchNewAppKey , unKeys ) :
"""Launches an instance of an application of type template , with its app key being pchNewAppKey ( which must be unique ) and optionally override sections
from the manifest file via AppOverrideKeys _ t""" | fn = self . function_table . launchTemplateApplication
pKeys = AppOverrideKeys_t ( )
result = fn ( pchTemplateAppKey , pchNewAppKey , byref ( pKeys ) , unKeys )
return result , pKeys |
def plot_synth_real ( real_template , synthetic , channels = False , size = ( 5 , 10 ) , ** kwargs ) :
"""Plot multiple channels of data for real data and synthetic .
: type real _ template : obspy . core . stream . Stream
: param real _ template : Stream of the real template
: type synthetic : obspy . core .... | import matplotlib . pyplot as plt
colours = [ 'k' , 'r' ]
labels = [ 'Real' , 'Synthetic' ]
if channels :
real = [ ]
synth = [ ]
for stachan in channels :
real . append ( real_template . select ( station = stachan [ 0 ] , channel = stachan [ 1 ] ) )
synth . append ( synthetic . select ( stat... |
def _help ( ) :
"""Display both SQLAlchemy and Python help statements""" | statement = '%s%s' % ( shelp , phelp % ', ' . join ( cntx_ . keys ( ) ) )
print statement . strip ( ) |
def get_vendor_extension_fields ( mapping ) :
"""Identify vendor extension fields and extract them into a new dictionary .
Examples :
> > > get _ vendor _ extension _ fields ( { ' test ' : 1 } )
> > > get _ vendor _ extension _ fields ( { ' test ' : 1 , ' x - test ' : 2 } )
{ ' x - test ' : 2}""" | return { k : v for k , v in mapping . items ( ) if k . startswith ( 'x-' ) } |
def _to_protobuf ( self ) :
"""Convert the current query into the equivalent protobuf .
Returns :
google . cloud . firestore _ v1beta1 . types . StructuredQuery : The
query protobuf .""" | projection = self . _normalize_projection ( self . _projection )
orders = self . _normalize_orders ( )
start_at = self . _normalize_cursor ( self . _start_at , orders )
end_at = self . _normalize_cursor ( self . _end_at , orders )
query_kwargs = { "select" : projection , "from" : [ query_pb2 . StructuredQuery . Collect... |
async def jsk_vc_stop ( self , ctx : commands . Context ) :
"""Stops running an audio source , if there is one .""" | voice = ctx . guild . voice_client
voice . stop ( )
await ctx . send ( f"Stopped playing audio in {voice.channel.name}." ) |
def kill_proc_tree ( pid , sig = signal . SIGTERM , include_parent = True , timeout = None , on_terminate = None ) :
"""Kill a process tree ( including grandchildren ) with signal
" sig " and return a ( gone , still _ alive ) tuple .
" on _ terminate " , if specified , is a callabck function which is
called a... | if pid == os . getpid ( ) :
raise RuntimeError ( "I refuse to kill myself" )
parent = psutil . Process ( pid )
children = parent . children ( recursive = True )
if include_parent :
children . append ( parent )
for p in children :
p . send_signal ( sig )
gone , alive = psutil . wait_procs ( children , timeou... |
def getApplicationAutoLaunch ( self , pchAppKey ) :
"""Gets the application auto - launch flag . This is only valid for applications which return true for VRApplicationProperty _ IsDashboardOverlay _ Bool .""" | fn = self . function_table . getApplicationAutoLaunch
result = fn ( pchAppKey )
return result |
def mouseMoved ( self , viewPos ) :
"""Updates the probe text with the values under the cursor .
Draws a vertical line and a symbol at the position of the probe .""" | try :
check_class ( viewPos , QtCore . QPointF )
self . crossLineVerShadow . setVisible ( False )
self . crossLineVertical . setVisible ( False )
self . probeLabel . setText ( "" )
self . probeDataItem . clear ( )
if ( self . _hasValidData ( ) and self . config . probeCti . configValue and self ... |
def set_timestamp ( self , timestamp = str ( datetime . datetime . utcfromtimestamp ( time . time ( ) ) ) ) :
"""set timestamp of embed content
: param timestamp : ( optional ) timestamp of embed content""" | self . timestamp = timestamp |
def _read_bytes_from_framed_body ( self , b ) :
"""Reads the requested number of bytes from a streaming framed message body .
: param int b : Number of bytes to read
: returns : Bytes read from source stream and decrypted
: rtype : bytes""" | plaintext = b""
final_frame = False
_LOGGER . debug ( "collecting %d bytes" , b )
while len ( plaintext ) < b and not final_frame :
_LOGGER . debug ( "Reading frame" )
frame_data , final_frame = deserialize_frame ( stream = self . source_stream , header = self . _header , verifier = self . verifier )
_LOGGE... |
def server_error ( request , template_name = '500.html' ) :
"""500 error handler .
Templates : : template : ` 500 . html `
Context : None""" | response = render_in_page ( request , template_name )
if response :
return response
try :
template = loader . get_template ( template_name )
except TemplateDoesNotExist :
return http . HttpResponseServerError ( '<h1>Server Error (500)</h1>' , content_type = 'text/html' )
return http . HttpResponseServerErro... |
def onscroll ( self , event ) :
"""Action to be taken when an event is triggered .
Event is scroll of the mouse ' s wheel . This leads to changing the temporal frame displayed .
: param event : Scroll of mouse wheel""" | if event . button == 'up' :
self . ind = ( self . ind + 1 ) % self . slices
else :
self . ind = ( self . ind - 1 ) % self . slices
self . update ( ) |
def replace_from_url ( self , photo , url , ** kwds ) :
"""Endpoint : / photo / < id > replace . json
Import a photo from the specified URL to replace an existing
photo .""" | result = self . _client . post ( "/photo/%s/replace.json" % self . _extract_id ( photo ) , photo = url , ** kwds ) [ "result" ]
return Photo ( self . _client , result ) |
def sanitize ( self ) :
"""Sanitize the data ( sort it , etc . ) before writing it to disk .
Template method that can be overridden in each catalog ' s subclassed
` Entry ` object .""" | name = self [ self . _KEYS . NAME ]
aliases = self . get_aliases ( includename = False )
if name not in aliases : # Assign the first source to alias , if not available assign us .
if self . _KEYS . SOURCES in self :
self . add_quantity ( self . _KEYS . ALIAS , name , '1' )
if self . _KEYS . ALIAS no... |
def call_backward ( self , proj_data , out = None ) :
"""Run an ASTRA back - projection on the given data using the GPU .
Parameters
proj _ data : ` ` proj _ space ` ` element
Projection data to which the back - projector is applied .
out : ` ` reco _ space ` ` element , optional
Element of the reconstruc... | with self . _mutex :
assert proj_data in self . proj_space
if out is not None :
assert out in self . reco_space
else :
out = self . reco_space . element ( )
# Copy data to GPU memory
if self . geometry . ndim == 2 :
astra . data2d . store ( self . sino_id , proj_data . asarra... |
def probe ( cls , resource , enable , disable , test , host , interval , http_method , http_response , threshold , timeout , url , window ) :
"""Set a probe for a webaccelerator""" | params = { 'host' : host , 'interval' : interval , 'method' : http_method , 'response' : http_response , 'threshold' : threshold , 'timeout' : timeout , 'url' : url , 'window' : window }
if enable :
params [ 'enable' ] = True
elif disable :
params [ 'enable' ] = False
if test :
result = cls . call ( 'hostin... |
def _ProcessEntries ( self , fd ) :
"""Extract entries from the xinetd config files .""" | p = config_file . KeyValueParser ( kv_sep = "{" , term = "}" , sep = None )
data = utils . ReadFileBytesAsUnicode ( fd )
entries = p . ParseEntries ( data )
for entry in entries :
for section , cfg in iteritems ( entry ) : # The parser returns a list of configs . There will only be one .
if cfg :
... |
def customwarn ( message , category , filename , lineno , * args , ** kwargs ) :
"""Use the psyplot . warning logger for categories being out of
PsyPlotWarning and PsyPlotCritical and the default warnings . showwarning
function for all the others .""" | if category is PsyPlotWarning :
logger . warning ( warnings . formatwarning ( "\n%s" % message , category , filename , lineno ) )
elif category is PsyPlotCritical :
logger . critical ( warnings . formatwarning ( "\n%s" % message , category , filename , lineno ) , exc_info = True )
else :
old_showwarning ( m... |
def init_app ( self , app , database = None ) :
"""Initialize application .""" | # Register application
if not app :
raise RuntimeError ( 'Invalid application.' )
self . app = app
if not hasattr ( app , 'extensions' ) :
app . extensions = { }
app . extensions [ 'peewee' ] = self
app . config . setdefault ( 'PEEWEE_CONNECTION_PARAMS' , { } )
app . config . setdefault ( 'PEEWEE_DATABASE_URI' ... |
def _get_installations ( self ) :
"""Get information about installations""" | response = None
for base_url in urls . BASE_URLS :
urls . BASE_URL = base_url
try :
response = requests . get ( urls . get_installations ( self . _username ) , headers = { 'Cookie' : 'vid={}' . format ( self . _vid ) , 'Accept' : 'application/json,' 'text/javascript, */*; q=0.01' , } )
if 2 == r... |
def set_name ( self , name ) :
"""RETURN NEW FILE WITH GIVEN EXTENSION""" | path = self . _filename . split ( "/" )
parts = path [ - 1 ] . split ( "." )
if len ( parts ) == 1 :
path [ - 1 ] = name
else :
path [ - 1 ] = name + "." + parts [ - 1 ]
return File ( "/" . join ( path ) ) |
def disp ( name = None , idx = None ) :
"""displays selected data from ( files written by ) the class ` CMADataLogger ` .
The call ` ` cma . disp ( name , idx ) ` ` is a shortcut for ` ` cma . CMADataLogger ( name ) . disp ( idx ) ` ` .
Arguments
` name `
name of the logger , filename prefix , ` None ` eval... | return CMADataLogger ( name if name else CMADataLogger . default_prefix ) . disp ( idx ) |
def get ( property_name ) :
"""Returns the value of the specified configuration property .
Property values stored in the user configuration file take
precedence over values stored in the system configuration
file .
: param property _ name : The name of the property to retrieve .
: return : The value of th... | config = _read_config ( _USER_CONFIG_FILE )
section = _MAIN_SECTION_NAME
try :
property_value = config . get ( section , property_name )
except ( NoOptionError , NoSectionError ) as error : # Try the system config file
try :
config = _read_config ( _SYSTEM_CONFIG_FILE )
property_value = config .... |
def AgregarEmisor ( self , tipo_cbte , pto_vta , nro_cbte , cod_caracter = None , fecha_inicio_act = None , iibb = None , nro_ruca = None , nro_renspa = None , cuit_autorizado = None , ** kwargs ) :
"Agrego los datos del emisor a la liq ." | # cod _ caracter y fecha _ inicio _ act no es requerido para ajustes
d = { 'tipoComprobante' : tipo_cbte , 'puntoVenta' : pto_vta , 'nroComprobante' : nro_cbte , 'codCaracter' : cod_caracter , 'fechaInicioActividades' : fecha_inicio_act , 'iibb' : iibb , 'nroRUCA' : nro_ruca , 'nroRenspa' : nro_renspa , 'cuitAutorizado... |
def dict_fun ( data , function ) :
"""Apply a function to all values in a dictionary , return a dictionary with
results .
Parameters
data : dict
a dictionary whose values are adequate input to the second argument
of this function .
function : function
a function that takes one argument
Returns
a d... | return dict ( ( k , function ( v ) ) for k , v in list ( data . items ( ) ) ) |
def is_backup_class ( cls ) :
"""Return true if given class supports back up . Currently this means a
gludb . data . Storable - derived class that has a mapping as defined in
gludb . config""" | return True if ( isclass ( cls ) and issubclass ( cls , Storable ) and get_mapping ( cls , no_mapping_ok = True ) ) else False |
def state_preorder_put_account_payment_info ( nameop , account_addr , token_type , amount ) :
"""Call this in a @ state _ create - decorated method .
Identifies the account that must be debited .""" | assert amount is None or isinstance ( amount , ( int , long ) ) , 'Amount is {} (type {})' . format ( amount , type ( amount ) )
assert account_addr is None or isinstance ( account_addr , ( str , unicode ) )
assert token_type is None or isinstance ( token_type , ( str , unicode ) )
nameop [ '__account_payment_info__' ]... |
def remove_label ( self , label ) :
"""Removes ` label ` from the catalogue , by removing all works carrying
it .
: param label : label to remove
: type label : ` str `""" | works_to_delete = [ ]
for work , work_label in self . items ( ) :
if work_label == label :
works_to_delete . append ( work )
for work in works_to_delete :
del self [ work ]
if self . _ordered_labels :
self . _ordered_labels . remove ( label ) |
def delete ( self , uri , query = None , ** kwargs ) :
"""make a DELETE request""" | return self . fetch ( 'delete' , uri , query , ** kwargs ) |
def include ( self , target ) :
"""Determine if a given value is included in the
array or object using ` is ` .""" | if self . _clean . isDict ( ) :
return self . _wrap ( target in self . obj . values ( ) )
else :
return self . _wrap ( target in self . obj ) |
def getUniqueFeaturesLocationsInObject ( self , name ) :
"""Return two sets . The first set contains the unique locations Ids in the
object . The second set contains the unique feature Ids in the object .""" | uniqueFeatures = set ( )
uniqueLocations = set ( )
for pair in self . objects [ name ] :
uniqueLocations = uniqueLocations . union ( { pair [ 0 ] } )
uniqueFeatures = uniqueFeatures . union ( { pair [ 1 ] } )
return uniqueLocations , uniqueFeatures |
def _populate_data ( self ) :
"""Assing some probe ' s raw meta data from API response to instance properties""" | if self . id is None :
self . id = self . meta_data . get ( "id" )
self . is_anchor = self . meta_data . get ( "is_anchor" )
self . country_code = self . meta_data . get ( "country_code" )
self . description = self . meta_data . get ( "description" )
self . is_public = self . meta_data . get ( "is_public" )
self . ... |
def clear_choice_ids ( self ) :
"""stub""" | if ( self . get_choice_ids_metadata ( ) . is_read_only ( ) or self . get_choice_ids_metadata ( ) . is_required ( ) ) :
raise NoAccess ( )
self . my_osid_object_form . _my_map [ 'choiceIds' ] = self . _choice_ids_metadata [ 'default_object_values' ] [ 0 ] |
def request ( self , max_width ) : # type : ( int ) - > Optional [ Tuple [ int , Chunk ] ]
"""Requests a sub - chunk of max _ width or shorter . Returns None if no chunks left .""" | if max_width < 1 :
raise ValueError ( 'requires positive integer max_width' )
s = self . chunk . s
length = len ( s )
if self . internal_offset == len ( s ) :
return None
width = 0
start_offset = i = self . internal_offset
replacement_char = u' '
while True :
w = wcswidth ( s [ i ] )
# If adding a chara... |
def legacy_write ( self , request_id , msg , max_doc_size , acknowledged , docs ) :
"""A proxy for SocketInfo . legacy _ write that handles event publishing .""" | if self . publish :
duration = datetime . datetime . now ( ) - self . start_time
cmd = self . _start ( request_id , docs )
start = datetime . datetime . now ( )
try :
result = self . sock_info . legacy_write ( request_id , msg , max_doc_size , acknowledged )
if self . publish :
duration = ( ... |
def selection_changed ( self , widget , event = None ) :
"""Notify state machine about tree view selection""" | # do not forward cursor selection updates if state update is running
# TODO maybe make this generic for respective abstract controller
if self . _state_which_is_updated :
return
super ( StateMachineTreeController , self ) . selection_changed ( widget , event ) |
def get_properties ( properties_file = 'raw.properties.json' , env = None , region = None ) :
"""Get contents of _ properties _ file _ for the _ env _ .
Args :
properties _ file ( str ) : File name of ` create - configs ` JSON output .
env ( str ) : Environment to read optionally .
region ( str ) : Region t... | with open ( properties_file , 'rt' ) as file_handle :
properties = json . load ( file_handle )
env_properties = properties . get ( env , properties )
contents = env_properties . get ( region , env_properties )
LOG . debug ( 'Found properties for %s:\n%s' , env , contents )
return contents |
def run_migrations_online ( ) :
"""Run migrations in ' online ' mode .
In this scenario we need to create an Engine
and associate a connection with the context .""" | app_conf = dci_config . generate_conf ( )
connectable = dci_config . get_engine ( app_conf )
with connectable . connect ( ) as connection :
context . configure ( connection = connection , target_metadata = target_metadata , )
with context . begin_transaction ( ) :
context . run_migrations ( ) |
def get_value ( self , name , parameters = None ) :
"""Return the value of a cached variable if applicable
The value of the variable ' name ' is returned , if no parameters are passed or if all parameters are identical
to the ones stored for the variable .
: param str name : Name of teh variable
: param dic... | if not isinstance ( parameters , dict ) :
raise TypeError ( "parameters must a dict" )
if name not in self . _cache :
return None
hash = self . _parameter_hash ( parameters )
hashdigest = hash . hexdigest ( )
return self . _cache [ name ] . get ( hashdigest , None ) |
def _enrich_link ( self , glossary ) :
"""Enrich the dict glossary [ ' link ' ] with an identifier onto the model""" | try :
Model = apps . get_model ( * glossary [ 'link' ] [ 'model' ] . split ( '.' ) )
obj = Model . objects . get ( pk = glossary [ 'link' ] [ 'pk' ] )
glossary [ 'link' ] . update ( identifier = str ( obj ) )
except ( KeyError , ObjectDoesNotExist ) :
pass |
def my_request_classifier ( environ ) :
"""Returns one of the classifiers ' dav ' , ' xmlpost ' , or ' browser ' ,
depending on the imperative logic below""" | request_method = REQUEST_METHOD ( environ )
if request_method in _DAV_METHODS :
return "dav"
useragent = USER_AGENT ( environ )
if useragent :
for agent in _DAV_USERAGENTS :
if useragent . find ( agent ) != - 1 :
return "dav"
if request_method == "POST" :
if CONTENT_TYPE ( environ ) == "... |
def post ( self , url , data , charset = CHARSET_UTF8 , headers = { } ) :
'''response json text''' | if 'Api-Lang' not in headers :
headers [ 'Api-Lang' ] = 'python'
if 'Content-Type' not in headers :
headers [ 'Content-Type' ] = "application/x-www-form-urlencoded;charset=" + charset
rsp = requests . post ( url , data , headers = headers , timeout = ( int ( self . conf ( HTTP_CONN_TIMEOUT , '10' ) ) , int ( se... |
def build ( self , builder ) :
"""Build XML by appending to builder""" | builder . start ( "SignatureRef" , dict ( SignatureOID = self . oid ) )
builder . end ( "SignatureRef" ) |
def count_all ( self ) :
"""Returns the total number of middleware in this chain and subchains .""" | return sum ( x . func . count_all ( ) if x . is_subchain else 1 for x in self ) |
def get_assessment_parts_by_ids ( self , assessment_part_ids ) :
"""Gets an ` ` AssessmentPartList ` ` corresponding to the given ` ` IdList ` ` .
arg : assessment _ part _ ids ( osid . id . IdList ) : the list of
` ` Ids ` ` to retrieve
return : ( osid . assessment . authoring . AssessmentPartList ) - the
... | # Implemented from template for
# osid . resource . ResourceLookupSession . get _ resources _ by _ ids
# NOTE : This implementation currently ignores plenary view
collection = JSONClientValidated ( 'assessment_authoring' , collection = 'AssessmentPart' , runtime = self . _runtime )
object_id_list = [ ]
for i in assessm... |
def prepare ( self , setup_func ) :
"""This decorator wrap a function which setup a environment before
running a command
@ manager . prepare ( setup _ func )
def some _ command ( ) :
pass""" | assert inspect . isfunction ( setup_func )
argsspec = inspect . getargspec ( setup_func )
if argsspec . args :
raise ValueError ( "prepare function shouldn't have any arguments" )
def decorator ( command_func ) :
@ functools . wraps ( command_func )
def wrapper ( * args , ** kwgs ) : # Run setup _ func befo... |
def parse ( self , raw ) :
"""Returns a Python object decoded from the bytes of this encoding .
Raises
~ ipfsapi . exceptions . DecodingError
Parameters
raw : bytes
Data to be parsed
Returns
object""" | results = list ( self . parse_partial ( raw ) )
results . extend ( self . parse_finalize ( ) )
return results [ 0 ] if len ( results ) == 1 else results |
def get_file_to_text ( self , share_name , directory_name , file_name , encoding = 'utf-8' , start_range = None , end_range = None , range_get_content_md5 = None , progress_callback = None , max_connections = 1 , max_retries = 5 , retry_wait = 1.0 , timeout = None ) :
'''Downloads a file as unicode text , with auto... | _validate_not_none ( 'share_name' , share_name )
_validate_not_none ( 'file_name' , file_name )
_validate_not_none ( 'encoding' , encoding )
file = self . get_file_to_bytes ( share_name , directory_name , file_name , start_range , end_range , range_get_content_md5 , progress_callback , max_connections , max_retries , r... |
def predict ( self , parameters , viterbi ) :
"""Run forward algorithm to find the predicted distribution over classes .""" | x_dot_parameters = np . einsum ( 'ijk,kl->ijl' , self . x , parameters )
if not viterbi :
alpha = forward_predict ( self . _lattice , x_dot_parameters , self . state_machine . n_states )
else :
alpha = forward_max_predict ( self . _lattice , x_dot_parameters , self . state_machine . n_states )
I , J , _ = self ... |
def _build ( self , input_modules , middle_modules , head_modules ) :
"""TBD""" | self . input_layer = self . _build_input_layer ( input_modules )
self . middle_layers = self . _build_middle_layers ( middle_modules )
self . heads = self . _build_task_heads ( head_modules )
# Construct loss module
reduction = self . config [ "train_config" ] [ "loss_fn_reduction" ]
self . criteria = SoftCrossEntropyL... |
def get_top ( self ) :
'''Returns the high data derived from the top file''' | try :
tops = self . get_tops ( )
except SaltRenderError as err :
log . error ( 'Unable to render top file: %s' , err . error )
return { }
return self . merge_tops ( tops ) |
def scan_line ( self , line , regex ) :
"""Checks if regex is in line , returns bool""" | return bool ( re . search ( regex , line , flags = re . IGNORECASE ) ) |
def connect ( self ) :
"""connect to the database
* * Return : * *
- ` ` dbConn ` ` - - the database connection
See the class docstring for usage""" | self . log . debug ( 'starting the ``get`` method' )
dbSettings = self . dbSettings
port = False
if "tunnel" in dbSettings and dbSettings [ "tunnel" ] :
port = self . _setup_tunnel ( tunnelParameters = dbSettings [ "tunnel" ] )
# SETUP A DATABASE CONNECTION
host = dbSettings [ "host" ]
user = dbSettings [ "user" ]
... |
def add_warning ( self , exception : BELParserWarning , context : Optional [ Mapping [ str , Any ] ] = None , ) -> None :
"""Add a warning to the internal warning log in the graph , with optional context information .
: param exception : The exception that occurred
: param context : The context from the parser ... | self . warnings . append ( ( self . path , exception , { } if context is None else context , ) ) |
def get_space_content_by_type ( self , space_key , content_type , depth = None , expand = None , start = None , limit = None , callback = None ) :
"""Returns the content in this given space with the given type .
: param space _ key ( string ) : A string containing the key of the space .
: param content _ type (... | assert content_type in [ "page" , "blogpost" ]
params = { }
if depth :
assert depth in { "all" , "root" }
params [ "depth" ] = depth
if expand :
params [ "expand" ] = expand
if start is not None :
params [ "start" ] = int ( start )
if limit is not None :
params [ "limit" ] = int ( limit )
return sel... |
def create ( cls , spec_path , address_maps ) :
"""Creates an address family from the given set of address maps .
: param spec _ path : The directory prefix shared by all address _ maps .
: param address _ maps : The family of maps that form this namespace .
: type address _ maps : : class : ` collections . I... | if spec_path == '.' :
spec_path = ''
for address_map in address_maps :
if not address_map . path . startswith ( spec_path ) :
raise DifferingFamiliesError ( 'Expected AddressMaps to share the same parent directory {}, ' 'but received: {}' . format ( spec_path , address_map . path ) )
objects_by_name = {... |
def list_topics ( self , Nwords = 10 ) :
"""List the top ` ` Nwords ` ` words for each topic .""" | return [ ( k , self . list_topic ( k , Nwords ) ) for k in xrange ( len ( self . phi ) ) ] |
def update_brand_by_id ( cls , brand_id , brand , ** kwargs ) :
"""Update Brand
Update attributes of Brand
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . update _ brand _ by _ id ( brand _ id , brand , async = Tr... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _update_brand_by_id_with_http_info ( brand_id , brand , ** kwargs )
else :
( data ) = cls . _update_brand_by_id_with_http_info ( brand_id , brand , ** kwargs )
return data |
def append_partition ( self , db_name , tbl_name , part_vals ) :
"""Parameters :
- db _ name
- tbl _ name
- part _ vals""" | self . send_append_partition ( db_name , tbl_name , part_vals )
return self . recv_append_partition ( ) |
def envvar_profile_cls ( profile_cls = None , ** profile_cls_options ) -> typing . Type [ EnvvarProfile ] :
"""A class decorator that makes the decorated class a sub - class of EnvvarProfile and transforms
its type annotations into envvar profile properties .""" | def decorator ( profile_cls ) :
profile_option_names = [ "profile_root" , "profile_activating_envvar" ]
profile_option_defaults = { "profile_root" : to_snake_case ( profile_cls . __name__ ) }
dct = { }
for option_name in profile_option_names :
if option_name in profile_cls_options :
... |
def pipe_sort ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""An operator that sorts the input source according to the specified key .
Not loopable . Not lazy .
Parameters
context : pipe2py . Context object
_ INPUT : pipe2py . modules pipe like object ( iterable of items )
kwargs - - oth... | test = kwargs . pop ( 'pass_if' , None )
_pass = utils . get_pass ( test = test )
key_defs = imap ( DotDict , utils . listize ( conf [ 'KEY' ] ) )
get_value = partial ( utils . get_value , ** kwargs )
parse_conf = partial ( utils . parse_conf , parse_func = get_value , ** kwargs )
keys = imap ( parse_conf , key_defs )
... |
def named_config ( self , func ) :
"""Decorator to turn a function into a named configuration .
See : ref : ` named _ configurations ` .""" | config_scope = ConfigScope ( func )
self . _add_named_config ( func . __name__ , config_scope )
return config_scope |
def get_dhcp_options ( dhcp_options_name = None , dhcp_options_id = None , region = None , key = None , keyid = None , profile = None ) :
'''Return a dict with the current values of the requested DHCP options set
CLI Example :
. . code - block : : bash
salt myminion boto _ vpc . get _ dhcp _ options ' myfunny... | if not any ( ( dhcp_options_name , dhcp_options_id ) ) :
raise SaltInvocationError ( 'At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.' )
if not dhcp_options_id and dhcp_options_name :
dhcp_options_id = _get_resource_id ( 'dhcp_options' , dhcp_options_name , region = regio... |
def load_widget ( path ) :
"""Load custom widget for the form field""" | i = path . rfind ( '.' )
module , attr = path [ : i ] , path [ i + 1 : ]
try :
mod = import_module ( module )
except ( ImportError , ValueError ) as e :
error_message = 'Error importing widget for BleachField %s: "%s"'
raise ImproperlyConfigured ( error_message % ( path , e ) )
try :
cls = getattr ( mod... |
def use_comparative_activity_view ( self ) :
"""Pass through to provider ActivityLookupSession . use _ comparative _ activity _ view""" | self . _object_views [ 'activity' ] = COMPARATIVE
# self . _ get _ provider _ session ( ' activity _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_comparative_activity_view ( )
except AttributeError :
pass |
def percentile ( self , lst_data , percent , key = lambda x : x ) :
"""calculates the ' num ' percentile of the items in the list""" | new_list = sorted ( lst_data )
# print ( ' new list = ' , new _ list )
# n = float ( len ( lst _ data ) )
k = ( len ( new_list ) - 1 ) * percent
f = math . floor ( k )
c = math . ceil ( k )
if f == c : # print ( key ( new _ list [ int ( k ) ] ) )
return key ( new_list [ int ( k ) ] )
d0 = float ( key ( new_list [ i... |
def getComicStrip ( self , url , data ) :
"""Get comic strip downloader for given URL and data .""" | imageUrls = self . fetchUrls ( url , data , self . imageSearch )
# map modifier function on image URLs
imageUrls = [ self . imageUrlModifier ( x , data ) for x in imageUrls ]
# remove duplicate URLs
imageUrls = set ( imageUrls )
if len ( imageUrls ) > 1 and not self . multipleImagesPerStrip :
out . warn ( u"Found %... |
def modelComparisonDataFrame ( modelcomparisonfile , splitparams ) :
"""Converts ` ` modelcomparison . md ` ` file to ` pandas ` DataFrame .
Running ` ` phydms _ comprehensive ` ` creates a file with the suffix
` ` modelcomparison . md ` ` . This function converts that file into a
DataFrame that is easy to ha... | df = ( pandas . read_csv ( modelcomparisonfile , sep = '|' , skiprows = [ 1 ] ) . select ( lambda x : 'Unnamed' not in x , axis = 1 ) )
# strip whitespace
df . columns = df . columns . str . strip ( )
for col in df . columns :
if pandas . api . types . is_string_dtype ( df [ col ] ) :
df [ col ] = df [ col ... |
def fwd_chunk ( self ) :
"""Returns the chunk following this chunk in the list of free chunks . If this chunk is not free , then it resides in
no such list and this method raises an error .
: returns : If possible , the forward chunk ; otherwise , raises an error""" | if self . is_free ( ) :
base = self . state . memory . load ( self . base + 2 * self . _chunk_size_t_size , self . _chunk_size_t_size )
return PTChunk ( base , self . state )
else :
raise SimHeapError ( "Attempted to access the forward chunk of an allocated chunk" ) |
def network_interfaces_list ( resource_group , ** kwargs ) :
'''. . versionadded : : 2019.2.0
List all network interfaces within a resource group .
: param resource _ group : The resource group name to list network
interfaces within .
CLI Example :
. . code - block : : bash
salt - call azurearm _ networ... | result = { }
netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs )
try :
nics = __utils__ [ 'azurearm.paged_object_to_list' ] ( netconn . network_interfaces . list ( resource_group_name = resource_group ) )
for nic in nics :
result [ nic [ 'name' ] ] = nic
except CloudError as exc :
... |
def getRvaFromOffset ( self , offset ) :
"""Converts a RVA to an offset .
@ type offset : int
@ param offset : The offset value to be converted to RVA .
@ rtype : int
@ return : The RVA obtained from the given offset .""" | rva = - 1
s = self . getSectionByOffset ( offset )
if s :
rva = ( offset - self . sectionHeaders [ s ] . pointerToRawData . value ) + self . sectionHeaders [ s ] . virtualAddress . value
return rva |
def delete ( self , alert_condition_infra_id ) :
"""This API endpoint allows you to delete an alert condition for infrastucture
: type alert _ condition _ infra _ id : integer
: param alert _ condition _ infra _ id : Alert Condition Infra ID
: rtype : dict
: return : The JSON response of the API""" | return self . _delete ( url = '{0}alerts/conditions/{1}' . format ( self . URL , alert_condition_infra_id ) , headers = self . headers ) |
def render_diagram ( out_base ) :
"""Render a data model diagram
Included in the diagram are all classes from the model registry .
For your project , write a small script that imports all models that you would like to
have included and then calls this function .
. . note : : This function requires the ' dot... | import codecs
import subprocess
import sadisplay
# generate class descriptions
desc = sadisplay . describe ( list ( model_registry . values ( ) ) , show_methods = False , show_properties = True , show_indexes = True , )
# write description in DOT format
with codecs . open ( out_base + '.dot' , 'w' , encoding = 'utf-8' ... |
def set_icon_file ( self , filename , rel = "icon" ) :
"""Allows to define an icon for the App
Args :
filename ( str ) : the resource file name ( ie . " / res : myicon . png " )
rel ( str ) : leave it unchanged ( standard " icon " )""" | mimetype , encoding = mimetypes . guess_type ( filename )
self . add_child ( "favicon" , '<link rel="%s" href="%s" type="%s" />' % ( rel , filename , mimetype ) ) |
def sparkline_size ( self , sparkline_size ) :
"""Sets the sparkline _ size of this ChartSettings .
For the single stat view , a misleadingly named property . This determines whether the sparkline of the statistic is displayed in the chart BACKGROUND , BOTTOM , or NONE # noqa : E501
: param sparkline _ size : T... | allowed_values = [ "BACKGROUND" , "BOTTOM" , "NONE" ]
# noqa : E501
if sparkline_size not in allowed_values :
raise ValueError ( "Invalid value for `sparkline_size` ({0}), must be one of {1}" # noqa : E501
. format ( sparkline_size , allowed_values ) )
self . _sparkline_size = sparkline_size |
def update_module ( self , modname , underlined = None ) :
"""Update the cache for global names in ` modname ` module
` modname ` is the name of a module .""" | try :
pymodule = self . project . get_module ( modname )
self . _add_names ( pymodule , modname , underlined )
except exceptions . ModuleNotFoundError :
pass |
def get_context_data ( self , ** kwargs ) :
"""Add the current tag in context .""" | context = super ( BaseTagDetail , self ) . get_context_data ( ** kwargs )
context [ 'tag' ] = self . tag
return context |
def explode_services_duplicates ( self , hosts , service ) :
"""Explodes services holding a ` duplicate _ foreach ` clause .
: param hosts : The hosts container
: type hosts : alignak . objects . host . Hosts
: param service : The service to explode
: type service : alignak . objects . service . Service""" | hname = getattr ( service , "host_name" , None )
if hname is None :
return
# the generator case , we must create several new services
# we must find our host , and get all key : value we need
host = hosts . find_by_name ( hname . strip ( ) )
if host is None :
service . add_error ( 'Error: The hostname %s is unk... |
def buscar_por_id ( self , id_ambiente ) :
"""Obtém um ambiente a partir da chave primária ( identificador ) .
: param id _ ambiente : Identificador do ambiente .
: return : Dicionário com a seguinte estrutura :
{ ' ambiente ' : { ' id ' : < id _ ambiente > ,
' link ' : < link > ,
' id _ divisao ' : < ... | if not is_valid_int_param ( id_ambiente ) :
raise InvalidParameterError ( u'O identificador do ambiente é inválido ou não foi informado.' )
url = 'environment/id/' + str ( id_ambiente ) + '/'
code , xml = self . submit ( None , 'GET' , url )
return self . response ( code , xml ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.