signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def saveSettings ( self , settings ) :
"""Saves the files for this menu to the settings .
: param settings | < QSettings >""" | value = wrapVariant ( os . path . pathsep . join ( self . filenames ( ) ) )
settings . setValue ( 'recent_files' , value ) |
def add ( self , field , val ) :
"Add a sample" | if engine . FieldDefinition . FIELDS [ field ] . _matcher is matching . TimeFilter :
val = self . _basetime - val
try :
self . total [ field ] += val
self . min [ field ] = min ( self . min [ field ] , val ) if field in self . min else val
self . max [ field ] = max ( self . max [ field ] , val )
except... |
def _evaluate ( self , x , y ) :
'''Returns the level of the interpolated function at each value in x , y .
Only called internally by HARKinterpolator2D . _ _ call _ _ ( etc ) .''' | if _isscalar ( x ) :
x_pos = max ( min ( self . xSearchFunc ( self . x_list , x ) , self . x_n - 1 ) , 1 )
y_pos = max ( min ( self . ySearchFunc ( self . y_list , y ) , self . y_n - 1 ) , 1 )
else :
x_pos = self . xSearchFunc ( self . x_list , x )
x_pos [ x_pos < 1 ] = 1
x_pos [ x_pos > self . x_n ... |
def delegate ( self , fn , * args , ** kwargs ) :
"""Return the given operation as a gevent future .""" | return self . subexecutor . spawn ( fn , * args , ** kwargs ) |
def main ( ) :
"""$ ls - - color = always | ansi2html > directories . html
$ sudo tail / var / log / messages | ccze - A | ansi2html > logs . html
$ task burndown | ansi2html > burndown . html""" | scheme_names = sorted ( six . iterkeys ( SCHEME ) )
version_str = pkg_resources . get_distribution ( 'ansi2html' ) . version
parser = optparse . OptionParser ( usage = main . __doc__ , version = "%%prog %s" % version_str )
parser . add_option ( "-p" , "--partial" , dest = "partial" , default = False , action = "store_t... |
def on_drag_data_get ( self , widget , context , data , info , time ) :
"""dragged state is inserted and its state _ id sent to the receiver
: param widget :
: param context :
: param data : SelectionData : contains state _ id
: param info :
: param time :""" | library_state = self . _get_selected_library_state ( )
import rafcon . gui . helpers . state_machine as gui_helper_state_machine
gui_helper_state_machine . add_state_by_drag_and_drop ( library_state , data ) |
def network_stats ( self ) :
"""Used by Flask to show informations on the network""" | statistics = { }
mstp_networks = [ ]
mstp_map = { }
ip_devices = [ ]
bacoids = [ ]
mstp_devices = [ ]
for address , bacoid in self . whois_answer [ 0 ] . keys ( ) :
if ":" in address :
net , mac = address . split ( ":" )
mstp_networks . append ( net )
mstp_devices . append ( mac )
tr... |
def avl_split_first ( root ) :
"""Removes the minimum element from the tree
Returns :
tuple : new _ root , first _ node
O ( log ( n ) ) = O ( height ( root ) )""" | if root is None :
raise IndexError ( 'Empty tree has no maximum element' )
root , left , right = avl_release_kids ( root )
if left is None :
new_root , first_node = right , root
else :
new_left , first_node = avl_split_first ( left )
new_root = avl_join ( new_left , right , root )
return ( new_root , fi... |
def wheelEvent ( self , event ) :
"""Emits the mouse _ wheel _ activated signal .
: param event : QMouseEvent""" | initial_state = event . isAccepted ( )
event . ignore ( )
self . mouse_wheel_activated . emit ( event )
if not event . isAccepted ( ) :
event . setAccepted ( initial_state )
super ( CodeEdit , self ) . wheelEvent ( event ) |
def send_data ( self , screen_id , format_p , data ) :
"""Initiates sending data to the target .
in screen _ id of type int
The screen ID where the drag and drop event occurred .
in format _ p of type str
The MIME type the data is in .
in data of type str
The actual data .
return progress of type : cl... | if not isinstance ( screen_id , baseinteger ) :
raise TypeError ( "screen_id can only be an instance of type baseinteger" )
if not isinstance ( format_p , basestring ) :
raise TypeError ( "format_p can only be an instance of type basestring" )
if not isinstance ( data , list ) :
raise TypeError ( "data can ... |
def _register ( self , obj ) :
"""Creates a random but unique session handle for a session object ,
register it in the sessions dictionary and return the value
: param obj : a session object .
: return : session handle
: rtype : int""" | session = None
while session is None or session in self . sessions :
session = random . randint ( 1000000 , 9999999 )
self . sessions [ session ] = obj
return session |
def intersection_nodes ( waynodes ) :
"""Returns a set of all the nodes that appear in 2 or more ways .
Parameters
waynodes : pandas . DataFrame
Mapping of way IDs to node IDs as returned by ` ways _ in _ bbox ` .
Returns
intersections : set
Node IDs that appear in 2 or more ways .""" | counts = waynodes . node_id . value_counts ( )
return set ( counts [ counts > 1 ] . index . values ) |
def by_housing_units ( self , lower = - 1 , upper = 2 ** 31 , zipcode_type = ZipcodeType . Standard , sort_by = SimpleZipcode . housing_units . name , ascending = False , returns = DEFAULT_LIMIT ) :
"""Search zipcode information by house of units .""" | return self . query ( housing_units_lower = lower , housing_units_upper = upper , sort_by = sort_by , zipcode_type = zipcode_type , ascending = ascending , returns = returns , ) |
def to_dict ( self ) :
'Convert a structure into a Python native type .' | ctx = Context ( )
ContextFlags = self . ContextFlags
ctx [ 'ContextFlags' ] = ContextFlags
if ( ContextFlags & CONTEXT_DEBUG_REGISTERS ) == CONTEXT_DEBUG_REGISTERS :
for key in self . _ctx_debug :
ctx [ key ] = getattr ( self , key )
if ( ContextFlags & CONTEXT_FLOATING_POINT ) == CONTEXT_FLOATING_POINT :
... |
def _on_github_user ( self , future , access_token , response ) :
"""Invoked as a callback when self . github _ request returns the response
to the request for user data .
: param method future : The callback method to pass along
: param str access _ token : The access token for the user ' s use
: param dic... | response [ 'access_token' ] = access_token
future . set_result ( response ) |
def create_database ( self , name , owner = None ) :
"""Create a new MapD database
Parameters
name : string
Database name""" | statement = ddl . CreateDatabase ( name , owner = owner )
self . _execute ( statement ) |
def all_settings ( self , uppercase_keys = False ) :
"""Return all settings as a ` dict ` .""" | d = { }
for k in self . all_keys ( uppercase_keys ) :
d [ k ] = self . get ( k )
return d |
def type ( self , value ) :
"""Sets the type of the message .
: type value : Types
: param value : the type
: raise AttributeError : if value is not a valid type""" | if value not in list ( defines . Types . values ( ) ) :
raise AttributeError
self . _type = value |
def path_url ( self ) :
"""Build the path URL to use .""" | url = [ ]
p = urlsplit ( self . full_url )
# Proxies use full URLs .
if p . scheme in self . proxies :
return self . full_url
path = p . path
if not path :
path = '/'
url . append ( path )
query = p . query
if query :
url . append ( '?' )
url . append ( query )
return '' . join ( url ) |
def lift ( self , func ) :
"""Map function over monadic value .
Takes a function and a monadic value and maps the function over the
monadic value
Haskell : liftM : : ( Monad m ) = > ( a - > b ) - > m a - > m b
This is really the same function as Functor . fmap , but is instead
implemented using bind , and... | return self . bind ( lambda x : self . unit ( func ( x ) ) ) |
def stop ( self ) :
"""Disconnect from device .""" | if self . _outstanding :
_LOGGER . warning ( 'There were %d outstanding requests' , len ( self . _outstanding ) )
self . _initial_message_sent = False
self . _outstanding = { }
self . _one_shots = { }
self . connection . close ( ) |
def forbidden ( request ) :
"""A basic 403 view , with a login button""" | template = pkg_resources . resource_string ( 'pyramid_persona' , 'templates/forbidden.html' ) . decode ( )
html = template % { 'js' : request . persona_js , 'button' : request . persona_button }
return Response ( html , status = '403 Forbidden' ) |
def convert ( document ) :
"""Convert a document to a Text object""" | raw_tokens = [ ]
curpos = 0
text_spans = [ ]
all_labels = [ ]
sent_spans = [ ]
word_texts = [ ]
for sentence in document :
startpos = curpos
for idx , ( text , label ) in enumerate ( sentence ) :
raw_tokens . append ( text )
word_texts . append ( text )
all_labels . append ( label )
... |
def print_success ( msg , color = True ) :
"""Print a success message .
: param string msg : the message
: param bool color : if ` ` True ` ` , print with POSIX color""" | if color and is_posix ( ) :
safe_print ( u"%s[INFO] %s%s" % ( ANSI_OK , msg , ANSI_END ) )
else :
safe_print ( u"[INFO] %s" % ( msg ) ) |
def max_element ( elements , ordered = None ) :
"""Returns the maximum number in ' elements ' . Uses ' ordered ' for comparisons ,
or ' < ' is none is provided .""" | assert is_iterable ( elements )
assert callable ( ordered ) or ordered is None
if not ordered :
ordered = operator . lt
max = elements [ 0 ]
for e in elements [ 1 : ] :
if ordered ( max , e ) :
max = e
return max |
def set_secure_cookie ( self , name : str , value : Union [ str , bytes ] , expires_days : int = 30 , version : int = None , ** kwargs : Any ) -> None :
"""Signs and timestamps a cookie so it cannot be forged .
You must specify the ` ` cookie _ secret ` ` setting in your Application
to use this method . It shou... | self . set_cookie ( name , self . create_signed_value ( name , value , version = version ) , expires_days = expires_days , ** kwargs ) |
def get_switchable_as_dense ( network , component , attr , snapshots = None , inds = None ) :
"""Return a Dataframe for a time - varying component attribute with values for all
non - time - varying components filled in with the default values for the
attribute .
Parameters
network : pypsa . Network
compon... | df = network . df ( component )
pnl = network . pnl ( component )
index = df . index
varying_i = pnl [ attr ] . columns
fixed_i = df . index . difference ( varying_i )
if inds is not None :
index = index . intersection ( inds )
varying_i = varying_i . intersection ( inds )
fixed_i = fixed_i . intersection (... |
def _stamped_deps ( stamp_directory , func , dependencies , * args , ** kwargs ) :
"""Run func , assumed to have dependencies as its first argument .""" | if not isinstance ( dependencies , list ) :
jobstamps_dependencies = [ dependencies ]
else :
jobstamps_dependencies = dependencies
kwargs . update ( { "jobstamps_cache_output_directory" : stamp_directory , "jobstamps_dependencies" : jobstamps_dependencies } )
return jobstamp . run ( func , dependencies , * args... |
def randint ( low , high , shape = _Null , dtype = _Null , ctx = None , out = None , ** kwargs ) :
"""Draw random samples from a discrete uniform distribution .
Samples are uniformly distributed over the half - open interval * [ low , high ) *
( includes * low * , but excludes * high * ) .
Parameters
low : ... | return _random_helper ( _internal . _random_randint , None , [ low , high ] , shape , dtype , ctx , out , kwargs ) |
def averageValues ( self ) :
"""return the averaged values in the grid""" | assert self . opts [ 'record_density' ] and self . opts [ 'method' ] == 'sum'
# dont increase value of partly filled cells ( density 0 . . 1 ) :
filled = self . density > 1
v = self . values . copy ( )
v [ filled ] /= self . density [ filled ]
# ONLY AS OPTION ? ? :
v [ ~ filled ] *= self . density [ ~ filled ]
return ... |
def create_stack ( self , name ) :
"""Creates stack if necessary .""" | deployment = find_exact ( self . api . deployments , name = name )
if not deployment :
try : # TODO : replace when python - rightscale handles non - json
self . api . client . post ( '/api/deployments' , data = { 'deployment[name]' : name } , )
except HTTPError as e :
log . error ( 'Failed to cr... |
def get_all_conditions ( self ) :
"""Returns a generator which yields groups of lists of conditions .
> > > for set _ id , label , field in gargoyle . get _ all _ conditions ( ) : # doctest : + SKIP
> > > print " % ( label ) s : % ( field ) s " % ( label , field . label ) # doctest : + SKIP""" | for condition_set in sorted ( self . get_condition_sets ( ) , key = lambda x : x . get_group_label ( ) ) :
group = unicode ( condition_set . get_group_label ( ) )
for field in condition_set . fields . itervalues ( ) :
yield condition_set . get_id ( ) , group , field |
def _loadMetaFromJson ( self , path ) :
"""Reads the json meta into memory .
: return : the meta .""" | try :
with ( path / 'metadata.json' ) . open ( ) as infile :
return json . load ( infile )
except FileNotFoundError :
logger . error ( 'Metadata does not exist at ' + str ( path ) )
return None |
def coordination_geometry_symmetry_measures_fallback_random ( self , coordination_geometry , NRANDOM = 10 , points_perfect = None ) :
"""Returns the symmetry measures for a random set of permutations for the coordination geometry
" coordination _ geometry " . Fallback implementation for the plane separation algor... | permutations_symmetry_measures = [ None ] * NRANDOM
permutations = list ( )
algos = list ( )
perfect2local_maps = list ( )
local2perfect_maps = list ( )
for iperm in range ( NRANDOM ) :
perm = np . random . permutation ( coordination_geometry . coordination_number )
permutations . append ( perm )
p2l = { }
... |
def _read_latex_files ( self ) :
'''Check if some latex output files exist
before first latex run , process them and return
the generated data .
- Parsing * . aux for citations counter and
existing glossaries .
- Getting content of files to detect changes .
- * . toc file
- all available glossaries fi... | if os . path . isfile ( '%s.aux' % self . project_name ) :
cite_counter = self . generate_citation_counter ( )
self . read_glossaries ( )
else :
cite_counter = { '%s.aux' % self . project_name : defaultdict ( int ) }
fname = '%s.toc' % self . project_name
if os . path . isfile ( fname ) :
with open ( fn... |
def _call_api ( self , uri_pattern , method , body = None , headers = None , parameters = None , ** kwargs ) :
"""Launch HTTP request to the API with given arguments
: param uri _ pattern : string pattern of the full API url with keyword arguments ( format string syntax )
: param method : HTTP method to execute... | kwargs [ API_ROOT_URL_ARG_NAME ] = self . api_root_url
url = uri_pattern . format ( ** kwargs )
logger . info ( "Executing API request [%s %s]" , method , url )
log_print_request ( logger , method , url , parameters , headers , body )
try :
response = requests . request ( method = method , url = url , data = body ,... |
def _load ( self , scale = 1.0 ) :
"""Load the MetImage RSR data for the band requested""" | data = np . genfromtxt ( self . requested_band_filename , unpack = True , names = [ 'wavenumber' , 'response' ] , skip_header = 4 )
# Data are wavenumbers in cm - 1:
wavelength = 1. / data [ 'wavenumber' ] * 10000.
response = data [ 'response' ]
# The real MetImage has 24 detectors . However , for now we store the
# si... |
def f_aoi ( surface_tilt , surface_azimuth , solar_zenith , solar_azimuth ) :
"""Calculate angle of incidence
: param surface _ tilt :
: param surface _ azimuth :
: param solar _ zenith :
: param solar _ azimuth :
: return : angle of incidence [ deg ]""" | return pvlib . irradiance . aoi ( surface_tilt , surface_azimuth , solar_zenith , solar_azimuth ) |
def load_iris ( ) :
"""Iris Dataset .""" | dataset = datasets . load_iris ( )
return Dataset ( load_iris . __doc__ , dataset . data , dataset . target , accuracy_score , stratify = True ) |
def use_db ( path , mode = WorkDB . Mode . create ) :
"""Open a DB in file ` path ` in mode ` mode ` as a context manager .
On exiting the context the DB will be automatically closed .
Args :
path : The path to the DB file .
mode : The mode in which to open the DB . See the ` Mode ` enum for
details .
R... | database = WorkDB ( path , mode )
try :
yield database
finally :
database . close ( ) |
def dump ( self , force = False ) :
"""Encodes the value using DER
: param force :
If the encoded contents already exist , clear them and regenerate
to ensure they are in DER format instead of BER format
: return :
A byte string of the DER - encoded value""" | self . _contents = self . chosen . dump ( force = force )
if self . _header is None or force :
self . _header = b''
if self . explicit is not None :
for class_ , tag in self . explicit :
self . _header = _dump_header ( class_ , 1 , tag , self . _header + self . _contents ) + self . _header
r... |
def flp_nonlinear_soco ( I , J , d , M , f , c ) :
"""flp _ nonlinear _ soco - - use
Parameters :
- I : set of customers
- J : set of facilities
- d [ i ] : demand for product i
- M [ j ] : capacity of facility j
- f [ j ] : fixed cost for using a facility in point j
- c [ i , j ] : unit cost of servi... | model = Model ( "nonlinear flp -- soco formulation" )
x , X , u = { } , { } , { }
for j in J :
X [ j ] = model . addVar ( ub = M [ j ] , vtype = "C" , name = "X(%s)" % j )
# for sum _ i x _ ij
u [ j ] = model . addVar ( vtype = "C" , name = "u(%s)" % j )
# for replacing sqrt sum _ i x _ ij in soco
f... |
def trocar_codigo_de_ativacao ( self , novo_codigo_ativacao , opcao = constantes . CODIGO_ATIVACAO_REGULAR , codigo_emergencia = None ) :
"""Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . trocar _ codigo _ de _ ativacao ` .
: return : Uma resposta SAT padrão .
: rtype : satcfe . resposta . padrao . Respos... | retorno = super ( ClienteSATLocal , self ) . trocar_codigo_de_ativacao ( novo_codigo_ativacao , opcao = opcao , codigo_emergencia = codigo_emergencia )
return RespostaSAT . trocar_codigo_de_ativacao ( retorno ) |
def get ( key , default = - 1 ) :
"""Backport support for original codes .""" | if isinstance ( key , int ) :
return ECDSA_Curve ( key )
if key not in ECDSA_Curve . _member_map_ :
extend_enum ( ECDSA_Curve , key , default )
return ECDSA_Curve [ key ] |
def make_disjunct_indices ( self , * others ) :
"""Return a copy with modified indices to ensure disjunct indices with
` others ` .
Each element in ` others ` may be an index symbol ( : class : ` . IdxSym ` ) ,
a index - range object ( : class : ` . IndexRangeBase ` ) or list of index - range
objects , or a... | new = self
other_index_symbols = set ( )
for other in others :
try :
if isinstance ( other , IdxSym ) :
other_index_symbols . add ( other )
elif isinstance ( other , IndexRangeBase ) :
other_index_symbols . add ( other . index_symbol )
elif hasattr ( other , 'ranges' ... |
def sanitize_release_group ( string ) :
"""Sanitize a ` release _ group ` string to remove content in square brackets .
: param str string : the release group to sanitize .
: return : the sanitized release group .
: rtype : str""" | # only deal with strings
if string is None :
return
# remove content in square brackets
string = re . sub ( r'\[\w+\]' , '' , string )
# strip and upper case
return string . strip ( ) . upper ( ) |
def ndstype ( self ) :
"""NDS type integer for this channel .
This property is mapped to the ` Channel . type ` string .""" | if self . type is not None :
return io_nds2 . Nds2ChannelType . find ( self . type ) . value |
def generate ( self , chars , format = 'png' ) :
"""Generate an Image Captcha of the given characters .
: param chars : text to be generated .
: param format : image file format""" | im = self . generate_image ( chars )
out = BytesIO ( )
im . save ( out , format = format )
out . seek ( 0 )
return out |
def operator ( self ) :
"""Supported Filter Operators
+ EQ - Equal To
+ NE - Not Equal To
+ GT - Greater Than
+ GE - Greater Than or Equal To
+ LT - Less Than
+ LE - Less Than or Equal To
+ SW - Starts With
+ IN - In String or Array
+ NI - Not in String or Array""" | return { 'EQ' : operator . eq , 'NE' : operator . ne , 'GT' : operator . gt , 'GE' : operator . ge , 'LT' : operator . lt , 'LE' : operator . le , 'SW' : self . _starts_with , 'IN' : self . _in , 'NI' : self . _ni , # not in
} |
def handle_onchain_secretreveal ( mediator_state : MediatorTransferState , onchain_secret_reveal : ContractReceiveSecretReveal , channelidentifiers_to_channels : ChannelMap , pseudo_random_generator : random . Random , block_number : BlockNumber , ) -> TransitionResult [ MediatorTransferState ] :
"""The secret was ... | secrethash = onchain_secret_reveal . secrethash
is_valid_reveal = is_valid_secret_reveal ( state_change = onchain_secret_reveal , transfer_secrethash = mediator_state . secrethash , secret = onchain_secret_reveal . secret , )
if is_valid_reveal :
secret = onchain_secret_reveal . secret
# Compare against the blo... |
def summary ( self , sortOn = None ) :
"""Summarize all the alignments for this title .
@ param sortOn : A C { str } attribute to sort titles on . One of ' length ' ,
' maxScore ' , ' medianScore ' , ' readCount ' , or ' title ' .
@ raise ValueError : If an unknown C { sortOn } value is given .
@ return : A... | titles = self if sortOn is None else self . sortTitles ( sortOn )
for title in titles :
yield self [ title ] . summary ( ) |
def _parse_ospf_process_id ( self , config ) :
"""Parses config file for the OSPF proc ID
Args :
config ( str ) : Running configuration
Returns :
dict : key : ospf _ process _ id ( int )""" | match = re . search ( r'^router ospf (\d+)' , config )
return dict ( ospf_process_id = int ( match . group ( 1 ) ) ) |
def InitDetectorNetwork ( numDets , detNetwork , LIGO3FLAG = 0 ) :
"""InitDetectorNetwork - function to initialise desired detector network
specified as input .
numDets - Number of IFOs in the detector network to be considered , can
take any value in the range [ 1,5 ] .
detNetwork - 5 character string to si... | # Create arrays for output
Noise = np . zeros ( ( N_fd , numDets ) , complex )
PSD = np . zeros ( ( N_fd , numDets ) , float )
detPosVector = np . zeros ( ( 3 , numDets ) , float )
detRespTensor = np . zeros ( ( 3 , 3 , numDets ) , float )
# Create detector names array
detNames = [ ]
if detNetwork [ 0 ] == 'H' :
de... |
def update_status ( self , helper , status ) :
"""update the helper""" | if status :
self . status ( status [ 0 ] )
# if the status is ok , add it to the long output
if status [ 0 ] == 0 :
self . add_long_output ( status [ 1 ] )
# if the status is not ok , add it to the summary
else :
self . add_summary ( status [ 1 ] ) |
def connect_amqp_by_unit ( self , sentry_unit , ssl = False , port = None , fatal = True , username = "testuser1" , password = "changeme" ) :
"""Establish and return a pika amqp connection to the rabbitmq service
running on a rmq juju unit .
: param sentry _ unit : sentry unit pointer
: param ssl : boolean , ... | host = sentry_unit . info [ 'public-address' ]
unit_name = sentry_unit . info [ 'unit_name' ]
# Default port logic if port is not specified
if ssl and not port :
port = 5671
elif not ssl and not port :
port = 5672
self . log . debug ( 'Connecting to amqp on {}:{} ({}) as ' '{}...' . format ( host , port , unit_... |
def delete_group_maintainer ( self , grp_name , user ) :
"""Delete the given user to the named group .
Both group and user must already exist for this to succeed .
Args :
name ( string ) : Name of group .
user ( string ) : User to add to group .
Raises :
requests . HTTPError on failure .""" | self . service . delete_group_maintainer ( grp_name , user , self . url_prefix , self . auth , self . session , self . session_send_opts ) |
def __authenticate ( self , ad , username , password ) :
'''Active Directory auth function
: param ad : LDAP connection string ( ' ldap : / / server ' )
: param username : username with domain ( ' user @ domain . name ' )
: param password : auth password
: return : ldap connection or None if error''' | result = None
conn = ldap . initialize ( ad )
conn . protocol_version = 3
conn . set_option ( ldap . OPT_REFERRALS , 0 )
user = self . __prepare_user_with_domain ( username )
self . logger . debug ( "Trying to auth with user '{}' to {}" . format ( user , ad ) )
try :
conn . simple_bind_s ( user , password )
res... |
def host ( self , * paths , ** query_kwargs ) :
"""create a new url object using the host as a base
if you had requested http : / / host / foo / bar , then this would append * paths and * * query _ kwargs
to http : / / host
: example :
# current url : http : / / host / foo / bar
print url # http : / / hos... | kwargs = self . _normalize_params ( * paths , ** query_kwargs )
return self . create ( self . root , ** kwargs ) |
def create_db_entry ( self , comment = '' ) :
"""Create a db entry for this task file info
and link it with a optional comment
: param comment : a comment for the task file entry
: type comment : str
: returns : The created TaskFile django instance and the comment . If the comment was empty , None is return... | jbfile = JB_File ( self )
p = jbfile . get_fullpath ( )
user = dj . get_current_user ( )
tf = dj . models . TaskFile ( path = p , task = self . task , version = self . version , releasetype = self . releasetype , descriptor = self . descriptor , typ = self . typ , user = user )
tf . full_clean ( )
tf . save ( )
note = ... |
def export_setting ( self ) :
"""Export setting from an existing file .""" | LOGGER . debug ( 'Export button clicked' )
home_directory = os . path . expanduser ( '~' )
file_name = self . organisation_line_edit . text ( ) . replace ( ' ' , '_' )
file_path , __ = QFileDialog . getSaveFileName ( self , self . tr ( 'Export InaSAFE settings' ) , os . path . join ( home_directory , file_name + '.json... |
def delete_logs ( room ) :
"""Deletes chat logs""" | from indico_chat . plugin import ChatPlugin
base_url = ChatPlugin . settings . get ( 'log_url' )
if not base_url or room . custom_server :
return
try :
response = requests . get ( posixpath . join ( base_url , 'delete' ) , params = { 'cr' : room . jid } ) . json ( )
except ( RequestException , ValueError ) :
... |
def textslice ( self , start , end ) :
"""Return a chunk referencing a slice of a scalar text value .""" | return self . _select ( self . _pointer . textslice ( start , end ) ) |
def update_resolver_nameservers ( resolver , nameservers , nameserver_filename ) :
"""Update a resolver ' s nameservers . The following priority is taken :
1 . Nameservers list provided as an argument
2 . A filename containing a list of nameservers
3 . The original nameservers associated with the resolver""" | if nameservers :
resolver . nameservers = nameservers
elif nameserver_filename :
nameservers = get_stripped_file_lines ( nameserver_filename )
resolver . nameservers = nameservers
else : # Use original nameservers
pass
return resolver |
def get_sigla ( self , work ) :
"""Returns a list of all of the sigla for ` work ` .
: param work : name of work
: type work : ` str `
: rtype : ` list ` of ` str `""" | return [ os . path . splitext ( os . path . basename ( path ) ) [ 0 ] for path in glob . glob ( os . path . join ( self . _path , work , '*.txt' ) ) ] |
def normalize_params ( params ) :
"""Take a list of dictionaries , and tokenize / normalize .""" | # Collect a set of all fields
fields = set ( )
for p in params :
fields . update ( p )
fields = sorted ( fields )
params2 = list ( pluck ( fields , params , MISSING ) )
# Non - basic types ( including MISSING ) are unique to their id
tokens = [ tuple ( x if isinstance ( x , ( int , float , str ) ) else id ( x ) for... |
def _new_alloc_handle ( stype , shape , ctx , delay_alloc , dtype , aux_types , aux_shapes = None ) :
"""Return a new handle with specified storage type , shape , dtype and context .
Empty handle is only used to hold results
Returns
handle
A new empty ndarray handle""" | hdl = NDArrayHandle ( )
for aux_t in aux_types :
if np . dtype ( aux_t ) != np . dtype ( "int64" ) :
raise NotImplementedError ( "only int64 is supported for aux types" )
aux_type_ids = [ int ( _DTYPE_NP_TO_MX [ np . dtype ( aux_t ) . type ] ) for aux_t in aux_types ]
aux_shapes = [ ( 0 , ) for aux_t in aux... |
def abspath ( self , path ) :
'''Transform the path to an absolute path
Args :
path ( string ) : The path to transform to an absolute path
Returns :
string : The absolute path to the file''' | if not path . startswith ( os . path . sep ) or path . startswith ( '~' ) :
path = os . path . expanduser ( os . path . join ( self . base_path , path ) )
return path |
def list_memberships ( self , subject_descriptor , direction = None , depth = None ) :
"""ListMemberships .
[ Preview API ] Get all the memberships where this descriptor is a member in the relationship .
: param str subject _ descriptor : Fetch all direct memberships of this descriptor .
: param str direction... | route_values = { }
if subject_descriptor is not None :
route_values [ 'subjectDescriptor' ] = self . _serialize . url ( 'subject_descriptor' , subject_descriptor , 'str' )
query_parameters = { }
if direction is not None :
query_parameters [ 'direction' ] = self . _serialize . query ( 'direction' , direction , '... |
def get_login_url ( self ) :
"""Generates CAS login URL""" | params = { 'service' : self . service_url }
if self . renew :
params . update ( { 'renew' : 'true' } )
params . update ( self . extra_login_params )
url = urllib_parse . urljoin ( self . server_url , 'login' )
query = urllib_parse . urlencode ( params )
return url + '?' + query |
def get_parsed_context ( pipeline , context_in_string ) :
"""Execute get _ parsed _ context handler if specified .
Dynamically load the module specified by the context _ parser key in pipeline
dict and execute the get _ parsed _ context function on that module .
Args :
pipeline : dict . Pipeline object .
... | logger . debug ( "starting" )
if 'context_parser' in pipeline :
parser_module_name = pipeline [ 'context_parser' ]
logger . debug ( f"context parser found: {parser_module_name}" )
parser_module = pypyr . moduleloader . get_module ( parser_module_name )
try :
logger . debug ( f"running parser {pa... |
def _parse_uri_options ( self , parsed_uri , use_ssl = False , ssl_options = None ) :
"""Parse the uri options .
: param parsed _ uri :
: param bool use _ ssl :
: return :""" | ssl_options = ssl_options or { }
kwargs = urlparse . parse_qs ( parsed_uri . query )
vhost = urlparse . unquote ( parsed_uri . path [ 1 : ] ) or DEFAULT_VIRTUAL_HOST
options = { 'ssl' : use_ssl , 'virtual_host' : vhost , 'heartbeat' : int ( kwargs . pop ( 'heartbeat' , [ DEFAULT_HEARTBEAT_INTERVAL ] ) [ 0 ] ) , 'timeou... |
def host ( self , value = None ) :
"""Return the host
: param string value : new host string""" | if value is not None :
return URL . _mutate ( self , host = value )
return self . _tuple . host |
def refresh_access_token ( credential ) :
"""Use a refresh token to request a new access token .
Not suported for access tokens obtained via Implicit Grant .
Parameters
credential ( OAuth2Credential )
An authorized user ' s OAuth 2.0 credentials .
Returns
( Session )
A new Session object with refreshe... | if credential . grant_type == auth . AUTHORIZATION_CODE_GRANT :
response = _request_access_token ( grant_type = auth . REFRESH_TOKEN , client_id = credential . client_id , client_secret = credential . client_secret , redirect_url = credential . redirect_url , refresh_token = credential . refresh_token , )
oauth... |
def parse_unicode ( self , i , wide = False ) :
"""Parse Unicode .""" | text = self . get_wide_unicode ( i ) if wide else self . get_narrow_unicode ( i )
value = int ( text , 16 )
single = self . get_single_stack ( )
if self . span_stack :
text = self . convert_case ( chr ( value ) , self . span_stack [ - 1 ] )
value = ord ( self . convert_case ( text , single ) ) if single is not ... |
def init_config ( app ) :
"""Initialize configuration .
. . note : : If CairoSVG is installed then the configuration
` ` FORMATTER _ BADGES _ ENABLE ` ` is ` ` True ` ` .
: param app : The Flask application .""" | try :
get_distribution ( 'CairoSVG' )
has_cairo = True
except DistributionNotFound :
has_cairo = False
app . config . setdefault ( 'FORMATTER_BADGES_ENABLE' , has_cairo )
for attr in dir ( config ) :
if attr . startswith ( 'FORMATTER_' ) :
app . config . setdefault ( attr , getattr ( config , at... |
def linkify_h_by_h ( self ) :
"""Link hosts with their parents
: return : None""" | for host in self : # The new member list
new_parents = [ ]
for parent in getattr ( host , 'parents' , [ ] ) :
parent = parent . strip ( )
o_parent = self . find_by_name ( parent )
if o_parent is not None :
new_parents . append ( o_parent . uuid )
else :
er... |
def register_tile ( self , hw_type , api_major , api_minor , name , fw_major , fw_minor , fw_patch , exec_major , exec_minor , exec_patch , slot , unique_id ) :
"""Register a tile with this controller .
This function adds the tile immediately to its internal cache of registered tiles
and queues RPCs to send all... | api_info = ( api_major , api_minor )
fw_info = ( fw_major , fw_minor , fw_patch )
exec_info = ( exec_major , exec_minor , exec_patch )
address = 10 + slot
info = TileInfo ( hw_type , name , api_info , fw_info , exec_info , slot , unique_id , state = TileState . JUST_REGISTERED , address = address )
self . tile_manager ... |
def update ( self , spec_obj , context , match_obj , line ) :
"""Update given spec object and parse context and return them again .
: param spec _ obj : An instance of Spec class
: param context : The parse context
: param match _ obj : The re . match object
: param line : The original line
: return : Giv... | assert spec_obj
assert context
assert match_obj
assert line
return self . update_impl ( spec_obj , context , match_obj , line ) |
async def set_power_settings ( self , target : str , value : str ) -> None :
"""Set power settings .""" | params = { "settings" : [ { "target" : target , "value" : value } ] }
return await self . services [ "system" ] [ "setPowerSettings" ] ( params ) |
def search ( self , trace_func : Callable [ [ List [ LineSequence ] , float , float , float , bool ] , None ] = None ) -> List [ LineSequence ] :
"""Issues new linear sequence search .
Each call to this method starts new search .
Args :
trace _ func : Optional callable which will be called for each simulated ... | def search_trace ( state : _STATE , temp : float , cost : float , probability : float , accepted : bool ) :
if trace_func :
trace_seqs , _ = state
trace_func ( trace_seqs , temp , cost , probability , accepted )
seqs , _ = optimization . anneal_minimize ( self . _create_initial_solution ( ) , self .... |
def logvol_prefactor ( n , p = 2. ) :
"""Returns the ln ( volume constant ) for an ` n ` - dimensional sphere with an
: math : ` L ^ p ` norm . The constant is defined as : :
lnf = n * ln ( 2 . ) + n * LogGamma ( 1 . / p + 1 ) - LogGamma ( n / p + 1 . )
By default the ` p = 2 . ` norm is used ( i . e . the st... | p *= 1.
# convert to float in case user inputs an integer
lnf = ( n * np . log ( 2. ) + n * special . gammaln ( 1. / p + 1. ) - special . gammaln ( n / p + 1 ) )
return lnf |
def open_database ( self ) :
"""Opens the sqlite database .""" | if not self . con :
try :
self . con = psycopg2 . connect ( host = self . host , database = self . dbname , user = self . user , password = self . password , port = self . port )
except psycopg2 . Error as e :
print ( "Error while opening database:" )
print ( e . pgerror ) |
def prepend_environ_path ( env , name , text , pathsep = os . pathsep ) :
"""Prepend ` text ` into a $ PATH - like environment variable . ` env ` is a
dictionary of environment variables and ` name ` is the variable name .
` pathsep ` is the character separating path elements , defaulting to
` os . pathsep ` ... | env [ name ] = prepend_path ( env . get ( name ) , text , pathsep = pathsep )
return env |
def load_map ( map , src_file , output_dir , scale = 1 , cache_dir = None , datasources_cfg = None , user_styles = [ ] , verbose = False ) :
"""Apply a stylesheet source file to a given mapnik Map instance , like mapnik . load _ map ( ) .
Parameters :
map :
Instance of mapnik . Map .
src _ file :
Location... | scheme , n , path , p , q , f = urlparse ( src_file )
if scheme in ( 'file' , '' ) :
assert exists ( src_file ) , "We'd prefer an input file that exists to one that doesn't"
if cache_dir is None :
cache_dir = expanduser ( CACHE_DIR )
# only make the cache dir if it wasn ' t user - provided
if not isdir ... |
def attach ( self , endpoints , serverish ) :
"""Attach a socket to zero or more endpoints . If endpoints is not null ,
parses as list of ZeroMQ endpoints , separated by commas , and prefixed by
' @ ' ( to bind the socket ) or ' > ' ( to connect the socket ) . Returns 0 if all
endpoints were valid , or - 1 if... | return lib . zsock_attach ( self . _as_parameter_ , endpoints , serverish ) |
def extract_translations ( self , string ) :
"""Extract messages from Python string .""" | tree = ast . parse ( string )
# ast _ visit ( tree )
visitor = TransVisitor ( self . tranz_functions , self . tranzchoice_functions )
visitor . visit ( tree )
return visitor . translations |
def reset ( self ) :
"""Reset state .""" | from samplerate . lowlevel import src_reset
if self . _state is None :
self . _create ( )
src_reset ( self . _state ) |
def remove_children ( self , reset_parent = True ) :
"""Remove all the children of this node .
: param bool reset _ parent : if ` ` True ` ` , set to ` ` None ` ` the parent attribute
of the children""" | if reset_parent :
for child in self . children :
child . parent = None
self . __children = [ ] |
def __query ( self , query , tagid = None ) :
"""Extracts nodes that match the query from the Response
: param query : Xpath Expresion
: type query : String
: param tagid : Tag ID
: type query : String
: returns : The queried nodes
: rtype : list""" | if self . encrypted :
document = self . decrypted_document
else :
document = self . document
return OneLogin_Saml2_Utils . query ( document , query , None , tagid ) |
def from_ofxparse ( data , institution ) :
"""Instantiate : py : class : ` ofxclient . Account ` subclass from ofxparse
module
: param data : an ofxparse account
: type data : An : py : class : ` ofxparse . Account ` object
: param institution : The parent institution of the account
: type institution : :... | description = data . desc if hasattr ( data , 'desc' ) else None
if data . type == AccountType . Bank :
return BankAccount ( institution = institution , number = data . account_id , routing_number = data . routing_number , account_type = data . account_type , description = description )
elif data . type == AccountT... |
def set ( self , locs , values ) :
"""Modify Block in - place with new item value
Returns
None""" | try :
self . values [ locs ] = values
except ( ValueError ) : # broadcasting error
# see GH6171
new_shape = list ( values . shape )
new_shape [ 0 ] = len ( self . items )
self . values = np . empty ( tuple ( new_shape ) , dtype = self . dtype )
self . values . fill ( np . nan )
self . values [ l... |
def find_strongest_extension ( class_id , ext_list ) :
"""Determine the strongest extension to a class based on defined criteria and format the return string accordingly .
The strength of an extension is calculated based on the number of uppercase letters ( CAP )
and the number of lowercase letters ( SM ) . The... | strongest_extension = max ( ext_list , key = lambda ext : sum ( 1 for char in ext if char . isupper ( ) ) - sum ( 1 for char in ext if char . islower ( ) ) )
return f'{class_id}.{strongest_extension}' |
def GetHostCpuUsedMs ( self ) :
'''Undocumented .''' | counter = c_uint64 ( )
ret = vmGuestLib . VMGuestLib_GetHostCpuUsedMs ( self . handle . value , byref ( counter ) )
if ret != VMGUESTLIB_ERROR_SUCCESS :
raise VMGuestLibException ( ret )
return counter . value |
def compute_batch ( self , duplicate_manager = None , context_manager = None ) :
"""Selects the new location to evaluate the objective .""" | x , _ = self . acquisition . optimize ( duplicate_manager = duplicate_manager )
return x |
def allow_sync ( self ) :
"""Allow sync queries within context . Close sync
connection on exit if connected .
Example : :
with database . allow _ sync ( ) :
PageBlock . create _ table ( True )""" | old_allow_sync = self . _allow_sync
self . _allow_sync = True
try :
yield
except :
raise
finally :
try :
self . close ( )
except self . Error :
pass
# already closed
self . _allow_sync = old_allow_sync |
def path_to_resource ( project , path , type = None ) :
"""Get the resource at path
You only need to specify ` type ` if ` path ` does not exist . It can
be either ' file ' or ' folder ' . If the type is ` None ` it is assumed
that the resource already exists .
Note that this function uses ` Project . get _... | project_path = path_relative_to_project_root ( project , path )
if project_path is None :
project_path = rope . base . project . _realpath ( path )
project = rope . base . project . get_no_project ( )
if type is None :
return project . get_resource ( project_path )
if type == 'file' :
return project . g... |
def get_tokens ( self , format_string ) :
"""Tokenize a logging format string .
: param format _ string : The logging format string .
: returns : A list of strings with formatting directives separated from surrounding text .""" | return [ t for t in self . tokenize_pattern . split ( format_string ) if t ] |
def resize ( self , signum , obj ) :
"""handler for SIGWINCH""" | self . s . clear ( )
stream_cursor = self . pads [ 'streams' ] . getyx ( ) [ 0 ]
for pad in self . pads . values ( ) :
pad . clear ( )
self . s . refresh ( )
self . set_screen_size ( )
self . set_title ( TITLE_STRING )
self . init_help ( )
self . init_streams_pad ( )
self . move ( stream_cursor , absolute = True , ... |
def _wrap_execute_after ( funcname ) :
"""Warp the given method , so it gets executed by the reactor
Wrap a method of : data : ` IRCCLient . out _ connection ` .
The returned function should be assigned to a : class : ` irc . client . SimpleIRCClient ` class .
: param funcname : the name of a : class : ` irc ... | def method ( self , * args , ** kwargs ) :
f = getattr ( self . out_connection , funcname )
p = functools . partial ( f , * args , ** kwargs )
self . reactor . scheduler . execute_after ( 0 , p )
method . __name__ = funcname
return method |
def parse_dict_header ( value ) :
"""Parse lists of key , value pairs as described by RFC 2068 Section 2 and
convert them into a python dict :
> > > d = parse _ dict _ header ( ' foo = " is a fish " , bar = " as well " ' )
> > > type ( d ) is dict
True
> > > sorted ( d . items ( ) )
[ ( ' bar ' , ' as w... | result = { }
for item in parse_http_list ( value ) :
if '=' not in item :
result [ item ] = None
continue
name , value = item . split ( '=' , 1 )
if value [ : 1 ] == value [ - 1 : ] == '"' :
value = unquote_header_value ( value [ 1 : - 1 ] )
result [ name ] = value
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.