signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _run_prospector_on ( filenames , tools , disabled_linters , show_lint_files , ignore_codes = None ) :
"""Run prospector on filename , using the specified tools .
This function enables us to run different tools on different
classes of files , which is necessary in the case of tests .""" | from prospector . run import Prospector , ProspectorConfig
assert tools
tools = list ( set ( tools ) - set ( disabled_linters ) )
return_dict = dict ( )
ignore_codes = ignore_codes or list ( )
# Early return if all tools were filtered out
if not tools :
return return_dict
# pylint doesn ' t like absolute paths , so... |
def validate_matrix ( self , data ) :
"""Validates matrix data and creates the config objects""" | is_grid_search = ( data . get ( 'grid_search' ) is not None or ( data . get ( 'grid_search' ) is None and data . get ( 'random_search' ) is None and data . get ( 'hyperband' ) is None and data . get ( 'bo' ) is None ) )
is_bo = data . get ( 'bo' ) is not None
validate_matrix ( data . get ( 'matrix' ) , is_grid_search =... |
def cov2corr ( cov ) :
"""Calculate the correlation matrix based on a
covariance matrix
Parameters
cov : 2D array
Returns
corr : 2D array
correlation converted from the covarince matrix""" | assert cov . ndim == 2 , 'covariance matrix should be 2D array'
inv_sd = 1 / np . sqrt ( np . diag ( cov ) )
corr = cov * inv_sd [ None , : ] * inv_sd [ : , None ]
return corr |
def setAsSent ( self , prekeyIds ) :
""": param preKeyIds :
: type preKeyIds : list
: return :
: rtype :""" | for prekeyId in prekeyIds :
q = "UPDATE prekeys SET sent_to_server = ? WHERE prekey_id = ?"
cursor = self . dbConn . cursor ( )
cursor . execute ( q , ( 1 , prekeyId ) )
self . dbConn . commit ( ) |
def _get_state ( self ) :
"""Returns the VM state ( e . g . running , paused etc . )
: returns : state ( string )""" | result = yield from self . _execute ( "showvminfo" , [ self . _vmname , "--machinereadable" ] )
for info in result . splitlines ( ) :
if '=' in info :
name , value = info . split ( '=' , 1 )
if name == "VMState" :
return value . strip ( '"' )
return "unknown" |
def current_rev_reg_id ( base_dir : str , cd_id : str ) -> str :
"""Return the current revocation registry identifier for
input credential definition identifier , in input directory .
Raise AbsentTails if no corresponding tails file , signifying no such revocation registry defined .
: param base _ dir : base ... | tags = [ int ( rev_reg_id2tag ( basename ( f ) ) ) for f in Tails . links ( base_dir ) if cd_id in basename ( f ) ]
if not tags :
raise AbsentTails ( 'No tails files present for cred def id {}' . format ( cd_id ) )
return rev_reg_id ( cd_id , str ( max ( tags ) ) ) |
def create_payload ( self ) :
"""Rename the payload key " prior _ id " to " prior " .
For more information , see ` Bugzilla # 1238757
< https : / / bugzilla . redhat . com / show _ bug . cgi ? id = 1238757 > ` _ .""" | payload = super ( LifecycleEnvironment , self ) . create_payload ( )
if ( _get_version ( self . _server_config ) < Version ( '6.1' ) and 'prior_id' in payload ) :
payload [ 'prior' ] = payload . pop ( 'prior_id' )
return payload |
def action ( arguments ) :
"""Given one more more sequence files , determine if the file is an alignment ,
the maximum sequence length and the total number of sequences . Provides
different output formats including tab ( tab - delimited ) , csv and align
( aligned as if part of a borderless table ) .""" | # Ignore SIGPIPE , for head support
common . exit_on_sigpipe ( )
common . exit_on_sigint ( )
handle = arguments . destination_file
output_format = arguments . output_format
if not output_format :
try :
output_format = 'align' if handle . isatty ( ) else 'tab'
except AttributeError :
output_forma... |
def _add_jitter ( self , vec ) :
""": param vec : array to jitter
: return : array , jittered version of arrays""" | if self . scatterchartdata . jitter == 0 or self . scatterchartdata . jitter is None :
return vec
return vec + np . random . rand ( 1 , len ( vec ) ) [ 0 ] * self . scatterchartdata . jitter |
def _create_subscription_definition ( gg_client , group_type , config ) :
"""Configure routing subscriptions for a Greengrass group .
group _ type : either default or an overridden group type
config : GroupConfigFile object used for routing subscriptions""" | logging . info ( '[begin] Configuring routing subscriptions' )
sub_info = gg_client . create_subscription_definition ( Name = "{0}_routing" . format ( group_type . type_name ) )
logging . info ( 'Created subscription definition: {0}' . format ( sub_info ) )
subs = group_type . get_subscription_definition ( config = con... |
def _image_loop ( self ) :
"""Retrieve an iterable of images either with , or without a progress bar .""" | if self . progress_bar and 'tqdm' in self . progress_bar . lower ( ) :
return tqdm ( self . imgs , desc = 'Saving PNGs as flat PDFs' , total = len ( self . imgs ) , unit = 'PDFs' )
else :
return self . imgs |
def _getPFilename ( self , native , prompt ) :
"""Get p _ filename field for this parameter
Same as get for non - list params""" | return self . get ( native = native , prompt = prompt ) |
def make_sshable ( c ) :
"""Set up passwordless SSH keypair & authorized _ hosts access to localhost .""" | user = c . travis . sudo . user
home = "~{0}" . format ( user )
# Run sudo ( ) as the new sudo user ; means less chown ' ing , etc .
c . config . sudo . user = user
ssh_dir = "{0}/.ssh" . format ( home )
# TODO : worth wrapping in ' sh - c ' and using ' & & ' instead of doing this ?
for cmd in ( "mkdir {0}" , "chmod 07... |
def to_native ( self , obj , name , value ) : # pylint : disable = unused - argument
"""Transform the MongoDB value into a Marrow Mongo value .""" | from marrow . mongo import Document
from marrow . mongo . trait import Derived
kind = self . _kind ( obj . __class__ )
if isinstance ( value , Document ) :
if __debug__ and kind and issubclass ( kind , Document ) and not isinstance ( value , kind ) :
raise ValueError ( "Not an instance of " + kind . __name_... |
def _search ( self ) :
"""Returns all documents in the doc dict .
This function is not a part of the DocManager API , and is only used
to simulate searching all documents from a backend .""" | results = [ ]
for _id in self . doc_dict :
entry = self . doc_dict [ _id ]
if entry . doc is not None :
results . append ( entry . merged_dict )
return results |
def deserialize ( cls , data ) :
"""Given some data from the queue , deserializes it into a ` ` Task ` `
instance .
The data must be similar in format to what comes from
` ` Task . serialize ` ` ( a JSON - serialized dictionary ) . Required keys are
` ` task _ id ` ` , ` ` retries ` ` & ` ` async ` ` .
: ... | data = json . loads ( data )
options = data . get ( 'options' , { } )
task = cls ( task_id = data [ 'task_id' ] , retries = data [ 'retries' ] , async = data [ 'async' ] )
func = import_attr ( data [ 'module' ] , data [ 'callable' ] )
task . to_call ( func , * data . get ( 'args' , [ ] ) , ** data . get ( 'kwargs' , { ... |
def action_fluents ( self ) -> Dict [ str , PVariable ] :
'''Returns action - fluent pvariables .''' | return { str ( pvar ) : pvar for pvar in self . pvariables if pvar . is_action_fluent ( ) } |
def basescript ( line ) :
'''> > > import pprint
> > > input _ line = ' { " level " : " warning " , " timestamp " : " 2018-02-07T06:37:00.297610Z " , " event " : " exited via keyboard interrupt " , " type " : " log " , " id " : " 20180207T063700_4d03fe800bd111e89ecb96000007bc65 " , " _ " : { " ln " : 58 , " file ... | log = json . loads ( line )
return dict ( timestamp = log [ 'timestamp' ] , data = log , id = log [ 'id' ] , type = log [ 'type' ] , level = log [ 'level' ] , event = log [ 'event' ] ) |
def linkify_h_by_realms ( self , realms ) :
"""Link hosts with realms
: param realms : realms object to link with
: type realms : alignak . objects . realm . Realms
: return : None""" | default_realm = realms . get_default ( )
for host in self :
if not getattr ( host , 'realm' , None ) : # Applying default realm to an host
host . realm = default_realm . uuid if default_realm else ''
host . realm_name = default_realm . get_name ( ) if default_realm else ''
host . got_default... |
def delete_attr ( self , name : str , axis : int = 0 ) -> None :
"""* * DEPRECATED * * - Use ` del ds . ra . key ` or ` del ds . ca . key ` instead , where ` key ` is replaced with the attribute name""" | deprecated ( "'delete_attr' is deprecated. Use 'del ds.ra.key' or 'del ds.ca.key' instead" )
if axis == 0 :
del self . ra [ name ]
else :
del self . ca [ name ] |
def to_bytes ( self ) :
"""Convert to bytes .
: rtype : bytes""" | return struct . pack ( "!IIIIHHbb" , self . width , self . height , self . x_offset , self . y_offset , self . delay , self . delay_den , self . depose_op , self . blend_op ) |
def _call_api ( self , url , method = 'GET' , params = None , data = None ) :
"""Method used to call the API .
It returns the raw JSON returned by the API or raises an exception
if something goes wrong .
: arg url : the URL to call
: kwarg method : the HTTP method to use when calling the specified
URL , c... | req = self . session . request ( method = method , url = url , params = params , headers = self . header , data = data , verify = not self . insecure , )
output = None
try :
output = req . json ( )
except Exception as err :
LOG . debug ( req . text )
# TODO : use a dedicated error class
raise Exception ... |
def rgb ( self ) :
"""Same as raw ( ) but RGB values are scaled to 0-255""" | ( red , green , blue ) = self . raw
return ( min ( int ( ( red * 255 ) / self . red_max ) , 255 ) , min ( int ( ( green * 255 ) / self . green_max ) , 255 ) , min ( int ( ( blue * 255 ) / self . blue_max ) , 255 ) ) |
def fill_borders ( self , * args ) :
"""Extrapolate tiepoint lons and lats to fill in the border of the
chunks .""" | to_run = [ ]
cases = { "y" : self . _fill_row_borders , "x" : self . _fill_col_borders }
for dim in args :
try :
to_run . append ( cases [ dim ] )
except KeyError :
raise NameError ( "Unrecognized dimension: " + str ( dim ) )
for fun in to_run :
fun ( ) |
def _call_parallel_target ( self , name , cdata , low ) :
'''The target function to call that will create the parallel thread / process''' | # we need to re - record start / end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime . datetime . utcnow ( )
tag = _gen_tag ( low )
try :
ret = self . states [ cdata [ 'full' ] ] ( * cdata [ 'args' ] , ** cdata [ 'kwargs' ] )
except Exception as exc :... |
def queue ( self ) :
"""Get a queue of notifications
Use it with Python with""" | queue = NotificationQueue ( )
self . _listeners . add ( queue )
yield queue
self . _listeners . remove ( queue ) |
def _get_commands ( filename , class_name , language ) :
"""Generate the related compilation and
execution commands .
Parameters
: param filename : str
The used filename .
: param class _ name : str
The used class name .
: param language : { ' c ' , ' go ' , ' java ' , ' js ' , ' php ' , ' ruby ' }
... | cname = str ( class_name )
fname = str ( filename )
lang = str ( language )
# Compilation variants :
comp_vars = { # gcc brain . c - o brain
'c' : 'gcc {} -lm -o {}' . format ( fname , cname ) , # javac Brain . java
'java' : 'javac {}' . format ( fname ) , # go build - o brain brain . go
'go' : 'go build -o {} {}.go' .... |
def formatResults ( self , op , results ) :
"""This formats the results of the database operations for printing
back to the caller
@ param op : operation to perform ( add , remove , update , get )
@ type op : string
@ param results : results from db queries in perspective _ commandline
@ type results : li... | formatted_results = ""
if op == 'add' : # list , alternating ident , uid
formatted_results += "user(s) added:\n"
for user in results :
if isinstance ( user , str ) :
formatted_results += "identifier: %s\n" % user
else :
formatted_results += "uid: %d\n\n" % user
elif op ==... |
def add_last_closed_file ( self , fname ) :
"""Add to last closed file list .""" | if fname in self . last_closed_files :
self . last_closed_files . remove ( fname )
self . last_closed_files . insert ( 0 , fname )
if len ( self . last_closed_files ) > 10 :
self . last_closed_files . pop ( - 1 ) |
def get_user_shakes ( self ) :
"""Get a list of Shake objects for the currently authenticated user .
Returns :
A list of Shake objects .""" | endpoint = '/api/shakes'
data = self . _make_request ( verb = "GET" , endpoint = endpoint )
shakes = [ Shake . NewFromJSON ( shk ) for shk in data [ 'shakes' ] ]
return shakes |
def parse_definition_docstring ( obj , process_doc ) :
"""Gets swag data from docstring for class based definitions""" | doc_lines , swag = None , None
full_doc = None
swag_path = getattr ( obj , 'swag_path' , None )
swag_type = getattr ( obj , 'swag_type' , 'yml' )
if swag_path is not None :
full_doc = load_from_file ( swag_path , swag_type )
else :
full_doc = inspect . getdoc ( obj )
if full_doc :
if full_doc . startswith (... |
def fit ( self , sequences , y = None ) :
"""Fit a PCCA lumping model using a sequence of cluster assignments .
Parameters
sequences : list ( np . ndarray ( dtype = ' int ' ) )
List of arrays of cluster assignments
y : None
Unused , present for sklearn compatibility only .
Returns
self""" | super ( PCCA , self ) . fit ( sequences , y = y )
self . _do_lumping ( )
return self |
def import_file ( self , dataTypeList = None , defaultInteraction = None , delimiters = None , delimitersForDataList = None , afile = None , firstRowAsColumnNames = None , indexColumnSourceInteraction = None , indexColumnTargetInteraction = None , indexColumnTypeInteraction = None , NetworkViewRendererList = None , Roo... | PARAMS = set_param ( [ "dataTypeList" , "defaultInteraction" , "delimiters" , "delimitersForDataList" , "file" , "firstRowAsColumnNames" , "indexColumnSourceInteraction" , "indexColumnTargetInteraction" , "indexColumnTypeInteraction" , "NetworkViewRendererList" , "RootNetworkList" , "startLoadRow" , "TargetColumnList" ... |
def addAsn1MibSource ( self , * asn1Sources , ** kwargs ) :
"""Adds path to a repository to search ASN . 1 MIB files .
Parameters
* asn1Sources :
one or more URL in form of : py : obj : ` str ` identifying local or
remote ASN . 1 MIB repositories . Path must include the * @ mib @ *
component which will be... | self . _args [ 0 ] . addAsn1MibSource ( * asn1Sources , ** kwargs )
return self |
def write_packages ( self , reqs_file ) :
"""Dump the packages in the catalog in a requirements file""" | write_file_lines ( reqs_file , ( '{}\n' . format ( package ) for package in self . packages ) ) |
def get ( self , path_info ) :
"""Gets the checksum for the specified path info . Checksum will be
retrieved from the state database if available .
Args :
path _ info ( dict ) : path info to get the checksum for .
Returns :
str or None : checksum for the specified path info or None if it
doesn ' t exist... | assert path_info [ "scheme" ] == "local"
path = path_info [ "path" ]
if not os . path . exists ( path ) :
return None
actual_mtime , actual_size = get_mtime_and_size ( path )
actual_inode = get_inode ( path )
existing_record = self . get_state_record_for_inode ( actual_inode )
if not existing_record :
return No... |
def allpossibilities ( self ) :
"""Returns all possible outputtemplates that may occur ( recusrively applied )""" | l = [ ]
if isinstance ( self . then , ParameterCondition ) : # recursive parametercondition
l += self . then . allpossibilities ( )
elif self . then :
l . append ( self . then )
if self . otherwise :
if isinstance ( self . otherwise , ParameterCondition ) :
l += self . otherwise . allpossibilities (... |
def delete ( self , cluster ) :
"""Deletes the cluster from persistent state .
: param cluster : cluster to delete from persistent state
: type cluster : : py : class : ` elasticluster . cluster . Cluster `""" | path = self . _get_cluster_storage_path ( cluster . name )
if os . path . exists ( path ) :
os . unlink ( path ) |
def upgradestep ( upgrade_product , version ) :
"""Decorator for updating the QuickInstaller of a upgrade""" | def wrap_func ( fn ) :
def wrap_func_args ( context , * args ) :
p = getToolByName ( context , 'portal_quickinstaller' ) . get ( upgrade_product )
setattr ( p , 'installedversion' , version )
return fn ( context , * args )
return wrap_func_args
return wrap_func |
def read_pid_status ( pid = "self" ) :
"""Returns the system process sstatus .
: param pid : The process ID .
: returns : The system process status .
: rtype : dict""" | data = { }
with open ( "/proc/%s/status" % ( pid , ) , "rb" ) as status_file :
for row in status_file :
fields = row . split ( )
if fields and fields [ 0 ] in [ b"VmRSS:" , b"Threads:" , b"FDSize:" ] :
try :
data [ fields [ 0 ] . decode ( "ascii" ) [ : - 1 ] ] = int ( fie... |
def move_dirty_lock_file ( dirty_lock_file , sm_path ) :
"""Move the dirt _ lock file to the sm _ path and thereby is not found by auto recovery of backup anymore""" | if dirty_lock_file is not None and not dirty_lock_file == os . path . join ( sm_path , dirty_lock_file . split ( os . sep ) [ - 1 ] ) :
logger . debug ( "Move dirty lock from root tmp folder {0} to state machine folder {1}" "" . format ( dirty_lock_file , os . path . join ( sm_path , dirty_lock_file . split ( os . ... |
def is_log_format ( value ) :
u"""Check whether the value as argument be included the following list .
[ ' ltsv ' , ' combined ' ]""" | log_levels = [ 'ltsv' , 'combined' ]
if value in log_levels :
return value
else :
err_message = ( '"log_format" supported following value: ' '{0}' . format ( log_levels ) )
raise validate . VdtValueError ( err_message ) |
def _run_alg ( self , max_iter ) :
"""Run Algorithm
Run the update step of a given algorithm up to the maximum number of
iterations .
Parameters
max _ iter : int
Maximum number of iterations""" | if self . progress :
with ProgressBar ( redirect_stdout = True , max_value = max_iter ) as bar :
self . _iterations ( max_iter , bar = bar )
else :
self . _iterations ( max_iter ) |
def get_experiment_results ( ) :
"""Computes the results of all experiments , stores it in redis , and prints it
out""" | redis = oz . redis . create_connection ( )
for experiment in oz . bandit . get_experiments ( redis ) :
experiment . compute_default_choice ( )
csq , confident = experiment . confidence ( )
print ( "%s:" % experiment . name )
print ( "- creation date: %s" % experiment . metadata [ "creation_date" ] )
... |
def ignore_stops_before_now ( self ) :
"""Ignore any stops received before this point""" | self . _sentinel_stop = object ( )
self . _q . put ( self . _sentinel_stop ) |
def frozen_price ( self ) :
"""[ float ] 冻结价格""" | if np . isnan ( self . _frozen_price ) :
raise RuntimeError ( "Frozen price of order {} is not supposed to be nan." . format ( self . order_id ) )
return self . _frozen_price |
def setShowGridColumns ( self , state ) :
"""Sets whether or not columns should be rendered when drawing the grid .
: param state | < bool >""" | delegate = self . itemDelegate ( )
if ( isinstance ( delegate , XTreeWidgetDelegate ) ) :
delegate . setShowGridColumns ( state ) |
def create ( self , obj , payload , async = False ) :
"""Function create
Create an new object
@ param obj : object name ( ' hosts ' , ' puppetclasses ' . . . )
@ param payload : the dict of the payload
@ param async : should this request be async , if true use
return . result ( ) to get the response
@ r... | self . url = self . base_url + obj
self . method = 'POST'
self . payload = json . dumps ( payload )
if async :
self . method = 'POST(Async)'
session = FuturesSession ( )
self . resp = session . post ( url = self . url , auth = self . auth , headers = self . headers , data = self . payload , cert = self . ca... |
def code_assist ( project , source_code , offset , resource = None , templates = None , maxfixes = 1 , later_locals = True ) :
"""Return python code completions as a list of ` CodeAssistProposal ` \ s
` resource ` is a ` rope . base . resources . Resource ` object . If
provided , relative imports are handled . ... | if templates is not None :
warnings . warn ( 'Codeassist no longer supports templates' , DeprecationWarning , stacklevel = 2 )
assist = _PythonCodeAssist ( project , source_code , offset , resource = resource , maxfixes = maxfixes , later_locals = later_locals )
return assist ( ) |
def get_magicc7_to_openscm_variable_mapping ( inverse = False ) :
"""Get the mappings from MAGICC7 to OpenSCM variables .
Parameters
inverse : bool
If True , return the inverse mappings i . e . OpenSCM to MAGICC7 mappings
Returns
dict
Dictionary of mappings""" | def get_openscm_replacement ( in_var ) :
if in_var . endswith ( "_INVERSE_EMIS" ) :
prefix = "Inverse Emissions"
elif in_var . endswith ( "_EMIS" ) :
prefix = "Emissions"
elif in_var . endswith ( "_CONC" ) :
prefix = "Atmospheric Concentrations"
elif in_var . endswith ( "_RF" ) :... |
def indentation_step ( node ) :
"""Dirty little trick to get the difference between each indentation level
Implemented by finding the shortest indentation string
( technically , the " least " of all of the indentation strings , but
tabs and spaces mixed won ' t get this far , so those are synonymous . )""" | r = find_root ( node )
# Collect all indentations into one set .
all_indents = set ( i . value for i in r . pre_order ( ) if i . type == token . INDENT )
if not all_indents : # nothing is indented anywhere , so we get to pick what we want
return u" "
# four spaces is a popular convention
else :
return mi... |
def run ( self , host : str = '0.0.0.0' , port : int = 8080 ) :
"""Start sirbot
Configure sirbot and start the aiohttp . web . Application
Args :
host ( str ) : host
port ( int ) : port""" | self . _loop . run_until_complete ( self . _configure_plugins ( ) )
web . run_app ( self . _app , host = host , port = port ) |
def build_conda_packages ( self ) :
"""Run the Linux build and use converter to build OSX""" | # # check if update is necessary
# if self . nversion = = self . pversion :
# raise SystemExit ( " Exited : new version = = existing version " )
# # tmp dir
bldir = "./tmp-bld"
if not os . path . exists ( bldir ) :
os . makedirs ( bldir )
# # iterate over builds
for pybuild in [ "2.7" , "3" ] : # # build and upload... |
def split_in_columns ( filterform , fields_per_column = None ) :
'''Return iterator that yields a column ( iterator too ) .
By default , flat field list is divided in columns with
fields _ per _ column elements in each ( fields _ per _ column is a
class attribute ) .''' | nfields = len ( filterform . fields )
if fields_per_column is None :
fields_per_column = filterform . fields_per_column
ncolumns , tail = divmod ( nfields , fields_per_column )
if tail > 0 :
ncolumns += 1
itr = iter ( filterform )
for _i in range ( ncolumns ) :
yield itertools . islice ( itr , fields_per_co... |
def receive_information_confirmation ( self , message ) :
"""A InformationConfirmation is received .
If : meth : ` the api version is supported
< AYABInterface . communication . Communication . api _ version _ is _ supported > ` ,
the communication object transitions into a
: class : ` InitializingMachine `... | if message . api_version_is_supported ( ) :
self . _next ( InitializingMachine )
else :
self . _next ( UnsupportedApiVersion )
self . _communication . controller = message |
def get_categorical_features_to_sampling ( examples , top_k ) :
"""Returns categorical features and a sampling of their most - common values .
The results of this slow function are used by the visualization repeatedly ,
so the results are cached .
Args :
examples : Examples to read to get feature samples . ... | observed_features = collections . defaultdict ( list )
# name - > [ value , ]
for example in examples :
for feature_name in get_categorical_feature_names ( example ) :
original_feature = parse_original_feature_from_example ( example , feature_name )
observed_features [ feature_name ] . extend ( orig... |
def dict_to_obj ( cls , dict_ , columns , row_columns , tab = '' , key_on = None ) :
""": param dict _ : dict of dict or dict of list
: param columns : list of strings to label the columns on print out
: param row _ columns : list of columns in the actually data
: param tab : str of the tab to use before the ... | if isinstance ( list ( dict_ . values ( ) ) [ 0 ] , dict ) :
row_columns = row_columns or columns or cls . _key_on_columns ( key_on , cls . _ordered_keys ( dict_ . values ( ) [ 0 ] ) )
column_index = cls . _create_column_index ( row_columns )
if key_on is None :
table = [ SeabornRow ( column_index ,... |
def add_name ( self , name_attr , space_attr , new_schema ) : # type : ( Text , Optional [ Text ] , NamedSchema ) - > Name
"""Add a new schema object to the name set .
@ arg name _ attr : name value read in schema
@ arg space _ attr : namespace value read in schema .
@ return : the Name that was just added ."... | to_add = Name ( name_attr , space_attr , self . default_namespace )
if to_add . fullname in VALID_TYPES :
fail_msg = '%s is a reserved type name.' % to_add . fullname
raise SchemaParseException ( fail_msg )
elif to_add . fullname in self . names :
fail_msg = 'The name "%s" is already in use.' % to_add . ful... |
def bk_black ( cls ) :
"Make the text background color black ." | wAttributes = cls . _get_text_attributes ( )
wAttributes &= ~ win32 . BACKGROUND_MASK
# wAttributes | = win32 . BACKGROUND _ BLACK
cls . _set_text_attributes ( wAttributes ) |
def readInstanceTag ( instanceID , tagName = "Name" , connection = None ) :
"""Load a tag from EC2
: param str instanceID : Instance ID to read the tag on
: param str tagName : Name of tag to load
: param connection : optional boto connection to use
: returns : the tag ' s value
: rtype : str""" | assert isinstance ( instanceID , basestring ) , ( "instanceID must be a string but is %r" % instanceID )
assert isinstance ( tagName , basestring ) , ( "tagName must be a string but is %r" % tagName )
if not connection : # Assume AWS credentials are in the environment or the instance is using an IAM role
connection... |
def send ( self , timeout = None ) :
"""Returns an event or None if no events occur before timeout .""" | if self . sigint_event and is_main_thread ( ) :
with ReplacedSigIntHandler ( self . sigint_handler ) :
return self . _send ( timeout )
else :
return self . _send ( timeout ) |
def set ( self , data_type , values ) :
"""Set the attribute value .
Args : :
data _ type : attribute data type ( see constants HC . xxx )
values : attribute value ( s ) ; specify a list to create
a multi - valued attribute ; a string valued
attribute can be created by setting ' data _ type '
to HC . CH... | try :
n_values = len ( values )
except :
values = [ values ]
n_values = 1
if data_type == HC . CHAR8 :
buf = _C . array_byte ( n_values )
# Allow values to be passed as a string .
# Noop if a list is passed .
values = list ( values )
for n in range ( n_values ) :
if not isinstanc... |
def save_bed ( cls , query , filename = sys . stdout ) :
"""write a bed12 file of the query .
Parameters
query : query
a table or query to save to file
filename : file
string or filehandle to write output""" | out = _open ( filename , 'w' )
for o in query :
out . write ( o . bed ( ) + '\n' ) |
def view ( self , rec ) :
'''View the page .''' | kwd = { 'pager' : '' , }
self . render ( 'wiki_page/page_view.html' , postinfo = rec , kwd = kwd , author = rec . user_name , format_date = tools . format_date , userinfo = self . userinfo , cfg = CMS_CFG ) |
def _process_tensor_event ( self , event , thresholds ) :
"""Converts a TensorEvent into a dict that encapsulates information on it .
Args :
event : The TensorEvent to convert .
thresholds : An array of floats that ranges from 0 to 1 ( in that
direction and inclusive of 0 and 1 ) .
Returns :
A JSON - ab... | return self . _make_pr_entry ( event . step , event . wall_time , tensor_util . make_ndarray ( event . tensor_proto ) , thresholds ) |
def sils_cut ( T , f , c , d , h ) :
"""solve _ sils - - solve the lot sizing problem with cutting planes
- start with a relaxed model
- add cuts until there are no fractional setup variables
Parameters :
- T : number of periods
- P : set of products
- f [ t ] : set - up costs ( on period t )
- c [ t ... | Ts = range ( 1 , T + 1 )
model = sils ( T , f , c , d , h )
y , x , I = model . data
# relax integer variables
for t in Ts :
y [ t ] . vtype = "C"
# compute D [ i , j ] = sum _ { t = i } ^ j d [ t ]
D = { }
for t in Ts :
s = 0
for j in range ( t , T + 1 ) :
s += d [ j ]
D [ t , j ] = s
EPS =... |
def getFaxStatsCounters ( self ) :
"""Query Asterisk Manager Interface for Fax Stats .
CLI Command - fax show stats
@ return : Dictionary of fax stats .""" | if not self . hasFax ( ) :
return None
info_dict = { }
cmdresp = self . executeCommand ( 'fax show stats' )
ctxt = 'general'
for section in cmdresp . strip ( ) . split ( '\n\n' ) [ 1 : ] :
i = 0
for line in section . splitlines ( ) :
mobj = re . match ( '(\S.*\S)\s*:\s*(\d+)\s*$' , line )
if... |
def start ( self ) :
"""Initiate the download .""" | log . info ( "Sending tftp download request to %s" % self . host )
log . info ( " filename -> %s" % self . file_to_transfer )
log . info ( " options -> %s" % self . options )
self . metrics . start_time = time . time ( )
log . debug ( "Set metrics.start_time to %s" % self . metrics . start_time )
# FIXME : put th... |
def longitude ( value ) :
""": param value : input string
: returns : longitude float , rounded to 5 digits , i . e . 1 meter maximum
> > > longitude ( ' 0.123456 ' )
0.12346""" | lon = round ( float_ ( value ) , 5 )
if lon > 180. :
raise ValueError ( 'longitude %s > 180' % lon )
elif lon < - 180. :
raise ValueError ( 'longitude %s < -180' % lon )
return lon |
def build_vars ( path = None ) :
"""Build initial vars .""" | init_vars = { "__name__" : "__main__" , "__package__" : None , "reload" : reload , }
if path is not None :
init_vars [ "__file__" ] = fixpath ( path )
# put reserved _ vars in for auto - completion purposes
for var in reserved_vars :
init_vars [ var ] = None
return init_vars |
def get_user ( self , name ) :
"""Finds the user in this instance with the specified name , and
returns a CloudDatabaseUser object . If no match is found , a
NoSuchDatabaseUser exception is raised .""" | try :
return self . _user_manager . get ( name )
except exc . NotFound :
raise exc . NoSuchDatabaseUser ( "No user by the name '%s' exists." % name ) |
def _plot_figure ( self , idx , fig_format = 'json' ) :
"""Returns the figure in html format on the
first call and""" | self . plot . update ( idx )
if self . embed :
patch = self . renderer . diff ( self . plot , binary = False )
msg = serialize_json ( dict ( content = patch . content , root = self . plot . state . _id ) )
return msg |
def get_app_key ( self ) :
"""If app _ key is not provided will look in environment
variables for username .""" | if self . app_key is None :
if os . environ . get ( self . username ) :
self . app_key = os . environ . get ( self . username )
else :
raise AppKeyError ( self . username ) |
def zforce ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
zforce
PURPOSE :
evaluate the vertical force F _ z ( R , z , t )
INPUT :
R - Cylindrical Galactocentric radius ( can be Quantity )
z - vertical height ( can be Quantity )
phi - azimuth ( optional ; can be Quantity )
t - time ( optional ; ca... | return self . _zforce_nodecorator ( R , z , phi = phi , t = t ) |
def match ( self , models , results , relation ) :
"""Match the eagerly loaded results to their parents .
: type models : list
: type results : Collection
: type relation : str""" | return self . match_many ( models , results , relation ) |
def compute_jackson_cheby_coeff ( filter_bounds , delta_lambda , m ) :
r"""To compute the m + 1 coefficients of the polynomial approximation of an ideal band - pass between a and b , between a range of values defined by lambda _ min and lambda _ max .
Parameters
filter _ bounds : list
[ a , b ]
delta _ lamb... | # Parameters check
if delta_lambda [ 0 ] > filter_bounds [ 0 ] or delta_lambda [ 1 ] < filter_bounds [ 1 ] :
_logger . error ( "Bounds of the filter are out of the lambda values" )
raise ( )
elif delta_lambda [ 0 ] > delta_lambda [ 1 ] :
_logger . error ( "lambda_min is greater than lambda_max" )
raise ... |
def predict ( self , X ) :
"""Predict risk scores .
Parameters
X : array - like , shape = ( n _ samples , n _ features )
Data matrix .
Returns
risk _ score : array , shape = ( n _ samples , )
Predicted risk scores .""" | check_is_fitted ( self , 'estimators_' )
if X . shape [ 1 ] != self . n_features_ :
raise ValueError ( 'Dimensions of X are inconsistent with training data: ' 'expected %d features, but got %s' % ( self . n_features_ , X . shape [ 1 ] ) )
n_samples = X . shape [ 0 ]
Xi = numpy . column_stack ( ( numpy . ones ( n_sa... |
def db_putHex ( self , db_name , key , value ) :
"""https : / / github . com / ethereum / wiki / wiki / JSON - RPC # db _ puthex
DEPRECATED""" | warnings . warn ( 'deprecated' , DeprecationWarning )
if not value . startswith ( '0x' ) :
value = add_0x ( value )
return ( yield from self . rpc_call ( 'db_putHex' , [ db_name , key , value ] ) ) |
def friedrich_coefficients ( x , param ) :
"""Coefficients of polynomial : math : ` h ( x ) ` , which has been fitted to
the deterministic dynamics of Langevin model
. . math : :
\dot{x}(t) = h(x(t)) + \mathcal{N}(0,R)
as described by [ 1 ] .
For short time - series this method is highly dependent on the ... | calculated = { }
# calculated is dictionary storing the calculated coefficients { m : { r : friedrich _ coefficients } }
res = { }
# res is a dictionary containg the results { " m _ 10 _ _ r _ 2 _ _ coeff _ 3 " : 15.43}
for parameter_combination in param :
m = parameter_combination [ 'm' ]
r = parameter_combina... |
def d2BinaryRochedx2 ( r , D , q , F ) :
"""Computes second derivative of the potential with respect to x .
@ param r : relative radius vector ( 3 components )
@ param D : instantaneous separation
@ param q : mass ratio
@ param F : synchronicity parameter""" | return ( 2 * r [ 0 ] * r [ 0 ] - r [ 1 ] * r [ 1 ] - r [ 2 ] * r [ 2 ] ) / ( r [ 0 ] * r [ 0 ] + r [ 1 ] * r [ 1 ] + r [ 2 ] * r [ 2 ] ) ** 2.5 + q * ( 2 * ( r [ 0 ] - D ) * ( r [ 0 ] - D ) - r [ 1 ] * r [ 1 ] - r [ 2 ] * r [ 2 ] ) / ( ( r [ 0 ] - D ) * ( r [ 0 ] - D ) + r [ 1 ] * r [ 1 ] + r [ 2 ] * r [ 2 ] ) ** 2.5 +... |
def _parse_phone_and_hash ( self , phone , phone_hash ) :
"""Helper method to both parse and validate phone and its hash .""" | phone = utils . parse_phone ( phone ) or self . _phone
if not phone :
raise ValueError ( 'Please make sure to call send_code_request first.' )
phone_hash = phone_hash or self . _phone_code_hash . get ( phone , None )
if not phone_hash :
raise ValueError ( 'You also need to provide a phone_code_hash.' )
return p... |
def comments ( self , case_id = None , variant_id = None , username = None ) :
"""Return comments for a case or variant .
Args :
case _ id ( str ) : id for a related case
variant _ id ( Optional [ str ] ) : id for a related variant""" | logger . debug ( "Looking for comments" )
comment_objs = self . query ( Comment )
if case_id :
comment_objs = comment_objs . filter_by ( case_id = case_id )
if variant_id :
comment_objs = comment_objs . filter_by ( variant_id = variant_id )
elif case_id :
comment_objs = comment_objs . filter_by ( variant_id... |
def json ( self , branch = 'master' , filename = '' ) :
"""Retrieve _ filename _ from GitLab .
Args :
branch ( str ) : Git Branch to find file .
filename ( str ) : Name of file to retrieve .
Returns :
dict : Decoded JSON .
Raises :
SystemExit : Invalid JSON provided .""" | file_contents = self . get ( branch = branch , filename = filename )
try :
json_dict = json . loads ( file_contents )
# TODO : Use json . JSONDecodeError when Python 3.4 has been deprecated
except ValueError as error :
msg = ( '"{filename}" appears to be invalid json. ' 'Please validate it with http://jsonlint.... |
def load_project ( cls , fname , auto_update = None , make_plot = True , draw = False , alternative_axes = None , main = False , encoding = None , enable_post = False , new_fig = True , clear = None , ** kwargs ) :
"""Load a project from a file or dict
This classmethod allows to load a project that has been store... | from pkg_resources import iter_entry_points
def get_ax_base ( name , alternatives ) :
ax_base = next ( iter ( obj ( arr_name = name ) . axes ) , None )
if ax_base is None :
ax_base = next ( iter ( obj ( arr_name = alternatives ) . axes ) , None )
if ax_base is not None :
alternatives . diffe... |
def load_images ( url , format = 'auto' , with_path = True , recursive = True , ignore_failure = True , random_order = False ) :
"""Loads images from a directory . JPEG and PNG images are supported .
Parameters
url : str
The string of the path where all the images are stored .
format : { ' PNG ' | ' JPG ' |... | from . . . import extensions as _extensions
from . . . util import _make_internal_url
return _extensions . load_images ( url , format , with_path , recursive , ignore_failure , random_order ) |
def _record_last_active ( self , host ) :
"""Put host first in our host list , so we try it first next time
The implementation of get _ active _ namenode relies on this reordering .""" | if host in self . hosts : # this check is for when user passes a host at request time
# Keep this thread safe : set hosts atomically and update it before the timestamp
self . hosts = [ host ] + [ h for h in self . hosts if h != host ]
self . _last_time_recorded_active = time . time ( ) |
def is_chinese ( name ) :
"""Check if a symbol is a Chinese character .
Note
Taken from http : / / stackoverflow . com / questions / 16441633 / python - 2-7 - test - if - characters - in - a - string - are - all - chinese - characters""" | if not name :
return False
for ch in name :
ordch = ord ( ch )
if not ( 0x3400 <= ordch <= 0x9fff ) and not ( 0x20000 <= ordch <= 0x2ceaf ) and not ( 0xf900 <= ordch <= ordch ) and not ( 0x2f800 <= ordch <= 0x2fa1f ) :
return False
return True |
def Insert ( self , index , rdfpathspec = None , ** kwarg ) :
"""Insert a single component at index .""" | if rdfpathspec is None :
rdfpathspec = self . __class__ ( ** kwarg )
if index == 0 : # Copy ourselves to a temp copy .
nested_proto = self . __class__ ( )
nested_proto . SetRawData ( self . GetRawData ( ) )
# Replace ourselves with the new object .
self . SetRawData ( rdfpathspec . GetRawData ( ) )
... |
def update_quota ( self , project_id , body = None ) :
"""Update a project ' s quotas .""" | return self . put ( self . quota_path % ( project_id ) , body = body ) |
def append ( self , name , value ) :
"""Appends the given value to the list variable with the given name .
: type name : string
: param name : The name of the variable .
: type value : object
: param value : The appended value .""" | if self . vars is None :
self . vars = { }
if name in self . vars :
self . vars [ name ] . append ( value )
else :
self . vars [ name ] = [ value ] |
def build_request ( self , input_data = None , * args , ** kwargs ) :
"""Builds request
: param input _ data :
: param args :
: param kwargs :
: return :""" | if input_data is not None :
self . input_data = input_data
if self . input_data is None :
raise ValueError ( 'Input data is None' )
if self . uo is None :
raise ValueError ( 'UO is None' )
self . request = RequestHolder ( )
self . request . nonce = get_random_vector ( EBConsts . FRESHNESS_NONCE_LEN )
self .... |
def value ( self ) :
"""Return current value for the metric""" | if self . buffer :
return np . mean ( [ ep [ 'l' ] for ep in self . buffer ] )
else :
return 0 |
def magic_contract ( * args , ** kwargs ) :
"""Drop - in replacement for ` ` pycontracts . contract ` ` decorator , except that it supports locally - visible types
: param args : Arguments to pass to the ` ` contract ` ` decorator
: param kwargs : Keyword arguments to pass to the ` ` contract ` ` decorator
: ... | def inner_decorator ( f ) :
for name , val in f . __globals__ . items ( ) :
if not name . startswith ( '_' ) and isinstance ( val , type ) :
safe_new_contract ( name , val )
return contract ( * args , ** kwargs ) ( f )
return inner_decorator |
def registerStatsHandler ( app , serverName , prefix = '/status/' ) :
"""Register the stats handler with a Flask app , serving routes
with a given prefix . The prefix defaults to ' / status / ' , which is
generally what you want .""" | if prefix [ - 1 ] != '/' :
prefix += '/'
handler = functools . partial ( statsHandler , serverName )
app . add_url_rule ( prefix , 'statsHandler' , handler , methods = [ 'GET' ] )
app . add_url_rule ( prefix + '<path:path>' , 'statsHandler' , handler , methods = [ 'GET' ] ) |
def insert_file ( self , file ) :
"""insert _ file ( file )
Load resources entries from FILE , and insert them into the
database . FILE can be a filename ( a string ) or a file object .""" | if type ( file ) is bytes :
file = open ( file , 'r' )
self . insert_string ( file . read ( ) ) |
def _postback ( self ) :
"""Perform PayPal Postback validation .""" | return requests . post ( self . get_endpoint ( ) , data = b"cmd=_notify-validate&" + self . query . encode ( "ascii" ) ) . content |
def wrap ( cls , value ) :
'''Some property types need to wrap their values in special containers , etc .''' | if isinstance ( value , dict ) :
if isinstance ( value , PropertyValueColumnData ) :
return value
else :
return PropertyValueColumnData ( value )
else :
return value |
def all_announcements_view ( request ) :
'''The view of manager announcements .''' | page_name = "Archives - All Announcements"
userProfile = UserProfile . objects . get ( user = request . user )
announcement_form = None
manager_positions = Manager . objects . filter ( incumbent = userProfile )
if manager_positions :
announcement_form = AnnouncementForm ( request . POST if "post_announcement" in re... |
def BulkLabel ( label , hostnames , owner = None , token = None , client_index = None ) :
"""Assign a label to a group of clients based on hostname .
Sets a label as an identifier to a group of clients . Removes the label from
other clients .
This can be used to automate labeling clients based on externally d... | if client_index is None :
client_index = CreateClientIndex ( token = token )
fqdns = set ( )
for hostname in hostnames :
fqdns . add ( hostname . lower ( ) )
labelled_urns = client_index . LookupClients ( [ "+label:%s" % label ] )
# If a labelled client fqdn isn ' t in the set of target fqdns remove the label .... |
def withRange ( cls , minimum , maximum ) :
"""Creates a subclass with value range constraint .""" | class X ( cls ) :
subtypeSpec = cls . subtypeSpec + constraint . ValueRangeConstraint ( minimum , maximum )
X . __name__ = cls . __name__
return X |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.