signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def request ( self , method , url , ** kwargs ) :
"""Overrides ` ` requests . Session . request ` ` to renew the IAM cookie
and then retry the original request ( if required ) .""" | # The CookieJar API prevents callers from getting an individual Cookie
# object by name .
# We are forced to use the only exposed method of discarding expired
# cookies from the CookieJar . Internally this involves iterating over
# the entire CookieJar and calling ` . is _ expired ( ) ` on each Cookie
# object .
self .... |
def _log_error_and_abort ( ret , obj ) :
'''helper function to update errors in the return structure''' | ret [ 'result' ] = False
ret [ 'abort' ] = True
if 'error' in obj :
ret [ 'comment' ] = '{0}' . format ( obj . get ( 'error' ) )
return ret |
def enqueue_task ( self , source , * args ) :
"""Enqueue a task execution . It will run in the background as soon
as the coordinator clears it to do so .""" | yield from self . cell . coord . enqueue ( self )
route = Route ( source , self . cell , self . spec , self . emit )
self . cell . loop . create_task ( self . coord_wrap ( route , * args ) )
# To guarantee that the event loop works fluidly , we manually yield
# once . The coordinator enqueue coroutine is not required t... |
def checksum ( self ) :
"""checksum : None - > single checksum byte
checksum adds all bytes of the binary , unescaped data in the
frame , saves the last byte of the result , and subtracts it from
0xFF . The final result is the checksum""" | total = 0
# Add together all bytes
for byte in self . data :
total += byteToInt ( byte )
# Only keep the last byte
total = total & 0xFF
return intToByte ( 0xFF - total ) |
def init_ui ( self ) :
"""Setup control widget UI .""" | self . control_layout = QHBoxLayout ( )
self . setLayout ( self . control_layout )
self . reset_button = QPushButton ( )
self . reset_button . setFixedSize ( 40 , 40 )
self . reset_button . setIcon ( QtGui . QIcon ( WIN_PATH ) )
self . game_timer = QLCDNumber ( )
self . game_timer . setStyleSheet ( "QLCDNumber {color: ... |
def _parse_group ( self , element ) :
"""Parse and add a group requirement for this trigger
: param element : The XML Element object
: type element : etree . _ Element""" | self . _log . debug ( 'Adding Trigger group: {group}' . format ( group = element . text ) )
if isinstance ( self . groups , set ) :
self . groups . add ( element . text )
elif self . groups is None :
self . groups = { element . text }
else :
raise TypeError ( 'Unrecognized group type, {type}: {groups}' . fo... |
def remove_video_for_course ( course_id , edx_video_id ) :
"""Soft deletes video for particular course .
Arguments :
course _ id ( str ) : id of the course
edx _ video _ id ( str ) : id of the video to be hidden""" | course_video = CourseVideo . objects . get ( course_id = course_id , video__edx_video_id = edx_video_id )
course_video . is_hidden = True
course_video . save ( ) |
def mavlink_packet ( self , msg ) :
'''handle an incoming mavlink packet''' | type = msg . get_type ( )
master = self . master
# add some status fields
if type in [ 'RC_CHANNELS' ] :
ilock = self . get_rc_input ( msg , self . interlock_channel )
if ilock <= 0 :
self . console . set_status ( 'ILOCK' , 'ILOCK:--' , fg = 'grey' , row = 4 )
elif ilock >= 1800 :
self . con... |
def add_rules ( ) :
"""Use the rules provided in this module to implement authorization checks for the ` ` django - user - tasks ` ` models .
These rules allow only superusers and the user who triggered a task to view its status or artifacts , cancel the
task , or delete the status information and all its relat... | rules . add_perm ( 'user_tasks.view_usertaskstatus' , STATUS_PERMISSION )
rules . add_perm ( 'user_tasks.cancel_usertaskstatus' , STATUS_PERMISSION )
rules . add_perm ( 'user_tasks.change_usertaskstatus' , rules . predicates . is_superuser )
rules . add_perm ( 'user_tasks.delete_usertaskstatus' , STATUS_PERMISSION )
ru... |
def _check_required_group ( self ) :
"""Returns True if the group requirement ( AUTH _ LDAP _ REQUIRE _ GROUP ) is
met . Always returns True if AUTH _ LDAP _ REQUIRE _ GROUP is None .""" | required_group_dn = self . settings . REQUIRE_GROUP
if required_group_dn is not None :
if not isinstance ( required_group_dn , LDAPGroupQuery ) :
required_group_dn = LDAPGroupQuery ( required_group_dn )
result = required_group_dn . resolve ( self )
if not result :
raise self . Authentication... |
def caller_name ( skip = 2 , include_lineno = False ) :
'''Get a name of a caller in the format module . class . method
` skip ` specifies how many levels of stack to skip while getting caller
name . skip = 1 means " who calls me " , skip = 2 " who calls my caller " etc .
An empty string is returned if skippe... | stack = inspect . stack ( )
start = 0 + skip
if len ( stack ) < start + 1 :
return ''
parentframe = stack [ start ] [ 0 ]
name = [ ]
if include_lineno is True :
try :
lineno = inspect . getframeinfo ( parentframe ) . lineno
except : # pylint : disable = bare - except
lineno = None
module = i... |
def wait_for_confirmation ( provider , transaction_id ) :
'Sleep on a loop until we see a confirmation of the transaction .' | while ( True ) :
transaction = provider . gettransaction ( transaction_id )
if transaction [ "confirmations" ] > 0 :
break
time . sleep ( 10 ) |
def toggle_autojump ( ) :
"""Toggles Autojump""" | if not autojump_enabled ( ) :
with open ( AUTOJUMP_FILE , 'w+' ) as ajfile :
ajfile . write ( "enabled" )
else :
os . remove ( AUTOJUMP_FILE ) |
def create_legend ( info , c , option = "clean" , use_index = False ) :
"""creating more informative legends""" | logging . debug ( " - creating legends" )
mass , loading , label = info . loc [ c , [ "masses" , "loadings" , "labels" ] ]
if use_index or not label :
label = c . split ( "_" )
label = "_" . join ( label [ 1 : ] )
if option == "clean" :
return label
if option == "mass" :
label = f"{label} ({mass:.2f}... |
def add_to_gitignore ( line : str ) :
"""Adds a line to the . gitignore file of the repo
Args :
line : line to add""" | if not line . endswith ( '\n' ) :
line = f'{line}\n'
if GIT_IGNORE . exists ( ) :
if line in GIT_IGNORE . read_text ( encoding = 'utf8' ) :
return
previous_content = GIT_IGNORE . read_text ( encoding = 'utf8' )
else :
previous_content = ''
GIT_IGNORE . write_text ( previous_content + line , enco... |
def _process_features ( features ) :
"""Generate the ` Features String ` from an iterable of features .
: param features : The features to generate the features string from .
: type features : : class : ` ~ collections . abc . Iterable ` of : class : ` str `
: return : The ` Features String `
: rtype : : cl... | parts = [ feature . encode ( "utf-8" ) + b"\x1f" for feature in features ]
parts . sort ( )
return b"" . join ( parts ) + b"\x1c" |
def pre_save ( self , model_instance , add ) :
"""Resizes , commits image to storage , and returns field ' s value just before saving .""" | file = getattr ( model_instance , self . attname )
if file and not file . _committed :
file . name = self . _clean_file_name ( model_instance , file . name )
file . file = self . _resize_image ( model_instance , file )
file . save ( file . name , file , save = False )
return file |
def dequeue ( ctx ) :
"""Sends a tweet from the queue""" | tweet = ctx . obj [ 'TWEETLIST' ] . peek ( )
if tweet is None :
click . echo ( "Nothing to dequeue." )
ctx . exit ( 1 )
if ctx . obj [ 'DRYRUN' ] :
click . echo ( tweet )
else :
tweet = ctx . obj [ 'TWEETLIST' ] . pop ( )
ctx . obj [ 'TWEEPY_API' ] . update_status ( tweet ) |
def get_vocab ( self , vocab_name , ** kwargs ) :
"""Returns data stream of an rdf vocabulary
args :
vocab _ name : the name or uri of the vocab to return""" | vocab_dict = self . __get_vocab_dict__ ( vocab_name , ** kwargs )
filepaths = list ( set ( [ os . path . join ( self . cache_dir , vocab_dict [ 'filename' ] ) , os . path . join ( self . vocab_dir , vocab_dict [ 'filename' ] ) ] ) )
for path in filepaths :
if os . path . exists ( path ) :
with open ( path ,... |
def _finalize_nonblock_blob ( self , sd , metadata , digest ) : # type : ( SyncCopy , blobxfer . models . synccopy . Descriptor , dict ,
# str ) - > None
"""Finalize Non - Block blob
: param SyncCopy self : this
: param blobxfer . models . synccopy . Descriptor sd : synccopy descriptor
: param dict metadata :... | # set md5 page blob property if required
if ( blobxfer . util . is_not_empty ( digest ) or sd . dst_entity . cache_control is not None ) :
self . _set_blob_properties ( sd , digest )
# set metadata if needed
if blobxfer . util . is_not_empty ( metadata ) :
self . _set_blob_metadata ( sd , metadata ) |
def _get_belief_package ( stmt ) :
"""Return the belief packages of a given statement recursively .""" | # This list will contain the belief packages for the given statement
belief_packages = [ ]
# Iterate over all the support parents
for st in stmt . supports : # Recursively get all the belief packages of the parent
parent_packages = _get_belief_package ( st )
package_stmt_keys = [ pkg . statement_key for pkg in ... |
def _visit ( self , L , marked , tempmarked ) :
"""Sort features topologically .
This recursive function uses depth - first search to find an ordering of
the features in the feature graph that is sorted both topologically and
with respect to genome coordinates .
Implementation based on Wikipedia ' s descrip... | assert not self . is_pseudo
if self in tempmarked :
raise Exception ( 'feature graph is cyclic' )
if self not in marked :
tempmarked [ self ] = True
features = list ( )
if self . siblings is not None and self . is_toplevel :
features . extend ( reversed ( self . siblings ) )
if self . childr... |
def unitResponse ( self , band ) :
"""This is used internally for : ref : ` pysynphot - formula - effstim `
calculations .""" | # sum = asumr ( band , nwave )
total = band . throughput . sum ( )
return 2.5 * math . log10 ( total ) |
def add_method_drop_down ( self , col_number , col_label ) :
"""Add drop - down - menu options for magic _ method _ codes columns""" | if self . data_type == 'ages' :
method_list = self . contribution . vocab . age_methods
else :
method_list = self . contribution . vocab . age_methods . copy ( )
method_list . update ( self . contribution . vocab . methods )
self . choices [ col_number ] = ( method_list , True ) |
def refund_order ( self , request , pk ) :
"""Refund the order specified by the pk""" | order = Order . objects . get ( id = pk )
order . refund ( )
return Response ( status = status . HTTP_204_NO_CONTENT ) |
def pvscan ( self ) :
"""Probes the volume group for physical volumes and returns a list of
PhysicalVolume instances : :
from lvm2py import *
lvm = LVM ( )
vg = lvm . get _ vg ( " myvg " )
pvs = vg . pvscan ( )
* Raises : *
* HandleError""" | self . open ( )
pv_list = [ ]
pv_handles = lvm_vg_list_pvs ( self . handle )
if not bool ( pv_handles ) :
return pv_list
pvh = dm_list_first ( pv_handles )
while pvh :
c = cast ( pvh , POINTER ( lvm_pv_list ) )
pv = PhysicalVolume ( self , pvh = c . contents . pv )
pv_list . append ( pv )
if dm_list... |
def add_folder_task ( self , dir_name = None ) :
'''添加上传任务 , 会弹出一个选择文件夹的对话框''' | folder_dialog = Gtk . FileChooserDialog ( _ ( 'Choose Folders..' ) , self . app . window , Gtk . FileChooserAction . SELECT_FOLDER , ( Gtk . STOCK_CANCEL , Gtk . ResponseType . CANCEL , Gtk . STOCK_OK , Gtk . ResponseType . OK ) )
folder_dialog . set_modal ( True )
folder_dialog . set_select_multiple ( True )
folder_di... |
def getIndexOfHeteroMen ( genotypes , menIndex ) :
"""Get the indexes of heterozygous men .
: param genotypes : the genotypes of everybody .
: param menIndex : the indexes of the men ( for the genotypes ) .
: type genotypes : numpy . array
: type menIndex : numpy . array
: returns : a : py : class : ` num... | toRemove = set ( )
for i in menIndex [ 0 ] :
for genotype in [ set ( j . split ( " " ) ) for j in genotypes [ : , i ] ] :
if len ( genotype ) != 1 : # We have an heterozygous
toRemove . add ( i )
toRemove = list ( toRemove )
toRemove . sort ( )
return ( np . array ( toRemove , dtype = int ) , ) |
def unregistercls ( self , schemacls = None , data_types = None ) :
"""Unregister schema class or associated data _ types .
: param type schemacls : sub class of Schema .
: param list data _ types : data _ types to unregister .""" | if schemacls is not None : # clean schemas by data type
for data_type in list ( self . _schbytype ) :
_schemacls = self . _schbytype [ data_type ]
if _schemacls is schemacls :
del self . _schbytype [ data_type ]
if data_types is not None :
for data_type in data_types :
if dat... |
def learn_from_domain ( self , method = 'random' , amount = 10 ) :
'''Learn SOM from artifacts introduced to the environment .
: param str method :
learning method , should be either ' random ' or ' closest ' , where
' random ' chooses * * amount * * random artifacts , and ' closest ' samples
closest artifa... | if method == 'none' :
return
arts = self . env . artifacts
if len ( arts ) == 0 :
return
if 'random' in method :
samples = min ( len ( arts ) , amount )
ars = np . random . choice ( arts , samples , replace = False )
for a in ars :
self . learn ( a , self . teaching_iterations )
if 'closest'... |
def alphakt_pth ( v , temp , v0 , alpha0 , k0 , n , z , t_ref = 300. , three_r = 3. * constants . R ) :
"""calculate thermal pressure from thermal expansion and bulk modulus
: param v : unit - cell volume in A ^ 3
: param temp : temperature in K
: param v0 : unit - cell volume in A ^ 3 at 1 bar
: param alph... | return alpha0 * k0 * ( temp - t_ref ) |
def add_update_topology_db ( self , ** params ) :
"""Add or update an entry to the topology DB .""" | topo_dict = params . get ( 'columns' )
session = db . get_session ( )
host = topo_dict . get ( 'host' )
protocol_interface = topo_dict . get ( 'protocol_interface' )
with session . begin ( subtransactions = True ) :
try : # Check if entry exists .
session . query ( DfaTopologyDb ) . filter_by ( host = host ... |
def change_page ( self , offset = None , max_page_count = None , nom = True ) :
"""Args :
* offset - Integer - The positive / negative change to apply
to the page .
* max _ page _ count - The maximum number of pages available .
* nom - None on Max or Min - If max number of pages reached ,
return none inst... | if offset == None :
return
if self . slots [ 'page' ] == None :
self . slots [ 'page' ] = 1
if ( self . slots [ 'page' ] + offset > max_page_count ) and nom :
return None
elif ( self . slots [ 'page' ] + offset < 1 ) and nom :
return None
else :
self . slots [ 'page' ] = norm_page_cnt ( self . slots... |
def get_response_page ( request , return_type , template_location , response_page_type ) :
"""Helper function to get an appropriate response page if it exists .
This function is not designed to be used directly as a view . It is
a helper function which can be called to check if a ResponsePage
exists for a Res... | try :
page = models . ResponsePage . objects . get ( is_active = True , type = response_page_type , )
template = loader . get_template ( template_location )
content_type = None
body = template . render ( RequestContext ( request , { 'request_path' : request . path , 'page' : page , } ) )
return retu... |
def _filepath_converter ( self , user_path , file_name ) :
"""Logic for obtaining a file path
: param user _ path : a path as provided by the user . perhaps a file or directory ?
: param file _ name : the name of the remote file
: return :""" | path = user_path or os . path . join ( os . getcwd ( ) , 'billing_reports' , os . path . sep )
dir_specified = path . endswith ( os . sep )
if dir_specified :
path = os . path . join ( path , file_name )
path = os . path . abspath ( path )
directory = os . path . dirname ( path )
if not os . path . isdir ( director... |
def _make_dep_lib_file_sym_links_and_copy_include_files ( self ) :
"""Make symbolick links for lib files and copy include files .
Do below steps for a dependency packages .
Dependency packages
- popt - devel
Steps
1 . Make symbolic links from system library files or downloaded lib
files to downloaded so... | if not self . _rpm_py_has_popt_devel_dep ( ) :
message = ( 'The RPM Python binding does not have popt-devel dependency' )
Log . debug ( message )
return
if self . _is_popt_devel_installed ( ) :
message = '{0} package is installed.' . format ( self . pacakge_popt_devel_name )
Log . debug ( message )
... |
def get_resource ( collection , key ) :
"""Return the appropriate * Response * for retrieving a single resource .
: param string collection : a : class : ` sandman . model . Model ` endpoint
: param string key : the primary key for the : class : ` sandman . model . Model `
: rtype : : class : ` flask . Respon... | resource = retrieve_resource ( collection , key )
_validate ( endpoint_class ( collection ) , request . method , resource )
return resource_response ( resource ) |
def set_site ( request ) :
"""Put the selected site ID into the session - posted to from
the " Select site " drop - down in the header of the admin . The
site ID is then used in favour of the current request ' s
domain in ` ` yacms . core . managers . CurrentSiteManager ` ` .""" | site_id = int ( request . GET [ "site_id" ] )
if not request . user . is_superuser :
try :
SitePermission . objects . get ( user = request . user , sites = site_id )
except SitePermission . DoesNotExist :
raise PermissionDenied
request . session [ "site_id" ] = site_id
admin_url = reverse ( "adm... |
def int_to_bytes ( i , minlen = 1 , order = 'big' ) : # pragma : no cover
"""convert integer to bytes""" | blen = max ( minlen , PGPObject . int_byte_len ( i ) , 1 )
if six . PY2 :
r = iter ( _ * 8 for _ in ( range ( blen ) if order == 'little' else range ( blen - 1 , - 1 , - 1 ) ) )
return bytes ( bytearray ( ( i >> c ) & 0xff for c in r ) )
return i . to_bytes ( blen , order ) |
def stop_instance ( self , instance ) :
"""Stops a single instance .
: param str instance : A Yamcs instance name .""" | params = { 'state' : 'stopped' }
url = '/instances/{}' . format ( instance )
self . patch_proto ( url , params = params ) |
def tree ( ) :
"""Example showing tree progress view""" | # Test data #
# For this example , we ' re obviously going to be feeding fictitious data
# to ProgressTree , so here it is
leaf_values = [ Value ( 0 ) for i in range ( 6 ) ]
bd_defaults = dict ( type = Bar , kwargs = dict ( max_value = 10 ) )
test_d = { "Warp Jump" : { "1) Prepare fuel" : { "Load Tanks" : { "Tank 1" : ... |
def update ( self , argv ) :
"""Update an index according to the given argument vector .""" | if len ( argv ) == 0 :
error ( "Command requires an index name" , 2 )
name = argv [ 0 ]
if name not in self . service . indexes :
error ( "Index '%s' does not exist" % name , 2 )
index = self . service . indexes [ name ]
# Read index metadata and construct command line parser rules that
# correspond to each edi... |
def generate_sample_cfn_module ( env_root , module_dir = None ) :
"""Generate skeleton CloudFormation sample module .""" | if module_dir is None :
module_dir = os . path . join ( env_root , 'sampleapp.cfn' )
generate_sample_module ( module_dir )
for i in [ 'stacks.yaml' , 'dev-us-east-1.env' ] :
shutil . copyfile ( os . path . join ( ROOT , 'templates' , 'cfn' , i ) , os . path . join ( module_dir , i ) )
os . mkdir ( os . path . j... |
def get_grade_entry_mdata ( ) :
"""Return default mdata map for GradeEntry""" | return { 'resource' : { 'element_label' : { 'text' : 'resource' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) , 'scriptTypeId' : str ( DEFAULT_SCRIPT_TYPE ) , 'formatTypeId' : str ( DEFAULT_FORMAT_TYPE ) , } , 'instructions' : { 'text' : 'accepts an osid.id.Id object' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TY... |
def estimate_hsr ( self , R , z = 0. , dR = 10. ** - 8. , ** kwargs ) :
"""NAME :
estimate _ hsr
PURPOSE :
estimate the exponential scale length of the radial dispersion at R
INPUT :
R - Galactocentric radius ( can be Quantity )
z = height ( default : 0 pc ) ( can be Quantity )
dR - range in R to use ... | Rs = [ R - dR / 2. , R + dR / 2. ]
sf = numpy . array ( [ self . sigmaR2 ( r , z , use_physical = False , ** kwargs ) for r in Rs ] )
lsf = numpy . log ( sf ) / 2.
return - dR / ( lsf [ 1 ] - lsf [ 0 ] ) |
def subtract ( self , other ) :
"""Subtract the { 0 } of two { 1 } objects .
Parameters
other : an { 1 } fitted instance .""" | self_estimate = getattr ( self , self . _estimate_name )
other_estimate = getattr ( other , other . _estimate_name )
new_index = np . concatenate ( ( other_estimate . index , self_estimate . index ) )
new_index = np . unique ( new_index )
return pd . DataFrame ( self_estimate . reindex ( new_index , method = "ffill" ) ... |
def connect ( * args , ** kwargs ) :
"""Connect to the database . Passes arguments along to
` ` pymongo . connection . Connection ` ` unmodified .
The Connection returned by this proxy method will be used by micromongo
for all of its queries . Micromongo will alter the behavior of this
conneciton object in ... | global __connection , __connection_args
__connection_args = ( args , dict ( kwargs ) )
# inject our class _ router
kwargs [ 'class_router' ] = class_router
__connection = Connection ( * args , ** kwargs )
return __connection |
def snapshot_present ( name , recursive = False , properties = None ) :
'''ensure snapshot exists and has properties set
name : string
name of snapshot
recursive : boolean
recursively create snapshots of all descendent datasets
properties : dict
additional zfs properties ( - o )
. . note :
Propertie... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
# # log configuration
log . debug ( 'zfs.snapshot_present::%s::config::recursive = %s' , name , recursive )
log . debug ( 'zfs.snapshot_present::%s::config::properties = %s' , name , properties )
# # ensure properties are zfs values
if propert... |
def paths ( self , value ) :
"""Setter for * * self . _ _ paths * * attribute .
: param value : Attribute value .
: type value : tuple or list""" | if value is not None :
assert type ( value ) in ( tuple , list ) , "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!" . format ( "paths" , value )
for path in value :
assert type ( path ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "paths" , path )
assert os . pa... |
def wait_for_instance_deletion ( self , credentials , name , ** kwargs ) :
"""Wait for deletion of instance based on the configuration data .
TODO : docstring""" | op_name = wait_for_instance_deletion ( credentials , self . project , self . zone , name , ** kwargs )
return op_name |
def release ( self , connection : Connection , reuse : bool = True ) :
'''Unregister a connection .
Args :
connection : Connection instance returned from : meth : ` acquire ` .
reuse : If True , the connection is made available for reuse .
Coroutine .''' | yield from self . _condition . acquire ( )
self . busy . remove ( connection )
if reuse :
self . ready . add ( connection )
self . _condition . notify ( )
self . _condition . release ( ) |
def edges_unique_length ( self ) :
"""How long is each unique edge .
Returns
length : ( len ( self . edges _ unique ) , ) float
Length of each unique edge""" | vector = np . subtract ( * self . vertices [ self . edges_unique . T ] )
length = np . linalg . norm ( vector , axis = 1 )
return length |
def pad ( a , desiredlength ) :
"""Pad an n - dimensional numpy array with zeros along the zero - th dimension
so that it is the desired length . Return it unchanged if it is greater
than or equal to the desired length""" | if len ( a ) >= desiredlength :
return a
islist = isinstance ( a , list )
a = np . array ( a )
diff = desiredlength - len ( a )
shape = list ( a . shape )
shape [ 0 ] = diff
padded = np . concatenate ( [ a , np . zeros ( shape , dtype = a . dtype ) ] )
return padded . tolist ( ) if islist else padded |
def _clamp_rgb_coordinate ( self , coord ) :
"""Clamps an RGB coordinate , taking into account whether or not the
color is upscaled or not .
: param float coord : The coordinate value .
: rtype : float
: returns : The clamped value .""" | if not self . is_upscaled :
return min ( max ( coord , 0.0 ) , 1.0 )
else :
return min ( max ( coord , 1 ) , 255 ) |
def eliminate_odd_chars ( s : str ) -> str :
"""This function eliminates all characters at odd positions in a string
Args :
s : a string from which odd characters need to be removed
Returns :
A new string that only contains characters at even positions in the original string
Examples :
> > > eliminate _... | new_string = ''
for i in range ( 1 , len ( s ) + 1 ) :
if i % 2 == 0 :
new_string += s [ i - 1 ]
return new_string |
def host_in_set ( ip , hosts , nets ) :
"""Return True if given ip is in host or network list .""" | if ip in hosts :
return True
if is_valid_ipv4 ( ip ) :
n = dq2num ( ip )
for net in nets :
if dq_in_net ( n , net ) :
return True
return False |
def newSharedReport ( self , checkid , ** kwargs ) :
"""Create a shared report ( banner ) .
Returns status message for operation
Optional parameters :
* auto - - Automatic period ( If false , requires : fromyear ,
frommonth , fromday , toyear , tomonth , today )
Type : Boolean
* type - - Banner type
T... | # Warn user about unhandled parameters
for key in kwargs :
if key not in [ 'auto' , 'type' , 'fromyear' , 'frommonth' , 'fromday' , 'toyear' , 'tomonth' , 'today' , 'sharedtype' ] :
sys . stderr . write ( "'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n' )
parameters = { 'checkid' : chec... |
def fetch ( self ) :
"""Fetch a StyleSheetInstance
: returns : Fetched StyleSheetInstance
: rtype : twilio . rest . autopilot . v1 . assistant . style _ sheet . StyleSheetInstance""" | params = values . of ( { } )
payload = self . _version . fetch ( 'GET' , self . _uri , params = params , )
return StyleSheetInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , ) |
def _wrapNavFrag ( self , frag , useAthena ) :
"""Wrap the given L { INavigableFragment } in the appropriate type of
L { _ PublicPageMixin } .""" | if useAthena :
return PublicAthenaLivePage ( self . _siteStore , frag )
else :
return PublicPage ( None , self . _siteStore , frag , None , None ) |
def edit_message_reply_markup ( self , chat_id : Union [ int , str ] , message_id : int , reply_markup : "pyrogram.InlineKeyboardMarkup" = None ) -> "pyrogram.Message" :
"""Use this method to edit only the reply markup of messages sent by the bot or via the bot ( for inline bots ) .
Args :
chat _ id ( ` ` int `... | r = self . send ( functions . messages . EditMessage ( peer = self . resolve_peer ( chat_id ) , id = message_id , reply_markup = reply_markup . write ( ) if reply_markup else None ) )
for i in r . updates :
if isinstance ( i , ( types . UpdateEditMessage , types . UpdateEditChannelMessage ) ) :
return pyrog... |
def get_filename ( self , stream , media_type , parser_context ) :
"""Detects the uploaded file name . First searches a ' filename ' url kwarg .
Then tries to parse Content - Disposition header .""" | try :
return parser_context [ 'kwargs' ] [ 'filename' ]
except KeyError :
pass
try :
meta = parser_context [ 'request' ] . META
disposition = parse_header ( meta [ 'HTTP_CONTENT_DISPOSITION' ] . encode ( 'utf-8' ) )
filename_parm = disposition [ 1 ]
if 'filename*' in filename_parm :
retu... |
def count_events ( ) :
"""pulls data from the queue , tabulates it and spawns a send event""" | # wait loop
while 1 : # sleep and let the queue build up
gevent . sleep ( FLUSH_INTERVAL )
# init the data points containers
events = Counter ( )
additional = { }
# flush the queue
while 1 :
try :
site , content_id , event , path = EVENTS_QUEUE . get_nowait ( )
ev... |
def receive ( self , diff , paths ) :
"""Return Context Manager for a file - like ( stream ) object to store a diff .""" | path = self . selectReceivePath ( paths )
keyName = self . _keyName ( diff . toUUID , diff . fromUUID , path )
if self . _skipDryRun ( logger ) ( "receive %s in %s" , keyName , self ) :
return None
progress = _BotoProgress ( diff . size ) if self . showProgress is True else None
return _Uploader ( self . bucket , k... |
def to_prettytable ( df ) :
"""Convert DataFrame into ` ` PrettyTable ` ` .""" | pt = PrettyTable ( )
pt . field_names = df . columns
for tp in zip ( * ( l for col , l in df . iteritems ( ) ) ) :
pt . add_row ( tp )
return pt |
def save ( self , ** kwargs ) :
"""Overrides models . Model . save
- Removes old file from the FS
- Generates new file .""" | self . remove_file ( )
if not self . image :
self . generate ( save = False )
else :
self . image . name = self . file ( )
super ( FormatedPhoto , self ) . save ( ** kwargs ) |
def combine_images ( imgs , register = True ) :
"""Combine similar images into one to reduce the noise
Parameters
imgs : list of 2d array
Series of images
register : Boolean , default False
True if the images should be register before combination
Returns
im : 2d array
The result image
Notes
This... | imgs = np . asarray ( imgs , dtype = "float" )
if register :
for i in range ( 1 , imgs . shape [ 0 ] ) :
ret = register_images ( imgs [ 0 , : , : ] , imgs [ i , : , : ] )
imgs [ i , : , : ] = rotate_scale_shift ( imgs [ i , : , : ] , * ret [ : 3 ] , np . nan )
return np . mean ( imgs , 0 ) |
def perp_product ( self , other ) :
"""Return the perp product of the given vectors . The perp product is
just a cross product where the third dimension is taken to be zero and
the result is returned as a scalar .""" | return self . x * other . y - self . y * other . x |
def elemDump ( self , f , cur ) :
"""Dump an XML / HTML node , recursive behaviour , children are
printed too .""" | if cur is None :
cur__o = None
else :
cur__o = cur . _o
libxml2mod . xmlElemDump ( f , self . _o , cur__o ) |
def merge_pages ( self , replacements ) :
"""Deprecated method .""" | warnings . warn ( "merge_pages has been deprecated in favour of merge_templates" , category = DeprecationWarning , stacklevel = 2 )
self . merge_templates ( replacements , "page_break" ) |
def to_jd ( dt : datetime , fmt : str = 'jd' ) -> float :
"""Converts a given datetime object to Julian date .
Algorithm is copied from https : / / en . wikipedia . org / wiki / Julian _ day
All variable names are consistent with the notation on the wiki page .
Parameters
fmt
dt : datetime
Datetime obje... | a = math . floor ( ( 14 - dt . month ) / 12 )
y = dt . year + 4800 - a
m = dt . month + 12 * a - 3
jdn = dt . day + math . floor ( ( 153 * m + 2 ) / 5 ) + 365 * y + math . floor ( y / 4 ) - math . floor ( y / 100 ) + math . floor ( y / 400 ) - 32045
jd = jdn + ( dt . hour - 12 ) / 24 + dt . minute / 1440 + dt . second ... |
def construct_from_string ( cls , string ) :
"""Construction from a string , raise a TypeError if not
possible""" | if string == cls . name :
return cls ( )
raise TypeError ( "Cannot construct a '{}' from " "'{}'" . format ( cls , string ) ) |
def run ( self , copy_to_current_on_exit = False , site_property = None ) :
"""Write the input file to the scratch directory , run packmol and return
the packed molecule .
Args :
copy _ to _ current _ on _ exit ( bool ) : Whether or not to copy the packmol
input / output files from the scratch directory to ... | scratch = tempfile . gettempdir ( )
with ScratchDir ( scratch , copy_to_current_on_exit = copy_to_current_on_exit ) as scratch_dir :
self . _write_input ( input_dir = scratch_dir )
packmol_input = open ( os . path . join ( scratch_dir , self . input_file ) , 'r' )
p = Popen ( self . packmol_bin , stdin = pa... |
def _insert ( self , trigram ) :
"""Insert a trigram in the DB""" | words = list ( map ( self . _sanitize , trigram ) )
key = self . _WSEP . join ( words [ : 2 ] ) . lower ( )
next_word = words [ 2 ]
self . _db . setdefault ( key , [ ] )
# we could use a set here , but sets are not serializables in JSON . This
# is the same reason we use dicts instead of defaultdicts .
if next_word not... |
def get_filename ( self , runSetName , fileExtension ) :
'''This function returns the name of the file for a run set
with an extension ( " txt " , " xml " ) .''' | fileName = self . benchmark . output_base_name + ".results."
if runSetName :
fileName += runSetName + "."
return fileName + fileExtension |
def migrate ( self ) -> None :
"""Migrate
Perform a database migration , upgrading to the latest schema level .""" | assert self . ormSessionCreator , "ormSessionCreator is not defined"
connection = self . _dbEngine . connect ( )
isDbInitialised = self . _dbEngine . dialect . has_table ( connection , 'alembic_version' , schema = self . _metadata . schema )
connection . close ( )
if isDbInitialised or not self . _enableCreateAll :
... |
def fit ( self , X , y = None ) :
"""Fit the inlier model given training data .
This function attempts to choose reasonable defaults for parameters
sigma and rho if none are specified , which could then be adjusted
to improve performance .
Parameters
X : array
Examples of inlier data , of dimension N ti... | N = X . shape [ 0 ]
if y is None :
y = np . zeros ( N )
self . classes = list ( set ( y ) )
self . classes . sort ( )
self . n_classes = len ( self . classes )
# If no kernel parameters specified , try to choose some defaults
if not self . sigma :
self . sigma = median_kneighbour_distance ( X )
self . gamma... |
def _position_encoding_init ( max_length , dim ) :
"""Init the sinusoid position encoding table""" | position_enc = np . arange ( max_length ) . reshape ( ( - 1 , 1 ) ) / ( np . power ( 10000 , ( 2. / dim ) * np . arange ( dim ) . reshape ( ( 1 , - 1 ) ) ) )
# Apply the cosine to even columns and sin to odds .
position_enc [ : , 0 : : 2 ] = np . sin ( position_enc [ : , 0 : : 2 ] )
# dim 2i
position_enc [ : , 1 : : 2 ... |
def extractResponse ( cls , request , teams ) :
"""Take a C { L { TeamsRequest } } and a list of groups
the user is member of and create a C { L { TeamsResponse } }
object containing the list of team names that are both
requested and in the membership list of the user .
@ param request : The teams extension... | self = cls ( )
for team in request . requestedTeams ( ) :
if team in teams :
self . teams . append ( team )
return self |
def puts ( self , addr , s ) :
"""Put string of bytes at given address . Will overwrite any previous
entries .""" | a = array ( 'B' , asbytes ( s ) )
for i in range_g ( len ( a ) ) :
self . _buf [ addr + i ] = a [ i ] |
def step ( self , observations , raw_rewards , processed_rewards , dones , actions ) :
"""Record the information obtained from taking a step in all envs .
Records ( observation , rewards , done ) in a new time - step and actions in the
current time - step .
If any trajectory gets done , we move that trajector... | # Pre - conditions
assert isinstance ( observations , np . ndarray )
assert isinstance ( raw_rewards , np . ndarray )
assert isinstance ( processed_rewards , np . ndarray )
assert isinstance ( dones , np . ndarray )
assert isinstance ( actions , np . ndarray )
# We assume that we step in all envs , i . e . not like res... |
def fast_ordering ( self , structure , num_remove_dict , num_to_return = 1 ) :
"""This method uses the matrix form of ewaldsum to calculate the ewald
sums of the potential structures . This is on the order of 4 orders of
magnitude faster when there are large numbers of permutations to
consider . There are fur... | self . logger . debug ( "Performing fast ordering" )
starttime = time . time ( )
self . logger . debug ( "Performing initial ewald sum..." )
ewaldmatrix = EwaldSummation ( structure ) . total_energy_matrix
self . logger . debug ( "Ewald sum took {} seconds." . format ( time . time ( ) - starttime ) )
starttime = time .... |
def find_match_scp ( self , rule ) : # pylint : disable - msg = R0911 , R0912
"""Handle scp commands .""" | orig_list = [ ]
orig_list . extend ( self . original_command_list )
binary = orig_list . pop ( 0 )
allowed_binaries = [ 'scp' , '/usr/bin/scp' ]
if binary not in allowed_binaries :
self . logdebug ( 'skipping scp processing - binary "%s" ' 'not in approved list.\n' % binary )
return
filepath = orig_list . pop (... |
def from_string ( rxn_string ) :
"""Generates a balanced reaction from a string . The reaction must
already be balanced .
Args :
rxn _ string :
The reaction string . For example , " 4 Li + O2 - > 2Li2O "
Returns :
BalancedReaction""" | rct_str , prod_str = rxn_string . split ( "->" )
def get_comp_amt ( comp_str ) :
return { Composition ( m . group ( 2 ) ) : float ( m . group ( 1 ) or 1 ) for m in re . finditer ( r"([\d\.]*(?:[eE]-?[\d\.]+)?)\s*([A-Z][\w\.\(\)]*)" , comp_str ) }
return BalancedReaction ( get_comp_amt ( rct_str ) , get_comp_amt ( p... |
def get_new_PCA_parameters ( self , event ) :
"""calculate statistics when temperatures are selected
or PCA type is changed""" | tmin = str ( self . tmin_box . GetValue ( ) )
tmax = str ( self . tmax_box . GetValue ( ) )
if tmin == "" or tmax == "" :
return
if tmin in self . T_list and tmax in self . T_list and ( self . T_list . index ( tmax ) <= self . T_list . index ( tmin ) ) :
return
PCA_type = self . PCA_type_box . GetValue ( )
if P... |
def document ( self ) :
"""Returns either the : tl : ` WebDocument ` content for
normal results or the : tl : ` Document ` for media results .""" | if isinstance ( self . result , types . BotInlineResult ) :
return self . result . content
elif isinstance ( self . result , types . BotInlineMediaResult ) :
return self . result . document |
def execute ( cls , command , shell = True ) :
"""Execute a shell command .""" | cls . debug ( 'execute command (shell flag:%r): %r ' % ( shell , command ) )
try :
check_call ( command , shell = shell )
return True
except CalledProcessError :
return False |
def from_text ( cls , fname , vocabUnicodeSize = 78 , desired_vocab = None , encoding = "utf-8" ) :
"""Create a WordVectors class based on a word2vec text file
Parameters
fname : path to file
vocabUnicodeSize : the maximum string length ( 78 , by default )
desired _ vocab : if set , this will ignore any wor... | with open ( fname , "rb" ) as fin :
header = fin . readline ( )
vocab_size , vector_size = list ( map ( int , header . split ( ) ) )
vocab = np . empty ( vocab_size , dtype = "<U%s" % vocabUnicodeSize )
vectors = np . empty ( ( vocab_size , vector_size ) , dtype = np . float )
for i , line in enumer... |
def call ( self , ** data ) :
"""Issue the call .
: param data : Data to pass in the * body * of the request .""" | uri , body , headers = self . prepare ( data )
return self . dispatch ( uri , body , headers ) |
def angles ( F , G , ip_B = None , compute_vectors = False ) :
"""Principal angles between two subspaces .
This algorithm is based on algorithm 6.2 in ` Knyazev , Argentati . Principal
angles between subspaces in an A - based scalar product : algorithms and
perturbation estimates . 2002 . ` This algorithm can... | # make sure that F . shape [ 1 ] > = G . shape [ 1]
reverse = False
if F . shape [ 1 ] < G . shape [ 1 ] :
reverse = True
F , G = G , F
QF , _ = qr ( F , ip_B = ip_B )
QG , _ = qr ( G , ip_B = ip_B )
# one or both matrices empty ? ( enough to check G here )
if G . shape [ 1 ] == 0 :
theta = numpy . ones ( F... |
def setLegendData ( self , * args , ** kwargs ) :
"""Set or genernate the legend data from this canteen .
Uses : py : func : ` . buildLegend ` for genernating""" | self . legendData = buildLegend ( * args , key = self . legendKeyFunc , ** kwargs ) |
def Vizier_query ( self , viz_cat , cat_name , ra , dec , radius , ra_col = 'RAJ2000' , dec_col = 'DEJ2000' , columns = [ "**" ] , append = False , group = True , ** kwargs ) :
"""Use astroquery to search a catalog for sources within a search cone
Parameters
viz _ cat : str
The catalog string from Vizier ( e ... | # Verify the cat _ name
if self . _catalog_check ( cat_name , append = append ) : # Cone search Vizier
print ( "Searching {} for sources within {} of ({}, {}). Please be patient..." . format ( viz_cat , radius , ra , dec ) )
crds = coord . SkyCoord ( ra = ra , dec = dec , frame = 'icrs' )
V = Vizier ( colum... |
def novelty ( self , img ) :
'''Image ' s distance to the agent ' s short - term memory . Usually distance
to the closest object / prototypical object model in the memory .''' | dist = self . stmem . distance ( img . flatten ( ) )
return dist |
def peak_interval ( self , name , alpha = _alpha , npoints = _npoints , ** kwargs ) :
"""Calculate peak interval for parameter .""" | data = self . get ( name , ** kwargs )
return peak_interval ( data , alpha , npoints ) |
def positive_integer ( value ) :
"""Ensure that the provided value is a positive integer .
Parameters
value : int
The number to evaluate
Returns
value : int
Returns a positive integer""" | try :
value = int ( value )
except Exception :
raise argparse . ArgumentTypeError ( 'Invalid int value: \'{}\'' . format ( value ) )
if value < 0 :
raise argparse . ArgumentTypeError ( 'Invalid positive int value: \'{}\'' . format ( value ) )
return value |
def psf_iteration ( self , num_iter = 10 , no_break = True , stacking_method = 'median' , block_center_neighbour = 0 , keep_psf_error_map = True , psf_symmetry = 1 , psf_iter_factor = 1 , verbose = True , compute_bands = None ) :
"""iterative PSF reconstruction
: param num _ iter : number of iterations in the pro... | # lens _ temp = copy . deepcopy ( lens _ input )
kwargs_model = self . _updateManager . kwargs_model
param_class = self . _param_class
lens_updated = param_class . update_lens_scaling ( self . _cosmo_temp , self . _lens_temp )
source_updated = param_class . image2source_plane ( self . _source_temp , lens_updated )
if c... |
def evaluateModel ( model , loader , device , batches_in_epoch = sys . maxsize , criterion = F . nll_loss , progress = None ) :
"""Evaluate pre - trained model using given test dataset loader .
: param model : Pretrained pytorch model
: type model : torch . nn . Module
: param loader : test dataset loader
:... | model . eval ( )
loss = 0
correct = 0
dataset_len = len ( loader . sampler )
if progress is not None :
loader = tqdm ( loader , ** progress )
with torch . no_grad ( ) :
for batch_idx , ( data , target ) in enumerate ( loader ) :
data , target = data . to ( device ) , target . to ( device )
outpu... |
def fig_network_input_structure ( fig , params , bottom = 0.1 , top = 0.9 , transient = 200 , T = [ 800 , 1000 ] , Df = 0. , mlab = True , NFFT = 256 , srate = 1000 , window = plt . mlab . window_hanning , noverlap = 256 * 3 / 4 , letters = 'abcde' , flim = ( 4 , 400 ) , show_titles = True , show_xlabels = True , show_... | # load spike as database
networkSim = CachedNetwork ( ** params . networkSimParams )
if analysis_params . bw :
networkSim . colors = phlp . get_colors ( len ( networkSim . X ) )
# ana _ params . set _ PLOS _ 2column _ fig _ style ( ratio = ratio )
# fig = plt . figure ( )
# fig . subplots _ adjust ( left = 0.06 , r... |
def common_divisors_sum ( x : int , y : int ) -> int :
"""Implement a Python function that calculates the sum of the common divisors of two integers .
Args :
x : An integer
y : Another integer
Returns :
The sum of all common divisors of x and y
Examples :
> > > common _ divisors _ sum ( 10 , 15)
> >... | common_divisors_total = 0
for i in range ( 1 , min ( x , y ) + 1 ) :
if ( x % i == 0 ) and ( y % i == 0 ) :
common_divisors_total += i
return common_divisors_total |
def _raveled_index_for ( self , param ) :
"""get the raveled index for a param
that is an int array , containing the indexes for the flattened
param inside this parameterized logic .
! Warning ! be sure to call this method on the highest parent of a hierarchy ,
as it uses the fixes to do its work""" | from . . param import ParamConcatenation
if isinstance ( param , ParamConcatenation ) :
return np . hstack ( ( self . _raveled_index_for ( p ) for p in param . params ) )
return param . _raveled_index ( ) + self . _offset_for ( param ) |
def get ( self , center , target , date ) :
"""Retrieve the position and velocity of a target with respect to a center
Args :
center ( Target ) :
target ( Target ) :
date ( Date ) :
Return :
numpy . array : length - 6 array position and velocity ( in m and m / s ) of the
target , with respect to the c... | if ( center . index , target . index ) in self . segments :
pos , vel = self . segments [ center . index , target . index ] . compute_and_differentiate ( date . jd )
sign = 1
else : # When we wish to get a segment that is not available in the files ( such as
# EarthBarycenter with respect to the Moon , for exam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.