signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _mkprox ( funcname ) :
"""Make lazy - init proxy function .""" | def prox ( * args , ** kwargs ) :
_init ( )
return getattr ( _module , funcname ) ( * args , ** kwargs )
return prox |
def visit_For ( self , node ) :
"""OUT = ( node , ) + last body statements
RAISES = body ' s that are not break or continue""" | currs = ( node , )
break_currs = tuple ( )
raises = ( )
# handle body
for n in node . body :
self . result . add_node ( n )
for curr in currs :
self . result . add_edge ( curr , n )
currs , nraises = self . visit ( n )
for nraise in nraises :
if isinstance ( nraise , ast . Break ) :
... |
def get_free_gpus ( max_procs = 0 ) :
"""Checks the number of processes running on your GPUs .
Parameters
max _ procs : int
Maximum number of procs allowed to run on a gpu for it to be considered
' available '
Returns
availabilities : list ( bool )
List of length N for an N - gpu system . The nth valu... | # Try connect with NVIDIA drivers
logger = logging . getLogger ( __name__ )
try :
py3nvml . nvmlInit ( )
except :
str_ = """Couldn't connect to nvml drivers. Check they are installed correctly."""
warnings . warn ( str_ , RuntimeWarning )
logger . warn ( str_ )
return [ ]
num_gpus = py3nvml . nvmlDe... |
def parse_string ( self , string , best = False ) :
'''Parses ` ` string ` ` trying to match each word to a : class : ` Concept ` . If ` ` best ` ` , will only return the top matches''' | if isinstance ( string , list ) :
items = string
else :
items = string . split ( )
item_list = [ ]
not_next = False
for item in items :
if self . negative :
if item == 'not' :
not_next = True
continue
if item [ 0 ] == '-' :
not_next = True
item... |
def get_ip_interface_output_interface_if_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_ip_interface = ET . Element ( "get_ip_interface" )
config = get_ip_interface
output = ET . SubElement ( get_ip_interface , "output" )
interface = ET . SubElement ( output , "interface" )
interface_type_key = ET . SubElement ( interface , "interface-type" )
interface_type_key . tex... |
def post_save_moderation ( self , sender , comment , request , ** kwargs ) :
"""Apply any necessary post - save moderation steps to new
comments .""" | model = comment . content_type . model_class ( )
if model not in self . _registry :
return
self . _registry [ model ] . email ( comment , comment . content_object , request ) |
def relation ( self , geometries1 , geometries2 , sr , relation = "esriGeometryRelationIntersection" , relationParam = "" ) :
"""The relation operation is performed on a geometry service resource . This
operation determines the pairs of geometries from the input geometry arrays
that participate in the specified... | relationType = [ "esriGeometryRelationCross" , "esriGeometryRelationDisjoint" , "esriGeometryRelationIn" , "esriGeometryRelationInteriorIntersection" , "esriGeometryRelationIntersection" , "esriGeometryRelationLineCoincidence" , "esriGeometryRelationLineTouch" , "esriGeometryRelationOverlap" , "esriGeometryRelationPoin... |
def descriptor_for_symbol ( self , symbol ) :
"""Given the symbol associated with the problem .
Returns the : class : ` ~ means . core . descriptors . Descriptor ` associated with that symbol
: param symbol : Symbol
: type symbol : basestring | : class : ` sympy . Symbol `
: return :""" | if isinstance ( symbol , basestring ) :
symbol = sympy . Symbol ( symbol )
try :
return self . _descriptions_dict [ symbol ]
except KeyError :
raise KeyError ( "Symbol {0!r} not found in left-hand-side of the equations" . format ( symbol ) ) |
def _get_renamed_diff ( self , blueprint , command , column , schema ) :
"""Get a new column instance with the new column name .
: param blueprint : The blueprint
: type blueprint : Blueprint
: param command : The command
: type command : Fluent
: param column : The column
: type column : orator . dbal ... | table_diff = self . _get_table_diff ( blueprint , schema )
return self . _set_renamed_columns ( table_diff , command , column ) |
def compute_from_text ( self , text , beta = 0.001 ) :
"""m . compute _ from _ text ( , text , beta = 0.001 ) - - Compute a matrix values from a text string of ambiguity codes .
Use Motif _ from _ text utility instead to build motifs on the fly .""" | prevlett = { 'B' : 'A' , 'D' : 'C' , 'V' : 'T' , 'H' : 'G' }
countmat = [ ]
text = re . sub ( '[\.\-]' , 'N' , text . upper ( ) )
for i in range ( len ( text ) ) :
D = { 'A' : 0 , 'C' : 0 , 'T' : 0 , 'G' : 0 }
letter = text [ i ]
if letter in [ 'B' , 'D' , 'V' , 'H' ] : # B = = no " A " , etc . . .
... |
def resize ( self , width , height ) :
"""Resizes the widget .
: param int width :
The width of the widget .
: param int height :
The height of the widget .""" | self . _width = width
self . _height = height
# update radio buttons width
for item in self . _rbuttons :
item . width = width
# update radio buttons height
if len ( self . _rbuttons ) > 0 : # work out the height of a button
button_height = height
if isinstance ( height , int ) :
if height % len ( s... |
def get_queryset_filters ( self , query ) :
"""Return the filtered queryset""" | conditions = Q ( )
for field_name in self . fields :
conditions |= Q ( ** { self . _construct_qs_filter ( field_name ) : query } )
return conditions |
def diff ( local_path , remote_path ) :
"""Return true if local and remote paths differ in contents""" | with hide ( 'commands' ) :
if isinstance ( local_path , basestring ) :
with open ( local_path ) as stream :
local_content = stream . read ( )
else :
pos = local_path . tell ( )
local_content = local_path . read ( )
local_path . seek ( pos )
remote_content = String... |
def _currentlyValidAsReferentFor ( self , store ) :
"""Is this object currently valid as a reference ? Objects which will be
deleted in this transaction , or objects which are not in the same store
are not valid . See attributes . reference . _ _ get _ _ .""" | if store is None : # If your store is None , you can refer to whoever you want . I ' m in
# a store but it doesn ' t matter that you ' re not .
return True
if self . store is not store :
return False
if self . __deletingObject :
return False
return True |
def registerSingleton ( self , key , factoryMethod , disposeMethod = None ) :
"""Binds a singleton instance to a key : whenever the requested key is resolved ,
if the instance is still None , it is created by calling factoryMethod ( container , key ) ;
otherwise , it is just returned .
When the client calls d... | return self . addRegistration ( key , SingletonRegistration ( factoryMethod , disposeMethod ) ) |
def simxSetJointPosition ( clientID , jointHandle , position , operationMode ) :
'''Please have a look at the function description / documentation in the V - REP user manual''' | return c_SetJointPosition ( clientID , jointHandle , position , operationMode ) |
def rebuild ( cls , session , tree_id = None ) :
"""This function rebuid tree .
Args :
session ( : mod : ` sqlalchemy . orm . session . Session ` ) : SQLAlchemy session
Kwargs :
tree _ id ( int or str ) : id of tree , default None
Example :
* : mod : ` sqlalchemy _ mptt . tests . TestTree . test _ rebui... | trees = session . query ( cls ) . filter_by ( parent_id = None )
if tree_id :
trees = trees . filter_by ( tree_id = tree_id )
for tree in trees :
cls . rebuild_tree ( session , tree . tree_id ) |
def _get_boolean ( data , position , dummy0 , dummy1 , dummy2 ) :
"""Decode a BSON true / false to python True / False .""" | end = position + 1
boolean_byte = data [ position : end ]
if boolean_byte == b'\x00' :
return False , end
elif boolean_byte == b'\x01' :
return True , end
raise InvalidBSON ( 'invalid boolean value: %r' % boolean_byte ) |
async def send_debug ( self ) :
"""Sends the debug draw execution . Put this after your debug creation functions .""" | await self . _execute ( debug = sc_pb . RequestDebug ( debug = [ debug_pb . DebugCommand ( draw = debug_pb . DebugDraw ( text = self . _debug_texts if self . _debug_texts else None , lines = self . _debug_lines if self . _debug_lines else None , boxes = self . _debug_boxes if self . _debug_boxes else None , spheres = s... |
def n_sed_plates_max ( sed_inputs = sed_dict ) :
"""Return the maximum possible number of plate settlers in a module given
plate spacing , thickness , angle , and unsupported length of plate settler .
Parameters
S _ plate : float
Edge to edge distance between plate settlers
thickness _ plate : float
Thi... | B_plate = sed_inputs [ 'plate_settlers' ] [ 'S' ] + sed_inputs [ 'plate_settlers' ] [ 'thickness' ]
return math . floor ( ( sed_inputs [ 'plate_settlers' ] [ 'L_cantilevered' ] . magnitude / B_plate . magnitude * np . tan ( sed_inputs [ 'plate_settlers' ] [ 'angle' ] . to ( u . rad ) . magnitude ) ) + 1 ) |
def _compileSmsRegexes ( self ) :
"""Compiles regular expression used for parsing SMS messages based on current mode""" | if self . _smsTextMode :
if self . CMGR_SM_DELIVER_REGEX_TEXT == None :
self . CMGR_SM_DELIVER_REGEX_TEXT = re . compile ( r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$' )
self . CMGR_SM_REPORT_REGEXT_TEXT = re . compile ( r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\... |
def _from_line ( cls , remote , line ) :
"""Create a new PushInfo instance as parsed from line which is expected to be like
refs / heads / master : refs / heads / master 05d2687 . . 1d0568e as bytes""" | control_character , from_to , summary = line . split ( '\t' , 3 )
flags = 0
# control character handling
try :
flags |= cls . _flag_map [ control_character ]
except KeyError :
raise ValueError ( "Control character %r unknown as parsed from line %r" % ( control_character , line ) )
# END handle control character... |
def Maxout ( x , num_unit ) :
"""Maxout as in the paper ` Maxout Networks < http : / / arxiv . org / abs / 1302.4389 > ` _ .
Args :
x ( tf . Tensor ) : a NHWC or NC tensor . Channel has to be known .
num _ unit ( int ) : a int . Must be divisible by C .
Returns :
tf . Tensor : of shape NHW ( C / num _ uni... | input_shape = x . get_shape ( ) . as_list ( )
ndim = len ( input_shape )
assert ndim == 4 or ndim == 2
ch = input_shape [ - 1 ]
assert ch is not None and ch % num_unit == 0
if ndim == 4 :
x = tf . reshape ( x , [ - 1 , input_shape [ 1 ] , input_shape [ 2 ] , ch / num_unit , num_unit ] )
else :
x = tf . reshape ... |
def from_bytes ( self , raw ) :
'''Return an Ethernet object reconstructed from raw bytes , or an
Exception if we can ' t resurrect the packet .''' | if len ( raw ) < Arp . _MINLEN :
raise NotEnoughDataError ( "Not enough bytes ({}) to reconstruct an Arp object" . format ( len ( raw ) ) )
fields = struct . unpack ( Arp . _PACKFMT , raw [ : Arp . _MINLEN ] )
try :
self . _hwtype = ArpHwType ( fields [ 0 ] )
self . _prototype = EtherType ( fields [ 1 ] )
... |
def parse_sgtin_96 ( sgtin_96 ) :
'''Given a SGTIN - 96 hex string , parse each segment .
Returns a dictionary of the segments .''' | if not sgtin_96 :
raise Exception ( 'Pass in a value.' )
if not sgtin_96 . startswith ( "30" ) : # not a sgtin , not handled
raise Exception ( 'Not SGTIN-96.' )
binary = "{0:020b}" . format ( int ( sgtin_96 , 16 ) ) . zfill ( 96 )
header = int ( binary [ : 8 ] , 2 )
tag_filter = int ( binary [ 8 : 11 ] , 2 )
pa... |
def ReceiveSOAP ( self , readerclass = None , ** kw ) :
'''Get back a SOAP message .''' | if self . ps :
return self . ps
if not self . IsSOAP ( ) :
raise TypeError ( 'Response is "%s", not "text/xml"' % self . reply_headers . type )
if len ( self . data ) == 0 :
raise TypeError ( 'Received empty response' )
self . ps = ParsedSoap ( self . data , readerclass = readerclass or self . readerclass ,... |
def _compute_oneletter ( self ) :
"""m . _ compute _ oneletter ( ) - - [ utility ] Set the oneletter member variable""" | letters = [ ]
for i in range ( self . width ) :
downcase = None
if self . bits [ i ] < 0.25 :
letters . append ( '.' )
continue
if self . bits [ i ] < 1.0 :
downcase = 'True'
tups = [ ( self . ll [ i ] [ x ] , x ) for x in ACGT if self . ll [ i ] [ x ] > 0.0 ]
if not tups : #... |
def read_lexical_file ( filename ) :
'''Reads in a GermaNet lexical information file and returns its
contents as a list of dictionary structures .
Arguments :
- ` filename ` : the name of the XML file to read''' | with open ( filename , 'rb' ) as input_file :
doc = etree . parse ( input_file )
synsets = [ ]
assert doc . getroot ( ) . tag == 'synsets'
for synset in doc . getroot ( ) :
if synset . tag != 'synset' :
print ( 'unrecognised child of <synsets>' , synset )
continue
synset_dict = dict ( synset... |
def set_pprint_format ( indent = None , width = None , depth = None ) :
"""This will set the constants for the pprint
: param indent : number of spaces to indent
: param width : max width of the line
: param depth : mas depth of the objects
: return : current settings""" | if indent is not None :
PPRINT_FORMAT [ 'indent' ] = indent
if width is not None :
PPRINT_FORMAT [ 'width' ] = width
if depth is not None :
PPRINT_FORMAT [ 'depth' ] = depth
return PPRINT_FORMAT |
def csv_from_items ( items , stream = None ) :
"""Write a list of items to stream in CSV format .
The items need to be attrs - decorated .""" | items = iter ( items )
first = next ( items )
cls = first . __class__
if stream is None :
stream = sys . stdout
fields = [ f . name for f in attr . fields ( cls ) ]
writer = csv . DictWriter ( stream , fieldnames = fields )
writer . writeheader ( )
writer . writerow ( attr . asdict ( first ) )
writer . writerows ( ... |
def _run_prospector ( filename , stamp_file_name , disabled_linters , show_lint_files ) :
"""Run prospector .""" | linter_tools = [ "pep257" , "pep8" , "pyflakes" ]
if can_run_pylint ( ) :
linter_tools . append ( "pylint" )
# Run prospector on tests . There are some errors we don ' t care about :
# - invalid - name : This is often triggered because test method names
# can be quite long . Descriptive test method names are
# good... |
def cummean ( expr , sort = None , ascending = True , unique = False , preceding = None , following = None ) :
"""Calculate cumulative mean of a sequence expression .
: param expr : expression for calculation
: param sort : name of the sort column
: param ascending : whether to sort in ascending order
: par... | data_type = _stats_type ( expr )
return _cumulative_op ( expr , CumMean , sort = sort , ascending = ascending , unique = unique , preceding = preceding , following = following , data_type = data_type ) |
def get_nodes_id_list_by_type ( self , node_type ) :
"""Get a list of node ' s id by requested type .
Returns a list of ids
: param node _ type : string with valid BPMN XML tag name ( e . g . ' task ' , ' sequenceFlow ' ) .""" | tmp_nodes = self . diagram_graph . nodes ( data = True )
id_list = [ ]
for node in tmp_nodes :
if node [ 1 ] [ consts . Consts . type ] == node_type :
id_list . append ( node [ 0 ] )
return id_list |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'entities' ) and self . entities is not None :
_dict [ 'entities' ] = [ x . _to_dict ( ) for x in self . entities ]
if hasattr ( self , 'location' ) and self . location is not None :
_dict [ 'location' ] = self . location
if hasattr ( self , 'text' ) and self . text is not None :... |
def mk_dropdown_tree ( cls , model , for_node = None ) :
"""Creates a tree - like list of choices""" | options = [ ( 0 , _ ( '-- root --' ) ) ]
for node in model . get_root_nodes ( ) :
cls . add_subtree ( for_node , node , options )
return options |
def cmServiceAccept ( ) :
"""CM SERVICE ACCEPT Section 9.2.5""" | a = TpPd ( pd = 0x5 )
b = MessageType ( mesType = 0x21 )
# 00100001
packet = a / b
return packet |
def lookup ( self , coordinates ) :
"""Lookup values at coordinates .
coordinates : arraylike of coordinates .
Clips if out of range ! ! TODO : option to throw exception instead .
TODO : Needs tests ! !""" | # Convert coordinates to indices
index_array = np . clip ( np . searchsorted ( self . bin_edges , coordinates ) - 1 , 0 , len ( self . bin_edges ) - 2 )
# Use the index array to slice the histogram
return self . histogram [ index_array ] |
def set_data ( self , data , copy = False ) :
"""Set data in the buffer ( deferred operation ) .
This completely resets the size and contents of the buffer .
Parameters
data : ndarray
Data to be uploaded
copy : bool
Since the operation is deferred , data may change before
data is actually uploaded to ... | data = np . array ( data , copy = copy )
nbytes = data . nbytes
if nbytes != self . _nbytes :
self . resize_bytes ( nbytes )
else : # Use SIZE to discard any previous data setting
self . _glir . command ( 'SIZE' , self . _id , nbytes )
if nbytes : # Only set data if there * is * data
self . _glir . command ... |
def set_value ( self , iter , column , value ) :
"""Set the value of the child model""" | # Delegate to child model
iter = self . convert_iter_to_child_iter ( iter )
self . get_model ( ) . set_value ( iter , column , value ) |
def sasviyaml ( self ) -> 'SASViyaML' :
"""This methods creates a SASViyaML object which you can use to run various analytics .
See the SASViyaML . py module .
: return : SASViyaML object""" | if not self . _loaded_macros :
self . _loadmacros ( )
self . _loaded_macros = True
return SASViyaML ( self ) |
def clean_pieces ( self , pieces ) :
"""Cleans the list of strings given as ` pieces ` . It replaces
multiple newlines by a maximum of 2 and returns a new list .
It also wraps the paragraphs nicely .""" | ret = [ ]
count = 0
for i in pieces :
if i == '\n' :
count = count + 1
else :
if i == '";' :
if count :
ret . append ( '\n' )
elif count > 2 :
ret . append ( '\n\n' )
elif count :
ret . append ( '\n' * count )
count = 0
... |
def get_integers ( bitwidth , unsigned , limit = 0 ) :
'''Get integers from fuzzdb database
bitwidth - The bitwidth that has to contain the integer
unsigned - Whether the type is unsigned
limit - Limit to | limit | results''' | if unsigned :
start , stop = 0 , ( ( 1 << bitwidth ) - 1 )
else :
start , stop = ( - ( 1 << bitwidth - 1 ) ) , ( 1 << ( bitwidth - 1 ) - 1 )
for num in _fuzzdb_integers ( limit ) :
if num >= start and num <= stop :
yield num |
def getAuthenticatedUser ( self , headers = None , query_params = None , content_type = "application/json" ) :
"""Get currently authenticated user ( if any ) .
It is method for GET / self""" | uri = self . client . base_url + "/self"
return self . client . get ( uri , None , headers , query_params , content_type ) |
def itemStyle ( self ) :
"""Returns the item style information for this item .
: return < XGanttWidgetItem . ItemStyle >""" | if ( self . useGroupStyleWithChildren ( ) and self . childCount ( ) ) :
return XGanttWidgetItem . ItemStyle . Group
return self . _itemStyle |
def override_role_permissions ( self ) :
"""Updates the role with the give datasource permissions .
Permissions not in the request will be revoked . This endpoint should
be available to admins only . Expects JSON in the format :
' role _ name ' : ' { role _ name } ' ,
' database ' : [ {
' datasource _ typ... | data = request . get_json ( force = True )
role_name = data [ 'role_name' ]
databases = data [ 'database' ]
db_ds_names = set ( )
for dbs in databases :
for schema in dbs [ 'schema' ] :
for ds_name in schema [ 'datasources' ] :
fullname = utils . get_datasource_full_name ( dbs [ 'name' ] , ds_na... |
def bounce_local ( drain = False ) :
'''Bounce Traffic Server on the local node . Bouncing Traffic Server shuts down
and immediately restarts the Traffic Server node .
drain
This option modifies the restart behavior such that traffic _ server
is not shut down until the number of active client connections
... | if _TRAFFICCTL :
cmd = _traffic_ctl ( 'server' , 'restart' )
else :
cmd = _traffic_line ( '-b' )
if drain :
cmd = cmd + [ '--drain' ]
return _subprocess ( cmd ) |
def ipath_from_ext ( self , ext ) :
"""Returns the path of the input file with extension ext .
Use it when the file does not exist yet .""" | return os . path . join ( self . workdir , self . prefix . idata + "_" + ext ) |
def add_vlan ( self , vlan_id , full_name , port_mode , qnq , c_tag ) :
"""Run flow to add VLAN ( s ) to interface
: param vlan _ id : Already validated number of VLAN ( s )
: param full _ name : Full interface name . Example : 2950 / Chassis 0 / FastEthernet0-23
: param port _ mode : port mode type . Should ... | try :
action_result = self . add_vlan_flow . execute_flow ( vlan_range = vlan_id , port_mode = port_mode , port_name = full_name , qnq = qnq , c_tag = c_tag )
self . result [ current_thread ( ) . name ] . append ( ( True , action_result ) )
except Exception as e :
self . _logger . error ( traceback . format... |
def __setKeySwitchGuardTime ( self , iKeySwitchGuardTime ) :
"""set the Key switch guard time
Args :
iKeySwitchGuardTime : key switch guard time
Returns :
True : successful to set key switch guard time
False : fail to set key switch guard time""" | print '%s call setKeySwitchGuardTime' % self . port
print iKeySwitchGuardTime
try :
cmd = 'keysequence guardtime %s' % str ( iKeySwitchGuardTime )
if self . __sendCommand ( cmd ) [ 0 ] == 'Done' :
time . sleep ( 1 )
return True
else :
return False
except Exception , e :
ModuleHel... |
def stop_volume ( name , force = False ) :
'''Stop a gluster volume
name
Volume name
force
Force stop the volume
. . versionadded : : 2015.8.4
CLI Example :
. . code - block : : bash
salt ' * ' glusterfs . stop _ volume mycluster''' | volinfo = info ( )
if name not in volinfo :
log . error ( 'Cannot stop non-existing volume %s' , name )
return False
if int ( volinfo [ name ] [ 'status' ] ) != 1 :
log . warning ( 'Attempt to stop already stopped volume %s' , name )
return True
cmd = 'volume stop {0}' . format ( name )
if force :
c... |
def manager ( self , ** kwargs ) :
"""Return a preference manager that can be used to retrieve preference values""" | return PreferencesManager ( registry = self , model = self . preference_model , ** kwargs ) |
def minify_css_files ( ) :
"""This command minified js files with UglifyCSS""" | for k , v in CSS_FILE_MAPPING . items ( ) :
input_files = " " . join ( v [ "input_files" ] )
output_file = v [ "output_file" ]
uglifyjs_command = "uglifycss {input_files} > {output_file}" . format ( input_files = input_files , output_file = output_file )
local ( uglifyjs_command ) |
def _end_file_syncing ( self , exitcode ) :
"""Stops file syncing / streaming but doesn ' t actually wait for everything to
finish . We print progress info later .""" | # TODO : there was a case where _ file _ event _ handlers was getting modified in the loop .
for handler in list ( self . _file_event_handlers . values ( ) ) :
handler . finish ( )
self . _file_pusher . finish ( )
self . _api . get_file_stream_api ( ) . finish ( exitcode )
# In Jupyter notebooks , wandb . init can ... |
def project ( * args , ** kwargs ) :
"""Build a projection for MongoDB .
Due to https : / / jira . mongodb . org / browse / SERVER - 3156 , until MongoDB 2.6,
the values must be integers and not boolean .
> > > project ( a = True ) = = { ' a ' : 1}
True
Once MongoDB 2.6 is released , replace use of this f... | projection = dict ( * args , ** kwargs )
return { key : int ( value ) for key , value in six . iteritems ( projection ) } |
def parse_data_slots ( value ) :
"""Parse data - slots value into slots used to wrap node , prepend to node or
append to node .
> > > parse _ data _ slots ( ' ' )
> > > parse _ data _ slots ( ' foo bar ' )
( [ ' foo ' , ' bar ' ] , [ ] , [ ] )
> > > parse _ data _ slots ( ' foo bar > foobar ' )
( [ ' fo... | value = unquote ( value )
if '>' in value :
wrappers , children = value . split ( '>' , 1 )
else :
wrappers = value
children = ''
if '*' in children :
prepends , appends = children . split ( '*' , 1 )
else :
prepends = children
appends = ''
wrappers = list ( filter ( bool , list ( map ( str . st... |
def sg_queue_context ( sess = None ) :
r"""Context helper for queue routines .
Args :
sess : A session to open queues . If not specified , a new session is created .
Returns :
None""" | # default session
sess = tf . get_default_session ( ) if sess is None else sess
# thread coordinator
coord = tf . train . Coordinator ( )
try : # start queue thread
threads = tf . train . start_queue_runners ( sess , coord )
yield
finally : # stop queue thread
coord . request_stop ( )
# wait thread to e... |
def int_dp_g ( arr , dp ) :
"""Mass weighted integral .""" | return integrate ( arr , to_pascal ( dp , is_dp = True ) , vert_coord_name ( dp ) ) / GRAV_EARTH |
def node_multiplier ( self , multiplier = 0.5 , seed = None ) :
"""Returns a toytree copy with all nodes multiplied by a constant
sampled uniformly between ( multiplier , 1 / multiplier ) .""" | random . seed ( seed )
ctree = self . _ttree . copy ( )
low , high = sorted ( [ multiplier , 1. / multiplier ] )
mult = random . uniform ( low , high )
for node in ctree . treenode . traverse ( ) :
node . dist = node . dist * mult
ctree . _coords . update ( )
return ctree |
def make_mapping ( self ) -> None :
"""Replaces the node with a new , empty mapping .
Note that this will work on the Node object that is passed to a yatiml _ savorize ( ) or yatiml _ sweeten ( ) function , but not on any of its attributes or items . If you need to set an attribute to a complex value , build a ya... | start_mark = StreamMark ( 'generated node' , 0 , 0 , 0 )
end_mark = StreamMark ( 'generated node' , 0 , 0 , 0 )
self . yaml_node = yaml . MappingNode ( 'tag:yaml.org,2002:map' , list ( ) , start_mark , end_mark ) |
def log_start ( task , logger = "TaskLogger" ) :
"""Begin logging of a task
Convenience function to log a task in the default
TaskLogger
Parameters
task : str
Name of the task to be started
logger : str , optional ( default : " TaskLogger " )
Unique name of the logger to retrieve
Returns
logger : ... | tasklogger = get_tasklogger ( logger )
tasklogger . start_task ( task )
return tasklogger |
def check_files_on_host ( java_home , host , files , batch_size ) :
"""Check the files on the host . Files are grouped together in groups
of batch _ size files . The dump class will be executed on each batch ,
sequentially .
: param java _ home : the JAVA _ HOME of the broker
: type java _ home : str
: pa... | with closing ( ssh_client ( host ) ) as ssh :
for i , batch in enumerate ( chunks ( files , batch_size ) ) :
command = check_corrupted_files_cmd ( java_home , batch )
_ , stdout , stderr = ssh . exec_command ( command )
report_stderr ( host , stderr )
print ( " {host}: file {n_file}... |
def _lookupIterator ( self , val ) :
"""An internal function to generate lookup iterators .""" | if val is None :
return lambda el , * args : el
return val if _ . isCallable ( val ) else lambda obj , * args : obj [ val ] |
def decode ( dct , intype = 'json' , raise_error = False ) :
"""decode dict objects , via decoder plugins , to new type
Parameters
intype : str
use decoder method from _ < intype > to encode
raise _ error : bool
if True , raise ValueError if no suitable plugin found
Examples
> > > load _ builtin _ plu... | for decoder in get_plugins ( 'decoders' ) . values ( ) :
if ( set ( list ( decoder . dict_signature ) ) . issubset ( dct . keys ( ) ) and hasattr ( decoder , 'from_{}' . format ( intype ) ) and getattr ( decoder , 'allow_other_keys' , False ) ) :
return getattr ( decoder , 'from_{}' . format ( intype ) ) ( ... |
def web_command ( command , ro = None , rw = None , links = None , image = 'datacats/web' , volumes_from = None , commit = False , clean_up = False , stream_output = None , entrypoint = None ) :
"""Run a single command in a web image optionally preloaded with the ckan
source and virtual envrionment .
: param co... | binds = ro_rw_to_binds ( ro , rw )
c = _get_docker ( ) . create_container ( image = image , command = command , volumes = binds_to_volumes ( binds ) , detach = False , host_config = _get_docker ( ) . create_host_config ( binds = binds , volumes_from = volumes_from , links = links ) , entrypoint = entrypoint )
_get_dock... |
def body ( self ) :
"""Returns the HTTP response body , deserialized if possible .
: rtype : mixed""" | if not self . _responses :
return None
if self . _responses [ - 1 ] . code >= 400 :
return self . _error_message ( )
return self . _deserialize ( ) |
def squeeze ( attrs , inputs , proto_obj ) :
"""Remove single - dimensional entries from the shape of a tensor .""" | new_attrs = translation_utils . _fix_attribute_names ( attrs , { 'axes' : 'axis' } )
return 'squeeze' , new_attrs , inputs |
def get ( cls , device_id , custom_headers = None ) :
"""Get a single Device . A Device is either a DevicePhone or a DeviceServer .
: type api _ context : context . ApiContext
: type device _ id : int
: type custom _ headers : dict [ str , str ] | None
: rtype : BunqResponseDevice""" | if custom_headers is None :
custom_headers = { }
api_client = client . ApiClient ( cls . _get_api_context ( ) )
endpoint_url = cls . _ENDPOINT_URL_READ . format ( device_id )
response_raw = api_client . get ( endpoint_url , { } , custom_headers )
return BunqResponseDevice . cast_from_bunq_response ( cls . _from_jso... |
def Lookup ( self , name ) :
"""Get the value associated with a name in the current context .
The current context could be an dictionary in a list , or a dictionary
outside a list .
Args :
name : name to lookup , e . g . ' foo ' or ' foo . bar . baz '
Returns :
The value , or self . undefined _ str
Ra... | if name == '@' :
return self . stack [ - 1 ] . context
parts = name . split ( '.' )
value = self . _LookUpStack ( parts [ 0 ] )
# Now do simple lookups of the rest of the parts
for part in parts [ 1 : ] :
try :
value = value [ part ]
except ( KeyError , TypeError ) : # TypeError for non - dictionari... |
def summary ( args ) :
"""% prog summary fastafile
Report the number of bases and sequences masked .""" | p = OptionParser ( summary . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
fastafile , = args
f = Fasta ( fastafile , index = False )
halfmaskedseqs = set ( )
allmasked = 0
allbases = 0
cutoff = 50
for key , seq in f . iteritems ( ) :
masked = 0
... |
def revert ( self , remotepath , revision , dir = None ) :
'''Usage : revert < remotepath > revisionid [ dir ]''' | rpath = get_pcs_path ( remotepath )
dir = get_pcs_path ( dir )
if not dir :
dir = os . path . dirname ( rpath )
return self . __panapi_revision_revert ( rpath , revision , dir ) |
def limit_result_set ( self , start , end ) :
"""By default , searches return all matching results .
This method restricts the number of results by setting the start
and end of the result set , starting from 1 . The starting and
ending results can be used for paging results when a certain
ordering is reques... | if not isinstance ( start , int ) or not isinstance ( end , int ) :
raise errors . InvalidArgument ( 'start and end arguments must be integers.' )
if end <= start :
raise errors . InvalidArgument ( 'End must be greater than start.' )
# because Python is 0 indexed
# Spec says that passing in ( 1 , 25 ) should in... |
def _get_with_criteria ( self , criteria , offset = None , limit = None ) :
'''returns items selected by criteria''' | SQL = SQLBuilder ( self . _table , criteria ) . select ( offset = offset , limit = limit )
self . _cursor . execute ( SQL )
for item in self . _cursor . fetchall ( ) :
yield self . _make_item ( item ) |
def make_email ( to , cc = None , bcc = None , subject = None , body = None ) :
"""Encodes either a simple e - mail address or a complete message with
( blind ) carbon copies and a subject and a body .
: param str | iterable to : The email address ( recipient ) . Multiple
values are allowed .
: param str | ... | return segno . make_qr ( make_make_email_data ( to = to , cc = cc , bcc = bcc , subject = subject , body = body ) ) |
def route_filter_rule_delete ( name , route_filter , resource_group , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Delete a route filter rule .
: param name : The route filter rule to delete .
: param route _ filter : The route filter containing the rule .
: param resource _ group : The resource group nam... | result = False
netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs )
try :
rule = netconn . route_filter_rules . delete ( resource_group_name = resource_group , route_filter_name = route_filter , rule_name = name )
rule . wait ( )
result = True
except CloudError as exc :
__utils__ [ 'a... |
def concat ( objs , dim = None , data_vars = 'all' , coords = 'different' , compat = 'equals' , positions = None , indexers = None , mode = None , concat_over = None ) :
"""Concatenate xarray objects along a new or existing dimension .
Parameters
objs : sequence of Dataset and DataArray objects
xarray objects... | # TODO : add join and ignore _ index arguments copied from pandas . concat
# TODO : support concatenating scalar coordinates even if the concatenated
# dimension already exists
from . dataset import Dataset
from . dataarray import DataArray
try :
first_obj , objs = utils . peek_at ( objs )
except StopIteration :
... |
def rollout ( self , batch_info : BatchInfo , model : RlModel , number_of_steps : int ) -> Rollout :
"""Calculate env rollout""" | assert not model . is_recurrent , "Replay env roller does not support recurrent models"
accumulator = TensorAccumulator ( )
episode_information = [ ]
# List of dictionaries with episode information
for step_idx in range ( number_of_steps ) :
step = model . step ( self . last_observation )
replay_extra_informati... |
def lastIndexOf ( self , item ) :
"""Return the position of the last occurrence of an
item in an array , or - 1 if the item is not included in the array .""" | array = self . obj
i = len ( array ) - 1
if not ( self . _clean . isList ( ) or self . _clean . isTuple ( ) ) :
return self . _wrap ( - 1 )
while i > - 1 :
if array [ i ] is item :
return self . _wrap ( i )
i -= 1
return self . _wrap ( - 1 ) |
def servers_update_addresses ( request , servers , all_tenants = False ) :
"""Retrieve servers networking information from Neutron if enabled .
Should be used when up to date networking information is required ,
and Nova ' s networking info caching mechanism is not fast enough .""" | # NOTE ( e0ne ) : we don ' t need to call neutron if we have no instances
if not servers :
return
# Get all ( filtered for relevant servers ) information from Neutron
try : # NOTE ( e0ne ) : we need tuple here to work with @ memoized decorator .
# @ memoized works with hashable arguments only .
ports = list_res... |
def slistStr ( slist ) :
"""Converts signed list to angle string .""" | slist = _fixSlist ( slist )
string = ':' . join ( [ '%02d' % x for x in slist [ 1 : ] ] )
return slist [ 0 ] + string |
def pop ( self , groupName , default = None ) :
"""Removes the * * groupName * * from the Groups and returns the list of
group members . If no group is found , * * default * * is returned .
* * groupName * * is a : ref : ` type - string ` . This must return either
* * default * * or a : ref : ` type - immutab... | return super ( BaseGroups , self ) . pop ( groupName , default ) |
def get_prinz_pot ( nstep , x0 = 0. , nskip = 1 , dt = 0.01 , kT = 10.0 , mass = 1.0 , damping = 1.0 ) :
r"""wrapper for the Prinz model generator""" | pw = PrinzModel ( dt , kT , mass = mass , damping = damping )
return pw . sample ( x0 , nstep , nskip = nskip ) |
def created_on ( self ) :
"""The creation timestamp .""" | timestamp = self . _info . get ( 'creationTime' )
return _parser . Parser . parse_timestamp ( timestamp ) |
def add_parameter ( self , indicator_id , content , name = 'comment' , ptype = 'string' ) :
"""Add a a parameter to the IOC .
: param indicator _ id : The unique Indicator / IndicatorItem id the parameter is associated with .
: param content : The value of the parameter .
: param name : The name of the parame... | parameters_node = self . parameters
criteria_node = self . top_level_indicator . getparent ( )
# first check for duplicate id , name pairs
elems = parameters_node . xpath ( './/param[@ref-id="{}" and @name="{}"]' . format ( indicator_id , name ) )
if len ( elems ) > 0 : # there is no actual restriction on duplicate par... |
def copy ( self ) :
"""Create a copy of this Vector""" | new_vec = Vector2 ( )
new_vec . X = self . X
new_vec . Y = self . Y
return new_vec |
def csv ( self , path , schema = None , sep = None , encoding = None , quote = None , escape = None , comment = None , header = None , inferSchema = None , ignoreLeadingWhiteSpace = None , ignoreTrailingWhiteSpace = None , nullValue = None , nanValue = None , positiveInf = None , negativeInf = None , dateFormat = None ... | self . _set_opts ( schema = schema , sep = sep , encoding = encoding , quote = quote , escape = escape , comment = comment , header = header , inferSchema = inferSchema , ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace , ignoreTrailingWhiteSpace = ignoreTrailingWhiteSpace , nullValue = nullValue , nanValue = nanValue... |
def wraps_with_context ( func , context ) :
"""Return a wrapped partial ( func , context )""" | wrapped = functools . partial ( func , context )
wrapped = functools . wraps ( func ) ( wrapped )
if asyncio . iscoroutinefunction ( func ) :
wrapped = asyncio . coroutine ( wrapped )
return wrapped |
def get_stored_metadata ( self , temp_ver ) :
"""Retrieves the metadata for the given template version from the store
Args :
temp _ ver ( TemplateVersion ) : template version to retrieve the
metadata for
Returns :
dict : the metadata of the given template version""" | with open ( self . _prefixed ( '%s.metadata' % temp_ver . name ) ) as f :
return json . load ( f ) |
def IndexedDB_deleteDatabase ( self , securityOrigin , databaseName ) :
"""Function path : IndexedDB . deleteDatabase
Domain : IndexedDB
Method name : deleteDatabase
Parameters :
Required arguments :
' securityOrigin ' ( type : string ) - > Security origin .
' databaseName ' ( type : string ) - > Databa... | assert isinstance ( securityOrigin , ( str , ) ) , "Argument 'securityOrigin' must be of type '['str']'. Received type: '%s'" % type ( securityOrigin )
assert isinstance ( databaseName , ( str , ) ) , "Argument 'databaseName' must be of type '['str']'. Received type: '%s'" % type ( databaseName )
subdom_funcs = self . ... |
def create_cssparameter ( self , name = None , value = None ) :
"""Create a new L { CssParameter } node as a child of this element , and attach it to the DOM .
Optionally set the name and value of the parameter , if they are both provided .
@ type name : string
@ param name : Optional . The name of the L { Cs... | elem = self . _node . makeelement ( '{%s}CssParameter' % SLDNode . _nsmap [ 'sld' ] , nsmap = SLDNode . _nsmap )
self . _node . append ( elem )
if not ( name is None or value is None ) :
elem . attrib [ 'name' ] = name
elem . text = value
return CssParameter ( self , len ( self . _node ) - 1 ) |
def checkArgs ( args ) :
"""Checks the arguments and options .
: param args : an object containing the options of the program .
: type args : argparse . Namespace
: returns : ` ` True ` ` if everything was OK .
If there is a problem with an option , an exception is raised using the
: py : class : ` Progra... | # Checking the input files
for suffix in [ ".tped" , ".tfam" , ".map" ] :
fileName = args . tfile + suffix
if not os . path . isfile ( fileName ) :
msg = "%(fileName)s: no such file" % locals ( )
raise ProgramError ( msg )
# Checking the concordance threshold
if ( ( args . snp_concordance_thresh... |
def read_request_headers ( self ) :
"""Read self . rfile into self . inheaders . Return success .""" | # then all the http headers
try :
read_headers ( self . rfile , self . inheaders )
except ValueError , ex :
self . simple_response ( "400 Bad Request" , ex . args [ 0 ] )
return False
mrbs = self . server . max_request_body_size
if mrbs and int ( self . inheaders . get ( "Content-Length" , 0 ) ) > mrbs :
... |
def convert_response_to_text ( response ) :
"""Convert a JSS HTML response to plaintext .""" | # Responses are sent as html . Split on the newlines and give us
# the < p > text back .
errorlines = response . text . encode ( "utf-8" ) . split ( "\n" )
error = [ ]
pattern = re . compile ( r"<p.*>(.*)</p>" )
for line in errorlines :
content_line = re . search ( pattern , line )
if content_line :
err... |
def info ( self ) -> Dict [ str , object ] :
'''dict : Information about the context
Example : :
' GL _ VENDOR ' : ' NVIDIA Corporation ' ,
' GL _ RENDERER ' : ' NVIDIA GeForce GT 650M OpenGL Engine ' ,
' GL _ VERSION ' : ' 4.1 NVIDIA - 10.32.0 355.11.10.10.40.102 ' ,
' GL _ POINT _ SIZE _ RANGE ' : ( 1.0... | if self . _info is None :
self . _info = self . mglo . info
return self . _info |
def script_string_to_notebook ( str , pth ) :
"""Convert a python script represented as string ` str ` to a notebook
with filename ` pth ` .""" | nb = py2jn . py_string_to_notebook ( str )
py2jn . write_notebook ( nb , pth ) |
def reduce_data_frame ( df , chunk_slicers , avg_cols = ( ) , uavg_cols = ( ) , minmax_cols = ( ) , nchunk_colname = 'nchunk' , uncert_prefix = 'u' , min_points_per_chunk = 3 ) :
"""" Reduce " a DataFrame by collapsing rows in grouped chunks . Returns another
DataFrame with similar columns but fewer rows .
Argu... | subds = [ df . iloc [ idx ] for idx in chunk_slicers ]
subds = [ sd for sd in subds if sd . shape [ 0 ] >= min_points_per_chunk ]
chunked = df . __class__ ( { nchunk_colname : np . zeros ( len ( subds ) , dtype = np . int ) } )
# Some future - proofing : allow possibility of different ways of mapping
# from a column gi... |
def get_constraints ( self ) :
"""Retrieve all of the relevant constraints , aggregated from the pipfile , resolver ,
and parent dependencies and their respective conflict resolution where possible .
: return : A set of * * InstallRequirement * * instances representing constraints
: rtype : Set""" | constraints = { c for c in self . resolver . parsed_constraints if c and c . name == self . entry . name }
pipfile_constraint = self . get_pipfile_constraint ( )
if pipfile_constraint :
constraints . add ( pipfile_constraint )
return constraints |
def dashboard ( request ) :
"Counts , aggregations and more !" | end_time = now ( )
start_time = end_time - timedelta ( days = 7 )
defaults = { 'start' : start_time , 'end' : end_time }
form = DashboardForm ( data = request . GET or defaults )
if form . is_valid ( ) :
start_time = form . cleaned_data [ 'start' ]
end_time = form . cleaned_data [ 'end' ]
# determine when track... |
def reduce_slice ( self , start , end , options = None ) :
"""Adds the Javascript built - in ` ` Riak . reduceSlice ` ` to the
query as a reduce phase .
: param start : the beginning of the slice
: type start : integer
: param end : the end of the slice
: type end : integer
: param options : phase optio... | if options is None :
options = dict ( )
options [ 'arg' ] = [ start , end ]
return self . reduce ( "Riak.reduceSlice" , options = options ) |
def templates ( self ) :
"""Iterate over the defined Templates .""" | template = lib . EnvGetNextDeftemplate ( self . _env , ffi . NULL )
while template != ffi . NULL :
yield Template ( self . _env , template )
template = lib . EnvGetNextDeftemplate ( self . _env , template ) |
def simple_round ( tol = 0 ) :
"""decorator for rounding a function ' s input argument and keywords to the
given precision * tol * . This decorator always rounds to a floating point
number .
Rounding is only done for arguments or keywords that are floats .
For example :
> > > @ simple _ round ( tol = 1)
... | def dec ( f ) :
def func ( * args , ** kwds ) :
if tol is None :
_args , _kwds = args , kwds
else :
_simple_round = simple_round_factory ( tol )
_args , _kwds = _simple_round ( * args , ** kwds )
return f ( * _args , ** _kwds )
return func
return dec |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.