signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def read_legacy ( filename ) :
"""Use VTK ' s legacy reader to read a file""" | reader = vtk . vtkDataSetReader ( )
reader . SetFileName ( filename )
# Ensure all data is fetched with poorly formated legacy files
reader . ReadAllScalarsOn ( )
reader . ReadAllColorScalarsOn ( )
reader . ReadAllNormalsOn ( )
reader . ReadAllTCoordsOn ( )
reader . ReadAllVectorsOn ( )
# Perform the read
reader . Upda... |
def check_redis_connected ( app_configs , ** kwargs ) :
"""A Django check to connect to the default redis connection
using ` ` django _ redis . get _ redis _ connection ` ` and see if Redis
responds to a ` ` PING ` ` command .""" | import redis
from django_redis import get_redis_connection
errors = [ ]
try :
connection = get_redis_connection ( 'default' )
except redis . ConnectionError as e :
msg = 'Could not connect to redis: {!s}' . format ( e )
errors . append ( checks . Error ( msg , id = health . ERROR_CANNOT_CONNECT_REDIS ) )
ex... |
def clear ( self ) :
"""Clear the cache , setting it to its initial state .""" | self . name . clear ( )
self . path . clear ( )
self . generated = False |
def read ( filename = 'cache' ) :
"""parameter : file _ path - path to cache file
return : data after parsing json file""" | cache_path = get_cache_path ( filename )
if not os . path . exists ( cache_path ) or os . stat ( cache_path ) . st_size == 0 :
return None
with open ( cache_path , 'r' ) as file :
return json . load ( file ) |
def del_hyperedge ( self , hyperedge ) :
"""Delete the given hyperedge .
@ type hyperedge : hyperedge
@ param hyperedge : Hyperedge identifier .""" | if ( hyperedge in self . hyperedges ( ) ) :
for n in self . edge_links [ hyperedge ] :
self . node_links [ n ] . remove ( hyperedge )
del ( self . edge_links [ hyperedge ] )
self . del_edge_labeling ( hyperedge )
self . graph . del_node ( ( hyperedge , 'h' ) ) |
def export ( self , nidm_version , export_dir ) :
"""Create prov entities and activities .""" | # Create " Cluster Labels Map " entity
self . add_attributes ( ( ( PROV [ 'type' ] , self . type ) , ( NIDM_IN_COORDINATE_SPACE , self . coord_space . id ) , ( PROV [ 'label' ] , self . label ) ) ) |
def parse ( self , stream , media_type = None , parser_context = None ) :
"""Parses the incoming bytestream as a multipart encoded form ,
and returns a DataAndFiles object .
` . data ` will be a ` QueryDict ` containing all the form parameters .
` . files ` will be a ` QueryDict ` containing all the form file... | parser_context = parser_context or { }
request = parser_context [ 'request' ]
encoding = parser_context . get ( 'encoding' , settings . DEFAULT_CHARSET )
meta = request . META . copy ( )
meta [ 'CONTENT_TYPE' ] = media_type
upload_handlers = request . upload_handlers
try :
parser = DjangoMultiPartParser ( meta , st... |
def update_telemetry_configurations ( self , configuration , timeout = - 1 ) :
"""Updates the telemetry configuration of a logical interconnect . Changes to the telemetry configuration are
asynchronously applied to all managed interconnects .
Args :
configuration :
The telemetry configuration for the logica... | telemetry_conf_uri = self . _get_telemetry_configuration_uri ( )
default_values = self . _get_default_values ( self . SETTINGS_TELEMETRY_CONFIG_DEFAULT_VALUES )
configuration = self . _helper . update_resource_fields ( configuration , default_values )
return self . _helper . update ( configuration , uri = telemetry_con... |
def force_unicode ( s , encoding = 'utf-8' , errors = 'strict' ) :
"""Similar to smart _ text , except that lazy instances are resolved to
strings , rather than kept as lazy objects .""" | # Handle the common case first , saves 30-40 % when s is an instance of
# six . text _ type . This function gets called often in that setting .
if isinstance ( s , six . text_type ) :
return s
if not isinstance ( s , six . string_types ) :
if six . PY3 :
if isinstance ( s , bytes ) :
s = six... |
def check_shape ( meth ) :
"""Decorator for larray magic methods , to ensure that the operand has
the same shape as the array .""" | @ wraps ( meth )
def wrapped_meth ( self , val ) :
if isinstance ( val , ( larray , numpy . ndarray ) ) :
if val . shape != self . _shape :
raise ValueError ( "shape mismatch: objects cannot be broadcast to a single shape" )
return meth ( self , val )
return wrapped_meth |
def detach ( self ) :
"""Detach the source from its customer .""" | # First , wipe default source on all customers that use this .
Customer . objects . filter ( default_source = self . id ) . update ( default_source = None )
try : # TODO - we could use the return value of sync _ from _ stripe _ data
# or call its internals - self . _ sync / _ attach _ objects _ hook etc here
# to updat... |
def __hosting_wechat_img ( self , content_info , hosting_callback ) :
"""将微信明细中图片托管到云端 , 同时将html页面中的对应图片替换
Parameters
content _ info : dict 微信文章明细字典
' content _ img _ list ' : [ ] , # 从微信文章解析出的原始图片列表
' content _ html ' : ' ' , # 从微信文章解析出文章的内容
hosting _ callback : callable
托管回调函数 , 传入单个图片链接 , 返回托管后的图片链接 ... | assert callable ( hosting_callback )
content_img_list = content_info . pop ( "content_img_list" )
content_html = content_info . pop ( "content_html" )
for idx , img_url in enumerate ( content_img_list ) :
hosting_img_url = hosting_callback ( img_url )
if not hosting_img_url : # todo 定义标准异常
raise Excepti... |
def a_stays_connected ( ctx ) :
"""Stay connected .""" | ctx . ctrl . connected = True
ctx . device . connected = False
return True |
def strip_line_magic_v3 ( cls , line ) :
"""strip _ line _ magic ( ) implementation for Python 3""" | matches = re . findall ( "run_line_magic\(([^]]+)" , line )
if matches and matches [ 0 ] : # This line contains the pattern
match = matches [ 0 ]
if match [ - 1 ] == ')' :
match = match [ : - 1 ]
# Just because the re way is hard
magic_kind , stripped = eval ( match )
else :
stripped = l... |
def save ( self ) :
"""save the current session
override , if session was saved earlier""" | if self . path :
self . _saveState ( self . path )
else :
self . saveAs ( ) |
def typical_price ( close_data , high_data , low_data ) :
"""Typical Price .
Formula :
TPt = ( HIGHt + LOWt + CLOSEt ) / 3""" | catch_errors . check_for_input_len_diff ( close_data , high_data , low_data )
tp = [ ( high_data [ idx ] + low_data [ idx ] + close_data [ idx ] ) / 3 for idx in range ( 0 , len ( close_data ) ) ]
return np . array ( tp ) |
def lookup ( self , allowed_types , ** kwargs ) :
"""Lookup an object of type ( allowed _ types ) . kwargs is sent
directly to the catalog .""" | at = getToolByName ( self , 'archetype_tool' )
for portal_type in allowed_types :
catalog = at . catalog_map . get ( portal_type , [ None ] ) [ 0 ]
catalog = getToolByName ( self , catalog )
kwargs [ 'portal_type' ] = portal_type
brains = catalog ( ** kwargs )
if brains :
return brains |
def _count_objs ( self , obj , path = None , ** kwargs ) :
"""cycles through the object and adds in count values
Args :
obj : the object to parse
path : the current path
kwargs :
current : a dictionary of counts for current call
sub _ val : the value to use for subtotal aggregation""" | sub_val = None
# pdb . set _ trace ( )
if isinstance ( obj , dict ) :
for key , value in obj . items ( ) :
if isinstance ( value , ( list , dict ) ) :
kwargs = self . _count_objs ( value , self . make_path ( key , path ) , ** kwargs )
else :
if self . make_path ( key , path )... |
def is_ancestor ( self , commit1 , commit2 , patch = False ) :
"""Returns True if commit1 is a direct ancestor of commit2 , or False
otherwise .
This method considers a commit to be a direct ancestor of itself""" | result = self . hg ( "log" , "-r" , "first(%s::%s)" % ( commit1 , commit2 ) , "--template" , "exists" , patch = patch )
return "exists" in result |
def accounting ( dbfile , config ) :
'''update radius accounting''' | try :
nas_id = config . get ( 'DEFAULT' , 'nas_id' )
nas_addr = config . get ( 'DEFAULT' , 'nas_addr' )
secret = config . get ( 'DEFAULT' , 'radius_secret' )
radius_addr = config . get ( 'DEFAULT' , 'radius_addr' )
radius_acct_port = config . getint ( 'DEFAULT' , 'radius_acct_port' )
radius_time... |
def geocode ( self , string , bounds = None , region = None , language = None , sensor = False ) :
'''Geocode an address .
Pls refer to the Google Maps Web API for the details of the parameters''' | if isinstance ( string , unicode ) :
string = string . encode ( 'utf-8' )
params = { 'address' : self . format_string % string , 'sensor' : str ( sensor ) . lower ( ) }
if bounds :
params [ 'bounds' ] = bounds
if region :
params [ 'region' ] = region
if language :
params [ 'language' ] = language
if not... |
def return_labels_numpy ( self , original = False ) :
"""Returns a 2d numpy array of labels
Parameters
original : if True , will return original labels , if False , will return transformed labels ( as defined by
label _ dict ) , default value : False
Returns
A numpy array of labels , each row corresponds ... | if self . _prepopulated is False :
raise errors . EmptyDatabase ( self . dbpath )
else :
engine = create_engine ( 'sqlite:////' + self . dbpath )
trainset . Base . metadata . create_all ( engine )
session_cl = sessionmaker ( bind = engine )
session = session_cl ( )
tmp_object = session . query (... |
def _string_in_table ( self , candidate : str ) -> List [ str ] :
"""Checks if the string occurs in the table , and if it does , returns the names of the columns
under which it occurs . If it does not , returns an empty list .""" | candidate_column_names : List [ str ] = [ ]
# First check if the entire candidate occurs as a cell .
if candidate in self . _string_column_mapping :
candidate_column_names = self . _string_column_mapping [ candidate ]
# If not , check if it is a substring pf any cell value .
if not candidate_column_names :
for ... |
def request ( self , path , action , data = '' ) :
"""To make a request to the API .""" | # Check if the path includes URL or not .
head = self . base_url
if path . startswith ( head ) :
path = path [ len ( head ) : ]
path = quote_plus ( path , safe = '/' )
if not path . startswith ( self . api ) :
path = self . api + path
log . debug ( 'Using path %s' % path )
# If we have data , convert to JSO... |
def geometry_range ( crd_range , elev , crd_type ) :
"""Range of coordinates . ( e . g . 2 latitude coordinates , and 0 longitude coordinates )
: param crd _ range : Latitude or Longitude values
: param elev : Elevation value
: param crd _ type : Coordinate type , lat or lon
: return dict :""" | d = OrderedDict ( )
coordinates = [ [ ] for i in range ( len ( crd_range ) ) ]
# latitude
if crd_type == "lat" :
for idx , i in enumerate ( crd_range ) :
coordinates [ idx ] = [ crd_range [ idx ] , "nan" ]
if elev :
coordinates [ idx ] . append ( elev )
# longitude
elif crd_type == "lon"... |
def ensure_yx_order ( func ) :
"""Wrap a function to ensure all array arguments are y , x ordered , based on kwarg .""" | @ functools . wraps ( func )
def wrapper ( * args , ** kwargs ) : # Check what order we ' re given
dim_order = kwargs . pop ( 'dim_order' , None )
x_first = _is_x_first_dim ( dim_order )
# If x is the first dimension , flip ( transpose ) every array within the function args .
if x_first :
args =... |
def asML ( self ) :
"""Convert this vector to the new mllib - local representation .
This does NOT copy the data ; it copies references .
: return : : py : class : ` pyspark . ml . linalg . SparseVector `
. . versionadded : : 2.0.0""" | return newlinalg . SparseVector ( self . size , self . indices , self . values ) |
def logsumexp ( x ) :
"""Numerically stable log ( sum ( exp ( x ) ) ) , also defined in scipy . misc""" | max_x = np . max ( x )
return max_x + np . log ( np . sum ( np . exp ( x - max_x ) ) ) |
def teardown ( self , np = np ) :
"""Lives in zipline . _ _ init _ _ for doctests .""" | if self . old_err is not None :
np . seterr ( ** self . old_err )
if self . old_opts is not None :
np . set_printoptions ( ** self . old_opts ) |
def img2img_transformer2d_tiny ( ) :
"""Tiny params .""" | hparams = img2img_transformer2d_base ( )
hparams . num_decoder_layers = 2
hparams . hidden_size = 128
hparams . batch_size = 4
hparams . max_length = 128
hparams . attention_key_channels = hparams . attention_value_channels = 0
hparams . filter_size = 128
hparams . num_heads = 4
hparams . pos = "timing"
hparams . img_l... |
def analyse_action ( func ) :
"""Analyse a function .""" | description = inspect . getdoc ( func ) or 'undocumented action'
arguments = [ ]
args , varargs , kwargs , defaults = inspect . getargspec ( func )
if varargs or kwargs :
raise TypeError ( 'variable length arguments for action not allowed.' )
if len ( args ) != len ( defaults or ( ) ) :
raise TypeError ( 'not a... |
def add_message ( request , level , message , extra_tags = '' , fail_silently = False , * args , ** kwargs ) :
"""Attempts to add a message to the request using the ' messages ' app .""" | if hasattr ( request , '_messages' ) :
return request . _messages . add ( level , message , extra_tags , * args , ** kwargs )
if not fail_silently :
raise MessageFailure ( 'You cannot add messages without installing ' 'django.contrib.messages.middleware.MessageMiddleware' ) |
def create_qrcode ( self , qrcode_data ) :
"""创建卡券二维码
: param qrcode _ data : 二维码信息
: return : 二维码 ticket , 可使用 : func : show _ qrcode 换取二维码文件""" | result = self . _post ( 'card/qrcode/create' , data = qrcode_data , result_processor = lambda x : x [ 'ticket' ] )
return result |
def to_pypsa ( network , mode , timesteps ) :
"""Translate graph based grid representation to PyPSA Network
For details from a user perspective see API documentation of
: meth : ` ~ . grid . network . EDisGo . analyze ` of the API class
: class : ` ~ . grid . network . EDisGo ` .
Translating eDisGo ' s grid... | # check if timesteps is array - like , otherwise convert to list ( necessary
# to obtain a dataframe when using . loc in time series functions )
if not hasattr ( timesteps , "__len__" ) :
timesteps = [ timesteps ]
# get topology and time series data
if mode is None :
mv_components = mv_to_pypsa ( network )
... |
def create_auth_token ( sender , instance , raw , created , ** kwargs ) :
"""Create token when a user is created ( from rest _ framework ) .""" | if not raw :
if created :
sender . objects . create ( user = instance ) |
def _getNodeFnib ( self , name , valu ) :
'''return a form , norm , info , buid tuple''' | form = self . model . form ( name )
if form is None :
raise s_exc . NoSuchForm ( name = name )
try :
norm , info = form . type . norm ( valu )
except Exception as e :
raise s_exc . BadPropValu ( prop = form . name , valu = valu , mesg = str ( e ) )
buid = s_common . buid ( ( form . name , norm ) )
return fo... |
def reminder_pdf ( self , reminder_id ) :
"""Opens a pdf of a reminder
: param reminder _ id : the reminder id
: return : dict""" | return self . _create_get_request ( resource = REMINDERS , billomat_id = reminder_id , command = PDF ) |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : # pylint : disable = too - many - arguments
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for specification of input and result values .
Implements the following equatio... | # obtain coefficients for required intensity measure type
coeffs = self . COEFFS_BEDROCK [ imt ] . copy ( )
# obtain site - class specific coefficients
a_1 , a_2 , sigma_site = self . _get_site_coeffs ( sites , imt )
coeffs . update ( { 'a1' : a_1 , 'a2' : a_2 , 'sigma_site' : sigma_site } )
# compute bedrock motion , ... |
def AddPoly ( self , poly , smart_duplicate_handling = True ) :
"""Adds a new polyline to the collection .""" | inserted_name = poly . GetName ( )
if poly . GetName ( ) in self . _name_to_shape :
if not smart_duplicate_handling :
raise ShapeError ( "Duplicate shape found: " + poly . GetName ( ) )
print ( "Warning: duplicate shape id being added to collection: " + poly . GetName ( ) )
if poly . GreedyPolyMatch... |
def result ( self , * args , ** kwargs ) :
"""Construye la consulta SQL""" | prettify = kwargs . get ( 'pretty' , False )
sql = 'UPDATE %s' % self . _class
if prettify :
sql += '\n'
else :
sql += ' '
if self . data :
sql += 'MERGE ' + json . dumps ( self . data )
if prettify :
sql += '\n'
else :
sql += ' '
if self . where_criteria . size ( ) > 0 :
sql += ... |
def register ( self , name , namespace ) :
"""Register a new namespace with the Configuration object .
Args :
name ( str ) : The name of the section / namespace .
namespace ( namespace . Namespace ) : The Namespace object to store .
Raises :
TypeError : If the namespace is not a Namespace object .
Value... | if name in self . _NAMESPACES :
raise ValueError ( "Namespace {0} already exists." . format ( name ) )
if not isinstance ( namespace , ns . Namespace ) :
raise TypeError ( "Namespaces must be of type Namespace." )
self . _NAMESPACES [ name ] = namespace |
def yaml_processor ( entity ) :
'''Unserialize raw POST data in YAML format to a Python data structure .
: param entity : raw POST data''' | if six . PY2 :
body = entity . fp . read ( )
else : # https : / / github . com / cherrypy / cherrypy / pull / 1572
contents = BytesIO ( )
body = entity . fp . read ( fp_out = contents )
contents . seek ( 0 )
body = salt . utils . stringutils . to_unicode ( contents . read ( ) )
try :
cherrypy . ... |
def space_row ( left , right , filler = ' ' , total_width = - 1 ) :
"""space the data in a row with optional filling
Arguments
left : str , to be aligned left
right : str , to be aligned right
filler : str , default ' ' .
must be of length 1
total _ width : int , width of line .
if negative number is ... | left = str ( left )
right = str ( right )
filler = str ( filler ) [ : 1 ]
if total_width < 0 :
spacing = - total_width
else :
spacing = total_width - len ( left ) - len ( right )
return left + filler * spacing + right |
def _draw_tile_layer ( self , tile , layer_name , c_filters , colour , t_filters , x , y , bg ) :
"""Draw the visible geometry in the specified map tile .""" | # Don ' t bother rendering if the tile is not visible
left = ( x + self . _screen . width // 4 ) * 2
top = y + self . _screen . height // 2
if ( left > self . _screen . width or left + self . _size * 2 < 0 or top > self . _screen . height or top + self . _size < 0 ) :
return 0
# Not all layers are available in ever... |
def _check ( self , args ) :
"""Exit in case of multiple exclusive arguments .""" | if sum ( bool ( args [ arg ] ) for arg in self . _mapping ) > 1 :
raise DocoptExit ( _ ( 'These options are mutually exclusive: {0}' , ', ' . join ( self . _mapping ) ) ) |
def to_json ( self , indent = 4 ) :
"""Serialize metas and reference attributes to a JSON string .
Keyword Arguments :
indent ( int ) : Space indentation , default to ` ` 4 ` ` .
Returns :
string : JSON datas .""" | agregate = { 'metas' : self . metas , }
agregate . update ( { k : getattr ( self , k ) for k in self . _rule_attrs } )
return json . dumps ( agregate , indent = indent ) |
def _waiting_expect ( self ) :
'''` ` True ` ` when the client is waiting for 100 Continue .''' | if self . _expect_sent is None :
if self . environ . get ( 'HTTP_EXPECT' , '' ) . lower ( ) == '100-continue' :
return True
self . _expect_sent = ''
return False |
def dn ( self , fraction , n = None ) :
r'''Computes the diameter at which a specified ` fraction ` of the
distribution falls under . Utilizes a bounded solver to search for the
desired diameter .
Parameters
fraction : float
Fraction of the distribution which should be under the calculated
diameter , [ ... | if fraction == 1.0 : # Avoid returning the maximum value of the search interval
fraction = 1.0 - epsilon
if fraction < 0 :
raise ValueError ( 'Fraction must be more than 0' )
elif fraction == 0 : # pragma : no cover
if self . truncated :
return self . d_min
return 0.0
# Solve to float previs... |
def add_padding ( self , name , left = 0 , right = 0 , top = 0 , bottom = 0 , value = 0 , input_name = 'data' , output_name = 'out' , padding_type = 'constant' ) :
"""Add a padding layer to the model . Kindly refer to NeuralNetwork . proto for details .
Parameters
name : str
The name of this layer .
left : ... | # Currently only constant padding is supported .
spec = self . spec
nn_spec = self . nn_spec
# Add a new layer
spec_layer = nn_spec . layers . add ( )
spec_layer . name = name
spec_layer . input . append ( input_name )
spec_layer . output . append ( output_name )
spec_layer_params = spec_layer . padding
# Set the param... |
def get_resource ( resource_name , key , identifier_fields , profile = 'pagerduty' , subdomain = None , api_key = None ) :
'''Get any single pagerduty resource by key .
We allow flexible lookup by any of a list of identifier _ fields .
So , for example , you can look up users by email address or name by calling... | # cache the expensive ' get all resources ' calls into _ _ context _ _ so that we do them once per salt run
if 'pagerduty_util.resource_cache' not in __context__ :
__context__ [ 'pagerduty_util.resource_cache' ] = { }
if resource_name not in __context__ [ 'pagerduty_util.resource_cache' ] :
if resource_name == ... |
def simple_preprocess ( doc , deacc = False , min_len = 2 , max_len = 15 ) :
"""Convert a document into a list of tokens .
This lowercases , tokenizes , de - accents ( optional ) . - - the output are final
tokens = unicode strings , that won ' t be processed any further .""" | tokens = [ token for token in tokenize ( doc , lower = True , deacc = deacc , errors = 'ignore' ) if min_len <= len ( token ) <= max_len and not token . startswith ( '_' ) ]
return tokens |
def iterencode ( self , o , _one_shot = False ) :
"""Encode the given object and yield each string
representation as available .
For example : :
for chunk in JSONEncoder ( ) . iterencode ( bigobject ) :
mysocket . write ( chunk )""" | c_make_encoder_original = json . encoder . c_make_encoder
json . encoder . c_make_encoder = None
if self . check_circular :
markers = { }
else :
markers = None
if self . ensure_ascii :
_encoder = json . encoder . encode_basestring_ascii
else :
_encoder = json . encoder . encode_basestring
def floatstr (... |
def _create_entry ( self , location , element , unique = True , delete_element = False ) :
"""Create an entry located at ` ` location ` ` .
Args :
location : String or : class : ` LocationDescriptor ` to describe a " separator location " ( i . e . dir1 / dir2 / dir3 for
instance ) .
element : Element to sto... | loc_descriptor = self . _get_location_descriptor ( location )
# find parent node
parent_node = self . _root_node
if loc_descriptor . nbr_of_sub_locations ( ) > 1 :
parent_node = self . _get_node ( loc_descriptor . get_sub_location_descriptor ( ) , create_non_existing_nodes = True )
# find child node if it exist
las... |
def _insert_manifest_item ( configurator , key , item ) :
"""Insert an item in the list of an existing manifest key""" | with _open_manifest ( configurator ) as f :
manifest = f . read ( )
if item in ast . literal_eval ( manifest ) . get ( key , [ ] ) :
return
pattern = """(["']{}["']:\\s*\\[)""" . format ( key )
repl = """\\1\n '{}',""" . format ( item )
manifest = re . sub ( pattern , repl , manifest , re . MULTILINE )
w... |
def _set ( self ) :
"""Get / Set a set .""" | class Sets ( object ) :
def __getitem__ ( _self , name ) :
return self . getSet ( name )
def __setitem__ ( _self , name , values ) :
self . getSet ( name ) . setValues ( values )
def __iter__ ( _self ) :
return self . getSets ( )
return Sets ( ) |
def from_file ( filename ) :
"""Parse cookie data from a text file in HTTP header format .
@ return : list of tuples ( headers , scheme , host , path )""" | entries = [ ]
with open ( filename ) as fd :
lines = [ ]
for line in fd . readlines ( ) :
line = line . rstrip ( )
if not line :
if lines :
entries . append ( from_headers ( "\r\n" . join ( lines ) ) )
lines = [ ]
else :
lines . append ... |
def emboss_pepstats_parser ( infile ) :
"""Get dictionary of pepstats results .
Args :
infile : Path to pepstats outfile
Returns :
dict : Parsed information from pepstats
TODO :
Only currently parsing the bottom of the file for percentages of properties .""" | with open ( infile ) as f :
lines = f . read ( ) . split ( '\n' )
info_dict = { }
for l in lines [ 38 : 47 ] :
info = l . split ( '\t' )
cleaninfo = list ( filter ( lambda x : x != '' , info ) )
prop = cleaninfo [ 0 ]
num = cleaninfo [ 2 ]
percent = float ( cleaninfo [ - 1 ] ) / float ( 100 )
... |
def getHostCertPath ( self , name ) :
'''Gets the path to a host certificate .
Args :
name ( str ) : The name of the host keypair .
Examples :
Get the path to the host certificate for the host " myhost " :
mypath = cdir . getHostCertPath ( ' myhost ' )
Returns :
str : The path if exists .''' | path = s_common . genpath ( self . certdir , 'hosts' , '%s.crt' % name )
if not os . path . isfile ( path ) :
return None
return path |
def mean_sq_jump_dist ( self , discard_frac = 0.1 ) :
"""Mean squared jumping distance estimated from chain .
Parameters
discard _ frac : float
fraction of iterations to discard at the beginning ( as a burn - in )
Returns
float""" | discard = int ( self . niter * discard_frac )
return msjd ( self . chain . theta [ discard : ] ) |
def set_size ( self , size ) :
"""Changes the file size .
in size of type int
The new file size .
raises : class : ` OleErrorNotimpl `
The method is not implemented yet .""" | if not isinstance ( size , baseinteger ) :
raise TypeError ( "size can only be an instance of type baseinteger" )
self . _call ( "setSize" , in_p = [ size ] ) |
def fast ( self ) :
"""Access the ' fast ' dimension
This mode yields iline or xline mode , depending on which one is laid
out ` faster ` , i . e . the line with linear disk layout . Use this mode if
the inline / crossline distinction isn ' t as interesting as traversing in
a fast manner ( typically when yo... | if self . sorting == TraceSortingFormat . INLINE_SORTING :
return self . iline
elif self . sorting == TraceSortingFormat . CROSSLINE_SORTING :
return self . xline
else :
raise RuntimeError ( "Unknown sorting." ) |
def ReadClientPostingLists ( self , keywords ) :
"""Looks up all clients associated with any of the given keywords .
Args :
keywords : A list of keywords we are interested in .
Returns :
A dict mapping each keyword to a list of matching clients .""" | start_time , filtered_keywords = self . _AnalyzeKeywords ( keywords )
return data_store . REL_DB . ListClientsForKeywords ( filtered_keywords , start_time = start_time ) |
def fake_exc_info ( exc_info , filename , lineno ) :
"""Helper for ` translate _ exception ` .""" | exc_type , exc_value , tb = exc_info
# figure the real context out
if tb is not None :
real_locals = tb . tb_frame . f_locals . copy ( )
ctx = real_locals . get ( 'context' )
if ctx :
locals = ctx . get_all ( )
else :
locals = { }
for name , value in real_locals . iteritems ( ) :
... |
def generate_one ( basename , xml ) :
'''generate headers for one XML file''' | directory = os . path . join ( basename , xml . basename )
print ( "Generating C implementation in directory %s" % directory )
mavparse . mkdir_p ( directory )
if xml . little_endian :
xml . mavlink_endian = "MAVLINK_LITTLE_ENDIAN"
else :
xml . mavlink_endian = "MAVLINK_BIG_ENDIAN"
if xml . crc_extra :
xml ... |
def signrawtransaction ( self , rawtxhash , parent_tx_outputs = None , private_key = None ) :
"""signrawtransaction returns status and rawtxhash
: rawtxhash - serialized transaction ( hex )
: parent _ tx _ outputs - outputs being spent by this transaction
: private _ key - a private key to sign this transacti... | if not parent_tx_outputs and not private_key :
return self . req ( "signrawtransaction" , [ rawtxhash ] )
else :
return self . req ( "signrawtransaction" , [ rawtxhash , parent_tx_outputs , private_key ] ) |
def read_static_uplink ( self ) :
"""Read the static uplink from file , if given .""" | if self . node_list is None or self . node_uplink_list is None :
return
for node , port in zip ( self . node_list . split ( ',' ) , self . node_uplink_list . split ( ',' ) ) :
if node . strip ( ) == self . host_name :
self . static_uplink = True
self . static_uplink_port = port . strip ( )
... |
async def SetPassword ( self , changes ) :
'''changes : typing . Sequence [ ~ EntityPassword ]
Returns - > typing . Sequence [ ~ ErrorResult ]''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'UserManager' , request = 'SetPassword' , version = 1 , params = _params )
_params [ 'changes' ] = changes
reply = await self . rpc ( msg )
return reply |
def close ( self ) :
"""Close any open connections to Redis .
: raises : : exc : ` tredis . exceptions . ConnectionError `""" | if not self . _connected . is_set ( ) :
raise exceptions . ConnectionError ( 'not connected' )
self . _closing = True
if self . _clustering :
for host in self . _cluster . keys ( ) :
self . _cluster [ host ] . close ( )
elif self . _connection :
self . _connection . close ( ) |
def connect ( self ) :
"""Set TCP _ NODELAY on socket""" | HTTPConnection . connect ( self )
self . sock . setsockopt ( socket . IPPROTO_TCP , socket . TCP_NODELAY , 1 ) |
def create ( self , ignore_warnings = None ) :
"""Create this AppProfile .
. . note : :
Uses the ` ` instance ` ` and ` ` app _ profile _ id ` ` on the current
: class : ` AppProfile ` in addition to the ` ` routing _ policy _ type ` ` ,
` ` description ` ` , ` ` cluster _ id ` ` and ` ` allow _ transaction... | return self . from_pb ( self . instance_admin_client . create_app_profile ( parent = self . _instance . name , app_profile_id = self . app_profile_id , app_profile = self . _to_pb ( ) , ignore_warnings = ignore_warnings , ) , self . _instance , ) |
def Cross ( width = 3 , color = 0 ) :
"""Draws a cross centered in the target area
: param width : width of the lines of the cross in pixels
: type width : int
: param color : color of the lines of the cross
: type color : pygame . Color""" | return Overlay ( Line ( "h" , width , color ) , Line ( "v" , width , color ) ) |
def check_response ( self , response ) :
"""Raises error if the response isn ' t successful .
: param response : requests . Response response to be checked""" | if response . status_code == 401 :
raise D4S2Error ( UNAUTHORIZED_MESSAGE )
if not 200 <= response . status_code < 300 :
raise D4S2Error ( "Request to {} failed with {}:\n{}." . format ( response . url , response . status_code , response . text ) ) |
def delete ( self , list_uuid , uuid ) :
"""Delete one list .""" | res = self . get ( list_uuid , uuid )
url = "%(base)s/%(list_uuid)s/contacts/%(uuid)s" % { 'base' : self . local_base_url , 'list_uuid' : list_uuid , 'uuid' : uuid }
self . core . delete ( url )
return res |
def install_requirements ( self ) :
"""Install Ubuntu Requirements""" | print ( 'Installing Requirements' )
print ( platform . dist ( ) )
if platform . dist ( ) [ 0 ] in [ 'Ubuntu' , 'LinuxMint' ] :
command = 'sudo apt-get install -y gcc git python3-dev zlib1g-dev make zip libssl-dev libbz2-dev liblzma-dev libcurl4-openssl-dev build-essential libxml2-dev apache2 zlib1g-dev bcftools bui... |
def additional_assets ( context : Context ) :
"""Collects assets from GOV . UK frontend toolkit""" | rsync_flags = '-avz' if context . verbosity == 2 else '-az'
for path in context . app . additional_asset_paths :
context . shell ( 'rsync %s %s %s/' % ( rsync_flags , path , context . app . asset_build_path ) ) |
def persistentRegisterInspector ( fullName , fullClassName , pythonPath = '' ) :
"""Registers an inspector
Loads or inits the inspector registry , register the inspector and saves the settings .
Important : instantiate a Qt application first to use the correct settings file / winreg .""" | registry = InspectorRegistry ( )
registry . loadOrInitSettings ( )
registry . registerInspector ( fullName , fullClassName , pythonPath = pythonPath )
registry . saveSettings ( ) |
def parse ( self , data ) : # type : ( bytes ) - > None
'''Parse the passed in data into a UDF ICB Tag .
Parameters :
data - The data to parse .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'UDF ICB Tag already initialized' )
( self . prior_num_direct_entries , self . strategy_type , self . strategy_param , self . max_num_entries , reserved , self . file_type , self . parent_icb_log_block_num , self . parent_icb_part_ref_num , se... |
def execute ( command , return_output = True , log_file = None , log_settings = None , error_logfile = None , timeout = None , line_function = None , poll_timing = 0.01 , logger = None , working_folder = None , env = None ) :
"""Execute a program and logs standard output into a file .
: param return _ output : re... | tmp_log = False
if log_settings :
log_folder = log_settings . get ( 'LOG_FOLDER' )
else :
tmp_log = True
log_folder = tempfile . mkdtemp ( )
if not log_file :
log_file = os . path . join ( log_folder , "commands" , "execute-command-logfile-%s.log" % UUID . uuid4 ( ) )
try :
if not os . path ... |
def cosine_similarity_vec ( num_tokens , num_removed_vec ) :
"""Return cosine similarity between a binary vector with all ones
of length ` ` num _ tokens ` ` and vectors of the same length with
` ` num _ removed _ vec ` ` elements set to zero .""" | remaining = - np . array ( num_removed_vec ) + num_tokens
return remaining / ( np . sqrt ( num_tokens + 1e-6 ) * np . sqrt ( remaining + 1e-6 ) ) |
def furnish ( app : web . Application ) :
"""Configures Application routes , readying it for running .
This function modifies routes and resources that were added by calling code ,
and must be called immediately prior to ` run ( app ) ` .
Args :
app ( web . Application ) :
The Aiohttp Application as creat... | app_name = app [ 'config' ] [ 'name' ]
prefix = '/' + app_name . lstrip ( '/' )
app . router . add_routes ( routes )
cors_middleware . enable_cors ( app )
# Configure CORS and prefixes on all endpoints .
known_resources = set ( )
for route in list ( app . router . routes ( ) ) :
if route . resource in known_resourc... |
def s3_get ( url : str , temp_file : IO ) -> None :
"""Pull a file directly from S3.""" | s3_resource = boto3 . resource ( "s3" )
bucket_name , s3_path = split_s3_path ( url )
s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file ) |
def from_config ( cls , obj , selectable , ingredient_constructor = ingredient_from_validated_dict , metadata = None ) :
"""Create a shelf using a dict shelf definition .
: param obj : A Python dictionary describing a Shelf .
: param selectable : A SQLAlchemy Table , a Recipe , a table name , or a
SQLAlchemy ... | from recipe import Recipe
if isinstance ( selectable , Recipe ) :
selectable = selectable . subquery ( )
elif isinstance ( selectable , basestring ) :
if '.' in selectable :
schema , tablename = selectable . split ( '.' )
else :
schema , tablename = None , selectable
selectable = Table (... |
def _add_gene_to_graph ( self , gene , variant_bnode , gene_id , relation ) :
""": param gene :
: param variant _ bnode :
: return :""" | model = Model ( self . graph )
if gene_id :
self . graph . addTriple ( variant_bnode , relation , gene_id )
elif gene :
LOG . info ( "gene %s not mapped to NCBI gene, making blank node" , gene )
gene_bnode = self . make_id ( "{0}" . format ( gene ) , "_" )
model . addIndividualToGraph ( gene_bnode , gen... |
def text ( self , x , y , txt = '' ) :
"Output a string" | txt = self . normalize_text ( txt )
if ( self . unifontsubset ) :
txt2 = self . _escape ( UTF8ToUTF16BE ( txt , False ) )
for uni in UTF8StringToArray ( txt ) :
self . current_font [ 'subset' ] . append ( uni )
else :
txt2 = self . _escape ( txt )
s = sprintf ( 'BT %.2f %.2f Td (%s) Tj ET' , x * sel... |
def reduce_ ( self ) :
r"""Return a degree - reduced version of the current curve .
. . _ pseudo - inverse :
https : / / en . wikipedia . org / wiki / Moore % E2%80%93Penrose _ pseudoinverse
Does this by converting the current nodes : math : ` v _ 0 , \ ldots , v _ n `
to new nodes : math : ` w _ 0 , \ ldot... | new_nodes = _curve_helpers . reduce_pseudo_inverse ( self . _nodes )
return Curve ( new_nodes , self . _degree - 1 , _copy = False ) |
def _extract_from_subworkflow ( vs , step ) :
"""Remove internal variable names when moving from sub - workflow to main .""" | substep_ids = set ( [ x . name for x in step . workflow ] )
out = [ ]
for var in vs :
internal = False
parts = var [ "id" ] . split ( "/" )
if len ( parts ) > 1 :
if parts [ 0 ] in substep_ids :
internal = True
if not internal :
var . pop ( "source" , None )
out . app... |
def is_java_project ( self ) :
"""Indicates if the project ' s main binary is a Java Archive .""" | if self . _is_java_project is None :
self . _is_java_project = isinstance ( self . arch , ArchSoot )
return self . _is_java_project |
def unicode_char ( ignored_chars = None ) :
"""returns a handler that listens for unicode characters""" | return lambda e : e . unicode if e . type == pygame . KEYDOWN and ( ( ignored_chars is None ) or ( e . unicode not in ignored_chars ) ) else EventConsumerInfo . DONT_CARE |
def _main ( ) :
"""Command - line program that reads in JSON from stdin and writes out
pretty - printed messages to stdout .""" | if argv [ 1 : ] :
stdout . write ( _CLI_HELP )
raise SystemExit ( )
for line in stdin :
try :
message = loads ( line )
except ValueError :
stdout . write ( "Not JSON: {}\n\n" . format ( line . rstrip ( b"\n" ) ) )
continue
if REQUIRED_FIELDS - set ( message . keys ( ) ) :
... |
def sql_to_csv ( sql , engine , filepath , chunksize = 1000 , overwrite = False ) :
"""Export sql result to csv file .
: param sql : : class : ` sqlalchemy . sql . selectable . Select ` instance .
: param engine : : class : ` sqlalchemy . engine . base . Engine ` .
: param filepath : file path .
: param chu... | if overwrite : # pragma : no cover
if os . path . exists ( filepath ) :
raise Exception ( "'%s' already exists!" % filepath )
import pandas as pd
columns = [ str ( column . name ) for column in sql . columns ]
with open ( filepath , "w" ) as f : # write header
df = pd . DataFrame ( [ ] , columns = colum... |
def base62_decode ( string ) :
"""Decode a Base X encoded string into the number
Arguments :
- ` string ` : The encoded string
- ` alphabet ` : The alphabet to use for encoding
Stolen from : http : / / stackoverflow . com / a / 1119769/1144479""" | alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
base = len ( alphabet )
strlen = len ( string )
num = 0
idx = 0
for char in string :
power = ( strlen - ( idx + 1 ) )
num += alphabet . index ( char ) * ( base ** power )
idx += 1
return int ( num ) |
def _extract_user_info ( user ) :
"""Creates a new user class with extracted user attributes for later use .
A new user object is needed to avoid overwritting of e . g . ` ` user . records ` ` .""" | temp_user = User ( )
copy_attributes = [ 'antennas' , 'name' , 'night_start' , 'night_end' , 'weekend' , 'home' ]
for attr in copy_attributes :
setattr ( temp_user , attr , getattr ( user , attr ) )
return temp_user |
def is_gzip_file ( abspath ) :
"""Parse file extension .
- * . json : uncompressed , utf - 8 encode json file
- * . gz : compressed , utf - 8 encode json file""" | abspath = abspath . lower ( )
_ , ext = os . path . splitext ( abspath )
if ext in [ ".gz" , ".zip" ] :
is_gzip = True
else :
is_gzip = False
return is_gzip |
def emit_children ( self , type = 'other' ) :
'''emit _ children
High - level api : Emit a string presentation of the model .
Parameters
type : ` str `
Type of model content required . Its value can be ' other ' , ' rpc ' , or
' notification ' .
Returns
str
A string presentation of the model that is... | def is_type ( element , type ) :
type_info = element . get ( 'type' )
if type == type_info :
return True
if type == 'rpc' or type == 'notification' :
return False
if type_info == 'rpc' or type_info == 'notification' :
return False
return True
ret = [ ]
for root in [ i for i i... |
def timer ( fun , * a , ** k ) :
"""define a timer for a rule function
for log and statistic purposes""" | @ wraps ( fun )
def timer ( * a , ** k ) :
start = arrow . now ( )
ret = fun ( * a , ** k )
end = arrow . now ( )
print ( 'timer:fun: %s\n start:%s,end:%s, took [%s]' % ( str ( fun ) , str ( start ) , str ( end ) , str ( end - start ) ) )
return ret
return timer |
def roles ( self , value ) :
"""Setter for * * self . _ _ roles * * attribute .
: param value : Attribute value .
: type value : dict""" | if value is not None :
assert type ( value ) is dict , "'{0}' attribute: '{1}' type is not 'dict'!" . format ( "roles" , value )
for key in value :
assert type ( key ) is Qt . ItemDataRole , "'{0}' attribute: '{1}' type is not 'Qt.ItemDataRole'!" . format ( "roles" , key )
self . __roles = value |
def html_to_pdf ( content , encoding = "utf-8" , link_callback = fetch_resources , ** kwargs ) :
"""Converts html ` ` content ` ` into PDF document .
: param unicode content : html content
: returns : PDF content
: rtype : : class : ` bytes `
: raises : : exc : ` ~ easy _ pdf . exceptions . PDFRenderingErro... | src = BytesIO ( content . encode ( encoding ) )
dest = BytesIO ( )
pdf = pisa . pisaDocument ( src , dest , encoding = encoding , link_callback = link_callback , ** kwargs )
if pdf . err :
logger . error ( "Error rendering PDF document" )
for entry in pdf . log :
if entry [ 0 ] == xhtml2pdf . default . ... |
def from_model ( cls , model_name , ** kwargs ) :
"""Define a grid using the specifications of a given model .
Parameters
model _ name : string
Name the model ( see : func : ` get _ supported _ models ` for available
model names ) .
Supports multiple formats ( e . g . , ' GEOS5 ' , ' GEOS - 5 ' or ' GEOS ... | settings = _get_model_info ( model_name )
model = settings . pop ( 'model_name' )
for k , v in list ( kwargs . items ( ) ) :
if k in ( 'resolution' , 'Psurf' ) :
settings [ k ] = v
return cls ( model , ** settings ) |
def V_from_h ( h , D , L , horizontal = True , sideA = None , sideB = None , sideA_a = 0 , sideB_a = 0 , sideA_f = None , sideA_k = None , sideB_f = None , sideB_k = None ) :
r'''Calculates partially full volume of a vertical or horizontal tank with
different head types according to [ 1 ] _ .
Parameters
h : f... | if sideA not in [ None , 'conical' , 'ellipsoidal' , 'torispherical' , 'spherical' , 'guppy' ] :
raise Exception ( 'Unspoorted head type for side A' )
if sideB not in [ None , 'conical' , 'ellipsoidal' , 'torispherical' , 'spherical' , 'guppy' ] :
raise Exception ( 'Unspoorted head type for side B' )
R = D / 2.... |
def sh_e_out ( cls , cmd , ** kwargs ) :
"""Run the command . and returns the stdout .""" | cmd_kwargs = { 'stdout' : subprocess . PIPE , }
cmd_kwargs . update ( kwargs )
return cls . sh_e ( cmd , ** cmd_kwargs ) [ 0 ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.