signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def report_device_status ( self , mode ) :
"""Report terminal status or cursor position .
: param int mode : if 5 - - terminal status , 6 - - cursor position ,
otherwise a noop .
. . versionadded : : 0.5.0""" | if mode == 5 : # Request for terminal status .
self . write_process_input ( ctrl . CSI + "0n" )
elif mode == 6 : # Request for cursor position .
x = self . cursor . x + 1
y = self . cursor . y + 1
# " Origin mode ( DECOM ) selects line numbering . "
if mo . DECOM in self . mode :
y -= self .... |
def solve ( self ) :
"""Runs dynamic simulation .
@ rtype : dict
@ return : Solution dictionary with the following keys :
- C { angles } - generator angles
- C { speeds } - generator speeds
- C { eq _ tr } - q component of transient voltage behind
reactance
- C { ed _ tr } - d component of transient v... | t0 = time ( )
buses = self . dyn_case . buses
solution = NewtonPF ( self . case ) . solve ( )
if not solution [ "converged" ] :
logger . error ( "Power flow did not converge. Exiting..." )
return { }
elif self . verbose :
logger . info ( "Power flow converged." )
# Construct augmented Ybus .
if self . verbo... |
def serialize_me ( self , arn , event_time , tech , item = None ) :
"""Dumps the proper JSON for the schema . If the event is too big , then don ' t include the item .
: param arn :
: param event _ time :
: param tech :
: param item :
: return :""" | payload = { 'arn' : arn , 'event_time' : event_time , 'tech' : tech }
if item :
payload [ 'item' ] = item
else :
payload [ 'event_too_big' ] = True
return self . dumps ( payload ) . data . replace ( '<empty>' , '' ) |
def term_matrix ( idlist , subject_category , taxon , ** kwargs ) :
"""Intersection between annotated objects
P1 not ( P1)
F1 0 5
not ( F1 ) 6 0""" | results = search_associations ( objects = idlist , subject_taxon = taxon , subject_category = subject_category , select_fields = [ M . SUBJECT , M . OBJECT_CLOSURE ] , facet_fields = [ ] , rows = - 1 , include_raw = True , ** kwargs )
docs = results [ 'raw' ] . docs
subjects_per_term = { }
smap = { }
for d in docs :
... |
def get_info ( pyfile ) :
'''Retrieve dunder values from a pyfile''' | info = { }
info_re = re . compile ( r"^__(\w+)__ = ['\"](.*)['\"]" )
with open ( pyfile , 'r' ) as f :
for line in f . readlines ( ) :
match = info_re . search ( line )
if match :
info [ match . group ( 1 ) ] = match . group ( 2 )
return info |
def locate ( self , minimum_version = None , maximum_version = None , jdk = False ) :
"""Finds a java distribution that meets the given constraints and returns it .
First looks for a cached version that was previously located , otherwise calls locate ( ) .
: param minimum _ version : minimum jvm version to look... | def _get_stricter_version ( a , b , name , stricter ) :
version_a = _parse_java_version ( name , a )
version_b = _parse_java_version ( name , b )
if version_a is None :
return version_b
if version_b is None :
return version_a
return stricter ( version_a , version_b )
# Take the tight... |
def _infer_map ( node , context ) :
"""Infer all values based on Dict . items""" | values = { }
for name , value in node . items :
if isinstance ( name , nodes . DictUnpack ) :
double_starred = helpers . safe_infer ( value , context )
if not double_starred :
raise exceptions . InferenceError
if not isinstance ( double_starred , nodes . Dict ) :
rais... |
def transform ( self , X ) :
"""Return this basis applied to X .
Parameters
X : ndarray
of shape ( N , d ) of observations where N is the number of samples ,
and d is the dimensionality of X .
Returns
ndarray :
of shape ( N , d * order + 1 ) , the extra 1 is from a prepended ones
column .""" | N , D = X . shape
pow_arr = np . arange ( self . order ) + 1
# Polynomial terms
Phi = X [ : , : , np . newaxis ] ** pow_arr
# Flatten along last axes
Phi = Phi . reshape ( N , D * self . order )
# Prepend intercept
if self . include_bias :
Phi = np . hstack ( ( np . ones ( ( N , 1 ) ) , Phi ) )
# TODO : Using np . ... |
def only_specific_multisets ( ent , multisets_to_show ) :
'''returns a pretty - printed string for specific features in a FeatureCollection''' | out_str = [ ]
for mset_name in multisets_to_show :
for key , count in ent [ mset_name ] . items ( ) :
out_str . append ( '%s - %d: %s' % ( mset_name , count , key ) )
return '\n' . join ( out_str ) |
def compiler_preprocessor_verbose ( compiler , extraflags ) :
"""Capture the compiler preprocessor stage in verbose mode""" | lines = [ ]
with open ( os . devnull , 'r' ) as devnull :
cmd = [ compiler , '-E' ]
cmd += extraflags
cmd += [ '-' , '-v' ]
p = Popen ( cmd , stdin = devnull , stdout = PIPE , stderr = PIPE )
p . wait ( )
p . stdout . close ( )
lines = p . stderr . read ( )
lines = lines . decode ( 'utf-... |
def preupdate ( self , force_refresh = True ) :
"""Return a dict with all current options prior submitting request .""" | ddata = MANUAL_OP_DATA . copy ( )
# force update to make sure status is accurate
if force_refresh :
self . update ( )
# select current controller and faucet
ddata [ 'select_controller' ] = self . _parent . controllers . index ( self . _controller )
ddata [ 'select_faucet' ] = self . _controller . faucets . index ( ... |
def add ( self , * args , ** kwargs ) :
"""Add the instance tied to the field for the given " value " ( via ` args ` ) to the index
For the parameters , see ` ` BaseIndex . add ` `""" | check_uniqueness = kwargs . get ( 'check_uniqueness' , True )
key = self . get_storage_key ( * args )
if self . field . unique and check_uniqueness :
self . check_uniqueness ( key = key , * args )
# Do index = > create a key to be able to retrieve parent pk with
# current field value ]
pk = self . instance . pk . g... |
def get_subgraph_by_induction ( graph , nodes : Iterable [ BaseEntity ] ) :
"""Induce a sub - graph over the given nodes or return None if none of the nodes are in the given graph .
: param pybel . BELGraph graph : A BEL graph
: param nodes : A list of BEL nodes in the graph
: rtype : Optional [ pybel . BELGr... | nodes = tuple ( nodes )
if all ( node not in graph for node in nodes ) :
return
return subgraph ( graph , nodes ) |
def _render ( self ) :
'''Standard rendering of bar graph .''' | cm_chars = self . _comp_style ( self . icons [ _ic ] * self . _num_complete_chars )
em_chars = self . _empt_style ( self . icons [ _ie ] * self . _num_empty_chars )
return f'{self._first}{cm_chars}{em_chars}{self._last} {self._lbl}' |
def get_authenticity_token ( self , url = _SIGNIN_URL ) :
"""Returns an authenticity _ token , mandatory for signing in""" | res = self . client . _get ( url = url , expected_status_code = 200 )
soup = BeautifulSoup ( res . text , _DEFAULT_BEAUTIFULSOUP_PARSER )
selection = soup . select ( _AUTHENTICITY_TOKEN_SELECTOR )
try :
authenticity_token = selection [ 0 ] . get ( "content" )
except :
raise ValueError ( "authenticity_token not ... |
def importSNPs ( name ) :
"""Import a SNP set shipped with pyGeno . Most of the datawraps only contain URLs towards data provided by third parties .""" | path = os . path . join ( this_dir , "bootstrap_data" , "SNPs/" + name )
PS . importSNPs ( path ) |
def construct_url ( self , style ) :
"""Return http / https or ws / wss url .""" | if style is API_URL :
if self . _ssl :
return 'https://{}:{}' . format ( self . _host , self . _port )
else :
return 'http://{}:{}' . format ( self . _host , self . _port )
elif style is SOCKET_URL :
if self . _ssl :
return 'wss://{}:{}' . format ( self . _host , self . _port )
e... |
def toGeoCoordinateString ( self , sr , coordinates , conversionType , conversionMode = "mgrsDefault" , numOfDigits = None , rounding = True , addSpaces = True ) :
"""The toGeoCoordinateString operation is performed on a geometry
service resource . The operation converts an array of
xy - coordinates into well -... | params = { "f" : "json" , "sr" : sr , "coordinates" : coordinates , "conversionType" : conversionType }
url = self . _url + "/toGeoCoordinateString"
if not conversionMode is None :
params [ 'conversionMode' ] = conversionMode
if isinstance ( numOfDigits , int ) :
params [ 'numOfDigits' ] = numOfDigits
if isinst... |
def markdown ( iterable , renderer = HTMLRenderer ) :
"""Output HTML with default settings .
Enables inline and block - level HTML tags .""" | with renderer ( ) as renderer :
return renderer . render ( Document ( iterable ) ) |
def authenticate ( self , username : str , password : str ) -> bool :
"""Do an Authentricate request and save the cookie returned to be used
on the following requests .
Return True if the request was successfull""" | self . username = username
self . password = password
auth_payload = """<authenticate1 xmlns=\"utcs\"
xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
<password>{password}</password>
<username>{username}</username>
... |
def Range ( start , limit , delta ) :
"""Range op .""" | return np . arange ( start , limit , delta , dtype = np . int32 ) , |
def compile_slides ( source ) :
'''Compiles the source to a remark . js slideshow .''' | # if it ' s a directory , do all md files .
if os . path . isdir ( source ) :
for f in os . listdir ( source ) :
if f . lower ( ) . endswith ( '.md' ) :
compile_markdown_file ( os . path . join ( source , f ) )
else :
compile_markdown_file ( source ) |
def iterator ( self , includeKey = True , includeValue = True , prefix = None ) :
"""Store iterator
: return : Iterator for data in all chunks""" | if not ( includeKey or includeValue ) :
raise ValueError ( "At least one of includeKey or includeValue " "should be true" )
lines = self . _lines ( )
if includeKey and includeValue :
return self . _keyValueIterator ( lines , prefix = prefix )
if includeValue :
return self . _valueIterator ( lines , prefix =... |
def _fill_entries ( self ) :
"""Populate entries dictionaries from index .""" | for file in self . index . files :
path = self . index . paths [ file . pathIndex ]
data_offset = file . dataOffset
data_size = file . dataSize
obj = RAFEntry ( self . _data_handle , path , data_offset , data_size )
# Add to full path dictionary
assert path not in self . entries_full
self . ... |
def create ( self , to , media_url , quality = values . unset , status_callback = values . unset , from_ = values . unset , sip_auth_username = values . unset , sip_auth_password = values . unset , store_media = values . unset , ttl = values . unset ) :
"""Create a new FaxInstance
: param unicode to : The phone n... | data = values . of ( { 'To' : to , 'MediaUrl' : media_url , 'Quality' : quality , 'StatusCallback' : status_callback , 'From' : from_ , 'SipAuthUsername' : sip_auth_username , 'SipAuthPassword' : sip_auth_password , 'StoreMedia' : store_media , 'Ttl' : ttl , } )
payload = self . _version . create ( 'POST' , self . _uri... |
def _fill ( self ) :
"""Advance the iterator without returning the old head .""" | prev = self . _head
super ( AutoApplyIterator , self ) . _fill ( )
if self . _head is not None :
self . on_next ( self . _head , prev ) |
def apply_channel ( val : Any , args : ApplyChannelArgs , default : TDefault = RaiseTypeErrorIfNotProvided ) -> Union [ np . ndarray , TDefault ] :
"""High performance evolution under a channel evolution .
If ` val ` defines an ` _ apply _ channel _ ` method , that method will be
used to apply ` val ` ' s chann... | # Check if the specialized method is present .
func = getattr ( val , '_apply_channel_' , None )
if func is not None :
result = func ( args )
if result is not NotImplemented and result is not None :
def err_str ( buf_num_str ) :
return ( "Object of type '{}' returned a result object equal to... |
def disconnect ( self ) :
"""Disconnect a connected client from the broker .""" | self . _state_mutex . acquire ( )
self . _state = mqtt_cs_disconnecting
self . _state_mutex . release ( )
self . _backoffCore . stopStableConnectionTimer ( )
if self . _sock is None and self . _ssl is None :
return MQTT_ERR_NO_CONN
return self . _send_disconnect ( ) |
def findNext ( self , text , wholeWords = False , caseSensitive = False , regexed = False , wrap = True ) :
"""Looks up the next iteration fot the inputed search term .
: param text | < str >
wholeWords | < bool >
caseSensitive | < bool >
regexed | < bool >
: return < bool >""" | return self . findFirst ( text , regexed , caseSensitive , wholeWords , wrap , True ) |
def detect_process ( cls , headers ) :
"""Returns tuple of process , legacy or None , None if not process originating .""" | try :
if 'Libprocess-From' in headers :
return PID . from_string ( headers [ 'Libprocess-From' ] ) , False
elif 'User-Agent' in headers and headers [ 'User-Agent' ] . startswith ( 'libprocess/' ) :
return PID . from_string ( headers [ 'User-Agent' ] [ len ( 'libprocess/' ) : ] ) , True
except Va... |
def verifyZeroInteractions ( * objs ) :
"""Verify that no methods have been called on given objs .
Note that strict mocks usually throw early on unexpected , unstubbed
invocations . Partial mocks ( ' monkeypatched ' objects or modules ) do not
support this functionality at all , bc only for the stubbed invoca... | for obj in objs :
theMock = _get_mock_or_raise ( obj )
if len ( theMock . invocations ) > 0 :
raise VerificationError ( "\nUnwanted interaction: %s" % theMock . invocations [ 0 ] ) |
def set_mysql_password ( self , username , password ) :
"""Update a mysql password for the provided username changing the
leader settings
To update root ' s password pass ` None ` in the username""" | if username is None :
username = 'root'
# get root password via leader - get , it may be that in the past ( when
# changes to root - password were not supported ) the user changed the
# password , so leader - get is more reliable source than
# config . previous ( ' root - password ' ) .
rel_username = None if usern... |
def GetStructFormatString ( self ) :
"""Retrieves the Python struct format string .
Returns :
str : format string as used by Python struct or None if format string
cannot be determined .""" | if self . _data_type_definition . format == definitions . FORMAT_UNSIGNED :
return self . _FORMAT_STRINGS_UNSIGNED . get ( self . _data_type_definition . size , None )
return self . _FORMAT_STRINGS_SIGNED . get ( self . _data_type_definition . size , None ) |
def get_meta_data ( self , request_adu ) :
"""" Extract MBAP header from request adu and return it . The dict has
4 keys : transaction _ id , protocol _ id , length and unit _ id .
: param request _ adu : A bytearray containing request ADU .
: return : Dict with meta data of request .""" | try :
transaction_id , protocol_id , length , unit_id = unpack_mbap ( request_adu [ : 7 ] )
except struct . error :
raise ServerDeviceFailureError ( )
return { 'transaction_id' : transaction_id , 'protocol_id' : protocol_id , 'length' : length , 'unit_id' : unit_id , } |
def create_entity_type ( project_id , display_name , kind ) :
"""Create an entity type with the given display name .""" | import dialogflow_v2 as dialogflow
entity_types_client = dialogflow . EntityTypesClient ( )
parent = entity_types_client . project_agent_path ( project_id )
entity_type = dialogflow . types . EntityType ( display_name = display_name , kind = kind )
response = entity_types_client . create_entity_type ( parent , entity_t... |
def UpdateResourcesFromDict ( dstpath , res , types = None , names = None , languages = None ) :
"""Update or add resources from resource dict in dll / exe file dstpath .
types = a list of resource types to update ( None = all )
names = a list of resource names to update ( None = all )
languages = a list of r... | if types :
types = set ( types )
if names :
names = set ( names )
if langauges :
languages = set ( languages )
for type_ in res :
if not types or type_ in types :
for name in res [ type_ ] :
if not names or name in names :
for language in res [ type_ ] [ name ] :
... |
def create_requests_session ( retries = None , backoff_factor = None , status_forcelist = None , pools_size = 4 , maxsize = 4 , ssl_verify = None , ssl_cert = None , proxy = None , session = None , ) :
"""Create a requests session that retries some errors .""" | # pylint : disable = too - many - branches
config = Configuration ( )
if retries is None :
if config . error_retry_max is None :
retries = 5
else :
retries = config . error_retry_max
if backoff_factor is None :
if config . error_retry_backoff is None :
backoff_factor = 0.23
else ... |
def filter ( self , entries ) :
"""Filter a set of declarations : keep only those related to this object .
This will keep :
- Declarations that ' override ' the current ones
- Declarations that are parameters to current ones""" | return [ entry for entry in entries if self . split ( entry ) [ 0 ] in self . declarations ] |
def pencil3 ( ) :
'''Install or update latest Pencil version 3 , a GUI prototyping tool .
While it is the newer one and the GUI is more fancy , it is the " more beta "
version of pencil . For exmaple , to display a svg export may fail from
within a reveal . js presentation .
More info :
Homepage : http : ... | repo_name = 'pencil3'
repo_dir = flo ( '~/repos/{repo_name}' )
print_msg ( '## fetch latest pencil\n' )
checkup_git_repo_legacy ( url = 'https://github.com/evolus/pencil.git' , name = repo_name )
run ( flo ( 'cd {repo_dir} && npm install' ) , msg = '\n## install npms\n' )
install_user_command_legacy ( 'pencil3' , penci... |
def votes ( self ) :
"""Returns all the votes related to this topic poll .""" | votes = [ ]
for option in self . options . all ( ) :
votes += option . votes . all ( )
return votes |
def _delete_element ( name , element_type , data , server = None ) :
'''Delete an element''' | _api_delete ( '{0}/{1}' . format ( element_type , quote ( name , safe = '' ) ) , data , server )
return name |
def read ( self , entity = None , attrs = None , ignore = None , params = None ) :
"""Provide a default value for ` ` entity ` ` .
By default , ` ` nailgun . entity _ mixins . EntityReadMixin . read ` ` provides a
default value for ` ` entity ` ` like so : :
entity = type ( self ) ( )
However , : class : ` ... | # read ( ) should not change the state of the object it ' s called on , but
# super ( ) alters the attributes of any entity passed in . Creating a new
# object and passing it to super ( ) lets this one avoid changing state .
if entity is None :
entity = type ( self ) ( self . _server_config , operatingsystem = self... |
def enqueue ( self , queue_identifier : QueueIdentifier , message : Message ) :
"""Enqueue a message to be sent , and notify main loop""" | assert queue_identifier . recipient == self . receiver
with self . _lock :
already_queued = any ( queue_identifier == data . queue_identifier and message == data . message for data in self . _message_queue )
if already_queued :
self . log . warning ( 'Message already in queue - ignoring' , receiver = pe... |
def get_forecast_errors ( y_hat , y_true , window_size = 5 , batch_size = 30 , smoothing_percent = 0.05 , smoothed = True ) :
"""Calculates the forecasting error for two arrays of data . If smoothed errors desired ,
runs EWMA .
Args :
y _ hat ( list ) : forecasted values . len ( y _ hat ) = = len ( y _ true )... | errors = [ abs ( y_h - y_t ) for y_h , y_t in zip ( y_hat , y_true ) ]
if not smoothed :
return errors
historical_error_window = int ( window_size * batch_size * smoothing_percent )
moving_avg = [ ]
for i in range ( len ( errors ) ) :
left_window = i - historical_error_window
right_window = i + historical_e... |
def _add_nat ( self ) :
"""Add pd . NaT to self""" | if is_period_dtype ( self ) :
raise TypeError ( 'Cannot add {cls} and {typ}' . format ( cls = type ( self ) . __name__ , typ = type ( NaT ) . __name__ ) )
# GH # 19124 pd . NaT is treated like a timedelta for both timedelta
# and datetime dtypes
result = np . zeros ( len ( self ) , dtype = np . int64 )
result . fil... |
def get_local_references ( tb , max_string_length = 1000 ) :
"""Find the values of the local variables within the traceback scope .
: param tb : traceback
: return : list of tuples containing ( variable name , value )""" | if 'self' in tb . tb_frame . f_locals :
_locals = [ ( 'self' , repr ( tb . tb_frame . f_locals [ 'self' ] ) ) ]
else :
_locals = [ ]
for k , v in tb . tb_frame . f_locals . iteritems ( ) :
if k == 'self' :
continue
try :
vstr = format_reference ( v , max_string_length = max_string_length... |
def encode ( self ) :
"""Encode the DAT packet . This method populates self . buffer , and
returns self for easy method chaining .""" | if len ( self . data ) == 0 :
log . debug ( "Encoding an empty DAT packet" )
data = self . data
if not isinstance ( self . data , bytes ) :
data = self . data . encode ( 'ascii' )
fmt = b"!HH%ds" % len ( data )
self . buffer = struct . pack ( fmt , self . opcode , self . blocknumber , data )
return self |
def subimage ( self , blc = ( ) , trc = ( ) , inc = ( ) , dropdegenerate = True ) :
"""Form a subimage .
An image object containing a subset of an image is returned .
The arguments blc ( bottom left corner ) , trc ( top right corner ) ,
and inc ( stride ) define the subset . Not all axes need to be specified ... | return image ( self . _subimage ( self . _adjustBlc ( blc ) , self . _adjustTrc ( trc ) , self . _adjustInc ( inc ) , dropdegenerate ) ) |
def unescape_path ( pth ) :
"""Hex / unicode unescapes a path .
Unescapes a path . Valid escapeds are ` ` ' \\ xYY ' ` ` , ` ` ' \\ uYYYY ' , or
` ` ' \\ UYYYYY ' ` ` where Y are hex digits giving the character ' s
unicode numerical value and double backslashes which are the escape
for single backslashes . ... | if isinstance ( pth , bytes ) :
pth = pth . decode ( 'utf-8' )
if sys . hexversion >= 0x03000000 :
if not isinstance ( pth , str ) :
raise TypeError ( 'pth must be str or bytes.' )
else :
if not isinstance ( pth , unicode ) :
raise TypeError ( 'pth must be unicode or str.' )
# Look for inval... |
def active_devices ( self , active_devices ) :
"""Sets the active _ devices of this ReportBillingData .
: param active _ devices : The active _ devices of this ReportBillingData .
: type : int""" | if active_devices is None :
raise ValueError ( "Invalid value for `active_devices`, must not be `None`" )
if active_devices is not None and active_devices < 0 :
raise ValueError ( "Invalid value for `active_devices`, must be a value greater than or equal to `0`" )
self . _active_devices = active_devices |
def set_XRef ( self , X = None , indtX = None , indtXlamb = None ) :
"""Reset the reference X
Useful if to replace channel indices by a time - vraying quantity
e . g . : distance to the magnetic axis""" | out = self . _checkformat_inputs_XRef ( X = X , indtX = indtX , indXlamb = indtXlamb )
X , nnch , indtX , indXlamb , indtXlamb = out
self . _ddataRef [ 'X' ] = X
self . _ddataRef [ 'nnch' ] = nnch
self . _ddataRef [ 'indtX' ] = indtX
self . _ddataRef [ 'indtXlamb' ] = indtXlamb
self . _ddata [ 'uptodate' ] = False |
def vscl ( s , v1 ) :
"""Multiply a scalar and a 3 - dimensional double precision vector .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / vscl _ c . html
: param s : Scalar to multiply a vector
: type s : float
: param v1 : Vector to be multiplied
: type v1 : 3 - Element A... | s = ctypes . c_double ( s )
v1 = stypes . toDoubleVector ( v1 )
vout = stypes . emptyDoubleVector ( 3 )
libspice . vscl_c ( s , v1 , vout )
return stypes . cVectorToPython ( vout ) |
def _set_protocol_type ( self , v , load = False ) :
"""Setter method for protocol _ type , mapped from YANG variable / mpls _ state / ldp / tunnels / ldp _ tunnels / protocol _ type ( mpls - protocol - type )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ protocol _ t... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'staticp' : { 'value' : 0 } , u'ldp' : { 'value' : 2 } , u'rsvp' : { 'value' : 1 } } , ) , is_leaf = True , yang_name = "protoco... |
def get_fitting_data ( bs , spin , band_id , kpoint_id , num_sample_points = 3 ) :
"""Extract fitting data for band extrema based on spin , kpoint and band .
Searches forward and backward from the extrema point , but will only sample
there data if there are enough points in that direction .
Args :
bs ( : ob... | # branch data provides data about the start and end points
# of specific band paths
branch_data = [ b for b in bs . get_branch ( kpoint_id ) if b [ 'index' ] == kpoint_id ] [ 0 ]
start_kpoint = bs . kpoints [ kpoint_id ]
fitting_data = [ ]
# check to see if there are enough points to sample from first
# check in the fo... |
def _as_dict ( self ) :
"""Returns a map of column names to cleaned values""" | values = self . _dynamic_columns or { }
for name , col in self . _columns . items ( ) :
values [ name ] = col . to_database ( getattr ( self , name , None ) )
return values |
def make_trace_config ( tracer : Tracer ) -> aiohttp . TraceConfig :
"""Creates aiohttp . TraceConfig with enabled aiozipking instrumentation
for aiohttp client .""" | trace_config = aiohttp . TraceConfig ( )
zipkin = ZipkinClientSignals ( tracer )
trace_config . on_request_start . append ( zipkin . on_request_start )
trace_config . on_request_end . append ( zipkin . on_request_end )
trace_config . on_request_exception . append ( zipkin . on_request_exception )
return trace_config |
def download_song ( song_url , song_title ) :
"""Download a song using youtube url and song title""" | outtmpl = song_title + '.%(ext)s'
ydl_opts = { 'format' : 'bestaudio/best' , 'outtmpl' : outtmpl , 'postprocessors' : [ { 'key' : 'FFmpegExtractAudio' , 'preferredcodec' : 'mp3' , 'preferredquality' : '192' , } , { 'key' : 'FFmpegMetadata' } , ] , }
with youtube_dl . YoutubeDL ( ydl_opts ) as ydl :
info_dict = ydl ... |
def connect ( self , name = None , remoteId = None , ha = None , verKeyRaw = None , publicKeyRaw = None ) :
"""Connect to the node specified by name .""" | if not name :
raise ValueError ( 'Remote name should be specified' )
publicKey = None
if name in self . remotes :
remote = self . remotes [ name ]
else :
publicKey = z85 . encode ( publicKeyRaw ) if publicKeyRaw else self . getPublicKey ( name )
verKey = z85 . encode ( verKeyRaw ) if verKeyRaw else self... |
def defragment6 ( pktlist ) :
"""Performs defragmentation of a list of IPv6 packets . Packets are reordered .
Crap is dropped . What lacks is completed by ' X ' characters .""" | l = [ x for x in pktlist if IPv6ExtHdrFragment in x ]
# remove non fragments
if not l :
return [ ]
id = l [ 0 ] [ IPv6ExtHdrFragment ] . id
llen = len ( l )
l = [ x for x in l if x [ IPv6ExtHdrFragment ] . id == id ]
if len ( l ) != llen :
warning ( "defragment6: some fragmented packets have been removed from l... |
def memory_usage ( self , key , samples = None ) :
"""Return the total memory usage for key , its value and associated
administrative overheads .
For nested data structures , ` ` samples ` ` is the number of elements to
sample . If left unspecified , the server ' s default is 5 . Use 0 to sample
all element... | args = [ ]
if isinstance ( samples , int ) :
args . extend ( [ Token . get_token ( 'SAMPLES' ) , samples ] )
return self . execute_command ( 'MEMORY USAGE' , key , * args ) |
def init_log ( logger , filename = None , loglevel = None ) :
"""Initializes the log file in the proper format .
Arguments :
filename ( str ) : Path to a file . Or None if logging is to
be disabled .
loglevel ( str ) : Determines the level of the log output .""" | formatter = logging . Formatter ( '[%(asctime)s] %(levelname)s: %(name)s: %(message)s' )
if loglevel :
logger . setLevel ( getattr ( logging , loglevel ) )
# We will allways print warnings and higher to stderr
ch = logging . StreamHandler ( )
ch . setLevel ( 'WARNING' )
ch . setFormatter ( formatter )
if filename :... |
def RunCommandOnHost ( cmd , hostname , ssh_key ) :
"""Executes a command via ssh and sends back the exit status code .""" | hostnames = [ hostname ]
results = RunCommandOnHosts ( cmd , hostnames , ssh_key )
assert ( len ( results ) == 1 )
return results [ 0 ] |
def iri_to_uri ( iri , charset = 'utf-8' ) :
r"""Converts any unicode based IRI to an acceptable ASCII URI . Werkzeug
always uses utf - 8 URLs internally because this is what browsers and HTTP
do as well . In some places where it accepts an URL it also accepts a
unicode IRI and converts it into a URI .
Exam... | iri = unicode ( iri )
scheme , auth , hostname , port , path , query , fragment = _uri_split ( iri )
scheme = scheme . encode ( 'ascii' )
hostname = hostname . encode ( 'idna' )
if ':' in hostname :
hostname = '[' + hostname + ']'
if auth :
if ':' in auth :
auth , password = auth . split ( ':' , 1 )
... |
def parse ( self , input_str , reference_date = "" ) :
"""Parses datetime information out of string input .
It invokes the SUTimeWrapper . annotate ( ) function in Java .
Args :
input _ str : The input as string that has to be parsed .
reference _ date : Optional reference data for SUTime .
Returns :
A ... | if not jpype . isThreadAttachedToJVM ( ) :
jpype . attachThreadToJVM ( )
if reference_date :
return json . loads ( self . _sutime . annotate ( input_str , reference_date ) )
return json . loads ( self . _sutime . annotate ( input_str ) ) |
def _feed_to_kafka ( self , json_item ) :
"""Sends a request to Kafka
: param json _ item : The json item to send
: returns : A boolean indicating whther the data was sent successfully or not""" | @ MethodTimer . timeout ( self . settings [ 'KAFKA_FEED_TIMEOUT' ] , False )
def _feed ( json_item ) :
try :
self . logger . debug ( "Sending json to kafka at " + str ( self . settings [ 'KAFKA_PRODUCER_TOPIC' ] ) )
future = self . producer . send ( self . settings [ 'KAFKA_PRODUCER_TOPIC' ] , json_... |
def tryimport ( modname , pipiname = None , ensure = False ) :
"""CommandLine :
python - m utool . util _ import - - test - tryimport
Example :
> > > # ENABLE _ DOCTEST
> > > from utool . util _ tests import * # NOQA
> > > import utool as ut
> > > modname = ' pyfiglet '
> > > pipiname = ' git + https ... | if pipiname is None :
pipiname = modname
try :
if util_inject . PRINT_INJECT_ORDER :
if modname not in sys . modules :
util_inject . noinject ( modname , N = 2 , via = 'ut.tryimport' )
module = __import__ ( modname )
return module
except ImportError as ex :
import utool as ut
... |
def _find_matching_instance ( cache_key ) :
"""Find a running TensorBoard instance compatible with the cache key .
Returns :
A ` TensorBoardInfo ` object , or ` None ` if none matches the cache key .""" | infos = get_all ( )
candidates = [ info for info in infos if info . cache_key == cache_key ]
for candidate in sorted ( candidates , key = lambda x : x . port ) : # TODO ( @ wchargin ) : Check here that the provided port is still live .
return candidate
return None |
def resample_signal ( self , data_frame ) :
"""Convenience method for frequency conversion and resampling of data frame .
Object must have a DatetimeIndex . After re - sampling , this methods interpolate the time magnitude sum
acceleration values and the x , y , z values of the data frame acceleration
: param... | df_resampled = data_frame . resample ( str ( 1 / self . sampling_frequency ) + 'S' ) . mean ( )
f = interpolate . interp1d ( data_frame . td , data_frame . mag_sum_acc )
new_timestamp = np . arange ( data_frame . td [ 0 ] , data_frame . td [ - 1 ] , 1.0 / self . sampling_frequency )
df_resampled . mag_sum_acc = f ( new... |
def _generate_uri ( admin_metadata , base_uri ) :
"""Return dataset URI .
: param admin _ metadata : dataset administrative metadata
: param base _ uri : base URI from which to derive dataset URI
: returns : dataset URI""" | name = admin_metadata [ "name" ]
uuid = admin_metadata [ "uuid" ]
# storage _ broker _ lookup = _ generate _ storage _ broker _ lookup ( )
# parse _ result = urlparse ( base _ uri )
# storage = parse _ result . scheme
StorageBroker = _get_storage_broker ( base_uri , config_path = None )
return StorageBroker . generate_... |
def disconnect ( self ) :
"""Disconnect from MQTT Broker .
Example :
| Disconnect |""" | try :
tmp = self . _mqttc
except AttributeError :
logger . info ( 'No MQTT Client instance found so nothing to disconnect from.' )
return
self . _disconnected = False
self . _unexpected_disconnect = False
self . _mqttc . on_disconnect = self . _on_disconnect
self . _mqttc . disconnect ( )
timer_start = time... |
def add_view ( self , view , name = None , position = None , closable = False , floatable = True , floating = None ) :
"""Add a widget to the main window .""" | # Set the name in the view .
view . view_index = self . _get_view_index ( view )
# The view name is ` < class _ name > < view _ index > ` , e . g . ` MyView0 ` .
view . name = name or view . __class__ . __name__ + str ( view . view_index )
# Get the Qt canvas for VisPy and matplotlib views .
widget = _try_get_vispy_can... |
def search ( self , filter , base_dn = None , attrs = None , scope = None , timeout = None , limit = None ) :
"""Search the directory .""" | if base_dn is None :
base_dn = self . _search_defaults . get ( 'base_dn' , '' )
if attrs is None :
attrs = self . _search_defaults . get ( 'attrs' , None )
if scope is None :
scope = self . _search_defaults . get ( 'scope' , ldap . SCOPE_SUBTREE )
if timeout is None :
timeout = self . _search_defaults .... |
def secure_authorized_channel ( credentials , request , target , ssl_credentials = None , ** kwargs ) :
"""Creates a secure authorized gRPC channel .
This creates a channel with SSL and : class : ` AuthMetadataPlugin ` . This
channel can be used to create a stub that can make authorized requests .
Example : :... | # Create the metadata plugin for inserting the authorization header .
metadata_plugin = AuthMetadataPlugin ( credentials , request )
# Create a set of grpc . CallCredentials using the metadata plugin .
google_auth_credentials = grpc . metadata_call_credentials ( metadata_plugin )
if ssl_credentials is None :
ssl_cr... |
def remove ( self , name_or_klass ) :
"""Removes a mode from the editor .
: param name _ or _ klass : The name ( or class ) of the mode to remove .
: returns : The removed mode .""" | _logger ( ) . log ( 5 , 'removing mode %r' , name_or_klass )
mode = self . get ( name_or_klass )
mode . on_uninstall ( )
self . _modes . pop ( mode . name )
return mode |
def is_installable_file ( path ) : # type : ( PipfileType ) - > bool
"""Determine if a path can potentially be installed""" | from packaging import specifiers
if isinstance ( path , Mapping ) :
path = convert_entry_to_path ( path )
# If the string starts with a valid specifier operator , test if it is a valid
# specifier set before making a path object ( to avoid breaking windows )
if any ( path . startswith ( spec ) for spec in "!=<>~" )... |
def Parse ( self , cmd , args , stdout , stderr , return_val , time_taken , knowledge_base ) :
"""Parse the dmidecode output . All data is parsed into a dictionary .""" | _ = stderr , time_taken , args , knowledge_base
# Unused .
self . CheckReturn ( cmd , return_val )
output = iter ( stdout . decode ( "utf-8" ) . splitlines ( ) )
# Compile all regexes in advance .
sys_info_re = re . compile ( r"\s*System Information" )
sys_regexes = { "system_manufacturer" : self . _re_compile ( "Manuf... |
def retire_asset_ddo ( self , did ) :
"""Retire asset ddo of Aquarius .
: param did : Asset DID string
: return : API response ( depends on implementation )""" | response = self . requests_session . delete ( f'{self.url}/{did}' , headers = self . _headers )
if response . status_code == 200 :
logging . debug ( f'Removed asset DID: {did} from metadata store' )
return response
raise AquariusGenericError ( f'Unable to remove DID: {response}' ) |
def start_drag ( self , sprite , cursor_x = None , cursor_y = None ) :
"""start dragging given sprite""" | cursor_x , cursor_y = cursor_x or sprite . x , cursor_y or sprite . y
self . _mouse_down_sprite = self . _drag_sprite = sprite
sprite . drag_x , sprite . drag_y = self . _drag_sprite . x , self . _drag_sprite . y
self . __drag_start_x , self . __drag_start_y = cursor_x , cursor_y
self . __drag_started = True |
async def cancel_task ( app : web . Application , task : asyncio . Task , * args , ** kwargs ) -> Any :
"""Convenience function for calling ` TaskScheduler . cancel ( task ) `
This will use the default ` TaskScheduler ` to cancel the given task .
Example :
import asyncio
from datetime import datetime
from... | return await get_scheduler ( app ) . cancel ( task , * args , ** kwargs ) |
def volume ( self , vol , clim = None , method = 'mip' , threshold = None , cmap = 'grays' ) :
"""Show a 3D volume
Parameters
vol : ndarray
Volume to render .
clim : tuple of two floats | None
The contrast limits . The values in the volume are mapped to
black and white corresponding to these values . De... | self . _configure_3d ( )
volume = scene . Volume ( vol , clim , method , threshold , cmap = cmap )
self . view . add ( volume )
self . view . camera . set_range ( )
return volume |
def splitbins ( t , trace = 0 ) :
"""t , trace = 0 - > ( t1 , t2 , shift ) . Split a table to save space .
t is a sequence of ints . This function can be useful to save space if
many of the ints are the same . t1 and t2 are lists of ints , and shift
is an int , chosen to minimize the combined size of t1 and t... | if trace :
def dump ( t1 , t2 , shift , bytes ) :
print ( "%d+%d bins at shift %d; %d bytes" % ( len ( t1 ) , len ( t2 ) , shift , bytes ) , file = sys . stderr )
print ( "Size of original table:" , len ( t ) * getsize ( t ) , "bytes" , file = sys . stderr )
n = len ( t ) - 1
# last valid index
maxshift... |
def _init ( self ) :
'''Prepare to run ( if not ready )''' | num = 0
for field in self . _fields :
field . _initialize ( )
self . _need_second_pass |= field . _need_second_pass
for field in self . _fields :
num += field . num_mutations ( )
self . _calculate_mutations ( num )
self . _initialize_default_buffer ( ) |
def remove_member ( self , login ) :
"""Remove ` ` login ` ` from this team .
: param str login : ( required ) , login of the member to remove
: returns : bool""" | warnings . warn ( 'This is no longer supported by the GitHub API, see ' 'https://developer.github.com/changes/2014-09-23-one-more-week' '-before-the-add-team-member-api-breaking-change/' , DeprecationWarning )
url = self . _build_url ( 'members' , login , base_url = self . _api )
return self . _boolean ( self . _delete... |
def _get_cursor_vertical_diff_once ( self ) :
"""Returns the how far down the cursor moved .""" | old_top_usable_row = self . top_usable_row
row , col = self . get_cursor_position ( )
if self . _last_cursor_row is None :
cursor_dy = 0
else :
cursor_dy = row - self . _last_cursor_row
logger . info ( 'cursor moved %d lines down' % cursor_dy )
while self . top_usable_row > - 1 and cursor_dy > 0 :
... |
def read ( self , n ) :
"""Read n bytes .
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF .""" | buf = self . _read_buf
pos = self . _read_pos
end = pos + n
if end <= len ( buf ) : # Fast path : the data to read is fully buffered .
self . _read_pos += n
return self . _update_pos ( buf [ pos : end ] )
# Slow path : read from the stream until enough bytes are read ,
# or until an EOF occurs or until read ( )... |
def tag_to_version ( tag , config = None ) :
"""take a tag that might be prefixed with a keyword and return only the version part
: param config : optional configuration object""" | trace ( "tag" , tag )
if not config :
config = Configuration ( )
tagdict = _parse_version_tag ( tag , config )
if not isinstance ( tagdict , dict ) or not tagdict . get ( "version" , None ) :
warnings . warn ( "tag %r no version found" % ( tag , ) )
return None
version = tagdict [ "version" ]
trace ( "versi... |
def resolve_name ( view ) :
"""Auto guesses name of the view .
For function it will be ` ` view . _ _ name _ _ ` `
For classes it will be ` ` view . url _ name ` `""" | if inspect . isfunction ( view ) :
return view . __name__
if hasattr ( view , 'url_name' ) :
return view . url_name
if isinstance ( view , six . string_types ) :
return view . split ( '.' ) [ - 1 ]
return None |
def attributes ( self ) :
"""generator [ VolumeAttribute ] : volume attributes generator .""" | if not self . _is_parsed :
self . _Parse ( )
self . _is_parsed = True
return iter ( self . _attributes . values ( ) ) |
def cmdline_params ( self , structure_file_name , surface_sample_file_name ) :
"""Synthesize command line parameters
e . g . [ [ ' struct . cssr ' ] , [ ' struct . vsa ' ] , [ 2.4 ] ]""" | parameters = [ ]
parameters += [ structure_file_name ]
parameters += [ surface_sample_file_name ]
pm_dict = self . get_dict ( )
# replace sampling method string by number
pm_dict [ 'sampling_method' ] = sampling_methods [ pm_dict [ 'sampling_method' ] ]
# order matters here !
for key in [ 'accessible_surface_area' , 's... |
def write ( self , s , ** args ) :
"""Write string to output descriptor . Strips control characters
from string before writing .""" | if self . filename is not None :
self . start_fileoutput ( )
if self . fd is None : # Happens when aborting threads times out
log . warn ( LOG_CHECK , "writing to unitialized or closed file" )
else :
try :
self . fd . write ( s , ** args )
except IOError :
msg = sys . exc_info ( ) [ 1 ]
... |
def random ( length : int = 8 , chars : str = digits + ascii_lowercase ) -> Iterator [ str ] :
"""A random string .
Not unique , but has around 1 in a million chance of collision ( with the default 8
character length ) . e . g . ' fubui5e6'
Args :
length : Length of the random string .
chars : The charact... | while True :
yield "" . join ( [ choice ( chars ) for _ in range ( length ) ] ) |
def _order_queries ( self ) :
"""αα
―α
α
΅αα
΄ αα
₯αΌα
α
§α― αα
©αα
₯α«αα
³α― αα
‘αα
§αα
©αΈαα
΅αα
‘ .""" | from . condition import Order
order = [ ]
for column in self . columns :
if column . order_by :
o = Order ( self . cls , column . attr , column . order_by )
order . append ( o . __query__ ( ) )
if not order :
k = self . columns [ 0 ] . attr
o = Order ( self . cls , k )
self . columns [ 0... |
def __build_index ( self , until = None , flush = False , verbose = False ) :
"""build / expand the index for this file .
: param until : expand the index until the record with this hash has been
incorporated and then stop . If None , go until the iterator
is exhausted . Note that if this hash is already in t... | assert ( self . _indexed_file_handle is not None )
if flush :
self . _index = { }
file_loc = self . _indexed_file_handle . tell ( )
if verbose :
self . _indexed_file_handle . seek ( 0 , 2 )
# seek to end
total = self . _indexed_file_handle . tell ( ) - file_loc
self . _indexed_file_handle . seek ( f... |
def check_selection ( self ) :
"""Check if selected text is r / w ,
otherwise remove read - only parts of selection""" | if self . current_prompt_pos is None :
self . set_cursor_position ( 'eof' )
else :
self . truncate_selection ( self . current_prompt_pos ) |
def get_grade_entry_form ( self , * args , ** kwargs ) :
"""Pass through to provider GradeEntryAdminSession . get _ grade _ entry _ form _ for _ update""" | # Implemented from kitosid template for -
# osid . resource . ResourceAdminSession . get _ resource _ form _ for _ update
# This method might be a bit sketchy . Time will tell .
if isinstance ( args [ - 1 ] , list ) or 'grade_entry_record_types' in kwargs :
return self . get_grade_entry_form_for_create ( * args , *... |
def pillar ( tgt = None , tgt_type = 'glob' , ** kwargs ) :
'''. . versionchanged : : 2017.7.0
The ` ` expr _ form ` ` argument has been renamed to ` ` tgt _ type ` ` , earlier
releases must use ` ` expr _ form ` ` .
Return cached pillars of the targeted minions
CLI Example :
. . code - block : : bash
s... | pillar_util = salt . utils . master . MasterPillarUtil ( tgt , tgt_type , use_cached_grains = True , grains_fallback = False , use_cached_pillar = True , pillar_fallback = False , opts = __opts__ )
cached_pillar = pillar_util . get_minion_pillar ( )
return cached_pillar |
def action ( context , request , action = None , resource = None , uid = None ) :
"""Various HTTP POST actions""" | # allow to set the method via the header
if action is None :
action = request . get_header ( "HTTP_X_HTTP_METHOD_OVERRIDE" , "CREATE" ) . lower ( )
# Fetch and call the action function of the API
func_name = "{}_items" . format ( action )
action_func = getattr ( api , func_name , None )
if action_func is None :
... |
def whole_sequence_accuracy ( y_true , y_pred , lengths ) :
"""Average accuracy measured on whole sequences .
Returns the fraction of sequences in y _ true that occur in y _ pred without a
single error .""" | lengths = np . asarray ( lengths )
end = np . cumsum ( lengths )
start = end - lengths
bounds = np . vstack ( [ start , end ] ) . T
errors = sum ( 1. for i , j in bounds if np . any ( y_true [ i : j ] != y_pred [ i : j ] ) )
return 1 - errors / len ( lengths ) |
def csv ( self , dirPath = None ) :
"""* Render the results in csv format *
* * Key Arguments : * *
- ` ` dirPath ` ` - - the path to the directory to save the rendered results to . Default * None *
* * Return : * *
- ` csvSources ` - - the top - level transient data
- ` csvPhot ` - - all photometry assoc... | if dirPath :
p = self . _file_prefix ( )
csvSources = self . sourceResults . csv ( filepath = dirPath + "/" + p + "sources.csv" )
csvPhot = self . photResults . csv ( filepath = dirPath + "/" + p + "phot.csv" )
csvSpec = self . specResults . csv ( filepath = dirPath + "/" + p + "spec.csv" )
csvFiles... |
def _prepare_consensus ( FetcherClass , results ) :
"""Given a list of results , return a list that is simplified to make consensus
determination possible . Returns two item tuple , first arg is simplified list ,
the second argument is a list of all services used in making these results .""" | # _ get _ results returns lists of 2 item list , first element is service , second is the returned value .
# when determining consensus amoung services , only take into account values returned .
if hasattr ( FetcherClass , "strip_for_consensus" ) :
to_compare = [ FetcherClass . strip_for_consensus ( value ) for ( f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.