signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def design_matrix ( phases , degree ) :
r"""Constructs an : math : ` N \ times 2n + 1 ` matrix of the form :
. . math : :
\ begin { bmatrix }
& \ sin ( 1 \ cdot 2 \ pi \ cdot \ phi _ 0)
& \ cos ( 1 \ cdot 2 \ pi \ cdot \ phi _ 0)
& \ ldots
& \ sin ( n \ cdot 2 \ pi \ cdot \ phi _ 0)
& \ cos ( n \ cdot... | n_samples = phases . size
# initialize coefficient matrix
M = numpy . empty ( ( n_samples , 2 * degree + 1 ) )
# indices
i = numpy . arange ( 1 , degree + 1 )
# initialize the Nxn matrix that is repeated within the
# sine and cosine terms
x = numpy . empty ( ( n_samples , degree ) )
# the Nxn matrix now has N copies of... |
def mark_whole_doc_dirty ( self ) :
"""Marks the whole document as dirty to force a full refresh . * * SLOW * *""" | text_cursor = self . _editor . textCursor ( )
text_cursor . select ( text_cursor . Document )
self . _editor . document ( ) . markContentsDirty ( text_cursor . selectionStart ( ) , text_cursor . selectionEnd ( ) ) |
def is_resource_modified ( environ , etag = None , data = None , last_modified = None , ignore_if_range = True ) :
"""Convenience method for conditional requests .
: param environ : the WSGI environment of the request to be checked .
: param etag : the etag for the response for comparison .
: param data : or ... | if etag is None and data is not None :
etag = generate_etag ( data )
elif data is not None :
raise TypeError ( "both data and etag given" )
if environ [ "REQUEST_METHOD" ] not in ( "GET" , "HEAD" ) :
return False
unmodified = False
if isinstance ( last_modified , string_types ) :
last_modified = parse_d... |
def regroup_if_changed ( group , op_list , name = None ) :
"""Creates a new group for op _ list if it has changed .
Args :
group : The current group . It is returned if op _ list is unchanged .
op _ list : The list of operations to check .
name : The name to use if a new group is created .
Returns :
Eit... | has_deltas = isinstance ( op_list , sequence_with_deltas . SequenceWithDeltas )
if ( group is None or len ( group . control_inputs ) != len ( op_list ) or ( has_deltas and op_list . has_changed ( ) ) ) :
if has_deltas :
op_list . mark ( )
if op_list :
return tf . group ( * op_list , name = name ... |
def make_argparser ( ) :
"""Setup argparse arguments .
: return : The parser which : class : ` MypolrCli ` expects parsed arguments from .
: rtype : argparse . ArgumentParser""" | parser = argparse . ArgumentParser ( prog = 'mypolr' , description = "Interacts with the Polr Project's API.\n\n" "User Guide and documentation: https://mypolr.readthedocs.io" , formatter_class = argparse . ArgumentDefaultsHelpFormatter , epilog = "NOTE: if configurations are saved, they are stored as plain text on dis... |
def report_data ( self , entity_data ) :
"""Used to report entity data ( metrics & snapshot ) to the host agent .""" | try :
response = None
response = self . client . post ( self . __data_url ( ) , data = self . to_json ( entity_data ) , headers = { "Content-Type" : "application/json" } , timeout = 0.8 )
# logger . warn ( " report _ data : response . status _ code is % s " % response . status _ code )
if response . sta... |
def start_class ( self , class_ ) :
"""Start all services of a given class . If this manager doesn ' t already
have a service of that class , it constructs one and starts it .""" | matches = filter ( lambda svc : isinstance ( svc , class_ ) , self )
if not matches :
svc = class_ ( )
self . register ( svc )
matches = [ svc ]
map ( self . start , matches )
return matches |
def GetEntries ( self , parser_mediator , match = None , ** unused_kwargs ) :
"""Extracts Safari history items .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
match ( Optional [ dict [ str : object ] ] ) : keys extracte... | format_version = match . get ( 'WebHistoryFileVersion' , None )
if format_version != 1 :
parser_mediator . ProduceExtractionWarning ( 'unsupported Safari history version: {0!s}' . format ( format_version ) )
return
if 'WebHistoryDates' not in match :
return
for history_entry in match . get ( 'WebHistoryDate... |
def parse_arg_types ( text = None , is_return_included = False ) :
""": param text : str of the text to parse , by default
uses calling function doc
: param is _ return _ included : bool if True return will be return as well
: return : dict of args and variable types""" | text = text or function_doc ( 2 )
if is_return_included :
text = text . replace ( ':return:' , ':param return:' )
ret = { }
def evl ( text_ ) :
try :
return eval ( text_ )
except Exception as e :
return text_
if ':param' in text :
for param in text . split ( ':param ' ) [ 1 : ] :
... |
def set_user_name ( uid , name , ** kwargs ) :
'''Set user name
: param uid : user number [ 1:16]
: param name : username ( limit of 16bytes )
: param kwargs :
- api _ host = 127.0.0.1
- api _ user = admin
- api _ pass = example
- api _ port = 623
- api _ kg = None
CLI Examples :
. . code - bloc... | with _IpmiCommand ( ** kwargs ) as s :
return s . set_user_name ( uid , name ) |
def _x_reduced ( self , x , y , n_sersic , r_eff , center_x , center_y ) :
"""coordinate transform to normalized radius
: param x :
: param y :
: param center _ x :
: param center _ y :
: return :""" | x_ = x - center_x
y_ = y - center_y
r = np . sqrt ( x_ ** 2 + y_ ** 2 )
if isinstance ( r , int ) or isinstance ( r , float ) :
r = max ( self . _s , r )
else :
r [ r < self . _s ] = self . _s
x_reduced = ( r / r_eff ) ** ( 1. / n_sersic )
return x_reduced |
def set_scale ( self , scale ) :
"""Set the device scale register .
Device must be in standby before calling this function
@ param scale : scale factor
@ return : No return value""" | register = self . MMA8452Q_Register [ 'XYZ_DATA_CFG' ]
self . board . i2c_read_request ( self . address , register , 1 , Constants . I2C_READ | Constants . I2C_END_TX_MASK , self . data_val , Constants . CB_TYPE_DIRECT )
config_reg = self . wait_for_read_result ( )
config_reg = config_reg [ self . data_start ]
config_r... |
def get_and_alter ( self , function ) :
"""Alters the currently stored reference by applying a function on it on and gets the old value .
: param function : ( Function ) , A stateful serializable object which represents the Function defined on
server side .
This object must have a serializable Function counte... | check_not_none ( function , "function can't be None" )
return self . _encode_invoke ( atomic_reference_get_and_alter_codec , function = self . _to_data ( function ) ) |
def get_relation_cols ( self ) :
"""Returns the filter active FilterRelation cols""" | retlst = [ ]
for flt , value in zip ( self . filters , self . values ) :
if isinstance ( flt , FilterRelation ) and value :
retlst . append ( flt . column_name )
return retlst |
async def ModelSet ( self , config ) :
'''config : typing . Mapping [ str , typing . Any ]
Returns - > None''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'Client' , request = 'ModelSet' , version = 2 , params = _params )
_params [ 'config' ] = config
reply = await self . rpc ( msg )
return reply |
def _set_random_data ( self ) :
"""sets page data from random request""" | rdata = self . _load_response ( 'random' )
rdata = rdata [ 'query' ] [ 'random' ] [ 0 ]
pageid = rdata . get ( 'id' )
title = rdata . get ( 'title' )
self . data . update ( { 'pageid' : pageid , 'title' : title } ) |
def queue ( self , queue , message , params = { } , uids = [ ] ) :
"""Queue a job in Rhumba""" | d = { 'id' : uuid . uuid1 ( ) . get_hex ( ) , 'version' : 1 , 'message' : message , 'params' : params }
if uids :
for uid in uids :
self . _get_client ( ) . lpush ( 'rhumba.dq.%s.%s' % ( uid , queue ) , json . dumps ( d ) )
else :
self . _get_client ( ) . lpush ( 'rhumba.q.%s' % queue , json . dumps ( d... |
def string_to_file ( path , input ) :
"""Write a file from a given string .""" | mkdir_p ( os . path . dirname ( path ) )
with codecs . open ( path , "w+" , "UTF-8" ) as file :
file . write ( input ) |
def field_mask ( original , modified ) :
"""Create a field mask by comparing two messages .
Args :
original ( ~ google . protobuf . message . Message ) : the original message .
If set to None , this field will be interpretted as an empty
message .
modified ( ~ google . protobuf . message . Message ) : the... | if original is None and modified is None :
return field_mask_pb2 . FieldMask ( )
if original is None and modified is not None :
original = copy . deepcopy ( modified )
original . Clear ( )
if modified is None and original is not None :
modified = copy . deepcopy ( original )
modified . Clear ( )
if ... |
def get ( args ) :
"""Get an Aegea configuration parameter by name""" | from . import config
for key in args . key . split ( "." ) :
config = getattr ( config , key )
print ( json . dumps ( config ) ) |
def stop ( self ) :
"""Stop the interface
: rtype : None""" | self . debug ( "()" )
try :
self . unjoin ( )
time . sleep ( 2 )
except :
self . exception ( "Failed to leave audience" )
super ( SensorClient , self ) . stop ( ) |
def register_workflow ( connection , domain , workflow ) :
"""Register a workflow type .
Return False if this workflow already registered ( and True otherwise ) .""" | args = get_workflow_registration_parameter ( workflow )
try :
connection . register_workflow_type ( domain = domain , ** args )
except ClientError as err :
if err . response [ 'Error' ] [ 'Code' ] == 'TypeAlreadyExistsFault' :
return False
# Ignore this error
raise
return True |
def execute_single ( self , request ) :
"""Builds , sends and handles the response to a single request , returning
the response .""" | if self . logger :
self . logger . debug ( 'Executing single request: %s' , request )
self . removeRequest ( request )
body = remoting . encode ( self . getAMFRequest ( [ request ] ) , strict = self . strict )
http_request = urllib2 . Request ( self . _root_url , body . getvalue ( ) , self . _get_execute_headers ( ... |
def setSegmentsMap ( self , segmentNameCount , lineMap ) :
"""Set the segments map
: param segmentNameCount : a dict with the segment name and the total number of segments with this name
: param lineMap : a list with the concerned segment . If the PV1 segment is the third if the HL7 message ,
the element in t... | self . segmentNameCount = segmentNameCount
self . lineMap = lineMap
# Build an alias map for simplicity in get
# PID is an alias of PID [ 1 ] if only 1 PID segment is present
for segName in segmentNameCount . keys ( ) :
if segmentNameCount [ segName ] == 1 :
self . aliasSegmentName [ segName ] = segName + "... |
def _elements_to_dict ( data , position , obj_end , opts , result = None ) :
"""Decode a BSON document into result .""" | if result is None :
result = opts . document_class ( )
end = obj_end - 1
while position < end :
key , value , position = _element_to_dict ( data , position , obj_end , opts )
result [ key ] = value
if position != obj_end :
raise InvalidBSON ( 'bad object or element length' )
return result |
def auth_user_ldap ( uname , pwd ) :
"""Attempts to bind using the uname / pwd combo passed in .
If that works , returns true . Otherwise returns false .""" | if not uname or not pwd :
logging . error ( "Username or password not supplied" )
return False
ld = ldap . initialize ( LDAP_URL )
if LDAP_VERSION_3 :
ld . set_option ( ldap . VERSION3 , 1 )
ld . start_tls_s ( )
udn = ld . search_s ( LDAP_SEARCH_BASE , ldap . SCOPE_ONELEVEL , '(%s=%s)' % ( LDAP_UNAME_ATTR ,... |
def write_gzipped_text ( basefilename : str , text : str ) -> None :
"""Writes text to a file compressed with ` ` gzip ` ` ( a ` ` . gz ` ` file ) .
The filename is used directly for the " inner " file and the extension
` ` . gz ` ` is appended to the " outer " ( zipped ) file ' s name .
This function exists ... | # noqa
zipfilename = basefilename + '.gz'
compresslevel = 9
mtime = 0
with open ( zipfilename , 'wb' ) as f :
with gzip . GzipFile ( basefilename , 'wb' , compresslevel , f , mtime ) as gz :
with io . TextIOWrapper ( gz ) as tw :
tw . write ( text ) |
def to_dict ( self ) :
"""Convert Term into raw dictionary data .""" | return { 'definition' : self . definition , 'id' : self . term_id , 'image' : self . image . to_dict ( ) , 'rank' : self . rank , 'term' : self . term } |
def __locate ( self ) :
"""Find the schema locally .""" | if self . ns [ 1 ] != self . schema . tns [ 1 ] :
return self . schema . locate ( self . ns ) |
def agent_entities ( self ) :
"""Returns a list of intent json objects""" | endpoint = self . _entity_uri ( )
entities = self . _get ( endpoint )
# should be list of dicts
if isinstance ( entities , dict ) : # error : entities = { status : { error } }
raise Exception ( entities [ "status" ] )
return [ Entity ( entity_json = i ) for i in entities if isinstance ( i , dict ) ] |
def define ( self , names , ** kwargs ) :
"""Define variables within the namespace .
This is similar to : meth : ` . Problem . define ` except that names must be
given as an iterable . This method accepts the same keyword arguments
as : meth : ` . Problem . define ` .""" | define_kwargs = dict ( self . _define_kwargs )
define_kwargs . update ( kwargs )
self . _problem . define ( * ( ( self , name ) for name in names ) , ** define_kwargs ) |
def _hash ( number , alphabet ) :
"""Hashes ` number ` using the given ` alphabet ` sequence .""" | hashed = ''
len_alphabet = len ( alphabet )
while True :
hashed = alphabet [ number % len_alphabet ] + hashed
number //= len_alphabet
if not number :
return hashed |
def add_line ( self , line , source , * lineno ) :
"""Add a line to the result""" | self . result . append ( line , source , * lineno ) |
def merge_segments ( filename , scan , cleanup = True , sizelimit = 0 ) :
"""Merges cands / noise pkl files from multiple segments to single cands / noise file .
Expects segment cands pkls with have ( 1 ) state dict and ( 2 ) cands dict .
Writes tuple state dict and duple of numpy arrays
A single pkl written ... | workdir = os . path . dirname ( filename )
fileroot = os . path . basename ( filename )
candslist = glob . glob ( os . path . join ( workdir , 'cands_' + fileroot + '_sc' + str ( scan ) + 'seg*.pkl' ) )
noiselist = glob . glob ( os . path . join ( workdir , 'noise_' + fileroot + '_sc' + str ( scan ) + 'seg*.pkl' ) )
ca... |
def get_orders ( self , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # list - orders""" | response = self . _get ( 'v2' , 'orders' , params = params )
return self . _make_api_object ( response , Order ) |
def parseTree ( self , root , state : ParseState ) -> List [ Dict ] :
"""Parses the XML ast tree recursively to generate a JSON AST
which can be ingested by other scripts to generate Python
scripts .
Args :
root : The current root of the tree .
state : The current state of the tree defined by an object of... | if root . tag in self . AST_TAG_HANDLERS :
return self . AST_TAG_HANDLERS [ root . tag ] ( root , state )
elif root . tag in self . libRtns :
return self . process_libRtn ( root , state )
else :
prog = [ ]
for node in root :
prog += self . parseTree ( node , state )
return prog |
def add_port ( zone , port , permanent = True ) :
'''Allow specific ports in a zone .
. . versionadded : : 2015.8.0
CLI Example :
. . code - block : : bash
salt ' * ' firewalld . add _ port internal 443 / tcp''' | cmd = '--zone={0} --add-port={1}' . format ( zone , port )
if permanent :
cmd += ' --permanent'
return __firewall_cmd ( cmd ) |
def _wr_txt_nts ( self , fout_txt , desc2nts , objgowr , verbose ) :
"""Write grouped and sorted GO IDs to GOs .""" | with open ( fout_txt , 'w' ) as prt :
self . _prt_ver_n_key ( prt , verbose )
prt . write ( '\n\n' )
prt . write ( '# ----------------------------------------------------------------\n' )
prt . write ( '# - Sections and GO IDs\n' )
prt . write ( '# ---------------------------------------------------... |
def get_amqp_settings ( ) :
"""Return all settings in dict in following format : :
" submodule _ name " : {
" vhost " : VIRTUALHOST ,
" exchange " : EXCHANGE ,
" queues " : {
QUEUE _ NAME : ROUTING _ KEY ,
QUEUE _ NAME : ROUTING _ KEY
" in _ key " : INPUT _ KEY ,
" out _ key " : OUTPUT _ KEY""" | amqp_settings = { }
for vhost in filter ( lambda x : x . endswith ( "VIRTUALHOST" ) , globals ( ) . keys ( ) ) :
vhost = "RABBITMQ_" + vhost . split ( "_" ) [ 1 ]
queues = { globals ( ) [ vhost + "_INPUT_QUEUE" ] : globals ( ) [ vhost + "_INPUT_KEY" ] , globals ( ) [ vhost + "_OUTPUT_QUEUE" ] : globals ( ) [ vh... |
def _create_shade_data ( self , position_data = None , room_id = None ) :
"""Create a shade data object to be sent to the hub""" | base = { ATTR_SHADE : { ATTR_ID : self . id } }
if position_data :
base [ ATTR_SHADE ] [ ATTR_POSITION_DATA ] = position_data
if room_id :
base [ ATTR_SHADE ] [ ATTR_ROOM_ID ] = room_id
return base |
def state_in ( self , value ) :
"""Parse ranges .""" | value = [ val for val in Traverser ( value , self . groups ) ]
if not value or not value [ 0 ] :
for val in self . literals - set ( value ) :
return ( yield val )
yield value [ 0 ] |
def get_activity_laps ( self , activity_id ) :
"""Gets the laps from an activity .
http : / / strava . github . io / api / v3 / activities / # laps
: param activity _ id : The activity for which to fetch laps .
: type activity _ id : int
: return : An iterator of : class : ` stravalib . model . ActivityLaps... | result_fetcher = functools . partial ( self . protocol . get , '/activities/{id}/laps' , id = activity_id )
return BatchedResultsIterator ( entity = model . ActivityLap , bind_client = self , result_fetcher = result_fetcher ) |
def parse ( self , raise_parsing_errors = True ) :
"""Process the file content .
Usage : :
> > > plist _ file _ parser = PlistFileParser ( " standard . plist " )
> > > plist _ file _ parser . parse ( )
True
> > > plist _ file _ parser . elements . keys ( )
[ u ' Dictionary A ' , u ' Number A ' , u ' Arr... | LOGGER . debug ( "> Reading elements from: '{0}'." . format ( self . path ) )
element_tree_parser = ElementTree . iterparse ( self . path )
self . __parsing_errors = [ ]
for action , element in element_tree_parser :
unmarshal = self . __unserializers . get ( element . tag )
if unmarshal :
data = unmarsh... |
def write_summary ( summary : dict , cache_dir : str ) :
"""Write the ` summary ` JSON to ` cache _ dir ` .
Updated the accessed timestamp to now before writing .""" | # update the summary last - accessed timestamp
summary [ 'accessed' ] = time ( )
with open ( join ( cache_dir , 'summary.json' ) , 'w' ) as summary_file :
summary_file . write ( json . dumps ( summary , indent = 4 , sort_keys = True ) ) |
def snapshots ( self , space_id , environment_id , resource_id , resource_kind = 'entries' ) :
"""Provides access to snapshot management methods .
API reference : https : / / www . contentful . com / developers / docs / references / content - management - api / # / reference / snapshots
: return : : class : ` S... | return SnapshotsProxy ( self , space_id , environment_id , resource_id , resource_kind ) |
def sanity_check_net ( self , net ) :
"""Check that net is a valid LogicNet .""" | from . wire import Input , Output , Const
from . memory import _MemReadBase
# general sanity checks that apply to all operations
if not isinstance ( net , LogicNet ) :
raise PyrtlInternalError ( 'error, net must be of type LogicNet' )
if not isinstance ( net . args , tuple ) :
raise PyrtlInternalError ( 'error,... |
def atoms_string_from_file ( filename ) :
"""Reads atomic shells from file such as feff . inp or ATOMS file
The lines are arranged as follows :
x y z ipot Atom Symbol Distance Number
with distance being the shell radius and ipot an integer identifying
the potential used .
Args :
filename : File name con... | with zopen ( filename , "rt" ) as fobject :
f = fobject . readlines ( )
coords = 0
atoms_str = [ ]
for line in f :
if coords == 0 :
find_atoms = line . find ( "ATOMS" )
if find_atoms >= 0 :
coords = 1
if coords == 1 and not ( "END" in line ) :
... |
def _wrap_client_error ( e ) :
"""Wrap botocore ClientError exception into ServerlessRepoClientError .
: param e : botocore exception
: type e : ClientError
: return : S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError""" | error_code = e . response [ 'Error' ] [ 'Code' ]
message = e . response [ 'Error' ] [ 'Message' ]
if error_code == 'BadRequestException' :
if "Failed to copy S3 object. Access denied:" in message :
match = re . search ( 'bucket=(.+?), key=(.+?)$' , message )
if match :
return S3Permissio... |
def listar_por_nome ( self , nome ) :
"""Obtém um equipamento a partir do seu nome .
: param nome : Nome do equipamento .
: return : Dicionário com a seguinte estrutura :
{ ' equipamento ' : { ' id ' : < id _ equipamento > ,
' nome ' : < nome _ equipamento > ,
' id _ tipo _ equipamento ' : < id _ tipo _... | if nome == '' or nome is None :
raise InvalidParameterError ( u'O nome do equipamento não foi informado.' )
url = 'equipamento/nome/' + urllib . quote ( nome ) + '/'
code , xml = self . submit ( None , 'GET' , url )
return self . response ( code , xml ) |
def ParseRecord ( self , parser_mediator , key , structure ) :
"""Parses a record and produces a Bash history event .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
key ( str ) : name of the parsed structure .
structur... | if key != 'log_entry' :
raise errors . ParseError ( 'Unable to parse record, unknown structure: {0:s}' . format ( key ) )
event_data = BashHistoryEventData ( )
event_data . command = structure . command
date_time = dfdatetime_posix_time . PosixTime ( timestamp = structure . timestamp )
event = time_events . DateTim... |
def create_embeded_pkcs7_signature ( data , cert , key ) :
"""Creates an embeded ( " nodetached " ) pkcs7 signature .
This is equivalent to the output of : :
openssl smime - sign - signer cert - inkey key - outform DER - nodetach < data
: type data : bytes
: type cert : str
: type key : str""" | # noqa : E501
assert isinstance ( data , bytes )
assert isinstance ( cert , str )
try :
pkey = crypto . load_privatekey ( crypto . FILETYPE_PEM , key )
signcert = crypto . load_certificate ( crypto . FILETYPE_PEM , cert )
except crypto . Error as e :
raise exceptions . CorruptCertificate from e
bio_in = cry... |
def evaluate_model_single_recording ( model_file , recording ) :
"""Evaluate a model for a single recording .
Parameters
model _ file : string
Model file ( . tar )
recording :
The handwritten recording .""" | ( preprocessing_queue , feature_list , model , output_semantics ) = load_model ( model_file )
results = evaluate_model_single_recording_preloaded ( preprocessing_queue , feature_list , model , output_semantics , recording )
return results |
def parse_imports ( self , original_first_thunk , first_thunk , forwarder_chain ) :
"""Parse the imported symbols .
It will fill a list , which will be available as the dictionary
attribute " imports " . Its keys will be the DLL names and the values
all the symbols imported from that object .""" | imported_symbols = [ ]
# The following has been commented as a PE does not
# need to have the import data necessarily witin
# a section , it can keep it in gaps between sections
# or overlapping other data .
# imports _ section = self . get _ section _ by _ rva ( first _ thunk )
# if not imports _ section :
# raise PEF... |
def query ( self , parents = None ) :
"""Compose the query and generate SPARQL .""" | # TODO : benchmark single - query strategy
q = Select ( [ ] )
q = self . project ( q , parent = True )
q = self . filter ( q , parents = parents )
if self . parent is None :
subq = Select ( [ self . var ] )
subq = self . filter ( subq , parents = parents )
subq = subq . offset ( self . node . offset )
s... |
def do_mailfy ( self , query , ** kwargs ) :
"""Verifying a mailfy query in this platform .
This might be redefined in any class inheriting from Platform . The only
condition is that any of this should return an equivalent array .
Args :
query : The element to be searched .
Return :
A list of elements t... | if self . check_mailfy ( query , kwargs ) :
expandedEntities = general . expandEntitiesFromEmail ( query )
r = { "type" : "i3visio.profile" , "value" : self . platformName + " - " + query , "attributes" : expandedEntities + [ { "type" : "i3visio.platform" , "value" : self . platformName , "attributes" : [ ] } ]... |
def _ln_rnn ( x , gamma , beta ) :
r"""Applies layer normalization .
Normalizes the last dimension of the tensor ` x ` .
Args :
x : A ` Tensor ` .
gamma : A constant ` Tensor ` . Scale parameter . Default is 1.
beta : A constant ` Tensor ` . Offset parameter . Default is 0.
Returns :
A ` Tensor ` with... | # calc layer mean , variance for final axis
mean , variance = tf . nn . moments ( x , axes = [ len ( x . get_shape ( ) ) - 1 ] , keep_dims = True )
# apply layer normalization
x = ( x - mean ) / tf . sqrt ( variance + tf . sg_eps )
# apply parameter
return gamma * x + beta |
def run ( self , args ) :
"""Erases the device connected to the J - Link .
Args :
self ( EraseCommand ) : the ` ` EraseCommand ` ` instance
args ( Namespace ) : the arguments passed on the command - line
Returns :
` ` None ` `""" | jlink = self . create_jlink ( args )
erased = jlink . erase ( )
print ( 'Bytes Erased: %d' % erased ) |
def format_pkg_list ( packages , versions_as_list , attr ) :
'''Formats packages according to parameters for list _ pkgs .''' | ret = copy . deepcopy ( packages )
if attr :
requested_attr = { 'epoch' , 'version' , 'release' , 'arch' , 'install_date' , 'install_date_time_t' }
if attr != 'all' :
requested_attr &= set ( attr + [ 'version' ] )
for name in ret :
versions = [ ]
for all_attr in ret [ name ] :
... |
def write ( self , addr , data ) :
'''Write to dummy memory
Parameters
addr : int
The register address .
data : list , tuple
Data ( byte array ) to be written .
Returns
nothing''' | logger . debug ( "Dummy SiTransferLayer.write addr: %s data: %s" % ( hex ( addr ) , data ) )
for curr_addr , d in enumerate ( data , start = addr ) :
self . mem [ curr_addr ] = array . array ( 'B' , [ d ] ) [ 0 ] |
def make_path_unique ( path , counts , new ) :
"""Given a path , a list of existing paths and counts for each of the
existing paths .""" | added = False
while any ( path == c [ : i ] for c in counts for i in range ( 1 , len ( c ) + 1 ) ) :
count = counts [ path ]
counts [ path ] += 1
if ( not new and len ( path ) > 1 ) or added :
path = path [ : - 1 ]
else :
added = True
path = path + ( int_to_roman ( count ) , )
if len... |
def render_unicode ( self , * args , ** data ) :
"""Render the output of this template as a unicode object .""" | return runtime . _render ( self , self . callable_ , args , data , as_unicode = True ) |
def geometry_within_radius ( geometry , center , radius ) :
"""To valid whether point or linestring or polygon is inside a radius around a center
Keyword arguments :
geometry - - point / linstring / polygon geojson object
center - - point geojson object
radius - - radius
if ( geometry inside radius ) retu... | if geometry [ 'type' ] == 'Point' :
return point_distance ( geometry , center ) <= radius
elif geometry [ 'type' ] == 'LineString' or geometry [ 'type' ] == 'Polygon' :
point = { }
# it ' s enough to check the exterior ring of the Polygon
coordinates = geometry [ 'coordinates' ] [ 0 ] if geometry [ 'typ... |
def vecs_to_datmesh ( x , y ) :
"""Converts input arguments x and y to a 2d meshgrid ,
suitable for calling Means , Covariances and Realizations .""" | x , y = meshgrid ( x , y )
out = zeros ( x . shape + ( 2 , ) , dtype = float )
out [ : , : , 0 ] = x
out [ : , : , 1 ] = y
return out |
def dict_copy ( func ) :
"copy dict args , to avoid modifying caller ' s copy" | def proxy ( * args , ** kwargs ) :
new_args = [ ]
new_kwargs = { }
for var in kwargs :
if isinstance ( kwargs [ var ] , dict ) :
new_kwargs [ var ] = dict ( kwargs [ var ] )
else :
new_kwargs [ var ] = kwargs [ var ]
for arg in args :
if isinstance ( arg ,... |
def decorator ( f ) :
"""Creates a paramatric decorator from a function . The resulting decorator
will optionally take keyword arguments .""" | @ functools . wraps ( f )
def decoratored_function ( * args , ** kwargs ) :
if args and len ( args ) == 1 :
return f ( * args , ** kwargs )
if args :
raise TypeError ( "This decorator only accepts extra keyword arguments." )
return lambda g : f ( g , ** kwargs )
return decoratored_function |
def write_perseus ( f , df ) :
"""Export a dataframe to Perseus ; recreating the format
: param f :
: param df :
: return :""" | # # # Generate the Perseus like type index
FIELD_TYPE_MAP = { 'Amino acid' : 'C' , 'Charge' : 'C' , 'Reverse' : 'C' , 'Potential contaminant' : 'C' , 'Multiplicity' : 'C' , 'Localization prob' : 'N' , 'PEP' : 'N' , 'Score' : 'N' , 'Delta score' : 'N' , 'Score for localization' : 'N' , 'Mass error [ppm]' : 'N' , 'Intens... |
def _pb_from_query ( query ) :
"""Convert a Query instance to the corresponding protobuf .
: type query : : class : ` Query `
: param query : The source query .
: rtype : : class : ` . query _ pb2 . Query `
: returns : A protobuf that can be sent to the protobuf API . N . b . that
it does not contain " in... | pb = query_pb2 . Query ( )
for projection_name in query . projection :
pb . projection . add ( ) . property . name = projection_name
if query . kind :
pb . kind . add ( ) . name = query . kind
composite_filter = pb . filter . composite_filter
composite_filter . op = query_pb2 . CompositeFilter . AND
if query . ... |
def step_context ( self ) :
"""Access the step _ context
: returns : twilio . rest . studio . v1 . flow . engagement . step . step _ context . StepContextList
: rtype : twilio . rest . studio . v1 . flow . engagement . step . step _ context . StepContextList""" | if self . _step_context is None :
self . _step_context = StepContextList ( self . _version , flow_sid = self . _solution [ 'flow_sid' ] , engagement_sid = self . _solution [ 'engagement_sid' ] , step_sid = self . _solution [ 'sid' ] , )
return self . _step_context |
def set_creds ( self , newCreds ) :
"""Manually update the current creds .""" | self . creds = newCreds
self . on_creds_changed ( newCreds )
return self |
def commit_pushdb ( self , coordinates , postscript = None ) :
"""Commit changes to the pushdb with a message containing the provided coordinates .""" | self . scm . commit ( 'pants build committing publish data for push of {coordinates}' '{postscript}' . format ( coordinates = coordinates , postscript = postscript or '' ) , verify = self . get_options ( ) . verify_commit ) |
def make_node ( cls , id_ , params , lineno ) :
"""This will return an AST node for a function / procedure call .""" | assert isinstance ( params , SymbolARGLIST )
entry = gl . SYMBOL_TABLE . access_func ( id_ , lineno )
if entry is None : # A syntax / semantic error
return None
if entry . callable is False : # Is it NOT callable ?
if entry . type_ != Type . string :
errmsg . syntax_error_not_array_nor_func ( lineno , i... |
def Max ( left : vertex_constructor_param_types , right : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex :
"""Finds the maximum between two vertices
: param left : one of the vertices to find the maximum of
: param right : one of the vertices to find the maximum of""" | return Double ( context . jvm_view ( ) . MaxVertex , label , cast_to_double_vertex ( left ) , cast_to_double_vertex ( right ) ) |
def identifySQLError ( self , sql , args , e ) :
"""Identify an appropriate SQL error object for the given message for the
supported versions of sqlite .
@ return : an SQLError""" | message = e . args [ 0 ]
if message . startswith ( "table" ) and message . endswith ( "already exists" ) :
return errors . TableAlreadyExists ( sql , args , e )
return errors . SQLError ( sql , args , e ) |
def evaluateplanarPotentials ( Pot , R , phi = None , t = 0. , dR = 0 , dphi = 0 ) :
"""NAME :
evaluateplanarPotentials
PURPOSE :
evaluate a ( list of ) planarPotential instance ( s )
INPUT :
Pot - ( list of ) planarPotential instance ( s )
R - Cylindrical radius ( can be Quantity )
phi = azimuth ( op... | return _evaluateplanarPotentials ( Pot , R , phi = phi , t = t , dR = dR , dphi = dphi ) |
def zscale ( image , nsamples = 1000 , contrast = 0.25 ) :
"""Implement IRAF zscale algorithm
nsamples = 1000 and contrast = 0.25 are the IRAF display task defaults
image is a 2 - d numpy array
returns ( z1 , z2)""" | # Sample the image
samples = zsc_sample ( image , nsamples )
return zscale_samples ( samples , contrast = contrast ) |
def timeseries ( self ) :
"""Feed - in time series of generator
It returns the actual time series used in power flow analysis . If
: attr : ` _ timeseries ` is not : obj : ` None ` , it is returned . Otherwise ,
: meth : ` timeseries ` looks for generation and curtailment time series
of the according type o... | if self . _timeseries is None : # get time series for active power depending on if they are
# differentiated by weather cell ID or not
if isinstance ( self . grid . network . timeseries . generation_fluctuating . columns , pd . MultiIndex ) :
if self . weather_cell_id :
try :
tim... |
def alpha_cased ( text , lower = False ) :
"""Filter text to just letters and homogenize case .
: param str text : what to filter and homogenize .
: param bool lower : whether to convert to lowercase ; default uppercase .
: return str : input filtered to just letters , with homogenized case .""" | text = "" . join ( filter ( lambda c : c . isalpha ( ) or c == GENERIC_PROTOCOL_KEY , text ) )
return text . lower ( ) if lower else text . upper ( ) |
def chunk_count ( swatch ) :
"""return the number of byte - chunks in a swatch object
this recursively walks the swatch list , returning 1 for a single color &
returns 2 for each folder plus 1 for each color it contains""" | if type ( swatch ) is dict :
if 'data' in swatch :
return 1
if 'swatches' in swatch :
return 2 + len ( swatch [ 'swatches' ] )
else :
return sum ( map ( chunk_count , swatch ) ) |
def rel_path_to ( self , dest ) :
"""Builds a relative path leading from this one to the given ` dest ` .
Note that these paths might be both relative , in which case they ' ll be
assumed to start from the same directory .""" | dest = self . __class__ ( dest )
orig_list = self . norm_case ( ) . _components ( )
dest_list = dest . _components ( )
i = - 1
for i , ( orig_part , dest_part ) in enumerate ( zip ( orig_list , dest_list ) ) :
if orig_part != self . _normcase ( dest_part ) :
up = [ '..' ] * ( len ( orig_list ) - i )
... |
def get_context_data ( self , ** kwargs ) :
"""Hook for adding arguments to the context .""" | context = { 'obj' : self . object }
if 'queryset' in kwargs :
context [ 'conf_msg' ] = self . get_confirmation_message ( kwargs [ 'queryset' ] )
context . update ( kwargs )
return context |
def neighbor ( self , ** kwargs ) :
"""Experimental neighbor method .
Args :
ip _ addr ( str ) : IP Address of BGP neighbor .
remote _ as ( str ) : Remote ASN of BGP neighbor .
rbridge _ id ( str ) : The rbridge ID of the device on which BGP will be
configured in a VCS fabric .
afis ( list ) : A list of... | ip_addr = ip_interface ( unicode ( kwargs . pop ( 'ip_addr' ) ) )
rbridge_id = kwargs . pop ( 'rbridge_id' , '1' )
delete = kwargs . pop ( 'delete' , False )
callback = kwargs . pop ( 'callback' , self . _callback )
remote_as = kwargs . pop ( 'remote_as' , None )
get_config = kwargs . pop ( 'get' , False )
if not get_c... |
def flush ( self ) :
"""Remove the whole storage""" | annotation = self . get_annotation ( )
if annotation . get ( ATTACHMENTS_STORAGE ) is not None :
del annotation [ ATTACHMENTS_STORAGE ] |
def match ( Class , path , pattern , flags = re . I , sortkey = None , ext = None ) :
"""for a given path and regexp pattern , return the files that match""" | return sorted ( [ Class ( fn = fn ) for fn in rglob ( path , f"*{ext or ''}" ) if re . search ( pattern , os . path . basename ( fn ) , flags = flags ) is not None and os . path . basename ( fn ) [ 0 ] != '~' # omit temp files
] , key = sortkey , ) |
def interface_list ( env , securitygroup_id , sortby ) :
"""List interfaces associated with security groups .""" | mgr = SoftLayer . NetworkManager ( env . client )
table = formatting . Table ( COLUMNS )
table . sortby = sortby
mask = ( '''networkComponentBindings[
networkComponentId,
networkComponent[
id,
port,
guest[
id,
... |
def minimum_sys ( cls , inherit_path ) :
"""Return the minimum sys necessary to run this interpreter , a la python - S .
: returns : ( sys . path , sys . path _ importer _ cache , sys . modules ) tuple of a
bare python installation .""" | site_libs = set ( cls . site_libs ( ) )
for site_lib in site_libs :
TRACER . log ( 'Found site-library: %s' % site_lib )
for extras_path in cls . _extras_paths ( ) :
TRACER . log ( 'Found site extra: %s' % extras_path )
site_libs . add ( extras_path )
site_libs = set ( os . path . normpath ( path ) for path... |
def _to_edges ( self , tokens ) :
"""This is an iterator that returns the nodes of our graph :
" This is a test " - > " None This " " This is " " is a " " a test " " test None "
Each is annotated with a boolean that tracks whether whitespace was
found between the two tokens .""" | # prepend self . order Nones
chain = self . _end_context + tokens + self . _end_context
has_space = False
context = [ ]
for i in xrange ( len ( chain ) ) :
context . append ( chain [ i ] )
if len ( context ) == self . order :
if chain [ i ] == self . SPACE_TOKEN_ID :
context . pop ( )
... |
def envelope ( ** kwargs ) :
"""Create OAI - PMH envelope for response .""" | e_oaipmh = Element ( etree . QName ( NS_OAIPMH , 'OAI-PMH' ) , nsmap = NSMAP )
e_oaipmh . set ( etree . QName ( NS_XSI , 'schemaLocation' ) , '{0} {1}' . format ( NS_OAIPMH , NS_OAIPMH_XSD ) )
e_tree = ElementTree ( element = e_oaipmh )
if current_app . config [ 'OAISERVER_XSL_URL' ] :
e_oaipmh . addprevious ( etre... |
def _message_to_payload ( cls , message ) :
'''Returns a Python object or a ProtocolError .''' | try :
return json . loads ( message . decode ( ) )
except UnicodeDecodeError :
message = 'messages must be encoded in UTF-8'
except json . JSONDecodeError :
message = 'invalid JSON'
raise cls . _error ( cls . PARSE_ERROR , message , True , None ) |
def form_invalid ( self , form ) :
'''Builds the JSON for the errors''' | response = { self . errors_key : { } }
response [ self . non_field_errors_key ] = form . non_field_errors ( )
response . update ( self . get_hidden_fields_errors ( form ) )
for field in form . visible_fields ( ) :
if field . errors :
response [ self . errors_key ] [ field . html_name ] = self . _get_field_e... |
def main ( ) :
parser = getparser ( )
args = parser . parse_args ( )
fn = args . fn
sitename = args . sitename
# User - specified output extent
# Note : not checked , untested
if args . extent is not None :
extent = ( args . extent ) . split ( )
else :
extent = ( geolib .... | # Saturation Correction Flag
# These are 0 to 5 , not _ saturated inconsequential applicable not _ computed not _ applicable
sat_corr_flg = f . get ( 'Data_40HZ/Quality/sat_corr_flg' ) [ mask ]
# valid _ idx * = ( sat _ corr _ flg < 2)
# Correction to elevation for saturated waveforms
# Notes suggest this might not be ... |
def _log_band_edge_information ( bs , edge_data ) :
"""Log data about the valence band maximum or conduction band minimum .
Args :
bs ( : obj : ` ~ pymatgen . electronic _ structure . bandstructure . BandStructureSymmLine ` ) :
The band structure .
edge _ data ( dict ) : The : obj : ` dict ` from ` ` bs . g... | if bs . is_spin_polarized :
spins = edge_data [ 'band_index' ] . keys ( )
b_indices = [ ', ' . join ( [ str ( i + 1 ) for i in edge_data [ 'band_index' ] [ spin ] ] ) + '({})' . format ( spin . name . capitalize ( ) ) for spin in spins ]
b_indices = ', ' . join ( b_indices )
else :
b_indices = ', ' . jo... |
def lock_instance ( cls , instance_or_pk , read = False ) :
"""Return a locked model instance in ` ` db . session ` ` .
: param instance _ or _ pk : An instance of this model class , or a
primary key . A composite primary key can be passed as a
tuple .
: param read : If ` True ` , a reading lock is obtained... | mapper = inspect ( cls )
pk_attrs = [ mapper . get_property_by_column ( c ) . class_attribute for c in mapper . primary_key ]
pk_values = cls . get_pk_values ( instance_or_pk )
clause = and_ ( * [ attr == value for attr , value in zip ( pk_attrs , pk_values ) ] )
return cls . query . filter ( clause ) . with_for_update... |
def validation_curve ( model , X , y , param_name , param_range , ax = None , logx = False , groups = None , cv = None , scoring = None , n_jobs = 1 , pre_dispatch = "all" , ** kwargs ) :
"""Displays a validation curve for the specified param and values , plotting
both the train and cross - validated test scores ... | # Initialize the visualizer
oz = ValidationCurve ( model , param_name , param_range , ax = ax , logx = logx , groups = groups , cv = cv , scoring = scoring , n_jobs = n_jobs , pre_dispatch = pre_dispatch )
# Fit and poof the visualizer
oz . fit ( X , y )
oz . poof ( ** kwargs )
return oz . ax |
def decode_aes256_base64_auto ( data , encryption_key ) :
"""Guesses AES cipher ( EBC or CBD ) from the length of the base64 encoded data .""" | assert isinstance ( data , bytes )
length = len ( data )
if length == 0 :
return b''
elif data [ 0 ] == b'!' [ 0 ] :
return decode_aes256_cbc_base64 ( data , encryption_key )
else :
return decode_aes256_ecb_base64 ( data , encryption_key ) |
def callback ( self , request , ** kwargs ) :
"""Called from the Service when the user accept to activate it
the url to go back after the external service call
: param request : contains the current session
: param kwargs : keyword args
: type request : dict
: type kwargs : dict
: rtype : string""" | code = request . GET . get ( 'code' , '' )
redirect_uri = '%s://%s%s' % ( request . scheme , request . get_host ( ) , reverse ( "reddit_callback" ) )
reddit = RedditApi ( client_id = self . consumer_key , client_secret = self . consumer_secret , redirect_uri = redirect_uri , user_agent = self . user_agent )
token = red... |
def output ( self , stream , disabletransferencoding = None ) :
"""Set output stream and send response immediately""" | if self . _sendHeaders :
raise HttpProtocolException ( 'Cannot modify response, headers already sent' )
self . outputstream = stream
try :
content_length = len ( stream )
except Exception :
pass
else :
self . header ( b'Content-Length' , str ( content_length ) . encode ( 'ascii' ) )
if disabletransferen... |
def sync_hooks ( user_id , repositories ) :
"""Sync repository hooks for a user .""" | from . api import GitHubAPI
try : # Sync hooks
gh = GitHubAPI ( user_id = user_id )
for repo_id in repositories :
try :
with db . session . begin_nested ( ) :
gh . sync_repo_hook ( repo_id )
# We commit per repository , because while the task is running
... |
def checkIfHashIsCracked ( hash = None , api_key = None ) :
'''Method that checks if the given hash is stored in the md5crack . com website .
: param hash : hash to verify .
: param api _ key : api _ key to be used in md5crack . com . If not provided , the API key will be searched in the config _ api _ keys . p... | # This is for i3visio
if api_key == None : # api _ key = raw _ input ( " Insert the API KEY here : \ t " )
allKeys = config_api_keys . returnListOfAPIKeys ( )
try :
api_key_data = allKeys [ "md5crack_com" ]
api_key = api_key_data [ "api_key" ]
except : # API _ Key not found
return { ... |
def _generate_doc ( ret ) :
'''Create a object that will be saved into the database based on
options .''' | # Create a copy of the object that we will return .
retc = ret . copy ( )
# Set the ID of the document to be the JID .
retc [ "_id" ] = ret [ "jid" ]
# Add a timestamp field to the document
retc [ "timestamp" ] = time . time ( )
return retc |
def write_result ( self , result ) :
"""Send back the result of this call .
Only one of this and ` write _ exc _ info ` may be called .
: param result :
Return value of the call""" | assert not self . finished , "Already sent a response"
if not self . result . thrift_spec :
self . finished = True
return
spec = self . result . thrift_spec [ 0 ]
if result is not None :
assert spec , "Tried to return a result for a void method."
setattr ( self . result , spec [ 2 ] , result )
self . fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.