signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
async def kickban ( self , channel , target , reason = None , range = 0 ) :
"""Kick and ban user from channel .""" | await self . ban ( channel , target , range )
await self . kick ( channel , target , reason ) |
def _check_once ( self ) :
"""A single attempt to call ismaster .
Returns a ServerDescription , or raises an exception .""" | address = self . _server_description . address
if self . _publish :
self . _listeners . publish_server_heartbeat_started ( address )
with self . _pool . get_socket ( { } ) as sock_info :
response , round_trip_time = self . _check_with_socket ( sock_info )
self . _avg_round_trip_time . add_sample ( round_tri... |
def check ( table = 'filter' , chain = None , rule = None , family = 'ipv4' ) :
'''Check for the existence of a rule in the table and chain
This function accepts a rule in a standard nftables command format ,
starting with the chain . Trying to force users to adapt to a new
method of creating rules would be i... | ret = { 'comment' : '' , 'result' : False }
if not chain :
ret [ 'comment' ] = 'Chain needs to be specified'
return ret
if not rule :
ret [ 'comment' ] = 'Rule needs to be specified'
return ret
res = check_table ( table , family = family )
if not res [ 'result' ] :
return res
res = check_chain ( tab... |
def list_npm_modules ( collector , no_print = False ) :
"""List the npm modules that get installed in a docker image for the react server""" | default = ReactServer ( ) . default_npm_deps ( )
for _ , module in sorted ( collector . configuration [ "__active_modules__" ] . items ( ) ) :
default . update ( module . npm_deps ( ) )
if not no_print :
print ( json . dumps ( default , indent = 4 , sort_keys = True ) )
return default |
def _JzStaeckelIntegrandSquared ( v , E , Lz , I3V , delta , u0 , cosh2u0 , sinh2u0 , potu0pi2 , pot ) : # potu0pi2 = potentialStaeckel ( u0 , nu . pi / 2 . , pot , delta )
"""The J _ z integrand : p _ v ( v ) / 2 / delta ^ 2""" | sin2v = nu . sin ( v ) ** 2.
dV = cosh2u0 * potu0pi2 - ( sinh2u0 + sin2v ) * potentialStaeckel ( u0 , v , pot , delta )
return E * sin2v + I3V + dV - Lz ** 2. / 2. / delta ** 2. / sin2v |
def CreateDefaultPartition ( client , ad_group_id ) :
"""Creates a default partition .
Args :
client : an AdWordsClient instance .
ad _ group _ id : an integer ID for an ad group .""" | ad_group_criterion_service = client . GetService ( 'AdGroupCriterionService' , version = 'v201809' )
operations = [ { 'operator' : 'ADD' , 'operand' : { 'xsi_type' : 'BiddableAdGroupCriterion' , 'adGroupId' : ad_group_id , # Make sure that caseValue and parentCriterionId are left unspecified .
# This makes this partiti... |
def get_themes ( urls ) :
'''takes in dict of names and urls , downloads and saves files''' | length = len ( urls )
counter = 1
widgets = [ 'Fetching themes:' , Percentage ( ) , ' ' , Bar ( marker = '-' ) , ' ' , ETA ( ) ]
pbar = ProgressBar ( widgets = widgets , maxval = length ) . start ( )
for i in urls . keys ( ) :
href = 'http://dotshare.it/dots/%s/0/raw/' % urls [ i ]
theme = urllib . urlopen ( hr... |
def update ( self , * args , ** kwargs ) :
"""Update the dictionary with the key / value pairs from * other * , overwriting
existing keys .
* update * accepts either another dictionary object or an iterable of
key / value pairs ( as a tuple or other iterable of length two ) . If
keyword arguments are specif... | if not self :
self . _dict_update ( * args , ** kwargs )
self . _list_update ( self . _iter ( ) )
return
if not kwargs and len ( args ) == 1 and isinstance ( args [ 0 ] , dict ) :
pairs = args [ 0 ]
else :
pairs = dict ( * args , ** kwargs )
if ( 10 * len ( pairs ) ) > len ( self ) :
self . _dic... |
def createProfile ( self , profile = None , clearLayout = True ) :
"""Prompts the user to create a new profile .""" | if profile :
prof = profile
elif not self . viewWidget ( ) or clearLayout :
prof = XViewProfile ( )
else :
prof = self . viewWidget ( ) . saveProfile ( )
blocked = self . signalsBlocked ( )
self . blockSignals ( False )
changed = self . editProfile ( prof )
self . blockSignals ( blocked )
if not changed :
... |
def runLateralDisambiguation ( noiseLevel = None , profile = False ) :
"""Runs a simple experiment where two objects share a ( location , feature ) pair .
At inference , one column sees that ambiguous pair , and the other sees a
unique one . We should see the first column rapidly converge to a
unique represen... | exp = L4L2Experiment ( "lateral_disambiguation" , numCorticalColumns = 2 , )
objects = createObjectMachine ( machineType = "simple" , numInputBits = 20 , sensorInputSize = 1024 , externalInputSize = 1024 , numCorticalColumns = 2 , )
objects . addObject ( [ ( 1 , 1 ) , ( 2 , 2 ) ] )
objects . addObject ( [ ( 1 , 1 ) , (... |
def get_location ( self , obj ) :
"""return user ' s location""" | if not obj . city and not obj . country :
return None
elif obj . city and obj . country :
return '%s, %s' % ( obj . city , obj . country )
elif obj . city or obj . country :
return obj . city or obj . country |
def role ( self , role_name ) :
"""Set role of current column
: param role _ name : name of the role to be selected .
: return :""" | field_name = self . name
field_roles = { field_name : MLField . translate_role_name ( role_name ) }
if field_roles :
return _change_singleton_roles ( self , field_roles , True )
else :
return self |
def _process_cascaded_category_contents ( records ) :
"""Travel from categories to subcontributions , flattening the whole event structure .
Yields everything that it finds ( except for elements whose protection has changed
but are not inheriting their protection settings from anywhere ) .
: param records : q... | category_prot_records = { rec . category_id for rec in records if rec . type == EntryType . category and rec . change == ChangeType . protection_changed }
category_move_records = { rec . category_id for rec in records if rec . type == EntryType . category and rec . change == ChangeType . moved }
changed_events = set ( ... |
def validate_config ( conf_dict ) :
"""Validate configuration .
: param conf _ dict : test configuration .
: type conf _ dict : { }
: raise InvalidConfigurationError :""" | # TASK improve validation
if APPLICATIONS not in conf_dict . keys ( ) :
raise InvalidConfigurationError ( 'Missing application configuration.' )
if SEED_FILES not in conf_dict . keys ( ) :
raise InvalidConfigurationError ( 'Missing seed file configuration.' )
if RUNS not in conf_dict . keys ( ) :
conf_dict ... |
def add_scan_alarm ( self , scan_id , host = '' , name = '' , value = '' , port = '' , test_id = '' , severity = '' , qod = '' ) :
"""Adds an alarm result to scan _ id scan .""" | self . scan_collection . add_result ( scan_id , ResultType . ALARM , host , name , value , port , test_id , severity , qod ) |
def next_object ( self ) :
"""Get next GridOut object from cursor .""" | grid_out = super ( self . __class__ , self ) . next_object ( )
if grid_out :
grid_out_class = create_class_with_framework ( AgnosticGridOut , self . _framework , self . __module__ )
return grid_out_class ( self . collection , delegate = grid_out )
else : # Exhausted .
return None |
def is_ancestor_of_bank ( self , id_ , bank_id ) :
"""Tests if an ` ` Id ` ` is an ancestor of a bank .
arg : id ( osid . id . Id ) : an ` ` Id ` `
arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of a bank
return : ( boolean ) - ` ` true ` ` if this ` ` id ` ` is an ancestor of
` ` bank _ id , ` ` ` ` f... | # Implemented from template for
# osid . resource . BinHierarchySession . is _ ancestor _ of _ bin
if self . _catalog_session is not None :
return self . _catalog_session . is_ancestor_of_catalog ( id_ = id_ , catalog_id = bank_id )
return self . _hierarchy_session . is_ancestor ( id_ = id_ , ancestor_id = bank_id ... |
def setxattr ( self , req , ino , name , value , flags ) :
"""Set an extended attribute
Valid replies :
reply _ err""" | self . reply_err ( req , errno . ENOSYS ) |
def refresh_menu ( self ) :
"""Refresh context menu""" | index = self . currentIndex ( )
condition = index . isValid ( )
self . edit_action . setEnabled ( condition )
self . remove_action . setEnabled ( condition )
self . refresh_plot_entries ( index ) |
def set_cell ( self , column_family_id , column , value , timestamp = None ) :
"""Sets a value in this row .
The cell is determined by the ` ` row _ key ` ` of this : class : ` DirectRow `
and the ` ` column ` ` . The ` ` column ` ` must be in an existing
: class : ` . ColumnFamily ` ( as determined by ` ` co... | self . _set_cell ( column_family_id , column , value , timestamp = timestamp , state = None ) |
def temperature_data_from_csv ( filepath_or_buffer , tz = None , date_col = "dt" , temp_col = "tempF" , gzipped = False , freq = None , ** kwargs ) :
"""Load temperature data from a CSV file .
Default format : :
dt , tempF
2017-01-01T00:00:00 + 00:00,21
2017-01-01T01:00:00 + 00:00,22.5
2017-01-01T02:00:00... | read_csv_kwargs = { "usecols" : [ date_col , temp_col ] , "dtype" : { temp_col : np . float64 } , "parse_dates" : [ date_col ] , "index_col" : date_col , }
if gzipped :
read_csv_kwargs . update ( { "compression" : "gzip" } )
# allow passing extra kwargs
read_csv_kwargs . update ( kwargs )
if tz is None :
tz = "... |
def disconnect ( self , name = None ) :
"""Clear internal Channel cache , allowing currently unused channels to be implictly closed .
: param str name : None , to clear the entire cache , or a name string to clear only a certain entry .""" | if name is None :
self . _channels = { }
else :
self . _channels . pop ( name )
if self . _ctxt is not None :
self . _ctxt . disconnect ( name ) |
def addSubEditor ( self , subEditor , isFocusProxy = False ) :
"""Adds a sub editor to the layout ( at the right but before the reset button )
Will add the necessary event filter to handle tabs and sets the strong focus so
that events will not propagate to the tree view .
If isFocusProxy is True the sub edito... | self . hBoxLayout . insertWidget ( len ( self . _subEditors ) , subEditor )
self . _subEditors . append ( subEditor )
subEditor . installEventFilter ( self )
subEditor . setFocusPolicy ( Qt . StrongFocus )
if isFocusProxy :
self . setFocusProxy ( subEditor )
return subEditor |
def xpathNextChild ( self , cur ) :
"""Traversal function for the " child " direction The child axis
contains the children of the context node in document order .""" | if cur is None :
cur__o = None
else :
cur__o = cur . _o
ret = libxml2mod . xmlXPathNextChild ( self . _o , cur__o )
if ret is None :
raise xpathError ( 'xmlXPathNextChild() failed' )
__tmp = xmlNode ( _obj = ret )
return __tmp |
def import_data_from_uris ( self , source_uris , dataset , table , schema = None , job = None , source_format = None , create_disposition = None , write_disposition = None , encoding = None , ignore_unknown_values = None , max_bad_records = None , allow_jagged_rows = None , allow_quoted_newlines = None , field_delimite... | source_uris = source_uris if isinstance ( source_uris , list ) else [ source_uris ]
project_id = self . _get_project_id ( project_id )
configuration = { "destinationTable" : { "projectId" : project_id , "tableId" : table , "datasetId" : dataset } , "sourceUris" : source_uris , }
if max_bad_records :
configuration [... |
def text ( self ) :
"""Get value of output stream ( StringIO ) .""" | if self . out :
self . out . close ( )
# pragma : nocover
return self . fp . getvalue ( ) |
def get_wikidata_qnum ( wikiarticle , wikisite ) :
"""Retrieve the Query number for a wikidata database of metadata about a particular article
> > > print ( get _ wikidata _ qnum ( wikiarticle = " Andromeda Galaxy " , wikisite = " enwiki " ) )
Q2469""" | resp = requests . get ( 'https://www.wikidata.org/w/api.php' , timeout = 5 , params = { 'action' : 'wbgetentities' , 'titles' : wikiarticle , 'sites' : wikisite , 'props' : '' , 'format' : 'json' } ) . json ( )
return list ( resp [ 'entities' ] ) [ 0 ] |
def disconnect ( self ) :
"""Disconnect from the device that we are currently connected to .""" | if not self . connected :
raise HardwareError ( "Cannot disconnect when we are not connected" )
# Close the streaming and tracing interfaces when we disconnect
self . _reports = None
self . _traces = None
self . _loop . run_coroutine ( self . adapter . disconnect ( 0 ) )
self . connected = False
self . connection_i... |
def build_elastic_query ( doc ) :
"""Build a query which follows ElasticSearch syntax from doc .
1 . Converts { " q " : " cricket " } to the below elastic query : :
" query " : {
" filtered " : {
" query " : {
" query _ string " : {
" query " : " cricket " ,
" lenient " : false ,
" default _ operato... | elastic_query , filters = { "query" : { "filtered" : { } } } , [ ]
for key in doc . keys ( ) :
if key == 'q' :
elastic_query [ 'query' ] [ 'filtered' ] [ 'query' ] = _build_query_string ( doc [ 'q' ] )
else :
_value = doc [ key ]
filters . append ( { "terms" : { key : _value } } if isins... |
async def dict ( self , full ) :
'''Open a HiveDict at the given full path .''' | node = await self . open ( full )
return await HiveDict . anit ( self , node ) |
def _is_declaration ( self , name , value ) :
"""Determines if a class attribute is a field value declaration .
Based on the name and value of the class attribute , return ` ` True ` ` if
it looks like a declaration of a default field value , ` ` False ` ` if it
is private ( name starts with ' _ ' ) or a clas... | if isinstance ( value , ( classmethod , staticmethod ) ) :
return False
elif enums . get_builder_phase ( value ) : # All objects with a defined ' builder phase ' are declarations .
return True
return not name . startswith ( "_" ) |
def register ( class_ = None , ** kwargs ) :
"""Registers a dataset with segment specific hyperparameters .
When passing keyword arguments to ` register ` , they are checked to be valid
keyword arguments for the registered Dataset class constructor and are
saved in the registry . Registered keyword arguments ... | def _real_register ( class_ ) : # Assert that the passed kwargs are meaningful
for kwarg_name , values in kwargs . items ( ) :
try :
real_args = inspect . getfullargspec ( class_ ) . args
except AttributeError : # pylint : disable = deprecated - method
real_args = inspect . g... |
def _group_changes ( cur , wanted , remove = False ) :
'''Determine if the groups need to be changed''' | old = set ( cur )
new = set ( wanted )
if ( remove and old != new ) or ( not remove and not new . issubset ( old ) ) :
return True
return False |
def get_objective_query_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the objective query service .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . learning . ObjectiveQuerySession ) - an
` ` ObjectiveQuerySession ` `
raise : NullArgument - ` ` proxy ` ` is ` ` ... | if not self . supports_objective_query ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . ObjectiveQuerySession ( proxy = proxy , runtime = self . _runtime ) |
def search ( self ) :
"""Search srt in project for cells matching list of terms .""" | matches = [ ]
for pattern in Config . patterns :
matches += self . termfinder ( pattern )
return sorted ( set ( matches ) , key = int ) |
def failUnlessWarns ( self , category , message , filename , f , * args , ** kwargs ) :
"""Fail if the given function doesn ' t generate the specified warning when
called . It calls the function , checks the warning , and forwards the
result of the function if everything is fine .
@ param category : the categ... | warningsShown = [ ]
def warnExplicit ( * args ) :
warningsShown . append ( args )
origExplicit = warnings . warn_explicit
try :
warnings . warn_explicit = warnExplicit
result = f ( * args , ** kwargs )
finally :
warnings . warn_explicit = origExplicit
if not warningsShown :
self . fail ( "No warning... |
def clean_expired_tokens ( opts ) :
'''Clean expired tokens from the master''' | loadauth = salt . auth . LoadAuth ( opts )
for tok in loadauth . list_tokens ( ) :
token_data = loadauth . get_tok ( tok )
if 'expire' not in token_data or token_data . get ( 'expire' , 0 ) < time . time ( ) :
loadauth . rm_token ( tok ) |
def log ( self , msg , level = "info" ) :
"""log this information to syslog or user provided logfile .""" | if not self . config . get ( "log_file" ) : # If level was given as a str then convert to actual level
level = LOG_LEVELS . get ( level , level )
syslog ( level , u"{}" . format ( msg ) )
else : # Binary mode so fs encoding setting is not an issue
with open ( self . config [ "log_file" ] , "ab" ) as f :
... |
def body ( self , data , data_type , ** kwargs ) :
"""Serialize data intended for a request body .
: param data : The data to be serialized .
: param str data _ type : The type to be serialized from .
: rtype : dict
: raises : SerializationError if serialization fails .
: raises : ValueError if data is No... | if data is None :
raise ValidationError ( "required" , "body" , True )
# Just in case this is a dict
internal_data_type = data_type . strip ( '[]{}' )
internal_data_type = self . dependencies . get ( internal_data_type , None )
if internal_data_type and not isinstance ( internal_data_type , Enum ) :
try :
... |
def get_instances ( self ) :
"""Returns a list of the instances of all the configured nodes .""" | return [ c . get ( 'instance' ) for c in self . runtime . _nodes . values ( ) if c . get ( 'instance' ) ] |
def _load ( self ) :
"""Function to collect reference data and connect it to the instance as
attributes .
Internal function , does not usually need to be called by the user , as
it is called automatically when an attribute is requested .
: return None""" | data = get_data ( self . endpoint , self . id_ , force_lookup = self . __force_lookup )
# Make our custom objects from the data .
for key , val in data . items ( ) :
if key == 'location_area_encounters' and self . endpoint == 'pokemon' :
params = val . split ( '/' ) [ - 3 : ]
ep , id_ , subr = param... |
def refreshResults ( self ) :
"""Joins together the queries from the fixed system , the search , and the
query builder to generate a query for the browser to display .""" | if ( self . currentMode ( ) == XOrbBrowserWidget . Mode . Detail ) :
self . refreshDetails ( )
elif ( self . currentMode ( ) == XOrbBrowserWidget . Mode . Card ) :
self . refreshCards ( )
else :
self . refreshThumbnails ( ) |
def subset_vcf ( in_file , region , out_file , config ) :
"""Subset VCF in the given region , handling bgzip and indexing of input .""" | work_file = vcfutils . bgzip_and_index ( in_file , config )
if not file_exists ( out_file ) :
with file_transaction ( config , out_file ) as tx_out_file :
bcftools = config_utils . get_program ( "bcftools" , config )
region_str = bamprep . region_to_gatk ( region )
cmd = "{bcftools} view -r ... |
def process_event ( self , event ) :
"""User input for the main map view .""" | if isinstance ( event , KeyboardEvent ) :
if event . key_code in [ Screen . ctrl ( "m" ) , Screen . ctrl ( "j" ) ] :
self . _scene . add_effect ( EnterLocation ( self . _screen , self . _longitude , self . _latitude , self . _on_new_location ) )
elif event . key_code in [ ord ( 'q' ) , ord ( 'Q' ) , Scr... |
def wait_for_parent_image_build ( self , nvr ) :
"""Given image NVR , wait for the build that produced it to show up in koji .
If it doesn ' t within the timeout , raise an error .
: return build info dict with ' nvr ' and ' id ' keys""" | self . log . info ( 'Waiting for Koji build for parent image %s' , nvr )
poll_start = time . time ( )
while time . time ( ) - poll_start < self . poll_timeout :
build = self . koji_session . getBuild ( nvr )
if build :
self . log . info ( 'Parent image Koji build found with id %s' , build . get ( 'id' )... |
def to_native_types ( self , slicer = None , na_rep = None , date_format = None , quoting = None , ** kwargs ) :
"""convert to our native types format , slicing if desired""" | values = self . values
i8values = self . values . view ( 'i8' )
if slicer is not None :
values = values [ ... , slicer ]
i8values = i8values [ ... , slicer ]
from pandas . io . formats . format import _get_format_datetime64_from_values
fmt = _get_format_datetime64_from_values ( values , date_format )
result = t... |
def optimize_layout_handler ( rule , handler ) :
"""Produce an " optimized " version of handler for the dispatcher to
limit reference lookups .""" | def runner ( walk , dispatcher , node ) :
yield LayoutChunk ( rule , handler , node )
return runner |
def _comparator_lt ( filter_value , tested_value ) :
"""Tests if the filter value is strictly greater than the tested value
tested _ value < filter _ value""" | if is_string ( filter_value ) :
value_type = type ( tested_value )
try : # Try a conversion
filter_value = value_type ( filter_value )
except ( TypeError , ValueError ) :
if value_type is int : # Integer / float comparison trick
try :
filter_value = float ( filter... |
def __stream_request ( self , method , url , request_args , headers = None ) :
"""_ _ stream _ request .
make a ' stream ' request . This method is called by
the ' request ' method after it has determined which
call applies : regular or streaming .""" | headers = headers if headers else { }
response = self . __request ( method , url , request_args , headers = headers , stream = True )
lines = response . iter_lines ( ITER_LINES_CHUNKSIZE )
for line in lines :
if line :
data = json . loads ( line . decode ( "utf-8" ) )
yield data |
def render_string ( self , template_name , ** kwargs ) :
"""This method was rewritten to support multiple template engine
( Determine by ` TEMPLATE _ ENGINE ` setting , could be ` tornado ` and ` jinja2 ` ) ,
it will only affect on template rendering process , ui modules feature ,
which is mostly exposed in `... | if 'tornado' == settings [ 'TEMPLATE_ENGINE' ] :
return super ( BaseHandler , self ) . render_string ( template_name , ** kwargs )
elif 'jinja2' == settings [ 'TEMPLATE_ENGINE' ] :
return jinja2_render ( template_name , ** kwargs )
else :
raise errors . SettingsError ( '%s is not a supported TEMPLATE_ENGINE... |
def _is_json_serialized_jws ( self , json_jws ) :
"""Check if we ' ve got a JSON serialized signed JWT .
: param json _ jws : The message
: return : True / False""" | json_ser_keys = { "payload" , "signatures" }
flattened_json_ser_keys = { "payload" , "signature" }
if not json_ser_keys . issubset ( json_jws . keys ( ) ) and not flattened_json_ser_keys . issubset ( json_jws . keys ( ) ) :
return False
return True |
def _fetch ( self ) :
"""Internal helper that fetches the ring from Redis , including only active
nodes / replicas . Returns a list of tuples ( start , replica ) ( see
_ fetch _ all docs for more details ) .""" | now = time . time ( )
expiry_time = now - NODE_TIMEOUT
data = self . conn . zrangebyscore ( self . key , expiry_time , 'INF' )
ring = [ ]
for node_data in data :
start , replica = node_data . decode ( ) . split ( ':' , 1 )
ring . append ( ( int ( start ) , replica ) )
ring = sorted ( ring , key = operator . ite... |
def run ( self , statement , parameters = None , ** kwparameters ) :
"""Run a Cypher statement within the context of this transaction .
The statement is sent to the server lazily , when its result is
consumed . To force the statement to be sent to the server , use
the : meth : ` . Transaction . sync ` method ... | self . _assert_open ( )
return self . session . run ( statement , parameters , ** kwparameters ) |
def get ( self , run_id ) :
"""Get a single run from the database .
: param run _ id : The ID of the run .
: return : The whole object from the database .
: raise NotFoundError when not found""" | id = self . _parse_id ( run_id )
run = self . generic_dao . find_record ( self . collection_name , { "_id" : id } )
if run is None :
raise NotFoundError ( "Run %s not found." % run_id )
return run |
def _adjust_rowcol ( self , insertion_point , no_to_insert , axis , tab = None ) :
"""Adjusts row and column sizes on insertion / deletion""" | if axis == 2 :
self . _shift_rowcol ( insertion_point , no_to_insert )
return
assert axis in ( 0 , 1 )
cell_sizes = self . col_widths if axis else self . row_heights
set_cell_size = self . set_col_width if axis else self . set_row_height
new_sizes = { }
del_sizes = [ ]
for pos , table in cell_sizes :
if pos... |
def reset ( self ) :
"""Resets the environment , and returns the state .
If it is a single agent environment , it returns that state for that agent . Otherwise , it returns a dict from
agent name to state .
Returns :
tuple or dict : For single agent environment , returns the same as ` step ` .
For multi -... | self . _reset_ptr [ 0 ] = True
self . _commands . clear ( )
for _ in range ( self . _pre_start_steps + 1 ) :
self . tick ( )
return self . _default_state_fn ( ) |
def edit ( cls , record , parent = None , uifile = '' , commit = True ) :
"""Prompts the user to edit the inputed record .
: param record | < orb . Table >
parent | < QWidget >
: return < bool > | accepted""" | # create the dialog
dlg = QDialog ( parent )
dlg . setWindowTitle ( 'Edit %s' % record . schema ( ) . name ( ) )
# create the widget
cls = record . schema ( ) . property ( 'widgetClass' , cls )
widget = cls ( dlg )
if ( uifile ) :
widget . setUiFile ( uifile )
widget . setRecord ( record )
widget . layout ( ) . set... |
def do_check_pep8 ( files , status ) :
"""Run the python pep8 tool against the filst of supplied files .
Append any linting errors to the returned status list
Args :
files ( str ) : list of files to run pep8 against
status ( list ) : list of pre - receive check failures to eventually print
to the user
R... | for file_name in files :
args = [ 'flake8' , '--max-line-length=120' , '{0}' . format ( file_name ) ]
output = run ( * args )
if output :
status . append ( "Python PEP8/Flake8: {0}: {1}" . format ( file_name , output ) )
return status |
def is_url ( path ) :
"""Test if path represents a valid URL .
: param str path : Path to file .
: return : True if path is valid url string , False otherwise .
: rtype : : py : obj : ` True ` or : py : obj : ` False `""" | try :
parse_result = urlparse ( path )
return all ( ( parse_result . scheme , parse_result . netloc , parse_result . path ) )
except ValueError :
return False |
def group_min ( groups , data ) :
"""Given a list of groups , find the minimum element of data within each group
Parameters
groups : ( n , ) sequence of ( q , ) int
Indexes of each group corresponding to each element in data
data : ( m , )
The data that groups indexes reference
Returns
minimums : ( n ... | # sort with major key groups , minor key data
order = np . lexsort ( ( data , groups ) )
groups = groups [ order ]
# this is only needed if groups is unsorted
data = data [ order ]
# construct an index which marks borders between groups
index = np . empty ( len ( groups ) , 'bool' )
index [ 0 ] = True
index [ 1 : ] = g... |
def to_python ( self , value ) :
"""Validates that the input can be converted to a datetime . Returns a
Python datetime . datetime object .""" | if value in validators . EMPTY_VALUES :
return None
if isinstance ( value , datetime . datetime ) :
return value
if isinstance ( value , datetime . date ) :
return datetime . datetime ( value . year , value . month , value . day )
if isinstance ( value , list ) : # Input comes from a 2 SplitDateTimeWidgets ... |
def adrinverter ( v_dc , p_dc , inverter , vtol = 0.10 ) :
r'''Converts DC power and voltage to AC power using Anton Driesse ' s
Grid - Connected PV Inverter efficiency model
Parameters
v _ dc : numeric
A scalar or pandas series of DC voltages , in volts , which are provided
as input to the inverter . If ... | p_nom = inverter [ 'Pnom' ]
v_nom = inverter [ 'Vnom' ]
pac_max = inverter [ 'Pacmax' ]
p_nt = inverter [ 'Pnt' ]
ce_list = inverter [ 'ADRCoefficients' ]
v_max = inverter [ 'Vmax' ]
v_min = inverter [ 'Vmin' ]
vdc_max = inverter [ 'Vdcmax' ]
mppt_hi = inverter [ 'MPPTHi' ]
mppt_low = inverter [ 'MPPTLow' ]
v_lim_upper... |
def reproduce ( self , survivors , p_crossover , two_point_crossover = False , target_size = None ) :
"""Reproduces the population from a pool of surviving chromosomes
until a target population size is met . Offspring are created
by selecting a survivor . Survivors with higher fitness have a
greater chance to... | assert 0 <= p_crossover <= 1
if not target_size :
target_size = self . orig_pop_size
num_survivors = len ( survivors )
# compute reproduction cumulative probabilities
# weakest member gets p = 0 but can be crossed - over with
cdf = compute_fitness_cdf ( survivors , self )
offspring = [ ]
while num_survivors + len (... |
def pull ( self , image = None , name = None , pull_folder = '' , ext = "simg" , force = False , capture = False , name_by_commit = False , name_by_hash = False , stream = False ) :
'''pull will pull a singularity hub or Docker image
Parameters
image : the complete image uri . If not provided , the client loade... | from spython . utils import check_install
check_install ( )
cmd = self . _init_command ( 'pull' )
# If Singularity version > 3.0 , we have sif format
if 'version 3' in self . version ( ) :
ext = 'sif'
# No image provided , default to use the client ' s loaded image
if image is None :
image = self . _get_uri ( )... |
def get_build_configuration_set ( id = None , name = None ) :
"""Get a specific BuildConfigurationSet by name or ID""" | content = get_build_configuration_set_raw ( id , name )
if content :
return utils . format_json ( content ) |
async def send ( from_addr , to_addrs , subject = "Ellis" , msg = "" , ** kwargs ) :
"""Sends an e - mail to the provided address .
: param from _ addr : E - mail address of the sender .
: type from _ addr : str
: param to _ addrs : E - mail address ( es ) of the receiver ( s ) .
: type to _ addrs : list or... | async with SMTP ( ) as client :
msg = "Subject: {0}\n\n{1}" . format ( subject , msg )
if kwargs : # To append kwargs to the given message , we first
# transform it into a more human friendly string :
values = "\n" . join ( [ "{0}: {1}" . format ( k , v ) for k , v in kwargs . items ( ) ] )
... |
def update ( self , friendly_name = values . unset , unique_name = values . unset , attributes = values . unset ) :
"""Update the ChannelInstance
: param unicode friendly _ name : A human - readable name for the Channel .
: param unicode unique _ name : A unique , addressable name for the Channel .
: param un... | data = values . of ( { 'FriendlyName' : friendly_name , 'UniqueName' : unique_name , 'Attributes' : attributes , } )
payload = self . _version . update ( 'POST' , self . _uri , data = data , )
return ChannelInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , sid = self . _solution ... |
def get_inst_info ( qry_string ) :
"""Get details for instances that match the qry _ string .
Execute a query against the AWS EC2 client object , that is
based on the contents of qry _ string .
Args :
qry _ string ( str ) : the query to be used against the aws ec2 client .
Returns :
qry _ results ( dict... | qry_prefix = "EC2C.describe_instances("
qry_real = qry_prefix + qry_string + ")"
qry_results = eval ( qry_real )
# pylint : disable = eval - used
return qry_results |
def on_lstClassifications_itemSelectionChanged ( self ) :
"""Update classification description label and unlock the Next button .
. . note : : This is an automatic Qt slot
executed when the field selection changes .""" | self . clear_further_steps ( )
classification = self . selected_classification ( )
# Exit if no selection
if not classification :
return
# Set description label
self . lblDescribeClassification . setText ( classification [ "description" ] )
# Enable the next button
self . parent . pbnNext . setEnabled ( True ) |
def CreateTask ( self , session_identifier ) :
"""Creates a task .
Args :
session _ identifier ( str ) : the identifier of the session the task is
part of .
Returns :
Task : task attribute container .""" | task = tasks . Task ( session_identifier )
logger . debug ( 'Created task: {0:s}.' . format ( task . identifier ) )
with self . _lock :
self . _tasks_queued [ task . identifier ] = task
self . _total_number_of_tasks += 1
self . SampleTaskStatus ( task , 'created' )
return task |
def get_kwargs ( self ) :
"""Returns kwargs for both publisher and subscriber classes""" | return { 'host' : self . host , 'port' : self . port , 'channel' : self . channel , 'password' : self . password } |
def sd ( self ) :
'''Calculate standard deviation of timeseries''' | v = self . var ( )
if len ( v ) :
return np . sqrt ( v )
else :
return None |
def replace_each ( text , items , count = None , strip = False ) :
'''Like ` ` replace ` ` , where each occurrence in ` ` items ` ` is a 2 - tuple of
` ` ( old , new ) ` ` pair .''' | for a , b in items :
text = replace ( text , a , b , count = count , strip = strip )
return text |
def divide ( self , other , inplace = True ) :
"""Returns the division of two gaussian distributions .
Parameters
other : GaussianDistribution
The GaussianDistribution to be divided .
inplace : boolean
If True , modifies the distribution itself , otherwise returns a new
GaussianDistribution object .
R... | return self . _operate ( other , operation = 'divide' , inplace = inplace ) |
def get_pmag_dir ( ) :
"""Returns directory in which PmagPy is installed""" | # this is correct for py2exe ( DEPRECATED )
# win _ frozen = is _ frozen ( )
# if win _ frozen :
# path = os . path . abspath ( unicode ( sys . executable , sys . getfilesystemencoding ( ) ) )
# path = os . path . split ( path ) [ 0]
# return path
# this is correct for py2app
try :
return os . environ [ 'RESOURCEPA... |
def onlinetime_get ( self , service_staff_id , start_date , end_date , session ) :
'''taobao . wangwang . eservice . onlinetime . get 日累计在线时长
描述 : 根据客服ID和日期 , 获取该客服 " 当日在线时长 " 。 备注 :
- 1 、 如果是操作者ID = 被查者ID , 返回被查者ID的 " 当日在线时长 " 。
- 2 、 如果操作者是组管理员 , 他可以查询他的组中的所有子帐号的 " 当日在线时长 " 。
- 3 、 如果操作者是主账户 , 他可以查询所有子帐号的... | request = TOPRequest ( 'taobao.wangwang.eservice.onlinetime.get' )
request [ 'service_staff_id' ] = service_staff_id
request [ 'start_date' ] = start_date
request [ 'end_date' ] = end_date
self . create ( self . execute ( request , session ) )
return self . online_times_list_on_days |
def render_unregistered ( error = None ) :
"""Render template file for the unregistered user .
Args :
error ( str , default None ) : Optional error message .
Returns :
str : Template filled with data .""" | return template ( read_index_template ( ) , registered = False , error = error , seeder_data = None , url_id = None , ) |
def set_walltime ( self , walltime ) :
"""Setting a walltime for the job
> > > job . set _ walltime ( datetime . timedelta ( hours = 2 , minutes = 30 ) )
: param walltime : Walltime of the job ( an instance of timedelta )
: returns : self
: rtype : self""" | if not isinstance ( walltime , timedelta ) :
raise TypeError ( 'walltime must be an instance of datetime.timedelta. %s given' % type ( walltime ) )
self . _options [ 'walltime' ] = walltime
return self |
def sanitizeStructTime ( struct ) :
"""Convert struct _ time tuples with possibly invalid values to valid
ones by substituting the closest valid value .""" | maxValues = ( 9999 , 12 , 31 , 23 , 59 , 59 )
minValues = ( 1 , 1 , 1 , 0 , 0 , 0 )
newstruct = [ ]
for value , maxValue , minValue in zip ( struct [ : 6 ] , maxValues , minValues ) :
newstruct . append ( max ( minValue , min ( value , maxValue ) ) )
return tuple ( newstruct ) + struct [ 6 : ] |
def get_authorization_url ( self , requested_scopes = None , redirect_uri = OAUTH_REDIRECT_URL , ** kwargs ) :
"""Initializes the oauth authorization flow , getting the
authorization url that the user must approve .
: param list [ str ] requested _ scopes : list of scopes to request access for
: param str red... | # TODO : remove this warning in future releases
if redirect_uri == OAUTH_REDIRECT_URL :
warnings . warn ( 'The default redirect uri was changed in version 1.1.4. to' ' "https://login.microsoftonline.com/common/oauth2/nativeclient".' ' You may have to change the registered app "redirect uri" or pass here the old "re... |
def _py2_and_3_joiner ( sep , joinable ) :
"""Allow ' \n ' . join ( . . . ) statements to work in Py2 and Py3.
: param sep :
: param joinable :
: return :""" | if ISPY3 :
sep = bytes ( sep , DEFAULT_ENCODING )
joined = sep . join ( joinable )
return joined . decode ( DEFAULT_ENCODING ) if ISPY3 else joined |
def create_fwrule ( kwargs = None , call = None ) :
'''Create a GCE firewall rule . The ' default ' network is used if not specified .
CLI Example :
. . code - block : : bash
salt - cloud - f create _ fwrule gce name = allow - http allow = tcp : 80''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The create_fwrule function must be called with -f or --function.' )
if not kwargs or 'name' not in kwargs :
log . error ( 'A name must be specified when creating a firewall rule.' )
return False
if 'allow' not in kwargs :
log . error ( 'Must use "allo... |
def _remove_clublog_xml_header ( self , cty_xml_filename ) :
"""remove the header of the Clublog XML File to make it
properly parseable for the python ElementTree XML parser""" | import tempfile
try :
with open ( cty_xml_filename , "r" ) as f :
content = f . readlines ( )
cty_dir = tempfile . gettempdir ( )
cty_name = os . path . split ( cty_xml_filename ) [ 1 ]
cty_xml_filename_no_header = os . path . join ( cty_dir , "NoHeader_" + cty_name )
with open ( cty_xml_fil... |
def analyzeModelWeightDistribution ( modelName , base ) :
"""Plot histogram of non - zero weight values .""" | model = torch . load ( modelName )
model . eval ( )
analyzeWeightDistribution ( model . l1 . weight . data , base ) |
def analyze ( self , handle , filename ) :
"""Submit a file for analysis .
: type handle : File handle
: param handle : Handle to file to upload for analysis .
: type filename : str
: param filename : File name .
: rtype : str
: return : File ID as a string""" | # multipart post files .
files = { "sample_file" : ( filename , handle ) }
# ensure the handle is at offset 0.
handle . seek ( 0 )
response = self . _request ( "/sample/submit" , method = 'POST' , files = files , headers = self . headers )
try :
if response . status_code == 200 and not response . json ( ) [ 'data' ... |
def _prep_subsampled_bams ( data , work_dir ) :
"""Prepare a subsampled BAM file with discordants from samblaster and minimal correct pairs .
This attempts to minimize run times by pre - extracting useful reads mixed
with subsampled normal pairs to estimate paired end distributions :
https : / / groups . goog... | sr_bam , disc_bam = sshared . get_split_discordants ( data , work_dir )
ds_bam = bam . downsample ( dd . get_align_bam ( data ) , data , 1e8 , read_filter = "-F 'not secondary_alignment and proper_pair'" , always_run = True , work_dir = work_dir )
out_bam = "%s-final%s" % utils . splitext_plus ( ds_bam )
if not utils .... |
def parse_config ( contents ) :
"""Parse config file into a list of Identity objects .""" | for identity_str , curve_name in re . findall ( r'\<(.*?)\|(.*?)\>' , contents ) :
yield device . interface . Identity ( identity_str = identity_str , curve_name = curve_name ) |
def write_xml ( xml_str , output_loc = None , filename = None ) :
"""Outputs the XML content ( string ) into a file .
If ` output _ loc ` is supplied and it ' s a file ( not directory ) , the output
will be saved there and the ` filename ` is ignored .
Args :
xml _ str : string with XML document
output _ ... | if not xml_str :
raise Dump2PolarionException ( "No data to write." )
filename_fin = _get_filename ( output_loc = output_loc , filename = filename )
with io . open ( filename_fin , "w" , encoding = "utf-8" ) as xml_file :
xml_file . write ( get_unicode_str ( xml_str ) )
logger . info ( "Data written to '%s'" , ... |
def config_to_options ( config ) :
"""Convert ConfigParser instance to argparse . Namespace
Parameters
config : object
A ConfigParser instance
Returns
object
An argparse . Namespace instance""" | class Options :
host = config . get ( 'smtp' , 'host' , raw = True )
port = config . getint ( 'smtp' , 'port' )
to_addr = config . get ( 'mail' , 'to_addr' , raw = True )
from_addr = config . get ( 'mail' , 'from_addr' , raw = True )
subject = config . get ( 'mail' , 'subject' , raw = True )
enc... |
def prt_detail ( self ) :
"""Nicely print stats information .""" | screen = [ "Detail info of %s: " % self . abspath , "total size = %s" % string_SizeInBytes ( self . size_total ) , "number of sub folders = %s" % self . num_folder_total , "number of total files = %s" % self . num_file_total , "lvl 1 file size = %s" % string_SizeInBytes ( self . size_current ) , "lvl 1 folder number = ... |
def region ( self , region = None , seqid = None , start = None , end = None , strand = None , featuretype = None , completely_within = False ) :
"""Return features within specified genomic coordinates .
Specifying genomic coordinates can be done in a flexible manner
Parameters
region : string , tuple , or Fe... | # Argument handling .
if region is not None :
if ( seqid is not None ) or ( start is not None ) or ( end is not None ) :
raise ValueError ( "If region is supplied, do not supply seqid, " "start, or end as separate kwargs" )
if isinstance ( region , six . string_types ) :
toks = region . split ( ... |
def processes ( self ) :
"""The proccesses for this app .""" | return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'ps' ) , obj = Process , app = self , map = ProcessListResource ) |
def get_relative_modpath ( module_fpath ) :
"""Returns path to module relative to the package root
Args :
module _ fpath ( str ) : module filepath
Returns :
str : modname
Example :
> > > # ENABLE _ DOCTEST
> > > from utool . util _ path import * # NOQA
> > > import utool as ut
> > > module _ fpath... | modsubdir_list = get_module_subdir_list ( module_fpath )
_ , ext = splitext ( module_fpath )
rel_modpath = join ( * modsubdir_list ) + ext
rel_modpath = ensure_crossplat_path ( rel_modpath )
return rel_modpath |
def curve ( self ) :
"""Curve of the super helix .""" | return HelicalCurve . pitch_and_radius ( self . major_pitch , self . major_radius , handedness = self . major_handedness ) |
def instance ( self , inst ) :
"""Called by _ _ parse _ xml _ file in source _ reader .""" | self . __inst = inst
# use inst , to reduce attribute access time
if isinstance ( inst , declarations . declaration_t ) and inst . location is not None and inst . location . file_name != '' :
inst . location . file_name = self . __files [ inst . location . file_name ] |
def move ( self , filename , target ) :
'''Move a file given its filename to another path in the storage
Default implementation perform a copy then a delete .
Backends should overwrite it if there is a better way .''' | self . copy ( filename , target )
self . delete ( filename ) |
def check_data ( cls , name , dims , is_unstructured ) :
"""A validation method for the data shape
Parameters
name : list of str with length 2
The variable names ( one for the first , two for the second array )
dims : list with length 2 of lists with length 1
The dimension of the arrays . Only 2D - Arrays... | if isinstance ( name , six . string_types ) or not is_iterable ( name ) :
name = [ name ]
dims = [ dims ]
is_unstructured = [ is_unstructured ]
msg = ( 'Two arrays are required (one for the scalar and ' 'one for the vector field)' )
if len ( name ) < 2 :
return [ None ] , [ msg ]
elif len ( name ) > 2 :... |
def get_querystring ( self ) :
"""Clean existing query string ( GET parameters ) by removing
arguments that we don ' t want to preserve ( sort parameter , ' page ' )""" | to_remove = self . get_querystring_parameter_to_remove ( )
query_string = urlparse ( self . request . get_full_path ( ) ) . query
query_dict = parse_qs ( query_string . encode ( 'utf-8' ) )
for arg in to_remove :
if arg in query_dict :
del query_dict [ arg ]
clean_query_string = urlencode ( query_dict , dos... |
def record_ce_entries ( self ) : # type : ( ) - > bytes
'''Return a string representing the Rock Ridge entries in the Continuation Entry .
Parameters :
None .
Returns :
A string representing the Rock Ridge entry .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'Rock Ridge extension not yet initialized' )
return self . _record ( self . ce_entries ) |
def to_url ( request ) :
"""Serialize as a URL for a GET request .""" | scheme , netloc , path , query , fragment = urlsplit ( to_utf8 ( request . url ) )
query = parse_qs ( query )
for key , value in request . data_and_params . iteritems ( ) :
query . setdefault ( key , [ ] ) . append ( value )
query = urllib . urlencode ( query , True )
return urlunsplit ( ( scheme , netloc , path , ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.