signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def removeContinuousSet ( self , continuousSet ) :
"""Removes the specified continuousSet from this repository .""" | q = models . ContinuousSet . delete ( ) . where ( models . ContinuousSet . id == continuousSet . getId ( ) )
q . execute ( ) |
def init_engine ( self , get_loader ) :
"""Construct and store a PipelineEngine from loader .
If get _ loader is None , constructs an ExplodingPipelineEngine""" | if get_loader is not None :
self . engine = SimplePipelineEngine ( get_loader , self . asset_finder , self . default_pipeline_domain ( self . trading_calendar ) , )
else :
self . engine = ExplodingPipelineEngine ( ) |
def fastqc ( self , file , output_dir ) :
"""Create command to run fastqc on a FASTQ file
: param str file : Path to file with sequencing reads
: param str output _ dir : Path to folder in which to place output
: return str : Command with which to run fastqc""" | # You can find the fastqc help with fastqc - - help
try :
pm = self . pm
except AttributeError : # Do nothing , this is just for path construction .
pass
else :
if not os . path . isabs ( output_dir ) and pm is not None :
output_dir = os . path . join ( pm . outfolder , output_dir )
self . make_sure... |
def do_bp ( self , arg ) :
"""[ ~ process ] bp < address > - set a code breakpoint""" | pid = self . get_process_id_from_prefix ( )
if not self . debug . is_debugee ( pid ) :
raise CmdError ( "target process is not being debugged" )
process = self . get_process ( pid )
token_list = self . split_tokens ( arg , 1 , 1 )
try :
address = self . input_address ( token_list [ 0 ] , pid )
deferred = Fa... |
def get ( self , ids , ** kwargs ) :
"""Method to get interfaces by their ids .
: param ids : List containing identifiers of interfaces .
: return : Dict containing interfaces .""" | url = build_uri_with_ids ( 'api/v3/interface/%s/' , ids )
return super ( ApiInterfaceRequest , self ) . get ( self . prepare_url ( url , kwargs ) ) |
def update_parameters ( parameters , grads , learning_rate = 1.2 ) :
"""Updates parameters using the gradient descent update rule given above
Arguments :
parameters - - python dictionary containing your parameters
grads - - python dictionary containing your gradients
Returns :
parameters - - python dictio... | # Retrieve each parameter from the dictionary " parameters "
W1 = parameters [ "W1" ]
b1 = parameters [ "b1" ]
W2 = parameters [ "W2" ]
b2 = parameters [ "b2" ]
# Retrieve each gradient from the dictionary " grads "
dW1 = grads [ "dW1" ]
db1 = grads [ "db1" ]
dW2 = grads [ "dW2" ]
db2 = grads [ "db2" ]
# Update rule fo... |
def create ( self , title , description = None , private = False ) :
"""Create a new collection .
This requires the ' write _ collections ' scope .
: param title [ string ] : The title of the collection . ( Required . )
: param description [ string ] : The collection ’ s description . ( Optional . )
: param... | url = "/collections"
data = { "title" : title , "description" : description , "private" : private }
result = self . _post ( url , data = data )
return CollectionModel . parse ( result ) |
def get_course_video_ids_with_youtube_profile ( course_ids = None , offset = None , limit = None ) :
"""Returns a list that contains all the course ids and video ids with the youtube profile
Args :
course _ ids ( list ) : valid course ids
limit ( int ) : batch records limit
offset ( int ) : an offset for se... | course_videos = ( CourseVideo . objects . select_related ( 'video' ) . prefetch_related ( 'video__encoded_videos' , 'video__encoded_videos__profile' ) . filter ( video__encoded_videos__profile__profile_name = 'youtube' ) . order_by ( 'id' ) . distinct ( ) )
if course_ids :
course_videos = course_videos . filter ( c... |
def load_hvjs ( cls , logo = False , bokeh_logo = False , mpl_logo = False , plotly_logo = False , JS = True , message = 'HoloViewsJS successfully loaded.' ) :
"""Displays javascript and CSS to initialize HoloViews widgets .""" | import jinja2
# Evaluate load _ notebook . html template with widgetjs code
if JS :
widgetjs , widgetcss = Renderer . html_assets ( extras = False , backends = [ ] , script = True )
else :
widgetjs , widgetcss = '' , ''
# Add classic notebook MIME renderer
widgetjs += nb_mime_js
templateLoader = jinja2 . FileSy... |
def waiting_config_state ( self , timeout = 300 ) :
"""waiting while real state equal config state
Args :
timeout - specify how long , in seconds , a command can take before server times out .
return True if operation success otherwise False""" | t_start = time . time ( )
while not self . check_config_state ( ) :
if time . time ( ) - t_start > timeout :
return False
time . sleep ( 0.1 )
return True |
def output_deployment_diagnostics ( awsclient , deployment_id , log_group , start_time = None ) :
"""diagnostics
: param awsclient :
: param deployment _ id :""" | headline = False
for instance_id in _list_deployment_instances ( awsclient , deployment_id ) :
diagnostics = _get_deployment_instance_diagnostics ( awsclient , deployment_id , instance_id )
# if error _ code ! = ' Success ' :
if diagnostics is not None :
error_code , script_name , message , log_tail... |
def _op_to_matrix ( self , op : Optional [ ops . Operation ] , qubits : Tuple [ ops . Qid , ... ] ) -> Optional [ np . ndarray ] :
"""Determines the effect of an operation on the given qubits .
If the operation is a 1 - qubit operation on one of the given qubits ,
or a 2 - qubit operation on both of the given q... | q1 , q2 = qubits
matrix = protocols . unitary ( op , None )
if matrix is None :
return None
assert op is not None
if op . qubits == qubits :
return matrix
if op . qubits == ( q2 , q1 ) :
return MergeInteractions . _flip_kron_order ( matrix )
if op . qubits == ( q1 , ) :
return np . kron ( matrix , np . ... |
def get_state_id_for_port ( port ) :
"""This method returns the state ID of the state containing the given port
: param port : Port to check for containing state ID
: return : State ID of state containing port""" | parent = port . parent
from rafcon . gui . mygaphas . items . state import StateView
if isinstance ( parent , StateView ) :
return parent . model . state . state_id |
def _call_wrapper ( self , time , function , * args ) :
"""Fired by tk . after , gets the callback and either executes the function and cancels or repeats""" | # execute the function
function ( * args )
if function in self . _callback . keys ( ) :
repeat = self . _callback [ function ] [ 1 ]
if repeat : # setup the call back again and update the id
callback_id = self . tk . after ( time , self . _call_wrapper , time , function , * args )
self . _callba... |
def _terminate_process_iou ( self ) :
"""Terminate the IOU process if running""" | if self . _iou_process :
log . info ( 'Stopping IOU process for IOU VM "{}" PID={}' . format ( self . name , self . _iou_process . pid ) )
try :
self . _iou_process . terminate ( )
# Sometime the process can already be dead when we garbage collect
except ProcessLookupError :
pass
self . ... |
def download ( dataset_label = None , destination_dir = None , dry_run = False ) :
"""Download sample data by data label . Warning : function with side effect !
Labels can be listed by sample _ data . data _ urls . keys ( ) . Returns downloaded files .
: param dataset _ label : label of data . If it is set to N... | if destination_dir is None :
destination_dir = op . join ( dataset_path ( get_root = True ) , "medical" , "orig" )
destination_dir = op . expanduser ( destination_dir )
logger . info ( "destination dir: {}" . format ( destination_dir ) )
if dataset_label is None :
dataset_label = data_urls . keys ( )
if type ( ... |
def __parse_database_accessions ( ) :
'''Gets and parses file''' | filename = get_file ( 'database_accession.tsv' )
with io . open ( filename , 'r' , encoding = 'cp1252' ) as textfile :
next ( textfile )
for line in textfile :
tokens = line . strip ( ) . split ( '\t' )
chebi_id = int ( tokens [ 1 ] )
if chebi_id not in __DATABASE_ACCESSIONS :
... |
def is_condition_met ( self , hand , win_tile , melds , is_tsumo ) :
"""Three closed pon sets , the other sets need not to be closed
: param hand : list of hand ' s sets
: param win _ tile : 136 tiles format
: param melds : list Meld objects
: param is _ tsumo :
: return : true | false""" | win_tile //= 4
open_sets = [ x . tiles_34 for x in melds if x . opened ]
chi_sets = [ x for x in hand if ( is_chi ( x ) and win_tile in x and x not in open_sets ) ]
pon_sets = [ x for x in hand if is_pon ( x ) ]
closed_pon_sets = [ ]
for item in pon_sets :
if item in open_sets :
continue
# if we do the ... |
def _split_generators ( self , dl_manager ) :
"""Returns SplitGenerators .""" | url = _DL_URLS [ self . builder_config . name ]
data_dirs = dl_manager . download_and_extract ( url )
path_to_dataset = os . path . join ( data_dirs , tf . io . gfile . listdir ( data_dirs ) [ 0 ] )
train_a_path = os . path . join ( path_to_dataset , "trainA" )
train_b_path = os . path . join ( path_to_dataset , "train... |
def get_jwt_decrypt_keys ( self , jwt , ** kwargs ) :
"""Get decryption keys from this keyjar based on information carried
in a JWE . These keys should be usable to decrypt an encrypted JWT .
: param jwt : A cryptojwt . jwt . JWT instance
: param kwargs : Other key word arguments
: return : list of usable k... | try :
_key_type = jwe_alg2keytype ( jwt . headers [ 'alg' ] )
except KeyError :
_key_type = ''
try :
_kid = jwt . headers [ 'kid' ]
except KeyError :
logger . info ( 'Missing kid' )
_kid = ''
keys = self . get ( key_use = 'enc' , owner = '' , key_type = _key_type )
try :
_aud = kwargs [ 'aud' ]
... |
def _ParseAndValidateRecord ( self , parser_mediator , text_file_object ) :
"""Parses and validates an Opera global history record .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
text _ file _ object ( dfvfs . TextFile ... | try :
title = text_file_object . readline ( size = self . _MAXIMUM_LINE_SIZE )
url = text_file_object . readline ( size = self . _MAXIMUM_LINE_SIZE )
timestamp = text_file_object . readline ( size = self . _MAXIMUM_LINE_SIZE )
popularity_index = text_file_object . readline ( size = self . _MAXIMUM_LINE_... |
def get_queryset ( self ) :
'''This is overwritten in order to not exclude drafts
and pages submitted for moderation''' | request = self . request
# Allow pages to be filtered to a specific type
if 'type' not in request . GET :
model = Page
else :
model_name = request . GET [ 'type' ]
try :
model = resolve_model_string ( model_name )
except LookupError :
raise BadRequestError ( "type doesn't exist" )
if... |
def get_transport ( host , username , key ) :
"""Create a transport object
: param host : the hostname to connect to
: type host : str
: param username : SSH username
: type username : str
: param key : key object used for authentication
: type key : paramiko . RSAKey
: return : a transport object
:... | if host == shakedown . master_ip ( ) :
transport = paramiko . Transport ( host )
else :
transport_master = paramiko . Transport ( shakedown . master_ip ( ) )
transport_master = start_transport ( transport_master , username , key )
if not transport_master . is_authenticated ( ) :
print ( "error: ... |
def do_dock6_flexible ( self , ligand_path , force_rerun = False ) :
"""Dock a ligand to the protein .
Args :
ligand _ path ( str ) : Path to ligand ( mol2 format ) to dock to protein
force _ rerun ( bool ) : If method should be rerun even if output file exists""" | log . debug ( '{}: running DOCK6...' . format ( self . id ) )
ligand_name = os . path . basename ( ligand_path ) . split ( '.' ) [ 0 ]
in_name = op . join ( self . dock_dir , "{}_{}_flexdock.in" . format ( self . id , ligand_name ) )
out_name = op . join ( self . dock_dir , "{}_{}_flexdock.out" . format ( self . id , l... |
def _read_routes_c ( ipv6 = False ) :
"""Retrieve Windows routes through a GetIpForwardTable2 call .
This is not available on Windows XP !""" | af = socket . AF_INET6 if ipv6 else socket . AF_INET
sock_addr_name = 'Ipv6' if ipv6 else 'Ipv4'
sin_addr_name = 'sin6_addr' if ipv6 else 'sin_addr'
metric_name = 'ipv6_metric' if ipv6 else 'ipv4_metric'
ip_len = 16 if ipv6 else 4
if ipv6 :
lifaddr = in6_getifaddr ( )
routes = [ ]
def _extract_ip_netmask ( obj ) :
... |
def _getEngineVersionHash ( self ) :
"""Computes the SHA - 256 hash of the JSON version details for the latest installed version of UE4""" | versionDetails = self . _getEngineVersionDetails ( )
hash = hashlib . sha256 ( )
hash . update ( json . dumps ( versionDetails , sort_keys = True , indent = 0 ) . encode ( 'utf-8' ) )
return hash . hexdigest ( ) |
def zone ( self ) -> Optional [ str ] :
"""Zone the device is assigned to .""" | if self . _device_category == DC_BASEUNIT :
return None
return '{:02x}-{:02x}' . format ( self . _group_number , self . _unit_number ) |
def make_params ( key_parts : Sequence [ str ] , variable_parts : VariablePartsType ) -> Dict [ str , Union [ str , Tuple [ str ] ] ] :
"""Map keys to variables . This map URL - pattern variables to a URL related parts
: param key _ parts : A list of URL parts
: param variable _ parts : A linked - list ( ala ne... | # The unwrapped variable parts are in reverse order .
# Instead of reversing those we reverse the key parts
# and avoid the O ( n ) space required for reversing the vars
return dict ( zip ( reversed ( key_parts ) , _unwrap ( variable_parts ) ) ) |
def binary_average ( start : int , end : int ) -> str :
"""Calculates the average of all integers in a given range ( inclusive ) , rounds to the nearest
integer , and returns it in binary form . If the starting value is larger than the ending value ,
it returns - 1.
Args :
start ( int ) : The starting value... | if start > end :
return - 1
total = sum ( range ( start , end + 1 ) )
avg = round ( total / ( end - start + 1 ) )
return bin ( avg ) |
def load_from_args ( args ) :
"""Given parsed commandline arguments , returns a list of ReadSource objects""" | if not args . reads :
return None
if args . read_source_name :
read_source_names = util . expand ( args . read_source_name , 'read_source_name' , 'read source' , len ( args . reads ) )
else :
read_source_names = util . drop_prefix ( args . reads )
filters = [ ]
for ( name , info ) in READ_FILTERS . items ( ... |
def _remaining_points ( hands ) :
''': param list hands : hands for which to compute the remaining points
: return : a list indicating the amount of points
remaining in each of the input hands''' | points = [ ]
for hand in hands :
points . append ( sum ( d . first + d . second for d in hand ) )
return points |
def process_utterance_online ( self , utterance , frame_size = 400 , hop_size = 160 , chunk_size = 1 , buffer_size = 5760000 , corpus = None ) :
"""Process the utterance in * * online * * mode , chunk by chunk .
The processed chunks are yielded one after another .
Args :
utterance ( Utterance ) : The utteranc... | return self . process_track_online ( utterance . track , frame_size = frame_size , hop_size = hop_size , start = utterance . start , end = utterance . end , utterance = utterance , corpus = corpus , chunk_size = chunk_size , buffer_size = buffer_size ) |
def lhs ( n , samples = None , criterion = None , iterations = None ) :
"""Generate a latin - hypercube design
Parameters
n : int
The number of factors to generate samples for
Optional
samples : int
The number of samples to generate for each factor ( Default : n )
criterion : str
Allowable values ar... | H = None
if samples is None :
samples = n
if criterion is not None :
assert criterion . lower ( ) in ( 'center' , 'c' , 'maximin' , 'm' , 'centermaximin' , 'cm' , 'correlation' , 'corr' ) , 'Invalid value for "criterion": {}' . format ( criterion )
else :
H = _lhsclassic ( n , samples )
if criterion is None... |
def download_url ( url , destination ) :
"""Download an external URL to the destination""" | from settings import VALID_IMAGE_EXTENSIONS
base_name , ext = os . path . splitext ( url )
ext = ext . lstrip ( '.' )
if ext not in VALID_IMAGE_EXTENSIONS :
raise Exception ( "Invalid image extension" )
base_path , filename = os . path . split ( destination )
os . makedirs ( base_path )
urllib . urlretrieve ( url ,... |
def system_switch_attributes_rbridge_id_chassis_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
system = ET . SubElement ( config , "system" , xmlns = "urn:brocade.com:mgmt:brocade-ras" )
switch_attributes = ET . SubElement ( system , "switch-attributes" )
rbridge_id = ET . SubElement ( switch_attributes , "rbridge-id" )
rbridge_id_key = ET . SubElement ( rbridge_id , "rbridge-i... |
def get_filename ( key , message , default = None , history = None ) :
"""Like : meth : ` prompt ` , but only accepts the name of an existing file
as an input .
: type key : str
: param key : The key under which to store the input in the : class : ` InputHistory ` .
: type message : str
: param message : ... | def _validate ( string ) :
if not os . path . isfile ( string ) :
return 'File not found. Please enter a filename.'
return prompt ( key , message , default , True , _validate , history ) |
def _dep_changed ( self , dep , code_changed = False , value_changed = False ) :
"""Called when a dependency ' s expression has changed .""" | self . changed ( code_changed , value_changed ) |
def plot_dos ( self , T = None , npoints = 10000 ) :
"""Plot the total Dos using DosPlotter ( )""" | if self . bzt_interp is None :
raise BoltztrapError ( "BztInterpolator not present" )
tdos = self . bzt_interp . get_dos ( T = T , npts_mu = npoints )
# print ( npoints )
dosPlotter = DosPlotter ( )
dosPlotter . add_dos ( 'Total' , tdos )
return dosPlotter |
def has_permissions ( ** perms ) :
"""A : func : ` . check ` that is added that checks if the member has all of
the permissions necessary .
The permissions passed in must be exactly like the properties shown under
: class : ` . discord . Permissions ` .
This check raises a special exception , : exc : ` . Mi... | def predicate ( ctx ) :
ch = ctx . channel
permissions = ch . permissions_for ( ctx . author )
missing = [ perm for perm , value in perms . items ( ) if getattr ( permissions , perm , None ) != value ]
if not missing :
return True
raise MissingPermissions ( missing )
return check ( predicate... |
def _run_opf ( self , P , q , AA , ll , uu , xmin , xmax , x0 , opt ) :
"""Solves the either quadratic or linear program .""" | AAcvx = tocvx ( AA )
nx = x0 . shape [ 0 ]
# number of variables
# add var limits to linear constraints
eyex = spmatrix ( 1.0 , range ( nx ) , range ( nx ) )
A = sparse ( [ eyex , AAcvx ] )
l = matrix ( [ - xmin , ll ] )
u = matrix ( [ xmax , uu ] )
Ae , be , Ai , bi = split_linear_constraints ( A , l , u )
if len ( P ... |
def show_subnet ( self , subnet , ** _params ) :
"""Fetches information of a certain subnet .""" | return self . get ( self . subnet_path % ( subnet ) , params = _params ) |
def _sfn ( l , mask , myrad , bcast_var ) :
"""Score classifier on searchlight data using cross - validation .
The classifier is in ` bcast _ var [ 2 ] ` . The labels are in ` bast _ var [ 0 ] ` . The
number of cross - validation folds is in ` bast _ var [ 1 ] .""" | clf = bcast_var [ 2 ]
data = l [ 0 ] [ mask , : ] . T
# print ( l [ 0 ] . shape , mask . shape , data . shape )
skf = model_selection . StratifiedKFold ( n_splits = bcast_var [ 1 ] , shuffle = False )
accuracy = np . mean ( model_selection . cross_val_score ( clf , data , y = bcast_var [ 0 ] , cv = skf , n_jobs = 1 ) )... |
def get_enum_from_name ( self , enum_name ) :
"""Return an enum from a name
Args :
enum _ name ( str ) : name of the enum
Returns :
Enum""" | return next ( ( e for e in self . enums if e . name == enum_name ) , None ) |
def trayicon_toggled ( self , settings , key , user_data ) :
"""If the gconf var use _ trayicon be changed , this method will
be called and will show / hide the trayicon .""" | if hasattr ( self . guake . tray_icon , 'set_status' ) :
self . guake . tray_icon . set_status ( settings . get_boolean ( key ) )
else :
self . guake . tray_icon . set_visible ( settings . get_boolean ( key ) ) |
def import_opml ( url ) :
"""Import an OPML file locally or from a URL . Uses your text attributes as aliases .""" | # Test if URL given is local , then open , parse out feed urls ,
# add feeds , set text = to aliases and report success , list feeds added
from bs4 import BeautifulSoup
try :
f = file ( url ) . read ( )
except IOError :
f = requests . get ( url ) . text
soup = BeautifulSoup ( f , "xml" )
links = soup . find_all... |
def _overwrite ( self , n ) :
"""Overwrite old file with new and keep file with suffix . old""" | if os . path . isfile ( n [ : - 4 ] ) :
shutil . copy2 ( n [ : - 4 ] , n [ : - 4 ] + ".old" )
print ( "Old file {0} saved as {1}.old" . format ( n [ : - 4 ] . split ( "/" ) [ - 1 ] , n [ : - 4 ] . split ( "/" ) [ - 1 ] ) )
if os . path . isfile ( n ) :
shutil . move ( n , n [ : - 4 ] )
print ( "New file... |
def listRoleIds ( self , * args , ** kwargs ) :
"""List Role IDs
If no limit is given , the roleIds of all roles are returned . Since this
list may become long , callers can use the ` limit ` and ` continuationToken `
query arguments to page through the responses .
This method gives output : ` ` v1 / list -... | return self . _makeApiCall ( self . funcinfo [ "listRoleIds" ] , * args , ** kwargs ) |
def createResourceMapFromStream ( in_stream , base_url = d1_common . const . URL_DATAONE_ROOT ) :
"""Create a simple OAI - ORE Resource Map with one Science Metadata document and any
number of Science Data objects , using a stream of PIDs .
Args :
in _ stream :
The first non - blank line is the PID of the r... | pids = [ ]
for line in in_stream :
pid = line . strip ( )
if pid == "#" or pid . startswith ( "# " ) :
continue
if len ( pids ) < 2 :
raise ValueError ( "Insufficient numbers of identifiers provided." )
logging . info ( "Read {} identifiers" . format ( len ( pids ) ) )
ore = ResourceMap ( base_url =... |
def deflate_write_block ( fo , block_bytes ) :
"""Write block in " deflate " codec .""" | # The first two characters and last character are zlib
# wrappers around deflate data .
data = compress ( block_bytes ) [ 2 : - 1 ]
write_long ( fo , len ( data ) )
fo . write ( data ) |
def csv ( self ) :
"""Returns the security rules as a CSV .
CSV format :
- id
- name
- description
- rules _ direction
- rules _ ip _ protocol
- rules _ from _ port
- rules _ to _ port
- rules _ grants _ group _ id
- rules _ grants _ name
- rules _ grants _ cidr _ ip
- rules _ description
... | # Generate a csv file in memory with all the data in
output = StringIO . StringIO ( )
fieldnames = [ 'id' , 'name' , 'description' , 'rules_direction' , 'rules_ip_protocol' , 'rules_from_port' , 'rules_to_port' , 'rules_grants_group_id' , 'rules_grants_name' , 'rules_grants_cidr_ip' , 'rules_description' ]
writer = csv... |
def runfile ( self , filename , args = None ) :
"""Run filename
args : command line arguments ( string )""" | if args is not None and not is_text_string ( args ) :
raise TypeError ( "expected a character buffer object" )
self . namespace [ '__file__' ] = filename
sys . argv = [ filename ]
if args is not None :
for arg in args . split ( ) :
sys . argv . append ( arg )
self . execfile ( filename )
sys . argv = [ ... |
def detect_xid_devices ( self ) :
"""For all of the com ports connected to the computer , send an
XID command ' _ c1 ' . If the device response with ' _ xid ' , it is
an xid device .""" | self . __xid_cons = [ ]
for c in self . __com_ports :
device_found = False
for b in [ 115200 , 19200 , 9600 , 57600 , 38400 ] :
con = XidConnection ( c , b )
try :
con . open ( )
except SerialException :
continue
con . flush_input ( )
con . flush_o... |
def init_parser ( ) :
"""Initialize the arguments parser .""" | parser = argparse . ArgumentParser ( description = "Automated development environment initialization" )
parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + __version__ )
subparsers = parser . add_subparsers ( title = "commands" )
# List command
parser_list = subparsers . add_parser ( "lis... |
def _next ( self ) :
"""Get the next summary and present it .""" | self . summaries . rotate ( - 1 )
current_summary = self . summaries [ 0 ]
self . _update_summary ( current_summary ) |
def dft_postprocess_data ( arr , real_grid , recip_grid , shift , axes , interp , sign = '-' , op = 'multiply' , out = None ) :
"""Post - process the Fourier - space data after DFT .
This function multiplies the given data with the separable
function : :
q ( xi ) = exp ( + - 1j * dot ( x [ 0 ] , xi ) ) * s * ... | arr = np . asarray ( arr )
if is_real_floating_dtype ( arr . dtype ) :
arr = arr . astype ( complex_dtype ( arr . dtype ) )
elif not is_complex_floating_dtype ( arr . dtype ) :
raise ValueError ( 'array data type {} is not a complex floating point ' 'data type' . format ( dtype_repr ( arr . dtype ) ) )
if out i... |
def add_leaf_node ( self , tree_id , node_id , values , relative_hit_rate = None ) :
"""Add a leaf node to the tree ensemble .
Parameters
tree _ id : int
ID of the tree to add the node to .
node _ id : int
ID of the node within the tree .
values : [ float | int | list | dict ]
Value ( s ) at the leaf ... | spec_node = self . tree_parameters . nodes . add ( )
spec_node . treeId = tree_id
spec_node . nodeId = node_id
spec_node . nodeBehavior = _TreeEnsemble_pb2 . TreeEnsembleParameters . TreeNode . TreeNodeBehavior . Value ( 'LeafNode' )
if not isinstance ( values , _collections . Iterable ) :
values = [ values ]
if re... |
def get_peaks ( self , method = "slope" , peak_amp_thresh = 0.00005 , valley_thresh = 0.00003 , intervals = None , lookahead = 20 , avg_interval = 100 ) :
"""This function expects SMOOTHED histogram . If you run it on a raw histogram ,
there is a high chance that it returns no peaks .
method can be interval / s... | peaks = { }
slope_peaks = { }
# Oh dear future me , please don ' t get confused with a lot of mess around
# indices around here . All indices ( eg : left _ index etc ) refer to indices
# of x or y ( of histogram ) .
if method == "slope" or method == "hybrid" : # step 1 : get the peaks
result = slope . peaks ( self ... |
def get_logger_data ( self ) :
'''Return data on managed loggers .
Returns a dictionary of managed logger configuration data . The format
is primarily controlled by the
: func : ` SocketStreamCapturer . dump _ handler _ config _ data ` function : :
< capture address > : < list of handler config for data cap... | return { address : stream_capturer [ 0 ] . dump_handler_config_data ( ) for address , stream_capturer in self . _stream_capturers . iteritems ( ) } |
def inferObject ( exp , objectId , objects , objectName ) :
"""Run inference on the given object .
objectName is the name of this object in the experiment .""" | # Create sequence of random sensations for this object for one column . The
# total number of sensations is equal to the number of points on the object .
# No point should be visited more than once .
objectSensations = { }
objectSensations [ 0 ] = [ ]
obj = objects [ objectId ]
objectCopy = [ pair for pair in obj ]
ran... |
def threshold_get_color ( self , value , name = None ) :
"""Obtain color for a value using thresholds .
The value will be checked against any defined thresholds . These should
have been set in the i3status configuration . If more than one
threshold is needed for a module then the name can also be supplied .
... | # If first run then process the threshold data .
if self . _thresholds is None :
self . _thresholds_init ( )
# allow name with different values
if isinstance ( name , tuple ) :
name_used = "{}/{}" . format ( name [ 0 ] , name [ 1 ] )
if name [ 2 ] :
self . _thresholds [ name_used ] = [ ( x [ 0 ] , s... |
def read_code_bytes ( self , size = 128 , offset = 0 ) :
"""Tries to read some bytes of the code currently being executed .
@ type size : int
@ param size : Number of bytes to read .
@ type offset : int
@ param offset : Offset from the program counter to begin reading .
@ rtype : str
@ return : Bytes re... | return self . get_process ( ) . read ( self . get_pc ( ) + offset , size ) |
def create ( self , ipv4s ) :
"""Method to create ipv4 ' s
: param ipv4s : List containing ipv4 ' s desired to be created on database
: return : None""" | data = { 'ips' : ipv4s }
return super ( ApiIPv4 , self ) . post ( 'api/v3/ipv4/' , data ) |
def add_post ( request , t_slug , t_id , p_id = False ) : # topic slug , topic id , post id
"""Creates a new post and attaches it to a topic""" | topic = get_object_or_404 ( Topic , id = t_id )
topic_url = '{0}page{1}/' . format ( topic . get_short_url ( ) , topic . page_count )
user = request . user
current_time = time . time ( )
form_title = 'Add a post'
if topic . is_locked : # If we mistakenly allowed reply on locked topic , bail with error msg .
message... |
def update_exc ( exc , msg , before = True , separator = "\n" ) :
"""Adds additional text to an exception ' s error message .
The new text will be added before the existing text by default ; to append
it after the original text , pass False to the ` before ` parameter .
By default the old and new text will be... | emsg = exc . message
if before :
parts = ( msg , separator , emsg )
else :
parts = ( emsg , separator , msg )
new_msg = "%s%s%s" % parts
new_args = ( new_msg , ) + exc . args [ 1 : ]
exc . message = new_msg
exc . args = new_args
return exc |
def _check_denied_group ( self ) :
"""Returns True if the negative group requirement ( AUTH _ LDAP _ DENY _ GROUP )
is met . Always returns True if AUTH _ LDAP _ DENY _ GROUP is None .""" | denied_group_dn = self . settings . DENY_GROUP
if denied_group_dn is not None :
is_member = self . _get_groups ( ) . is_member_of ( denied_group_dn )
if is_member :
raise self . AuthenticationFailed ( "user does not satisfy AUTH_LDAP_DENY_GROUP" )
return True |
def get_groups ( self ) :
"""Return a list of groups of atom indexes
Each atom in a group belongs to the same molecule or residue .""" | groups = [ ]
for a_index , m_index in enumerate ( self . molecules ) :
if m_index >= len ( groups ) :
groups . append ( [ a_index ] )
else :
groups [ m_index ] . append ( a_index )
return groups |
def data2schema ( _data = None , _force = False , _besteffort = True , _registry = None , _factory = None , _buildkwargs = None , ** kwargs ) :
"""Get the schema able to instanciate input data .
The default value of schema will be data .
Can be used such as a decorator :
. . code - block : : python
@ data2s... | if _data is None :
return lambda _data : data2schema ( _data , _force = False , _besteffort = True , _registry = None , _factory = None , _buildkwargs = None , ** kwargs )
result = None
fdata = _data ( ) if isinstance ( _data , DynamicValue ) else _data
datatype = type ( fdata )
content = getattr ( fdata , '__dict_... |
def to_utf8 ( str_or_unicode ) :
"""Safely returns a UTF - 8 version of a given string
> > > utils . to _ utf8 ( u ' hi ' )
' hi '""" | if not isinstance ( str_or_unicode , six . text_type ) :
return str_or_unicode . encode ( "utf-8" , "ignore" )
return str ( str_or_unicode ) |
def FontForLabels ( self , dc ) :
'''Return the default GUI font , scaled for printing if necessary .''' | font = wx . SystemSettings_GetFont ( wx . SYS_DEFAULT_GUI_FONT )
scale = dc . GetPPI ( ) [ 0 ] / wx . ScreenDC ( ) . GetPPI ( ) [ 0 ]
font . SetPointSize ( scale * font . GetPointSize ( ) )
return font |
def modification_time ( self ) :
"""dfdatetime . DateTimeValues : modification time or None if not available .""" | if self . _stat_info is None :
return None
timestamp = int ( self . _stat_info . st_mtime )
return dfdatetime_posix_time . PosixTime ( timestamp = timestamp ) |
def plotCompareTrackAAModel ( self , ** kwargs ) :
"""NAME :
plotCompareTrackAAModel
PURPOSE :
plot the comparison between the underlying model ' s dOmega _ perp vs . dangle _ r ( line ) and the track in ( x , v ) ' s dOmega _ perp vs . dangle _ r ( dots ; explicitly calculating the track ' s action - angle c... | # First calculate the model
model_adiff = ( self . _ObsTrackAA [ : , 3 : ] - self . _progenitor_angle ) [ : , 0 ] * self . _sigMeanSign
model_operp = numpy . dot ( self . _ObsTrackAA [ : , : 3 ] - self . _progenitor_Omega , self . _dsigomeanProgDirection ) * self . _sigMeanSign
# Then calculate the track ' s frequency ... |
def parameter_struct_dict ( self ) :
"""Dictionary containing PyAtomData structs for the force field .""" | if self . _parameter_struct_dict is None :
self . _parameter_struct_dict = self . _make_ff_params_dict ( )
elif self . auto_update_f_params :
new_hash = hash ( tuple ( [ tuple ( item ) for sublist in self . values ( ) for item in sublist . values ( ) ] ) )
if self . _old_hash != new_hash :
self . _p... |
def _replace_deferred ( self , arg , context ) :
"""This replaces all deferred nodes ( UnboundVariables and _ DeferredLayers ) .
If arg is a sequence or a dict , then it ' s deferred values are also replaced .
Args :
arg : The argument to replace . If a list or a dict , then all items are also
replaced .
... | if isinstance ( arg , UnboundVariable ) :
return context [ arg ]
elif isinstance ( arg , _DeferredLayer ) : # pylint : disable = protected - access
return arg . _construct ( context )
elif isinstance ( arg , tuple ) :
return tuple ( ( self . _replace_deferred ( x , context ) for x in arg ) )
elif ( isinstan... |
def get_cdpp ( self , flux = None ) :
'''Returns the scalar CDPP for the light curve .''' | if flux is None :
flux = self . flux
return self . _mission . CDPP ( self . apply_mask ( flux ) , cadence = self . cadence ) |
def compute ( cls , observation , prediction ) :
"""Compute a z - score from an observation and a prediction .""" | assert isinstance ( observation , dict )
try :
p_value = prediction [ 'mean' ]
# Use the prediction ' s mean .
except ( TypeError , KeyError , IndexError ) : # If there isn ' t one . . .
try :
p_value = prediction [ 'value' ]
# Use the prediction ' s value .
except ( TypeError , IndexErr... |
def tag ( self ) :
"""Get the string representation of the tag used to annotate the status in VOSpace .
@ return : str""" | return "{}{}_{}{:02d}" . format ( self . target . prefix , self , self . target . version , self . target . ccd ) |
def delete ( self , _id ) :
"""Delete a document or create a DELETE revision
: param str _ id : The ID of the document to be deleted
: returns : JSON Mongo client response including the " n " key to show number of objects effected""" | mongo_response = yield self . collection . remove ( { "_id" : ObjectId ( _id ) } )
raise Return ( mongo_response ) |
def read_nonblocking ( self , size = 1 , timeout = None ) :
"""This reads data from the file descriptor .
This is a simple implementation suitable for a regular file . Subclasses using ptys or pipes should override it .
The timeout parameter is ignored .""" | try :
s = os . read ( self . child_fd , size )
except OSError as err :
if err . args [ 0 ] == errno . EIO : # Linux - style EOF
self . flag_eof = True
raise EOF ( 'End Of File (EOF). Exception style platform.' )
raise
if s == b'' : # BSD - style EOF
self . flag_eof = True
raise EOF (... |
def convert_ipynbs ( directory ) :
"""Recursively converts all ipynb files in a directory into rst files in
the same directory .""" | # The ipython _ examples dir has to be in the same dir as this script
for root , subfolders , files in os . walk ( os . path . abspath ( directory ) ) :
for f in files :
if ".ipynb_checkpoints" not in root :
if f . endswith ( "ipynb" ) :
ipynb_to_rst ( root , f ) |
def evaluate_tour_M ( self , tour ) :
"""Use Cythonized version to evaluate the score of a current tour""" | from . chic import score_evaluate_M
return score_evaluate_M ( tour , self . active_sizes , self . M ) |
def blocks_info ( self , hashes , pending = False , source = False ) :
"""Retrieves a json representations of * * blocks * * with transaction
* * amount * * & block * * account * *
: param hashes : List of block hashes to return info for
: type hashes : list of str
: param pending : If true , returns pendin... | hashes = self . _process_value ( hashes , 'list' )
payload = { "hashes" : hashes }
if pending :
payload [ 'pending' ] = self . _process_value ( pending , 'strbool' )
if source :
payload [ 'source' ] = self . _process_value ( source , 'strbool' )
resp = self . call ( 'blocks_info' , payload )
blocks = resp . get... |
def _indexing_list_tuple_of_data ( data , i , indexings = None ) :
"""Data is a list / tuple of data structures ( e . g . list of numpy arrays ) .
` ` indexings ` ` are the indexing functions for each element of
` ` data ` ` . If ` ` indexings ` ` are not given , the indexing functions
for the individual stru... | if not indexings :
return [ multi_indexing ( x , i ) for x in data ]
return [ multi_indexing ( x , i , indexing ) for x , indexing in zip ( data , indexings ) ] |
def validate_username ( form , field ) :
"""Wrap username validator for WTForms .""" | try :
validate_username ( field . data )
except ValueError as e :
raise ValidationError ( e )
try :
user_profile = UserProfile . get_by_username ( field . data )
if current_userprofile . is_anonymous or ( current_userprofile . user_id != user_profile . user_id and field . data != current_userprofile . u... |
def get_authorize_url ( self , ** params ) :
'''Returns a formatted authorize URL .
: param \ * \ * params : Additional keyworded arguments to be added to the
URL querystring .
: type \ * \ * params : dict''' | params . update ( { 'client_id' : self . client_id } )
return self . authorize_url + '?' + urlencode ( params ) |
def _raise_error ( self , status_code , raw_data ) :
"""Locate appropriate exception and raise it .""" | error_message = raw_data
additional_info = None
try :
if raw_data :
additional_info = json . loads ( raw_data )
error_message = additional_info . get ( 'error' , error_message )
if isinstance ( error_message , dict ) and 'type' in error_message :
error_message = error_message [ '... |
def attach_grad ( self , grad_req = 'write' , stype = None ) :
"""Attach a gradient buffer to this NDArray , so that ` backward `
can compute gradient with respect to it .
Parameters
grad _ req : { ' write ' , ' add ' , ' null ' }
How gradient will be accumulated .
- ' write ' : gradient will be overwritt... | from . import zeros as _zeros
if stype is not None :
grad = _zeros ( self . shape , stype = stype )
else :
grad = op . zeros_like ( self )
# pylint : disable = undefined - variable
grad_req = _GRAD_REQ_MAP [ grad_req ]
check_call ( _LIB . MXAutogradMarkVariables ( 1 , ctypes . pointer ( self . handle ) , ct... |
def custom_search_model ( model , query , preview = False , published = False , id_field = "id" , sort_pinned = True , field_map = { } ) :
"""Filter a model with the given filter .
` field _ map ` translates incoming field names to the appropriate ES names .""" | if preview :
func = preview_filter_from_query
else :
func = filter_from_query
f = func ( query , id_field = id_field , field_map = field_map )
# filter by published
if published :
if f :
f &= Range ( published = { "lte" : timezone . now ( ) } )
else :
f = Range ( published = { "lte" : ti... |
def set_extended_elements ( self ) :
"""Parses and sets non required elements""" | self . set_creative_commons ( )
self . set_owner ( )
self . set_subtitle ( )
self . set_summary ( ) |
def add_member ( self , legislator , role = 'member' , ** kwargs ) :
"""Add a member to the committee object .
: param legislator : name of the legislator
: param role : role that legislator holds in the committee
( eg . chairman ) default : ' member '""" | self [ 'members' ] . append ( dict ( name = legislator , role = role , ** kwargs ) ) |
def do_alarm_count ( mc , args ) :
'''Count alarms .''' | fields = { }
if args . alarm_definition_id :
fields [ 'alarm_definition_id' ] = args . alarm_definition_id
if args . metric_name :
fields [ 'metric_name' ] = args . metric_name
if args . metric_dimensions :
fields [ 'metric_dimensions' ] = utils . format_dimensions_query ( args . metric_dimensions )
if args... |
def general_stats_addcols ( self , data , headers = None , namespace = None ) :
"""Helper function to add to the General Statistics variable .
Adds to report . general _ stats and does not return anything . Fills
in required config variables if not supplied .
: param data : A dict with the data . First key sh... | if headers is None :
headers = { }
# Use the module namespace as the name if not supplied
if namespace is None :
namespace = self . name
# Guess the column headers from the data if not supplied
if headers is None or len ( headers ) == 0 :
hs = set ( )
for d in data . values ( ) :
hs . update ( d... |
def Needleman_Wunsch ( w1 , w2 , d = - 1 , alphabet = "abcdefghijklmnopqrstuvwxyz" , S = Default_Matrix ( 26 , 1 , - 1 ) ) :
"""Computes allignment using Needleman - Wunsch algorithm . The alphabet
parameter is used for specifying the alphabetical order of the similarity
matrix . Similarity matrix is initialize... | # S must be a square matrix matching the length of your alphabet
if len ( S ) != len ( alphabet ) or len ( S [ 0 ] ) != len ( alphabet ) :
raise AssertionError ( "Unexpected dimensions of Similarity matrix, S." " S must be a n by n square matrix, where n is the" " length of your predefined alphabet" )
m , n = len (... |
def post ( self , request , * args , ** kwargs ) :
"""Check if an URL is provided and if trackbacks
are enabled on the Entry .
If so the URL is registered one time as a trackback .""" | url = request . POST . get ( 'url' )
if not url :
return self . get ( request , * args , ** kwargs )
entry = self . get_object ( )
site = Site . objects . get_current ( )
if not entry . trackbacks_are_open :
return self . render_to_response ( { 'error' : 'Trackback is not enabled for %s' % entry . title } )
tit... |
def generate_swagger_html ( swagger_static_root , swagger_json_url ) :
"""given a root directory for the swagger statics , and
a swagger json path , return back a swagger html designed
to use those values .""" | tmpl = _get_template ( "swagger.html" )
return tmpl . render ( swagger_root = swagger_static_root , swagger_json_url = swagger_json_url ) |
def get_similar_users ( self , users = None , k = 10 ) :
"""Get the k most similar users for each entry in ` users ` .
Each type of recommender has its own model for the similarity
between users . For example , the factorization _ recommender will
return the nearest users based on the cosine similarity
betw... | if users is None :
get_all_users = True
users = _SArray ( )
else :
get_all_users = False
if isinstance ( users , list ) :
users = _SArray ( users )
def check_type ( arg , arg_name , required_type , allowed_types ) :
if not isinstance ( arg , required_type ) :
raise TypeError ( "Parameter " +... |
def ping ( destination , source = None , ttl = None , timeout = None , size = None , count = None , vrf = None , ** kwargs ) : # pylint : disable = unused - argument
'''Executes a ping on the network device and returns a dictionary as a result .
destination
Hostname or IP address of remote host
source
Sourc... | return salt . utils . napalm . call ( napalm_device , # pylint : disable = undefined - variable
'ping' , ** { 'destination' : destination , 'source' : source , 'ttl' : ttl , 'timeout' : timeout , 'size' : size , 'count' : count , 'vrf' : vrf } ) |
def IPT_to_XYZ ( cobj , * args , ** kwargs ) :
"""Converts IPT to XYZ .""" | ipt_values = numpy . array ( cobj . get_value_tuple ( ) )
lms_values = numpy . dot ( numpy . linalg . inv ( IPTColor . conversion_matrices [ 'lms_to_ipt' ] ) , ipt_values )
lms_prime = numpy . sign ( lms_values ) * numpy . abs ( lms_values ) ** ( 1 / 0.43 )
xyz_values = numpy . dot ( numpy . linalg . inv ( IPTColor . c... |
def stats ( self , alpha = 0.05 , start = 0 , batches = 100 , chain = None , quantiles = ( 2.5 , 25 , 50 , 75 , 97.5 ) ) :
"""Generate posterior statistics for node .
: Parameters :
alpha : float
The alpha level for generating posterior intervals . Defaults to
0.05.
start : int
The starting index from w... | return self . trace . stats ( alpha = alpha , start = start , batches = batches , chain = chain , quantiles = quantiles ) |
def has_apps ( names , check_platform = True ) :
"""Check whether the applications [ < name > , . . . ] are installed .""" | if check_platform :
Environment . _platform_is_windows ( )
for name in names :
yield Environment . has_app ( str ( name ) , check_platform = False ) |
def _checkMetadata ( self , variantFile ) :
"""Checks that metadata is consistent""" | metadata = self . _getMetadataFromVcf ( variantFile )
if self . _metadata is not None and self . _metadata != metadata :
raise exceptions . InconsistentMetaDataException ( variantFile . filename ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.