signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _rebuild_all_command_chains ( self ) :
"""Rebuilds execution chain for all registered commands .
This method is typically called when intercepters are changed .
Because of that it is more efficient to register intercepters
before registering commands ( typically it will be done in abstract classes ) .
H... | self . _commands_by_name = { }
for command in self . _commands :
self . _build_command_chain ( command ) |
def password ( self , value ) :
"""gets / sets the current password""" | if isinstance ( value , str ) :
self . _password = value
self . _handler = None |
def parse_options ( self , kwargs ) :
"""Validate the provided kwargs and return options as json string .""" | kwargs = { camelize ( key ) : value for key , value in kwargs . items ( ) }
for key in kwargs . keys ( ) :
assert key in self . valid_options , ( 'The option {} is not in the available options: {}.' . format ( key , ', ' . join ( self . valid_options ) ) )
assert isinstance ( kwargs [ key ] , self . valid_optio... |
def load ( args ) :
""": param args : Will be used to infer the proper configuration name , or
if args . ceph _ conf is passed in , that will take precedence""" | path = args . ceph_conf or '{cluster}.conf' . format ( cluster = args . cluster )
try :
f = open ( path )
except IOError as e :
raise exc . ConfigError ( "%s; has `ceph-deploy new` been run in this directory?" % e )
else :
with contextlib . closing ( f ) :
return parse ( f ) |
def send_async ( self , msg , persist = False ) :
"""Arrange for ` msg ` to be delivered to this context , with replies
directed to a newly constructed receiver . : attr : ` dst _ id
< Message . dst _ id > ` is set to the target context ID , and : attr : ` reply _ to
< Message . reply _ to > ` is set to the n... | if self . router . broker . _thread == threading . currentThread ( ) : # TODO
raise SystemError ( 'Cannot making blocking call on broker thread' )
receiver = Receiver ( self . router , persist = persist , respondent = self )
msg . dst_id = self . context_id
msg . reply_to = receiver . handle
_v and LOG . debug ( '%... |
def name ( cls ) :
"""Return the preferred name as which this command will be known .""" | name = cls . __name__ . replace ( "_" , "-" ) . lower ( )
name = name [ 4 : ] if name . startswith ( "cmd-" ) else name
return name |
def default_for ( self , style_type ) :
"""Return ` w : style [ @ w : type = " * { style _ type } * ] [ - 1 ] ` or | None | if not found .""" | default_styles_for_type = [ s for s in self . _iter_styles ( ) if s . type == style_type and s . default ]
if not default_styles_for_type :
return None
# spec calls for last default in document order
return default_styles_for_type [ - 1 ] |
def get_sketch ( self , sketch_id ) :
"""Get information on the specified sketch .
Args :
sketch _ id ( int ) : ID of sketch
Returns :
dict : Dictionary of sketch information
Raises :
ValueError : Sketch is inaccessible""" | resource_url = '{0:s}/sketches/{1:d}/' . format ( self . api_base_url , sketch_id )
response = self . session . get ( resource_url )
response_dict = response . json ( )
try :
response_dict [ 'objects' ]
except KeyError :
raise ValueError ( 'Sketch does not exist or you have no access' )
return response_dict |
def from_merge_origin ( cls , tc ) :
"""Return instance created from merge - origin tc element .""" | other_tc = tc . tbl . tc ( tc . row_idx + tc . rowSpan - 1 , # - - - other _ row _ idx
tc . col_idx + tc . gridSpan - 1 # - - - other _ col _ idx
)
return cls ( tc , other_tc ) |
def assert_valid_execution_arguments ( schema : GraphQLSchema , document : DocumentNode , raw_variable_values : Dict [ str , Any ] = None , ) -> None :
"""Check that the arguments are acceptable .
Essential assertions before executing to provide developer feedback for improper use
of the GraphQL library .""" | if not document :
raise TypeError ( "Must provide document" )
# If the schema used for execution is invalid , throw an error .
assert_valid_schema ( schema )
# Variables , if provided , must be a dictionary .
if not ( raw_variable_values is None or isinstance ( raw_variable_values , dict ) ) :
raise TypeError (... |
def set_id ( self , id = '$' ) :
"""Set the last - read message id for each stream in the consumer group . By
default , this will be the special " $ " identifier , meaning all messages
are marked as having been read .
: param id : id of last - read message ( or " $ " ) .""" | accum = { }
for key in self . keys :
accum [ key ] = self . database . xgroup_setid ( key , self . name , id )
return accum |
def main ( argv : typing . Optional [ typing . Sequence ] = None ) -> typing . NoReturn :
"""Main entry point for the konch CLI .""" | args = parse_args ( argv )
if args [ "--debug" ] :
logging . basicConfig ( format = "%(levelname)s %(filename)s: %(message)s" , level = logging . DEBUG )
logger . debug ( args )
config_file : typing . Union [ Path , None ]
if args [ "init" ] :
config_file = Path ( args [ "<config_file>" ] or CONFIG_FILE )
i... |
def arbitrary_object_to_string ( a_thing ) :
"""take a python object of some sort , and convert it into a human readable
string . this function is used extensively to convert things like " subject "
into " subject _ key , function - > function _ key , etc .""" | # is it None ?
if a_thing is None :
return ''
# is it already a string ?
if isinstance ( a_thing , six . string_types ) :
return a_thing
if six . PY3 and isinstance ( a_thing , six . binary_type ) :
try :
return a_thing . decode ( 'utf-8' )
except UnicodeDecodeError :
pass
# does it have... |
def _is_significant ( stats , metrics = None ) :
"""Filter significant motifs based on several statistics .
Parameters
stats : dict
Statistics disctionary object .
metrics : sequence
Metric with associated minimum values . The default is
( ( " max _ enrichment " , 3 ) , ( " roc _ auc " , 0.55 ) , ( " en... | if metrics is None :
metrics = ( ( "max_enrichment" , 3 ) , ( "roc_auc" , 0.55 ) , ( "enr_at_fpr" , 0.55 ) )
for stat_name , min_value in metrics :
if stats . get ( stat_name , 0 ) < min_value :
return False
return True |
def _make_txn ( signer , setting_key , payload ) :
"""Creates and signs a sawtooth _ settings transaction with with a payload .""" | serialized_payload = payload . SerializeToString ( )
header = TransactionHeader ( signer_public_key = signer . get_public_key ( ) . as_hex ( ) , family_name = 'sawtooth_settings' , family_version = '1.0' , inputs = _config_inputs ( setting_key ) , outputs = _config_outputs ( setting_key ) , dependencies = [ ] , payload... |
def get_root ( self , ** kwargs ) :
'''Returns this tree if it has no parents , or , alternatively , moves
up via the parent links of this tree until reaching the tree with
no parents , and returnes the parentless tree as the root .''' | if self . parent == None :
return self
else :
return self . parent . get_root ( ** kwargs ) |
def _logpdf ( self , ** kwargs ) :
"""Returns the log of the pdf at the given values . The keyword
arguments must contain all of parameters in self ' s params . Unrecognized
arguments are ignored .""" | if kwargs not in self :
return - numpy . inf
return self . _lognorm + numpy . log ( self . _dfunc ( numpy . array ( [ kwargs [ p ] for p in self . _params ] ) ) ) . sum ( ) |
def endpoint ( self , * args ) :
"""endpoint : Decorates a function to make it a CLI endpoint
The function must be called do _ < some > _ < action > and accept one ' args '
parameter . It will be converted into a . / cli some action commandline
endpoint .
A set of Arguments can be passed to the decorator , ... | # Decorator function
def decorator ( func ) :
func_name = func . __name__
func_name = func_name . replace ( "do_" , "" )
actions = func_name . split ( "_" )
cmd_parser = None
sub = self . subparsers
wcount = 0
# For each word in the command we build the parsing tree
for word in actions :... |
def kde_plot_df ( df , xlims = None , ** kwargs ) :
"""Plots kde estimates of distributions of samples in each cell of the
input pandas DataFrame .
There is one subplot for each dataframe column , and on each subplot there
is one kde line .
Parameters
df : pandas data frame
Each cell must contain a 1d n... | assert xlims is None or isinstance ( xlims , dict )
figsize = kwargs . pop ( 'figsize' , ( 6.4 , 1.5 ) )
num_xticks = kwargs . pop ( 'num_xticks' , None )
nrows = kwargs . pop ( 'nrows' , 1 )
ncols = kwargs . pop ( 'ncols' , int ( np . ceil ( len ( df . columns ) / nrows ) ) )
normalize = kwargs . pop ( 'normalize' , T... |
def output_forecasts_json ( self , forecasts , condition_model_names , size_model_names , dist_model_names , track_model_names , json_data_path , out_path ) :
"""Output forecast values to geoJSON file format .
: param forecasts :
: param condition _ model _ names :
: param size _ model _ names :
: param tra... | total_tracks = self . data [ "forecast" ] [ "total" ]
for r in np . arange ( total_tracks . shape [ 0 ] ) :
track_id = total_tracks . loc [ r , "Track_ID" ]
print ( track_id )
track_num = track_id . split ( "_" ) [ - 1 ]
ensemble_name = total_tracks . loc [ r , "Ensemble_Name" ]
member = total_track... |
def _convert_claripy_bool_ast ( self , cond ) :
"""Convert recovered reaching conditions from claripy ASTs to ailment Expressions
: return : None""" | if isinstance ( cond , ailment . Expr . Expression ) :
return cond
if cond . op == "BoolS" and claripy . is_true ( cond ) :
return cond
if cond in self . _condition_mapping :
return self . _condition_mapping [ cond ]
_mapping = { 'Not' : lambda cond_ : ailment . Expr . UnaryOp ( None , 'Not' , self . _conve... |
def forever ( klass , * args , ** kws ) :
"""Create a server and block the calling thread until KeyboardInterrupt .
Shorthand for : : :
with Server ( * args , * * kws ) :
try ;
time . sleep ( 99999)
except KeyboardInterrupt :
pass""" | with klass ( * args , ** kws ) :
_log . info ( "Running server" )
try :
while True :
time . sleep ( 100 )
except KeyboardInterrupt :
pass
finally :
_log . info ( "Stopping server" ) |
def get_elements ( parent_to_parse , element_path ) :
""": return : all elements by name from the parsed parent element .
: see : get _ element ( parent _ to _ parse , element _ path )""" | element = get_element ( parent_to_parse )
if element is None or not element_path :
return [ ]
return element . findall ( element_path ) |
def retrieve ( self , id ) :
"""Retrieve a single lead
Returns a single lead available to the user , according to the unique lead ID provided
If the specified lead does not exist , this query returns an error
: calls : ` ` get / leads / { id } ` `
: param int id : Unique identifier of a Lead .
: return : ... | _ , _ , lead = self . http_client . get ( "/leads/{id}" . format ( id = id ) )
return lead |
def register ( self , observers ) :
"""Concrete method of Subject . register ( ) .
Register observers as an argument to self . observers .""" | if isinstance ( observers , list ) or isinstance ( observers , tuple ) :
for observer in observers : # check whether inhelitance " base . Observer "
if isinstance ( observer , base . Observer ) :
self . _observers . append ( observer )
else :
raise InhelitanceError ( base . O... |
def hierarchical_redundancy ( rdf , fix = False ) :
"""Check for and optionally remove extraneous skos : broader relations .
: param Graph rdf : An rdflib . graph . Graph object .
: param bool fix : Fix the problem by removing skos : broader relations between
concepts that are otherwise connected by skos : br... | for conc , parent1 in rdf . subject_objects ( SKOS . broader ) :
for parent2 in rdf . objects ( conc , SKOS . broader ) :
if parent1 == parent2 :
continue
# must be different
if parent2 in rdf . transitive_objects ( parent1 , SKOS . broader ) :
if fix :
... |
def get_contents_to_filename ( self , filename , headers = None , cb = None , num_cb = 10 , torrent = False , version_id = None , res_download_handler = None , response_headers = None , callback = None ) :
"""Retrieve an object from S3 using the name of the Key object as the
key in S3 . Store contents of the obje... | fp = open ( filename , 'wb' )
def got_contents_to_filename ( response ) :
fp . close ( )
# if last _ modified date was sent from s3 , try to set file ' s timestamp
if self . last_modified != None :
try :
modified_tuple = rfc822 . parsedate_tz ( self . last_modified )
modified... |
def remote_read ( self , maxlength ) :
"""Called from remote worker to read at most L { maxlength } bytes of data
@ type maxlength : C { integer }
@ param maxlength : Maximum number of data bytes that can be returned
@ return : Data read from L { fp }
@ rtype : C { string } of bytes read from file""" | if self . fp is None :
return ''
data = self . fp . read ( maxlength )
return data |
def get_id ( name = None , tags = None , region = None , key = None , keyid = None , profile = None , in_states = None , filters = None ) :
'''Given instance properties , return the instance id if it exists .
CLI Example :
. . code - block : : bash
salt myminion boto _ ec2 . get _ id myinstance''' | instance_ids = find_instances ( name = name , tags = tags , region = region , key = key , keyid = keyid , profile = profile , in_states = in_states , filters = filters )
if instance_ids :
log . info ( "Instance ids: %s" , " " . join ( instance_ids ) )
if len ( instance_ids ) == 1 :
return instance_ids [... |
async def get_tree ( self , prefix , * , dc = None , separator = None , watch = None , consistency = None ) :
"""Gets all keys with a prefix of Key during the transaction .
Parameters :
prefix ( str ) : Prefix to fetch
separator ( str ) : List only up to a given separator
dc ( str ) : Specify datacenter tha... | response = await self . _read ( prefix , dc = dc , recurse = True , separator = separator , watch = watch , consistency = consistency )
result = response . body
for data in result :
data [ "Value" ] = decode_value ( data [ "Value" ] , data [ "Flags" ] )
return consul ( result , meta = extract_meta ( response . head... |
def scale ( input_value , input_min , input_max , out_min , out_max ) :
"""scale a value from one range to another""" | # Figure out how ' wide ' each range is
input_span = input_max - input_min
output_span = out_max - out_min
# Convert the left range into a 0-1 range ( float )
valuescaled = float ( input_value - input_min ) / float ( input_span )
# Convert the 0-1 range into a value in the right range .
return out_min + ( valuescaled *... |
def _sigma_pi_hiE ( self , Tp , a ) :
"""General expression for Tp > 5 GeV ( Eq 7)""" | m_p = self . _m_p
csip = ( Tp - 3.0 ) / m_p
m1 = a [ 0 ] * csip ** a [ 3 ] * ( 1 + np . exp ( - a [ 1 ] * csip ** a [ 4 ] ) )
m2 = 1 - np . exp ( - a [ 2 ] * csip ** 0.25 )
multip = m1 * m2
return self . _sigma_inel ( Tp ) * multip |
def create ( self , req , driver ) :
"""Create a network
Create a new netowrk on special cloud
with :
: Param req
: Type object Request""" | response = driver . create_network ( req . params )
data = { 'action' : "create" , 'controller' : "network" , 'cloud' : req . environ [ 'calplus.cloud' ] , 'response' : response }
return data |
def create_asset_content ( self , asset_content_form = None ) :
"""Creates new ` ` AssetContent ` ` for a given asset .
: param asset _ content _ form : the form for this ` ` AssetContent ` `
: type asset _ content _ form : ` ` osid . repository . AssetContentForm ` `
: return : the new ` ` AssetContent ` `
... | if asset_content_form is None :
raise NullArgument ( )
if not isinstance ( asset_content_form , abc_repository_objects . AssetContentForm ) :
raise InvalidArgument ( 'argument type is not an AssetContentForm' )
if asset_content_form . is_for_update ( ) :
raise InvalidArgument ( 'form is for update only, not... |
def has_style ( node ) :
"""Tells us if node element has defined styling .
: Args :
- node ( : class : ` ooxml . doc . Element ` ) : Element
: Returns :
True or False""" | elements = [ 'b' , 'i' , 'u' , 'strike' , 'color' , 'jc' , 'sz' , 'ind' , 'superscript' , 'subscript' , 'small_caps' ]
return any ( [ True for elem in elements if elem in node . rpr ] ) |
def ExtractPathSpecs ( self , path_specs , find_specs = None , recurse_file_system = True , resolver_context = None ) :
"""Extracts path specification from a specific source .
Args :
path _ specs ( Optional [ list [ dfvfs . PathSpec ] ] ) : path specifications .
find _ specs ( Optional [ list [ dfvfs . FindSp... | for path_spec in path_specs :
for extracted_path_spec in self . _ExtractPathSpecs ( path_spec , find_specs = find_specs , recurse_file_system = recurse_file_system , resolver_context = resolver_context ) :
yield extracted_path_spec |
def from_json ( cls , json_info ) :
"""Build a Trial instance from a json string .""" | if json_info is None :
return None
return TrialRecord ( trial_id = json_info [ "trial_id" ] , job_id = json_info [ "job_id" ] , trial_status = json_info [ "status" ] , start_time = json_info [ "start_time" ] , params = json_info [ "params" ] ) |
def render ( self , size ) :
"""render identicon to PIL . Image
@ param size identicon patchsize . ( image size is 3 * [ size ] )
@ return PIL . Image""" | # decode the code
middle , corner , side , foreColor , backColor = self . decode ( self . code )
size = int ( size )
# make image
image = Image . new ( "RGB" , ( size * 3 , size * 3 ) )
draw = ImageDraw . Draw ( image )
# fill background
draw . rectangle ( ( 0 , 0 , image . size [ 0 ] , image . size [ 1 ] ) , fill = 0 ... |
def population ( self ) :
"Class containing the population and all the individuals generated" | try :
return self . _p
except AttributeError :
self . _p = self . _population_class ( base = self , tournament_size = self . _tournament_size , classifier = self . classifier , labels = self . _labels , es_extra_test = self . es_extra_test , popsize = self . _popsize , random_generations = self . _random_genera... |
def save_params ( self , fname ) :
"""Saves model parameters to file .
Parameters
fname : str
Path to output param file .
Examples
> > > # An example of saving module parameters .
> > > mod . save _ params ( ' myfile ' )""" | arg_params , aux_params = self . get_params ( )
save_dict = { ( 'arg:%s' % k ) : v . as_in_context ( cpu ( ) ) for k , v in arg_params . items ( ) }
save_dict . update ( { ( 'aux:%s' % k ) : v . as_in_context ( cpu ( ) ) for k , v in aux_params . items ( ) } )
ndarray . save ( fname , save_dict ) |
def set_input_func ( self , input_func ) :
"""Set input _ func of device .
Valid values depend on the device and should be taken from
" input _ func _ list " .
Return " True " on success and " False " on fail .""" | # For selection of sources other names then at receiving sources
# have to be used
# AVR - X receiver needs source mapping to set input _ func
if self . _receiver_type in [ AVR_X . type , AVR_X_2016 . type ] :
direct_mapping = False
try :
linp = CHANGE_INPUT_MAPPING [ self . _input_func_list [ input_fun... |
def RunOnce ( self ) :
"""Run this once on init .""" | global WEBAUTH_MANAGER
# pylint : disable = global - statement
# pylint : disable = g - bad - name
WEBAUTH_MANAGER = BaseWebAuthManager . GetPlugin ( config . CONFIG [ "AdminUI.webauth_manager" ] ) ( )
# pylint : enable = g - bad - name
logging . info ( "Using webauth manager %s" , WEBAUTH_MANAGER ) |
def process_url ( url , server_name = "" , document_root = None , check_security = True ) :
"""Goes through the url and returns a dictionary of fields .
For example :
img / photos / 2008/05/12 / WIZARDS _ 0034_05022035 _ r329x151 . jpg ? e315d4515574cec417b1845392ba687dd98c17ce
actions : [ ( ' r ' , ' 329x151... | from . network import Http404
from settings import ( BASE_PATH , ORIG_BASE_PATH , USE_VHOSTS , VHOST_DOC_BASE , EXTERNAL_PREFIX )
try :
request_uri , security_hash = url . split ( "?" , 1 )
except ValueError :
request_uri , security_hash = url , ""
external_prefix = EXTERNAL_PREFIX
is_external = request_uri . s... |
def libvlc_audio_output_device_enum ( mp ) :
'''Gets a list of potential audio output devices ,
See L { libvlc _ audio _ output _ device _ set } ( ) .
@ note : Not all audio outputs support enumerating devices .
The audio output may be functional even if the list is empty ( NULL ) .
@ note : The list may no... | f = _Cfunctions . get ( 'libvlc_audio_output_device_enum' , None ) or _Cfunction ( 'libvlc_audio_output_device_enum' , ( ( 1 , ) , ) , None , ctypes . POINTER ( AudioOutputDevice ) , MediaPlayer )
return f ( mp ) |
def local_subset ( self , * args , ** kwargs ) :
'''Run : ref : ` execution modules < all - salt . modules > ` against subsets of minions
. . versionadded : : 2016.3.0
Wraps : py : meth : ` salt . client . LocalClient . cmd _ subset `''' | local = salt . client . get_local_client ( mopts = self . opts )
return local . cmd_subset ( * args , ** kwargs ) |
def get_formfield ( model , field ) :
"""Return the formfied associate to the field of the model""" | class_field = model . _meta . get_field ( field )
if hasattr ( class_field , "field" ) :
formfield = class_field . field . formfield ( )
else :
formfield = class_field . formfield ( )
# Otherwise the formfield contain the reverse relation
if isinstance ( formfield , ChoiceField ) :
formfield . choices = cla... |
def list_pp ( ll , separator = '|' , header_line = True , autonumber = True ) :
"""pretty print list of lists ll""" | if autonumber :
for cnt , i in enumerate ( ll ) :
i . insert ( 0 , cnt if cnt > 0 or not header_line else '#' )
def lenlst ( l ) :
return [ len ( str ( i ) ) for i in l ]
lst_len = [ lenlst ( i ) for i in ll ]
lst_rot = zip ( * lst_len [ : : - 1 ] )
lst_len = [ max ( i ) for i in lst_rot ]
frmt = separa... |
def strand_barplot ( self ) :
"""Plot a bargraph showing the strandedness of alignments""" | # Plot bar graph of groups
keys = [ 'End 1 Sense' , 'End 1 Antisense' , 'End 2 Sense' , 'End 2 Antisense' ]
# Config for the plot
pconfig = { 'id' : 'rna_seqc_strandedness_plot' , 'title' : 'RNA-SeQC: Strand Specificity' , 'ylab' : '% Reads' , 'cpswitch_counts_label' : '# Reads' , 'cpswitch_percent_label' : '% Reads' ,... |
def target_to_ipv4_short ( target ) :
"""Attempt to return a IPv4 short range list from a target string .""" | splitted = target . split ( '-' )
if len ( splitted ) != 2 :
return None
try :
start_packed = inet_pton ( socket . AF_INET , splitted [ 0 ] )
end_value = int ( splitted [ 1 ] )
except ( socket . error , ValueError ) :
return None
start_value = int ( binascii . hexlify ( bytes ( start_packed [ 3 ] ) ) , ... |
def tobinary ( series , path , prefix = 'series' , overwrite = False , credentials = None ) :
"""Writes out data to binary format .
Parameters
series : Series
The data to write
path : string path or URI to directory to be created
Output files will be written underneath path .
Directory will be created a... | from six import BytesIO
from thunder . utils import check_path
from thunder . writers import get_parallel_writer
if not overwrite :
check_path ( path , credentials = credentials )
overwrite = True
def tobuffer ( kv ) :
firstkey = None
buf = BytesIO ( )
for k , v in kv :
if firstkey is None :... |
def funding ( self ) :
"""List of namedtuples parsed funding information in the form
( agency string id acronym country ) .""" | path = [ 'item' , 'xocs:meta' , 'xocs:funding-list' , 'xocs:funding' ]
funds = listify ( chained_get ( self . _json , path , [ ] ) )
out = [ ]
fund = namedtuple ( 'Funding' , 'agency string id acronym country' )
for item in funds :
new = fund ( agency = item . get ( 'xocs:funding-agency' ) , string = item . get ( '... |
def round_to ( self , dt , hour , minute , second , mode = "floor" ) :
"""Round the given datetime to specified hour , minute and second .
: param mode : ' floor ' or ' ceiling '
* * 中文文档 * *
将给定时间对齐到最近的一个指定了小时 , 分钟 , 秒的时间上 。""" | mode = mode . lower ( )
new_dt = datetime ( dt . year , dt . month , dt . day , hour , minute , second )
if mode == "floor" :
if new_dt <= dt :
return new_dt
else :
return rolex . add_days ( new_dt , - 1 )
elif mode == "ceiling" :
if new_dt >= dt :
return new_dt
else :
re... |
def createDataFromFile ( self , filePath , inputEncoding = None , defaultFps = None ) :
"""Fetch a given filePath and parse its contents .
May raise the following exceptions :
* RuntimeError - generic exception telling that parsing was unsuccessfull
* IOError - failed to open a file at given filePath
@ retu... | file_ = File ( filePath )
if inputEncoding is None :
inputEncoding = file_ . detectEncoding ( )
inputEncoding = inputEncoding . lower ( )
videoInfo = VideoInfo ( defaultFps ) if defaultFps is not None else file_ . detectFps ( )
subtitles = self . _parseFile ( file_ , inputEncoding , videoInfo . fps )
data = Subtitl... |
def by_type ( blocks , slist = None ) :
"""Sort blocks into layout , internal volume , data or unknown
Arguments :
Obj : blocks - - List of block objects .
List : slist - - ( optional ) List of block indexes .
Returns :
List : layout - - List of block indexes of blocks containing the
volume table record... | layout = [ ]
data = [ ]
int_vol = [ ]
unknown = [ ]
for i in blocks :
if slist and i not in slist :
continue
if blocks [ i ] . is_vtbl and blocks [ i ] . is_valid :
layout . append ( i )
elif blocks [ i ] . is_internal_vol and blocks [ i ] . is_valid :
int_vol . append ( i )
elif... |
def Collect ( self , knowledge_base , artifact_definition , searcher , file_system ) :
"""Collects values using a file artifact definition .
Args :
knowledge _ base ( KnowledgeBase ) : to fill with preprocessing information .
artifact _ definition ( artifacts . ArtifactDefinition ) : artifact definition .
s... | for source in artifact_definition . sources :
if source . type_indicator not in ( artifact_definitions . TYPE_INDICATOR_FILE , artifact_definitions . TYPE_INDICATOR_PATH ) :
continue
for path in source . paths : # Make sure the path separators used in the artifact definition
# correspond to those us... |
def output ( data , ** kwargs ) : # pylint : disable = unused - argument
'''Print the output data in JSON''' | try :
dump_opts = { 'indent' : 4 , 'default' : repr }
if 'output_indent' in __opts__ :
indent = __opts__ . get ( 'output_indent' )
sort_keys = False
if indent == 'pretty' :
indent = 4
sort_keys = True
elif isinstance ( indent , six . integer_types ) :
... |
def _get_ordered_idx ( self , mask_missing_values ) :
"""Decide in what order we will update the features .
As a homage to the MICE R package , we will have 4 main options of
how to order the updates , and use a random order if anything else
is specified .
Also , this function skips features which have no m... | frac_of_missing_values = mask_missing_values . mean ( axis = 0 )
missing_values_idx = np . nonzero ( frac_of_missing_values ) [ 0 ]
if self . imputation_order == 'roman' :
ordered_idx = missing_values_idx
elif self . imputation_order == 'arabic' :
ordered_idx = missing_values_idx [ : : - 1 ]
elif self . imputat... |
def _parse_resource ( self , resource ) :
"""Ensure compliance with the spec ' s resource objects section
: param resource :
dict JSON API resource object""" | link = 'jsonapi.org/format/#document-resource-objects'
rid = isinstance ( resource . get ( 'id' ) , unicode )
rtype = isinstance ( resource . get ( 'type' ) , unicode )
if not rtype or ( self . req . is_patching and not rid ) :
self . fail ( 'JSON API requires that every resource object MUST ' 'contain a `type` top... |
def parse ( self ) :
"""parse geojson and ensure is collection""" | try :
self . parsed_data = json . loads ( self . data )
except UnicodeError as e :
self . parsed_data = json . loads ( self . data . decode ( 'latin1' ) )
except Exception as e :
raise Exception ( 'Error while converting response from JSON to python. %s' % e )
if self . parsed_data . get ( 'type' , '' ) != ... |
def get_ssid ( _ , data ) :
"""http : / / git . kernel . org / cgit / linux / kernel / git / jberg / iw . git / tree / util . c ? id = v3.17 # n313.
Positional arguments :
data - - bytearray data to read .
Returns :
String .""" | converted = list ( )
for i in range ( len ( data ) ) :
try :
c = unichr ( data [ i ] )
except NameError :
c = chr ( data [ i ] )
if unicodedata . category ( c ) != 'Cc' and c not in ( ' ' , '\\' ) :
converted . append ( c )
elif c == '\0' :
converted . append ( c )
el... |
def _try_get_state_scope ( name , mark_name_scope_used = True ) :
"""Returns a fresh variable / name scope for a module ' s state .
In order to import a module into a given scope without major complications
we require the scope to be empty . This function deals with deciding an unused
scope where to define th... | tmp_scope_name = tf_v1 . get_variable_scope ( ) . name
if tmp_scope_name :
tmp_scope_name += "/"
with tf . name_scope ( tmp_scope_name ) : # Pick an unused variable scope .
with tf_v1 . variable_scope ( None , default_name = name , auxiliary_name_scope = False ) as vs :
abs_state_scope = vs . name + "/"... |
def from_data ( source ) :
"""Infers a table / view schema from its JSON representation , a list of records , or a Pandas
dataframe .
Args :
source : the Pandas Dataframe , a dictionary representing a record , a list of heterogeneous
data ( record ) or homogeneous data ( list of records ) from which to infe... | if isinstance ( source , pandas . DataFrame ) :
bq_schema = Schema . _from_dataframe ( source )
elif isinstance ( source , list ) :
if len ( source ) == 0 :
bq_schema = source
elif all ( isinstance ( d , dict ) for d in source ) :
if all ( 'name' in d and 'type' in d for d in source ) : # It... |
def restructuredtext ( text , ** kwargs ) :
"""Applies reStructuredText conversion to a string , and returns the
HTML .""" | from docutils import core
parts = core . publish_parts ( source = text , writer_name = 'html4css1' , ** kwargs )
return parts [ 'fragment' ] |
def adapt_datetimefield_value ( self , value ) :
"""Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns .""" | if value is None :
return None
if self . connection . _DJANGO_VERSION >= 14 and settings . USE_TZ :
if timezone . is_aware ( value ) : # pyodbc donesn ' t support datetimeoffset
value = value . astimezone ( timezone . utc )
if not self . connection . features . supports_microsecond_precision :
value... |
def remove_all ( self , filter , force = False , timeout = - 1 ) :
"""Deletes the set of datacenters according to the specified parameters . A filter is required to identify the set
of resources to be deleted .
Args :
filter :
A general filter / query string to narrow the list of items that will be removed ... | return self . _client . delete_all ( filter = filter , force = force , timeout = timeout ) |
def dlogpdf_df_dtheta ( self , f , y , Y_metadata = None ) :
"""TODO : Doc strings""" | if self . size > 0 :
if self . not_block_really :
raise NotImplementedError ( "Need to make a decorator for this!" )
if isinstance ( self . gp_link , link_functions . Identity ) :
return self . dlogpdf_dlink_dtheta ( f , y , Y_metadata = Y_metadata )
else :
inv_link_f = self . gp_lin... |
def mmi_to_delimited_text ( self ) :
"""Return the mmi data as a delimited test string .
: returns : A delimited text string that can easily be written to disk
for e . g . use by gdal _ grid .
: rtype : str
The returned string will look like this : :
123.0750,01.7900,1
123.1000,01.7900,1.14
123.1250,0... | delimited_text = 'lon,lat,mmi\n'
for row in self . mmi_data :
delimited_text += '%s,%s,%s\n' % ( row [ 0 ] , row [ 1 ] , row [ 2 ] )
return delimited_text |
def write_memory ( self , session , space , offset , data , width , extended = False ) :
"""Write in an 8 - bit , 16 - bit , 32 - bit , 64 - bit value to the specified memory space and offset .
Corresponds to viOut * functions of the VISA library .
: param session : Unique logical identifier to a session .
: ... | if width == 8 :
return self . out_8 ( session , space , offset , data , extended )
elif width == 16 :
return self . out_16 ( session , space , offset , data , extended )
elif width == 32 :
return self . out_32 ( session , space , offset , data , extended )
elif width == 64 :
return self . out_64 ( sessi... |
def flush ( self ) :
"""Flush pending items to Dynamo""" | items = [ ]
for data in self . _to_put :
items . append ( encode_put ( self . connection . dynamizer , data ) )
for data in self . _to_delete :
items . append ( encode_delete ( self . connection . dynamizer , data ) )
self . _write ( items )
self . _to_put = [ ]
self . _to_delete = [ ] |
def upper_key ( fn ) :
""": param fn : a key function
: return :
a function that wraps around the supplied key function to ensure
the returned key is in uppercase .""" | def upper ( key ) :
try :
return key . upper ( )
except AttributeError :
return key
return process_key ( upper , fn ) |
def lomb_scargle_fast ( t , y , dy = 1 , f0 = 0 , df = None , Nf = None , center_data = True , fit_offset = True , use_fft = True , freq_oversampling = 5 , nyquist_factor = 2 , trig_sum_kwds = None ) :
"""Compute a lomb - scargle periodogram for the given data
This implements both an O [ N ^ 2 ] method if use _ f... | # Validate and setup input data
t , y , dy = map ( np . ravel , np . broadcast_arrays ( t , y , dy ) )
w = 1. / ( dy ** 2 )
w /= w . sum ( )
# Validate and setup frequency grid
if df is None :
peak_width = 1. / ( t . max ( ) - t . min ( ) )
df = peak_width / freq_oversampling
if Nf is None :
avg_Nyquist = 0... |
def _load_ini ( self , namespace , config_file ) :
"""Load INI style configuration .""" | self . LOG . debug ( "Loading %r..." % ( config_file , ) )
ini_file = ConfigParser . SafeConfigParser ( )
ini_file . optionxform = str
# case - sensitive option names
if ini_file . read ( config_file ) :
self . _set_from_ini ( namespace , ini_file )
else :
self . LOG . warning ( "Configuration file %r not found... |
def trigger_events ( events , loop ) :
"""Trigger event callbacks ( functions or async )
: param events : one or more sync or async functions to execute
: param loop : event loop""" | for event in events :
result = event ( loop )
if isawaitable ( result ) :
loop . run_until_complete ( result ) |
def delete ( self ) :
"""Deletes the resource .""" | return self . _client . _delete ( self . __class__ . base_url ( self . sys [ 'space' ] . id , self . sys [ 'id' ] , environment_id = self . _environment_id ) ) |
def make_data ( ) :
"""creates example data set""" | I , d = multidict ( { 1 : 80 , 2 : 270 , 3 : 250 , 4 : 160 , 5 : 180 } )
# demand
J , M , f = multidict ( { 1 : [ 500 , 1000 ] , 2 : [ 500 , 1000 ] , 3 : [ 500 , 1000 ] } )
# capacity , fixed costs
c = { ( 1 , 1 ) : 4 , ( 1 , 2 ) : 6 , ( 1 , 3 ) : 9 , # transportation costs
( 2 , 1 ) : 5 , ( 2 , 2 ) : 4 , ( 2 , 3 ) : 7... |
def _method_complete ( self , result ) :
"""Called after a registered method with the result .""" | if isinstance ( result , ( PrettyTensor , Loss , PrettyTensorTupleMixin ) ) :
return result
elif ( isinstance ( result , collections . Sequence ) and not isinstance ( result , six . string_types ) ) :
return self . with_sequence ( result )
else :
return self . with_tensor ( result ) |
def delete ( self , context , plan ) :
"""Include a delete operation to the given plan .
: param execution . Context context :
Current execution context .
: param list plan :
List of : class : ` execution . Operation ` instances .""" | op = execution . Delete ( self . __comp_name , self . __comp ( ) )
if op not in plan and self . available ( context ) != False :
for dep_stub in self . __dependents ( self . __comp_stub_reg . get ( None ) ) :
dep_stub . delete ( context , plan )
plan . append ( op ) |
def anonymous_login_view ( request ) :
'''View for an admin to log her / himself out and login the anonymous user .''' | logout ( request )
try :
spineless = User . objects . get ( username = ANONYMOUS_USERNAME )
except User . DoesNotExist :
random_password = User . objects . make_random_password ( )
spineless = User . objects . create_user ( username = ANONYMOUS_USERNAME , first_name = "Anonymous" , last_name = "Coward" , pa... |
def text_to_edtf ( text ) :
"""Generate EDTF string equivalent of a given natural language date string .""" | if not text :
return
t = text . lower ( )
# try parsing the whole thing
result = text_to_edtf_date ( t )
if not result : # split by list delims and move fwd with the first thing that returns a non - empty string .
# TODO : assemble multiple dates into a { } or [ ] structure .
for split in [ "," , ";" , "or" ] :... |
def _read_para_host_id ( self , code , cbit , clen , * , desc , length , version ) :
"""Read HIP HOST _ ID parameter .
Structure of HIP HOST _ ID parameter [ RFC 7401 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Type | Length |
| HI Length | DI - Type | DI Length |
| Alg... | def _read_host_identifier ( length , code ) :
algorithm = _HI_ALGORITHM . get ( code , 'Unassigned' )
if algorithm == 'ECDSA' :
host_id = dict ( curve = _ECDSA_CURVE . get ( self . _read_unpack ( 2 ) ) , pubkey = self . _read_fileng ( length - 2 ) , )
elif algorithm == 'ECDSA_LOW' :
host_id ... |
def __get_stack_trace ( self , depth = 16 , bUseLabels = True , bMakePretty = True ) :
"""Tries to get a stack trace for the current function using the debug
helper API ( dbghelp . dll ) .
@ type depth : int
@ param depth : Maximum depth of stack trace .
@ type bUseLabels : bool
@ param bUseLabels : C { T... | aProcess = self . get_process ( )
arch = aProcess . get_arch ( )
bits = aProcess . get_bits ( )
if arch == win32 . ARCH_I386 :
MachineType = win32 . IMAGE_FILE_MACHINE_I386
elif arch == win32 . ARCH_AMD64 :
MachineType = win32 . IMAGE_FILE_MACHINE_AMD64
elif arch == win32 . ARCH_IA64 :
MachineType = win32 .... |
def __Connection_End_lineEdit_set_ui ( self ) :
"""Fills * * Connection _ End _ lineEdit * * Widget .""" | # Adding settings key if it doesn ' t exists .
self . __settings . get_key ( self . __settings_section , "connection_end" ) . isNull ( ) and self . __settings . set_key ( self . __settings_section , "connection_end" , self . __connection_end )
connection_end = self . __settings . get_key ( self . __settings_section , "... |
def create_initial ( self , address_values ) :
"""Create futures from inputs with the current value for that address
at the start of that context .
Args :
address _ values ( list of tuple ) : The tuple is string , bytes of the
address and value .""" | with self . _lock :
for add , val in address_values :
self . _state [ add ] = _ContextFuture ( address = add , result = val ) |
def put_event_multi_touch ( self , count , contacts , scan_time ) :
"""Sends a multi - touch pointer event . The coordinates are expressed in
pixels and start from [ 1,1 ] which corresponds to the top left
corner of the virtual display .
The guest may not understand or may choose to ignore this event .
: py... | if not isinstance ( count , baseinteger ) :
raise TypeError ( "count can only be an instance of type baseinteger" )
if not isinstance ( contacts , list ) :
raise TypeError ( "contacts can only be an instance of type list" )
for a in contacts [ : 10 ] :
if not isinstance ( a , baseinteger ) :
raise T... |
def show_fibrechannel_interface_info_output_show_fibrechannel_interface_show_fibrechannel_info_port_interface ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_fibrechannel_interface_info = ET . Element ( "show_fibrechannel_interface_info" )
config = show_fibrechannel_interface_info
output = ET . SubElement ( show_fibrechannel_interface_info , "output" )
show_fibrechannel_interface = ET . SubElement ( output , "show-fibrechannel-interfa... |
def random_points ( self , n , minmass = None , maxmass = None , minage = None , maxage = None , minfeh = None , maxfeh = None ) :
"""Returns n random mass , age , feh points , none of which are out of range .
: param n :
Number of desired points .
: param minmass , maxmass : ( optional )
Desired allowed ra... | if minmass is None :
minmass = self . minmass
if maxmass is None :
maxmass = self . maxmass
if minage is None :
minage = self . minage
if maxage is None :
maxage = self . maxage
if minfeh is None :
minfeh = self . minfeh
if maxfeh is None :
maxfeh = self . maxfeh
ms = rand . uniform ( minmass , ... |
def p_jr ( p ) :
"""asm : JR jr _ flags COMMA expr
| JR jr _ flags COMMA pexpr""" | p [ 4 ] = Expr . makenode ( Container ( '-' , p . lineno ( 3 ) ) , p [ 4 ] , Expr . makenode ( Container ( MEMORY . org + 2 , p . lineno ( 1 ) ) ) )
p [ 0 ] = Asm ( p . lineno ( 1 ) , 'JR %s,N' % p [ 2 ] , p [ 4 ] ) |
def kill ( self , container , signal = None ) :
"""Kill a container or send a signal to a container .
Args :
container ( str ) : The container to kill
signal ( str or int ) : The signal to send . Defaults to ` ` SIGKILL ` `
Raises :
: py : class : ` docker . errors . APIError `
If the server returns an ... | url = self . _url ( "/containers/{0}/kill" , container )
params = { }
if signal is not None :
if not isinstance ( signal , six . string_types ) :
signal = int ( signal )
params [ 'signal' ] = signal
res = self . _post ( url , params = params )
self . _raise_for_status ( res ) |
def __return_json ( url ) :
"""Returns JSON data which is returned by querying the API service
Called by
- meaning ( )
- synonym ( )
: param url : the complete formatted url which is then queried using requests
: returns : json content being fed by the API""" | with try_URL ( ) :
response = requests . get ( url )
if response . status_code == 200 :
return response . json ( )
else :
return False |
def ne ( self , value ) :
"""Construct a not equal to ( ` ` ! = ` ` ) filter .
: param value : Filter value
: return : : class : ` filters . Field < filters . Field > ` object
: rtype : filters . Field""" | self . op = '!='
self . negate_op = '='
self . value = self . _value ( value )
return self |
def draw_polygon ( self , * pts , close_path : bool = True , stroke : Color = None , stroke_width : float = 1 , stroke_dash : typing . Sequence = None , fill : Color = None ) -> None :
"""Draws the given linear path .""" | pass |
def run ( self ) :
"""Executed by Sphinx .
: returns : Single DisqusNode instance with config values passed as arguments .
: rtype : list""" | disqus_shortname = self . get_shortname ( )
disqus_identifier = self . get_identifier ( )
return [ DisqusNode ( disqus_shortname , disqus_identifier ) ] |
def ensure_state ( default_getter , exc_class , default_msg = None ) :
"""Create a decorator factory function .""" | def decorator ( getter = default_getter , msg = default_msg ) :
def ensure_decorator ( f ) :
@ wraps ( f )
def inner ( self , * args , ** kwargs ) :
if not getter ( self ) :
raise exc_class ( msg ) if msg else exc_class ( )
return f ( self , * args , ** kwargs... |
def load_project_metrics ( ) :
"""Create project metrics for financial indicator
Updates them if already exists""" | all_metrics = FinancialIndicator . METRICS
for key in all_metrics :
df = getattr ( data , key )
pronac = 'PRONAC'
if key == 'planilha_captacao' :
pronac = 'Pronac'
pronacs = df [ pronac ] . unique ( ) . tolist ( )
create_finance_metrics ( all_metrics [ key ] , pronacs ) |
def remove_root_objective_bank ( self , alias = None , objective_bank_id = None ) :
"""Removes a root objective bank .
arg : objective _ bank _ id ( osid . id . Id ) : the ` ` Id ` ` of an
objective bank
raise : NotFound - ` ` objective _ bank _ id ` ` is not a root
raise : NullArgument - ` ` objective _ ba... | url_path = self . _urls . roots ( alias = alias )
current_root_ids = self . _get_request ( url_path ) [ 'ids' ]
modified_list = [ ]
for root_id in current_root_ids :
if root_id != str ( objective_bank_id ) :
modified_list . append ( root_id )
new_root_ids = { 'ids' : modified_list }
return self . _put_reque... |
def backup_restore ( cls , block_id , impl , working_dir ) :
"""Restore from a backup , given the virutalchain implementation module and block number .
NOT THREAD SAFE . DO NOT CALL WHILE INDEXING .
Return True on success
Raise exception on error , i . e . if a backup file is missing""" | backup_dir = config . get_backups_directory ( impl , working_dir )
backup_paths = cls . get_backup_paths ( block_id , impl , working_dir )
for p in backup_paths :
assert os . path . exists ( p ) , "No such backup file: {}" . format ( p )
for p in cls . get_state_paths ( impl , working_dir ) :
pbase = os . path ... |
def _split_file ( self , data = '' ) :
"""Splits SAR output or SAR output file ( in ASCII format ) in order to
extract info we need for it , in the format we want .
: param data : Input data instead of file
: type data : str .
: return : ` ` List ` ` - style of SAR file sections separated by
the type of i... | # Filename passed checks through _ _ init _ _
if ( ( self . __filename and os . access ( self . __filename , os . R_OK ) ) or data != '' ) :
fhandle = None
if data == '' :
try :
fhandle = os . open ( self . __filename , os . O_RDONLY )
except OSError :
print ( ( "Couldn't... |
def predict ( self , * args , ** kwargs ) :
"""Predict given DataFrame using the given model . Actual prediction steps will not
be executed till an operational step is called .
After execution , three columns will be appended to the table :
| Field name | Type | Comments |
| prediction _ result | string | f... | return super ( PmmlModel , self ) . predict ( * args , ** kwargs ) |
def get_stp_mst_detail_output_cist_port_oper_bpdu_filter ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" )
config = get_stp_mst_detail
output = ET . SubElement ( get_stp_mst_detail , "output" )
cist = ET . SubElement ( output , "cist" )
port = ET . SubElement ( cist , "port" )
oper_bpdu_filter = ET . SubElement ( port , "oper-bpdu-... |
def redis ( self ) :
"""Return instance of Redis .""" | if self . _redis is None :
self . _redis = redis . StrictRedis ( host = self . args . redis_host , port = self . args . redis_port )
return self . _redis |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.