signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def update_feature_type_rates ( sender , instance , created , * args , ** kwargs ) :
"""Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate .""" | if created :
for role in ContributorRole . objects . all ( ) :
FeatureTypeRate . objects . create ( role = role , feature_type = instance , rate = 0 ) |
def loads ( conditions_string ) :
"""Deserializes the conditions property into its corresponding
components : the condition _ structure and the condition _ list .
Args :
conditions _ string : String defining valid and / or conditions .
Returns :
A tuple of ( condition _ structure , condition _ list ) .
... | decoder = ConditionDecoder ( _audience_condition_deserializer )
# Create a custom JSONDecoder using the ConditionDecoder ' s object _ hook method
# to create the condition _ structure as well as populate the condition _ list
json_decoder = json . JSONDecoder ( object_hook = decoder . object_hook )
# Perform the decodin... |
def int_gps_time_to_str ( t ) :
"""Takes an integer GPS time , either given as int or lal . LIGOTimeGPS , and
converts it to a string . If a LIGOTimeGPS with nonzero decimal part is
given , raises a ValueError .""" | if isinstance ( t , int ) :
return str ( t )
elif isinstance ( t , float ) : # Wouldn ' t this just work generically ?
int_t = int ( t )
if abs ( t - int_t ) > 0. :
raise ValueError ( 'Need an integer GPS time, got %s' % str ( t ) )
return str ( int_t )
elif isinstance ( t , lal . LIGOTimeGPS ) ... |
def parse ( self , limit = None ) :
"""Override Source . parse ( )
Args :
: param limit ( int , optional ) limit the number of rows processed
Returns :
: return None""" | if limit is not None :
LOG . info ( "Only parsing first %d rows" , limit )
protein_paths = self . _get_file_paths ( self . tax_ids , 'protein_links' )
col = [ 'NCBI taxid' , 'entrez' , 'STRING' ]
for taxon in protein_paths :
ensembl = Ensembl ( self . graph_type , self . are_bnodes_skized )
string_file_path... |
def sqlupdate ( table , rowupdate , where ) :
"""Generates SQL update table set . . .
Returns ( sql , parameters )
> > > sqlupdate ( ' mytable ' , { ' field1 ' : 3 , ' field2 ' : ' hello ' } , { ' id ' : 5 } )
( ' update mytable set field1 = % s , field2 = % s where id = % s ' , [ 3 , ' hello ' , 5 ] )""" | validate_name ( table )
fields = sorted ( rowupdate . keys ( ) )
validate_names ( fields )
values = [ rowupdate [ field ] for field in fields ]
setparts = [ field + '=%s' for field in fields ]
setclause = ', ' . join ( setparts )
sql = "update {} set " . format ( table ) + setclause
( whereclause , wherevalues ) = sqlw... |
def post_async ( self , path , params = None ) :
"""Asynchronously calls a function on a child block
Args :
path ( list ) : The path to post to
params ( dict ) : parameters for the call
Returns :
Future : as single Future that will resolve to the result""" | request = Post ( self . _get_next_id ( ) , path , params )
request . set_callback ( self . _q . put )
future = self . _dispatch_request ( request )
return future |
def admin_permission_factory ( admin_view ) :
"""Default factory for creating a permission for an admin .
It tries to load a : class : ` invenio _ access . permissions . Permission `
instance if ` invenio _ access ` is installed .
Otherwise , it loads a : class : ` flask _ principal . Permission ` instance . ... | try :
pkg_resources . get_distribution ( 'invenio-access' )
from invenio_access import Permission
except pkg_resources . DistributionNotFound :
from flask_principal import Permission
return Permission ( action_admin_access ) |
def get_text_contents ( self ) :
"""Fetch the decoded text contents of a Unicode encoded Entry .
Since this should return the text contents from the file
system , we check to see into what sort of subclass we should
morph this Entry .""" | try :
self = self . disambiguate ( must_exist = 1 )
except SCons . Errors . UserError : # There was nothing on disk with which to disambiguate
# this entry . Leave it as an Entry , but return a null
# string so calls to get _ text _ contents ( ) in emitters and
# the like ( e . g . in qt . py ) don ' t have to disa... |
def hit_create ( self , numWorkers , reward , duration ) :
'''Create a HIT''' | if self . sandbox :
mode = 'sandbox'
else :
mode = 'live'
server_loc = str ( self . config . get ( 'Server Parameters' , 'host' ) )
use_psiturk_ad_server = self . config . getboolean ( 'Shell Parameters' , 'use_psiturk_ad_server' )
if use_psiturk_ad_server :
if not self . web_services . check_credentials ( ... |
def _get_task_descriptor_info ( self , courseid , taskid ) :
""": param courseid : the course id of the course
: param taskid : the task id of the task
: raise InvalidNameException , TaskNotFoundException
: return : a tuple , containing :
( descriptor filename ,
task file manager for the descriptor )""" | if not id_checker ( courseid ) :
raise InvalidNameException ( "Course with invalid name: " + courseid )
if not id_checker ( taskid ) :
raise InvalidNameException ( "Task with invalid name: " + taskid )
task_fs = self . get_task_fs ( courseid , taskid )
for ext , task_file_manager in self . _task_file_managers .... |
def load_spelling ( spell_file = SPELLING_FILE ) :
"""Load the term _ freq from spell _ file""" | with open ( spell_file ) as f :
tokens = f . read ( ) . split ( '\n' )
size = len ( tokens )
term_freq = { token : size - i for i , token in enumerate ( tokens ) }
return term_freq |
def set_used_labels ( self , labels ) :
"""Specify which trials to use in subsequent analysis steps .
This function masks trials based on their class labels .
Parameters
labels : list of class labels
Marks all trials that have a label that is in the ` labels ` list for further processing .
Returns
self ... | mask = np . zeros ( self . cl_ . size , dtype = bool )
for l in labels :
mask = np . logical_or ( mask , self . cl_ == l )
self . trial_mask_ = mask
return self |
def topic_over_time ( self , k , mode = 'counts' , slice_kwargs = { } ) :
"""Calculate the representation of topic ` ` k ` ` in the corpus over time .""" | return self . corpus . feature_distribution ( 'topics' , k , mode = mode , ** slice_kwargs ) |
def array ( self ) :
"""Returns a numpy array containing the last stored values .""" | if self . _ind < self . shape :
return self . _values [ : self . _ind ]
if not self . _cached :
ind = int ( self . _ind % self . shape )
self . _cache [ : self . shape - ind ] = self . _values [ ind : ]
self . _cache [ self . shape - ind : ] = self . _values [ : ind ]
self . _cached = True
return se... |
def replace_namespaced_replication_controller_scale ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""replace _ namespaced _ replication _ controller _ scale # noqa : E501
replace scale of the specified ReplicationController # noqa : E501
This method makes a synchronous HTTP request by default .... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_replication_controller_scale_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . replace_namespaced_replication_controller_scale_with_http_info ( name , nam... |
def tri_filter ( self , inplace = False ) :
"""Returns an all triangle mesh . More complex polygons will be broken
down into triangles .
Parameters
inplace : bool , optional
Updates mesh in - place while returning nothing .
Returns
mesh : vtki . PolyData
Mesh containing only triangles . None when inpl... | trifilter = vtk . vtkTriangleFilter ( )
trifilter . SetInputData ( self )
trifilter . PassVertsOff ( )
trifilter . PassLinesOff ( )
trifilter . Update ( )
mesh = _get_output ( trifilter )
if inplace :
self . overwrite ( mesh )
else :
return mesh |
def getSrcBlockParents ( self , url , block ) :
"""List block at src DBS""" | # blockname = block . replace ( " # " , urllib . quote _ plus ( ' # ' ) )
# resturl = " % s / blockparents ? block _ name = % s " % ( url , blockname )
params = { 'block_name' : block }
return cjson . decode ( self . callDBSService ( url , 'blockparents' , params , { } ) ) |
def cowsay ( text = '' , align = 'centre' ) :
"""Simulate an ASCII cow saying text .
: type text : string
: param text : The text to print out .
: type align : string
: param algin : Where to align the cow . Can be ' left ' , ' centre ' or ' right '""" | # Make align lowercase
align = align . lower ( )
# Set the cowtext
cowtext = str ( text )
# Set top part of speech bubble to the length of the text plus 2
topbar = ' ' * ( len ( text ) + 2 )
# Set bottom part of speech bubble to the length of the text plus 2
bottombar = ' ' * ( len ( text ) + 2 )
# If align is centre
i... |
def _serve_clients ( self ) :
'''Accept cients and serve , one separate thread per client .''' | self . __up = True
while self . __up :
log . debug ( 'Waiting for a client to connect' )
try :
conn , addr = self . skt . accept ( )
log . debug ( 'Received connection from %s:%d' , addr [ 0 ] , addr [ 1 ] )
except socket . error as error :
if not self . __up :
return
... |
def read ( self , data ) :
"""Handles incoming raw sensor data and broadcasts it to specified
udp servers and connected tcp clients
: param data : NMEA raw sentences incoming data""" | self . log ( 'Received NMEA data:' , data , lvl = debug )
# self . log ( data , pretty = True )
if self . _tcp_socket is not None and len ( self . _connected_tcp_endpoints ) > 0 :
self . log ( 'Publishing data on tcp server' , lvl = debug )
for endpoint in self . _connected_tcp_endpoints :
self . fireEv... |
def compile ( pattern , flags = 0 , auto_compile = None ) : # noqa A001
"""Compile both the search or search and replace into one object .""" | if isinstance ( pattern , Bre ) :
if auto_compile is not None :
raise ValueError ( "Cannot compile Bre with a different auto_compile!" )
elif flags != 0 :
raise ValueError ( "Cannot process flags argument with a compiled pattern" )
return pattern
else :
if auto_compile is None :
... |
def convert_field_value ( type_ , value ) :
"""Convert atomic field value according to the type""" | if value == "." :
return None
elif type_ in ( "Character" , "String" ) :
if "%" in value :
for k , v in record . UNESCAPE_MAPPING :
value = value . replace ( k , v )
return value
else :
try :
return _CONVERTERS [ type_ ] ( value )
except ValueError :
warnings . wa... |
def call ( self , command , * args ) :
"""Sends call to the function , whose name is specified by command .
Used by Script invocations and normalizes calls using standard
Redis arguments to use the expected redis - py arguments .""" | command = self . _normalize_command_name ( command )
args = self . _normalize_command_args ( command , * args )
redis_function = getattr ( self , command )
value = redis_function ( * args )
return self . _normalize_command_response ( command , value ) |
def add_tools ( self , * tools ) :
'''Adds tools to the plot .
Args :
* tools ( Tool ) : the tools to add to the Plot
Returns :
None''' | for tool in tools :
if not isinstance ( tool , Tool ) :
raise ValueError ( "All arguments to add_tool must be Tool subclasses." )
self . toolbar . tools . append ( tool ) |
def setup_files ( class_dir , seed ) :
"""Returns shuffled files""" | # make sure its reproducible
random . seed ( seed )
files = list_files ( class_dir )
files . sort ( )
random . shuffle ( files )
return files |
def check_value_error_for_parity ( value_error : ValueError , call_type : ParityCallType ) -> bool :
"""For parity failing calls and functions do not return None if the transaction
will fail but instead throw a ValueError exception .
This function checks the thrown exception to see if it ' s the correct one and... | try :
error_data = json . loads ( str ( value_error ) . replace ( "'" , '"' ) )
except json . JSONDecodeError :
return False
if call_type == ParityCallType . ESTIMATE_GAS :
code_checks_out = error_data [ 'code' ] == - 32016
message_checks_out = 'The execution failed due to an exception' in error_data [ ... |
def default_working_dir ( ) :
"""Get the default configuration directory for blockstackd""" | import nameset . virtualchain_hooks as virtualchain_hooks
return os . path . expanduser ( '~/.{}' . format ( virtualchain_hooks . get_virtual_chain_name ( ) ) ) |
def iwls ( y , x , family , offset , y_fix , ini_betas = None , tol = 1.0e-8 , max_iter = 200 , wi = None ) :
"""Iteratively re - weighted least squares estimation routine
Parameters
y : array
n * 1 , dependent variable
x : array
n * k , designs matrix of k independent variables
family : family object
... | n_iter = 0
diff = 1.0e6
if ini_betas is None :
betas = np . zeros ( ( x . shape [ 1 ] , 1 ) , np . float )
else :
betas = ini_betas
if isinstance ( family , Binomial ) :
y = family . link . _clean ( y )
if isinstance ( family , Poisson ) :
y_off = y / offset
y_off = family . starting_mu ( y_off )
... |
def update ( self , ** kwargs ) :
"""Update the drawing
: param kwargs : Drawing properties""" | # Update node properties with additional elements
svg_changed = False
for prop in kwargs :
if prop == "drawing_id" :
pass
# No good reason to change a drawing _ id
elif getattr ( self , prop ) != kwargs [ prop ] :
if prop == "svg" : # To avoid spamming client with large data we don ' t s... |
def send_result ( pipe , data ) :
"""Send result handling pickling and communication errors .""" | try :
pipe . send ( data )
except ( pickle . PicklingError , TypeError ) as error :
error . traceback = format_exc ( )
pipe . send ( RemoteException ( error , error . traceback ) ) |
def _fetchAllChildren ( self ) :
"""Fetches all fields that this variable contains .
Only variables with a structured data type can have fields .""" | assert self . canFetchChildren ( ) , "canFetchChildren must be True"
childItems = [ ]
# Add fields in case of an array of structured type .
if self . _isStructured :
for fieldName in self . _array . dtype . names :
childItem = FieldRti ( self . _array , nodeName = fieldName , fileName = self . fileName )
... |
def split_delimited_symbol ( symbol ) :
"""Takes in a symbol that may be delimited and splits it in to a company
symbol and share class symbol . Also returns the fuzzy symbol , which is the
symbol without any fuzzy characters at all .
Parameters
symbol : str
The possibly - delimited symbol to be split
R... | # return blank strings for any bad fuzzy symbols , like NaN or None
if symbol in _delimited_symbol_default_triggers :
return '' , ''
symbol = symbol . upper ( )
split_list = re . split ( pattern = _delimited_symbol_delimiters_regex , string = symbol , maxsplit = 1 , )
# Break the list up in to its two components , ... |
def start_recv ( sockfile = None ) :
'''Open a server on Unix Domain Socket''' | if sockfile is not None :
SOCKFILE = sockfile
else : # default sockfile
SOCKFILE = "/tmp/snort_alert"
if os . path . exists ( SOCKFILE ) :
os . unlink ( SOCKFILE )
unsock = socket . socket ( socket . AF_UNIX , socket . SOCK_DGRAM )
unsock . bind ( SOCKFILE )
logging . warning ( 'Unix socket start listening.... |
def get_version_info ( self , key_name = 'ver_sw_release' ) :
"""get the ( major , minor , patch , type ) version information as tuple .
Returns None if not found
definition of type is :
> = 0 : development
> = 64 : alpha version
> = 128 : beta version
> = 192 : RC version
= = 255 : release version""" | if key_name in self . _msg_info_dict :
val = self . _msg_info_dict [ key_name ]
return ( ( val >> 24 ) & 0xff , ( val >> 16 ) & 0xff , ( val >> 8 ) & 0xff , val & 0xff )
return None |
def draw ( self ) :
"""使用draw方法将图形绘制在窗口里""" | self . update_all ( )
self . vertex_list . draw ( self . gl )
pyglet . gl . glLoadIdentity ( ) |
def _values ( expr ) :
"""Retrieve values of a dict
: param expr : dict sequence / scalar
: return :""" | if isinstance ( expr , SequenceExpr ) :
dtype = expr . data_type
else :
dtype = expr . value_type
return composite_op ( expr , DictValues , df_types . List ( dtype . value_type ) ) |
def run ( self , ** kwargs ) :
'''Run all benchmarks .
Extras kwargs are passed to benchmarks construtors .''' | self . report_start ( )
for bench in self . benchmarks :
bench = bench ( before = self . report_before_method , after = self . report_after_method , after_each = self . report_progress , debug = self . debug , ** kwargs )
self . report_before_class ( bench )
bench . run ( )
self . report_after_class ( b... |
def update_port_monitor ( self , resource , timeout = - 1 ) :
"""Updates the port monitor configuration of a logical interconnect .
Args :
resource : Port monitor configuration .
Returns :
dict : Port monitor configuration .""" | data = resource . copy ( )
if 'type' not in data :
data [ 'type' ] = 'port-monitor'
uri = "{}{}" . format ( self . data [ "uri" ] , self . PORT_MONITOR_PATH )
return self . _helper . update ( data , uri = uri , timeout = timeout ) |
def iconFile ( self ) :
"""Returns the icon file that is linked that to this plugin .
: return < str >""" | if not os . path . isfile ( self . _iconFile ) :
return projexui . resources . find ( self . _iconFile )
return self . _iconFile |
def get_block ( self , parent , config = 'running_config' ) :
"""Scans the config and returns a block of code
Args :
parent ( str ) : The parent string to search the config for and
return the block
config ( str ) : A text config string to be searched . Default
is to search the running - config of the Node... | try :
parent = r'^%s$' % parent
return self . node . section ( parent , config = config )
except TypeError :
return None |
def current_path ( local_function ) :
"""Get current path , refers to ` how - do - i - get - the - path - of - the - current - executed - file - in - python ` _
Examples :
. . code - block : : Python
from pygeoc . utils import UtilClass
curpath = UtilClass . current _ path ( lambda : 0)
. . _ how - do - i... | from inspect import getsourcefile
fpath = getsourcefile ( local_function )
if fpath is None :
return None
return os . path . dirname ( os . path . abspath ( fpath ) ) |
def normalize_mapping_line ( mapping_line , previous_source_column = 0 ) :
"""Often times the position will remain stable , such that the naive
process will end up with many redundant values ; this function will
iterate through the line and remove all extra values .""" | if not mapping_line :
return [ ] , previous_source_column
# Note that while the local record here is also done as a 4 - tuple ,
# element 1 and 2 are never used since they are always provided by
# the segments in the mapping line ; they are defined for consistency
# reasons .
def regenerate ( segment ) :
if len... |
def _fit ( self , df ) :
"""Private fit method of the Estimator , which trains the model .""" | simple_rdd = df_to_simple_rdd ( df , categorical = self . get_categorical_labels ( ) , nb_classes = self . get_nb_classes ( ) , features_col = self . getFeaturesCol ( ) , label_col = self . getLabelCol ( ) )
simple_rdd = simple_rdd . repartition ( self . get_num_workers ( ) )
keras_model = model_from_yaml ( self . get_... |
def subtract ( self , other , numPartitions = None ) :
"""Return each value in C { self } that is not contained in C { other } .
> > > x = sc . parallelize ( [ ( " a " , 1 ) , ( " b " , 4 ) , ( " b " , 5 ) , ( " a " , 3 ) ] )
> > > y = sc . parallelize ( [ ( " a " , 3 ) , ( " c " , None ) ] )
> > > sorted ( x... | # note : here ' True ' is just a placeholder
rdd = other . map ( lambda x : ( x , True ) )
return self . map ( lambda x : ( x , True ) ) . subtractByKey ( rdd , numPartitions ) . keys ( ) |
def _validateClasses ( classes ) :
"""Check to make sure that a glyph is not part of more than
one class . If this is found , an ExtractorError is raised .""" | glyphToClass = { }
for className , glyphList in classes . items ( ) :
for glyphName in glyphList :
if glyphName not in glyphToClass :
glyphToClass [ glyphName ] = set ( )
glyphToClass [ glyphName ] . add ( className )
for glyphName , groupList in glyphToClass . items ( ) :
if len ( g... |
def alias_relationship ( self , relationship_id , alias_id ) :
"""Adds an ` ` Id ` ` to a ` ` Relationship ` ` for the purpose of creating compatibility .
The primary ` ` Id ` ` of the ` ` Relationship ` ` is determined by the
provider . The new ` ` Id ` ` performs as an alias to the primary
` ` Id ` ` . If t... | # Implemented from template for
# osid . resource . ResourceAdminSession . alias _ resources _ template
self . _alias_id ( primary_id = relationship_id , equivalent_id = alias_id ) |
def aperture_photometry ( data , apertures , error = None , mask = None , method = 'exact' , subpixels = 5 , unit = None , wcs = None ) :
"""Perform aperture photometry on the input data by summing the flux
within the given aperture ( s ) .
Parameters
data : array _ like , ` ~ astropy . units . Quantity ` , `... | data , error , mask , wcs = _prepare_photometry_input ( data , error , mask , wcs , unit )
if method == 'subpixel' :
if ( int ( subpixels ) != subpixels ) or ( subpixels <= 0 ) :
raise ValueError ( 'subpixels must be a positive integer.' )
scalar_aperture = False
if isinstance ( apertures , Aperture ) :
... |
def p_parameter_2 ( p ) :
"""parameter _ 2 : qualifierList dataType parameterName
| qualifierList dataType parameterName array""" | args = { }
if len ( p ) == 5 :
args [ 'is_array' ] = True
args [ 'array_size' ] = p [ 4 ]
quals = OrderedDict ( [ ( x . name , x ) for x in p [ 1 ] ] )
p [ 0 ] = CIMParameter ( p [ 3 ] , p [ 2 ] , qualifiers = quals , ** args ) |
def histogram_and_plot ( df , column = 0 , width = 0.9 , resolution = 2 , str_timetags = True , counted = False , title = '' , xlabel = None , datetime_format = '%b %d, %Y' , num_labels = 24 , bins = None , labels = None , color = None , alpha = None , normalize = True , percent = False , padding = 0.03 , formatter = N... | try :
assert len ( bins ) == len ( counted ) + 1
his0 , his1 = bins , counted
except :
his0 , his1 = [ ] , [ ]
if isinstance ( df , basestring ) and os . path . isfile ( df ) :
df = pd . DataFrame . from_csv ( df )
if not isinstance ( df , pd . DataFrame ) :
df = pd . DataFrame ( df ... |
def listTasks ( self , opts = { } , queryOpts = { } ) :
"""Get information about all Koji tasks .
Calls " listTasks " XML - RPC .
: param dict opts : Eg . { ' state ' : [ task _ states . OPEN ] }
: param dict queryOpts : Eg . { ' order ' : ' priority , create _ time ' }
: returns : deferred that when fired ... | opts [ 'decode' ] = True
# decode xmlrpc data in " request "
data = yield self . call ( 'listTasks' , opts , queryOpts )
tasks = [ ]
for tdata in data :
task = Task . fromDict ( tdata )
task . connection = self
tasks . append ( task )
defer . returnValue ( tasks ) |
def setup_conf ( conf_globals ) :
"""Setup function that is called from within the project ' s
docs / conf . py module that takes the conf module ' s globals ( ) and
assigns the values that can be automatically determined from the
current project , such as project name , package name , version and
author ."... | project_path = abspath ( join ( dirname ( conf_globals [ "__file__" ] ) , ".." ) )
chdir ( project_path )
sys . path . insert ( 0 , project_path )
authors_file = "AUTHORS"
version = None
author = None
setup = "setup.py"
setup_path = join ( project_path , setup )
ignore = ( setup , )
# First try and get the author and v... |
def unreduce_like ( array , original_array , axis , keepdims ) :
"""Reverse summing over a dimension .
Args :
array : The array that was reduced .
original _ array : An array whose shape to unreduce to .
axis : The axis or axes that were summed .
keepdims : Whether these axes were kept as singleton axes .... | atype = type ( array )
unreducer = unreducers [ atype ]
shape = shape_functions [ atype ]
return unreducer ( array , shape ( original_array ) , axis , keepdims ) |
def plotnoise ( noisepkl , mergepkl , plot_width = 950 , plot_height = 400 ) :
"""Make two panel plot to summary noise analysis with estimated flux scale""" | d = pickle . load ( open ( mergepkl ) )
ndist , imstd , flagfrac = plotnoisedist ( noisepkl , plot_width = plot_width / 2 , plot_height = plot_height )
fluxscale = calcfluxscale ( d , imstd , flagfrac )
logger . info ( 'Median image noise is {0:.3} Jy.' . format ( fluxscale * imstd ) )
ncum , imnoise = plotnoisecum ( n... |
def __merge_all_bgedges_between_two_vertices ( self , vertex1 , vertex2 ) :
"""Merges all edge between two supplied vertices into a single edge from a perspective of multi - color merging .
: param vertex1 : a first out of two vertices edges between which are to be merged together
: type vertex1 : any python ha... | # no actual merging is performed , but rather all edges between two vertices are deleted
# and then added with a merge argument set to true
edges_multicolors = [ deepcopy ( data [ "attr_dict" ] [ "multicolor" ] ) for v1 , v2 , data in self . bg . edges ( nbunch = vertex1 , data = True ) if v2 == vertex2 ]
self . __dele... |
def except_ ( self , enumerable , key = lambda x : x ) :
"""Returns enumerable that subtracts given enumerable elements from self
: param enumerable : enumerable object
: param key : key selector as lambda expression
: return : new Enumerable object""" | if not isinstance ( enumerable , Enumerable3 ) :
raise TypeError ( u"enumerable parameter must be an instance of Enumerable" )
membership = ( 0 if key ( element ) in enumerable . intersect ( self , key ) . select ( key ) else 1 for element in self )
return Enumerable3 ( itertools . compress ( self , membership ) ) |
def print_ ( * objects , ** kwargs ) :
"""print _ ( * objects , sep = None , end = None , file = None , flush = False )
Args :
objects ( object ) : zero or more objects to print
sep ( str ) : Object separator to use , defaults to ` ` " " ` `
end ( str ) : Trailing string to use , defaults to ` ` " \\ n " ` ... | sep = kwargs . get ( "sep" )
sep = sep if sep is not None else " "
end = kwargs . get ( "end" )
end = end if end is not None else "\n"
file = kwargs . get ( "file" )
file = file if file is not None else sys . stdout
flush = bool ( kwargs . get ( "flush" , False ) )
if is_win :
_print_windows ( objects , sep , end ,... |
def generateRandomSymbol ( numColumns , sparseCols ) :
"""Generates a random SDR with sparseCols number of active columns
@ param numColumns ( int ) number of columns in the temporal memory
@ param sparseCols ( int ) number of sparse columns for desired SDR
@ return symbol ( list ) SDR""" | symbol = list ( )
remainingCols = sparseCols
while remainingCols > 0 :
col = random . randrange ( numColumns )
if col not in symbol :
symbol . append ( col )
remainingCols -= 1
return symbol |
def restore_default ( self , key ) :
"""Restore ( and return ) default value for the specified key .
This method will only work for a ConfigObj that was created
with a configspec and has been validated .
If there is no default value for this key , ` ` KeyError ` ` is raised .""" | default = self . default_values [ key ]
dict . __setitem__ ( self , key , default )
if key not in self . defaults :
self . defaults . append ( key )
return default |
def geweke ( x , seg_length , seg_stride , end_idx , ref_start , ref_end = None , seg_start = 0 ) :
"""Calculates Geweke conervergence statistic for a chain of data .
This function will advance along the chain and calculate the
statistic for each step .
Parameters
x : numpy . array
A one - dimensional arr... | # lists to hold statistic and end index
stats = [ ]
ends = [ ]
# get the beginning of all segments
starts = numpy . arange ( seg_start , end_idx , seg_stride )
# get second segment of data at the end to compare
x_end = x [ ref_start : ref_end ]
# loop over all segments
for start in starts : # find the end of the first ... |
def to_code ( self , context : Context = None ) :
"""Generate the code and return it as a string .""" | # Do not override this method !
context = context or Context ( )
for imp in self . imports :
if imp not in context . imports :
context . imports . append ( imp )
counter = Counter ( )
lines = list ( self . to_lines ( context = context , counter = counter ) )
if counter . num_indented_non_doc_blocks == 0 :
... |
def delete_asset ( self , asset_id , asset_type ) :
"""Delete the asset with the provided asset _ id .
Args :
asset _ id : The id of the asset .
asset _ type : The asset type .
Returns :""" | return self . asset ( asset_id , asset_type = asset_type , action = 'DELETE' ) |
def remove_bad_sequence ( codon_list , bad_seq , bad_seqs ) :
"""Make a silent mutation to the given codon list to remove the first instance
of the given bad sequence found in the gene sequence . If the bad sequence
isn ' t found , nothing happens and the function returns false . Otherwise the
function return... | gene_seq = '' . join ( codon_list )
problem = bad_seq . search ( gene_seq )
if not problem :
return False
bs_start_codon = problem . start ( ) // 3
bs_end_codon = problem . end ( ) // 3
for i in range ( bs_start_codon , bs_end_codon ) :
problem_codon = codon_list [ i ]
amino_acid = translate_dna ( problem_c... |
def split_token ( output ) :
"""Split an output into token tuple , real output tuple .
: param output :
: return : tuple , tuple""" | output = ensure_tuple ( output )
flags , i , len_output , data_allowed = set ( ) , 0 , len ( output ) , True
while i < len_output and isflag ( output [ i ] ) :
if output [ i ] . must_be_first and i :
raise ValueError ( "{} flag must be first." . format ( output [ i ] ) )
if i and output [ i - 1 ] . must... |
def compile_suffix_regex ( entries ) :
"""Compile a sequence of suffix rules into a regex object .
entries ( tuple ) : The suffix rules , e . g . spacy . lang . punctuation . TOKENIZER _ SUFFIXES .
RETURNS ( regex object ) : The regex object . to be used for Tokenizer . suffix _ search .""" | expression = "|" . join ( [ piece + "$" for piece in entries if piece . strip ( ) ] )
return re . compile ( expression ) |
def extract ( self , m ) :
"""extract info specified in option""" | self . _clear ( )
self . m = m
# self . _ preprocess ( )
if self . option != [ ] :
self . _url_filter ( )
self . _email_filter ( )
if 'tex' in self . option :
self . _tex_filter ( )
# if ' email ' in self . option :
# self . _ email _ filter ( )
if 'telephone' in self . option :
... |
def suppressed ( self ) :
"""Returns the number of seconds that this search is blocked from running
( possibly 0 ) .
: return : The number of seconds .
: rtype : ` ` integer ` `""" | r = self . _run_action ( "suppress" )
if r . suppressed == "1" :
return int ( r . expiration )
else :
return 0 |
def _get_cache_dir ( ) :
'''Get pillar cache directory . Initialize it if it does not exist .''' | cache_dir = os . path . join ( __opts__ [ 'cachedir' ] , 'pillar_s3fs' )
if not os . path . isdir ( cache_dir ) :
log . debug ( 'Initializing S3 Pillar Cache' )
os . makedirs ( cache_dir )
return cache_dir |
def change ( ui , repo , * pats , ** opts ) :
"""create , edit or delete a change list
Create , edit or delete a change list .
A change list is a group of files to be reviewed and submitted together ,
plus a textual description of the change .
Change lists are referred to by simple alphanumeric names .
Ch... | if codereview_disabled :
raise hg_util . Abort ( codereview_disabled )
dirty = { }
if len ( pats ) > 0 and GoodCLName ( pats [ 0 ] ) :
name = pats [ 0 ]
if len ( pats ) != 1 :
raise hg_util . Abort ( "cannot specify CL name and file patterns" )
pats = pats [ 1 : ]
cl , err = LoadCL ( ui , re... |
def DEFINE_bool ( self , name , default , help , constant = False ) :
"""A helper for defining boolean options .""" | self . AddOption ( type_info . Bool ( name = name , default = default , description = help ) , constant = constant ) |
def hideFromPublicBundle ( self , otpk_pub ) :
"""Hide a one - time pre key from the public bundle .
: param otpk _ pub : The public key of the one - time pre key to hide , encoded as a
bytes - like object .""" | self . __checkSPKTimestamp ( )
for otpk in self . __otpks :
if otpk . pub == otpk_pub :
self . __otpks . remove ( otpk )
self . __hidden_otpks . append ( otpk )
self . __refillOTPKs ( ) |
def unitResponse ( self , band ) :
"""This is used internally for : ref : ` pysynphot - formula - effstim `
calculations .""" | wave = band . wave
total = band . trapezoidIntegration ( wave , band . throughput / wave )
modtot = total * ( 1.0e-29 / H )
return 1.0 / modtot |
def atoms_order ( self ) :
"""Morgan like algorithm for graph nodes ordering
: return : dict of atom - weight pairs""" | if not len ( self ) : # for empty containers
return { }
elif len ( self ) == 1 : # optimize single atom containers
return dict . fromkeys ( self , 2 )
params = { n : ( int ( node ) , tuple ( sorted ( int ( edge ) for edge in self . _adj [ n ] . values ( ) ) ) ) for n , node in self . atoms ( ) }
newlevels = { }... |
def DeleteMessageHandlerRequests ( self , requests ) :
"""Deletes a list of message handler requests from the database .""" | for r in requests :
flow_dict = self . message_handler_requests . get ( r . handler_name , { } )
if r . request_id in flow_dict :
del flow_dict [ r . request_id ]
flow_dict = self . message_handler_leases . get ( r . handler_name , { } )
if r . request_id in flow_dict :
del flow_dict [ r... |
def token ( self , id , ** kwargs ) :
"""Retrieve a service request ID from a token .
> > > Three ( ' api . city . gov ' ) . token ( ' 12345 ' )
{ ' service _ request _ id ' : { ' for ' : { ' token ' : ' 12345 ' } } }""" | data = self . get ( 'tokens' , id , ** kwargs )
return data |
def traverse ( self , callback ) :
'''Traverse through all keys and values ( in - order )
and replace keys and values with the return values
from the callback function .''' | def _traverse_node ( path , node , callback ) :
ret_val = callback ( path , node )
if ret_val is not None : # replace node with the return value
node = ret_val
else : # traverse deep into the hierarchy
if isinstance ( node , YAMLDict ) :
for k , v in node . items ( ) :
... |
def _selectTree ( self ) :
"""Matches the tree selection to the views selection .""" | self . uiGanttTREE . blockSignals ( True )
self . uiGanttTREE . clearSelection ( )
for item in self . uiGanttVIEW . scene ( ) . selectedItems ( ) :
item . treeItem ( ) . setSelected ( True )
self . uiGanttTREE . blockSignals ( False ) |
def load_table_data ( self ) :
"""Calls the ` ` get _ { { table _ name } } _ data ` ` methods for each table class .
When returning , the loaded data is set on the tables .""" | # We only want the data to be loaded once , so we track if we have . . .
if not self . _table_data_loaded :
for table_name , table in self . _tables . items ( ) : # Fetch the data function .
func_name = "get_%s_data" % table_name
data_func = getattr ( self , func_name , None )
if data_func i... |
def _transform_key_value ( self , key , value , map_dict ) :
'''Massage keys and values for iapp dict to look like JSON .
: param key : string dictionary key
: param value : string dictionary value
: param map _ dict : dictionary to map key names''' | if key in self . tcl_list_patterns :
value = self . _parse_tcl_list ( key , value )
if key in map_dict :
key = map_dict [ key ]
return key , value |
def read_backend ( self ) :
'''Returns the : class : ` stdnet . BackendStructure ` .''' | session = self . session
if session is not None :
if self . _field :
return session . model ( self . _field . model ) . read_backend
else :
return session . model ( self ) . read_backend |
def encodeSemiOctets ( number ) :
"""Semi - octet encoding algorithm ( e . g . for phone numbers )
: return : bytearray containing the encoded octets
: rtype : bytearray""" | if len ( number ) % 2 == 1 :
number = number + 'F'
# append the " end " indicator
octets = [ int ( number [ i + 1 ] + number [ i ] , 16 ) for i in xrange ( 0 , len ( number ) , 2 ) ]
return bytearray ( octets ) |
def unwrap_message ( self , message , signature ) :
"""Verifies the supplied signature against the message and decrypts the message if ' confidentiality ' was
negotiated .
A SignatureException is raised if the signature cannot be parsed or the version is unsupported
A SequenceException is raised if the sequen... | if not self . is_established :
raise Exception ( "Context has not been established" )
if self . _wrapper is None :
raise Exception ( "Neither sealing or signing have been negotiated" )
else :
return self . _wrapper . unwrap ( message , signature ) |
def command2str ( num ) :
"""Turn command number into name""" | for attr in SLOT . __dict__ . keys ( ) :
if not attr . startswith ( '_' ) and attr == attr . upper ( ) :
if getattr ( SLOT , attr ) == num :
return 'SLOT_%s' % attr
return "0x%02x" % ( num ) |
def on_unaryop ( self , node ) : # ( ' op ' , ' operand ' )
"""Unary operator .""" | return op2func ( node . op ) ( self . run ( node . operand ) ) |
def relativeAreaSTE ( self ) :
'''return STE area - relative to image area''' | s = self . noSTE . shape
return np . sum ( self . mask_STE ) / ( s [ 0 ] * s [ 1 ] ) |
def norm ( self , valu ) :
'''Normalize the value for a given type .
Args :
valu ( obj ) : The value to normalize .
Returns :
( ( obj , dict ) ) : The normalized valu , info tuple .
Notes :
The info dictionary uses the following key conventions :
subs ( dict ) : The normalized sub - fields as name : v... | func = self . _type_norms . get ( type ( valu ) )
if func is None :
raise s_exc . NoSuchFunc ( name = self . name , mesg = 'no norm for type: %r' % ( type ( valu ) , ) )
return func ( valu ) |
def get_mean ( self , col , row ) :
"""Returns the mean at this location ( if valid location ) .
: param col : the 0 - based column index
: type col : int
: param row : the 0 - based row index
: type row : int
: return : the mean
: rtype : float""" | return javabridge . call ( self . jobject , "getMean" , "(II)D" , col , row ) |
def worker_exec ( self , ** kwargs ) :
"""Target function of workers""" | self . feed ( ** kwargs )
self . logger . info ( 'thread {} exit' . format ( current_thread ( ) . name ) ) |
def remove_experiment_choice ( experiment , choice ) :
"""Removes an experiment choice""" | redis = oz . redis . create_connection ( )
oz . bandit . Experiment ( redis , experiment ) . remove_choice ( choice ) |
def get_translation_speed ( self , distance_from_target ) :
"""Returns the translation speed for ` ` distance _ from _ target ` `
in units per radius .""" | return ( distance_from_target * np . tan ( self . fov_deg / 2.0 / 180.0 * np . pi ) ) |
async def get_record ( type_ : str , id : str , options : str ) :
"""Retrieves a record from the wallet storage .
: param type _ : String
: param id : String
: param options : String
Example :
import json
await Wallet . add _ record ( {
' id ' : ' RecordId ' ,
' tags ' : json . dumps ( {
' tag1 ' ... | logger = logging . getLogger ( __name__ )
if not hasattr ( Wallet . get_record , "cb" ) :
logger . debug ( "vcx_wallet_get_record: Creating callback" )
Wallet . get_record . cb = create_cb ( CFUNCTYPE ( None , c_uint32 , c_uint32 , c_char_p ) )
c_type_ = c_char_p ( type_ . encode ( 'utf-8' ) )
c_id = c_char_p (... |
def thin_string_list ( list_of_strings , max_nonempty_strings = 50 , blank = '' ) :
"""Designed for composing lists of strings suitable for pyplot axis labels
Often the xtick spacing doesn ' t allow room for 100 ' s of text labels , so this
eliminates every other one , then every other one of those , until they... | # blank some labels to make sure they don ' t overlap
list_of_strings = list ( list_of_strings )
istep = 2
while sum ( bool ( s ) for s in list_of_strings ) > max_nonempty_strings :
list_of_strings = [ blank if i % istep else s for i , s in enumerate ( list_of_strings ) ]
istep += 2
return list_of_strings |
def mod ( self ) :
"""Modulus of vector .""" | return math . sqrt ( self . x ** 2 + self . y ** 2 + self . z ** 2 ) |
def fetch_gpml_usps_resampled_data ( transpose_data = True , data_home = None ) :
"""Fetch the USPS handwritten digits dataset from the internet and parse
appropriately into python arrays
> > > usps _ resampled = fetch _ gpml _ usps _ resampled _ data ( )
> > > usps _ resampled . train . targets . shape
(46... | data_home = get_data_home ( data_home = data_home )
data_filename = os . path . join ( data_home , 'usps_resampled/usps_resampled.mat' )
if not os . path . exists ( data_filename ) :
r = requests . get ( 'http://www.gaussianprocess.org/gpml/data/' 'usps_resampled.tar.bz2' )
with tarfile . open ( fileobj = Bytes... |
def _line_by_type ( self , line , header , hgroups , htypes , out , want_type , collapse_quals_fn = None ) :
"""Parse out key value pairs for line information based on a group of values .""" | for index , htype in ( ( i , t ) for i , t in enumerate ( htypes ) if t == want_type ) :
col = hgroups [ index ] [ 0 ]
key = header [ col ]
# self . _ clean _ header ( header [ col ] )
if collapse_quals_fn :
val = collapse_quals_fn ( line , header , hgroups [ index ] )
else :
val = l... |
def tolist ( expr , ** kwargs ) :
"""Pack all data in the sequence into a list
: param expr :
: param unique : make every elements in the sequence to be unique
: return :""" | unique = kwargs . get ( 'unique' , kwargs . get ( '_unique' , False ) )
output_type = None
if isinstance ( expr , ( SequenceExpr , SequenceGroupBy ) ) :
output_type = types . List ( expr . _data_type )
return _reduction ( expr , ToList , output_type , _unique = unique ) |
def checksum ( fpath , hasher = None , asbytes = False ) :
"""Returns the checksum of the file at the given path as a hex string
( default ) or as a bytes literal . Uses MD5 by default .
* * Attribution * * :
Based on code from
` Stack Overflow < https : / / stackoverflow . com / a / 3431835/789078 > ` _ ."... | def blockiter ( fpath , blocksize = 0x1000 ) :
with open ( fpath , "rb" ) as afile :
block = afile . read ( blocksize )
while len ( block ) > 0 :
yield block
block = afile . read ( blocksize )
hasher = hasher or hashlib . md5 ( )
for block in blockiter ( fpath ) :
hasher ... |
def begin_transaction ( self , transaction_type , trace_parent = None ) :
"""Start a new transactions and bind it in a thread - local variable
: returns the Transaction object""" | if trace_parent :
is_sampled = bool ( trace_parent . trace_options . recorded )
else :
is_sampled = self . _sample_rate == 1.0 or self . _sample_rate > random . random ( )
transaction = Transaction ( self , transaction_type , trace_parent = trace_parent , is_sampled = is_sampled )
if trace_parent is None :
... |
def xflatten ( iterable , transform , check = is_iterable ) :
"""Apply a transform to iterable before flattening at each level .""" | for value in transform ( iterable ) :
if check ( value ) :
for flat in xflatten ( value , transform , check ) :
yield flat
else :
yield value |
def path ( self , which = None ) :
"""Extend ` ` nailgun . entity _ mixins . Entity . path ` ` .
The format of the returned path depends on the value of ` ` which ` ` :
add
/ content _ view _ components / add
remove
/ content _ view _ components / remove
Otherwise , call ` ` super ` ` .""" | if which in ( 'add' , 'remove' ) :
return '{0}/{1}' . format ( super ( ContentViewComponent , self ) . path ( which = 'base' ) , which )
return super ( ContentViewComponent , self ) . path ( which ) |
def initialize_options ( self , * args ) :
"""omit - Wstrict - prototypes from CFLAGS since its only valid for C code .""" | import distutils . sysconfig
cfg_vars = distutils . sysconfig . get_config_vars ( )
# if ' CFLAGS ' in cfg _ vars :
# cfg _ vars [ ' CFLAGS ' ] = cfg _ vars [ ' CFLAGS ' ] . replace ( ' - Wstrict - prototypes ' , ' ' )
for k , v in cfg_vars . items ( ) :
if isinstance ( v , str ) and v . find ( "-Wstrict-prototypes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.