signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def find_multiple ( line , lookup ) :
"""regexp search with one value to return .
: param line : Line
: param lookup : regexp
: return : List of match groups or False""" | match = re . search ( lookup , line )
if match :
ret = [ ]
for i in range ( 1 , len ( match . groups ( ) ) + 1 ) :
ret . append ( match . group ( i ) )
if ret :
return ret
return False |
def receive_promise ( self , msg ) :
'''Returns an Accept messages if a quorum of Promise messages is achieved''' | self . observe_proposal ( msg . proposal_id )
if not self . leader and msg . proposal_id == self . proposal_id and msg . from_uid not in self . promises_received :
self . promises_received . add ( msg . from_uid )
if self . highest_accepted_id is None or msg . last_accepted_id > self . highest_accepted_id :
... |
def exec_cmd ( self , command , ** kwargs ) :
"""Wrapper method that can be changed in the inheriting classes .""" | self . _is_allowed_command ( command )
self . _check_command_parameters ( ** kwargs )
return self . _exec_cmd ( command , ** kwargs ) |
def coordinate ( self , panes = [ ] , index = 0 ) :
"""Update pane coordinate tuples based on their height and width relative to other panes
within the dimensions of the current window .
We account for panes with a height of 1 where the bottom coordinates are the same as the top .
Account for floating panes a... | y = 0
# height
for i , element in enumerate ( self . panes ) :
x = 0
# width
if isinstance ( element , list ) :
current_height = 0
for j , pane in enumerate ( element ) :
if pane . hidden :
continue
current_width = pane . width
current_heig... |
def consumer_process_task ( processor , log_groups , check_point_tracker ) :
"""return TaskResult if failed ,
return ProcessTaskResult if succeed
: param processor :
: param log _ groups :
: param check _ point _ tracker :
: return :""" | try :
check_point = processor . process ( log_groups , check_point_tracker )
check_point_tracker . flush_check ( )
except Exception as e :
return TaskResult ( e )
return ProcessTaskResult ( check_point ) |
def _setup ( self ) :
"""Perform initial setup of the settings class , such as getting the settings module and setting the settings""" | settings_module = None
# Get the settings module from the environment variables
try :
settings_module = os . environ [ global_settings . MODULE_VARIABLE ]
except KeyError :
error_message = "Settings not properly configured. Cannot find the environment variable {0}" . format ( global_settings . MODULE_VARIABLE ... |
def __field_to_parameter_type_and_format ( self , field ) :
"""Converts the field variant type into a tuple describing the parameter .
Args :
field : An instance of a subclass of messages . Field .
Returns :
A tuple with the type and format of the field , respectively .
Raises :
TypeError : if the field... | # We use lowercase values for types ( e . g . ' string ' instead of ' STRING ' ) .
variant = field . variant
if variant == messages . Variant . MESSAGE :
raise TypeError ( 'A message variant can\'t be used in a parameter.' )
# Note that the 64 - bit integers are marked as strings - - this is to
# accommodate JavaSc... |
def _create_subviews ( path , corpus ) :
"""Load the subviews based on testing _ list . txt and validation _ list . txt""" | test_list_path = os . path . join ( path , 'testing_list.txt' )
dev_list_path = os . path . join ( path , 'validation_list.txt' )
test_list = textfile . read_separated_lines ( test_list_path , separator = '/' , max_columns = 2 )
dev_list = textfile . read_separated_lines ( dev_list_path , separator = '/' , max_columns ... |
def parseValue ( self , value ) :
"""Parse the given value and return result .""" | if self . isVector ( ) :
return list ( map ( self . _pythonType , value . split ( ',' ) ) )
if self . typ == 'boolean' :
return _parseBool ( value )
return self . _pythonType ( value ) |
def prepare_task ( self , items ) :
"""Prepare scenario for impact function variable .
: param items : Dictionary containing settings for impact function .
: type items : Python dictionary .
: return : A tuple containing True and dictionary containing parameters
if post processor success . Or False and an e... | status = True
message = ''
# get hazard
if 'hazard' in items :
hazard_path = items [ 'hazard' ]
hazard = self . define_layer ( hazard_path )
if not hazard :
status = False
message = self . tr ( 'Unable to find {hazard_path}' ) . format ( hazard_path = hazard_path )
else :
hazard = None
... |
def l2_norm ( params ) :
"""Computes l2 norm of params by flattening them into a vector .""" | flattened , _ = flatten ( params )
return np . dot ( flattened , flattened ) |
def _data_in_prefetch_buffers ( self , offset ) :
"""if a block of data is present in the prefetch buffers , at the given
offset , return the offset of the relevant prefetch buffer . otherwise ,
return None . this guarantees nothing about the number of bytes
collected in the prefetch buffer so far .""" | k = [ i for i in self . _prefetch_data . keys ( ) if i <= offset ]
if len ( k ) == 0 :
return None
index = max ( k )
buf_offset = offset - index
if buf_offset >= len ( self . _prefetch_data [ index ] ) : # it ' s not here
return None
return index |
def start_raylet ( redis_address , node_ip_address , raylet_name , plasma_store_name , worker_path , temp_dir , num_cpus = None , num_gpus = None , resources = None , object_manager_port = None , node_manager_port = None , redis_password = None , use_valgrind = False , use_profiler = False , stdout_file = None , stderr... | config = config or { }
config_str = "," . join ( [ "{},{}" . format ( * kv ) for kv in config . items ( ) ] )
if use_valgrind and use_profiler :
raise Exception ( "Cannot use valgrind and profiler at the same time." )
num_initial_workers = ( num_cpus if num_cpus is not None else multiprocessing . cpu_count ( ) )
st... |
def wait_for_import ( self , connection_id , wait_interval ) :
"""Wait until connection state is no longer ` ` IMPORT _ CONFIGURATION ` ` .
Args :
connection _ id ( str ) : Heroku Connect connection to monitor .
wait _ interval ( int ) : How frequently to poll in seconds .
Raises :
CommandError : If fetch... | self . stdout . write ( self . style . NOTICE ( 'Waiting for import' ) , ending = '' )
state = utils . ConnectionStates . IMPORT_CONFIGURATION
while state == utils . ConnectionStates . IMPORT_CONFIGURATION : # before you get the first state , the API can be a bit behind
self . stdout . write ( self . style . NOTICE... |
def type ( self ) :
"""Certificate type .
: return : The type of the certificate .
: rtype : CertificateType""" | if self . _device_mode == 1 or self . _type == CertificateType . developer :
return CertificateType . developer
elif self . _type == CertificateType . bootstrap :
return CertificateType . bootstrap
else :
return CertificateType . lwm2m |
def bookmark_list ( ) :
"""Executor for ` globus bookmark list `""" | client = get_client ( )
bookmark_iterator = client . bookmark_list ( )
def get_ep_name ( item ) :
ep_id = item [ "endpoint_id" ]
try :
ep_doc = client . get_endpoint ( ep_id )
return display_name_or_cname ( ep_doc )
except TransferAPIError as err :
if err . code == "EndpointDeleted" ... |
def refine ( video , episode_refiners = None , movie_refiners = None , ** kwargs ) :
"""Refine a video using : ref : ` refiners ` .
. . note : :
Exceptions raised in refiners are silently passed and logged .
: param video : the video to refine .
: type video : : class : ` ~ subliminal . video . Video `
: ... | refiners = ( )
if isinstance ( video , Episode ) :
refiners = episode_refiners or ( 'metadata' , 'tvdb' , 'omdb' )
elif isinstance ( video , Movie ) :
refiners = movie_refiners or ( 'metadata' , 'omdb' )
for refiner in refiners :
logger . info ( 'Refining video with %s' , refiner )
try :
refiner... |
def listFiles ( self , dataset = "" , block_name = "" , logical_file_name = "" , release_version = "" , pset_hash = "" , app_name = "" , output_module_label = "" , run_num = - 1 , origin_site_name = "" , lumi_list = "" , detail = False , validFileOnly = 0 , sumOverLumi = 0 ) :
"""API to list files in DBS . Either n... | logical_file_name = logical_file_name . replace ( "*" , "%" )
release_version = release_version . replace ( "*" , "%" )
pset_hash = pset_hash . replace ( "*" , "%" )
app_name = app_name . replace ( "*" , "%" )
block_name = block_name . replace ( "*" , "%" )
origin_site_name = origin_site_name . replace ( "*" , "%" )
da... |
def before_first_request ( self , fn ) :
"""Registers a function to be run before the first request to this
instance of the application .
The function will be called without any arguments and its return
value is ignored .""" | self . _defer ( lambda app : app . before_first_request ( fn ) )
return fn |
def setStartAction ( self , action , * args , ** kwargs ) :
"""Set a function to call when run ( ) is called , before the main action is called .
Parameters
action : function pointer
The function to call .
* args
Positional arguments to pass to action .
* * kwargs :
Keyword arguments to pass to action... | self . init_action = action
self . init_args = args
self . init_kwargs = kwargs |
def on_btn_demag_gui ( self , event ) :
"""Open Demag GUI""" | if not self . check_for_meas_file ( ) :
return
if not self . check_for_uncombined_files ( ) :
return
outstring = "demag_gui.py -WD %s" % self . WD
print ( "-I- running python script:\n %s" % ( outstring ) )
if self . data_model_num == 2 :
demag_gui . start ( self . WD , standalone_app = False , parent = sel... |
def yaw ( self ) :
"""Calculates the Yaw of the Quaternion .""" | x , y , z , w = self . x , self . y , self . z , self . w
return math . asin ( 2 * x * y + 2 * z * w ) |
def convert_data_to_dtype ( data , data_type , mot_float_type = 'float' ) :
"""Convert the given input data to the correct numpy type .
Args :
data ( ndarray ) : The value to convert to the correct numpy type
data _ type ( str ) : the data type we need to convert the data to
mot _ float _ type ( str ) : the... | scalar_dtype = ctype_to_dtype ( data_type , mot_float_type )
if isinstance ( data , numbers . Number ) :
data = scalar_dtype ( data )
if is_vector_ctype ( data_type ) :
shape = data . shape
dtype = ctype_to_dtype ( data_type , mot_float_type )
ve = np . zeros ( shape [ : - 1 ] , dtype = dtype )
if l... |
def quantile_normalize ( matrix , inplace = False , target = None ) :
"""Quantile normalization , allowing for missing values ( NaN ) .
In case of nan values , this implementation will calculate evenly
distributed quantiles and fill in the missing data with those values .
Quantile normalization is then perfor... | assert isinstance ( matrix , ExpMatrix )
assert isinstance ( inplace , bool )
if target is not None :
assert isinstance ( target , np . ndarray ) and np . issubdtype ( target . dtype , np . float )
if not inplace : # make a copy of the original data
matrix = matrix . copy ( )
X = matrix . X
_ , n = X . shape
na... |
def _apply_scope ( self , scope , builder ) :
"""Apply a single scope on the given builder instance .
: param scope : The scope to apply
: type scope : callable or Scope
: param builder : The builder to apply the scope to
: type builder : Builder""" | if callable ( scope ) :
scope ( builder )
elif isinstance ( scope , Scope ) :
scope . apply ( builder , self . get_model ( ) ) |
def are_none ( sequences : Sequence [ Sized ] ) -> bool :
"""Returns True if all sequences are None .""" | if not sequences :
return True
return all ( s is None for s in sequences ) |
def build_server_from_config ( config , section_name , server_klass = None , handler_klass = None ) :
"""Build a server from a provided : py : class : ` configparser . ConfigParser `
instance . If a ServerClass or HandlerClass is specified , then the
object must inherit from the corresponding AdvancedHTTPServer... | server_klass = ( server_klass or AdvancedHTTPServer )
handler_klass = ( handler_klass or RequestHandler )
port = config . getint ( section_name , 'port' )
web_root = None
if config . has_option ( section_name , 'web_root' ) :
web_root = config . get ( section_name , 'web_root' )
if config . has_option ( section_nam... |
def PlaceSOffsetT ( self , x ) :
"""PlaceSOffsetT prepends a SOffsetT to the Builder , without checking
for space .""" | N . enforce_number ( x , N . SOffsetTFlags )
self . head = self . head - N . SOffsetTFlags . bytewidth
encode . Write ( packer . soffset , self . Bytes , self . Head ( ) , x ) |
def run ( self , cmdline_args = None , program_name = "start_service" , version = workflows . version ( ) , ** kwargs ) :
"""Example command line interface to start services .
: param cmdline _ args : List of command line arguments to pass to parser
: param program _ name : Name of the command line tool to disp... | # Enumerate all known services
known_services = workflows . services . get_known_services ( )
# Set up parser
parser = OptionParser ( usage = program_name + " [options]" if program_name else None , version = version )
parser . add_option ( "-?" , action = "help" , help = SUPPRESS_HELP )
parser . add_option ( "-s" , "--... |
def get_taxids ( list_of_names ) :
"""> > > mylist = [ ' Arabidopsis thaliana ' , ' Carica papaya ' ]
> > > get _ taxids ( mylist )
[1 , 2]""" | from jcvi . apps . fetch import batch_taxids
return [ int ( x ) for x in batch_taxids ( list_of_names ) ] |
def istext ( somestr ) :
"""Checks that some string is a text
: param str somestr :
It is some string that will be checked for text .
The text is string that contains only words or special words such as preposition
( what is the word and the special word see at help ( palindromus . isword ) and help ( palin... | # check invalid data types
OnlyStringsCanBeChecked ( somestr )
# get all matches
matches = re . findall ( r'\w+' , somestr . strip ( ) , flags = re . IGNORECASE | re . MULTILINE )
if not len ( matches ) :
return False
else :
for match in matches :
if match . find ( "_" ) >= 0 or ( not isspecword ( match... |
def process_link ( self , env , refnode , has_explicit_title , title , target ) :
"""This handles some special cases for reference links in . NET
First , the standard Sphinx reference syntax of ` ` : ref : ` Title < Link > ` ` ` ,
where a reference to ` ` Link ` ` is created with title ` ` Title ` ` , causes
... | result = super ( DotNetXRefRole , self ) . process_link ( env , refnode , has_explicit_title , title , target )
( title , target ) = result
if not has_explicit_title : # If the first character is a tilde , don ' t display the parent name
title = title . lstrip ( '.' )
target = target . lstrip ( '~' )
if tit... |
def safe_expand ( template , mapping ) :
"""Safe string template expansion . Raises an error if the provided substitution mapping has circularities .""" | for _ in range ( len ( mapping ) + 1 ) :
_template = template
template = string . Template ( template ) . safe_substitute ( mapping )
if template == _template :
return template
else :
raise ValueError ( "circular mapping provided!" ) |
def greater ( lhs , rhs ) :
"""Returns the result of element - wise * * greater than * * ( > ) comparison operation
with broadcasting .
For each element in input arrays , return 1 ( true ) if lhs elements are greater than rhs ,
otherwise return 0 ( false ) .
Equivalent to ` ` lhs > rhs ` ` and ` ` mx . nd .... | # pylint : disable = no - member , protected - access
return _ufunc_helper ( lhs , rhs , op . broadcast_greater , lambda x , y : 1 if x > y else 0 , _internal . _greater_scalar , _internal . _lesser_scalar ) |
def hatnotes ( self ) :
"""list : Parse hatnotes from the HTML
Note :
Not settable
Note :
Side effect is to also pull the html which can be slow
Note :
This is a parsing operation and not part of the standard API""" | if self . _hatnotes is None :
self . _hatnotes = list ( )
soup = BeautifulSoup ( self . html , "html.parser" )
notes = soup . findAll ( "" , { "class" : "hatnote" } )
if notes is not None :
for note in notes :
tmp = list ( )
for child in note . children :
... |
def serialize ( self , path ) :
"""Saves the raw ( read unsmoothed ) histogram data to the given path using
pickle python module .""" | pickle . dump ( [ self . x , self . y_raw ] , file ( path , 'w' ) ) |
def multi_to_dict ( multi ) :
'''Transform a Werkzeug multidictionnary into a flat dictionnary''' | return dict ( ( key , value [ 0 ] if len ( value ) == 1 else value ) for key , value in multi . to_dict ( False ) . items ( ) ) |
def read_td_query ( query , engine , index_col = None , parse_dates = None , distributed_join = False , params = None ) :
'''Read Treasure Data query into a DataFrame .
Returns a DataFrame corresponding to the result set of the query string .
Optionally provide an index _ col parameter to use one of the columns... | if params is None :
params = { }
# header
header = engine . create_header ( "read_td_query" )
if engine . type == 'presto' and distributed_join is not None :
header += "-- set session distributed_join = '{0}'\n" . format ( 'true' if distributed_join else 'false' )
# execute
r = engine . execute ( header + query... |
def height ( self ) :
"""Returns height of the ( sub ) tree , without considering
empty leaf - nodes
> > > create ( dimensions = 2 ) . height ( )
> > > create ( [ ( 1 , 2 ) ] ) . height ( )
> > > create ( [ ( 1 , 2 ) , ( 2 , 3 ) ] ) . height ( )""" | min_height = int ( bool ( self ) )
return max ( [ min_height ] + [ c . height ( ) + 1 for c , p in self . children ] ) |
def radec2azel ( ra_deg : float , dec_deg : float , lat_deg : float , lon_deg : float , time : datetime ) -> Tuple [ float , float ] :
"""converts right ascension , declination to azimuth , elevation
Parameters
ra _ deg : float or numpy . ndarray of float
right ascension to target [ degrees ]
dec _ deg : fl... | ra = atleast_1d ( ra_deg )
dec = atleast_1d ( dec_deg )
lat = atleast_1d ( lat_deg )
lon = atleast_1d ( lon_deg )
if ra . shape != dec . shape :
raise ValueError ( 'az and el must be same shape ndarray' )
if not ( lat . size == 1 and lon . size == 1 ) :
raise ValueError ( 'need one observer and one or more (az... |
def get_std_dev_area ( self , mag , rake ) :
"""Standard deviation for WC1994 . Magnitude is ignored .""" | assert rake is None or - 180 <= rake <= 180
if rake is None : # their " All " case
return 0.24
elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : # strike slip
return 0.22
elif rake > 0 : # thrust / reverse
return 0.26
else : # normal
return 0.22 |
def par_compute_residuals ( i ) :
"""Compute components of the residual and stopping thresholds that
can be done in parallel .
Parameters
i : int
Index of group to compute""" | # Compute the residuals in parallel , need to check if the residuals
# depend on alpha
global mp_ry0
global mp_ry1
global mp_sy0
global mp_sy1
global mp_nrmAx
global mp_nrmBy
global mp_nrmu
mp_ry0 [ i ] = np . sum ( ( mp_DXnr [ i ] - mp_Y0 [ i ] ) ** 2 )
mp_ry1 [ i ] = mp_alpha ** 2 * np . sum ( ( mp_Xnr [ mp_grp [ i ]... |
def partes ( self , num_partes = 11 ) :
"""Particiona a chave do CF - e - SAT em uma lista de * n * segmentos .
: param int num _ partes : O número de segmentos ( partes ) em que os digitos
da chave do CF - e - SAT serão particionados . * * Esse número deverá
resultar em uma divisão inteira por 44 ( o co... | assert 44 % num_partes == 0 , 'O numero de partes nao produz um ' 'resultado inteiro (partes por 44 digitos): ' 'num_partes=%s' % num_partes
salto = 44 // num_partes
return [ self . _campos [ n : ( n + salto ) ] for n in range ( 0 , 44 , salto ) ] |
def makeExtensionLoginMethod ( extensionKey ) :
'''Return a function that will call the vim . SessionManager . Login ( ) method
with the given parameters . The result of this function can be passed as
the " loginMethod " to a SessionOrientedStub constructor .''' | def _doLogin ( soapStub ) :
si = vim . ServiceInstance ( "ServiceInstance" , soapStub )
sm = si . content . sessionManager
if not sm . currentSession :
si . content . sessionManager . LoginExtensionByCertificate ( extensionKey )
return _doLogin |
def get_next_objective_bank ( self ) :
"""Gets the next ObjectiveBank in this list .
return : ( osid . learning . ObjectiveBank ) - the next ObjectiveBank
in this list . The has _ next ( ) method should be used to
test that a next ObjectiveBank is available before
calling this method .
raise : IllegalStat... | try :
next_object = next ( self )
except StopIteration :
raise IllegalState ( 'no more elements available in this list' )
except Exception : # Need to specify exceptions here !
raise OperationFailed ( )
else :
return next_object |
def jinja_fragment_extension ( tag , endtag = None , name = None , tag_only = False , allow_args = True , callblock_args = None ) :
"""Decorator to easily create a jinja extension which acts as a fragment .""" | if endtag is None :
endtag = "end" + tag
def decorator ( f ) :
def parse ( self , parser ) :
lineno = parser . stream . next ( ) . lineno
args = [ ]
kwargs = [ ]
if allow_args :
args , kwargs = parse_block_signature ( parser )
call = self . call_method ( "supp... |
def gray2qimage ( gray , normalize = False ) :
"""Convert the 2D numpy array ` gray ` into a 8 - bit , indexed QImage _
with a gray colormap . The first dimension represents the vertical
image axis .
The parameter ` normalize ` can be used to normalize an image ' s
value range to 0 . . 255:
` normalize ` ... | if _np . ndim ( gray ) != 2 :
raise ValueError ( "gray2QImage can only convert 2D arrays" + " (try using array2qimage)" if _np . ndim ( gray ) == 3 else "" )
h , w = gray . shape
result = _qt . QImage ( w , h , _qt . QImage . Format_Indexed8 )
if not _np . ma . is_masked ( gray ) :
for i in range ( 256 ) :
... |
def add_cors_headers ( request , response ) :
"""Add cors headers needed for web app implementation .""" | response . headerlist . append ( ( 'Access-Control-Allow-Origin' , '*' ) )
response . headerlist . append ( ( 'Access-Control-Allow-Methods' , 'GET, OPTIONS' ) )
response . headerlist . append ( ( 'Access-Control-Allow-Headers' , ',' . join ( DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS ) ) ) |
def get_alerts_since ( self , timestamp ) :
"""Returns all the ` Alert ` objects of this ` Trigger ` that were fired since the specified timestamp .
: param timestamp : time object representing the point in time since when alerts have to be fetched
: type timestamp : int , ` ` datetime . datetime ` ` or ISO8601... | unix_timestamp = timeformatutils . to_UNIXtime ( timestamp )
result = [ ]
for alert in self . alerts :
if alert . last_update >= unix_timestamp :
result . append ( alert )
return result |
def log_to_parquet ( bro_log , parquet_file , compression = 'SNAPPY' , row_group_size = 1000000 ) :
"""write _ to _ parquet : Converts a Bro log into a Parquet file
Args :
bro _ log ( string : The full path to the bro log to be saved as a Parquet file
parquet _ file ( string ) : The full path to the filename ... | # Set up various parameters
current_row_set = [ ]
writer = None
num_rows = 0
# Spin up the bro reader on a given log file
reader = BroLogReader ( bro_log )
for num_rows , row in enumerate ( reader . readrows ( ) ) : # Append the row to the row set
current_row_set . append ( row )
# If we have enough rows add to... |
def build_query_uri ( self , start = 0 , count = - 1 , filter = '' , query = '' , sort = '' , view = '' , fields = '' , uri = None , scope_uris = '' ) :
"""Builds the URI given the parameters .
More than one request can be send to get the items , regardless the query parameter ' count ' , because the actual
num... | if filter :
filter = self . __make_query_filter ( filter )
if query :
query = "&query=" + quote ( query )
if sort :
sort = "&sort=" + quote ( sort )
if view :
view = "&view=" + quote ( view )
if fields :
fields = "&fields=" + quote ( fields )
if scope_uris :
scope_uris = "&scopeUris=" + quote ( ... |
def read_file ( filepath ) :
"""read the file""" | with io . open ( filepath , "r" ) as filepointer :
res = filepointer . read ( )
return res |
def from_sky ( cls , magnitudelimit = None ) :
'''Create a Constellation from a criteria search of the whole sky .
Parameters
magnitudelimit : float
Maximum magnitude ( for Ve = " estimated V " ) .''' | # define a query for cone search surrounding this center
criteria = { }
if magnitudelimit is not None :
criteria [ cls . defaultfilter + 'mag' ] = '<{}' . format ( magnitudelimit )
v = Vizier ( columns = cls . columns , column_filters = criteria )
v . ROW_LIMIT = - 1
# run the query
print ( 'querying Vizier for {},... |
def leehom_general_stats_table ( self ) :
"""Take the parsed stats from the leeHom report and add it to the
basic stats table at the top of the report""" | headers = { }
headers [ 'merged_trimming' ] = { 'title' : '{} Merged (Trimming)' . format ( config . read_count_prefix ) , 'description' : 'Merged clusters from trimming ({})' . format ( config . read_count_desc ) , 'min' : 0 , 'scale' : 'PuRd' , 'modify' : lambda x : x * config . read_count_multiplier , 'shared_key' :... |
def authenticate ( self , provider ) :
"""Starts OAuth authorization flow , will redirect to 3rd party site .""" | callback_url = url_for ( ".callback" , provider = provider , _external = True )
provider = self . get_provider ( provider )
session [ 'next' ] = request . args . get ( 'next' ) or ''
return provider . authorize ( callback_url ) |
def eigenvector_centrality_und ( CIJ ) :
'''Eigenector centrality is a self - referential measure of centrality :
nodes have high eigenvector centrality if they connect to other nodes
that have high eigenvector centrality . The eigenvector centrality of
node i is equivalent to the ith element in the eigenvect... | from scipy import linalg
n = len ( CIJ )
vals , vecs = linalg . eig ( CIJ )
i = np . argmax ( vals )
return np . abs ( vecs [ : , i ] ) |
def xorsum ( t ) :
"""异或校验
: param t :
: type t :
: return :
: rtype :""" | _b = t [ 0 ]
for i in t [ 1 : ] :
_b = _b ^ i
_b &= 0xff
return _b |
def put ( self , path , value ) :
"""Insert or update configuration key with value""" | return lib . zconfig_put ( self . _as_parameter_ , path , value ) |
def valid_string ( val ) :
"""Expects unicode
Char : : = # x9 | # xA | # xD | [ # x20 - # xD7FF ] | [ # xE000 - # xFFFD ] |
[ # x10000 - # x10FFFF ]""" | for char in val :
try :
char = ord ( char )
except TypeError :
raise NotValid ( "string" )
if char == 0x09 or char == 0x0A or char == 0x0D :
continue
elif 0x20 <= char <= 0xD7FF :
continue
elif 0xE000 <= char <= 0xFFFD :
continue
elif 0x10000 <= char <= 0x... |
def mean_oob_mae_weight ( trees ) :
"""Returns weights proportional to the out - of - bag mean absolute error for each tree .""" | weights = [ ]
active_trees = [ ]
for tree in trees :
oob_mae = tree . out_of_bag_mae
if oob_mae is None or oob_mae . mean is None :
continue
weights . append ( oob_mae . mean )
active_trees . append ( tree )
if not active_trees :
return
weights = normalize ( weights )
return zip ( weights , ... |
def search_references ( self , reference_set_id , accession = None , md5checksum = None ) :
"""Returns an iterator over the References fulfilling the specified
conditions from the specified Dataset .
: param str reference _ set _ id : The ReferenceSet to search .
: param str accession : If not None , return t... | request = protocol . SearchReferencesRequest ( )
request . reference_set_id = reference_set_id
request . accession = pb . string ( accession )
request . md5checksum = pb . string ( md5checksum )
request . page_size = pb . int ( self . _page_size )
return self . _run_search_request ( request , "references" , protocol . ... |
def post_versions_undo ( self , version_id ) :
"""Undo post version ( Requires login ) ( UNTESTED ) .
Parameters :
version _ id ( int ) :""" | return self . _get ( 'post_versions/{0}/undo.json' . format ( version_id ) , method = 'PUT' , auth = True ) |
def resize ( self , size , interp = 'nearest' ) :
"""Resize the image .
Parameters
size : int , float , or tuple
* int - Percentage of current size .
* float - Fraction of current size .
* tuple - Size of the output image .
interp : : obj : ` str ` , optional
Interpolation to use for re - sizing ( ' n... | resized_data = sm . imresize ( self . data , size , interp = interp , mode = 'L' )
return SegmentationImage ( resized_data , self . _frame ) |
def url_escape ( value , plus = True ) :
"""Returns a URL - encoded version of the given value .
If ` ` plus ` ` is true ( the default ) , spaces will be represented
as " + " instead of " % 20 " . This is appropriate for query strings
but not for the path component of a URL . Note that this default
is the r... | quote = urllib_parse . quote_plus if plus else urllib_parse . quote
return quote ( utf8 ( value ) ) |
def password_attributes_max_lockout_duration ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
password_attributes = ET . SubElement ( config , "password-attributes" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" )
max_lockout_duration = ET . SubElement ( password_attributes , "max-lockout-duration" )
max_lockout_duration . text = kwargs . pop ( 'max_lockout_duration' )
callback ... |
def pre_save ( self , * args , ** kwargs ) :
"Returns field ' s value just before saving ." | value = super ( CharField , self ) . pre_save ( * args , ** kwargs )
return self . get_prep_value ( value ) |
def generate ( command , name , init_system , overwrite , deploy , start , verbose , ** params ) :
"""Create a service .
` COMMAND ` is the path to the executable to run""" | # TODO : Add a ` prefix ` flag which can be used to prefix
# ` COMMAND ` with ` su - c ` , etc . .
try :
Serv ( init_system , verbose = verbose ) . generate ( command , name , overwrite , deploy , start , ** params )
except ServError as ex :
sys . exit ( ex ) |
def reduce ( self , start = 0 , end = None ) :
"""Returns result of applying ` self . operation `
to a contiguous subsequence of the array .
self . operation (
arr [ start ] , operation ( arr [ start + 1 ] , operation ( . . . arr [ end ] ) ) )
Parameters
start : int
beginning of the subsequence
end : ... | if end is None :
end = self . _capacity - 1
if end < 0 :
end += self . _capacity
return self . _reduce_helper ( start , end , 1 , 0 , self . _capacity - 1 ) |
def get ( self , * , kind : Type = None , tag : Hashable = None , ** _ ) -> Iterator :
"""Get an iterator of objects by kind or tag .
kind : Any type . Pass to get a subset of contained items with the given
type .
tag : Any Hashable object . Pass to get a subset of contained items with
the given tag .
Pas... | if kind is None and tag is None :
raise TypeError ( "get() takes at least one keyword-only argument. 'kind' or 'tag'." )
kinds = self . all
tags = self . all
if kind is not None :
kinds = self . kinds [ kind ]
if tag is not None :
tags = self . tags [ tag ]
return ( x for x in kinds . intersection ( tags ) ... |
def _BernII_to_Flavio_II ( C , udlnu , parameters ) :
"""From BernII to FlavioII basis
for charged current process semileptonic operators .
` udlnu ` should be of the form ' udl _ enu _ tau ' , ' cbl _ munu _ e ' etc .""" | p = parameters
u = uflav [ udlnu [ 0 ] ]
d = dflav [ udlnu [ 1 ] ]
l = lflav [ udlnu [ 4 : udlnu . find ( 'n' ) ] ]
lp = lflav [ udlnu [ udlnu . find ( '_' , 5 ) + 1 : len ( udlnu ) ] ]
ind = udlnu [ 0 ] + udlnu [ 1 ] + udlnu [ 4 : udlnu . find ( 'n' ) ] + udlnu [ udlnu . find ( '_' , 5 ) + 1 : len ( udlnu ) ]
ind2 = u... |
def __fieldNorm ( self , fieldName ) :
"""Normalizes a dbf field name to fit within the spec and the
expectations of certain ESRI software .""" | if len ( fieldName ) > 11 :
fieldName = fieldName [ : 11 ]
fieldName = fieldName . upper ( )
fieldName . replace ( ' ' , '_' ) |
def fix ( self ) :
"""Return a version of the source code with PEP 8 violations fixed .""" | pep8_options = { 'ignore' : self . options . ignore , 'select' : self . options . select , 'max_line_length' : self . options . max_line_length , 'hang_closing' : self . options . hang_closing , }
results = _execute_pep8 ( pep8_options , self . source )
if self . options . verbose :
progress = { }
for r in resu... |
def job_success_message ( self , job , queue , job_result ) :
"""Return the message to log when a job is successful""" | return '[%s|%s|%s] success, in %s' % ( queue . _cached_name , job . pk . get ( ) , job . _cached_identifier , job . duration ) |
def _send_cmd ( self , cmd : str ) :
"""Encode IQFeed API messages .""" | self . _sock . sendall ( cmd . encode ( encoding = 'latin-1' , errors = 'strict' ) ) |
def parse_bss ( bss ) :
"""Parse data prepared by nla _ parse ( ) and nla _ parse _ nested ( ) into Python - friendly formats .
Automatically chooses the right data - type for each attribute and converts it into Python integers , strings , unicode ,
etc objects .
Positional arguments :
bss - - dictionary wi... | # First parse data into Python data types . Weed out empty values .
intermediate = dict ( )
_get ( intermediate , bss , 'NL80211_BSS_BSSID' , libnl . attr . nla_data )
# MAC address of access point .
_get ( intermediate , bss , 'NL80211_BSS_FREQUENCY' , libnl . attr . nla_get_u32 )
# Frequency in MHz .
_get ( intermedi... |
def pclass_field_for_attribute ( self ) :
""": return : A pyrsistent field reflecting this attribute and its type model .""" | return self . type_model . pclass_field_for_type ( required = self . required , default = self . default , ) |
def next_frame_sv2p_tiny ( ) :
"""Tiny SV2P model .""" | hparams = next_frame_sv2p_atari_softmax ( )
hparams . batch_size = 2
hparams . tiny_mode = True
hparams . num_masks = 1
hparams . video_modality_loss_cutoff = 0.4
hparams . video_num_input_frames = 4
hparams . video_num_target_frames = 4
return hparams |
def declare_consumer ( self , queue , no_ack , callback , consumer_tag , nowait = False ) :
"""Declare a consumer .""" | @ functools . wraps ( callback )
def _callback_decode ( channel , method , header , body ) :
return callback ( ( channel , method , header , body ) )
return self . channel . basic_consume ( _callback_decode , queue = queue , no_ack = no_ack , consumer_tag = consumer_tag ) |
def simulated_quantize ( x , num_bits , noise ) :
"""Simulate quantization to num _ bits bits , with externally - stored scale .
num _ bits is the number of bits used to store each value .
noise is a float32 Tensor containing values in [ 0 , 1 ) .
Each value in noise should take different values across
diff... | shape = x . get_shape ( ) . as_list ( )
if not ( len ( shape ) >= 2 and shape [ - 1 ] > 1 ) :
return x
max_abs = tf . reduce_max ( tf . abs ( x ) , - 1 , keepdims = True ) + 1e-9
max_int = 2 ** ( num_bits - 1 ) - 1
scale = max_abs / max_int
x /= scale
x = tf . floor ( x + noise )
# dequantize before storing ( since... |
def yubiotp ( ctx , slot , public_id , private_id , key , no_enter , force , serial_public_id , generate_private_id , generate_key ) :
"""Program a Yubico OTP credential .""" | dev = ctx . obj [ 'dev' ]
controller = ctx . obj [ 'controller' ]
if public_id and serial_public_id :
ctx . fail ( 'Invalid options: --public-id conflicts with ' '--serial-public-id.' )
if private_id and generate_private_id :
ctx . fail ( 'Invalid options: --private-id conflicts with ' '--generate-public-id.' )... |
def weights_multi_problem ( labels , taskid = - 1 ) :
"""Assign weight 1.0 to only the " targets " portion of the labels .
Weight 1.0 is assigned to all labels past the taskid .
Args :
labels : A Tensor of int32s .
taskid : an int32 representing the task id for a problem .
Returns :
A Tensor of floats .... | taskid = check_nonnegative ( taskid )
past_taskid = tf . cumsum ( to_float ( tf . equal ( labels , taskid ) ) , axis = 1 )
# Additionally zero out the task id location
past_taskid *= to_float ( tf . not_equal ( labels , taskid ) )
non_taskid = to_float ( labels )
return to_float ( tf . not_equal ( past_taskid * non_tas... |
def move_leadership ( self , partition , new_leader ) :
"""Return a new state that is the result of changing the leadership of
a single partition .
: param partition : The partition index of the partition to change the
leadership of .
: param new _ leader : The broker index of the new leader replica .""" | new_state = copy ( self )
# Update the partition replica tuple
source = new_state . replicas [ partition ] [ 0 ]
new_leader_index = self . replicas [ partition ] . index ( new_leader )
new_state . replicas = tuple_alter ( self . replicas , ( partition , lambda replicas : tuple_replace ( replicas , ( 0 , replicas [ new_... |
def reset ( self ) :
"Close the current failed connection and prepare for a new one" | log . info ( "resetting client" )
rpc_client = self . _rpc_client
self . _addrs . append ( self . _peer . addr )
self . __init__ ( self . _addrs )
self . _rpc_client = rpc_client
self . _dispatcher . rpc_client = rpc_client
rpc_client . _client = weakref . ref ( self ) |
def ensure_rng ( random_state = None ) :
"""Creates a random number generator based on an optional seed . This can be
an integer or another random state for a seeded rng , or None for an
unseeded rng .""" | if random_state is None :
random_state = np . random . RandomState ( )
elif isinstance ( random_state , int ) :
random_state = np . random . RandomState ( random_state )
else :
assert isinstance ( random_state , np . random . RandomState )
return random_state |
async def request ( self , method , url = None , * , path = '' , retries = 1 , connection_timeout = 60 , ** kwargs ) :
'''This is the template for all of the ` http method ` methods for
the Session .
Args :
method ( str ) : A http method , such as ' GET ' or ' POST ' .
url ( str ) : The url the request shou... | timeout = kwargs . get ( 'timeout' , None )
req_headers = kwargs . pop ( 'headers' , None )
if self . headers is not None :
headers = copy ( self . headers )
if req_headers is not None :
headers . update ( req_headers )
req_headers = headers
async with self . sema :
if url is None :
url = self . _ma... |
def set_client ( self , * args , ** kwargs ) :
'''Se você possui informações cadastradas sobre o comprador você pode utilizar
este método para enviar estas informações para o PagSeguro . É uma boa prática pois
evita que seu cliente tenha que preencher estas informações novamente na página
do PagSe... | self . client = { }
for arg , value in kwargs . iteritems ( ) :
if value :
self . client [ arg ] = value
client_schema ( self . client ) |
def ExtractEvents ( self , parser_mediator , registry_key , codepage = 'cp1252' , ** kwargs ) :
"""Extracts events from a Windows Registry key .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
registry _ key ( dfwinreg . ... | self . _ParseMRUListKey ( parser_mediator , registry_key , codepage = codepage ) |
def _init_glyph ( self , plot , mapping , properties ) :
"""Returns a Bokeh glyph object .""" | properties . pop ( 'legend' , None )
for prop in [ 'color' , 'alpha' ] :
if prop not in properties :
continue
pval = properties . pop ( prop )
line_prop = 'line_%s' % prop
fill_prop = 'fill_%s' % prop
if line_prop not in properties :
properties [ line_prop ] = pval
if fill_prop n... |
def value ( self , raw_value ) :
"""Decode param as decimal value .""" | try :
return decimal . Decimal ( raw_value )
except decimal . InvalidOperation :
raise ValueError ( "Could not parse '{}' value as decimal" . format ( raw_value ) ) |
def write_svg_debug ( matrix , version , out , scale = 15 , border = None , fallback_color = 'fuchsia' , color_mapping = None , add_legend = True ) :
"""Internal SVG serializer which is useful to debugging purposes .
This function is not exposed to the QRCode class by intention and the
resulting SVG document is... | clr_mapping = { 0x0 : '#fff' , 0x1 : '#000' , 0x2 : 'red' , 0x3 : 'orange' , 0x4 : 'gold' , 0x5 : 'green' , }
if color_mapping is not None :
clr_mapping . update ( color_mapping )
border = get_border ( version , border )
width , height = get_symbol_size ( version , scale , border )
matrix_size = get_symbol_size ( v... |
def split ( input_layer , split_dim = 0 , num_splits = 2 ) :
"""Splits this Tensor along the split _ dim into num _ splits Equal chunks .
Examples :
* ` [ 1 , 2 , 3 , 4 ] - > [ 1 , 2 ] , [ 3 , 4 ] `
* ` [ [ 1 , 1 ] , [ 2 , 2 ] , [ 3 , 3 ] , [ 4 , 4 ] ] - > [ [ 1 , 1 ] , [ 2 , 2 ] ] , [ [ 3 , 3 ] , [ 4 , 4 ] ]... | shape = input_layer . shape
_check_split_dims ( num_splits , split_dim , shape )
splits = tf . split ( value = input_layer , num_or_size_splits = num_splits , axis = split_dim )
return input_layer . with_sequence ( splits ) |
def create_hit ( self , title , description , keywords , reward , duration_hours , lifetime_days , ad_url , notification_url , approve_requirement , max_assignments , us_only , blacklist = None , annotation = None , ) :
"""Create the actual HIT and return a dict with its useful properties .""" | frame_height = 600
mturk_question = self . _external_question ( ad_url , frame_height )
qualifications = self . build_hit_qualifications ( approve_requirement , us_only , blacklist )
# We need a HIT _ Type in order to register for REST notifications
hit_type_id = self . register_hit_type ( title , description , reward ... |
def logp_plus_loglike ( self ) :
'''The summed log - probability of all stochastic variables that depend on
self . stochastics , and self . stochastics .''' | sum = logp_of_set ( self . markov_blanket )
if self . verbose > 2 :
print_ ( '\t' + self . _id + ' Current log-likelihood plus current log-probability' , sum )
return sum |
def get_events ( self ) :
"""Returns a list of all joystick events that have occurred since the last
call to ` get _ events ` . The list contains events in the order that they
occurred . If no events have occurred in the intervening time , the
result is an empty list .""" | result = [ ]
while self . _wait ( 0 ) :
event = self . _read ( )
if event :
result . append ( event )
return result |
def has_readonly ( self , s ) :
"""Tests whether store ` s ` is read - only .""" | for t in self . transitions :
if list ( t . lhs [ s ] ) != list ( t . rhs [ s ] ) :
return False
return True |
def check_import ( ) :
"""Try to import the aeneas package and return ` ` True ` ` if that fails .""" | try :
import aeneas
print_success ( u"aeneas OK" )
return False
except ImportError :
print_error ( u"aeneas ERROR" )
print_info ( u" Unable to load the aeneas Python package" )
print_info ( u" This error is probably caused by:" )
print_info ( u" A. you did not download/g... |
def require_json ( ) :
"""Load the best available json library on demand .""" | # Fails when " json " is missing and " simplejson " is not installed either
try :
import json
# pylint : disable = F0401
return json
except ImportError :
try :
import simplejson
# pylint : disable = F0401
return simplejson
except ImportError as exc :
raise ImportError... |
def _get_name_from_content_type ( self , request ) :
"""Get name from Content - Type header""" | content_type = request . META . get ( 'CONTENT_TYPE' , None )
if content_type : # remove the possible charset - encoding info
return util . strip_charset ( content_type )
return None |
def get_supported_boot_mode ( self ) :
"""Retrieves the supported boot mode .
: returns : any one of the following proliantutils . ilo . constants :
SUPPORTED _ BOOT _ MODE _ LEGACY _ BIOS _ ONLY ,
SUPPORTED _ BOOT _ MODE _ UEFI _ ONLY ,
SUPPORTED _ BOOT _ MODE _ LEGACY _ BIOS _ AND _ UEFI""" | system = self . _get_host_details ( )
bios_uefi_class_val = 0
# value for bios _ only boot mode
if ( 'Bios' in system [ 'Oem' ] [ 'Hp' ] and 'UefiClass' in system [ 'Oem' ] [ 'Hp' ] [ 'Bios' ] ) :
bios_uefi_class_val = ( system [ 'Oem' ] [ 'Hp' ] [ 'Bios' ] [ 'UefiClass' ] )
return mappings . GET_SUPPORTED_BOOT_MOD... |
def main ( self , c ) :
""": type c : Complex
: rtype : Sfix""" | conj = self . conjugate . main ( c )
mult = self . complex_mult . main ( c , conj )
angle = self . angle . main ( mult )
self . y = self . GAIN_SFIX * angle
return self . y |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.