signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_fragment ( self , list_of_indextuples , give_only_index = False , use_lookup = None ) :
"""Get the indices of the atoms in a fragment .
The list _ of _ indextuples contains all bondings from the
molecule to the fragment . ` ` [ ( 1,3 ) , ( 2,4 ) ] ` ` means for example that the
fragment is connected o... | if use_lookup is None :
use_lookup = settings [ 'defaults' ] [ 'use_lookup' ]
exclude = [ tuple [ 0 ] for tuple in list_of_indextuples ]
index_of_atom = list_of_indextuples [ 0 ] [ 1 ]
fragment_index = self . get_coordination_sphere ( index_of_atom , exclude = set ( exclude ) , n_sphere = float ( 'inf' ) , only_sur... |
def set_rate ( rate ) :
"""Defines the ideal rate at which computation is to be performed
: arg rate : the frequency in Hertz
: type rate : int or float
: raises : TypeError : if argument ' rate ' is not int or float""" | if not ( isinstance ( rate , int ) or isinstance ( rate , float ) ) :
raise TypeError ( "argument to set_rate is expected to be int or float" )
global loop_duration
loop_duration = 1.0 / rate |
def get_calls ( self , job_name ) :
'''Reads file by given name and returns CallEdge array''' | config = self . file_index . get_by_name ( job_name ) . yaml
calls = self . get_calls_from_dict ( config , from_name = job_name )
return calls |
def attr_to_dict ( obj , attr , dct ) :
"""Add attribute to dict if it exists .
: param dct :
: param obj : object
: param attr : object attribute name
: return : dict""" | if hasattr ( obj , attr ) :
dct [ attr ] = getattr ( obj , attr )
return dct |
def change_email ( self , old_email , new_email ) :
"""Changes the email of the current account
: param old _ email : The current email
: param new _ email : The new email to set""" | log . info ( "[+] Changing account email to '{}'" . format ( new_email ) )
return self . _send_xmpp_element ( account . ChangeEmailRequest ( self . password , old_email , new_email ) ) |
def angles ( self ) -> Tuple [ float ] :
"""Returns the angles ( alpha , beta , gamma ) of the lattice .""" | m = self . _matrix
lengths = self . lengths
angles = np . zeros ( 3 )
for i in range ( 3 ) :
j = ( i + 1 ) % 3
k = ( i + 2 ) % 3
angles [ i ] = abs_cap ( dot ( m [ j ] , m [ k ] ) / ( lengths [ j ] * lengths [ k ] ) )
angles = np . arccos ( angles ) * 180.0 / pi
return tuple ( angles . tolist ( ) ) |
def database_list_folder ( object_id , input_params = { } , always_retry = True , ** kwargs ) :
"""Invokes the / database - xxxx / listFolder API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Databases # API - method % 3A - % 2Fdatabase - xxxx % 2FlistFolder""" | return DXHTTPRequest ( '/%s/listFolder' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def dimensionless_contents ( streams , kdims , no_duplicates = True ) :
"""Return a list of stream parameters that have not been associated
with any of the key dimensions .""" | names = stream_parameters ( streams , no_duplicates )
return [ name for name in names if name not in kdims ] |
def loads ( self , config , content , prefer = None ) :
"""An abstract loads method which loads an instance from some content .
: param class config : The config class to load into
: param str content : The content to load from
: param str prefer : The preferred serialization module name
: raises ValueError... | loader = self . _prefer_package ( prefer )
loads_hook_name = f"on_{loader}_loads"
loads_hook = getattr ( self , loads_hook_name , None )
if not callable ( loads_hook ) :
raise ValueError ( f"no loads handler for {self.imported!r}, requires method " f"{loads_hook_name!r} in {self!r}" )
return loads_hook ( self . han... |
def has_obstory_metadata ( self , status_id ) :
"""Check for the presence of the given metadata item
: param string status _ id :
The metadata item ID
: return :
True if we have a metadata item with this ID , False otherwise""" | self . con . execute ( 'SELECT 1 FROM archive_metadata WHERE publicId=%s;' , ( status_id , ) )
return len ( self . con . fetchall ( ) ) > 0 |
def run ( configobj = None ) :
"""TEAL interface for the ` acscteforwardmodel ` function .""" | acscteforwardmodel ( configobj [ 'input' ] , exec_path = configobj [ 'exec_path' ] , time_stamps = configobj [ 'time_stamps' ] , verbose = configobj [ 'verbose' ] , quiet = configobj [ 'quiet' ] , single_core = configobj [ 'single_core' ] ) |
def _read_protos ( self , size ) :
"""Read next layer protocol type .
Positional arguments :
* size - - int , buffer size
Returns :
* str - - next layer ' s protocol name""" | _byte = self . _read_unpack ( size )
_prot = ETHERTYPE . get ( _byte )
return _prot |
def check_diag ( self , jac , name ) :
"""Check matrix ` ` jac ` ` for diagonal elements that equals 0""" | system = self . system
pos = [ ]
names = [ ]
pairs = ''
size = jac . size
diag = jac [ 0 : size [ 0 ] ** 2 : size [ 0 ] + 1 ]
for idx in range ( size [ 0 ] ) :
if abs ( diag [ idx ] ) <= 1e-8 :
pos . append ( idx )
for idx in pos :
names . append ( system . varname . __dict__ [ name ] [ idx ] )
if len (... |
def _digits ( minval , maxval ) :
"""Digits needed to comforatbly display values in [ minval , maxval ]""" | if minval == maxval :
return 3
else :
return min ( 10 , max ( 2 , int ( 1 + abs ( np . log10 ( maxval - minval ) ) ) ) ) |
def _is_node_an_element ( self , node ) :
"""Return True if the given node is an ElementTree Element , a fact that
can be tricky to determine if the cElementTree implementation is
used .""" | # Try the simplest approach first , works for plain old ElementTree
if isinstance ( node , BaseET . Element ) :
return True
# For cElementTree we need to be more cunning ( or find a better way )
if hasattr ( node , 'makeelement' ) and isinstance ( node . tag , basestring ) :
return True |
def _read_stderr ( self ) :
'''Continuously read stderr for error messages .''' | try :
while self . _process . returncode is None :
line = yield from self . _process . stderr . readline ( )
if not line :
break
if self . _stderr_callback :
yield from self . _stderr_callback ( line )
except Exception :
_logger . exception ( 'Unhandled read stder... |
def do_db ( self , arg ) :
"""[ ~ thread ] db < register > - show memory contents as bytes
[ ~ thread ] db < register - register > - show memory contents as bytes
[ ~ thread ] db < register > < size > - show memory contents as bytes
[ ~ process ] db < address > - show memory contents as bytes
[ ~ process ] ... | self . print_memory_display ( arg , HexDump . hexblock )
self . last_display_command = self . do_db |
def print_all ( self ) :
""": return :""" | output = "\n\n# Git information \n" "-------------------------------------------\n" " Branch :\t{0}\n" " Version:\t{1}\n" " Summary:\t{2}\n" "-------------------------------------------\n\n" . format ( self . get_branch ( ) , str ( self . get_version ( ) ) , self . repo . commit ( ) . summary , )
print ( output ) |
def create_image ( self , df_dir_path , image , use_cache = False ) :
"""create image : get atomic - reactor sdist tarball , build image and tag it
: param df _ path :
: param image :
: return :""" | logger . debug ( "creating build image: df_dir_path = '%s', image = '%s'" , df_dir_path , image )
if not os . path . isdir ( df_dir_path ) :
raise RuntimeError ( "Directory '%s' does not exist." % df_dir_path )
tmpdir = tempfile . mkdtemp ( )
df_tmpdir = os . path . join ( tmpdir , 'df-%s' % uuid . uuid4 ( ) )
git_... |
import re
def swap_whitespace_and_underscore ( input_string ) :
"""This function replaces whitespaces in a string with underscores and vice versa using regular expressions .
Examples :
swap _ whitespace _ and _ underscore ( ' Jumanji The Jungle ' ) - > ' Jumanji _ The _ Jungle '
swap _ whitespace _ and _ unde... | if " " in input_string :
return re . sub ( ' ' , '_' , input_string )
else :
return re . sub ( '_' , ' ' , input_string ) |
def selectPeerToIntroduce ( self , otherPeers ) :
"""Choose a peer to introduce . Return a q2q address or None , if there are
no suitable peers to introduce at this time .""" | for peer in otherPeers :
if peer not in self . otherPeers :
self . otherPeers . append ( peer )
return peer |
def list ( self , status = values . unset , unique_name = values . unset , date_created_after = values . unset , date_created_before = values . unset , limit = None , page_size = None ) :
"""Lists RoomInstance records from the API as a list .
Unlike stream ( ) , this operation is eager and will load ` limit ` rec... | return list ( self . stream ( status = status , unique_name = unique_name , date_created_after = date_created_after , date_created_before = date_created_before , limit = limit , page_size = page_size , ) ) |
def related_domains ( self , domains ) :
"""Get list of domain names that have been seen requested around the
same time ( up to 60 seconds before or after ) to the given domain name .
Args :
domains : an enumerable of strings domain names
Returns :
An enumerable of [ domain name , scores ]""" | api_name = 'opendns-related_domains'
fmt_url_path = u'links/name/{0}.json'
return self . _multi_get ( api_name , fmt_url_path , domains ) |
def recursive_replace ( list_ , target , repl = - 1 ) :
r"""Recursively removes target in all lists and sublists and replaces them with
the repl variable""" | repl_list = [ recursive_replace ( item , target , repl ) if isinstance ( item , ( list , np . ndarray ) ) else ( repl if item == target else item ) for item in list_ ]
return repl_list |
def __xd_iterator_pass_on ( arr , view , fun ) :
"""Like xd _ iterator , but the fun return values are always passed on to the next and only the last returned .""" | # create list of iterations
iterations = [ [ None ] if dim in view else list ( range ( arr . shape [ dim ] ) ) for dim in range ( arr . ndim ) ]
# iterate , create slicer , execute function and collect results
passon = None
for indices in itertools . product ( * iterations ) :
slicer = [ slice ( None ) if idx is No... |
def setup_logger ( logger = None , level = 'INFO' ) :
"""Setup logging for CLI use .
Tries to do some conditionals to prevent handlers from being added twice .
Just to be safe .
Parameters
logger : : py : class : ` Logger `
logger instance for tmuxp""" | if not logger : # if no logger exists , make one
logger = logging . getLogger ( )
if not logger . handlers : # setup logger handlers
channel = logging . StreamHandler ( )
channel . setFormatter ( log . DebugLogFormatter ( ) )
# channel . setFormatter ( log . LogFormatter ( ) )
logger . setLevel ( le... |
def static ( self , max_steps , step_size ) :
"""Set Back - off to Static
Set the sampler parameters for static back off
Inputs :
max _ steps :
maximum optimization steps to be taken
step _ size :
the step size of the back - off""" | self . _dynamic = False
# begin checks
try :
self . _max_steps = int ( max_steps )
except :
print ( "Error: Input 1 (max_steps) has to be an int." )
return 0
try :
assert self . _max_steps >= 0
except :
print ( "Warning: Input 1 (max_steps) has to be non-negative." )
print ( "Setting max_steps t... |
def getmtime ( self , filepath ) :
"""Gets the last time that the file was modified .""" | if self . is_ssh ( filepath ) :
self . _check_ftp ( )
source = self . _get_remote ( filepath )
mtime = self . ftp . stat ( source ) . st_mtime
else :
mtime = os . path . getmtime ( filepath )
return mtime |
def element_should_be_visible ( self , locator , loglevel = 'INFO' ) :
"""Verifies that element identified with locator is visible .
Key attributes for arbitrary elements are ` id ` and ` name ` . See
` introduction ` for details about locating elements .
New in AppiumLibrary 1.4.5""" | if not self . _element_find ( locator , True , True ) . is_displayed ( ) :
self . log_source ( loglevel )
raise AssertionError ( "Element '%s' should be visible " "but did not" % locator ) |
def shapeexprlabel_to_IRI ( self , shapeExprLabel : ShExDocParser . ShapeExprLabelContext ) -> Union [ ShExJ . BNODE , ShExJ . IRIREF ] :
"""shapeExprLabel : iri | blankNode""" | if shapeExprLabel . iri ( ) :
return self . iri_to_iriref ( shapeExprLabel . iri ( ) )
else :
return ShExJ . BNODE ( shapeExprLabel . blankNode ( ) . getText ( ) ) |
def update_status ( self , reset = False ) :
"""Update device status .""" | if self . healthy_update_timer and not reset :
return
# get device features only once
if not self . device_features :
self . handle_features ( self . get_features ( ) )
# Get status from device to register / keep alive UDP
self . handle_status ( )
# Schedule next execution
self . setup_update_timer ( ) |
def pauli_string ( self , qubits = None ) :
"""Return a string representation of this PauliTerm without its coefficient and with
implicit qubit indices .
If a list of qubits is provided , each character in the resulting string represents
a Pauli operator on the corresponding qubit . If qubit indices are not p... | if qubits is None :
warnings . warn ( "Please provide a list of qubits when using PauliTerm.pauli_string" , DeprecationWarning )
qubits = self . get_qubits ( )
return '' . join ( self [ q ] for q in qubits ) |
def decrypt ( v , key = None , keyfile = None ) :
"""Encrypt an string""" | cipher = functions . get_cipher ( key , keyfile )
return cipher . decrypt ( v ) |
def accept_token ( self , require_token = False , scopes_required = None , render_errors = True ) :
"""Use this to decorate view functions that should accept OAuth2 tokens ,
this will most likely apply to API functions .
Tokens are accepted as part of the query URL ( access _ token value ) or
a POST form valu... | def wrapper ( view_func ) :
@ wraps ( view_func )
def decorated ( * args , ** kwargs ) :
token = None
if 'Authorization' in request . headers and request . headers [ 'Authorization' ] . startswith ( 'Bearer ' ) :
token = request . headers [ 'Authorization' ] . split ( None , 1 ) [ 1 ... |
def create_database ( destroy_existing = False ) :
"""Create db and tables if it doesn ' t exist""" | if not os . path . exists ( DB_NAME ) :
logger . info ( 'Create database: {0}' . format ( DB_NAME ) )
open ( DB_NAME , 'a' ) . close ( )
Show . create_table ( )
Episode . create_table ( )
Setting . create_table ( ) |
def entry_point ( ) :
"""The entry that CLI is executed from""" | try :
provider_group_factory ( )
notifiers_cli ( obj = { } )
except NotifierException as e :
click . secho ( f"ERROR: {e.message}" , bold = True , fg = "red" )
exit ( 1 ) |
def disconnect_async ( self , conn_id , callback ) :
"""Asynchronously disconnect from a device that has previously been connected
Args :
conn _ id ( int ) : a unique identifier for this connection on the DeviceManager
that owns this adapter .
callback ( callable ) : A function called as callback ( conn _ i... | try :
context = self . conns . get_context ( conn_id )
except ArgumentError :
callback ( conn_id , self . id , False , "Could not find connection information" )
return
self . conns . begin_disconnection ( conn_id , callback , self . get_config ( 'default_timeout' ) )
topics = context [ 'topics' ]
disconn_me... |
def _encode_msg ( self , start_pos , offset , timestamp , key , value , attributes = 0 ) :
"""Encode msg data into the ` msg _ buffer ` , which should be allocated
to at least the size of this message .""" | magic = self . _magic
buf = self . _buffer
pos = start_pos
# Write key and value
pos += self . KEY_OFFSET_V0 if magic == 0 else self . KEY_OFFSET_V1
if key is None :
struct . pack_into ( ">i" , buf , pos , - 1 )
pos += self . KEY_LENGTH
else :
key_size = len ( key )
struct . pack_into ( ">i" , buf , pos... |
def get ( self , project_name , updatetime = None , md5sum = None ) :
'''get project data object , return None if not exists''' | if time . time ( ) - self . last_check_projects > self . CHECK_PROJECTS_INTERVAL :
self . _check_projects ( )
if self . _need_update ( project_name , updatetime , md5sum ) :
self . _update_project ( project_name )
return self . projects . get ( project_name , None ) |
def interpolate ( G , f_subsampled , keep_inds , order = 100 , reg_eps = 0.005 , ** kwargs ) :
r"""Interpolate a graph signal .
Parameters
G : Graph
f _ subsampled : ndarray
A graph signal on the graph G .
keep _ inds : ndarray
List of indices on which the signal is sampled .
order : int
Degree of t... | L_reg = G . L + reg_eps * sparse . eye ( G . N )
K_reg = getattr ( G . mr , 'K_reg' , kron_reduction ( L_reg , keep_inds ) )
green_kernel = getattr ( G . mr , 'green_kernel' , filters . Filter ( G , lambda x : 1. / ( reg_eps + x ) ) )
alpha = K_reg . dot ( f_subsampled )
try :
Nv = np . shape ( f_subsampled ) [ 1 ]... |
def _netstat_bsd ( ) :
'''Return netstat information for BSD flavors''' | ret = [ ]
if __grains__ [ 'kernel' ] == 'NetBSD' :
for addr_family in ( 'inet' , 'inet6' ) :
cmd = 'netstat -f {0} -an | tail -n+3' . format ( addr_family )
out = __salt__ [ 'cmd.run' ] ( cmd , python_shell = True )
for line in out . splitlines ( ) :
comps = line . split ( )
... |
def copy ( self ) :
"""Return a shallow copy .""" | return self . __class__ ( self . operations . copy ( ) , self . collection , self . document ) |
def transaction_type ( self , value ) :
"""Set the TransactionType ( with Input Validation )""" | if value is not None :
if value not in self . ALLOWED_TRANSACTION_TYPES :
raise AttributeError ( '%s transaction_type element must be one of %s not %s' % ( self . __class__ . __name__ , ',' . join ( self . ALLOWED_TRANSACTION_TYPES ) , value , ) )
self . _transaction_type = value |
def _list_records ( self , rtype = None , name = None , content = None ) :
"""List all records .
record _ type , name and content are used to filter the records .
If possible it filters during the query , otherwise afterwards .
An empty list is returned if no records are found .""" | filter_query = { }
if rtype :
filter_query [ "record_type" ] = rtype
if name :
name = self . _relative_name ( name )
filter_query [ "name" ] = name
payload = self . _get ( "/v1/domains/{0}/records" . format ( self . domain ) , query_params = filter_query , )
records = [ ]
for data in payload :
record = ... |
def print_success ( msg ) :
"""Print a warning message""" | if IS_POSIX :
print ( u"%s[INFO] %s%s" % ( ANSI_OK , msg , ANSI_END ) )
else :
print ( u"[INFO] %s" % ( msg ) ) |
def addIndex ( self , index ) :
"""Adds the inputted index to this table schema .
: param index | < orb . Index >""" | index . setSchema ( self )
self . __indexes [ index . name ( ) ] = index |
def population_observer ( population , num_generations , num_evaluations , args ) :
"""Print the current population of the evolutionary computation to the screen .
This function displays the current population of the evolutionary
computation to the screen in fitness - sorted order .
. . Arguments :
populati... | population . sort ( reverse = True )
print ( '----------------------------------------------------------------------------' )
print ( ' Current Population' )
print ( '----------------------------------------------------------------------------' )
for ind in population :
print ( str ( ind ... |
def short_label ( self ) :
"""str : A short description of the group .
> > > device . group . short _ label
' Kitchen + 1'""" | group_names = sorted ( [ m . player_name for m in self . members ] )
group_label = group_names [ 0 ]
if len ( group_names ) > 1 :
group_label += " + {}" . format ( len ( group_names ) - 1 )
return group_label |
def report ( self ) :
"""Present all information that was gathered in an html file that
allows browsing the results .""" | # make this prettier
html = u'<hr/><a name="%s"></a>\n' % self . name ( )
# Intro
html = html + "<h2> Plugin <em>" + self . name ( ) + "</em></h2>\n"
# Files
if len ( self . copied_files ) :
html = html + "<p>Files copied:<br><ul>\n"
for afile in self . copied_files :
html = html + '<li><a href="%s">%s<... |
def build_rotation ( vec3 ) :
"""Build a rotation matrix .
vec3 is a Vector3 defining the axis about which to rotate the object .""" | if not isinstance ( vec3 , Vector3 ) :
raise ValueError ( "rotAmt must be a Vector3" )
return Matrix4 . x_rotate ( vec3 . x ) * Matrix4 . y_rotate ( vec3 . y ) * Matrix4 . z_rotate ( vec3 . z ) |
def is_domain_class_domain_attribute ( ent , attr_name ) :
"""Checks if the given attribute name is a resource attribute ( i . e . , either
a member or a aggregate attribute ) of the given registered resource .""" | attr = get_domain_class_attribute ( ent , attr_name )
return attr != RESOURCE_ATTRIBUTE_KINDS . TERMINAL |
def findAction ( self , text ) :
"""Looks up the action based on the inputed text .
: return < QAction > | | None""" | for action in self . actionGroup ( ) . actions ( ) :
if ( text in ( action . objectName ( ) , action . text ( ) ) ) :
return action
return None |
def create_one_time_invoice ( self , charges ) :
'''Charges should be a list of charges to execute immediately . Each
value in the charges diectionary should be a dictionary with the
following keys :
code
Your code for this charge . This code will be displayed in the
user ' s invoice and is limited to 36 ... | data = { }
for n , charge in enumerate ( charges ) :
each_amount = Decimal ( charge [ 'each_amount' ] )
each_amount = each_amount . quantize ( Decimal ( '.01' ) )
data [ 'charges[%d][chargeCode]' % n ] = charge [ 'code' ]
data [ 'charges[%d][quantity]' % n ] = charge . get ( 'quantity' , 1 )
data [ ... |
def imshow ( self , array , * args , ** kwargs ) :
"""Display an image , i . e . data on a 2D regular raster .
If ` ` array ` ` is a : class : ` ~ gwpy . types . Array2D ` ( e . g . a
: class : ` ~ gwpy . spectrogram . Spectrogram ` ) , then the defaults are
_ different _ to those in the upstream
: meth : `... | if isinstance ( array , Array2D ) :
return self . _imshow_array2d ( array , * args , ** kwargs )
image = super ( Axes , self ) . imshow ( array , * args , ** kwargs )
self . autoscale ( enable = None , axis = 'both' , tight = None )
return image |
def send ( self , pkt ) :
"""Send a packet""" | # Use the routing table to find the output interface
iff = pkt . route ( ) [ 0 ]
if iff is None :
iff = conf . iface
# Assign the network interface to the BPF handle
if self . assigned_interface != iff :
try :
fcntl . ioctl ( self . outs , BIOCSETIF , struct . pack ( "16s16x" , iff . encode ( ) ) )
... |
def base_dir ( self ) :
"""str : GEM - PRO project folder .""" | if self . root_dir :
return op . join ( self . root_dir , self . id )
else :
return None |
def get_gene_associations ( model ) :
"""Create gene association for class : class : ` . GeneDeletionStrategy ` .
Return a dict mapping reaction IDs to
: class : ` psamm . expression . boolean . Expression ` objects ,
representing relationships between reactions and related genes . This helper
function shou... | for reaction in model . reactions :
assoc = None
if reaction . genes is None :
continue
elif isinstance ( reaction . genes , string_types ) :
assoc = boolean . Expression ( reaction . genes )
else :
variables = [ boolean . Variable ( g ) for g in reaction . genes ]
assoc ... |
def update_dist_caches ( dist_path , fix_zipimporter_caches ) :
"""Fix any globally cached ` dist _ path ` related data
` dist _ path ` should be a path of a newly installed egg distribution ( zipped
or unzipped ) .
sys . path _ importer _ cache contains finder objects that have been cached when
importing d... | # There are several other known sources of stale zipimport . zipimporter
# instances that we do not clear here , but might if ever given a reason to
# do so :
# * Global setuptools pkg _ resources . working _ set ( a . k . a . ' master working
# set ' ) may contain distributions which may in turn contain their
# zipimp... |
def in_casapy ( helper , caltable = None , selectcals = { } , plotoptions = { } , xaxis = None , yaxis = None , figfile = None ) :
"""This function is run inside the weirdo casapy IPython environment ! A
strange set of modules is available , and the
` pwkit . environments . casa . scripting ` system sets up a v... | if caltable is None :
raise ValueError ( 'caltable' )
show_gui = ( figfile is None )
cp = helper . casans . cp
helper . casans . tp . setgui ( show_gui )
cp . open ( caltable )
cp . selectcal ( ** selectcals )
cp . plotoptions ( ** plotoptions )
cp . plot ( xaxis , yaxis )
if show_gui :
import pylab as pl
p... |
def community_post_comment_delete ( self , post_id , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / help _ center / post _ comments # delete - comment" | api_path = "/api/v2/community/posts/{post_id}/comments/{id}.json"
api_path = api_path . format ( post_id = post_id , id = id )
return self . call ( api_path , method = "DELETE" , ** kwargs ) |
def block ( self , userId , minute ) :
"""封禁用户方法 ( 每秒钟限 100 次 ) 方法
@ param userId : 用户 Id 。 ( 必传 )
@ param minute : 封禁时长 , 单位为分钟 , 最大值为43200分钟 。 ( 必传 )
@ return code : 返回码 , 200 为正常 。
@ return errorMessage : 错误信息 。""" | desc = { "name" : "CodeSuccessReslut" , "desc" : " http 成功返回结果" , "fields" : [ { "name" : "code" , "type" : "Integer" , "desc" : "返回码,200 为正常。" } , { "name" : "errorMessage" , "type" : "String" , "desc" : "错误信息。" } ] }
r = self . call_api ( method = ( 'API' , 'POST' , 'application/x-www-form-urlencoded' ) , action = '/... |
def flasher ( msg , severity = None ) :
"""Flask ' s flash if available , logging call if not""" | try :
flash ( msg , severity )
except RuntimeError :
if severity == 'danger' :
logging . error ( msg )
else :
logging . info ( msg ) |
def _ValidateTimeRange ( timerange ) :
"""Parses a timerange argument and always returns non - None timerange .""" | if len ( timerange ) != 2 :
raise ValueError ( "Timerange should be a sequence with 2 items." )
( start , end ) = timerange
precondition . AssertOptionalType ( start , rdfvalue . RDFDatetime )
precondition . AssertOptionalType ( end , rdfvalue . RDFDatetime ) |
def play ( self , sox_effects = ( ) ) :
"""Play the segment .""" | audio_data = self . getAudioData ( )
logging . getLogger ( ) . info ( "Playing speech segment (%s): '%s'" % ( self . lang , self ) )
cmd = [ "sox" , "-q" , "-t" , "mp3" , "-" ]
if sys . platform . startswith ( "win32" ) :
cmd . extend ( ( "-t" , "waveaudio" ) )
cmd . extend ( ( "-d" , "trim" , "0.1" , "reverse" , "... |
def _parseIntegerArgument ( args , key , defaultValue ) :
"""Attempts to parse the specified key in the specified argument
dictionary into an integer . If the argument cannot be parsed ,
raises a BadRequestIntegerException . If the key is not present ,
return the specified default value .""" | ret = defaultValue
try :
if key in args :
try :
ret = int ( args [ key ] )
except ValueError :
raise exceptions . BadRequestIntegerException ( key , args [ key ] )
except TypeError :
raise Exception ( ( key , args ) )
return ret |
def _get_ax_freq ( ax ) :
"""Get the freq attribute of the ax object if set .
Also checks shared axes ( eg when using secondary yaxis , sharex = True
or twinx )""" | ax_freq = getattr ( ax , 'freq' , None )
if ax_freq is None : # check for left / right ax in case of secondary yaxis
if hasattr ( ax , 'left_ax' ) :
ax_freq = getattr ( ax . left_ax , 'freq' , None )
elif hasattr ( ax , 'right_ax' ) :
ax_freq = getattr ( ax . right_ax , 'freq' , None )
if ax_fre... |
def read_filtering_config ( self ) :
"""Read configuration options in section " filtering " .""" | section = "filtering"
if self . has_option ( section , "ignorewarnings" ) :
self . config [ 'ignorewarnings' ] = [ f . strip ( ) . lower ( ) for f in self . get ( section , 'ignorewarnings' ) . split ( ',' ) ]
if self . has_option ( section , "ignore" ) :
for line in read_multiline ( self . get ( section , "ign... |
def csrf_failure ( request , reason = '' ) :
"""CSRF - failure view which converts the failed POST request into a GET
and calls the original view with a sensible error message presented
to the user .
: param request : the HttpRequest
: param reason : non - localised failure description""" | if _csrf_failed_view . no_moj_csrf :
from django . views . csrf import csrf_failure
return csrf_failure ( request , reason = reason )
# present a sensible error message to users
if reason == REASON_NO_CSRF_COOKIE :
reason = _ ( 'Please try again.' ) + ' ' + _ ( 'Make sure you haven’t disabled cookies.' )
el... |
def calc_rfc_sfc_v1 ( self ) :
"""Calculate the corrected fractions rainfall / snowfall and total
precipitation .
Required control parameters :
| NmbZones |
| RfCF |
| SfCF |
Calculated flux sequences :
| RfC |
| SfC |
Basic equations :
: math : ` RfC = RfCF \\ cdot FracRain ` \n
: math : ` Sf... | con = self . parameters . control . fastaccess
flu = self . sequences . fluxes . fastaccess
for k in range ( con . nmbzones ) :
flu . rfc [ k ] = flu . fracrain [ k ] * con . rfcf [ k ]
flu . sfc [ k ] = ( 1. - flu . fracrain [ k ] ) * con . sfcf [ k ] |
def check_if_numbers_are_consecutive ( list_ ) :
"""Returns True if numbers in the list are consecutive
: param list _ : list of integers
: return : Boolean""" | return all ( ( True if second - first == 1 else False for first , second in zip ( list_ [ : - 1 ] , list_ [ 1 : ] ) ) ) |
def showtraceback ( self , * args , ** kwargs ) :
"""Display the exception that just occurred .""" | # Override for avoid using sys . excepthook PY - 12600
try :
type , value , tb = sys . exc_info ( )
sys . last_type = type
sys . last_value = value
sys . last_traceback = tb
tblist = traceback . extract_tb ( tb )
del tblist [ : 1 ]
lines = traceback . format_list ( tblist )
if lines :
... |
def notify_update ( self , x , y , width , height ) :
"""Informs about an update .
Gets called by the display object where this buffer is
registered .
in x of type int
in y of type int
in width of type int
in height of type int""" | if not isinstance ( x , baseinteger ) :
raise TypeError ( "x can only be an instance of type baseinteger" )
if not isinstance ( y , baseinteger ) :
raise TypeError ( "y can only be an instance of type baseinteger" )
if not isinstance ( width , baseinteger ) :
raise TypeError ( "width can only be an instance... |
def _parse_url ( host , provided_protocol = None ) :
"""Process the provided host and protocol to return them in a standardized
way that can be subsequently used by Cytomine methods .
If the protocol is not specified , HTTP is the default .
Only HTTP and HTTPS schemes are supported .
Parameters
host : str... | protocol = "http"
# default protocol
if host . startswith ( "http://" ) :
protocol = "http"
elif host . startswith ( "https://" ) :
protocol = "https"
elif provided_protocol is not None :
provided_protocol = provided_protocol . replace ( "://" , "" )
if provided_protocol in ( "http" , "https" ) :
... |
def parse_keyring ( self , namespace = None ) :
"""Find settings from keyring .""" | results = { }
if not keyring :
return results
if not namespace :
namespace = self . prog
for option in self . _options :
secret = keyring . get_password ( namespace , option . name )
if secret :
results [ option . dest ] = option . type ( secret )
return results |
def get_as_csv ( self , output_file_path : Optional [ str ] = None ) -> str :
"""Returns the table object as a CSV string .
: param output _ file _ path : The output file to save the CSV to , or None .
: return : CSV representation of the table .""" | output = StringIO ( ) if not output_file_path else open ( output_file_path , 'w' )
try :
csv_writer = csv . writer ( output )
csv_writer . writerow ( self . columns )
for row in self . rows :
csv_writer . writerow ( row )
output . seek ( 0 )
return output . read ( )
finally :
output . cl... |
def setup_logging ( default_path = 'logging.yaml' , env_key = 'LOG_CFG' ) :
"""Setup logging configuration""" | path = default_path
value = os . getenv ( env_key , None )
if value :
path = value
if os . path . exists ( path ) :
with open ( path , 'rt' ) as f :
configs = yaml . safe_load ( f . read ( ) )
logging . config . dictConfig ( configs )
else :
logging . config . dictConfig ( config ) |
def from_file ( cls , fp , format_ = None , fps = None , ** kwargs ) :
"""Read subtitle file from file object .
See : meth : ` SSAFile . load ( ) ` for full description .
Note :
This is a low - level method . Usually , one of : meth : ` SSAFile . load ( ) `
or : meth : ` SSAFile . from _ string ( ) ` is pre... | if format_ is None : # Autodetect subtitle format , then read again using correct parser .
# The file might be a pipe and we need to read it twice ,
# so just buffer everything .
text = fp . read ( )
fragment = text [ : 10000 ]
format_ = autodetect_format ( fragment )
fp = io . StringIO ( text )
impl = ... |
def set_hflip ( self , val ) :
"""Flip all the images in the animation list horizontally .""" | self . __horizontal_flip = val
for image in self . images :
image . h_flip = val |
def cluster_resources ( self ) :
"""Get the current total cluster resources .
Note that this information can grow stale as nodes are added to or
removed from the cluster .
Returns :
A dictionary mapping resource name to the total quantity of that
resource in the cluster .""" | resources = defaultdict ( int )
clients = self . client_table ( )
for client in clients : # Only count resources from live clients .
if client [ "IsInsertion" ] :
for key , value in client [ "Resources" ] . items ( ) :
resources [ key ] += value
return dict ( resources ) |
def user_addmedia ( userids , active , mediatypeid , period , sendto , severity , ** kwargs ) :
'''Add new media to multiple users .
. . versionadded : : 2016.3.0
: param userids : ID of the user that uses the media
: param active : Whether the media is enabled ( 0 enabled , 1 disabled )
: param mediatypeid... | conn_args = _login ( ** kwargs )
ret = { }
try :
if conn_args :
method = 'user.addmedia'
params = { "users" : [ ] }
# Users
if not isinstance ( userids , list ) :
userids = [ userids ]
for user in userids :
params [ 'users' ] . append ( { "userid" : us... |
def delete ( self , ** context ) :
"""Removes this record from the database . If the dryRun flag is specified then the command will be logged and not executed .
: note From version 0.6.0 on , this method now accepts a mutable
keyword dictionary of values . You can supply any member
value for either the < orb ... | if not self . isRecord ( ) :
return 0
event = orb . events . DeleteEvent ( record = self , context = self . context ( ** context ) )
if self . processEvent ( event ) :
self . onDelete ( event )
if event . preventDefault :
return 0
if self . __delayed :
self . __delayed = False
self . read ( )
with W... |
def full_block_key ( self ) :
"""Returns the " correct " usage key value with the run filled in .""" | if self . block_key . run is None : # pylint : disable = unexpected - keyword - arg , no - value - for - parameter
return self . block_key . replace ( course_key = self . course_key )
return self . block_key |
def retain_error ( self , error , frame = None ) :
"""Adds details of an error to the report .
: param error : The error exception to add to the report .""" | if frame is None :
stack = traceback . format_exc ( )
self . labels . add ( "@iopipe/error" )
else :
stack = "\n" . join ( traceback . format_stack ( frame ) )
self . labels . add ( "@iopipe/timeout" )
details = { "name" : type ( error ) . __name__ , "message" : "{}" . format ( error ) , "stack" : stack... |
def clean_username ( self ) :
"""Ensure the username doesn ' t exist or contain invalid chars .
We limit it to slugifiable chars since it ' s used as the slug
for the user ' s profile view .""" | username = self . cleaned_data . get ( "username" )
if username . lower ( ) != slugify ( username ) . lower ( ) :
raise forms . ValidationError ( ugettext ( "Username can only contain letters, numbers, dashes " "or underscores." ) )
lookup = { "username__iexact" : username }
try :
User . objects . exclude ( id ... |
def get_work ( self , worker_id , available_gb = None , lease_time = None , work_spec_names = None , max_jobs = None ) :
'''obtain a WorkUnit instance based on available memory for the
worker process .
: param worker _ id : unique identifier string for a worker to
which a WorkUnit will be assigned , if availa... | if not isinstance ( available_gb , ( int , float ) ) :
raise ProgrammerError ( 'must specify available_gb' )
if ( max_jobs is not None ) and ( max_jobs != 1 ) :
logger . error ( 'redis rejester does not support max_jobs. ignoring and getting 1' )
if lease_time is None :
lease_time = self . default_lifetime
... |
def shutdown_abort ( ) :
'''Abort a shutdown . Only available while the dialog box is being
displayed to the user . Once the shutdown has initiated , it cannot be
aborted .
Returns :
bool : ` ` True ` ` if successful , otherwise ` ` False ` `
CLI Example :
. . code - block : : bash
salt ' minion - id ... | try :
win32api . AbortSystemShutdown ( '127.0.0.1' )
return True
except pywintypes . error as exc :
( number , context , message ) = exc . args
log . error ( 'Failed to abort system shutdown' )
log . error ( 'nbr: %s' , number )
log . error ( 'ctx: %s' , context )
log . error ( 'msg: %s' , m... |
def save_element_as_image_file ( self , selector , file_name , folder = None ) :
"""Take a screenshot of an element and save it as an image file .
If no folder is specified , will save it to the current folder .""" | element = self . find_element ( selector )
element_png = element . screenshot_as_png
if len ( file_name . split ( '.' ) [ 0 ] ) < 1 :
raise Exception ( "Error: file_name length must be > 0." )
if not file_name . endswith ( ".png" ) :
file_name = file_name + ".png"
image_file_path = None
if folder :
if folde... |
def json2pattern ( s ) :
"""Convert JSON format to a query pattern .
Includes even mongo shell notation without quoted key names .""" | # make valid JSON by wrapping field names in quotes
s , _ = re . subn ( r'([{,])\s*([^,{\s\'"]+)\s*:' , ' \\1 "\\2" : ' , s )
# handle shell values that are not valid JSON
s = shell2json ( s )
# convert to 1 where possible , to get rid of things like new Date ( . . . )
s , n = re . subn ( r'([:,\[])\s*([^{}\[\]"]+?)\s*... |
def load ( self , filename ) :
"""Load a frequency list from file ( in the format produced by the save method )""" | f = io . open ( filename , 'r' , encoding = 'utf-8' )
for line in f :
data = line . strip ( ) . split ( "\t" )
type , count = data [ : 2 ]
self . count ( type , count )
f . close ( ) |
def _normalize_percent_rgb ( value ) :
"""Normalize ` ` value ` ` for use in a percentage ` ` rgb ( ) ` ` triplet , as
follows :
* If ` ` value ` ` is less than 0 % , convert to 0 % .
* If ` ` value ` ` is greater than 100 % , convert to 100 % .
Examples :
> > > _ normalize _ percent _ rgb ( ' 0 % ' )
>... | percent = value . split ( '%' ) [ 0 ]
percent = float ( percent ) if '.' in percent else int ( percent )
if 0 <= percent <= 100 :
return '%s%%' % percent
if percent < 0 :
return '0%'
if percent > 100 :
return '100%' |
def configure_root_iam_credentials ( self , access_key , secret_key , region = None , iam_endpoint = None , sts_endpoint = None , max_retries = - 1 , mount_point = DEFAULT_MOUNT_POINT ) :
"""Configure the root IAM credentials to communicate with AWS .
There are multiple ways to pass root IAM credentials to the Va... | params = { 'access_key' : access_key , 'secret_key' : secret_key , 'region' : region , 'iam_endpoint' : iam_endpoint , 'sts_endpoint' : sts_endpoint , 'max_retries' : max_retries , }
api_path = '/v1/{mount_point}/config/root' . format ( mount_point = mount_point )
return self . _adapter . post ( url = api_path , json =... |
def get_by_slug ( tag_slug ) :
'''Get label by slug .''' | label_recs = TabTag . select ( ) . where ( TabTag . slug == tag_slug )
return label_recs . get ( ) if label_recs else False |
def keyPressEvent ( self , event ) :
"press ESCAPE to quit the application" | key = event . key ( )
if key == Qt . Key_Escape :
self . app . quit ( ) |
def print_colormaps ( cmaps , N = 256 , returnrgb = True , savefiles = False ) :
'''Print colormaps in 256 RGB colors to text files .
: param returnrgb = False : Whether or not to return the rgb array . Only makes sense to do if print one colormaps ' rgb .''' | rgb = [ ]
for cmap in cmaps :
rgbtemp = cmap ( np . linspace ( 0 , 1 , N ) ) [ np . newaxis , : , : 3 ] [ 0 ]
if savefiles :
np . savetxt ( cmap . name + '-rgb.txt' , rgbtemp )
rgb . append ( rgbtemp )
if returnrgb :
return rgb |
def _startup ( self ) :
"""Called during _ _ init _ _ . Check consistency of schema in database with
classes in memory . Load all Python modules for stored items , and load
version information for upgrader service to run later .""" | typesToCheck = [ ]
for oid , module , typename , version in self . querySchemaSQL ( _schema . ALL_TYPES ) :
if self . debug :
print
print 'SCHEMA:' , oid , module , typename , version
if typename not in _typeNameToMostRecentClass :
try :
namedAny ( module )
except Val... |
def compare_two_documents ( kls , doc1 , doc2 ) :
"""Compare two documents by converting them into json objects and back to strings and compare""" | first = doc1
if isinstance ( doc1 , string_types ) :
try :
first = json . loads ( doc1 )
except ( ValueError , TypeError ) as error :
log . warning ( "Failed to convert doc into a json object\terror=%s" , error )
yield error . args [ 0 ]
return
second = doc2
if isinstance ( doc2 ... |
def notify_modified ( room , event , user ) :
"""Notifies about the modification of a chatroom .
: param room : the chatroom
: param event : the event
: param user : the user performing the action""" | tpl = get_plugin_template_module ( 'emails/modified.txt' , chatroom = room , event = event , user = user )
_send ( event , tpl ) |
def merge_coords_for_inplace_math ( objs , priority_vars = None ) :
"""Merge coordinate variables without worrying about alignment .
This function is used for merging variables in coordinates . py .""" | expanded = expand_variable_dicts ( objs )
variables = merge_variables ( expanded , priority_vars )
assert_unique_multiindex_level_names ( variables )
return variables |
def set_keyspace ( self , keyspace ) :
"""Change the keyspace which will be used for subsequent requests to this
CassandraClusterPool , and return a Deferred that will fire once it can
be verified that connections can successfully use that keyspace .
If something goes wrong trying to change a connection to th... | # push a real set _ keyspace on some ( any ) connection ; the idea is that
# if it succeeds there , it is likely to succeed everywhere , and vice
# versa . don ' t bother waiting for all connections to change - some of
# them may be doing long blocking tasks and by the time they ' re done ,
# the keyspace might be chan... |
def url_to_fn ( url ) :
"""Convert ` url ` to filename used to download the datasets .
` ` http : / / kitakitsune . org / xe ` ` - > ` ` kitakitsune . org _ xe ` ` .
Args :
url ( str ) : URL of the resource .
Returns :
str : Normalized URL .""" | url = url . replace ( "http://" , "" ) . replace ( "https://" , "" )
url = url . split ( "?" ) [ 0 ]
return url . replace ( "%" , "_" ) . replace ( "/" , "_" ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.