signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def roll_down_capture ( returns , factor_returns , window = 10 , ** kwargs ) :
"""Computes the down capture measure over a rolling window .
see documentation for : func : ` ~ empyrical . stats . down _ capture ` .
( pass all args , kwargs required )
Parameters
returns : pd . Series or np . ndarray
Daily r... | return roll ( returns , factor_returns , window = window , function = down_capture , ** kwargs ) |
def execute_log ( args , root_dir ) :
"""Print the current log file .
Args :
args [ ' keys ' ] ( int ) : If given , we only look at the specified processes .
root _ dir ( string ) : The path to the root directory the daemon is running in .""" | # Print the logs of all specified processes
if args . get ( 'keys' ) :
config_dir = os . path . join ( root_dir , '.config/pueue' )
queue_path = os . path . join ( config_dir , 'queue' )
if os . path . exists ( queue_path ) :
queue_file = open ( queue_path , 'rb' )
try :
queue = ... |
def format ( self , source ) :
"""Specifies the input data source format .
: param source : string , name of the data source , e . g . ' json ' , ' parquet ' .
> > > df = spark . read . format ( ' json ' ) . load ( ' python / test _ support / sql / people . json ' )
> > > df . dtypes
[ ( ' age ' , ' bigint ... | self . _jreader = self . _jreader . format ( source )
return self |
def submit ( self , selector , by = By . CSS_SELECTOR ) :
"""Alternative to self . driver . find _ element _ by _ * ( SELECTOR ) . submit ( )""" | if page_utils . is_xpath_selector ( selector ) :
by = By . XPATH
element = self . wait_for_element_visible ( selector , by = by , timeout = settings . SMALL_TIMEOUT )
element . submit ( )
self . __demo_mode_pause_if_active ( ) |
def stop ( self , timeout = 1.0 ) :
"""Stop the handler thread ( from another thread ) .
Parameters
timeout : float , optional
Seconds to wait for server to have * started * .""" | if timeout :
self . _running . wait ( timeout )
self . _running . clear ( )
# Make sure to wake the run thread .
self . _wake . set ( ) |
def Xor ( * xs , simplify = True ) :
"""Expression exclusive or ( XOR ) operator
If * simplify * is ` ` True ` ` , return a simplified expression .""" | xs = [ Expression . box ( x ) . node for x in xs ]
y = exprnode . xor ( * xs )
if simplify :
y = y . simplify ( )
return _expr ( y ) |
def get_nodekey ( self , token , types = types , coll_abc = collections . abc ) :
'''Given a particular token , check the visitor instance for methods
mathing the computed methodnames ( the function is a generator ) .''' | # Check the mro .
for mro_type in type ( token ) . __mro__ :
yield mro_type . __name__
# Check for callability .
if callable ( token ) :
yield 'callable'
# Check for the collections . abc types .
abc_types = ( 'Hashable' , 'Iterable' , 'Iterator' , 'Sized' , 'Container' , 'Callable' , 'Set' , 'MutableSet' , 'Ma... |
def resume ( self , vehID ) :
"""resume ( string ) - > None
Resumes the vehicle from the current stop ( throws an error if the vehicle is not stopped ) .""" | self . _connection . _beginMessage ( tc . CMD_SET_VEHICLE_VARIABLE , tc . CMD_RESUME , vehID , 1 + 4 )
self . _connection . _string += struct . pack ( "!Bi" , tc . TYPE_COMPOUND , 0 )
self . _connection . _sendExact ( ) |
def teecsv ( table , source = None , encoding = None , errors = 'strict' , write_header = True , ** csvargs ) :
"""Returns a table that writes rows to a CSV file as they are iterated over .""" | source = write_source_from_arg ( source )
csvargs . setdefault ( 'dialect' , 'excel' )
return teecsv_impl ( table , source = source , encoding = encoding , errors = errors , write_header = write_header , ** csvargs ) |
def load ( stream = None ) :
"""Loads filters from a stream , normally an open file . If one is
not passed , filters are loaded from a default location within
the project .""" | if stream :
loads ( stream . read ( ) )
else :
data = pkgutil . get_data ( insights . __name__ , _filename )
return loads ( data ) if data else None |
def to_nifti ( obj , like = None , header = None , affine = None , extensions = Ellipsis , version = 1 ) :
'''to _ nifti ( obj ) yields a Nifti2Image object that is as equivalent as possible to the given object
obj . If obj is a Nifti2Image already , then it is returned unmolested ; other deduction rules
are de... | from neuropythy . mri import Subject
obj0 = obj
# First go from like to explicit versions of affine and header :
if like is not None :
if isinstance ( like , nib . analyze . AnalyzeHeader ) or isinstance ( like , nib . freesurfer . mghformat . MGHHeader ) :
if header is None :
header = like
... |
def string_to_identifier ( s , white_space_becomes = '_' ) :
"""Takes a string and makes it suitable for use as an identifier
Translates to lower case
Replaces white space by the white _ space _ becomes character ( default = underscore ) .
Removes and punctuation .""" | import re
s = s . lower ( )
s = re . sub ( r"\s+" , white_space_becomes , s )
# replace whitespace with underscores
s = re . sub ( r"-" , "_" , s )
# replace hyphens with underscores
s = re . sub ( r"[^A-Za-z0-9_]" , "" , s )
# remove everything that ' s not a character , a digit or a _
return s |
def tritonast2arybo ( e , use_exprs = True , use_esf = False , context = None ) :
'''Convert a subset of Triton ' s AST into Arybo ' s representation
Args :
e : Triton AST
use _ esf : use ESFs when creating the final expression
context : dictionnary that associates Triton expression ID to arybo expressions ... | children_ = e . getChildren ( )
children = ( tritonast2arybo ( c , use_exprs , use_esf , context ) for c in children_ )
reversed_children = ( tritonast2arybo ( c , use_exprs , use_esf , context ) for c in reversed ( children_ ) )
Ty = e . getType ( )
if Ty == TAstN . ZX :
n = next ( children )
v = next ( childr... |
def lossfn ( real_input , fake_input , compress , hparams , lsgan , name ) :
"""Loss function .""" | eps = 1e-12
with tf . variable_scope ( name ) :
d1 = discriminator ( real_input , compress , hparams , "discriminator" )
d2 = discriminator ( fake_input , compress , hparams , "discriminator" , reuse = True )
if lsgan :
dloss = tf . reduce_mean ( tf . squared_difference ( d1 , 0.9 ) ) + tf . reduce_... |
def performSearch ( platformNames = [ ] , queries = [ ] , process = False , excludePlatformNames = [ ] ) :
"""Method to perform the search itself on the different platforms .
Args :
platforms : List of < Platform > objects .
queries : List of queries to be performed .
process : Whether to process all the pr... | # Grabbing the < Platform > objects
platforms = platform_selection . getPlatformsByName ( platformNames , mode = "searchfy" , excludePlatformNames = excludePlatformNames )
results = [ ]
for q in queries :
for pla in platforms : # This returns a json . txt !
entities = pla . getInfo ( query = q , process = p... |
def ema ( eqdata , ** kwargs ) :
"""Exponential moving average with the given span .
Parameters
eqdata : DataFrame
Must have exactly 1 column on which to calculate EMA
span : int , optional
Span for exponential moving average . Cf . ` pandas . stats . moments . ewma
< http : / / pandas . pydata . org / ... | if len ( eqdata . shape ) > 1 and eqdata . shape [ 1 ] != 1 :
_selection = kwargs . get ( 'selection' , 'Adj Close' )
_eqdata = eqdata . loc [ : , _selection ]
else :
_eqdata = eqdata
_span = kwargs . get ( 'span' , 20 )
_col = kwargs . get ( 'outputcol' , 'EMA' )
_emadf = pd . DataFrame ( index = _eqdata .... |
def _normalize_encoding ( encoding ) :
"""returns normalized name for < encoding >
see dist / src / Parser / tokenizer . c ' get _ normal _ name ( ) '
for implementation details / reference
NOTE : for now , parser . suite ( ) raises a MemoryError when
a bad encoding is used . ( SF bug # 979739)""" | if encoding is None :
return None
# lower ( ) + ' _ ' / ' - ' conversion
encoding = encoding . replace ( '_' , '-' ) . lower ( )
if encoding == 'utf-8' or encoding . startswith ( 'utf-8-' ) :
return 'utf-8'
for variant in [ 'latin-1' , 'iso-latin-1' , 'iso-8859-1' ] :
if ( encoding == variant or encoding . ... |
def set_image ( self ) :
"""Parses image element and set values""" | temp_soup = self . full_soup
for item in temp_soup . findAll ( 'item' ) :
item . decompose ( )
image = temp_soup . find ( 'image' )
try :
self . image_title = image . find ( 'title' ) . string
except AttributeError :
self . image_title = None
try :
self . image_url = image . find ( 'url' ) . string
exce... |
def listify ( * args ) :
"""Convert args to a list , unless there ' s one arg and it ' s a
function , then acts a decorator .""" | if ( len ( args ) == 1 ) and callable ( args [ 0 ] ) :
func = args [ 0 ]
@ wraps ( func )
def _inner ( * args , ** kwargs ) :
return list ( func ( * args , ** kwargs ) )
return _inner
else :
return list ( args ) |
def minimize ( func , x0 , data = None , method = None , lower_bounds = None , upper_bounds = None , constraints_func = None , nmr_observations = None , cl_runtime_info = None , options = None ) :
"""Minimization of one or more variables .
For an easy wrapper of function maximization , see : func : ` maximize ` .... | if not method :
method = 'Powell'
cl_runtime_info = cl_runtime_info or CLRuntimeInfo ( )
if len ( x0 . shape ) < 2 :
x0 = x0 [ ... , None ]
lower_bounds = _bounds_to_array ( lower_bounds or np . ones ( x0 . shape [ 1 ] ) * - np . inf )
upper_bounds = _bounds_to_array ( upper_bounds or np . ones ( x0 . shape [ 1... |
def _flattenComponent ( glyphSet , component ) :
"""Returns a list of tuples ( baseGlyph , transform ) of nested component .""" | glyph = glyphSet [ component . baseGlyph ]
if not glyph . components :
transformation = Transform ( * component . transformation )
return [ ( component . baseGlyph , transformation ) ]
all_flattened_components = [ ]
for nested in glyph . components :
flattened_components = _flattenComponent ( glyphSet , nes... |
def handle_set_services ( self , req ) :
"""Handles the POST v2 / < account > / . services call for setting services
information . Can only be called by a reseller . admin .
In the : func : ` handle _ get _ account ` ( GET v2 / < account > ) call , a section of
the returned JSON dict is ` services ` . This se... | if not self . is_reseller_admin ( req ) :
return self . denied_response ( req )
account = req . path_info_pop ( )
if req . path_info != '/.services' or not account or account [ 0 ] == '.' :
return HTTPBadRequest ( request = req )
try :
new_services = json . loads ( req . body )
except ValueError as err :
... |
def respond ( self , text , sessionID = "general" ) :
"""Generate a response to the user input .
: type text : str
: param text : The string to be mapped
: rtype : str""" | text = self . __normalize ( text )
previousText = self . __normalize ( self . conversation [ sessionID ] [ - 2 ] )
text_correction = self . __correction ( text )
current_topic = self . topic [ sessionID ]
current_topic_order = current_topic . split ( "." )
while current_topic_order :
try :
return self . __r... |
def meth_set_acl ( args ) :
"""Assign an ACL role to a list of users for a workflow .""" | acl_updates = [ { "user" : user , "role" : args . role } for user in set ( expand_fc_groups ( args . users ) ) if user != fapi . whoami ( ) ]
id = args . snapshot_id
if not id : # get the latest snapshot _ id for this method from the methods repo
r = fapi . list_repository_methods ( namespace = args . namespace , n... |
def dict ( self , key_depth = 1000 , tree_depth = 1 ) :
"""Creates a random # dict
@ key _ depth : # int number of keys per @ tree _ depth to generate random
values for
@ tree _ depth : # int dict tree dimensions size , i . e .
1 = | { key : value } |
2 = | { key : { key : value } , key2 : { key2 : value2... | if not tree_depth :
return self . _map_type ( )
return { self . randstr : self . dict ( key_depth , tree_depth - 1 ) for x in range ( key_depth ) } |
def send_activation_email ( self , user ) :
"""Send the activation email . The activation key is the username ,
signed using TimestampSigner .""" | activation_key = self . get_activation_key ( user )
context = self . get_email_context ( activation_key )
context [ 'user' ] = user
subject = render_to_string ( template_name = self . email_subject_template , context = context , request = self . request )
# Force subject to a single line to avoid header - injection
# i... |
def source_decode ( sourcecode , verbose = 0 ) :
"""Decode operator source and import operator class .
Parameters
sourcecode : string
a string of operator source ( e . g ' sklearn . feature _ selection . RFE ' )
verbose : int , optional ( default : 0)
How much information TPOT communicates while it ' s ru... | tmp_path = sourcecode . split ( '.' )
op_str = tmp_path . pop ( )
import_str = '.' . join ( tmp_path )
try :
if sourcecode . startswith ( 'tpot.' ) :
exec ( 'from {} import {}' . format ( import_str [ 4 : ] , op_str ) )
else :
exec ( 'from {} import {}' . format ( import_str , op_str ) )
op_... |
def latitude ( self , value ) :
"""Set latitude value .""" | self . _latitude = math . radians ( float ( value ) )
assert - self . PI / 2 <= self . _latitude <= self . PI / 2 , "latitude value should be between -90..90." |
def calculate_maxgold ( gold_grid : list , rows : int , cols : int ) -> int :
"""Defines a function to solve the gold mine problem .
Args :
gold _ grid : a two - dimensional list containing the amount of gold in each cell .
rows : number of rows in the gold grid .
cols : number of columns in the gold grid .... | max_gold_values = [ [ 0 for _ in range ( cols ) ] for _ in range ( rows ) ]
for column in reversed ( range ( cols ) ) :
for row in range ( rows ) :
right = max_gold_values [ row ] [ column + 1 ] if column != cols - 1 else 0
right_up = max_gold_values [ row - 1 ] [ column + 1 ] if row != 0 and column... |
def do_IHaveRequest ( self , apdu ) :
"""Respond to a I - Have request .""" | if _debug :
WhoHasIHaveServices . _debug ( "do_IHaveRequest %r" , apdu )
# check for required parameters
if apdu . deviceIdentifier is None :
raise MissingRequiredParameter ( "deviceIdentifier required" )
if apdu . objectIdentifier is None :
raise MissingRequiredParameter ( "objectIdentifier required" )
if ... |
def get_logging_fields ( self , model ) :
"""Returns a dictionary mapping of the fields that are used for
keeping the acutal audit log entries .""" | rel_name = '_%s_audit_log_entry' % model . _meta . object_name . lower ( )
def entry_instance_to_unicode ( log_entry ) :
try :
result = '%s: %s %s at %s' % ( model . _meta . object_name , log_entry . object_state , log_entry . get_action_type_display ( ) . lower ( ) , log_entry . action_date , )
except ... |
def run ( self , quiet = None , server = '' ) :
"""Start the tornado server , run forever .
' quiet ' and ' server ' arguments are no longer used , they are keep only for backward compatibility""" | try :
loop = IOLoop ( )
http_server = HTTPServer ( WSGIContainer ( self . app ) )
http_server . listen ( self . port )
loop . start ( )
except socket . error as serr : # Re raise the socket error if not " [ Errno 98 ] Address already in use "
if serr . errno != errno . EADDRINUSE :
raise ser... |
def union ( * lists , ** kwargs ) :
"""Ignore :
% timeit len ( reduce ( set . union , map ( set , x ) ) )
% timeit len ( ut . union ( * x ) )
% timeit len ( ut . unique ( ut . flatten ( ut . lmap ( np . unique , x ) ) ) )
% timeit len ( ut . unique ( ut . flatten ( x ) ) )
% timeit len ( ut . union ( * x ... | if kwargs . get ( 'ordered' , True ) :
return union_ordered ( * lists )
else :
return list_union ( * lists ) |
def emit ( self , signal , * args ) :
"""Emits a signal through the dispatcher .
: param signal | < str >
* args | additional arguments""" | if not ( self . signalsBlocked ( ) or self . signalBlocked ( signal ) ) :
super ( XViewDispatch , self ) . emit ( SIGNAL ( signal ) , * args ) |
def bootstrap ( parser = None , args = None , descriptors = None ) :
"""Bootstrap a feat process , handling command line arguments .
@ param parser : the option parser to use ; more options will be
added to the parser ; if not specified or None
a new one will be created
@ type parser : optparse . OptionPars... | tee = log . init ( )
# The purpose of having log buffer here , is to be able to dump the
# log lines to a journal after establishing connection with it .
# This is done in stage _ configure ( ) of net agency Startup procedure .
tee . add_keeper ( 'buffer' , log . LogBuffer ( limit = 10000 ) )
# use the resolver from tw... |
def has_enumerated_namespace_name ( self , namespace : str , name : str ) -> bool :
"""Check that the namespace is defined by an enumeration and that the name is a member .""" | return self . has_enumerated_namespace ( namespace ) and name in self . namespace_to_terms [ namespace ] |
def _indent ( indent = 0 , quote = '' , indent_char = ' ' ) :
"""Indent util function , compute new indent _ string""" | if indent > 0 :
indent_string = '' . join ( ( str ( quote ) , ( indent_char * ( indent - len ( quote ) ) ) ) )
else :
indent_string = '' . join ( ( ( '\x08' * ( - 1 * ( indent - len ( quote ) ) ) ) , str ( quote ) ) )
if len ( indent_string ) :
INDENT_STRINGS . append ( indent_string ) |
def _read_data ( file_obj , fo_encoding , value_count , bit_width ) :
"""Read data from the file - object using the given encoding .
The data could be definition levels , repetition levels , or actual values .""" | vals = [ ]
if fo_encoding == parquet_thrift . Encoding . RLE :
seen = 0
while seen < value_count :
values = encoding . read_rle_bit_packed_hybrid ( file_obj , bit_width )
if values is None :
break
# EOF was reached .
vals += values
seen += len ( values )
e... |
def parse_intf_section ( interface ) :
"""Parse a single entry from show interfaces output .
Different cases :
mgmt0 is up
admin state is up
Ethernet2/1 is up
admin state is up , Dedicated Interface
Vlan1 is down ( Administratively down ) , line protocol is down , autostate enabled
Ethernet154/1/48 is... | interface = interface . strip ( )
re_protocol = ( r"^(?P<intf_name>\S+?)\s+is\s+(?P<status>.+?)" r",\s+line\s+protocol\s+is\s+(?P<protocol>\S+).*$" )
re_intf_name_state = r"^(?P<intf_name>\S+) is (?P<intf_state>\S+).*"
re_is_enabled_1 = r"^admin state is (?P<is_enabled>\S+)$"
re_is_enabled_2 = r"^admin state is (?P<is_... |
def translate ( offset , dtype = None ) :
"""Translate by an offset ( x , y , z ) .
Parameters
offset : array - like , shape ( 3 , )
Translation in x , y , z .
dtype : dtype | None
Output type ( if None , don ' t cast ) .
Returns
M : ndarray
Transformation matrix describing the translation .""" | assert len ( offset ) == 3
x , y , z = offset
M = np . array ( [ [ 1. , 0. , 0. , 0. ] , [ 0. , 1. , 0. , 0. ] , [ 0. , 0. , 1. , 0. ] , [ x , y , z , 1.0 ] ] , dtype )
return M |
def clausulae_analysis ( prosody ) :
"""Return dictionary in which the key is a type of clausula and the value is its frequency .
: param prosody : the prosody of a prose text ( must be in the format of the scansion produced by the scanner classes .
: return : dictionary of prosody""" | prosody = '' . join ( prosody )
return { 'cretic + trochee' : prosody . count ( '¯˘¯¯x' ) , '4th paeon + trochee' : prosody . count ( '˘˘˘¯¯x' ) , '1st paeon + trochee' : prosody . count ( '¯˘˘˘¯x' ) , 'substituted cretic + trochee' : prosody . count ( '˘˘˘˘˘¯x' ) , '1st paeon + anapest' : prosody . count ( '¯˘˘˘˘˘x' )... |
def generate_code_challenge ( verifier ) :
"""source : https : / / github . com / openstack / deb - python - oauth2client
Creates a ' code _ challenge ' as described in section 4.2 of RFC 7636
by taking the sha256 hash of the verifier and then urlsafe
base64 - encoding it .
Args :
verifier : bytestring , ... | digest = hashlib . sha256 ( verifier . encode ( 'utf-8' ) ) . digest ( )
return base64 . urlsafe_b64encode ( digest ) . rstrip ( b'=' ) . decode ( 'utf-8' ) |
def patch_worker_run_task ( ) :
"""Patches the ` ` luigi . worker . Worker . _ run _ task ` ` method to store the worker id and the id of its
first task in the task . This information is required by the sandboxing mechanism""" | _run_task = luigi . worker . Worker . _run_task
def run_task ( self , task_id ) :
task = self . _scheduled_tasks [ task_id ]
task . _worker_id = self . _id
task . _worker_task = self . _first_task
try :
_run_task ( self , task_id )
finally :
task . _worker_id = None
task . _w... |
def sequence_to_graph ( G , seq , color = 'black' ) :
"""Automatically construct graph given a sequence of characters .""" | for x in seq :
if x . endswith ( "_1" ) : # Mutation
G . node ( x , color = color , width = "0.1" , shape = "circle" , label = "" )
else :
G . node ( x , color = color )
for a , b in pairwise ( seq ) :
G . edge ( a , b , color = color ) |
def cut_matrix ( self , n ) :
"""The matrix of connections that are severed by this cut .""" | cm = np . zeros ( ( n , n ) )
for part in self . partition :
from_ , to = self . direction . order ( part . mechanism , part . purview )
# All indices external to this part
external = tuple ( set ( self . indices ) - set ( to ) )
cm [ np . ix_ ( from_ , external ) ] = 1
return cm |
def close_stale_prs ( self , update , pull_request , scheduled ) :
"""Closes stale pull requests for the given update , links to the new pull request and deletes
the stale branch .
A stale PR is a PR that :
- Is not merged
- Is not closed
- Has no commits ( except the bot commit )
: param update :
: p... | closed = [ ]
if self . bot_token and not pull_request . is_initial :
for pr in self . pull_requests :
close_pr = False
same_title = pr . canonical_title ( self . config . pr_prefix ) == pull_request . canonical_title ( self . config . pr_prefix )
if scheduled and pull_request . is_scheduled ... |
def remove_entity_headers ( headers , allowed = ( "expires" , "content-location" ) ) :
"""Remove all entity headers from a list or : class : ` Headers ` object . This
operation works in - place . ` Expires ` and ` Content - Location ` headers are
by default not removed . The reason for this is : rfc : ` 2616 ` ... | allowed = set ( x . lower ( ) for x in allowed )
headers [ : ] = [ ( key , value ) for key , value in headers if not is_entity_header ( key ) or key . lower ( ) in allowed ] |
def generate_session_key ( hmac_secret = b'' ) :
""": param hmac _ secret : optional HMAC
: type hmac _ secret : : class : ` bytes `
: return : ( session _ key , encrypted _ session _ key ) tuple
: rtype : : class : ` tuple `""" | session_key = random_bytes ( 32 )
encrypted_session_key = PKCS1_OAEP . new ( UniverseKey . Public , SHA1 ) . encrypt ( session_key + hmac_secret )
return ( session_key , encrypted_session_key ) |
def _isophote_list_to_table ( isophote_list ) :
"""Convert an ` ~ photutils . isophote . IsophoteList ` instance to
a ` ~ astropy . table . QTable ` .
Parameters
isophote _ list : list of ` ~ photutils . isophote . Isophote ` or a ` ~ photutils . isophote . IsophoteList ` instance
A list of isophotes .
Re... | properties = OrderedDict ( )
properties [ 'sma' ] = 'sma'
properties [ 'intens' ] = 'intens'
properties [ 'int_err' ] = 'intens_err'
properties [ 'eps' ] = 'ellipticity'
properties [ 'ellip_err' ] = 'ellipticity_err'
properties [ 'pa' ] = 'pa'
properties [ 'pa_err' ] = 'pa_err'
properties [ 'grad_r_error' ] = 'grad_rer... |
def get_unspents ( address , blockchain_client = BlockcypherClient ( ) ) :
"""Get the spendable transaction outputs , also known as UTXOs or
unspent transaction outputs .""" | if not isinstance ( blockchain_client , BlockcypherClient ) :
raise Exception ( 'A BlockcypherClient object is required' )
url = '%s/addrs/%s?unspentOnly=true&includeScript=true' % ( BLOCKCYPHER_BASE_URL , address )
if blockchain_client . auth :
r = requests . get ( url + '&token=' + blockchain_client . auth [ ... |
def community_url ( self ) :
""": return : e . g https : / / steamcommunity . com / profiles / 123456789
: rtype : : class : ` str `""" | suffix = { EType . Individual : "profiles/%s" , EType . Clan : "gid/%s" , }
if self . type in suffix :
url = "https://steamcommunity.com/%s" % suffix [ self . type ]
return url % self . as_64
return None |
def search ( self , q = None , advanced = False , limit = None , info = False , reset_query = True ) :
"""Execute a search and return the results , up to the ` ` SEARCH _ LIMIT ` ` .
Arguments :
q ( str ) : The query to execute . * * Default : * * The current helper - formed query , if any .
There must be som... | # If q not specified , use internal , helper - built query
if q is None :
res = self . _ex_search ( info = info , limit = limit )
if reset_query :
self . reset_query ( )
return res
# If q was specified , run a totally independent query with a new SearchHelper
# Init SearchHelper with query , then ca... |
def fastdtw ( x , y , radius = 1 , dist = None ) :
'''return the approximate distance between 2 time series with O ( N )
time and memory complexity
Parameters
x : array _ like
input array 1
y : array _ like
input array 2
radius : int
size of neighborhood when expanding the path . A higher value will... | x , y , dist = __prep_inputs ( x , y , dist )
return __fastdtw ( x , y , radius , dist ) |
def _get_kvc ( kv_arg ) :
'''Returns a tuple keys , values , count for kv _ arg ( which can be a dict or a
tuple containing keys , values and optinally count .''' | if isinstance ( kv_arg , Mapping ) :
return six . iterkeys ( kv_arg ) , six . itervalues ( kv_arg ) , len ( kv_arg )
assert 2 <= len ( kv_arg ) <= 3 , 'Argument must be a mapping or a sequence (keys, values, [len])'
return ( kv_arg [ 0 ] , kv_arg [ 1 ] , kv_arg [ 2 ] if len ( kv_arg ) == 3 else len ( kv_arg [ 0 ] )... |
def create_scree_plot ( data , o_filename , options ) :
"""Creates the scree plot .
: param data : the eigenvalues .
: param o _ filename : the name of the output files .
: param options : the options .
: type data : numpy . ndarray
: type o _ filename : str
: type options : argparse . Namespace""" | # Importing plt
mpl . use ( "Agg" )
import matplotlib . pyplot as plt
plt . ioff ( )
# Computing the cumulative sum
cumul_data = np . cumsum ( data )
# Creating the figure and axes
fig , axes = plt . subplots ( 2 , 1 , figsize = ( 8 , 16 ) )
# The title of the figure
fig . suptitle ( options . scree_plot_title , fontsi... |
def text ( self , data ) :
"""Generates SpaceCharacters and Characters tokens
Depending on what ' s in the data , this generates one or more
` ` SpaceCharacters ` ` and ` ` Characters ` ` tokens .
For example :
> > > from html5lib . treewalkers . base import TreeWalker
> > > # Give it an empty tree just s... | data = data
middle = data . lstrip ( spaceCharacters )
left = data [ : len ( data ) - len ( middle ) ]
if left :
yield { "type" : "SpaceCharacters" , "data" : left }
data = middle
middle = data . rstrip ( spaceCharacters )
right = data [ len ( middle ) : ]
if middle :
yield { "type" : "Characters" , "data" : mi... |
def _build ( self , args ) :
'''Build a package''' | if len ( args ) < 2 :
raise SPMInvocationError ( 'A path to a formula must be specified' )
self . abspath = args [ 1 ] . rstrip ( '/' )
comps = self . abspath . split ( '/' )
self . relpath = comps [ - 1 ]
formula_path = '{0}/FORMULA' . format ( self . abspath )
if not os . path . exists ( formula_path ) :
rais... |
def merge ( base : Dict [ Any , Any ] , extension : Dict [ Any , Any ] ) -> Dict [ Any , Any ] :
'''Merge extension into base recursively .
* * Argumetnts * *
: ` ` base ` ` : dictionary to overlay values onto
: ` ` extension ` ` : dictionary to overlay with
* * Return Value ( s ) * *
Resulting dictionary... | _ = copy . deepcopy ( base )
for key , value in extension . items ( ) :
if isinstance ( value , Dict ) and key in _ :
_ [ key ] = merge ( _ [ key ] , value )
else :
_ [ key ] = value
return _ |
def query ( string ) :
"""query ( user string ) - - make http request to duckduckgo api , to get result
in json format , then call parse _ result .""" | url = "https://api.duckduckgo.com/?q="
formating = "&format=json"
query_string = url + '+' . join ( string ) + formating
try :
result = json . loads ( requests . get ( query_string ) . text )
except :
print "I'm sorry! Something went wrong. Maybe we could try again later."
return
parse_result ( result ) |
def plot_samples ( self , prop , fig = None , label = True , histtype = 'step' , bins = 50 , lw = 3 , ** kwargs ) :
"""Plots histogram of samples of desired property .
: param prop :
Desired property ( must be legit column of samples )
: param fig :
Argument for : func : ` plotutils . setfig ` ( ` ` None ` ... | setfig ( fig )
samples , stats = self . prop_samples ( prop )
fig = plt . hist ( samples , bins = bins , normed = True , histtype = histtype , lw = lw , ** kwargs )
plt . xlabel ( prop )
plt . ylabel ( 'Normalized count' )
if label :
med , lo , hi = stats
plt . annotate ( '$%.2f^{+%.2f}_{-%.2f}$' % ( med , hi ,... |
def read ( self , pos , size , ** kwargs ) :
"""Reads some data from the file , storing it into memory .
: param pos : The address to write the read data into memory
: param size : The requested length of the read
: return : The real length of the read""" | data , realsize = self . read_data ( size , ** kwargs )
if not self . state . solver . is_true ( realsize == 0 ) :
self . state . memory . store ( pos , data , size = realsize )
return realsize |
def grep_file ( query , item ) :
"""This function performs the actual grep on a given file .""" | return [ '%s: %s' % ( item , line ) for line in open ( item ) if re . search ( query , line ) ] |
def normalize_variables ( cls , variables ) :
"""Make sure version is treated consistently""" | # if the version is False , empty string , etc , throw it out
if variables . get ( 'version' , True ) in ( '' , False , '_NO_VERSION' , None ) :
del variables [ 'version' ]
return super ( PackageResource , cls ) . normalize_variables ( variables ) |
def _prop0 ( self , rho , T ) :
"""Ideal gas properties""" | rhoc = self . _constants . get ( "rhoref" , self . rhoc )
Tc = self . _constants . get ( "Tref" , self . Tc )
delta = rho / rhoc
tau = Tc / T
ideal = self . _phi0 ( tau , delta )
fio = ideal [ "fio" ]
fiot = ideal [ "fiot" ]
fiott = ideal [ "fiott" ]
propiedades = _fase ( )
propiedades . h = self . R * T * ( 1 + tau * ... |
def get_position ( self , ) :
"""Return a recommended position for this widget to appear
This implemenation returns a position so that the widget is vertically centerd on the mouse
and 10 pixels left of the mouse
: returns : the position
: rtype : QPoint
: raises : None""" | pos = QtGui . QCursor . pos ( )
if self . _alignment & QtCore . Qt . AlignLeft == QtCore . Qt . AlignLeft :
pos . setX ( pos . x ( ) - self . _offset )
elif self . _alignment & QtCore . Qt . AlignRight == QtCore . Qt . AlignRight :
pos . setX ( pos . x ( ) - self . frameGeometry ( ) . width ( ) + self . _offset... |
def sections ( self , kind = None ) :
"""Return all sections ( optionally of given kind only )""" | result = [ ]
for section in self . parser . sections ( ) : # Selected kind only if provided
if kind is not None :
try :
section_type = self . parser . get ( section , "type" )
if section_type != kind :
continue
except NoOptionError :
continue
r... |
def register ( self , endpoint , procedure = None , options = None ) :
"""Register a procedure for remote calling .
Replace : meth : ` autobahn . wamp . interface . IApplicationSession . register `""" | def proxy_endpoint ( * args , ** kwargs ) :
return self . _callbacks_runner . put ( partial ( endpoint , * args , ** kwargs ) )
return self . _async_session . register ( proxy_endpoint , procedure = procedure , options = options ) |
def locateChild ( self , ctx , segments ) :
"""Return a Deferred which will fire with the customized version of the
resource being located .""" | D = defer . maybeDeferred ( self . currentResource . locateChild , ctx , segments )
def finishLocating ( ( nextRes , nextPath ) ) :
custom = ixmantissa . ICustomizable ( nextRes , None )
if custom is not None :
return ( custom . customizeFor ( self . forWho ) , nextPath )
self . currentResource = ne... |
def _remove_regions ( in_file , remove_beds , ext , data ) :
"""Subtract a list of BED files from an input BED .
General approach handling none , one and more remove _ beds .""" | from bcbio . variation import bedutils
out_file = "%s-%s.bed" % ( utils . splitext_plus ( in_file ) [ 0 ] , ext )
if not utils . file_uptodate ( out_file , in_file ) :
with file_transaction ( data , out_file ) as tx_out_file :
with bedtools_tmpdir ( data ) :
if len ( remove_beds ) == 0 :
... |
def _get ( self , components , picker , ** params ) :
"""Generic get which handles call to api and setting of results
Return : Results object""" | url = '/' . join ( ( self . base , ) + components )
headers = { "Authorization" : "Token token=" + self . _token }
params [ 'page' ] = params . get ( 'page' ) or self . page
params [ 'per_page' ] = params . get ( 'per_page' ) or self . per_page
r = requests . get ( "." . join ( [ url , self . format ] ) , params = para... |
def dispatch ( self , * args , ** kwargs ) :
"""Only staff members can access this view""" | return super ( GetAppListJsonView , self ) . dispatch ( * args , ** kwargs ) |
def _CheckStorageFile ( self , storage_file_path ) : # pylint : disable = arguments - differ
"""Checks if the storage file path is valid .
Args :
storage _ file _ path ( str ) : path of the storage file .
Raises :
BadConfigOption : if the storage file path is invalid .""" | if os . path . exists ( storage_file_path ) :
if not os . path . isfile ( storage_file_path ) :
raise errors . BadConfigOption ( 'Storage file: {0:s} already exists and is not a file.' . format ( storage_file_path ) )
logger . warning ( 'Appending to an already existing storage file.' )
dirname = os . p... |
def get_words ( file_path = None , content = None , extension = None ) :
"""Extract all words from a source code file to be used in code completion .
Extract the list of words that contains the file in the editor ,
to carry out the inline completion similar to VSCode .""" | if ( file_path is None and ( content is None or extension is None ) or file_path and content and extension ) :
error_msg = ( 'Must provide `file_path` or `content` and `extension`' )
raise Exception ( error_msg )
if file_path and content is None and extension is None :
extension = os . path . splitext ( fil... |
def get ( self , request , * args , ** kwargs ) :
"""redirect user to captive page
with the social auth token in the querystring
( which will allow the captive page to send the token to freeradius )""" | if not request . GET . get ( 'cp' ) :
return HttpResponse ( _ ( 'missing cp GET param' ) , status = 400 )
self . authorize ( request , * args , ** kwargs )
return HttpResponseRedirect ( self . get_redirect_url ( request ) ) |
def distance_restraint_force ( self , atoms , distances , strengths ) :
"""Parameters
atoms : tuple of tuple of int or str
Pair of atom indices to be restrained , with shape ( n , 2 ) ,
like ( ( a1 , a2 ) , ( a3 , a4 ) ) . Items can be str compatible with MDTraj DSL .
distances : tuple of float
Equilibriu... | system = self . system
force = mm . HarmonicBondForce ( )
force . setUsesPeriodicBoundaryConditions ( self . system . usesPeriodicBoundaryConditions ( ) )
for pair , distance , strength in zip ( atoms , distances , strengths ) :
indices = [ ]
for atom in pair :
if isinstance ( atom , str ) :
... |
def combine_sets ( * sets ) :
"""Combine multiple sets to create a single larger set .""" | combined = set ( )
for s in sets :
combined . update ( s )
return combined |
def load_from_environ ( ) :
"""Load the SMC URL , API KEY and optional SSL certificate from
the environment .
Fields are : :
SMC _ ADDRESS = http : / / 1.1.1.1:8082
SMC _ API _ KEY = 123abc
SMC _ CLIENT _ CERT = path / to / cert
SMC _ TIMEOUT = 30 ( seconds )
SMC _ API _ VERSION = 6.1 ( optional - use... | try :
from urllib . parse import urlparse
except ImportError :
from urlparse import urlparse
smc_address = os . environ . get ( 'SMC_ADDRESS' , '' )
smc_apikey = os . environ . get ( 'SMC_API_KEY' , '' )
smc_timeout = os . environ . get ( 'SMC_TIMEOUT' , None )
api_version = os . environ . get ( 'SMC_API_VERSIO... |
def attribute_name ( self , attribute_name ) :
"""Sets the attribute _ name of this CatalogQueryRange .
The name of the attribute to be searched .
: param attribute _ name : The attribute _ name of this CatalogQueryRange .
: type : str""" | if attribute_name is None :
raise ValueError ( "Invalid value for `attribute_name`, must not be `None`" )
if len ( attribute_name ) < 1 :
raise ValueError ( "Invalid value for `attribute_name`, length must be greater than or equal to `1`" )
self . _attribute_name = attribute_name |
def render ( template , ** kwargs ) :
"""Renders the HTML containing provided summaries .
The summary has to be an instance of summary . Summary ,
or at least contain similar properties : title , image , url ,
description and collections : titles , images , descriptions .""" | import jinja2
import os . path as path
searchpath = path . join ( path . dirname ( __file__ ) , "templates" )
loader = jinja2 . FileSystemLoader ( searchpath = searchpath )
env = jinja2 . Environment ( loader = loader )
temp = env . get_template ( template )
return temp . render ( ** kwargs ) |
def _read_htm_ids ( self , mount_point ) :
"""! Function scans mbed . htm to get information about TargetID .
@ param mount _ point mbed mount point ( disk / drive letter )
@ return Function returns targetID , in case of failure returns None .
@ details Note : This function should be improved to scan variety ... | result = { }
target_id = None
for line in self . _htm_lines ( mount_point ) :
target_id = target_id or self . _target_id_from_htm ( line )
return target_id , result |
def _set_default_serializer ( self , name ) :
"""Set the default serialization method used by this library .
: param name : The name of the registered serialization method .
For example , ` ` json ` ` ( default ) , ` ` pickle ` ` , ` ` yaml ` ` ,
or any custom methods registered using : meth : ` register ` . ... | try :
( self . _default_content_type , self . _default_content_encoding , self . _default_encode ) = self . _encoders [ name ]
except KeyError :
raise SerializerNotInstalled ( "No encoder installed for %s" % name ) |
def get_shared_memory_bytes ( ) :
"""Get the size of the shared memory file system .
Returns :
The size of the shared memory file system in bytes .""" | # Make sure this is only called on Linux .
assert sys . platform == "linux" or sys . platform == "linux2"
shm_fd = os . open ( "/dev/shm" , os . O_RDONLY )
try :
shm_fs_stats = os . fstatvfs ( shm_fd )
# The value shm _ fs _ stats . f _ bsize is the block size and the
# value shm _ fs _ stats . f _ bavail i... |
def run ( self ) :
"""Runs this step until it has completed successfully , or been
skipped .""" | stop_watcher = threading . Event ( )
watcher = None
if self . watch_func :
watcher = threading . Thread ( target = self . watch_func , args = ( self . stack , stop_watcher ) )
watcher . start ( )
try :
while not self . done :
self . _run_once ( )
finally :
if watcher :
stop_watcher . set... |
def indices_within_segments ( times , segment_files , ifo = None , segment_name = None ) :
"""Return the list of indices that should be vetoed by the segments in the
list of veto _ files .
Parameters
times : numpy . ndarray of integer type
Array of gps start times
segment _ files : string or list of strin... | veto_segs = segmentlist ( [ ] )
indices = numpy . array ( [ ] , dtype = numpy . uint32 )
for veto_file in segment_files :
veto_segs += select_segments_by_definer ( veto_file , segment_name , ifo )
veto_segs . coalesce ( )
start , end = segments_to_start_end ( veto_segs )
if len ( start ) > 0 :
idx = indices_wit... |
def emit_var_assign ( self , var , t ) :
"""Emits code for storing a value into a variable
: param var : variable ( node ) to be updated
: param t : the value to emmit ( e . g . a _ label , a const , a tN . . . )""" | p = '*' if var . byref else ''
# Indirection prefix
if self . O_LEVEL > 1 and not var . accessed :
return
if not var . type_ . is_basic :
raise NotImplementedError ( )
if var . scope == SCOPE . global_ :
self . emit ( 'store' + self . TSUFFIX ( var . type_ ) , var . mangled , t )
elif var . scope == SCOPE .... |
def iter_rows ( self , start = None , end = None ) :
"""Iterate each of the Region rows in this region""" | start = start or 0
end = end or self . nrows
for i in range ( start , end ) :
yield self . iloc [ i , : ] |
def get ( self , sensor_type = 'temperature_core' ) :
"""Get sensors list .""" | self . __update__ ( )
if sensor_type == 'temperature_core' :
ret = [ s for s in self . sensors_list if s [ 'unit' ] == SENSOR_TEMP_UNIT ]
elif sensor_type == 'fan_speed' :
ret = [ s for s in self . sensors_list if s [ 'unit' ] == SENSOR_FAN_UNIT ]
else : # Unknown type
logger . debug ( "Unknown sensor type ... |
def is_java_jni_project ( self ) :
"""Indicates if the project ' s main binary is a Java Archive , which
interacts during its execution with native libraries ( via JNI ) .""" | if self . _is_java_jni_project is None :
self . _is_java_jni_project = isinstance ( self . arch , ArchSoot ) and self . simos . is_javavm_with_jni_support
return self . _is_java_jni_project |
def PathExists ( v ) :
"""Verify the path exists , regardless of its type .
> > > os . path . basename ( PathExists ( ) ( _ _ file _ _ ) ) . startswith ( ' validators . py ' )
True
> > > with raises ( Invalid , ' path does not exist ' ) :
. . . PathExists ( ) ( " random _ filename _ goes _ here . py " )
>... | try :
if v :
v = str ( v )
return os . path . exists ( v )
else :
raise PathInvalid ( "Not a Path" )
except TypeError :
raise PathInvalid ( "Not a Path" ) |
def wait_for_empty_queue ( self , wait_log_interval = 0 , wait_reason = '' ) :
"""Sit around and wait for the queue to become empty
parameters :
wait _ log _ interval - while sleeping , it is helpful if the thread
periodically announces itself so that we
know that it is still alive . This number is
the ti... | seconds = 0
while True :
if self . task_queue . empty ( ) :
break
self . quit_check ( )
if wait_log_interval and not seconds % wait_log_interval :
self . logger . info ( '%s: %dsec so far' , wait_reason , seconds )
self . quit_check ( )
seconds += 1
time . sleep ( 1.0 ) |
def in6_get6to4Prefix ( addr ) :
"""Returns the / 48 6to4 prefix associated with provided IPv4 address
On error , None is returned . No check is performed on public / private
status of the address""" | try :
addr = inet_pton ( socket . AF_INET , addr )
addr = inet_ntop ( socket . AF_INET6 , b'\x20\x02' + addr + b'\x00' * 10 )
except :
return None
return addr |
def rungtd1d ( time : Union [ datetime , str , np . ndarray ] , altkm : np . ndarray , glat : float , glon : float ) -> xarray . Dataset :
"""This is the " atomic " function looped by other functions""" | time = todt64 ( time )
# % % get solar parameters for date
f107Ap = gi . getApF107 ( time , smoothdays = 81 )
f107a = f107Ap [ 'f107s' ] . item ( )
f107 = f107Ap [ 'f107' ] . item ( )
Ap = f107Ap [ 'Ap' ] . item ( )
# % % dimensions
altkm = np . atleast_1d ( altkm )
assert altkm . ndim == 1
assert isinstance ( glon , (... |
def enumeration ( values , converter = str , default = '' ) :
"""Return an enumeration string based on the given values .
The following four examples show the standard output of function
| enumeration | :
> > > from hydpy . core . objecttools import enumeration
> > > enumeration ( ( ' text ' , 3 , [ ] ) )
... | values = tuple ( converter ( value ) for value in values )
if not values :
return default
if len ( values ) == 1 :
return values [ 0 ]
if len ( values ) == 2 :
return ' and ' . join ( values )
return ', and ' . join ( ( ', ' . join ( values [ : - 1 ] ) , values [ - 1 ] ) ) |
def has_layer ( self , class_ : Type [ L ] , became : bool = True ) -> bool :
"""Test the presence of a given layer type .
: param class _ : Layer class you ' re interested in .
: param became : Allow transformed layers in results""" | return ( class_ in self . _index or ( became and class_ in self . _transformed ) ) |
def _rv_standard ( self , word , vowels ) :
"""Return the standard interpretation of the string region RV .
If the second letter is a consonant , RV is the region after the
next following vowel . If the first two letters are vowels , RV is
the region after the next following consonant . Otherwise , RV is
th... | rv = ""
if len ( word ) >= 2 :
if word [ 1 ] not in vowels :
for i in range ( 2 , len ( word ) ) :
if word [ i ] in vowels :
rv = word [ i + 1 : ]
break
elif word [ : 2 ] in vowels :
for i in range ( 2 , len ( word ) ) :
if word [ i ] not i... |
def IntegerAbs ( input_vertex : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex :
"""Takes the absolute value of a vertex
: param input _ vertex : the vertex""" | return Integer ( context . jvm_view ( ) . IntegerAbsVertex , label , cast_to_integer_vertex ( input_vertex ) ) |
def filter_headers ( criterion ) :
"""Filter already loaded headers against some criterion .
The criterion function must accept a single argument , which is an instance
of sastool . classes2 . header . Header , or one of its subclasses . The function
must return True if the header is to be kept or False if it... | ip = get_ipython ( )
for headerkind in [ 'processed' , 'raw' ] :
for h in ip . user_ns [ '_headers' ] [ headerkind ] [ : ] :
if not criterion ( h ) :
ip . user_ns [ '_headers' ] [ headerkind ] . remove ( h )
ip . user_ns [ 'allsamplenames' ] = { h . title for h in ip . user_ns [ '_headers' ] [ '... |
def validate ( cls , mapper_spec ) :
"""Validates mapper spec .
Args :
mapper _ spec : The MapperSpec for this InputReader .
Raises :
BadReaderParamsError : required parameters are missing or invalid .""" | if mapper_spec . input_reader_class ( ) != cls :
raise BadReaderParamsError ( "Input reader class mismatch" )
params = _get_params ( mapper_spec )
if cls . BATCH_SIZE_PARAM in params :
try :
batch_size = int ( params [ cls . BATCH_SIZE_PARAM ] )
if batch_size < 1 :
raise BadReaderPar... |
def get_user ( self , user_id = None , username = None , email = None ) :
"""Returns the user specified by either ID , username or email .
Since more than user can have the same email address , searching by that
term will return a list of 1 or more User objects . Searching by
username or ID will return a sing... | if user_id :
uri = "/users/%s" % user_id
elif username :
uri = "/users?name=%s" % username
elif email :
uri = "/users?email=%s" % email
else :
raise ValueError ( "You must include one of 'user_id', " "'username', or 'email' when calling get_user()." )
resp , resp_body = self . method_get ( uri )
if resp... |
def iteration ( self , node_status = True ) :
"""Execute a single model iteration
: return : Iteration _ id , Incremental node status ( dictionary node - > status )""" | # One iteration changes the opinion of all agents using the following procedure :
# - first all agents communicate with institutional information I using a deffuant like rule
# - then random pairs of agents are selected to interact ( N pairs )
# - interaction depends on state of agents but also internal cognitive struc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.