signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _request ( self , method , url , params = None , uploads = None ) :
"""Request to server and handle transfer status .""" | c = pycurl . Curl ( )
if method == self . POST :
c . setopt ( c . POST , 1 )
if uploads is not None :
if isinstance ( uploads , dict ) : # handle single upload
uploads = [ uploads ]
for upload in uploads :
params += [ ( upload [ 'field' ] , ( c . FORM_FILE , upload [ 'pat... |
def _shutdown ( self ) :
"""Shut down the server .""" | for exit_handler in self . _exit_handlers :
exit_handler ( )
if self . _socket :
self . _socket . close ( )
self . _socket = None |
def listMemberHelps ( TargetGroup ) :
r"""Gets help on a group ' s children .""" | Members = [ ]
for Member in TargetGroup . Members . values ( ) : # get unique children ( by discarding aliases )
if Member not in Members :
Members . append ( Member )
Ret = [ ]
for Member in Members :
Config = Member . Config
Ret . append ( ( '%s%s' % ( Config [ 'name' ] , ', %s' % Config [ 'alias'... |
async def editMessageLiveLocation ( self , msg_identifier , latitude , longitude , reply_markup = None ) :
"""See : https : / / core . telegram . org / bots / api # editmessagelivelocation
: param msg _ identifier : Same as in : meth : ` . Bot . editMessageText `""" | p = _strip ( locals ( ) , more = [ 'msg_identifier' ] )
p . update ( _dismantle_message_identifier ( msg_identifier ) )
return await self . _api_request ( 'editMessageLiveLocation' , _rectify ( p ) ) |
def _called_from_setup ( run_frame ) :
"""Attempt to detect whether run ( ) was called from setup ( ) or by another
command . If called by setup ( ) , the parent caller will be the
' run _ command ' method in ' distutils . dist ' , and * its * caller will be
the ' run _ commands ' method . If called any other... | if run_frame is None :
msg = "Call stack not available. bdist_* commands may fail."
warnings . warn ( msg )
if platform . python_implementation ( ) == 'IronPython' :
msg = "For best results, pass -X:Frames to enable call stack."
warnings . warn ( msg )
return True
res = inspect . getoute... |
def error ( self , msg , previous = False ) :
"""Raise a ParseException .
We provide information to help locate the error in the config to allow
easy config debugging for users . previous indicates that the error
actually occurred at the end of the previous line .""" | token = self . tokens [ self . current_token - 1 ]
line_no = self . line
if previous :
line_no -= 1
line = self . raw [ line_no ]
position = token [ "start" ] - self . line_start
if previous :
position = len ( line ) + 2
raise ParseException ( msg , line , line_no + 1 , position , token [ "value" ] ) |
def create_data_dir ( ) :
"""Creates the DATA _ DIR .
: return :""" | from django_productline . context import PRODUCT_CONTEXT
if not os . path . exists ( PRODUCT_CONTEXT . DATA_DIR ) :
os . mkdir ( PRODUCT_CONTEXT . DATA_DIR )
print ( '*** Created DATA_DIR in %s' % PRODUCT_CONTEXT . DATA_DIR )
else :
print ( '...DATA_DIR already exists.' ) |
def add_header ( self , name : str , value : _HeaderTypes ) -> None :
"""Adds the given response header and value .
Unlike ` set _ header ` , ` add _ header ` may be called multiple times
to return multiple values for the same header .""" | self . _headers . add ( name , self . _convert_header_value ( value ) ) |
def update ( self , data ) :
""": see : : meth : RedisMap . update""" | result = None
if data :
pipe = self . _client . pipeline ( transaction = False )
for k in data . keys ( ) :
pipe . exists ( self . get_key ( k ) )
exists = pipe . execute ( )
exists = exists . count ( True )
_rk , _dumps = self . get_key , self . _dumps
data = { _rk ( key ) : _dumps ( va... |
def input_waiting ( self ) :
"""Query the number of bytes waiting to be read from the serial port .
Returns :
int : number of bytes waiting to be read .
Raises :
SerialError : if an I / O or OS error occurs .""" | # Get input waiting
buf = array . array ( 'I' , [ 0 ] )
try :
fcntl . ioctl ( self . _fd , termios . TIOCINQ , buf , True )
except OSError as e :
raise SerialError ( e . errno , "Querying input waiting: " + e . strerror )
return buf [ 0 ] |
def rtc_as_set ( self ) :
"""Returns current RTC AS configured for current neighbors .""" | rtc_as_set = set ( )
for neigh in self . _neighbors . values ( ) :
rtc_as_set . add ( neigh . rtc_as )
return rtc_as_set |
def load_plugins ( self ) :
"""Load plugins from entry point ( s ) .""" | from pkg_resources import iter_entry_points
seen = set ( )
for entry_point in self . entry_points :
for ep in iter_entry_points ( entry_point ) :
if ep . name in seen :
continue
seen . add ( ep . name )
try :
plugincls = ep . load ( )
except Exception as exc :... |
def input ( self , data ) :
"""小数据片段拼接成完整数据包
如果内容足够则yield数据包""" | self . buf += data
while len ( self . buf ) > HEADER_SIZE :
data_len = struct . unpack ( 'i' , self . buf [ 0 : HEADER_SIZE ] ) [ 0 ]
if len ( self . buf ) >= data_len + HEADER_SIZE :
content = self . buf [ HEADER_SIZE : data_len + HEADER_SIZE ]
self . buf = self . buf [ data_len + HEADER_SIZE :... |
def _next_job ( self ) :
"""execute the next job from the top of the queue""" | if self . __job_queue : # Produce message from the top of the queue
job = self . __job_queue . pop ( )
# logging . debug ( " queue = % s , popped % r " , self . _ _ job _ queue , job )
job . process ( ) |
def yaml ( self , dirPath = None ) :
"""* Render the results in yaml format *
* * Key Arguments : * *
- ` ` dirPath ` ` - - the path to the directory to save the rendered results to . Default * None *
* * Return : * *
- ` yamlSources ` - - the top - level transient data
- ` yamlPhot ` - - all photometry a... | if dirPath :
p = self . _file_prefix ( )
yamlSources = self . sourceResults . yaml ( filepath = dirPath + "/" + p + "sources.yaml" )
yamlPhot = self . photResults . yaml ( filepath = dirPath + "/" + p + "phot.yaml" )
yamlSpec = self . specResults . yaml ( filepath = dirPath + "/" + p + "spec.yaml" )
... |
def column_family_definition ( keyspace , column_family ) :
'''Return a dictionary of column family definitions for the given
keyspace / column _ family
CLI Example :
. . code - block : : bash
salt ' * ' cassandra . column _ family _ definition < keyspace > < column _ family >''' | sys = _sys_mgr ( )
try :
return vars ( sys . get_keyspace_column_families ( keyspace ) [ column_family ] )
except Exception :
log . debug ( 'Invalid Keyspace/CF combination' )
return None |
def get_by_flags ( self , flags ) :
"""Iterate all register infos matching the given flags .""" | for reg in self . _reg_infos :
if reg . flags & flags == flags :
yield reg |
def request ( self , uri , method , * args , ** kwargs ) :
"""Formats the request into a dict representing the headers
and body that will be used to make the API call .""" | if self . timeout :
kwargs [ "timeout" ] = self . timeout
kwargs [ "verify" ] = self . verify_ssl
kwargs . setdefault ( "headers" , kwargs . get ( "headers" , { } ) )
kwargs [ "headers" ] [ "User-Agent" ] = self . user_agent
kwargs [ "headers" ] [ "Accept" ] = "application/json"
if ( "body" in kwargs ) or ( "data" ... |
def _marginal_loglike ( self , x ) :
"""Internal function to calculate and cache the marginal likelihood""" | yedge = self . _nuis_pdf . marginalization_bins ( )
yw = yedge [ 1 : ] - yedge [ : - 1 ]
yc = 0.5 * ( yedge [ 1 : ] + yedge [ : - 1 ] )
s = self . like ( x [ : , np . newaxis ] , yc [ np . newaxis , : ] )
# This does the marginalization integral
z = 1. * np . sum ( s * yw , axis = 1 )
self . _marg_z = np . zeros ( z . ... |
def _parse_canonical_regex ( doc ) :
"""Decode a JSON regex to bson . regex . Regex .""" | regex = doc [ '$regularExpression' ]
if len ( doc ) != 1 :
raise TypeError ( 'Bad $regularExpression, extra field(s): %s' % ( doc , ) )
if len ( regex ) != 2 :
raise TypeError ( 'Bad $regularExpression must include only "pattern"' 'and "options" components: %s' % ( doc , ) )
return Regex ( regex [ 'pattern' ] ,... |
def to_str ( number ) :
"""Convert a task state ID number to a string .
: param int number : task state ID , eg . 1
: returns : state name like eg . " OPEN " , or " ( unknown ) " if we don ' t know the
name of this task state ID number .""" | states = globals ( )
for name , value in states . items ( ) :
if number == value and name . isalpha ( ) and name . isupper ( ) :
return name
return '(unknown state %d)' % number |
def prune ( self , edge , length = None ) :
"""Prunes a subtree from the main Tree , retaining an edge length
specified by length ( defaults to entire length ) . The length is sanity -
checked by edge _ length _ check , to ensure it is within the bounds
[0 , edge . length ] .
Returns the basal node of the p... | length = length or edge . length
edge_length_check ( length , edge )
n = edge . head_node
self . tree . _tree . prune_subtree ( n , suppress_unifurcations = False )
n . edge_length = length
self . tree . _dirty = True
return n |
def get_next_action ( self , request , application , label , roles ) :
"""Process the get _ next _ action request at the current step .""" | # if user is logged and and not applicant , steal the
# application
if 'is_applicant' in roles : # if we got this far , then we either we are logged in as applicant ,
# or we know the secret for this application .
new_person = None
reason = None
details = None
attrs , _ = saml . parse_attributes ( reque... |
def delete_tag ( self , tag ) :
"""DELETE / : login / machines / : id / tags / : tag
Delete a tag and its corresponding value on the machine .""" | j , r = self . datacenter . request ( 'DELETE' , self . path + '/tags/' + tag )
r . raise_for_status ( ) |
def remove_scene ( self , scene_id ) :
"""remove a scene by Scene ID""" | if self . state . activeSceneId == scene_id :
err_msg = "Requested to delete scene {sceneNum}, which is currently active. Cannot delete active scene." . format ( sceneNum = scene_id )
logging . info ( err_msg )
return ( False , 0 , err_msg )
try :
del self . state . scenes [ scene_id ]
logging . deb... |
def print_subcommands ( data , nested_content , markDownHelp = False , settings = None ) :
"""Each subcommand is a dictionary with the following keys :
[ ' usage ' , ' action _ groups ' , ' bare _ usage ' , ' name ' , ' help ' ]
In essence , this is all tossed in a new section with the title ' name ' .
Appare... | definitions = map_nested_definitions ( nested_content )
items = [ ]
if 'children' in data :
subCommands = nodes . section ( ids = [ "Sub-commands:" ] )
subCommands += nodes . title ( 'Sub-commands:' , 'Sub-commands:' )
for child in data [ 'children' ] :
sec = nodes . section ( ids = [ child [ 'name'... |
def make_chunk_for ( output_dir = LOCAL_DIR , local_dir = LOCAL_DIR , game_dir = None , model_num = 1 , positions = EXAMPLES_PER_GENERATION , threads = 8 , sampling_frac = 0.02 ) :
"""Explicitly make a golden chunk for a given model ` model _ num `
( not necessarily the most recent one ) .
While we haven ' t ye... | game_dir = game_dir or fsdb . selfplay_dir ( )
ensure_dir_exists ( output_dir )
models = [ model for model in fsdb . get_models ( ) if model [ 0 ] < model_num ]
buf = ExampleBuffer ( positions , sampling_frac = sampling_frac )
files = [ ]
for _ , model in sorted ( models , reverse = True ) :
local_model_dir = os . ... |
def _get_ignore_from_manifest_lines ( lines ) :
"""Gather the various ignore patterns from a MANIFEST . in .
' lines ' should be a list of strings with comments removed
and continuation lines joined .
Returns a list of standard ignore patterns and a list of regular
expressions to ignore .""" | ignore = [ ]
ignore_regexps = [ ]
for line in lines :
try :
cmd , rest = line . split ( None , 1 )
except ValueError : # no whitespace , so not interesting
continue
for part in rest . split ( ) : # distutils enforces these warnings on Windows only
if part . startswith ( '/' ) :
... |
def subnet_2_json ( self ) :
"""transform ariane _ clip3 subnet object to Ariane server JSON obj
: return : Ariane JSON obj""" | LOGGER . debug ( "Subnet.subnet_2_json" )
json_obj = { 'subnetID' : self . id , 'subnetName' : self . name , 'subnetDescription' : self . description , 'subnetIP' : self . ip , 'subnetMask' : self . mask , 'subnetRoutingAreaID' : self . routing_area_id , 'subnetIPAddressesID' : self . ipAddress_ids , 'subnetLocationsID... |
def raw_datastream ( request , pid , dsid , repo = None , headers = None , as_of_date = None ) :
'''Access raw datastream content from a Fedora object .
Returns : class : ` ~ django . http . HttpResponse ` for HEAD requests ,
: class : ` ~ django . http . StreamingHttpResponse ` for GET requests . The
headers... | return _raw_datastream ( request , pid , dsid , repo = repo , headers = headers , as_of_date = as_of_date ) |
def get_output_key ( self , args , kwargs ) :
"""Return the key that the output should be cached with , given
arguments , keyword arguments , and a list of arguments to ignore .""" | # Get a dictionary mapping argument names to argument values where
# ignored arguments are omitted .
filtered_args = joblib . func_inspect . filter_args ( self . func , self . ignore , args , kwargs )
# Get a sorted tuple of the filtered argument .
filtered_args = tuple ( sorted ( filtered_args . values ( ) ) )
# Use n... |
def state_create ( history_id_key , table_name , collision_checker , always_set = [ ] ) :
"""Decorator for the check ( ) method on state - creating operations .
Makes sure that :
* there is a _ _ preorder _ _ field set , which contains the state - creating operation ' s associated preorder
* there is a _ _ ta... | def wrap ( check ) :
def wrapped_check ( state_engine , nameop , block_id , checked_ops ) :
rc = check ( state_engine , nameop , block_id , checked_ops )
# pretty sure this isn ' t necessary any longer , but leave this is an assert just in case
assert op_get_opcode_name ( nameop [ 'op' ] ) i... |
def collect_num ( self ) :
"""获取答案收藏数
: return : 答案收藏数量
: rtype : int""" | element = self . soup . find ( "a" , { "data-za-a" : "click_answer_collected_count" } )
if element is None :
return 0
else :
return int ( element . get_text ( ) ) |
def handle_set_citation_double ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults :
"""Handle a ` ` SET Citation = { " X " , " Y " } ` ` statement .""" | values = tokens [ 'values' ]
if values [ 0 ] == CITATION_TYPE_PUBMED and not is_int ( values [ 1 ] ) :
raise InvalidPubMedIdentifierWarning ( self . get_line_number ( ) , line , position , values [ 1 ] )
self . citation = dict ( zip ( ( CITATION_TYPE , CITATION_REFERENCE ) , values ) )
return tokens |
def executeAndWait ( self , query , clientCtx ) :
"""run a query synchronously and return a handle ( QueryHandle ) .
Parameters :
- query
- clientCtx""" | self . send_executeAndWait ( query , clientCtx )
return self . recv_executeAndWait ( ) |
def retrieve_xml ( pdb_id , silent = True ) :
'''The RCSB website now compresses XML files .''' | xml_gz = retrieve_file_from_RCSB ( get_rcsb_files_connection ( ) , "/download/%s.xml.gz" % pdb_id , silent = silent )
cf = StringIO . StringIO ( )
cf . write ( xml_gz )
cf . seek ( 0 )
df = gzip . GzipFile ( fileobj = cf , mode = 'rb' )
contents = df . read ( )
df . close ( )
return contents |
def jplace_split ( self , original_jplace , cluster_dict ) :
'''To make GraftM more efficient , reads are dereplicated and merged into
one file prior to placement using pplacer . This function separates the
single jplace file produced by this process into the separate jplace
files , one per input file ( if mu... | output_hash = { }
for placement in original_jplace [ 'placements' ] : # for each placement
alias_placements_list = [ ]
nm_dict = { }
p = placement [ 'p' ]
if 'nm' in placement . keys ( ) :
nm = placement [ 'nm' ]
elif 'n' in placement . keys ( ) :
nm = placement [ 'n' ]
else :
... |
def _var ( self ) :
"""Get / Set a variable .""" | class Variables ( object ) :
def __getitem__ ( _self , name ) :
return self . getVariable ( name )
def __setitem__ ( _self , name , value ) :
self . getVariable ( name ) . setValue ( value )
def __iter__ ( _self ) :
return self . getVariables ( )
return Variables ( ) |
def rerender ( self ) :
'''Rerender all derived images from the original .
If optmization settings or expected sizes changed ,
they will be used for the new rendering .''' | with self . fs . open ( self . original , 'rb' ) as f_img :
img = io . BytesIO ( f_img . read ( ) )
# Store the image in memory to avoid overwritting
self . save ( img , filename = self . filename , bbox = self . bbox , overwrite = True ) |
def xs ( self , key , axis = 0 , level = None , drop_level = True ) :
"""Return cross - section from the Series / DataFrame .
This method takes a ` key ` argument to select data at a particular
level of a MultiIndex .
Parameters
key : label or tuple of label
Label contained in the index , or partially in ... | axis = self . _get_axis_number ( axis )
labels = self . _get_axis ( axis )
if level is not None :
loc , new_ax = labels . get_loc_level ( key , level = level , drop_level = drop_level )
# create the tuple of the indexer
indexer = [ slice ( None ) ] * self . ndim
indexer [ axis ] = loc
indexer = tupl... |
def get_recp_symmetry_operation ( structure , symprec = 0.01 ) :
"""Find the symmetric operations of the reciprocal lattice ,
to be used for hkl transformations
Args :
structure ( Structure ) : conventional unit cell
symprec : default is 0.001""" | recp_lattice = structure . lattice . reciprocal_lattice_crystallographic
# get symmetry operations from input conventional unit cell
# Need to make sure recp lattice is big enough , otherwise symmetry
# determination will fail . We set the overall volume to 1.
recp_lattice = recp_lattice . scale ( 1 )
recp = Structure ... |
def clearAllowList ( self ) :
"""clear all entries in whitelist table
Returns :
True : successful to clear the whitelist
False : fail to clear the whitelist""" | print '%s call clearAllowList' % self . port
# remove all entries in whitelist
try :
print 'clearing whitelist entries:'
for addr in self . _addressfilterSet :
print addr
# disable whitelist
if self . __setAddressfilterMode ( 'disable' ) :
self . _addressfilterMode = 'disable'
# ... |
def advance_by ( self , amount ) :
"""Advance the time reference by the given amount .
: param ` float ` amount : number of seconds to advance .
: raise ` ValueError ` : if * amount * is negative .""" | if amount < 0 :
raise ValueError ( "cannot retreat time reference: amount {} < 0" . format ( amount ) )
self . __delta += amount |
def _get_all_merges ( routing_table ) :
"""Get possible sets of entries to merge .
Yields
: py : class : ` ~ . Merge `""" | # Memorise entries that have been considered as part of a merge
considered_entries = set ( )
for i , entry in enumerate ( routing_table ) : # If we ' ve already considered this entry then skip
if i in considered_entries :
continue
# Construct a merge by including other routing table entries below this
... |
def error ( self , message , set_error_state = False ) :
"""Log an error messsage .
: param message : Log message .""" | if set_error_state :
if message not in self . _errors :
self . _errors . append ( message )
self . set_error_state ( )
self . logger . error ( message ) |
def logon ( ) :
'''Logs into the bluecoat _ sslv device and returns the session cookies .''' | session = requests . session ( )
payload = { "jsonrpc" : "2.0" , "id" : "ID0" , "method" : "login" , "params" : [ DETAILS [ 'username' ] , DETAILS [ 'password' ] , DETAILS [ 'auth' ] , True ] }
logon_response = session . post ( DETAILS [ 'url' ] , data = json . dumps ( payload ) , verify = False )
if logon_response . s... |
def simple_response ( self , status , msg = '' ) :
"""Write a simple response back to the client .""" | status = str ( status )
proto_status = '%s %s\r\n' % ( self . server . protocol , status )
content_length = 'Content-Length: %s\r\n' % len ( msg )
content_type = 'Content-Type: text/plain\r\n'
buf = [ proto_status . encode ( 'ISO-8859-1' ) , content_length . encode ( 'ISO-8859-1' ) , content_type . encode ( 'ISO-8859-1... |
def game_events ( game_id , innings_endpoint = False ) :
"""Return dictionary of events for a game with matching id .""" | # get data from data module
if not innings_endpoint :
data = mlbgame . data . get_game_events ( game_id )
endpoint = 'game_events'
else :
data = mlbgame . data . get_innings ( game_id )
endpoint = 'innings'
# parse XML
parsed = etree . parse ( data )
root = parsed . getroot ( )
# empty output file
outpu... |
def stp ( self , val = True ) :
"""Turn STP protocol on / off .""" | if val :
state = 'on'
else :
state = 'off'
_runshell ( [ brctlexe , 'stp' , self . name , state ] , "Could not set stp on %s." % self . name ) |
def _run ( self ) :
"""Calls self . run ( ) and wraps for errors .""" | try :
if self . run ( ) :
broadcaster . success ( self )
else :
broadcaster . failure ( self )
except StandardError :
import traceback
traceback . print_exc ( )
self . _stop ( )
raise
except Exception :
self . _stop ( )
raise
return True |
def migrate_big_urls ( big_urls = BIG_URLS , inplace = True ) :
r"""Migrate the big _ urls table schema / structure from a dict of lists to a dict of dicts
> > > big _ urls = { ' x ' : ( 1 , 2 , 3 , " 4x " ) , ' y ' : ( " yme " , " cause " ) }
> > > inplace = migrate _ big _ urls ( big _ urls = big _ urls )
>... | if not inplace :
big_urls = deepcopy ( big_urls )
for name , meta in big_urls . items ( ) :
big_urls [ name ] = dict ( zip ( range ( len ( meta ) ) , meta ) )
big_urls [ name ] = dict ( zip ( range ( len ( meta ) ) , meta ) )
# big _ urls [ name ] [ ' filenames ' ] = [ normalize _ ext ( big _ urls ) ]
r... |
def _unsigned_bounds ( self ) :
"""Get lower bound and upper bound for ` self ` in unsigned arithmetic .
: return : a list of ( lower _ bound , upper _ bound ) tuples .""" | ssplit = self . _ssplit ( )
if len ( ssplit ) == 1 :
lb = ssplit [ 0 ] . lower_bound
ub = ssplit [ 0 ] . upper_bound
return [ ( lb , ub ) ]
elif len ( ssplit ) == 2 : # ssplit [ 0 ] is on the left hemisphere , and ssplit [ 1 ] is on the right hemisphere
lb_1 = ssplit [ 0 ] . lower_bound
ub_1 = sspli... |
def fill_out ( self , data , prefix = '' , skip_reset = False ) :
"""Fill out ` ` data ` ` by dictionary ( key is name attribute of inputs ) . You
can pass normal Pythonic data and don ' t have to care about how to use
API of WebDriver .
By ` ` prefix ` ` you can specify prefix of all name attributes . For ex... | for elm_name , value in data . items ( ) :
FormElement ( self , prefix + elm_name ) . fill_out ( value , skip_reset ) |
def list_files ( self , offset = None , limit = None , api = None ) :
"""List files in a folder
: param api : Api instance
: param offset : Pagination offset
: param limit : Pagination limit
: return : List of files""" | api = api or self . _API
if not self . is_folder ( ) :
raise SbgError ( '{name} is not a folder' . format ( name = self . name ) )
url = self . _URL [ 'list_folder' ] . format ( id = self . id )
return super ( File , self . __class__ ) . _query ( api = api , url = url , offset = offset , limit = limit , fields = '_... |
def _raise_error_if_not_sarray ( dataset , variable_name = "SArray" ) :
"""Check if the input is an SArray . Provide a proper error
message otherwise .""" | err_msg = "Input %s is not an SArray."
if not isinstance ( dataset , _SArray ) :
raise ToolkitError ( err_msg % variable_name ) |
def Cylinder ( center = ( 0. , 0. , 0. ) , direction = ( 1. , 0. , 0. ) , radius = 0.5 , height = 1.0 , resolution = 100 , ** kwargs ) :
"""Create the surface of a cylinder .
Parameters
center : list or np . ndarray
Location of the centroid in [ x , y , z ]
direction : list or np . ndarray
Direction cylin... | capping = kwargs . get ( 'capping' , kwargs . get ( 'cap_ends' , True ) )
cylinderSource = vtk . vtkCylinderSource ( )
cylinderSource . SetRadius ( radius )
cylinderSource . SetHeight ( height )
cylinderSource . SetCapping ( capping )
cylinderSource . SetResolution ( resolution )
cylinderSource . Update ( )
surf = Poly... |
def predict ( self , h = 5 , intervals = False ) :
"""Makes forecast with the estimated model
Parameters
h : int ( default : 5)
How many steps ahead would you like to forecast ?
intervals : boolean ( default : False )
Whether to return prediction intervals
Returns
- pd . DataFrame with predicted value... | if self . latent_variables . estimated is False :
raise Exception ( "No latent variables estimated!" )
else :
lmda , Y , scores = self . _model ( self . latent_variables . get_z_values ( ) )
date_index = self . shift_dates ( h )
if self . latent_variables . estimation_method in [ 'M-H' ] :
sim_v... |
def render ( self ) :
"""Render the form and all sections to HTML""" | return Markup ( env . get_template ( 'form.html' ) . render ( form = self , render_open_tag = True , render_close_tag = True , render_before = True , render_sections = True , render_after = True , generate_csrf_token = None if self . disable_csrf else _csrf_generation_function ) ) |
def get_merge ( self , path , local_destination ) :
"""Using snakebite getmerge to implement this .
: param path : HDFS directory
: param local _ destination : path on the system running Luigi
: return : merge of the directory""" | return list ( self . get_bite ( ) . getmerge ( path = path , dst = local_destination ) ) |
def unload ( filename ) :
"""Unload a SPICE kernel .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / unload _ c . html
: param filename : The name of a kernel to unload .
: type filename : str""" | if isinstance ( filename , list ) :
for f in filename :
libspice . unload_c ( stypes . stringToCharP ( f ) )
return
filename = stypes . stringToCharP ( filename )
libspice . unload_c ( filename ) |
def sync_role_definitions ( self ) :
"""Inits the Superset application with security roles and such""" | from superset import conf
logging . info ( 'Syncing role definition' )
self . create_custom_permissions ( )
# Creating default roles
self . set_role ( 'Admin' , self . is_admin_pvm )
self . set_role ( 'Alpha' , self . is_alpha_pvm )
self . set_role ( 'Gamma' , self . is_gamma_pvm )
self . set_role ( 'granter' , self . ... |
def normalize_eols ( text , eol = '\n' ) :
"""Use the same eol ' s in text""" | for eol_char , _ in EOL_CHARS :
if eol_char != eol :
text = text . replace ( eol_char , eol )
return text |
def _handle_sighup ( self , signum : int , frame : Any ) -> None :
"""Used internally to fail the task when connection to RabbitMQ is
lost during the execution of the task .""" | logger . warning ( "Catched SIGHUP" )
exc_info = self . _heartbeat_exc_info
self . _heartbeat_exc_info = None
# Format exception info to see in tools like Sentry .
formatted_exception = '' . join ( traceback . format_exception ( * exc_info ) )
# noqa
raise HeartbeatError ( exc_info ) |
def any_i18n ( * args ) :
"""Return True if any argument appears to be an i18n string .""" | for a in args :
if a is not None and not isinstance ( a , str ) :
return True
return False |
def main ( ) :
"""NAME
plotdi _ a . py
DESCRIPTION
plots equal area projection from dec inc data and fisher mean , cone of confidence
INPUT FORMAT
takes dec , inc , alpha95 as first three columns in space delimited file
SYNTAX
plotdi _ a . py [ - i ] [ - f FILE ]
OPTIONS
- f FILE to read file name... | fmt , plot = 'svg' , 0
if len ( sys . argv ) > 0 :
if '-h' in sys . argv : # check if help is needed
print ( main . __doc__ )
sys . exit ( )
# graceful quit
if '-fmt' in sys . argv :
ind = sys . argv . index ( '-fmt' )
fmt = sys . argv [ ind + 1 ]
if '-sav' in sys . a... |
def uninstall_python ( python , runas = None ) :
'''Uninstall a python implementation .
python
The version of python to uninstall . Should match one of the versions
listed by : mod : ` pyenv . versions < salt . modules . pyenv . versions > `
CLI Example :
. . code - block : : bash
salt ' * ' pyenv . uni... | python = re . sub ( r'^python-' , '' , python )
args = '--force {0}' . format ( python )
_pyenv_exec ( 'uninstall' , args , runas = runas )
return True |
def evaluate_single_config ( hparams , sampling_temp , max_num_noops , agent_model_dir , eval_fn = _eval_fn_with_learner ) :
"""Evaluate the PPO agent in the real environment .""" | tf . logging . info ( "Evaluating metric %s" , get_metric_name ( sampling_temp , max_num_noops , clipped = False ) )
eval_hparams = trainer_lib . create_hparams ( hparams . base_algo_params )
env = setup_env ( hparams , batch_size = hparams . eval_batch_size , max_num_noops = max_num_noops , rl_env_max_episode_steps = ... |
def update_gradients_full ( self , dL_dK , X , X2 = None , reset = True ) :
"""Given the derivative of the objective wrt the covariance matrix
( dL _ dK ) , compute the gradient wrt the parameters of this kernel ,
and store in the parameters object as e . g . self . variance . gradient""" | self . variance . gradient = np . sum ( self . K ( X , X2 ) * dL_dK ) / self . variance
# now the lengthscale gradient ( s )
dL_dr = self . dK_dr_via_X ( X , X2 ) * dL_dK
if self . ARD :
tmp = dL_dr * self . _inv_dist ( X , X2 )
if X2 is None :
X2 = X
if use_stationary_cython :
self . length... |
def pairinplace ( args ) :
"""% prog pairinplace bulk . fasta
Pair up the records in bulk . fasta by comparing the names for adjacent
records . If they match , print to bulk . pairs . fasta , else print to
bulk . frags . fasta .""" | from jcvi . utils . iter import pairwise
p = OptionParser ( pairinplace . __doc__ )
p . add_option ( "-r" , dest = "rclip" , default = 1 , type = "int" , help = "pair ID is derived from rstrip N chars [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help... |
def local_symbol_table ( imports = None , symbols = ( ) ) :
"""Constructs a local symbol table .
Args :
imports ( Optional [ SymbolTable ] ) : Shared symbol tables to import .
symbols ( Optional [ Iterable [ Unicode ] ] ) : Initial local symbols to add .
Returns :
SymbolTable : A mutable local symbol tabl... | return SymbolTable ( table_type = LOCAL_TABLE_TYPE , symbols = symbols , imports = imports ) |
def ext_pillar ( minion_id , # pylint : disable = W0613
pillar , # pylint : disable = W0613
command ) :
'''Execute a command and read the output as YAML''' | try :
command = command . replace ( '%s' , minion_id )
output = __salt__ [ 'cmd.run_stdout' ] ( command , python_shell = True )
return salt . utils . yaml . safe_load ( output )
except Exception :
log . critical ( 'YAML data from \'%s\' failed to parse. Command output:\n%s' , command , output )
retu... |
def refresh_entitlement ( owner , repo , identifier , show_tokens ) :
"""Refresh an entitlement in a repository .""" | client = get_entitlements_api ( )
with catch_raise_api_exception ( ) :
data , _ , headers = client . entitlements_refresh_with_http_info ( owner = owner , repo = repo , identifier = identifier , show_tokens = show_tokens )
ratelimits . maybe_rate_limit ( client , headers )
return data . to_dict ( ) |
def makeUserLoginMethod ( username , password , locale = None ) :
'''Return a function that will call the vim . SessionManager . Login ( ) method
with the given parameters . The result of this function can be passed as
the " loginMethod " to a SessionOrientedStub constructor .''' | def _doLogin ( soapStub ) :
si = vim . ServiceInstance ( "ServiceInstance" , soapStub )
sm = si . content . sessionManager
if not sm . currentSession :
si . content . sessionManager . Login ( username , password , locale )
return _doLogin |
def sign ( self , subject , ** prefs ) :
"""Sign text , a message , or a timestamp using this key .
: param subject : The text to be signed
: type subject : ` ` str ` ` , : py : obj : ` ~ pgpy . PGPMessage ` , ` ` None ` `
: raises : : py : exc : ` ~ pgpy . errors . PGPError ` if the key is passphrase - prote... | sig_type = SignatureType . BinaryDocument
hash_algo = prefs . pop ( 'hash' , None )
if subject is None :
sig_type = SignatureType . Timestamp
if isinstance ( subject , PGPMessage ) :
if subject . type == 'cleartext' :
sig_type = SignatureType . CanonicalDocument
subject = subject . message
sig = PGP... |
def publish_report ( report , args , old_commit , new_commit ) :
"""Publish the RST report based on the user request .""" | # Print the report to stdout unless the user specified - - quiet .
output = ""
if not args . quiet and not args . gist and not args . file :
return report
if args . gist :
gist_url = post_gist ( report , old_commit , new_commit )
output += "\nReport posted to GitHub Gist: {0}" . format ( gist_url )
if args ... |
def qteRegisterMacro ( self , macroCls , replaceMacro : bool = False , macroName : str = None ) :
"""Register a macro .
If ` ` macroName ` ` is * * None * * then its named is deduced from
its class name ( see ` ` qteMacroNameMangling ` ` for details ) .
Multiple macros with the same name can co - exist as lon... | # Check type of input arguments .
if not issubclass ( macroCls , QtmacsMacro ) :
args = ( 'macroCls' , 'class QtmacsMacro' , inspect . stack ( ) [ 0 ] [ 3 ] )
raise QtmacsArgumentError ( * args )
# Try to instantiate the macro class .
try :
macroObj = macroCls ( )
except Exception :
msg = 'The macro <b>... |
def makeLeader ( self , node_id ) :
"""Add an annotation property to the given ` ` ` node _ id ` ` `
to be the clique _ leader .
This is a monarchism .
: param node _ id :
: return :""" | self . graph . addTriple ( node_id , self . globaltt [ 'clique_leader' ] , True , object_is_literal = True , literal_type = 'xsd:boolean' ) |
def get_user_summary ( self , begin_date , end_date ) :
"""获取用户增减数据
详情请参考
http : / / mp . weixin . qq . com / wiki / 3 / ecfed6e1a0a03b5f35e5efac98e864b7 . html
: param begin _ date : 起始日期
: param end _ date : 结束日期
: return : 统计数据列表""" | res = self . _post ( 'getusersummary' , data = { 'begin_date' : self . _to_date_str ( begin_date ) , 'end_date' : self . _to_date_str ( end_date ) } )
return res [ 'list' ] |
def leading_whitespace ( self , inputstring ) :
"""Count leading whitespace .""" | count = 0
for i , c in enumerate ( inputstring ) :
if c == " " :
count += 1
elif c == "\t" :
count += tabworth - ( i % tabworth )
else :
break
if self . indchar is None :
self . indchar = c
elif c != self . indchar :
self . strict_err_or_warn ( "found mixing o... |
def findAddressCandidates ( self , addressDict = None , singleLine = None , maxLocations = 10 , outFields = "*" , outSR = 4326 , searchExtent = None , location = None , distance = 2000 , magicKey = None , category = None ) :
"""The findAddressCandidates operation is performed on a geocode
service resource . The r... | url = self . _url + "/findAddressCandidates"
params = { "f" : "json" , "distance" : distance }
if addressDict is None and singleLine is None :
raise Exception ( "A singleline address or an address dictionary must be passed into this function" )
if not magicKey is None :
params [ 'magicKey' ] = magicKey
if not c... |
def _ensure_module_folder_exists ( ) :
"""Checks to see if the module folder exists . If it does not , create it .
If there is an existing file with the same name , we raise a RuntimeError .""" | if not os . path . isdir ( MODULES_FOLDER_PATH ) :
try :
os . mkdir ( MODULES_FOLDER_PATH )
except OSError , e :
if "file already exists" in str ( e ) :
raise RuntimeError ( "Could not create modules folder: file exists with the same name" ) |
def cas2tas ( cas , h ) :
"""cas2tas conversion both m / s h in m""" | p , rho , T = atmos ( h )
qdyn = p0 * ( ( 1. + rho0 * cas * cas / ( 7. * p0 ) ) ** 3.5 - 1. )
tas = np . sqrt ( 7. * p / rho * ( ( 1. + qdyn / p ) ** ( 2. / 7. ) - 1. ) )
tas = - 1 * tas if cas < 0 else tas
return tas |
def CountFlowLogEntries ( self , client_id , flow_id ) :
"""Returns number of flow log entries of a given flow .""" | return len ( self . ReadFlowLogEntries ( client_id , flow_id , 0 , sys . maxsize ) ) |
def clean_data ( data ) :
"""Shift to lower case , replace unknowns with UNK , and listify""" | new_data = [ ]
VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; '
for sample in data :
new_sample = [ ]
for char in sample [ 1 ] . lower ( ) : # Just grab the string , not the label
if char in VALID :
new_sample . append ( char )
else :
new_sample . append ( 'UNK' )
... |
def write_to_table ( self , query , dataset = None , table = None , external_udf_uris = None , allow_large_results = None , use_query_cache = None , priority = None , create_disposition = None , write_disposition = None , use_legacy_sql = None , maximum_billing_tier = None , flatten = None , project_id = None , ) :
... | configuration = { "query" : query , }
project_id = self . _get_project_id ( project_id )
if dataset and table :
configuration [ 'destinationTable' ] = { "projectId" : project_id , "tableId" : table , "datasetId" : dataset }
if allow_large_results is not None :
configuration [ 'allowLargeResults' ] = allow_large... |
def encode_field ( self , field , value ) :
"""Encode the given value as JSON .
Args :
field : a messages . Field for the field we ' re encoding .
value : a value for field .
Returns :
A python value suitable for json . dumps .""" | for encoder in _GetFieldCodecs ( field , 'encoder' ) :
result = encoder ( field , value )
value = result . value
if result . complete :
return value
if isinstance ( field , messages . EnumField ) :
if field . repeated :
remapped_value = [ GetCustomJsonEnumMapping ( field . type , python_... |
def use_comparative_asset_view ( self ) :
"""Pass through to provider AssetLookupSession . use _ comparative _ asset _ view""" | self . _object_views [ 'asset' ] = COMPARATIVE
# self . _ get _ provider _ session ( ' asset _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_comparative_asset_view ( )
except AttributeError :
pass |
def WriteClientSnapshotHistory ( self , clients ) :
"""Writes the full history for a particular client .""" | if clients [ 0 ] . client_id not in self . metadatas :
raise db . UnknownClientError ( clients [ 0 ] . client_id )
for client in clients :
startup_info = client . startup_info
client . startup_info = None
snapshots = self . clients . setdefault ( client . client_id , { } )
snapshots [ client . times... |
def check_future_import ( node ) :
"""If this is a future import , return set of symbols that are imported ,
else return None .""" | # node should be the import statement here
savenode = node
if not ( node . type == syms . simple_stmt and node . children ) :
return set ( )
node = node . children [ 0 ]
# now node is the import _ from node
if not ( node . type == syms . import_from and # node . type = = token . NAME and # seems to break it
hasattr... |
def ungrab_hotkey ( self , item ) :
"""Ungrab a hotkey .
If the hotkey has no filter regex , it is global and is grabbed recursively from the root window
If it has a filter regex , iterate over all children of the root and ungrab from matching windows""" | import copy
newItem = copy . copy ( item )
if item . get_applicable_regex ( ) is None :
self . __enqueue ( self . __ungrabHotkey , newItem . hotKey , newItem . modifiers , self . rootWindow )
if self . __needsMutterWorkaround ( item ) :
self . __enqueue ( self . __ungrabRecurse , newItem , self . rootWi... |
def typecast ( type_ , value ) :
"""Tries to smartly typecast the given value with the given type .
: param type _ : The type to try to use for the given value
: param value : The value to try and typecast to the given type
: return : The typecasted value if possible , otherwise just the original value""" | # NOTE : does not do any special validation of types before casting
# will just raise errors on type casting failures
if is_builtin_type ( type_ ) or is_collections_type ( type_ ) or is_enum_type ( type_ ) : # FIXME : move to Types enum and TYPE _ MAPPING entry
if is_bytes_type ( type_ ) :
return decode_byt... |
def _get_mod_mtime ( self , filepath ) :
"""Gets the modified time of the file or its accompanying XML file ,
whichever is greater .""" | file_mtime = self . tramp . getmtime ( filepath )
xmlpath = self . get_xmldoc_path ( filepath )
if self . tramp . exists ( xmlpath ) :
xml_mtime = self . tramp . getmtime ( xmlpath )
if xml_mtime > file_mtime :
file_mtime = xml_mtime
return file_mtime |
def _setup_language_variables ( self ) :
"""Check for availability of corpora for a language .
TODO : Make the selection of available languages dynamic from dirs
within ` ` corpora ` ` which contain a ` ` corpora . py ` ` file .""" | if self . language not in AVAILABLE_LANGUAGES : # If no official repos , check if user has custom
user_defined_corpora = self . _check_distributed_corpora_file ( )
if user_defined_corpora :
return user_defined_corpora
else :
msg = 'Corpora not available (either core or user-defined) for the ... |
def show_frontpage ( self ) :
"""If on a subreddit , remember it and head back to the front page .
If this was pressed on the front page , go back to the last subreddit .""" | if self . content . name != '/r/front' :
target = '/r/front'
self . toggled_subreddit = self . content . name
else :
target = self . toggled_subreddit
# target still may be empty string if this command hasn ' t yet been used
if target is not None :
self . refresh_content ( order = 'ignore' , name = targ... |
def GMailer ( recipients , username , password , subject = 'Log message from lggr.py' ) :
"""Sends messages as emails to the given list
of recipients , from a GMail account .""" | import smtplib
srvr = smtplib . SMTP ( 'smtp.gmail.com' , 587 )
srvr . ehlo ( )
srvr . starttls ( )
srvr . ehlo ( )
srvr . login ( username , password )
if not ( isinstance ( recipients , list ) or isinstance ( recipients , tuple ) ) :
recipients = [ recipients ]
gmail_sender = '{0}@gmail.com' . format ( username )... |
def set_cache_url ( self ) :
"""Set the URL to be used for caching .""" | # remove anchor from cached target url since we assume
# URLs with different anchors to have the same content
self . cache_url = urlutil . urlunsplit ( self . urlparts [ : 4 ] + [ u'' ] )
if self . cache_url is not None :
assert isinstance ( self . cache_url , unicode ) , repr ( self . cache_url ) |
def handle_put_account ( self , req ) :
"""Handles the PUT v2 / < account > call for adding an account to the auth
system . Can only be called by a . reseller _ admin .
By default , a newly created UUID4 will be used with the reseller prefix
as the account id used when creating corresponding service accounts ... | if not self . is_reseller_admin ( req ) :
return self . denied_response ( req )
account = req . path_info_pop ( )
if req . path_info or not account or account [ 0 ] == '.' :
return HTTPBadRequest ( request = req )
account_suffix = req . headers . get ( 'x-account-suffix' )
if not account_suffix :
account_su... |
def get_turbine_data_from_oedb ( turbine_type , fetch_curve , overwrite = False ) :
r"""Fetches data for one wind turbine type from the OpenEnergy Database ( oedb ) .
If turbine data exists in local repository it is loaded from this file . The
file is created when turbine data was loaded from oedb in
: py : f... | # hdf5 filename
filename = os . path . join ( os . path . dirname ( __file__ ) , 'data' , 'turbine_data_oedb.h5' )
if os . path . isfile ( filename ) and not overwrite :
logging . debug ( "Turbine data is fetched from {}" . format ( filename ) )
with pd . HDFStore ( filename ) as hdf_store :
turbine_dat... |
def find_usage ( self ) :
"""Determine the current usage for each limit of this service ,
and update corresponding Limit via
: py : meth : ` ~ . AwsLimit . _ add _ current _ usage ` .""" | logger . debug ( "Checking usage for service %s" , self . service_name )
self . connect ( )
for lim in self . limits . values ( ) :
lim . _reset_usage ( )
try :
self . _find_usage_filesystems ( )
except ( EndpointConnectionError , ClientError , ConnectTimeout ) as ex :
logger . warning ( 'Caught exception w... |
def nb_fit ( data , P_init = None , R_init = None , epsilon = 1e-8 , max_iters = 100 ) :
"""Fits the NB distribution to data using method of moments .
Args :
data ( array ) : genes x cells
P _ init ( array , optional ) : NB success prob param - genes x 1
R _ init ( array , optional ) : NB stopping param - g... | means = data . mean ( 1 )
variances = data . var ( 1 )
if ( means > variances ) . any ( ) :
raise ValueError ( "For NB fit, means must be less than variances" )
genes , cells = data . shape
# method of moments
P = 1.0 - means / variances
R = means * ( 1 - P ) / P
for i in range ( genes ) :
result = minimize ( n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.