signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def setMode ( self , mode ) :
"""Sets the type of crypting mode , pyDes . ECB or pyDes . CBC""" | _baseDes . setMode ( self , mode )
for key in ( self . __key1 , self . __key2 , self . __key3 ) :
key . setMode ( mode ) |
def _decode_time_rotation_index ( self , time_rot_index ) :
'''Return the time struct index to use for log rotation checks''' | time_index_decode_table = { 'year' : 0 , 'years' : 0 , 'tm_year' : 0 , 'month' : 1 , 'months' : 1 , 'tm_mon' : 1 , 'day' : 2 , 'days' : 2 , 'tm_mday' : 2 , 'hour' : 3 , 'hours' : 3 , 'tm_hour' : 3 , 'minute' : 4 , 'minutes' : 4 , 'tm_min' : 4 , 'second' : 5 , 'seconds' : 5 , 'tm_sec' : 5 , }
if time_rot_index not in ti... |
async def addCharm ( self , charm , series ) :
""": param charm string :
Charm holds the URL of the charm to be added .
: param series string :
Series holds the series of the charm to be added
if the charm default is not sufficient .""" | # We don ' t add local charms because they ' ve already been added
# by self . _ handle _ local _ charms
if charm . startswith ( 'local:' ) :
return charm
entity_id = await self . charmstore . entityId ( charm )
log . debug ( 'Adding %s' , entity_id )
await self . client_facade . AddCharm ( None , entity_id )
retur... |
def AddValue ( self , registry_value ) :
"""Adds a value .
Args :
registry _ value ( WinRegistryValue ) : Windows Registry value .
Raises :
KeyError : if the value already exists .""" | name = registry_value . name . upper ( )
if name in self . _values :
raise KeyError ( 'Value: {0:s} already exists.' . format ( registry_value . name ) )
self . _values [ name ] = registry_value |
def animate ( self , seq_name ) :
"""Returns a generator which " executes " an animation sequence for the given
` ` seq _ name ` ` , inasmuch as the next frame for the given animation is
yielded when requested .
: param seq _ name : The name of a previously defined animation sequence .
: type seq _ name : s... | while True :
index = 0
anim = getattr ( self . animations , seq_name )
speed = anim . speed if hasattr ( anim , "speed" ) else 1
num_frames = len ( anim . frames )
while index < num_frames :
frame = anim . frames [ int ( index ) ]
index += speed
if isinstance ( frame , int ) ... |
def get_app_state ( device_id , app_id ) :
"""Get the state of the requested app""" | if not is_valid_app_id ( app_id ) :
abort ( 403 )
if not is_valid_device_id ( device_id ) :
abort ( 403 )
if device_id not in devices :
abort ( 404 )
app_state = devices [ device_id ] . app_state ( app_id )
return jsonify ( state = app_state , status = app_state ) |
def csv_reader ( unicode_csv_data , dialect = None , ** kwargs ) :
"""csv . reader doesn ' t support Unicode input , so need to use some tricks
to work around this .
Source : https : / / docs . python . org / 2 / library / csv . html # csv - examples""" | import csv
dialect = dialect or csv . excel
if is_py3 : # Python3 supports encoding by default , so just return the object
for row in csv . reader ( unicode_csv_data , dialect = dialect , ** kwargs ) :
yield [ cell for cell in row ]
else : # csv . py doesn ' t do Unicode ; encode temporarily as UTF - 8:
... |
def change_filename ( filehandle , meta ) :
"""Changes the filename to reflect the conversion from PDF to JPG .
This method will preserve the original filename in the meta dictionary .""" | filename = secure_filename ( meta . get ( 'filename' , filehandle . filename ) )
basename , _ = os . path . splitext ( filename )
meta [ 'original_filename' ] = filehandle . filename
filehandle . filename = filename + '.jpg'
return filehandle |
def get_joyner_boore_distance ( self , mesh ) :
"""Compute and return Joyner - Boore distance to each point of ` ` mesh ` ` .
Point ' s depth is ignored .
See
: meth : ` openquake . hazardlib . geo . surface . base . BaseSurface . get _ joyner _ boore _ distance `
for definition of this distance .
: retur... | # we perform a hybrid calculation ( geodetic mesh - to - mesh distance
# and distance on the projection plane for close points ) . first ,
# we find the closest geodetic distance for each point of target
# mesh to this one . in general that distance is greater than
# the exact distance to enclosing polygon of this mesh... |
def dashboard_present ( name , dashboard = None , dashboard_from_pillar = None , rows = None , rows_from_pillar = None , profile = 'grafana' ) :
'''Ensure the grafana dashboard exists and is managed .
name
Name of the grafana dashboard .
dashboard
A dict that defines a dashboard that should be managed .
d... | ret = { 'name' : name , 'result' : None , 'comment' : '' , 'changes' : { } }
if not profile :
raise SaltInvocationError ( 'profile is a required argument.' )
if dashboard and dashboard_from_pillar :
raise SaltInvocationError ( 'dashboard and dashboard_from_pillar are' ' mutually exclusive arguments.' )
hosts , ... |
def hexa_word ( data , separator = ' ' ) :
"""Convert binary data to a string of hexadecimal WORDs .
@ type data : str
@ param data : Binary data .
@ type separator : str
@ param separator :
Separator between the hexadecimal representation of each WORD .
@ rtype : str
@ return : Hexadecimal representa... | if len ( data ) & 1 != 0 :
data += '\0'
return separator . join ( [ '%.4x' % struct . unpack ( '<H' , data [ i : i + 2 ] ) [ 0 ] for i in compat . xrange ( 0 , len ( data ) , 2 ) ] ) |
def pre_operations ( self , mode = None ) :
"""Return pre - operations only for the mode asked""" | version_mode = self . _get_version_mode ( mode = mode )
return version_mode . pre_operations |
def detail_get ( self , session , fields = [ ] , ** kwargs ) :
'''taobao . logistics . orders . detail . get 批量查询物流订单 , 返回详细信息
查询物流订单的详细信息 , 涉及用户隐私字段 。 ( 注 : 该API主要是提供给卖家查询物流订单使用 , 买家查询物流订单 , 建议使用taobao . logistics . trace . search )''' | request = TOPRequest ( 'taobao.logistics.orders.detail.get' )
if not fields :
shipping = Shipping ( )
fields = shipping . fields
request [ 'fields' ] = fields
for k , v in kwargs . iteritems ( ) :
if k not in ( 'tid' , 'buyer_nick' , 'status' , 'seller_confirm' , 'receiver_name' , 'start_created' , 'end_cre... |
def group ( self , lst , n ) :
"""Group an iterable into an n - tuples iterable . Incomplete
tuples are discarded""" | return itertools . izip ( * [ itertools . islice ( lst , i , None , n ) for i in range ( n ) ] ) |
def _assert_link_secret ( self , action : str ) :
"""Raise AbsentLinkSecret if link secret is not set .
: param action : action requiring link secret""" | if self . _link_secret is None :
LOGGER . debug ( 'HolderProver._assert_link_secret: action %s requires link secret but it is not set' , action )
raise AbsentLinkSecret ( 'Action {} requires link secret but it is not set' . format ( action ) ) |
def _find_executable ( prog , pathext = ( "" , ) ) :
"""protected""" | pathlist = _decode_if_not_text ( os . environ . get ( 'PATH' , '' ) ) . split ( os . pathsep )
for dir in pathlist :
for ext in pathext :
filename = os . path . join ( dir , prog + ext )
try :
st = os . stat ( filename )
except os . error :
continue
if stat . ... |
def doInteractions ( self , number = 1 ) :
"""Directly maps the agents and the tasks .""" | t0 = time . time ( )
for _ in range ( number ) :
self . _oneInteraction ( )
elapsed = time . time ( ) - t0
logger . info ( "%d interactions executed in %.3fs." % ( number , elapsed ) )
return self . stepid |
def seqrecord ( self , allele , locus ) :
"""Gets the Annotation from the found sequence
: return : The Annotation from the found sequence
: rtype : Annotation""" | try :
db = self . server [ self . dbversion + "_" + locus ]
except :
self . logger . error ( "The database " + self . dbversion + "_" + locus + " does not exist!" )
return ''
seqrecord = db . lookup ( name = allele )
return seqrecord |
def _split_generators ( self , dl_manager ) :
"""Return the validation split of ImageNet2012.
Args :
dl _ manager : download manager object .
Returns :
validation split .""" | splits = super ( Imagenet2012Corrupted , self ) . _split_generators ( dl_manager )
validation = splits [ 1 ]
return [ validation ] |
def from_string ( cls , string , * , default_func = None ) :
'''Construct a Service from a string .
If default _ func is provided and any ServicePart is missing , it is called with
default _ func ( protocol , part ) to obtain the missing part .''' | if not isinstance ( string , str ) :
raise TypeError ( f'service must be a string: {string}' )
parts = string . split ( '://' , 1 )
if len ( parts ) == 2 :
protocol , address = parts
else :
item , = parts
protocol = None
if default_func :
if default_func ( item , ServicePart . HOST ) and def... |
def get_scaled_v2 ( self , amount ) :
"""Return a new Vec2 with x and y multiplied by amount .""" | return Vec2 ( self . x * amount , self . y * amount ) |
def list ( self , id = None ) :
"""List all running processes
: param id : optional PID for the process to list""" | args = { 'pid' : id }
self . _process_chk . check ( args )
return self . _client . json ( 'process.list' , args ) |
def check_is_a_sequence ( var , allow_none = False ) :
"""Calls is _ a _ sequence and raises a type error if the check fails .""" | if not is_a_sequence ( var , allow_none = allow_none ) :
raise TypeError ( "var must be a list or tuple, however type(var) is {}" . format ( type ( var ) ) ) |
def linkfetch ( self ) :
"""Public method to call the internal methods""" | request , handle = self . open ( )
self . _add_headers ( request )
if handle :
self . _get_crawled_urls ( handle , request ) |
def count_above_mean ( x ) :
"""Returns the number of values in x that are higher than the mean of x
: param x : the time series to calculate the feature of
: type x : numpy . ndarray
: return : the value of this feature
: return type : float""" | m = np . mean ( x )
return np . where ( x > m ) [ 0 ] . size |
def lookup ( self , lsid ) :
"""Look up the name of a module by LSID assigned by the authority .
Returns None if the LSID is not found .
: param lsid :
: return : string or none""" | if self . registered_modules is None or lsid not in self . registered_modules :
return None
else :
return self . registered_modules [ lsid ] |
def group_records ( self , key_function ) :
"""Return a dict with the records grouped by the key returned by
` key _ function ` .
` key _ function ` takes a record and returns the value from the record to
group by ( see examples in the group _ records _ by _ * methods below ) .
The return value is a dict , ... | sorted_records = sorted ( self . records , key = key_function )
grouped_records = itertools . groupby ( sorted_records , key = key_function )
return dict ( [ ( key , list ( group ) ) for key , group in grouped_records ] ) |
def brier_score ( observations , forecasts ) :
"""Calculate the Brier score ( BS )
The Brier score ( BS ) scores binary forecasts $ k \ in \ { 0 , 1 \ } $ ,
. . math :
BS ( p , k ) = ( p _ 1 - k ) ^ 2,
where $ p _ 1 $ is the forecast probability of $ k = 1 $ .
Parameters
observations , forecasts : array... | machine_eps = np . finfo ( float ) . eps
forecasts = np . asarray ( forecasts )
if ( forecasts < 0.0 ) . any ( ) or ( forecasts > ( 1.0 + machine_eps ) ) . any ( ) :
raise ValueError ( 'forecasts must not be outside of the unit interval ' '[0, 1]' )
observations = np . asarray ( observations )
if observations . ndi... |
def run ( self ) :
"""Run the sync .
Confront the local and the remote directories and perform the needed changes .""" | # Check if remote path is present
try :
self . sftp . stat ( self . remote_path )
except FileNotFoundError as e :
if self . create_remote_directory :
self . sftp . mkdir ( self . remote_path )
self . logger . info ( "Created missing remote dir: '" + self . remote_path + "'" )
else :
... |
def get_handlers ( self , component_context , instance ) :
"""Sets up service providers for the given component
: param component _ context : The ComponentContext bean
: param instance : The component instance
: return : The list of handlers associated to the given component
( never None )""" | # Extract information from the context
logger_field = component_context . get_handler ( constants . HANDLER_LOGGER )
if not logger_field : # Error : log it and either raise an exception
# or ignore this handler
_logger . warning ( "Logger iPOPO handler can't find its configuration" )
# Here , we ignore the erro... |
def yaml_tag_constructor ( loader , tag , node ) :
"""convert shorthand intrinsic function to full name""" | def _f ( loader , tag , node ) :
if tag == '!GetAtt' :
return node . value . split ( '.' )
elif type ( node ) == yaml . SequenceNode :
return loader . construct_sequence ( node )
else :
return node . value
if tag == '!Ref' :
key = 'Ref'
else :
key = 'Fn::{}' . format ( tag [ ... |
def get_views ( self , name = None ) :
"""Get the list of : py : class : ` ~ streamsx . rest _ primitives . View ` elements associated with this job .
Args :
name ( str , optional ) : Returns view ( s ) matching ` name ` . ` name ` can be a regular expression . If ` name `
is not supplied , then all views ass... | return self . _get_elements ( self . views , 'views' , View , name = name ) |
def _process_doc ( self , doc ) :
"""Applies DCS to a document to extract its core concepts and their weights .""" | # Prep
doc = doc . lower ( )
tagged_tokens = [ ( t , penn_to_wordnet ( t . tag_ ) ) for t in spacy ( doc , tag = True , parse = False , entity = False ) ]
tokens = [ t for t , tag in tagged_tokens ]
term_concept_map = self . _disambiguate_doc ( tagged_tokens )
concept_weights = self . _weight_concepts ( tokens , term_c... |
def hdmbrcheck ( disk_mbr , sector_count , bootable ) : # type : ( bytes , int , bool ) - > int
'''A function to sanity check an El Torito Hard Drive Master Boot Record ( HDMBR ) .
On success , it returns the system _ type ( also known as the partition type ) that
should be fed into the rest of the El Torito me... | # The MBR that we want to see to do hd emulation boot for El Torito is a standard
# x86 MBR , documented here :
# https : / / en . wikipedia . org / wiki / Master _ boot _ record # Sector _ layout
# In brief , it should consist of 512 bytes laid out like :
# Offset 0x0 - 0x1BD : Bootstrap code area
# Offset 0x1BE - 0x1... |
def key_periods ( ciphertext , max_key_period ) :
"""Rank all key periods for ` ` ciphertext ` ` up to and including ` ` max _ key _ period ` `
Example :
> > > key _ periods ( ciphertext , 30)
[2 , 4 , 8 , 3 , . . . ]
Args :
ciphertext ( str ) : The text to analyze
max _ key _ period ( int ) : The maxim... | if max_key_period <= 0 :
raise ValueError ( "max_key_period must be a positive integer" )
key_scores = [ ]
for period in range ( 1 , min ( max_key_period , len ( ciphertext ) ) + 1 ) :
score = abs ( ENGLISH_IC - index_of_coincidence ( * split_columns ( ciphertext , period ) ) )
key_scores . append ( ( perio... |
def str_to_datetime ( dt_str , fmt = '%Y-%m-%d %H:%M:%S' ) :
"""字符串转换为datetime类型数据
: param dt _ str :
: param fmt :
: return :""" | d_time = datetime . datetime . strptime ( dt_str , fmt )
return d_time |
def _diff ( self , dir1 , dir2 ) :
"""Private function which only does directory diff""" | self . _dcmp = self . _compare ( dir1 , dir2 )
if self . _dcmp . left_only :
self . log ( 'Only in %s' % dir1 )
for x in sorted ( self . _dcmp . left_only ) :
self . log ( '>> %s' % x )
self . log ( '' )
if self . _dcmp . right_only :
self . log ( 'Only in %s' % dir2 )
for x in sorted ( self... |
def create_executable_script ( filepath , body , program = None ) :
"""Create an executable script .
Args :
filepath ( str ) : File to create .
body ( str or callable ) : Contents of the script . If a callable , its code
is used as the script body .
program ( str ) : Name of program to launch the script ,... | program = program or "python"
if callable ( body ) :
from rez . utils . sourcecode import SourceCode
code = SourceCode ( func = body )
body = code . source
if not body . endswith ( '\n' ) :
body += '\n'
with open ( filepath , 'w' ) as f : # TODO : make cross platform
f . write ( "#!/usr/bin/env %s\n... |
def ParseOptions ( cls , options , output_module ) :
"""Parses and validates options .
Args :
options ( argparse . Namespace ) : parser options .
output _ module ( TimesketchOutputModule ) : output module to configure .
Raises :
BadConfigObject : when the output module object is of the wrong type .
BadC... | if not isinstance ( output_module , timesketch_out . TimesketchOutputModule ) :
raise errors . BadConfigObject ( 'Output module is not an instance of TimesketchOutputModule' )
document_type = cls . _ParseStringOption ( options , 'document_type' , default_value = cls . _DEFAULT_DOCUMENT_TYPE )
output_module . SetDoc... |
def _get_online_chapter ( self , book_name , book_chapter , cache_chapter ) :
"""Retrieves an entire chapter of a book in the Bible in the form of a
list .
If cache _ chapter is " True " , this method will cache the chapter
in " ~ / . diyr / bible / < book > / < chapter > . txt " .""" | url = self . build_recovery_online_url ( book_name , book_chapter )
logging . debug ( "Looking up chapter at URL: {}" . format ( url ) )
r = requests . get ( url )
if r . status_code != 200 :
logging . error ( "Could not look up {} {} at URL {}" . format ( book_name , book_chapter , url ) )
raise Exception ( "C... |
def _archive_entry_year ( self , category ) :
"Return ARCHIVE _ ENTRY _ YEAR from settings ( if exists ) or year of the newest object in category" | year = getattr ( settings , 'ARCHIVE_ENTRY_YEAR' , None )
if not year :
n = now ( )
try :
year = Listing . objects . filter ( category__site__id = settings . SITE_ID , category__tree_path__startswith = category . tree_path , publish_from__lte = n ) . values ( 'publish_from' ) [ 0 ] [ 'publish_from' ] . ... |
def build_tor_connection ( connection , build_state = True , wait_for_proto = True , password_function = lambda : None ) :
"""This is used to build a valid TorState ( which has . protocol for
the TorControlProtocol ) . For example : :
from twisted . internet import reactor
from twisted . internet . endpoints ... | if IStreamClientEndpoint . providedBy ( connection ) :
endpoint = connection
elif isinstance ( connection , tuple ) :
if len ( connection ) == 2 :
reactor , socket = connection
if ( os . path . exists ( socket ) and os . stat ( socket ) . st_mode & ( stat . S_IRGRP | stat . S_IRUSR | stat . S_IR... |
def check_load ( grid , mode ) :
"""Checks for over - loading of branches and transformers for MV or LV grid .
Parameters
grid : GridDing0
Grid identifier .
mode : str
Kind of grid ( ' MV ' or ' LV ' ) .
Returns
: obj : ` dict `
Dict of critical branches with max . relative overloading , and the
f... | crit_branches = { }
crit_stations = [ ]
if mode == 'MV' : # load load factors ( conditions ) for cables , lines and trafos for load - and feedin case
# load _ factor _ mv _ trans _ lc _ normal = float ( cfg _ ding0 . get ( ' assumptions ' ,
# ' load _ factor _ mv _ trans _ lc _ normal ' ) )
load_factor_mv_line_lc_n... |
def update_pull_request ( self , git_pull_request_to_update , repository_id , pull_request_id , project = None ) :
"""UpdatePullRequest .
[ Preview API ] Update a pull request
: param : class : ` < GitPullRequest > < azure . devops . v5_1 . git . models . GitPullRequest > ` git _ pull _ request _ to _ update : ... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if repository_id is not None :
route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' )
if pull_request_id is not None :
route_values ... |
def joinCommissioned ( self , strPSKd = 'threadjpaketest' , waitTime = 20 ) :
"""start joiner
Args :
strPSKd : Joiner ' s PSKd
Returns :
True : successful to start joiner
False : fail to start joiner""" | print '%s call joinCommissioned' % self . port
cmd = WPANCTL_CMD + 'joiner --start %s %s' % ( strPSKd , self . provisioningUrl )
print cmd
if self . __sendCommand ( cmd ) [ 0 ] != "Fail" :
if self . __getJoinerState ( ) :
self . __sendCommand ( WPANCTL_CMD + 'joiner --attach' )
time . sleep ( 30 )
... |
def SPI_write ( self , chip_select , data ) :
'Writes data to SPI device selected by chipselect bit .' | dat = list ( data )
dat . insert ( 0 , chip_select )
return self . bus . write_i2c_block ( self . address , dat ) ; |
def from_json ( cls , json_obj , variables = None ) :
"""Constructs an Objective from the provided json - object .
Example
> > > import json
> > > with open ( " path _ to _ file . json " ) as infile :
> > > obj = Objective . from _ json ( json . load ( infile ) )""" | if variables is None :
variables = { }
expression = parse_expr ( json_obj [ "expression" ] , variables )
return cls ( expression , direction = json_obj [ "direction" ] , name = json_obj [ "name" ] ) |
def login ( self ) :
"""Logs into Reddit in order to display a personalised front page .""" | data = { 'user' : self . options [ 'username' ] , 'passwd' : self . options [ 'password' ] , 'api_type' : 'json' }
response = self . client . post ( 'http://www.reddit.com/api/login' , data = data )
self . client . modhash = response . json ( ) [ 'json' ] [ 'data' ] [ 'modhash' ] |
def save_any_file ( data , filename ) :
"""Determines a Saver based on the the file extension . Returns whether successfully saved .
: param filename : the name of the file to save
: type filename : str
: param data : the data to save
: type data : Instances
: return : whether successfully saved
: rtype... | saver = saver_for_file ( filename )
if saver is None :
return False
else :
saver . save_file ( data , filename )
return True |
def render_full ( self , request , lodgeit_url = None ) :
"""Render the Full HTML page with the traceback info .""" | app = request . app
root_path = request . app . ps . debugtoolbar . cfg . prefix
exc = escape ( self . exception )
summary = self . render_summary ( include_title = False , request = request )
token = request . app [ 'debugtoolbar' ] [ 'pdbt_token' ]
vars = { 'evalex' : app . ps . debugtoolbar . cfg . intercept_exc == ... |
def get_fd_from_freqtau ( template = None , ** kwargs ) :
"""Return frequency domain ringdown with all the modes specified .
Parameters
template : object
An object that has attached properties . This can be used to substitute
for keyword arguments . A common example would be a row in an xml table .
lmns :... | input_params = props ( template , freqtau_required_args , ** kwargs )
# Get required args
f_0 , tau = lm_freqs_taus ( ** input_params )
lmns = input_params [ 'lmns' ]
for lmn in lmns :
if int ( lmn [ 2 ] ) == 0 :
raise ValueError ( 'Number of overtones (nmodes) must be greater ' 'than zero.' )
# The followi... |
def get_email_context ( self , ** kwargs ) :
'''Overrides EmailRecipientMixin''' | context = super ( Registration , self ) . get_email_context ( ** kwargs )
context . update ( { 'first_name' : self . customer . first_name , 'last_name' : self . customer . last_name , 'registrationComments' : self . comments , 'registrationHowHeardAboutUs' : self . howHeardAboutUs , 'eventList' : [ x . get_email_conte... |
def skip ( self , chars = spaceCharactersBytes ) :
"""Skip past a list of characters""" | p = self . position
# use property for the error - checking
while p < len ( self ) :
c = self [ p : p + 1 ]
if c not in chars :
self . _position = p
return c
p += 1
self . _position = p
return None |
def vm_snapshot_delete ( vm_name , kwargs = None , call = None ) :
'''Deletes a virtual machine snapshot from the provided VM .
. . versionadded : : 2016.3.0
vm _ name
The name of the VM from which to delete the snapshot .
snapshot _ id
The ID of the snapshot to be deleted .
CLI Example :
. . code - b... | if call != 'action' :
raise SaltCloudSystemExit ( 'The vm_snapshot_delete action must be called with -a or --action.' )
if kwargs is None :
kwargs = { }
snapshot_id = kwargs . get ( 'snapshot_id' , None )
if snapshot_id is None :
raise SaltCloudSystemExit ( 'The vm_snapshot_delete function requires a \'snap... |
def mex_hat_dir ( x , y , sigma ) :
r"""Directional Mexican hat
This method implements a directional Mexican hat ( or Ricker ) wavelet .
Parameters
x : float
Input data point for Gaussian
y : float
Input data point for Mexican hat
sigma : float
Standard deviation ( filter scale )
Returns
float d... | x = check_float ( x )
sigma = check_float ( sigma )
return - 0.5 * ( x / sigma ) ** 2 * mex_hat ( y , sigma ) |
def _parse_account_information ( self , rows ) :
"""Parses the character ' s account information
Parameters
rows : : class : ` list ` of : class : ` bs4 . Tag ` , optional
A list of all rows contained in the table .""" | acc_info = { }
if not rows :
return
for row in rows :
cols_raw = row . find_all ( 'td' )
cols = [ ele . text . strip ( ) for ele in cols_raw ]
field , value = cols
field = field . replace ( "\xa0" , "_" ) . replace ( " " , "_" ) . replace ( ":" , "" ) . lower ( )
value = value . replace ( "\xa0"... |
def iterdupes ( self , compare = None , filt = None ) :
'''streaming item iterator with low overhead duplicate file detection
Parameters :
- compare compare function between files ( defaults to md5sum )''' | if not compare :
compare = self . md5sum
seen_siz = { }
# # store size - > first seen filename
seen_sum = { }
# # store chksum - > first seen filename
size_func = lambda x : os . stat ( x ) . st_size
for ( fsize , f ) in self . iteritems ( want_dirs = False , func = size_func , filt = filt ) :
if fsize not in s... |
def _dt_to_epoch_ns ( dt_series ) :
"""Convert a timeseries into an Int64Index of nanoseconds since the epoch .
Parameters
dt _ series : pd . Series
The timeseries to convert .
Returns
idx : pd . Int64Index
The index converted to nanoseconds since the epoch .""" | index = pd . to_datetime ( dt_series . values )
if index . tzinfo is None :
index = index . tz_localize ( 'UTC' )
else :
index = index . tz_convert ( 'UTC' )
return index . view ( np . int64 ) |
def delete_hook ( self , auth , username , repo_name , hook_id ) :
"""Deletes the hook with id ` ` hook _ id ` ` for repo with name ` ` repo _ name ` `
owned by the user with username ` ` username ` ` .
: param auth . Authentication auth : authentication object
: param str username : username of owner of repo... | path = "/repos/{u}/{r}/hooks/{i}" . format ( u = username , r = repo_name , i = hook_id )
self . delete ( path , auth = auth ) |
def create_widget ( self ) :
"""Create the underlying label widget .""" | d = self . declaration
self . widget = View ( self . get_context ( ) , None , d . style ) |
def adjoint ( self ) :
"""Adjoint operator represented by the adjoint matrix .
Returns
adjoint : ` MatrixOperator `""" | return MatrixOperator ( self . matrix . conj ( ) . T , domain = self . range , range = self . domain , axis = self . axis ) |
def couldChangeLane ( self , vehID , direction ) :
"""couldChangeLane ( string , int ) - > bool
Return whether the vehicle could change lanes in the specified direction""" | state = self . getLaneChangeState ( vehID , direction ) [ 0 ]
return state != tc . LCA_UNKNOWN and ( state & tc . LCA_BLOCKED == 0 ) |
def get_context ( self , request , page , ** kwargs ) :
"""Include in context items to be visible on listing page""" | context = super ( ListingPagePlugin , self ) . get_context ( request , page , ** kwargs )
context [ 'items_to_list' ] = page . get_items_to_list ( request )
return context |
def _hugoniot_p ( self , v ) :
"""calculate static pressure at 300 K .
: param v : unit - cell volume in A ^ 3
: return : static pressure at t _ ref ( = 300 K ) in GPa""" | rho = self . _get_rho ( v )
params = self . _set_params ( self . params_hugoniot )
if self . nonlinear :
return hugoniot_p_nlin ( rho , * params )
else :
return hugoniot_p ( rho , * params ) |
def _make_decorator ( measuring_func ) :
"""morass of closures for making decorators / descriptors""" | def _decorator ( name = None , metric = call_default ) :
def wrapper ( func ) :
name_ = name if name is not None else func . __module__ + '.' + func . __name__
class instrument_decorator ( object ) : # must be a class for descriptor magic to work
@ wraps ( func )
def __call__... |
def _find_items ( self , paths , processor , include_toplevel = False , include_children = False , recurse = False , check_nonexistence = False ) :
'''Request file info from the NameNode and call the processor on the node ( s ) returned
: param paths :
A list of paths that need to be processed
: param process... | if not paths :
paths = [ posixpath . join ( "/user" , get_current_username ( ) ) ]
# Expand paths if necessary ( / foo / { bar , baz } - - > [ ' / foo / bar ' , ' / foo / baz ' ] )
paths = glob . expand_paths ( paths )
for path in paths :
if not path . startswith ( "/" ) :
path = self . _join_user_path ... |
def get_compositions_by_ids ( self , composition_ids ) :
"""Gets a ` ` CompositionList ` ` corresponding to the given ` ` IdList ` ` .
arg : composition _ ids ( osid . id . IdList ) : the list of ` ` Ids ` ` to
retrieve
return : ( osid . repository . CompositionList ) - the returned
` ` Composition list ` `... | # Implemented from template for
# osid . resource . ResourceLookupSession . get _ resources _ by _ ids
# NOTE : This implementation currently ignores plenary view
collection = JSONClientValidated ( 'repository' , collection = 'Composition' , runtime = self . _runtime )
object_id_list = [ ]
for i in composition_ids :
... |
def probe_dtz ( self , board : chess . Board ) -> int :
"""Probes DTZ tables for distance to zero information .
Both DTZ and WDL tables are required in order to probe for DTZ .
Returns a positive value if the side to move is winning , ` ` 0 ` ` if the
position is a draw and a negative value if the side to mov... | v = self . probe_dtz_no_ep ( board )
if not board . ep_square or self . variant . captures_compulsory :
return v
v1 = - 3
# Generate all en - passant moves .
for move in board . generate_legal_ep ( ) :
board . push ( move )
try :
v0_plus , _ = self . probe_ab ( board , - 2 , 2 )
v0 = - v0_pl... |
def get_function_hash ( self , func , args = None , kwargs = None , ttl = None , key = None , noc = None ) :
"""Compute the hash of the function to be evaluated .""" | base_hash = settings . HASH_FUNCTION ( )
if PY3 :
base_hash . update ( func . __name__ . encode ( settings . DEFAULT_ENCODING ) )
else :
base_hash . update ( func . __name__ )
if args :
for a in args :
if PY3 :
base_hash . update ( repr ( a ) . encode ( settings . DEFAULT_ENCODING ) )
... |
def _ReadCharacterDataTypeDefinition ( self , definitions_registry , definition_values , definition_name , is_member = False ) :
"""Reads a character data type definition .
Args :
definitions _ registry ( DataTypeDefinitionsRegistry ) : data type definitions
registry .
definition _ values ( dict [ str , obj... | return self . _ReadFixedSizeDataTypeDefinition ( definitions_registry , definition_values , data_types . CharacterDefinition , definition_name , self . _SUPPORTED_ATTRIBUTES_FIXED_SIZE_DATA_TYPE , is_member = is_member , supported_size_values = ( 1 , 2 , 4 ) ) |
def get_dependency ( self , worker_ctx ) :
"""Inject a dispatch method onto the service instance""" | extra_headers = self . get_message_headers ( worker_ctx )
def dispatch ( event_type , event_data ) :
self . publisher . publish ( event_data , exchange = self . exchange , routing_key = event_type , extra_headers = extra_headers )
return dispatch |
def outfiles ( markov , fmt , nfiles , progress , start = 0 ) :
"""Get output file paths .
Parameters
markov : ` markovchain . base . MarkovBase `
Markov chain generator .
fmt : ` str `
File path format string .
nfiles : ` int `
Number of files .
progress : ` bool `
Show progress bars .
start : ... | pbar = None
channels = markov . imgtype . channels
tr = markov . scanner . traversal
if progress and not isinstance ( tr [ 0 ] , TraversalProgressWrapper ) :
tr [ 0 ] = TraversalProgressWrapper ( tr [ 0 ] , channels )
tr = tr [ 0 ]
try :
with _outfiles ( fmt , nfiles , progress ) as fnames :
for fname i... |
def static ( self , uri , file_or_directory , * args , ** kwargs ) :
"""Create a websocket route from a decorated function
: param uri : endpoint at which the socket endpoint will be accessible .
: type uri : str
: param args : captures all of the positional arguments passed in
: type args : tuple ( Any )
... | kwargs . setdefault ( 'pattern' , r'/?.+' )
kwargs . setdefault ( 'use_modified_since' , True )
kwargs . setdefault ( 'use_content_range' , False )
kwargs . setdefault ( 'stream_large_files' , False )
kwargs . setdefault ( 'name' , 'static' )
kwargs . setdefault ( 'host' , None )
kwargs . setdefault ( 'strict_slashes' ... |
def delete_namespaced_ingress ( self , name , namespace , ** kwargs ) :
"""delete an Ingress
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ namespaced _ ingress ( name , namespace , async _ req = Tru... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_namespaced_ingress_with_http_info ( name , namespace , ** kwargs )
else :
( data ) = self . delete_namespaced_ingress_with_http_info ( name , namespace , ** kwargs )
return data |
def read_index ( self , fh , indexed_fh , rec_iterator = None , rec_hash_func = None , parse_hash = str , flush = True , no_reindex = True , verbose = False ) :
"""Populate this index from a file . Input format is just a tab - separated file ,
one record per line . The last column is the file location for the rec... | # set the record iterator and hash functions , if they were given
if rec_iterator is not None :
self . record_iterator = rec_iterator
if rec_hash_func is not None :
self . record_hash_function = rec_hash_func
# disable re - indexing ?
self . _no_reindex = no_reindex
# figure out what kind of index identifier we... |
def activate_status_output_activate_entries_status ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
activate_status = ET . Element ( "activate_status" )
config = activate_status
output = ET . SubElement ( activate_status , "output" )
activate_entries = ET . SubElement ( output , "activate-entries" )
status = ET . SubElement ( activate_entries , "status" )
status . text = kwargs . po... |
def subplots ( scale_x = None , scale_y = None , scale = None , ** kwargs ) :
r'''Run ` ` matplotlib . pyplot . subplots ` ` with ` ` figsize ` ` set to the correct multiple of the default .
: additional options :
* * scale , scale _ x , scale _ y * * ( ` ` < float > ` ` )
Scale the figure - size ( along one ... | if 'figsize' in kwargs :
return plt . subplots ( ** kwargs )
width , height = mpl . rcParams [ 'figure.figsize' ]
if scale is not None :
width *= scale
height *= scale
if scale_x is not None :
width *= scale_x
if scale_y is not None :
height *= scale_y
nrows = kwargs . pop ( 'nrows' , 1 )
ncols = kw... |
def mainloop ( self ) :
"""The main loop .""" | # proxy = config . engine . open ( )
if len ( self . args ) != 3 :
self . fatal ( "You MUST provide names for index (row), column, and value!" )
# Load data
df = pd . read_json ( sys . stdin , orient = 'records' )
df [ self . args [ 0 ] ] = df [ self . args [ 0 ] ] . str . slice ( 0 , 42 )
# print ( df [ self . arg... |
def get_history ( self , symbols , start , end = None , resolution = "1T" , tz = "UTC" ) :
"""Get historical market data .
Connects to Blotter and gets historical data from storage
: Parameters :
symbols : list
List of symbols to fetch history for
start : datetime / string
History time period start date... | return self . blotter . history ( symbols , start , end , resolution , tz ) |
def send_markdown ( self , agent_id , user_ids , content , party_ids = '' , tag_ids = '' ) :
"""markdown消息
https : / / work . weixin . qq . com / api / doc # 90000/90135/90236 / markdown % E6 % B6%88 % E6%81 % AF
> 目前仅支持markdown语法的子集
> 微工作台 ( 原企业号 ) 不支持展示markdown消息
: param agent _ id : 企业应用的id , 整型 。 可在应用的设... | msg = { "msgtype" : "markdown" , "markdown" : { "content" : content } }
return self . _send_message ( agent_id = agent_id , user_ids = user_ids , party_ids = party_ids , tag_ids = tag_ids , msg = msg ) |
def find_root ( self , rows ) :
"""Attempt to find / create a reasonable root node from list / set of rows
rows - - key : PStatRow mapping
TODO : still need more robustness here , particularly in the case of
threaded programs . Should be tracing back each row to root , breaking
cycles by sorting on cumulati... | maxes = sorted ( rows . values ( ) , key = lambda x : x . cumulative )
if not maxes :
raise RuntimeError ( """Null results!""" )
root = maxes [ - 1 ]
roots = [ root ]
for key , value in rows . items ( ) :
if not value . parents :
log . debug ( 'Found node root: %s' , value )
if value not in root... |
def _set_bearer_user_vars_local ( token , allowed_client_ids , scopes ) :
"""Validate the oauth bearer token on the dev server .
Since the functions in the oauth module return only example results in local
development , this hits the tokeninfo endpoint and attempts to validate the
token . If it ' s valid , we... | # Get token info from the tokeninfo endpoint .
result = urlfetch . fetch ( '%s?%s' % ( _TOKENINFO_URL , urllib . urlencode ( { 'access_token' : token } ) ) )
if result . status_code != 200 :
try :
error_description = json . loads ( result . content ) [ 'error_description' ]
except ( ValueError , KeyErro... |
def import_metadata ( self , elements ) :
"""Import information from GPX metadata .
Args :
elements ( etree . Element ) : GPX metadata subtree""" | metadata_elem = lambda name : etree . QName ( GPX_NS , name )
for child in elements . getchildren ( ) :
tag_ns , tag_name = child . tag [ 1 : ] . split ( '}' )
if not tag_ns == GPX_NS :
continue
if tag_name in ( 'name' , 'desc' , 'keywords' ) :
setattr ( self , tag_name , child . text )
... |
def _get_select_commands ( self , source , tables ) :
"""Create select queries for all of the tables from a source database .
: param source : Source database name
: param tables : Iterable of table names
: return : Dictionary of table keys , command values""" | # Create dictionary of select queries
row_queries = { tbl : self . select_all ( tbl , execute = False ) for tbl in tqdm ( tables , total = len ( tables ) , desc = 'Getting {0} select queries' . format ( source ) ) }
# Convert command strings into lists of commands
for tbl , command in row_queries . items ( ) :
if i... |
def load ( self , filename ) :
"""Load a result from the given JSON file .""" | LOGGER . info ( "Loading result from '%s'." , filename )
if filename . endswith ( ".gz" ) :
with gzip . open ( filename , "rb" ) as file_handle :
result = MemoteResult ( json . loads ( file_handle . read ( ) . decode ( "utf-8" ) ) )
else :
with open ( filename , "r" , encoding = "utf-8" ) as file_handle... |
async def monitor_start ( self , monitor ) :
'''Create the socket listening to the ` ` bind ` ` address .
If the platform does not support multiprocessing sockets set the
number of workers to 0.''' | cfg = self . cfg
if ( not platform . has_multiprocessing_socket or cfg . concurrency == 'thread' ) :
cfg . set ( 'workers' , 0 )
servers = await self . binds ( monitor )
if not servers :
raise ImproperlyConfigured ( 'Could not open a socket. ' 'No address to bind to' )
addresses = [ ]
for server in servers . va... |
def init ( self ) :
"""Init the connection to the InfluxDB server .""" | if not self . export_enable :
return None
try :
db = InfluxDBClient ( host = self . host , port = self . port , username = self . user , password = self . password , database = self . db )
get_all_db = [ i [ 'name' ] for i in db . get_list_database ( ) ]
except InfluxDBClientError as e :
logger . critic... |
def query_ssos ( self ) :
"""Use the MPC file that has been built up in processing this work
unit to generate another workunit .""" | self . _ssos_queried = True
mpc_filename = self . save ( )
return self . builder . build_workunit ( mpc_filename ) |
def close ( self ) :
"""close the interface""" | logging . debug ( "closing interface" )
self . closed = True
self . read_sem . release ( )
self . thread . join ( )
usb . util . dispose_resources ( self . dev ) |
def unblock ( self , event ) :
'''Remove a block''' | if event not in self . blockEvents :
return
self . blockEvents [ event ] . unblock ( event )
del self . blockEvents [ event ] |
def toImage ( self , array , origin = "" ) :
"""Converts an array with metadata to a two - dimensional image .
: param ` numpy . ndarray ` array : The array to convert to image .
: param str origin : Path to the image , optional .
: return : a : class : ` Row ` that is a two dimensional image .
. . versiona... | if not isinstance ( array , np . ndarray ) :
raise TypeError ( "array argument should be numpy.ndarray; however, it got [%s]." % type ( array ) )
if array . ndim != 3 :
raise ValueError ( "Invalid array shape" )
height , width , nChannels = array . shape
ocvTypes = ImageSchema . ocvTypes
if nChannels == 1 :
... |
def _rest_request_to_json ( self , address , auth , ssl_verify , object_path , service_name , tags = None , * args , ** kwargs ) :
"""Query the given URL and return the JSON response""" | response_json = None
tags = [ ] if tags is None else tags
service_check_tags = [ 'url:{}' . format ( self . _get_url_base ( address ) ) ] + tags
url = address
if object_path :
url = self . _join_url_dir ( url , object_path )
# Add args to the url
if args :
for directory in args :
url = self . _join_url_... |
def kernel_image ( self , kernel_image ) :
"""Sets the kernel image path for this QEMU VM .
: param kernel _ image : QEMU kernel image path""" | kernel_image = self . manager . get_abs_image_path ( kernel_image )
log . info ( 'QEMU VM "{name}" [{id}] has set the QEMU kernel image path to {kernel_image}' . format ( name = self . _name , id = self . _id , kernel_image = kernel_image ) )
self . _kernel_image = kernel_image |
def solvedbd_sm ( ah , d , b , c = None , axis = 4 ) :
r"""Solve a diagonal block linear system with a diagonal term
using the Sherman - Morrison equation .
The solution is obtained by independently solving a set of linear
systems of the form ( see : cite : ` wohlberg - 2016 - efficient ` )
. . math : :
(... | a = np . conj ( ah )
if c is None :
c = solvedbd_sm_c ( ah , a , d , axis )
if have_numexpr :
cb = inner ( c , b , axis = axis )
return ne . evaluate ( '(b - (a * cb)) / d' )
else :
return ( b - ( a * inner ( c , b , axis = axis ) ) ) / d |
def OnSearchDirectionButton ( self , event ) :
"""Event handler for search direction toggle button""" | if "DOWN" in self . search_options :
flag_index = self . search_options . index ( "DOWN" )
self . search_options [ flag_index ] = "UP"
elif "UP" in self . search_options :
flag_index = self . search_options . index ( "UP" )
self . search_options [ flag_index ] = "DOWN"
else :
raise AttributeError ( ... |
def geosgeometry_str_to_struct ( value ) :
'''Parses a geosgeometry string into struct .
Example :
SRID = 5432 ; POINT ( 12.0 13.0)
Returns :
> > [ 5432 , 12.0 , 13.0]''' | result = geos_ptrn . match ( value )
if not result :
return None
return { 'srid' : result . group ( 1 ) , 'x' : result . group ( 2 ) , 'y' : result . group ( 3 ) , } |
def refresh ( self , ** kwargs ) :
"""Refreshes the plot by rerendering it and then pushing
the updated data if the plot has an associated Comm .""" | traverse_setter ( self , '_force' , True )
key = self . current_key if self . current_key else self . keys [ 0 ]
dim_streams = [ stream for stream in self . streams if any ( c in self . dimensions for c in stream . contents ) ]
stream_params = stream_parameters ( dim_streams )
key = tuple ( None if d in stream_params e... |
def save_user_config ( username , conf_dict , path = settings . LOGIN_FILE ) :
"""Save user ' s configuration to otherwise unused field ` ` full _ name ` ` in passwd
file .""" | users = load_users ( path = path )
users [ username ] [ "full_name" ] = _encode_config ( conf_dict )
save_users ( users , path = path ) |
def add_header ( self , name , value ) :
'''Attach an email header to send with the message .
: param name : The name of the header value .
: param value : The header value .''' | if self . headers is None :
self . headers = [ ]
self . headers . append ( dict ( Name = name , Value = value ) ) |
def connect ( self , driver ) :
"""Connect using the SSH protocol specific FSM .""" | # 0 1 2
events = [ driver . password_re , self . device . prompt_re , driver . unable_to_connect_re , # 3 4 5 6 7
NEWSSHKEY , KNOWN_HOSTS , HOST_KEY_FAILED , MODULUS_TOO_SMALL , PROTOCOL_DIFFER , # 8 9 10
driver . timeout_re , pexpect . TIMEOUT , driver . syntax_error_re ]
transitions = [ ( driver . password_re , [ 0 ,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.