signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def author_edit_view ( self , context ) :
"""Child blocks can override this to control the view shown to authors in Studio when
editing this block ' s children .""" | fragment = Fragment ( )
self . render_children ( context , fragment , can_reorder = True , can_add = False )
return fragment |
def to_html ( self , codebase ) :
"""Convert this ClassDoc to HTML . This returns the default long - form
HTML description that ' s used when the full docs are built .""" | return ( '<a name = "%s" />\n<div class = "jsclass">\n' + '<h3>%s</h3>\n%s\n<h4>Methods</h4>\n%s</div>' ) % ( self . name , self . name , htmlize_paragraphs ( codebase . translate_links ( self . doc , self ) ) + codebase . build_see_html ( self . see , 'h4' , self ) , '\n' . join ( method . to_html ( codebase ) for met... |
def get_indels ( self , one_based = True ) :
"""Return a data structure containing all indels in the read .
Returns the tuple ( insertions , deletions )
insertions = [ ( pos1 , ins1 ) , ( pos2 , ins2 ) ]
posN = start position ( preceding base , VCF - style )
insN = length of inserted sequence ( not includin... | cigar = self . get_cigar ( )
# CIGAR _ OP = list ( ' MIDNSHP = X ' )
insertions = [ ]
deletions = [ ]
position_offset = 0
position_start = self . get_position ( one_based = one_based )
while cigar :
cigar_size , cigar_op = cigar . pop ( 0 )
if cigar_op in [ 0 , 7 , 8 ] : # M alignment match ( can be a sequence ... |
def _validate_extra_component ( bs_data ) :
'''Extra checks for component basis files''' | assert len ( bs_data [ 'elements' ] ) > 0
# Make sure size of the coefficient matrix matches the number of exponents
for el in bs_data [ 'elements' ] . values ( ) :
if not 'electron_shells' in el :
continue
for s in el [ 'electron_shells' ] :
nprim = len ( s [ 'exponents' ] )
if nprim <=... |
def get_roots ( app = None ) :
'''Returns the list of root packages / modules exposing endpoints .
If app is provided , only returns those of enabled plugins''' | roots = set ( )
plugins = app . config [ 'PLUGINS' ] if app else None
for name in ENTRYPOINTS . keys ( ) :
for ep in iter_all ( name ) :
if plugins is None or ep . name in plugins :
roots . add ( ep . module_name . split ( '.' , 1 ) [ 0 ] )
return list ( roots ) |
def step4 ( self ) :
"""step4 ( ) takes off - ant , - ence etc . , in context < c > vcvc < v > .""" | if self . b [ self . k - 1 ] == 'a' :
if self . ends ( "al" ) :
pass
else :
return
elif self . b [ self . k - 1 ] == 'c' :
if self . ends ( "ance" ) :
pass
elif self . ends ( "ence" ) :
pass
else :
return
elif self . b [ self . k - 1 ] == 'e' :
if self . e... |
def insert_arguments_into_query ( compilation_result , arguments ) :
"""Insert the arguments into the compiled GraphQL query to form a complete query .
Args :
compilation _ result : a CompilationResult object derived from the GraphQL compiler
arguments : dict , mapping argument name to its value , for every p... | _ensure_arguments_are_provided ( compilation_result . input_metadata , arguments )
if compilation_result . language == MATCH_LANGUAGE :
return insert_arguments_into_match_query ( compilation_result , arguments )
elif compilation_result . language == GREMLIN_LANGUAGE :
return insert_arguments_into_gremlin_query ... |
def find_by_client ( cls , from_client , limit = None , before_time = None , before_message_id = None ) : # type : ( str , Optional [ int ] , Optional [ Union [ datetime , float ] ] , Optional [ str ] ) - > List [ Message ]
"""获取某个 client 的聊天记录
: param from _ client : 要获取聊天记录的 client id
: param limit : 返回条数限制 ,... | query_params = { }
# type : Dict [ str , Any ]
query_params [ 'from' ] = from_client
if limit is not None :
query_params [ 'limit' ] = limit
if isinstance ( before_time , datetime ) :
query_params [ 'max_ts' ] = round ( before_time . timestamp ( ) * 1000 )
elif isinstance ( before_time , six . integer_types ) o... |
def getlanguage ( self , language = None , windowsversion = None ) :
"""Get and return the manifest ' s language as string .
Can be either language - culture e . g . ' en - us ' or a string indicating
language neutrality , e . g . ' x - ww ' on Windows XP or ' none ' on Vista
and later .""" | if not language :
language = self . language
if language in ( None , "" , "*" , "neutral" ) :
return ( LANGUAGE_NEUTRAL_NT5 , LANGUAGE_NEUTRAL_NT6 ) [ ( windowsversion or sys . getwindowsversion ( ) ) >= ( 6 , ) ]
return language |
def checkout ( cwd , rev = None , force = False , opts = '' , git_opts = '' , user = None , password = None , ignore_retcode = False , output_encoding = None ) :
'''Interface to ` git - checkout ( 1 ) ` _
cwd
The path to the git checkout
opts
Any additional options to add to the command line , in a single s... | cwd = _expand_path ( cwd , user )
command = [ 'git' ] + _format_git_opts ( git_opts )
command . append ( 'checkout' )
if force :
command . append ( '--force' )
opts = _format_opts ( opts )
command . extend ( opts )
checkout_branch = any ( x in opts for x in ( '-b' , '-B' ) )
if rev is None :
if not checkout_bra... |
def _build_effective_configuration ( self ) :
"""It might happen that the current value of one ( or more ) below parameters stored in
the controldata is higher than the value stored in the global cluster configuration .
Example : max _ connections in global configuration is 100 , but in controldata
` Current ... | OPTIONS_MAPPING = { 'max_connections' : 'max_connections setting' , 'max_prepared_transactions' : 'max_prepared_xacts setting' , 'max_locks_per_transaction' : 'max_locks_per_xact setting' }
if self . _major_version >= 90400 :
OPTIONS_MAPPING [ 'max_worker_processes' ] = 'max_worker_processes setting'
data = self . ... |
def aspage ( self ) :
"""Return TiffPage from file .""" | if self . offset is None :
raise ValueError ( 'cannot return virtual frame as page.' )
self . parent . filehandle . seek ( self . offset )
return TiffPage ( self . parent , index = self . index ) |
def from_dict ( cls , pref , prefix = None ) :
"""Create a Prefix object from a dict .
Suitable for creating Prefix objects from XML - RPC input .""" | if prefix is None :
prefix = Prefix ( )
prefix . id = pref [ 'id' ]
if pref [ 'vrf_id' ] is not None : # VRF is not mandatory
prefix . vrf = VRF . get ( pref [ 'vrf_id' ] )
prefix . family = pref [ 'family' ]
prefix . prefix = pref [ 'prefix' ]
prefix . display_prefix = pref [ 'display_prefix' ]
prefix . descri... |
def get_today_all ( output = 'pd' ) :
"""today all
Returns :
[ type ] - - [ description ]""" | data = [ ]
today = str ( datetime . date . today ( ) )
codes = QA_fetch_get_stock_list ( 'stock' ) . code . tolist ( )
bestip = select_best_ip ( ) [ 'stock' ]
for code in codes :
try :
l = QA_fetch_get_stock_day ( code , today , today , '00' , ip = bestip )
except :
bestip = select_best_ip ( ) [... |
def get_css ( self ) :
"""Fetches and returns stylesheet file path or contents , for both
print and screen contexts , depending if we want a standalone
presentation or not .""" | css = { }
print_css = os . path . join ( self . theme_dir , 'css' , 'print.css' )
if not os . path . exists ( print_css ) : # Fall back to default theme
print_css = os . path . join ( THEMES_DIR , 'default' , 'css' , 'print.css' )
if not os . path . exists ( print_css ) :
raise IOError ( u"Cannot find c... |
def _status ( self ) :
"""Return html saying whether this Action is reverted by another
one or reverts another one .""" | text = ""
# Turns out that is related field in null , Django
# doesn ' t even make it a property of the object
# http : / / code . djangoproject . com / ticket / 11920
if hasattr ( self , "reverts" ) :
text += '(reverts <a href="%s">%s</a>)<br/>' % ( self . reverts . get_absolute_url ( ) , self . reverts . id )
if ... |
def comments_2 ( self , value = None ) :
"""Corresponds to IDD Field ` comments _ 2 `
Args :
value ( str ) : value for IDD Field ` comments _ 2 `
if ` value ` is None it will not be checked against the
specification and is assumed to be a missing value
Raises :
ValueError : if ` value ` is not a valid v... | if value is not None :
try :
value = str ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type str ' 'for field `comments_2`' . format ( value ) )
if ',' in value :
raise ValueError ( 'value should not contain a comma ' 'for field `comments_2`' )
self . _comme... |
def generate_cart_upload_redirect_url ( self , ** kwargs ) :
"""https : / / www . sandbox . paypal . com / webscr
? cmd = _ cart
& upload = 1""" | required_vals = ( 'business' , 'item_name_1' , 'amount_1' , 'quantity_1' )
self . _check_required ( required_vals , ** kwargs )
url = "%s?cmd=_cart&upload=1" % self . config . PAYPAL_URL_BASE
additional = self . _encode_utf8 ( ** kwargs )
additional = urlencode ( additional )
return url + "&" + additional |
def _move_cursor_to_line ( self , line ) :
"""Moves the cursor to the specified line , if possible .""" | last_line = self . _text_edit . document ( ) . blockCount ( ) - 1
self . _cursor . clearSelection ( )
self . _cursor . movePosition ( self . _cursor . End )
to_insert = ''
for i in range ( line - last_line ) :
to_insert += '\n'
if to_insert :
self . _cursor . insertText ( to_insert )
self . _cursor . movePositi... |
def handling_exceptions ( self ) :
"""Perform proper exception handling .""" | try :
if self . using_jobs :
with handling_broken_process_pool ( ) :
yield
else :
yield
except SystemExit as err :
self . register_error ( err . code )
except BaseException as err :
if isinstance ( err , CoconutException ) :
logger . display_exc ( )
elif not isins... |
def add_log_file ( logger , log_file , global_log_file = False ) :
"""Add a log file to this logger . If global _ log _ file is true , log _ file will be handed the root logger , otherwise it will only be used by this particular logger .
Parameters
logger : obj : ` logging . Logger `
The logger .
log _ file... | if global_log_file :
add_root_log_file ( log_file )
else :
hdlr = logging . FileHandler ( log_file )
formatter = logging . Formatter ( '%(asctime)s %(name)-10s %(levelname)-8s %(message)s' , datefmt = '%m-%d %H:%M:%S' )
hdlr . setFormatter ( formatter )
logger . addHandler ( hdlr ) |
def flush ( self , key = None ) :
"""Flush the cache .
If I { key } is specified , only that item is flushed . Otherwise
the entire cache is flushed .
@ param key : the key to flush
@ type key : ( dns . name . Name , int , int ) tuple or None""" | if not key is None :
if key in self . data :
del self . data [ key ]
else :
self . data = { }
self . next_cleaning = time . time ( ) + self . cleaning_interval |
def Convert ( self , metadata , conn , token = None ) :
"""Converts NetworkConnection to ExportedNetworkConnection .""" | result = ExportedNetworkConnection ( metadata = metadata , family = conn . family , type = conn . type , local_address = conn . local_address , remote_address = conn . remote_address , state = conn . state , pid = conn . pid , ctime = conn . ctime )
return [ result ] |
def frompil ( cls , image , compression = Compression . PACK_BITS ) :
"""Create a new PSD document from PIL Image .
: param image : PIL Image object .
: param compression : ImageData compression option . See
: py : class : ` ~ psd _ tools . constants . Compression ` .
: return : A : py : class : ` ~ psd _ t... | header = cls . _make_header ( image . mode , image . size )
# TODO : Add default metadata .
# TODO : Perhaps make this smart object .
image_data = ImageData ( compression = compression )
image_data . set_data ( [ channel . tobytes ( ) for channel in image . split ( ) ] , header )
return cls ( PSD ( header = header , im... |
def forwards ( self , orm ) :
"Write your forwards methods here ." | for doc in orm [ 'document_library.Document' ] . objects . all ( ) :
for title in doc . documenttitle_set . all ( ) :
title . is_published = doc . is_published
title . save ( ) |
def update ( self , activity_sid = values . unset , attributes = values . unset , friendly_name = values . unset , reject_pending_reservations = values . unset ) :
"""Update the WorkerInstance
: param unicode activity _ sid : The activity _ sid
: param unicode attributes : The attributes
: param unicode frien... | return self . _proxy . update ( activity_sid = activity_sid , attributes = attributes , friendly_name = friendly_name , reject_pending_reservations = reject_pending_reservations , ) |
def setFontUnderline ( self , state ) :
"""Sets whether or not this editor is currently in underline state .
: param state | < bool >""" | font = self . currentFont ( )
font . setUnderline ( state )
self . setCurrentFont ( font ) |
def config_find_lines ( regex , source = 'running' ) :
r'''. . versionadded : : 2019.2.0
Return the configuration lines that match the regular expressions from the
` ` regex ` ` argument . The configuration is read from the network device
interrogated .
regex
The regular expression to match the configurat... | config_txt = __salt__ [ 'net.config' ] ( source = source ) [ 'out' ] [ source ]
return __salt__ [ 'ciscoconfparse.find_lines' ] ( config = config_txt , regex = regex ) |
def compare_vectorized ( self , comp_func , labels_left , labels_right , * args , ** kwargs ) :
"""Compute the similarity between values with a callable .
This method initialises the comparing of values with a custom
function / callable . The function / callable should accept
numpy . ndarray ' s .
Example
... | label = kwargs . pop ( 'label' , None )
if isinstance ( labels_left , tuple ) :
labels_left = list ( labels_left )
if isinstance ( labels_right , tuple ) :
labels_right = list ( labels_right )
feature = BaseCompareFeature ( labels_left , labels_right , args , kwargs , label = label )
feature . _f_compare_vector... |
def set_logging_settings ( profile , setting , value , store = 'local' ) :
'''Configure logging settings for the Windows firewall .
Args :
profile ( str ) :
The firewall profile to configure . Valid options are :
- domain
- public
- private
setting ( str ) :
The logging setting to configure . Valid ... | # Input validation
if profile . lower ( ) not in ( 'domain' , 'public' , 'private' ) :
raise ValueError ( 'Incorrect profile: {0}' . format ( profile ) )
if setting . lower ( ) not in ( 'allowedconnections' , 'droppedconnections' , 'filename' , 'maxfilesize' ) :
raise ValueError ( 'Incorrect setting: {0}' . for... |
def get_version ( self , service_id , version_number ) :
"""Get the version for a particular service .""" | content = self . _fetch ( "/service/%s/version/%d" % ( service_id , version_number ) )
return FastlyVersion ( self , content ) |
def DumpArtifactsToYaml ( self , sort_by_os = True ) :
"""Dump a list of artifacts into a yaml string .""" | artifact_list = self . GetArtifacts ( )
if sort_by_os : # Sort so its easier to split these if necessary .
yaml_list = [ ]
done_set = set ( )
for os_name in rdf_artifacts . Artifact . SUPPORTED_OS_LIST :
done_set = set ( a for a in artifact_list if a . supported_os == [ os_name ] )
# Separat... |
def add_uppercase ( table ) :
"""Extend the table with uppercase options
> > > print ( " а " in add _ uppercase ( { " а " : " a " } ) )
True
> > > print ( add _ uppercase ( { " а " : " a " } ) [ " а " ] = = " a " )
True
> > > print ( " А " in add _ uppercase ( { " а " : " a " } ) )
True
> > > print ( ... | orig = table . copy ( )
orig . update ( dict ( ( k . capitalize ( ) , v . capitalize ( ) ) for k , v in table . items ( ) ) )
return orig |
def to_routing_header ( params ) :
"""Returns a routing header string for the given request parameters .
Args :
params ( Mapping [ str , Any ] ) : A dictionary containing the request
parameters used for routing .
Returns :
str : The routing header string .""" | if sys . version_info [ 0 ] < 3 : # Python 2 does not have the " safe " parameter for urlencode .
return urlencode ( params ) . replace ( "%2F" , "/" )
return urlencode ( params , # Per Google API policy ( go / api - url - encoding ) , / is not encoded .
safe = "/" , ) |
def align ( fastq_file , pair_file , index_dir , names , align_dir , data ) :
"""Perform piped alignment of fastq input files , generating sorted , deduplicated BAM .""" | umi_ext = "-cumi" if "umi_bam" in data else ""
out_file = os . path . join ( align_dir , "{0}-sort{1}.bam" . format ( dd . get_sample_name ( data ) , umi_ext ) )
num_cores = data [ "config" ] [ "algorithm" ] . get ( "num_cores" , 1 )
rg_info = novoalign . get_rg_info ( names )
preset = "sr"
pair_file = pair_file if pai... |
def block_uid ( value : Union [ str , BlockUID , None ] ) -> BlockUID :
"""Convert value to BlockUID instance
: param value : Value to convert
: return :""" | if isinstance ( value , BlockUID ) :
return value
elif isinstance ( value , str ) :
return BlockUID . from_str ( value )
elif value is None :
return BlockUID . empty ( )
else :
raise TypeError ( "Cannot convert {0} to BlockUID" . format ( type ( value ) ) ) |
def _build_table ( self ) -> Dict [ State , Tuple [ Multiplex , ... ] ] :
"""Private method which build the table which map a State to the active multiplex .""" | result : Dict [ State , Tuple [ Multiplex , ... ] ] = { }
for state in self . influence_graph . all_states ( ) :
result [ state ] = tuple ( multiplex for multiplex in self . influence_graph . multiplexes if multiplex . is_active ( state ) )
return result |
def simple ( self ) :
'''A string representation with only one period delimiter .''' | if self . _days :
return '%sD' % self . totaldays
elif self . months :
return '%sM' % self . _months
elif self . years :
return '%sY' % self . years
else :
return '' |
def add_category ( self , category ) :
"""Add a category assigned to this message
: rtype : Category""" | self . _categories = self . _ensure_append ( category , self . _categories ) |
def get_object_type_by_name ( object_type_name ) :
""": return : type suitable to handle the given object type name .
Use the type to create new instances .
: param object _ type _ name : Member of TYPES
: raise ValueError : In case object _ type _ name is unknown""" | if object_type_name == b"commit" :
from . import commit
return commit . Commit
elif object_type_name == b"tag" :
from . import tag
return tag . TagObject
elif object_type_name == b"blob" :
from . import blob
return blob . Blob
elif object_type_name == b"tree" :
from . import tree
return ... |
def iter_trees ( nexson , nexson_version = None ) :
"""generator over all trees in all trees elements .
yields a tuple of 3 items :
trees element ID ,
tree ID ,
the tree obj""" | if nexson_version is None :
nexson_version = detect_nexson_version ( nexson )
nex = get_nexml_el ( nexson )
if _is_by_id_hbf ( nexson_version ) :
trees_group_by_id = nex [ 'treesById' ]
group_order = nex . get ( '^ot:treesElementOrder' , [ ] )
if len ( group_order ) < len ( trees_group_by_id ) :
... |
def getContinuousSetByName ( self , name ) :
"""Returns the ContinuousSet with the specified name , or raises
an exception otherwise .""" | if name not in self . _continuousSetNameMap :
raise exceptions . ContinuousSetNameNotFoundException ( name )
return self . _continuousSetNameMap [ name ] |
def dump ( self , sender = None , ** kwargs ) :
'''Retrieve raw email dump for this bounce .
: param sender : A : class : ` BounceDump ` object to get dump with .
Defaults to ` None ` .
: param \ * \ * kwargs : Keyword arguments passed to
: func : ` requests . request ` .''' | if sender is None :
if self . _sender is None :
sender = _default_bounce_dump
else :
sender = BounceDump ( api_key = self . _sender . api_key , test = self . _sender . test , secure = self . _sender . secure )
return sender . get ( self . id , ** kwargs ) |
def get_nameid_data ( request , key = None ) :
"""Gets the NameID Data of the the Logout Request
: param request : Logout Request Message
: type request : string | DOMDocument
: param key : The SP key
: type key : string
: return : Name ID Data ( Value , Format , NameQualifier , SPNameQualifier )
: rtyp... | if isinstance ( request , etree . _Element ) :
elem = request
else :
if isinstance ( request , Document ) :
request = request . toxml ( )
elem = fromstring ( request , forbid_dtd = True )
name_id = None
encrypted_entries = OneLogin_Saml2_Utils . query ( elem , '/samlp:LogoutRequest/saml:EncryptedID'... |
def replace_multi ( self , keys , ttl = 0 , format = None , persist_to = 0 , replicate_to = 0 ) :
"""Replace multiple keys . Multi variant of : meth : ` replace `
. . seealso : : : meth : ` replace ` , : meth : ` upsert _ multi ` , : meth : ` upsert `""" | return _Base . replace_multi ( self , keys , ttl = ttl , format = format , persist_to = persist_to , replicate_to = replicate_to ) |
def cache ( opts , serial ) :
'''Returns the returner modules''' | return LazyLoader ( _module_dirs ( opts , 'cache' , 'cache' ) , opts , tag = 'cache' , pack = { '__opts__' : opts , '__context__' : { 'serial' : serial } } , ) |
def block_process_call ( self , address , register , value ) :
"""SMBus Block Write - Block Read Process Call
SMBus Block Write - Block Read Process Call was introduced in
Revision 2.0 of the specification .
This command selects a device register ( through the Comm byte ) , sends
1 to 31 bytes of data to it... | return self . smbus . block_process_call ( address , register , value ) |
def mkdir_command ( endpoint_plus_path ) :
"""Executor for ` globus mkdir `""" | endpoint_id , path = endpoint_plus_path
client = get_client ( )
autoactivate ( client , endpoint_id , if_expires_in = 60 )
res = client . operation_mkdir ( endpoint_id , path = path )
formatted_print ( res , text_format = FORMAT_TEXT_RAW , response_key = "message" ) |
def filter_attribute_value_assertions ( ava , attribute_restrictions = None ) :
"""Will weed out attribute values and values according to the
rules defined in the attribute restrictions . If filtering results in
an attribute without values , then the attribute is removed from the
assertion .
: param ava : T... | if not attribute_restrictions :
return ava
for attr , vals in list ( ava . items ( ) ) :
_attr = attr . lower ( )
try :
_rests = attribute_restrictions [ _attr ]
except KeyError :
del ava [ attr ]
else :
if _rests is None :
continue
if isinstance ( vals , ... |
def reflect_left ( self , value ) :
"""Only reflects the value if is > self .""" | if value > self :
value = self . reflect ( value )
return value |
def add_to_configs ( self , configs ) :
"""Add one or more measurement configurations to the stored
configurations
Parameters
configs : list or numpy . ndarray
list or array of configurations
Returns
configs : Kx4 numpy . ndarray
array holding all configurations of this instance""" | if len ( configs ) == 0 :
return None
if self . configs is None :
self . configs = np . atleast_2d ( configs )
else :
configs = np . atleast_2d ( configs )
self . configs = np . vstack ( ( self . configs , configs ) )
return self . configs |
def uses_base_tear_down ( cls ) :
"""Checks whether the tearDown method is the BasePlug implementation .""" | this_tear_down = getattr ( cls , 'tearDown' )
base_tear_down = getattr ( BasePlug , 'tearDown' )
return this_tear_down . __code__ is base_tear_down . __code__ |
def _message ( self , beacon_config , invert_hello = False ) :
"""Overridden : meth : ` . WBeaconGouverneurMessenger . _ message ` method . Appends encoded host group names
to requests and responses .
: param beacon _ config : beacon configuration
: return : bytes""" | m = WBeaconGouverneurMessenger . _message ( self , beacon_config , invert_hello = invert_hello )
hostgroups = self . _message_hostgroup_generate ( )
if len ( hostgroups ) > 0 :
m += ( WHostgroupBeaconMessenger . __message_groups_splitter__ + hostgroups )
return m |
def schedule ( self , recipients = None , sender = None , priority = None ) :
"""Schedules message for a delivery .
Puts message ( and dispatches if any ) data into DB .
: param list | None recipients : recipient ( or a list ) or None .
If ` None ` Dispatches should be created before send using ` prepare _ di... | if priority is None :
priority = self . priority
self . _message_model , self . _dispatch_models = Message . create ( self . get_alias ( ) , self . get_context ( ) , recipients = recipients , sender = sender , priority = priority )
return self . _message_model , self . _dispatch_models |
def _install_one ( repo_url , branch , destination , commit = '' , patches = None , exclude_modules = None , include_modules = None , base = False , work_directory = '' ) :
"""Install a third party odoo add - on
: param string repo _ url : url of the repo that contains the patch .
: param string branch : name o... | patches = patches or [ ]
patches = [ core . FilePatch ( file = patch [ 'file' ] , work_directory = work_directory ) if 'file' in patch else core . Patch ( ** patch ) for patch in patches ]
addon_cls = core . Base if base else core . Addon
addon = addon_cls ( repo_url , branch , commit = commit , patches = patches , exc... |
def csv_writer ( parser , keep , extract , args ) :
"""Writes the data in CSV format .""" | # The output
output = sys . stdout if args . output == "-" else open ( args . output , "w" )
try : # Getting the samples
samples = np . array ( parser . get_samples ( ) , dtype = str )
k = _get_sample_select ( samples = samples , keep = keep )
# Writing the CSV header
print ( "sample_id" , "variant_id" ... |
def build_includes ( cls , include_packages ) :
"""cx _ freeze doesn ' t support the star ( * ) method of sub - module inclusion , so all submodules must be included
explicitly .
Example ( From SaltStack 2014.7 ) :
salt
salt . fileserver
salt . fileserver . gitfs
salt . fileserver . hgfs
salt . filese... | includes , package_root_paths = cls . _split_packages ( include_packages )
for package_path , package_name in six . iteritems ( package_root_paths ) :
includes . add ( package_name )
if re . search ( r'__init__.py.*$' , package_path ) : # Looks like a package . Walk the directory and see if there are more .
... |
def _create_model_matrices ( self ) :
"""Creates model matrices / vectors
Returns
None ( changes model attributes )""" | self . model_Y = np . array ( self . data [ self . max_lag : self . data . shape [ 0 ] ] )
self . model_scores = np . zeros ( self . model_Y . shape [ 0 ] ) |
def dict_of_lists_add ( dictionary , key , value ) : # type : ( DictUpperBound , Any , Any ) - > None
"""Add value to a list in a dictionary by key
Args :
dictionary ( DictUpperBound ) : Dictionary to which to add values
key ( Any ) : Key within dictionary
value ( Any ) : Value to add to list in dictionary ... | list_objs = dictionary . get ( key , list ( ) )
list_objs . append ( value )
dictionary [ key ] = list_objs |
def convert ( json_input , build_direction = "LEFT_TO_RIGHT" , table_attributes = None ) :
"""Converts JSON to HTML Table format .
Parameters
json _ input : dict
JSON object to convert into HTML .
build _ direction : { " TOP _ TO _ BOTTOM " , " LEFT _ TO _ RIGHT " }
String denoting the build direction of ... | json_converter = JsonConverter ( build_direction = build_direction , table_attributes = table_attributes )
return json_converter . convert ( json_input ) |
def raise_error ( self , exception_type , # type : Type [ Exception ]
message # type : Text
) : # type : ( . . . ) - > NoReturn
"""Raise an exception with the current parser state information and error message .""" | error_message = '{} at {}' . format ( message , repr ( self ) )
raise exception_type ( error_message ) |
def list ( self , identity = values . unset , limit = None , page_size = None ) :
"""Lists MemberInstance records from the API as a list .
Unlike stream ( ) , this operation is eager and will load ` limit ` records into
memory before returning .
: param unicode identity : The ` identity ` value of the resourc... | return list ( self . stream ( identity = identity , limit = limit , page_size = page_size , ) ) |
def create_snappy_message ( payloads , key = None ) :
"""Construct a Snappy Message containing multiple Messages
The given payloads will be encoded , compressed , and sent as a single atomic
message to Kafka .
Arguments :
payloads : list ( bytes ) , a list of payload to send be sent to Kafka
key : bytes ,... | message_set = KafkaProtocol . _encode_message_set ( [ create_message ( payload , pl_key ) for payload , pl_key in payloads ] )
snapped = snappy_encode ( message_set )
codec = ATTRIBUTE_CODEC_MASK & CODEC_SNAPPY
return kafka . structs . Message ( 0 , 0x00 | codec , key , snapped ) |
def _direct_nbody_force ( q , m , t , pot , softening , softening_args ) :
"""Calculate the force""" | # First do the particles
# Calculate all the distances
nq = len ( q )
dim = len ( q [ 0 ] )
dist_vec = nu . zeros ( ( nq , nq , dim ) )
dist = nu . zeros ( ( nq , nq ) )
for ii in range ( nq ) :
for jj in range ( ii + 1 , nq ) :
dist_vec [ ii , jj , : ] = q [ jj ] - q [ ii ]
dist_vec [ jj , ii , : ]... |
def filenamify ( title ) :
"""Convert a string to something suitable as a file name . E . g .
Matlagning del 1 av 10 - Räksmörgås | SVT Play
- > matlagning . del . 1 . av . 10 . - . raksmorgas . svt . play""" | # ensure it is unicode
title = ensure_unicode ( title )
# NFD decomposes chars into base char and diacritical mark , which
# means that we will get base char when we strip out non - ascii .
title = unicodedata . normalize ( 'NFD' , title )
# Convert to lowercase
# Drop any non ascii letters / digits
# Drop any leading ... |
async def create ( cls , user_id : Union [ int , str ] , is_active : bool = True , is_admin : bool = False , resource_policy : str = None , rate_limit : int = None , fields : Iterable [ str ] = None ) -> dict :
'''Creates a new keypair with the given options .
You need an admin privilege for this operation .''' | if fields is None :
fields = ( 'access_key' , 'secret_key' )
uid_type = 'Int!' if isinstance ( user_id , int ) else 'String!'
q = 'mutation($user_id: {0}, $input: KeyPairInput!) {{' . format ( uid_type ) + ' create_keypair(user_id: $user_id, props: $input) {' ' ok msg keypair { $fields }' ' }' '}'
q = q . repl... |
def main ( args = None ) :
"""Build and run parser
: param args : cli args from tests""" | parser = argument_parser ( )
args = parser . parse_args ( args )
# If ' func ' isn ' t present , something is misconfigured above or no ( positional ) arg was given .
if not hasattr ( args , 'func' ) :
args = parser . parse_args ( [ 'help' ] )
# show help
# Convert argparse . Namespace into dict and clean it up .
#... |
def print ( self ) :
"""Print results table .
> > > Results ( [ ' title ' ] , [ ( ' Konosuba ' , ) , ( ' Oreimo ' , ) ] ) . print ( )
# title
1 Konosuba
2 Oreimo""" | print ( tabulate ( ( ( i , * row ) for i , row in enumerate ( self . results , 1 ) ) , headers = self . headers , ) ) |
def create_criteria ( cls , query ) :
"""Return a criteria from a dictionary containing a query .
Query should be a dictionary , keyed by field name . If the value is
a list , it will be divided into multiple criteria as required .""" | criteria = [ ]
for name , value in query . items ( ) :
if isinstance ( value , list ) :
for inner_value in value :
criteria += cls . create_criteria ( { name : inner_value } )
else :
criteria . append ( { 'criteria' : { 'field' : name , 'value' : value , } , } )
return criteria or No... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : FormContext for this FormInstance
: rtype : twilio . rest . authy . v1 . form . FormContext""" | if self . _context is None :
self . _context = FormContext ( self . _version , form_type = self . _solution [ 'form_type' ] , )
return self . _context |
def parent ( self ) :
"""A new URL with last part of path removed and cleaned up query and
fragment .""" | path = self . raw_path
if not path or path == "/" :
if self . raw_fragment or self . raw_query_string :
return URL ( self . _val . _replace ( query = "" , fragment = "" ) , encoded = True )
return self
parts = path . split ( "/" )
val = self . _val . _replace ( path = "/" . join ( parts [ : - 1 ] ) , qu... |
def partial_autocorrelation ( self , x , param = None ) :
"""As in tsfresh ` partial _ autocorrelation < https : / / github . com / blue - yonder / tsfresh / blob / master / tsfresh / feature _ extraction / feature _ calculators . py # L308 > ` _
Calculates the value of the partial autocorrelation function at the... | if param is None :
param = [ { 'lag' : 3 } , { 'lag' : 5 } , { 'lag' : 6 } ]
_partialc = feature_calculators . partial_autocorrelation ( x , param )
logging . debug ( "partial autocorrelation by tsfresh calculated" )
return _partialc |
def suffix ( args ) :
"""% prog suffix fastqfile CAG
Filter reads based on suffix .""" | p = OptionParser ( suffix . __doc__ )
p . set_outfile ( )
opts , args = p . parse_args ( args )
if len ( args ) != 2 :
sys . exit ( not p . print_help ( ) )
fastqfile , sf = args
fw = must_open ( opts . outfile , "w" )
nreads = nselected = 0
for rec in iter_fastq ( fastqfile ) :
nreads += 1
if rec is None :... |
def is_parseable ( self ) :
"""See if URL target is parseable for recursion .""" | if self . is_directory ( ) :
return True
if self . content_type in self . ContentMimetypes :
return True
log . debug ( LOG_CHECK , "URL with content type %r is not parseable." , self . content_type )
return False |
def _set_enhanced_voq_max_queue_depth ( self , v , load = False ) :
"""Setter method for enhanced _ voq _ max _ queue _ depth , mapped from YANG variable / telemetry / profile / enhanced _ voq _ max _ queue _ depth ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "name" , enhanced_voq_max_queue_depth . enhanced_voq_max_queue_depth , yang_name = "enhanced-voq-max-queue-depth" , rest_name = "enhanced-voq-max-queue-depth" , parent = self , is_container = 'list' , user_orde... |
def new ( cls , alias , cert ) :
"""Helper function to create a new TrustedCertEntry .
: param str alias : The alias for the Trusted Cert Entry
: param str certs : The certificate , as a byte string .
: returns : A loaded : class : ` TrustedCertEntry ` instance , ready
to be placed in a keystore .""" | timestamp = int ( time . time ( ) ) * 1000
tke = cls ( timestamp = timestamp , # Alias must be lower case or it will corrupt the keystore for Java Keytool and Keytool Explorer
alias = alias . lower ( ) , cert = cert )
return tke |
def getDefaultUncertainty ( self , result = None ) :
"""Return the uncertainty value , if the result falls within
specified ranges for the service from which this analysis was derived .""" | if result is None :
result = self . getResult ( )
uncertainties = self . getUncertainties ( )
if uncertainties :
try :
res = float ( result )
except ( TypeError , ValueError ) : # if analysis result is not a number , then we assume in range
return None
for d in uncertainties :
_m... |
def B3 ( formula ) :
"""Rewrite formula eval result into Boolean3
: param formula :
: return : Boolean3""" | if isinstance ( formula , true ) or formula is True or formula == Boolean3 . Top . name or formula == Boolean3 . Top . value :
return Boolean3 . Top
if isinstance ( formula , false ) or formula is False or formula == Boolean3 . Bottom . name or formula == Boolean3 . Bottom . value :
return Boolean3 . Bottom
els... |
def get_risk_models ( oqparam , kind = 'vulnerability vulnerability_retrofitted ' 'fragility consequence' ) :
""": param oqparam :
an OqParam instance
: param kind :
a space - separated string with the kinds of risk models to read
: returns :
a dictionary riskid - > loss _ type , kind - > function""" | kinds = kind . split ( )
rmodels = AccumDict ( )
for kind in kinds :
for key in sorted ( oqparam . inputs ) :
mo = re . match ( '(occupants|%s)_%s$' % ( COST_TYPE_REGEX , kind ) , key )
if mo :
loss_type = mo . group ( 1 )
# the cost _ type in the key
# can be occ... |
def select_with_index ( self , selector ) :
'''Transforms each element of a sequence into a new form , incorporating
the index of the element .
Each element is transformed through a selector function which accepts
the element value and its zero - based index in the source sequence . The
generated sequence i... | return self . _create ( self . _pool . imap_unordered ( star , zip ( itertools . repeat ( selector ) , enumerate ( iter ( self ) ) ) , self . _chunksize ) ) |
def to_wire_dict ( self ) :
"""Return a simplified transport object for logging and caching .
The transport object must contain these attributes :
- url _ data . valid : bool
Indicates if URL is valid
- url _ data . result : unicode
Result string
- url _ data . warnings : list of tuples ( tag , warning ... | return dict ( valid = self . valid , extern = self . extern [ 0 ] , result = self . result , warnings = self . warnings [ : ] , name = self . name or u"" , title = self . get_title ( ) , parent_url = self . parent_url or u"" , base_ref = self . base_ref or u"" , base_url = self . base_url or u"" , url = self . url or u... |
def set_LObj ( self , LObj = None ) :
"""Set the LObj attribute , storing objects the instance depends on
For example :
A Detect object depends on a vessel and some apertures
That link between should be stored somewhere ( for saving / loading ) .
LObj does this : it stores the ID ( as dict ) of all objects ... | self . _LObj = { }
if LObj is not None :
if type ( LObj ) is not list :
LObj = [ LObj ]
for ii in range ( 0 , len ( LObj ) ) :
if type ( LObj [ ii ] ) is ID :
LObj [ ii ] = LObj [ ii ] . _todict ( )
ClsU = list ( set ( [ oo [ 'Cls' ] for oo in LObj ] ) )
for c in ClsU :
... |
def _compute_next_evaluations ( self , pending_zipped_X = None , ignored_zipped_X = None ) :
"""Computes the location of the new evaluation ( optimizes the acquisition in the standard case ) .
: param pending _ zipped _ X : matrix of input configurations that are in a pending state ( i . e . , do not have an eval... | # # - - - Update the context if any
self . acquisition . optimizer . context_manager = ContextManager ( self . space , self . context )
# # # - - - Activate de _ duplication
if self . de_duplication :
duplicate_manager = DuplicateManager ( space = self . space , zipped_X = self . X , pending_zipped_X = pending_zipp... |
def dump ( destination , xs , model = None , properties = False , indent = True , ** kwargs ) :
"""Serialize Xmrs ( or subclass ) objects to PENMAN and write to a file .
Args :
destination : filename or file object
xs : iterator of : class : ` ~ delphin . mrs . xmrs . Xmrs ` objects to
serialize
model : X... | text = dumps ( xs , model = model , properties = properties , indent = indent , ** kwargs )
if hasattr ( destination , 'write' ) :
print ( text , file = destination )
else :
with open ( destination , 'w' ) as fh :
print ( text , file = fh ) |
def resolve_source_mapping ( source_directory : str , output_directory : str , sources : Sources ) -> Mapping [ str , str ] :
"""Returns a mapping from absolute source path to absolute output path as specified
by the sources object . Files are not guaranteed to exist .""" | result = { os . path . join ( source_directory , source_file ) : os . path . join ( output_directory , output_file ) for source_file , output_file in sources . files . items ( ) }
filesystem = get_filesystem ( )
for glob in sources . globs :
matches = filesystem . list ( source_directory , glob . patterns , exclude... |
def overlap ( self , max_hang = 100 ) :
"""Determine the type of overlap given query , ref alignment coordinates
Consider the following alignment between sequence a and b :
aLhang \ / aRhang
/ - - - - - bLhang / \ bRhang
Terminal overlap : a before b , b before a
Contain overlap : a in b , b in a""" | aL , aR = 1 , self . reflen
bL , bR = 1 , self . querylen
aLhang , aRhang = self . start1 - aL , aR - self . end1
bLhang , bRhang = self . start2 - bL , bR - self . end2
if self . orientation == '-' :
bLhang , bRhang = bRhang , bLhang
s1 = aLhang + bRhang
s2 = aRhang + bLhang
s3 = aLhang + aRhang
s4 = bLhang + bRha... |
def _handle_produce_response ( self , node_id , send_time , batches , response ) :
"""Handle a produce response .""" | # if we have a response , parse it
log . debug ( 'Parsing produce response: %r' , response )
if response :
batches_by_partition = dict ( [ ( batch . topic_partition , batch ) for batch in batches ] )
for topic , partitions in response . topics :
for partition_info in partitions :
if response... |
def h_v_t ( header , key ) :
"""get header value with title
try to get key from header and consider case sensitive
e . g . header [ ' x - log - abc ' ] or header [ ' X - Log - Abc ' ]
: param header :
: param key :
: return :""" | if key not in header :
key = key . title ( )
if key not in header :
raise ValueError ( "Unexpected header in response, missing: " + key + " headers:\n" + str ( header ) )
return header [ key ] |
def main ( ) :
"""NAME
angle . py
DESCRIPTION
calculates angle between two input directions D1 , D2
INPUT ( COMMAND LINE ENTRY )
D1 _ dec D1 _ inc D1 _ dec D2 _ inc
OUTPUT
angle
SYNTAX
angle . py [ - h ] [ - i ] [ command line options ] [ < filename ]
OPTIONS
- h prints help and quits
- i fo... | out = ""
if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-F' in sys . argv :
ind = sys . argv . index ( '-F' )
o = sys . argv [ ind + 1 ]
out = open ( o , 'w' )
if '-i' in sys . argv :
cont = 1
while cont == 1 :
dir1 , dir2 = [ ] , [ ]
try :
an... |
def softDeactivate ( rh ) :
"""Deactivate a virtual machine by first shutting down Linux and
then log it off .
Input :
Request Handle with the following properties :
function - ' POWERVM '
subfunction - ' SOFTOFF '
userid - userid of the virtual machine
parms [ ' maxQueries ' ] - Maximum number of que... | rh . printSysLog ( "Enter powerVM.softDeactivate, userid: " + rh . userid )
strCmd = "echo 'ping'"
iucvResults = execCmdThruIUCV ( rh , rh . userid , strCmd )
if iucvResults [ 'overallRC' ] == 0 : # We could talk to the machine , tell it to shutdown nicely .
strCmd = "shutdown -h now"
iucvResults = execCmdThruI... |
def get_n_cluster_in_events ( event_numbers ) :
'''Calculates the number of cluster in every given event .
An external C + + library is used since there is no sufficient solution in python possible .
Because of np . bincount # BUG # 225 for values > int32 and the different handling under 32/64 bit operating sys... | logging . debug ( "Calculate the number of cluster in every given event" )
event_numbers = np . ascontiguousarray ( event_numbers )
# change memory alignement for c + + library
result_event_numbers = np . empty_like ( event_numbers )
result_count = np . empty_like ( event_numbers , dtype = np . uint32 )
result_size = a... |
def train ( args , params ) :
'''Train model''' | x_train , y_train , x_test , y_test = load_mnist_data ( args )
model = create_mnist_model ( params )
# nni
model . fit ( x_train , y_train , batch_size = args . batch_size , epochs = args . epochs , verbose = 1 , validation_data = ( x_test , y_test ) , callbacks = [ SendMetrics ( ) , TensorBoard ( log_dir = TENSORBOARD... |
def build_instance_name ( inst , obj = None ) :
"""Return an instance name from an instance , and set instance . path""" | if obj is None :
for _ in inst . properties . values ( ) :
inst . path . keybindings . __setitem__ ( _ . name , _ . value )
return inst . path
if not isinstance ( obj , list ) :
return build_instance_name ( inst , get_keys_from_class ( obj ) )
keys = { }
for _ in obj :
if _ not in inst . propert... |
def reset_point_source_cache ( self , bool = True ) :
"""deletes all the cache in the point source class and saves it from then on
: return :""" | for imageModel in self . _imageModel_list :
imageModel . reset_point_source_cache ( bool = bool ) |
def main ( ) :
"""NAME
basemap _ magic . py
NB : this program no longer maintained - use plot _ map _ pts . py for greater functionality
DESCRIPTION
makes a map of locations in er _ sites . txt
SYNTAX
basemap _ magic . py [ command line options ]
OPTIONS
- h prints help message and quits
- f SFILE... | dir_path = '.'
sites_file = 'er_sites.txt'
ocean = 0
res = 'i'
proj = 'merc'
prn_name = 0
prn_loc = 0
fancy = 0
rivers , boundaries = 0 , 0
padlon , padlat , gridspace , details = .5 , .5 , .5 , 1
fmt = 'pdf'
if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-f' in sys . argv :
ind = sys .... |
def to_dict ( self ) :
'''Return a dict of the attributes .''' | return dict ( raw = self . raw , scheme = self . scheme , authority = self . authority , netloc = self . authority , path = self . path , query = self . query , fragment = self . fragment , userinfo = self . userinfo , username = self . username , password = self . password , host = self . host , hostname = self . host... |
def _make_unknown_name ( self , cursor ) :
'''Creates a name for unname type''' | parent = cursor . lexical_parent
pname = self . get_unique_name ( parent )
log . debug ( '_make_unknown_name: Got parent get_unique_name %s' , pname )
# we only look at types declarations
_cursor_decl = cursor . type . get_declaration ( )
# we had the field index from the parent record , as to differenciate
# between u... |
def get_embedded_object ( self , signature_id ) :
'''Retrieves a embedded signing object
Retrieves an embedded object containing a signature url that can be opened in an iFrame .
Args :
signature _ id ( str ) : The id of the signature to get a signature url for
Returns :
An Embedded object''' | request = self . _get_request ( )
return request . get ( self . EMBEDDED_OBJECT_GET_URL + signature_id ) |
def steal_page ( self , page ) :
"""Steal a page from another document""" | if page . doc == self :
return
self . fs . mkdir_p ( self . path )
new_page = ImgPage ( self , self . nb_pages )
logger . info ( "%s --> %s" % ( str ( page ) , str ( new_page ) ) )
new_page . _steal_content ( page ) |
def record ( self , action , props = None , path = KISSmetrics . RECORD_PATH , resp = False ) :
"""Record event for identity with any properties .
: param action : event performed
: param props : any additional data to include
: type props : dict
: param resp : indicate whether to return response
: type r... | self . check_id_key ( )
timestamp = None
if not props :
props = { }
response = self . client . record ( person = self . identity , event = action , properties = props , timestamp = timestamp , path = path )
if resp :
return response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.