signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _get_template ( self , root = None , ** metadata_defaults ) :
"""Iterate over items metadata _ defaults { prop : val , . . . } to populate template""" | if root is None :
if self . _data_map is None :
self . _init_data_map ( )
root = self . _xml_root = self . _data_map [ '_root' ]
template_tree = self . _xml_tree = create_element_tree ( root )
for prop , val in iteritems ( metadata_defaults ) :
path = self . _data_map . get ( prop )
if path and ... |
def set_npartitions ( self , npartitions = None ) :
"""Set the number of partitions to use for dask""" | if npartitions is None :
self . _npartitions = cpu_count ( ) * 2
else :
self . _npartitions = npartitions
return self |
def facebook_authorization_required ( redirect_uri = FACEBOOK_AUTHORIZATION_REDIRECT_URL , permissions = None ) :
"""Require the user to authorize the application .
: param redirect _ uri : A string describing an URL to redirect to after authorization is complete .
If ` ` None ` ` , redirects to the current URL... | def decorator ( function ) :
@ wraps ( function )
def wrapper ( request , * args , ** kwargs ) : # We know the user has been authenticated via a canvas page if a signed request is set .
canvas = request . facebook is not False and hasattr ( request . facebook , "signed_request" )
# The user has ... |
def _blockedPairs ( self , blocks ) :
"""Generate tuples of pairs of records from a block of records
Arguments :
blocks - - an iterable sequence of blocked records""" | block , blocks = core . peek ( blocks )
self . _checkBlock ( block )
product = itertools . product
pairs = ( product ( base , target ) for base , target in blocks )
return pairs |
def check_grammar ( self , ok_start_symbols = set ( ) , out = sys . stderr ) :
'''Check grammar for :
- unused left - hand side nonterminals that are neither start symbols
or listed in ok _ start _ symbols
- unused right - hand side nonterminals , i . e . not tokens
- right - recursive rules . These can slo... | warnings = 0
( lhs , rhs , tokens , right_recursive , dup_rhs ) = self . check_sets ( )
if lhs - ok_start_symbols :
warnings += 1
out . write ( "LHS symbols not used on the RHS:\n" )
out . write ( " " + ( ', ' . join ( sorted ( lhs ) ) + "\n" ) )
if rhs :
warnings += 1
out . write ( "RHS symbols no... |
def _access ( self , subs , acc_type , val ) :
"""_ access ( subs , acc _ type , val ) accesses the array element specified by
the tuple of subscript values , subs . If acc _ type = = _ GET _ it
returns the value of this element ; else it sets this element to the
value of the argument val .""" | if isinstance ( subs , int ) : # if subs is just an integer , take it to be an index value .
subs = ( subs , )
if len ( subs ) == 0 :
raise For2PyError ( "Zero-length arrays currently not handled." )
bounds = self . _bounds
sub_arr = self . _values
ndims = len ( subs )
for i in range ( ndims ) :
this_pos = ... |
def export_model ( model_path ) :
"""Take the latest checkpoint and copy it to model _ path .
Assumes that all relevant model files are prefixed by the same name .
( For example , foo . index , foo . meta and foo . data - 00000 - of - 00001 ) .
Args :
model _ path : The path ( can be a gs : / / path ) to ex... | estimator = tf . estimator . Estimator ( model_fn , model_dir = FLAGS . work_dir , params = FLAGS . flag_values_dict ( ) )
latest_checkpoint = estimator . latest_checkpoint ( )
all_checkpoint_files = tf . gfile . Glob ( latest_checkpoint + '*' )
for filename in all_checkpoint_files :
suffix = filename . partition (... |
async def disconnect ( self , conn_id ) :
"""Disconnect from a connected device .
See : meth : ` AbstractDeviceAdapter . disconnect ` .""" | adapter_id = self . _get_property ( conn_id , 'adapter' )
await self . adapters [ adapter_id ] . disconnect ( conn_id )
self . _teardown_connection ( conn_id ) |
def FindFileContainingSymbol ( self , symbol ) :
"""Gets the FileDescriptor for the file containing the specified symbol .
Args :
symbol : The name of the symbol to search for .
Returns :
A FileDescriptor that contains the specified symbol .
Raises :
KeyError : if the file cannot be found in the pool ."... | symbol = _NormalizeFullyQualifiedName ( symbol )
try :
return self . _descriptors [ symbol ] . file
except KeyError :
pass
try :
return self . _enum_descriptors [ symbol ] . file
except KeyError :
pass
try :
return self . _FindFileContainingSymbolInDb ( symbol )
except KeyError :
pass
try :
... |
def merge_inner ( clsdict ) :
"""Merge the inner class ( es ) of a class :
e . g class A { . . . } class A $ foo { . . . } class A $ bar { . . . }
= = > class A { class foo { . . . } class bar { . . . } . . . }""" | samelist = False
done = { }
while not samelist :
samelist = True
classlist = list ( clsdict . keys ( ) )
for classname in classlist :
parts_name = classname . rsplit ( '$' , 1 )
if len ( parts_name ) > 1 :
mainclass , innerclass = parts_name
innerclass = innerclass [ ... |
def process ( self , sched , coro ) :
"""If there aren ' t enough coroutines waiting for the signal as the
recipicient param add the calling coro in another queue to be activated
later , otherwise activate the waiting coroutines .""" | super ( Signal , self ) . process ( sched , coro )
self . result = len ( sched . sigwait [ self . name ] )
if self . result < self . recipients :
sched . signals [ self . name ] = self
self . coro = coro
return
for waitop , waitcoro in sched . sigwait [ self . name ] :
waitop . result = self . value
if ... |
def check_data_is_empty ( data ) : # type : ( bytes ) - > bool
"""Check if data is empty via MD5
: param bytes data : data to check
: rtype : bool
: return : if data is empty""" | contentmd5 = compute_md5_for_data_asbase64 ( data )
datalen = len ( data )
if datalen == _MAX_PAGE_SIZE_BYTES :
if contentmd5 == _EMPTY_MAX_PAGE_SIZE_MD5 :
return True
else :
data_chk = b'\0' * datalen
if compute_md5_for_data_asbase64 ( data_chk ) == contentmd5 :
return True
return False |
def execute_sql ( self , * args , ** kwargs ) :
"""Sync execute SQL query , ` allow _ sync ` must be set to True .""" | assert self . _allow_sync , ( "Error, sync query is not allowed! Call the `.set_allow_sync()` " "or use the `.allow_sync()` context manager." )
if self . _allow_sync in ( logging . ERROR , logging . WARNING ) :
logging . log ( self . _allow_sync , "Error, sync query is not allowed: %s %s" % ( str ( args ) , str ( k... |
def process ( self ) :
'''Process .
Coroutine .''' | self . _item_session . request = request = Request ( self . _item_session . url_record . url )
verdict = self . _fetch_rule . check_ftp_request ( self . _item_session ) [ 0 ]
if not verdict :
self . _item_session . skip ( )
return
self . _add_request_password ( request )
dir_name , filename = self . _item_sessi... |
def inp ( i ) :
"""Input : {
text - text to print
Output : {
return - return code = 0
string - input string""" | t = i [ 'text' ]
if con_encoding == '' :
x = sys . stdin . encoding
if x == None :
b = t . encode ( )
else :
b = t . encode ( x , 'ignore' )
else :
b = t . encode ( con_encoding , 'ignore' )
# pragma : no cover
if sys . version_info [ 0 ] > 2 :
try :
b = b . decode ( sys . st... |
def init_blueprint ( self , blueprint , path = "templates.yaml" ) :
"""Initialize a Flask Blueprint , similar to init _ app , but without the access
to the application config .
Keyword Arguments :
blueprint { Flask Blueprint } - - Flask Blueprint instance to initialize
( Default : { None } )
path { str } ... | if self . _route is not None :
raise TypeError ( "route cannot be set when using blueprints!" )
# we need to tuck our reference to this Assistant instance
# into the blueprint object and find it later !
blueprint . assist = self
# BlueprintSetupState . add _ url _ rule gets called underneath the covers and
# concat... |
def simple_polygon_without_brush ( layer , width = '0.26' , color = QColor ( 'black' ) ) :
"""Simple style to apply a border line only to a polygon layer .
: param layer : The layer to style .
: type layer : QgsVectorLayer
: param color : Color to use for the line . Default to black .
: type color : QColor ... | registry = QgsApplication . symbolLayerRegistry ( )
line_metadata = registry . symbolLayerMetadata ( "SimpleLine" )
symbol = QgsSymbol . defaultSymbol ( layer . geometryType ( ) )
# Line layer
line_layer = line_metadata . createSymbolLayer ( { 'width' : width , 'color' : color . name ( ) , 'offset' : '0' , 'penstyle' :... |
def to_netcdf ( data , filename , * , group = "posterior" , coords = None , dims = None ) :
"""Save dataset as a netcdf file .
WARNING : Only idempotent in case ` data ` is InferenceData
Parameters
data : InferenceData , or any object accepted by ` convert _ to _ inference _ data `
Object to be saved
file... | inference_data = convert_to_inference_data ( data , group = group , coords = coords , dims = dims )
file_name = inference_data . to_netcdf ( filename )
return file_name |
def _parse_roles ( self ) :
"""Generate a dictionary for configured roles from oslo _ config .
Due to limitations in ini format , it ' s necessary to specify
roles in a flatter format than a standard dictionary . This
function serves to transform these roles into a standard
python dictionary .""" | roles = { }
for keystone_role , flask_role in self . config . roles . items ( ) :
roles . setdefault ( flask_role , set ( ) ) . add ( keystone_role )
return roles |
def get_backend_name ( self , location ) :
"""Return the name of the version control backend if found at given
location , e . g . vcs . get _ backend _ name ( ' / path / to / vcs / checkout ' )""" | for vc_type in self . _registry . values ( ) :
path = os . path . join ( location , vc_type . dirname )
if os . path . exists ( path ) :
return vc_type . name
return None |
def return_hdr ( self ) :
"""Return the header for further use .
Returns
subj _ id : str
subject identification code
start _ time : datetime
start time of the dataset
s _ freq : float
sampling frequency
chan _ name : list of str
list of all the channels
n _ samples : int
number of samples in t... | hdr = { }
hdr [ 's_freq' ] = self . s_freq
hdr [ 'chan_name' ] = [ 'RRi' ]
with open ( self . filename , 'rt' ) as f :
head = [ next ( f ) for x in range ( 12 ) ]
hdr [ 'subj_id' ] = head [ 0 ] [ 11 : - 3 ]
hdr [ 'start_time' ] = DEFAULT_DATETIME
hdr [ 'recorder' ] = head [ 2 ] [ 10 : ]
hdr [ 's_fre... |
def init_db_conn ( connection_name , HOSTS = None ) :
"""Initialize a redis connection by each connection string
defined in the configuration file""" | el = elasticsearch . Elasticsearch ( hosts = HOSTS )
el_pool . connections [ connection_name ] = ElasticSearchClient ( el ) |
def get_target_args ( self , alias ) :
"""Returns a list of FunctionArgs for the specified target _ type .""" | target_types = list ( self . _buildfile_aliases . target_types_by_alias . get ( alias ) )
if not target_types :
raise TaskError ( 'No such target type: {}' . format ( alias ) )
return self . get_args_for_target_type ( target_types [ 0 ] ) |
def remaining_quota ( self , remaining_quota ) :
"""Sets the remaining _ quota of this ServicePackageMetadata .
Current available service package quota .
: param remaining _ quota : The remaining _ quota of this ServicePackageMetadata .
: type : int""" | if remaining_quota is None :
raise ValueError ( "Invalid value for `remaining_quota`, must not be `None`" )
if remaining_quota is not None and remaining_quota < 0 :
raise ValueError ( "Invalid value for `remaining_quota`, must be a value greater than or equal to `0`" )
self . _remaining_quota = remaining_quota |
def format_docstring ( template_ = "{__doc__}" , * args , ** kwargs ) :
r"""Parametrized decorator for adding / changing a function docstring .
For changing a already available docstring in the function , the
` ` " { _ _ doc _ _ } " ` ` in the template is replaced by the original function
docstring .
Parame... | def decorator ( func ) :
if func . __doc__ :
kwargs [ "__doc__" ] = func . __doc__ . format ( * args , ** kwargs )
func . __doc__ = template_ . format ( * args , ** kwargs )
return func
return decorator |
def get_port_channel_detail_output_lacp_aggr_member_sync ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_port_channel_detail = ET . Element ( "get_port_channel_detail" )
config = get_port_channel_detail
output = ET . SubElement ( get_port_channel_detail , "output" )
lacp = ET . SubElement ( output , "lacp" )
aggr_member = ET . SubElement ( lacp , "aggr-member" )
sync = ET . SubElemen... |
def inversefunc ( func , y_values = None , domain = None , image = None , open_domain = None , args = ( ) , accuracy = 2 ) :
r"""Obtain the inverse of a function .
Returns the numerical inverse of the function ` f ` . It may return a callable
that can be used to calculate the inverse , or the inverse of certain... | domain , image , open_domain , args = _normparams_inversefunc ( domain , image , open_domain , args )
ymin , ymax = image
xmin , xmax = domain
xmin_open , xmax_open = open_domain
# Calculating if the function is increasing or decreasing , using ref points
# anywhere in the valid range ( Function has to be strictly mono... |
def get_property_names ( obj ) :
"""Gets names of all properties implemented in specified object .
: param obj : an objec to introspect .
: return : a list with property names .""" | property_names = [ ]
for property_name in dir ( obj ) :
property = getattr ( obj , property_name )
if PropertyReflector . _is_property ( property , property_name ) :
property_names . append ( property_name )
return property_names |
def event_return ( events ) :
'''Return event to a postgres server
Require that configuration be enabled via ' event _ return '
option in master config .''' | conn = _get_conn ( )
if conn is None :
return None
cur = conn . cursor ( )
for event in events :
tag = event . get ( 'tag' , '' )
data = event . get ( 'data' , '' )
sql = '''INSERT INTO salt_events
(tag, data, master_id)
VALUES (%s, %s, %s)'''
cur . execute ( sql , ( ... |
def _ProcessAMCacheProgramKey ( self , am_entry , parser_mediator ) :
"""Parses an Amcache Root / Programs key for events .
Args :
am _ entry ( pyregf . key ) : amcache Programs key .
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvf... | amcache_datetime = am_entry . get_value_by_name ( self . _AMCACHE_P_INSTALLDATE ) . get_data_as_integer ( )
event_data = AmcacheProgramEventData ( )
name = am_entry . get_value_by_name ( self . _AMCACHE_P_NAME )
if name :
event_data . name = name . get_data_as_string ( )
version = am_entry . get_value_by_name ( sel... |
def Deserializer ( stream_or_string , ** options ) :
"""Deserialize a stream or string of JSON data .""" | geometry_field = options . get ( "geometry_field" , "geom" )
def FeatureToPython ( dictobj ) :
properties = dictobj [ 'properties' ]
model_name = options . get ( "model_name" ) or properties . pop ( 'model' )
# Deserialize concrete fields only ( bypass dynamic properties )
model = _get_model ( model_nam... |
def get_kernel_data ( self ) :
"""Get the kernel data needed for this optimization routine to work .""" | return { 'subplex_scratch_float' : LocalMemory ( 'mot_float_type' , 4 + self . _var_replace_dict [ 'NMR_PARAMS' ] * 2 + self . _var_replace_dict [ 'MAX_SUBSPACE_LENGTH' ] * 2 + ( self . _var_replace_dict [ 'MAX_SUBSPACE_LENGTH' ] * 2 + self . _var_replace_dict [ 'MAX_SUBSPACE_LENGTH' ] + 1 ) ** 2 + 1 ) , 'subplex_scrat... |
def write_rk4 ( path , name , laser , omega , gamma , r , Lij , states = None , verbose = 1 ) :
r"""This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
` \ rho _ { ij } ` using the Runge - Kutta method of order 4.
INPUT :
- ` ` path ` ` - A string with t... | global omega_rescaled
t0 = time ( )
Ne = len ( omega [ 0 ] )
Nl = len ( laser )
if states == None :
states = range ( 1 , Ne + 1 )
# We make some checks
for i in range ( Ne ) :
for j in range ( Ne ) :
b1 = not ( '.' in str ( omega [ i ] [ j ] ) or 'e' in str ( omega [ i ] [ j ] ) )
if b1 :
... |
def assign_notification_from_gvm ( self , model , prop_name , info ) :
"""Handles gtkmvc3 notification from global variable manager
Calls update of whole list store in case new variable was added . Avoids to run updates without reasonable change .
Holds tree store and updates row elements if is - locked or glob... | if info [ 'method_name' ] in [ 'set_locked_variable' ] or info [ 'result' ] is Exception :
return
if info [ 'method_name' ] in [ 'lock_variable' , 'unlock_variable' ] :
key = info . kwargs . get ( 'key' , info . args [ 1 ] ) if len ( info . args ) > 1 else info . kwargs [ 'key' ]
if key in self . list_store... |
def for_language ( self , language_code ) :
"""Set the default language for all objects returned with this
query .""" | clone = self . _clone ( )
clone . _default_language = language_code
return clone |
def libvlc_media_get_meta ( p_md , e_meta ) :
'''Read the meta of the media .
If the media has not yet been parsed this will return NULL .
This methods automatically calls L { libvlc _ media _ parse _ async } ( ) , so after calling
it you may receive a libvlc _ MediaMetaChanged event . If you prefer a synchro... | f = _Cfunctions . get ( 'libvlc_media_get_meta' , None ) or _Cfunction ( 'libvlc_media_get_meta' , ( ( 1 , ) , ( 1 , ) , ) , string_result , ctypes . c_void_p , Media , Meta )
return f ( p_md , e_meta ) |
def format_query_result ( self , query_result , query_path , return_type = list , preceding_depth = None ) :
"""Formats the query result based on the return type requested .
: param query _ result : ( dict or str or list ) , yaml query result
: param query _ path : ( str , list ( str ) ) , representing query pa... | if type ( query_result ) != return_type :
converted_result = self . format_with_handler ( query_result , return_type )
else :
converted_result = query_result
converted_result = self . add_preceding_dict ( converted_result , query_path , preceding_depth )
return converted_result |
def count_args ( node , results ) : # type : ( Node , Dict [ str , Base ] ) - > Tuple [ int , bool , bool , bool ]
"""Count arguments and check for self and * args , * * kwds .
Return ( selfish , count , star , starstar ) where :
- count is total number of args ( including * args , * * kwds )
- selfish is Tru... | count = 0
selfish = False
star = False
starstar = False
args = results . get ( 'args' )
if isinstance ( args , Node ) :
children = args . children
elif isinstance ( args , Leaf ) :
children = [ args ]
else :
children = [ ]
# Interpret children according to the following grammar :
# ( ( ' * ' | ' * * ' ) ? N... |
def get_attributes ( self , name_list ) :
"""Get Attributes
Get a list of attributes as a name / value dictionary .
: param name _ list :
A list of attribute names ( strings ) .
: return :
A name / value dictionary ( both names and values are strings ) .""" | properties = { }
for name in name_list :
value = self . get_attribute ( name )
if value is not None :
properties [ name ] = value
return properties |
def get_fd_value ( tag ) :
"""Getters for data that also work with implicit transfersyntax
: param tag : the tag to read""" | if tag . VR == 'OB' or tag . VR == 'UN' :
value = struct . unpack ( 'd' , tag . value ) [ 0 ]
return value
return tag . value |
def rowCount ( self , qindex = QModelIndex ( ) ) :
"""Array row number""" | if self . total_rows <= self . rows_loaded :
return self . total_rows
else :
return self . rows_loaded |
def streaming_callback ( self , body_part ) :
"""Handles a streaming chunk of the response .
The streaming _ response callback gives no indication about whether the
received chunk is the last in the stream . The " last _ response " instance
variable allows us to keep track of the last received chunk of the
... | b64_body_string = base64 . b64encode ( body_part ) . decode ( 'utf-8' )
response = { 'message_id' : self . _message_id , 'data' : b64_body_string , }
if self . _last_response is None : # This represents the first chunk of data to be streamed to the caller .
# Attach status and header information to this item .
resp... |
def set_sunrise ( self , duration ) :
"""Turn the bulb on and create a sunrise .""" | self . set_transition_time ( duration / 100 )
for i in range ( 0 , duration ) :
try :
data = "action=on&color=3;{}" . format ( i )
request = requests . post ( '{}/{}/{}' . format ( self . resource , URI , self . _mac ) , data = data , timeout = self . timeout )
if request . status_code == 20... |
def coords ( self , coords ) :
"""Fractional a coordinate""" | self . _coords = np . array ( coords )
self . _frac_coords = self . _lattice . get_fractional_coords ( self . _coords ) |
def _start_speaker ( self , settings ) :
"""Starts BGPSpeaker using the given settings .""" | # Check required settings .
_required_settings = ( LOCAL_AS , ROUTER_ID , )
for required in _required_settings :
if required not in settings :
raise ApplicationException ( desc = 'Required BGP configuration missing: %s' % required )
# Set event notify handlers if no corresponding handler specified .
setting... |
def destroy ( name , call = None ) :
'''Destroy a machine by name
CLI Example :
. . code - block : : bash
salt - cloud - d vm _ name''' | if call == 'function' :
raise SaltCloudSystemExit ( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' )
__utils__ [ 'cloud.fire_event' ] ( 'event' , 'destroying instance' , 'salt/cloud/{0}/destroying' . format ( name ) , args = { 'name' : name } , sock_dir = __opts__ [ 'sock_dir' ] , transp... |
def add_child ( self , ** kwargs ) :
"""Adds a child to the node .""" | if not self . is_leaf ( ) : # there are child nodes , delegate insertion to add _ sibling
if self . node_order_by :
pos = 'sorted-sibling'
else :
pos = 'last-sibling'
last_child = self . get_last_child ( )
last_child . _cached_parent_obj = self
return last_child . add_sibling ( pos ,... |
def addpubs ( p1 , p2 , outcompressed = True ) :
'''Pubkey inputs can be compressed or uncompressed , as long as
they ' re valid keys and hex strings . Use the validatepubkey ( )
function to validate them first . The compression of the input
keys does not do anything or matter in any way . Only the
outcompr... | if len ( p1 ) == 66 :
p1 = uncompress ( p1 )
if len ( p2 ) == 66 :
p2 = uncompress ( p2 )
x , y = ecadd ( int ( p1 [ 2 : 66 ] , 16 ) , int ( p1 [ 66 : ] , 16 ) , int ( p2 [ 2 : 66 ] , 16 ) , int ( p2 [ 66 : ] , 16 ) )
x = dechex ( x , 32 )
y = dechex ( y , 32 )
o = '04' + x + y
if outcompressed :
return com... |
def cli ( ctx , debug , config , path , cache ) :
"""\U0 001F98A Inspect and search through the complexity of your source code .
To get started , run setup :
$ wily setup
To reindex any changes in your source code :
$ wily build < src >
Then explore basic metrics with :
$ wily report < file >
You can ... | ctx . ensure_object ( dict )
ctx . obj [ "DEBUG" ] = debug
if debug :
logger . setLevel ( "DEBUG" )
else :
logger . setLevel ( "INFO" )
ctx . obj [ "CONFIG" ] = load_config ( config )
if path :
logger . debug ( f"Fixing path to {path}" )
ctx . obj [ "CONFIG" ] . path = path
if cache :
logger . debug... |
def generate_targets ( self , local_go_targets = None ) :
"""Generate Go targets in memory to form a complete Go graph .
: param local _ go _ targets : The local Go targets to fill in a complete target graph for . If
` None ` , then all local Go targets under the Go source root are used .
: type local _ go _ ... | # TODO ( John Sirois ) : support multiple source roots like GOPATH does ?
# The GOPATH ' s 1st element is read - write , the rest are read - only ; ie : their sources build to
# the 1st element ' s pkg / and bin / dirs .
go_roots_by_category = defaultdict ( list )
# TODO : Add " find source roots for lang " functionali... |
def get_data ( name ) :
"""This function extracts the data from the Tplot Variables stored in memory .
Parameters :
name : str
Name of the tplot variable
Returns :
time _ val : pandas dataframe index
data _ val : list
Examples :
> > > # Retrieve the data from Variable 1
> > > import pytplot
> > ... | global data_quants
if name not in data_quants . keys ( ) :
print ( "That name is currently not in pytplot" )
return
temp_data_quant = data_quants [ name ]
data_val = temp_data_quant . data . values
time_val = temp_data_quant . data . index
return ( time_val , data_val ) |
def worker ( self , fifo ) :
'''Worker thread continuously filtering and converting data when data becomes available .''' | logging . debug ( 'Starting worker thread for %s' , fifo )
self . _fifo_conditions [ fifo ] . acquire ( )
while True :
try :
data_tuple = self . _fifo_data_deque [ fifo ] . popleft ( )
except IndexError :
self . _fifo_conditions [ fifo ] . wait ( self . readout_interval )
# sleep a littl... |
def has_field ( self , dotted_name ) :
"""Checks whether the layer has the given field name .
Can get a dotted name , i . e . layer . sublayer . subsublayer . field""" | parts = dotted_name . split ( '.' )
cur_layer = self
for part in parts :
if part in cur_layer . field_names :
cur_layer = cur_layer . get_field ( part )
else :
return False
return True |
def RegisterResources ( self , client_resources ) :
"""Update stats with info about resources consumed by a single client .""" | self . user_cpu_stats . RegisterValue ( client_resources . cpu_usage . user_cpu_time )
self . system_cpu_stats . RegisterValue ( client_resources . cpu_usage . system_cpu_time )
self . network_bytes_sent_stats . RegisterValue ( client_resources . network_bytes_sent )
self . worst_performers . Append ( client_resources ... |
def reload_libraries ( library_directories : list = None ) :
"""Reload the libraries stored in the project ' s local and shared library
directories""" | directories = library_directories or [ ]
project = cauldron . project . get_internal_project ( )
if project :
directories += project . library_directories
if not directories :
return
def reload_module ( path : str , library_directory : str ) :
path = os . path . dirname ( path ) if path . endswith ( '__init... |
def patch_logging ( self ) :
"""Patches built - in Python logging if necessary .""" | if not hasattr ( logging , "getLogger" ) :
def getLogger ( name = None ) :
other = Logger ( self )
if name is not None :
other . name = name
return other
logging . getLogger = getLogger |
def fit_from_cfg ( cls , choosers , chosen_fname , alternatives , cfgname , outcfgname = None ) :
"""Parameters
choosers : DataFrame
A dataframe of rows of agents that have made choices .
chosen _ fname : string
A string indicating the column in the choosers dataframe which
gives which alternative the cho... | logger . debug ( 'start: fit from configuration {}' . format ( cfgname ) )
lcm = cls . from_yaml ( str_or_buffer = cfgname )
lcm . fit ( choosers , alternatives , choosers [ chosen_fname ] )
for k , v in lcm . _group . models . items ( ) :
print ( "LCM RESULTS FOR SEGMENT %s\n" % str ( k ) )
v . report_fit ( )
... |
def delete ( self , path , data = None ) :
"""Executes a DELETE .
' path ' may not be None . Should include the full path to the
resoure .
' data ' may be None or a dictionary .
Returns a named tuple that includes :
status : the HTTP status code
json : the returned JSON - HAL
If the key was not set , ... | # Argument error checking .
assert path is not None
assert data is None or isinstance ( data , dict )
# Execute the request .
response = self . conn . request ( 'DELETE' , path , data , self . _get_headers ( ) )
# Extract the result .
self . _last_status = response_status = response . status
response_content = response... |
def create_fontgroup ( self , option = None , text = None , title = None , tip = None , fontfilters = None , without_group = False ) :
"""Option = None - > setting plugin font""" | if title :
fontlabel = QLabel ( title )
else :
fontlabel = QLabel ( _ ( "Font" ) )
fontbox = QFontComboBox ( )
if fontfilters is not None :
fontbox . setFontFilters ( fontfilters )
sizelabel = QLabel ( " " + _ ( "Size" ) )
sizebox = QSpinBox ( )
sizebox . setRange ( 7 , 100 )
self . fontboxes [ ( fontbox ,... |
def mpi_submit ( nslave , worker_args , worker_envs ) :
"""customized submit script , that submit nslave jobs , each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args arguments to launch each... | worker_args += [ '%s=%s' % ( k , str ( v ) ) for k , v in worker_envs . items ( ) ]
sargs = ' ' . join ( args . command + worker_args )
if args . hostfile is None :
cmd = ' ' . join ( [ 'mpirun -n %d' % ( nslave ) ] + args . command + worker_args )
else :
cmd = ' ' . join ( [ 'mpirun -n %d --hostfile %s' % ( ns... |
def find_remote_by_client_id ( client_id ) :
"""Return a remote application based with given client ID .""" | for remote in current_oauthclient . oauth . remote_apps . values ( ) :
if remote . name == 'cern' and remote . consumer_key == client_id :
return remote |
def ice_days ( tasmax , freq = 'YS' ) :
r"""Number of ice / freezing days
Number of days where daily maximum temperatures are below 0 ° C .
Parameters
tasmax : xarrray . DataArray
Maximum daily temperature [ ° C ] or [ K ]
freq : str , optional
Resampling frequency
Returns
xarray . DataArray
Numbe... | tu = units . parse_units ( tasmax . attrs [ 'units' ] . replace ( '-' , '**-' ) )
fu = 'degC'
frz = 0
if fu != tu :
frz = units . convert ( frz , fu , tu )
f = ( tasmax < frz ) * 1
return f . resample ( time = freq ) . sum ( dim = 'time' ) |
def Auth ( email = None , password = None ) :
"""Get a reusable google data client .""" | gd_client = SpreadsheetsService ( )
gd_client . source = "texastribune-ttspreadimporter-1"
if email is None :
email = os . environ . get ( 'GOOGLE_ACCOUNT_EMAIL' )
if password is None :
password = os . environ . get ( 'GOOGLE_ACCOUNT_PASSWORD' )
if email and password :
gd_client . ClientLogin ( email , pass... |
def from_result ( cls , container , result ) :
"""Create from ambiguous result .""" | if result is None :
raise errors . NoObjectException
elif cls . is_prefix ( result ) :
return cls . from_prefix ( container , result )
elif cls . is_key ( result ) :
return cls . from_key ( container , result )
raise errors . CloudException ( "Unknown boto result type: %s" % type ( result ) ) |
def estimate_frequency ( self , start : int , end : int , sample_rate : float ) :
"""Estimate the frequency of the baseband signal using FFT
: param start : Start of the area that shall be investigated
: param end : End of the area that shall be investigated
: param sample _ rate : Sample rate of the signal
... | # ensure power of 2 for faster fft
length = 2 ** int ( math . log2 ( end - start ) )
data = self . data [ start : start + length ]
try :
w = np . fft . fft ( data )
frequencies = np . fft . fftfreq ( len ( w ) )
idx = np . argmax ( np . abs ( w ) )
freq = frequencies [ idx ]
freq_in_hertz = abs ( fr... |
def decodeIlxResp ( resp ) :
"""We need this until we can get json back directly and this is SUPER nasty""" | lines = [ _ for _ in resp . text . split ( '\n' ) if _ ]
# strip empties
if 'successfull' in lines [ 0 ] :
return [ ( _ . split ( '"' ) [ 1 ] , ilxIdFix ( _ . split ( ': ' ) [ - 1 ] ) ) for _ in lines [ 1 : ] ]
elif 'errors' in lines [ 0 ] :
return [ ( _ . split ( '"' ) [ 1 ] , ilxIdFix ( _ . split ( '(' ) [ 1 ... |
def get_field ( self , name ) :
"""Return a list all fields which corresponds to the regexp
: param name : the name of the field ( a python regexp )
: rtype : a list with all : class : ` EncodedField ` objects""" | # TODO could use a generator here
prog = re . compile ( name )
l = [ ]
for i in self . get_classes ( ) :
for j in i . get_fields ( ) :
if prog . match ( j . get_name ( ) ) :
l . append ( j )
return l |
def add_header ( self , header , value ) : # type : ( str , str ) - > None
"""Add a persistent header - this header will be applied to all
requests sent during the current client session .
. . deprecated : : 0.5.0
Use config . headers instead
: param str header : The header name .
: param str value : The ... | warnings . warn ( "Private attribute _client.add_header is deprecated. Use config.headers instead." , DeprecationWarning )
self . config . headers [ header ] = value |
def crack ( ciphertext , * fitness_functions , min_key = 0 , max_key = 26 , shift_function = shift_case_english ) :
"""Break ` ` ciphertext ` ` by enumerating keys between ` ` min _ key ` ` and ` ` max _ key ` ` .
Example :
> > > decryptions = crack ( " KHOOR " , fitness . english . quadgrams )
> > > print ( ... | if min_key >= max_key :
raise ValueError ( "min_key cannot exceed max_key" )
decryptions = [ ]
for key in range ( min_key , max_key ) :
plaintext = decrypt ( key , ciphertext , shift_function = shift_function )
decryptions . append ( Decryption ( plaintext , key , score ( plaintext , * fitness_functions ) )... |
def select_sub ( self , query , as_ ) :
"""Add a subselect expression to the query
: param query : A QueryBuilder instance
: type query : QueryBuilder
: param as _ : The subselect alias
: type as _ : str
: return : The current QueryBuilder instance
: rtype : QueryBuilder""" | if isinstance ( query , QueryBuilder ) :
bindings = query . get_bindings ( )
query = query . to_sql ( )
elif isinstance ( query , basestring ) :
bindings = [ ]
else :
raise ArgumentError ( "Invalid subselect" )
return self . select_raw ( "(%s) AS %s" % ( query , self . _grammar . wrap ( as_ ) ) , bindin... |
def _writeContaminantTable ( self , session , fileObject , mapTable , contaminants , replaceParamFile ) :
"""This method writes the contaminant transport mapping table case .""" | # Write the contaminant mapping table header
fileObject . write ( '%s\n' % ( mapTable . name ) )
fileObject . write ( 'NUM_CONTAM %s\n' % ( mapTable . numContam ) )
# Write out each contaminant and it ' s values
for contaminant in contaminants :
fileObject . write ( '"%s" "%s" %s\n' % ( contaminant . name , conta... |
def get_cache_key ( content , ** kwargs ) :
'''generate cache key''' | cache_key = ''
for key in sorted ( kwargs . keys ( ) ) :
cache_key = '{cache_key}.{key}:{value}' . format ( cache_key = cache_key , key = key , value = kwargs [ key ] , )
cache_key = '{content}{cache_key}' . format ( content = content , cache_key = cache_key , )
# fix for non ascii symbols , ensure encoding , pytho... |
def verb_chain_ends ( self ) :
"""The end positions of ` ` verb _ chains ` ` elements .""" | if not self . is_tagged ( VERB_CHAINS ) :
self . tag_verb_chains ( )
return self . ends ( VERB_CHAINS ) |
def categorymembers ( self , page : 'WikipediaPage' , ** kwargs ) -> PagesDict :
"""Returns pages in given category with respect to parameters
API Calls for parameters :
- https : / / www . mediawiki . org / w / api . php ? action = help & modules = query % 2Bcategorymembers
- https : / / www . mediawiki . or... | params = { 'action' : 'query' , 'list' : 'categorymembers' , 'cmtitle' : page . title , 'cmlimit' : 500 , }
used_params = kwargs
used_params . update ( params )
raw = self . _query ( page , used_params )
self . _common_attributes ( raw [ 'query' ] , page )
v = raw [ 'query' ]
while 'continue' in raw :
params [ 'cmc... |
def _uploadStream ( self , fileName , update = False , encrypt = True ) :
"""Yields a context manager that can be used to write to the bucket
with a stream . See : class : ` ~ toil . jobStores . utils . WritablePipe ` for an example .
Will throw assertion error if the file shouldn ' t be updated
and yet exist... | blob = self . bucket . blob ( bytes ( fileName ) , encryption_key = self . sseKey if encrypt else None )
class UploadPipe ( WritablePipe ) :
def readFrom ( self , readable ) :
if not update :
assert not blob . exists ( )
blob . upload_from_file ( readable )
with UploadPipe ( ) as writabl... |
def to_jd ( year , month , day ) :
'''Determine Julian day from Bahai date''' | gy = year - 1 + EPOCH_GREGORIAN_YEAR
if month != 20 :
m = 0
else :
if isleap ( gy + 1 ) :
m = - 14
else :
m = - 15
return gregorian . to_jd ( gy , 3 , 20 ) + ( 19 * ( month - 1 ) ) + m + day |
def run_estimate ( unknown_gate , qnum , repetitions ) :
"""Construct the following phase estimator circuit and execute simulations .
- - - H - - - - - @ - - - - - | | - - - M - - - [ m4 ] : lowest bit
- - - H - - - - - @ - - - - - + - - - - - | | - - - M - - - [ m3]
| | | QFT _ inv |
- - - H - - - - - @ - ... | qubits = [ None ] * qnum
for i in range ( len ( qubits ) ) :
qubits [ i ] = cirq . GridQubit ( 0 , i )
ancilla = cirq . GridQubit ( 0 , len ( qubits ) )
circuit = cirq . Circuit . from_ops ( cirq . H . on_each ( * qubits ) , [ cirq . ControlledGate ( unknown_gate ** ( 2 ** i ) ) . on ( qubits [ qnum - i - 1 ] , anc... |
def swap_memory ( ) :
'''. . versionadded : : 2014.7.0
Return a dict that describes swap memory statistics .
. . note : :
This function is only available in psutil version 0.6.0 and above .
CLI Example :
. . code - block : : bash
salt ' * ' ps . swap _ memory''' | if psutil . version_info < ( 0 , 6 , 0 ) :
msg = 'swap_memory is only available in psutil 0.6.0 or greater'
raise CommandExecutionError ( msg )
return dict ( psutil . swap_memory ( ) . _asdict ( ) ) |
def pass_q_v1 ( self ) :
"""Update the outlet link sequence .
Required derived parameter :
| QFactor |
Required flux sequences :
| lland _ fluxes . Q |
Calculated flux sequence :
| lland _ outlets . Q |
Basic equation :
: math : ` Q _ { outlets } = QFactor \\ cdot Q _ { fluxes } `""" | der = self . parameters . derived . fastaccess
flu = self . sequences . fluxes . fastaccess
out = self . sequences . outlets . fastaccess
out . q [ 0 ] += der . qfactor * flu . q |
def format_close ( code : int , reason : str ) -> str :
"""Display a human - readable version of the close code and reason .""" | if 3000 <= code < 4000 :
explanation = "registered"
elif 4000 <= code < 5000 :
explanation = "private use"
else :
explanation = CLOSE_CODES . get ( code , "unknown" )
result = f"code = {code} ({explanation}), "
if reason :
result += f"reason = {reason}"
else :
result += "no reason"
return result |
def host_trigger ( trg_queue , user = None , group = None , mode = None ) :
'''Installs a host trigger for the specified queue .''' | trigger ( trg_queue , user = user , group = group , mode = mode , trigger = _c . FSQ_HOSTS_TRIGGER ) |
def get_activating_mods ( self ) :
"""Extract INDRA ActiveForm Statements with a single mod from BEL .
The SPARQL pattern used for extraction from BEL looks for a
ModifiedProteinAbundance as subject and an Activiy of a
ProteinAbundance as object .
Examples :
proteinAbundance ( HGNC : INSR , proteinModific... | q_mods = prefixes + """
SELECT ?speciesName ?actType ?mod ?pos ?rel ?stmt ?species
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasRelationship ?rel .
?stmt belvoc:hasSubject ?subject .
?stmt belvoc:hasObject ?object .
... |
def _update_camera_pos ( self ) :
"""Set the camera position and orientation""" | # transform will be updated several times ; do not update camera
# transform until we are done .
ch_em = self . events . transform_change
with ch_em . blocker ( self . _update_transform ) :
tr = self . transform
tr . reset ( )
up , forward , right = self . _get_dim_vectors ( )
# Create mapping so correc... |
def add_prefix ( self , prefix , uri ) :
"""Add I { static } mapping of an XML namespace prefix to a namespace .
This is useful for cases when a wsdl and referenced schemas make heavy
use of namespaces and those namespaces are subject to changed .
@ param prefix : An XML namespace prefix .
@ type prefix : s... | root = self . wsdl . root
mapped = root . resolvePrefix ( prefix , None )
if mapped is None :
root . addPrefix ( prefix , uri )
return
if mapped [ 1 ] != uri :
raise Exception ( '"%s" already mapped as "%s"' % ( prefix , mapped ) ) |
def bidcollateral ( ctx , collateral_symbol , collateral_amount , debt_symbol , debt_amount , account ) :
"""Bid for collateral in the settlement fund""" | print_tx ( ctx . bitshares . bid_collateral ( Amount ( collateral_amount , collateral_symbol ) , Amount ( debt_amount , debt_symbol ) , account = account , ) ) |
def check_autosign ( self , keyid , autosign_grains = None ) :
'''Checks if the specified keyid should automatically be signed .''' | if self . opts [ 'auto_accept' ] :
return True
if self . check_signing_file ( keyid , self . opts . get ( 'autosign_file' , None ) ) :
return True
if self . check_autosign_dir ( keyid ) :
return True
if self . check_autosign_grains ( autosign_grains ) :
return True
return False |
def create_vectored_io_next_entry ( ase ) : # type : ( blobxfer . models . azure . StorageEntity ) - > str
"""Create Vectored IO next entry id
: param blobxfer . models . azure . StorageEntity ase : Azure Storage Entity
: rtype : str
: return : vectored io next entry""" | return ';' . join ( ( ase . client . primary_endpoint , ase . container , ase . name ) ) |
def _compute_distance_scaling ( self , rup , dists , C ) :
"""Compute distance - scaling term , equations ( 3 ) and ( 4 ) , pag 107.""" | Mref = 4.5
Rref = 1.0
R = np . sqrt ( dists . rjb ** 2 + C [ 'h' ] ** 2 )
return ( C [ 'c1' ] + C [ 'c2' ] * ( rup . mag - Mref ) ) * np . log ( R / Rref ) + C [ 'c3' ] * ( R - Rref ) |
def loadStructuredGrid ( filename ) : # not tested
"""Load a ` ` vtkStructuredGrid ` ` object from file and return a ` ` Actor ( vtkActor ) ` ` object .""" | reader = vtk . vtkStructuredGridReader ( )
reader . SetFileName ( filename )
reader . Update ( )
gf = vtk . vtkStructuredGridGeometryFilter ( )
gf . SetInputConnection ( reader . GetOutputPort ( ) )
gf . Update ( )
return Actor ( gf . GetOutput ( ) ) |
def random_offspring ( self ) :
"Returns an offspring with the associated weight ( s )" | function_set = self . function_set
function_selection = self . _function_selection_ins
function_selection . density = self . population . density
function_selection . unfeasible_functions . clear ( )
for i in range ( self . _number_tries_feasible_ind ) :
if self . _function_selection :
func_index = function... |
def match ( self , messy_data , threshold = 0.5 , n_matches = 1 , generator = False ) : # pragma : no cover
"""Identifies pairs of records that refer to the same entity , returns
tuples containing a set of record ids and a confidence score as a float
between 0 and 1 . The record _ ids within each set should ref... | blocked_pairs = self . _blockData ( messy_data )
clusters = self . matchBlocks ( blocked_pairs , threshold , n_matches )
clusters = ( cluster for cluster in clusters if len ( cluster ) )
if generator :
return clusters
else :
return list ( clusters ) |
def map_is_in_fov ( m : tcod . map . Map , x : int , y : int ) -> bool :
"""Return True if the cell at x , y is lit by the last field - of - view
algorithm .
. . note : :
This function is slow .
. . deprecated : : 4.5
Use : any : ` tcod . map . Map . fov ` to check this property .""" | return bool ( lib . TCOD_map_is_in_fov ( m . map_c , x , y ) ) |
def _update_xmit_period ( self ) :
"""Update transmission period of the BFD session .""" | # RFC5880 Section 6.8.7.
if self . _desired_min_tx_interval > self . _remote_min_rx_interval :
xmit_period = self . _desired_min_tx_interval
else :
xmit_period = self . _remote_min_rx_interval
# This updates the transmission period of BFD Control packets .
# ( RFC5880 Section 6.8.2 & 6.8.3 . )
if self . _detect... |
def pyglet_image_loader ( filename , colorkey , ** kwargs ) :
"""basic image loading with pyglet
returns pyglet Images , not textures
This is a basic proof - of - concept and is likely to fail in some situations .
Missing :
Transparency
Tile Rotation
This is slow as well .""" | if colorkey :
logger . debug ( 'colorkey not implemented' )
image = pyglet . image . load ( filename )
def load_image ( rect = None , flags = None ) :
if rect :
try :
x , y , w , h = rect
y = image . height - y - h
tile = image . get_region ( x , y , w , h )
e... |
def validate_location_for_story_element ( sender , instance , action , reverse , pk_set , * args , ** kwargs ) :
'''Validates that location is from same outline as story node .''' | if action == 'pre_add' :
if reverse :
for spk in pk_set :
story_node = StoryElementNode . objects . get ( pk = spk )
if instance . outline != story_node . outline :
raise IntegrityError ( _ ( 'Location must be from same outline as story node.' ) )
else :
f... |
def ingest_memory ( self , memory ) :
"""Transform the memory into bytes
: param memory : Compose memory definition . ( 1g , 24k )
: type memory : memory string or integer
: return : The memory in bytes
: rtype : int""" | def lshift ( num , shift ) :
return num << shift
def rshift ( num , shift ) :
return num >> shift
if isinstance ( memory , int ) : # Memory was specified as an integer , meaning it is in bytes
memory = '{}b' . format ( memory )
bit_shift = { 'g' : { 'func' : lshift , 'shift' : 30 } , 'm' : { 'func' : lshift... |
def random_reset_mutation ( random , candidate , args ) :
"""Return the mutants produced by randomly choosing new values .
This function performs random - reset mutation . It assumes that
candidate solutions are composed of discrete values . This function
makes use of the bounder function as specified in the ... | bounder = args [ '_ec' ] . bounder
try :
values = bounder . values
except AttributeError :
values = None
if values is not None :
rate = args . setdefault ( 'mutation_rate' , 0.1 )
mutant = copy . copy ( candidate )
for i , m in enumerate ( mutant ) :
if random . random ( ) < rate :
... |
def _hor_matrix ( self , C , P ) :
"""Given two points C , P calculate matrix that rotates and translates the vector C - > P such that C is mapped to Point ( 0 , 0 ) , and P to some point on the x axis""" | S = ( P - C ) . unit
# unit vector C - > P
return Matrix ( 1 , 0 , 0 , 1 , - C . x , - C . y ) * Matrix ( S . x , - S . y , S . y , S . x , 0 , 0 ) |
def compute_center_of_mass ( self , filename ) :
"""Center of mass is computed using the sensitivity data output from CRMod
Data weights can be applied using command line options""" | sens = np . loadtxt ( filename , skiprows = 1 )
X = sens [ : , 0 ]
Z = sens [ : , 1 ]
# C = ( np . abs ( sens [ : , 2 ] ) ) # . / np . max ( np . abs ( sens [ : , 2 ] ) )
C = sens [ : , 2 ]
x_center = 0
z_center = 0
sens_sum = 0
for i in range ( 0 , C . shape [ 0 ] ) : # unweighted
if ( self . weight == 0 ) :
... |
def rao_blackwell_ledoit_wolf ( S , n ) :
"""Rao - Blackwellized Ledoit - Wolf shrinkaged estimator of the covariance
matrix .
Parameters
S : array , shape = ( n , n )
Sample covariance matrix ( e . g . estimated with np . cov ( X . T ) )
n : int
Number of data points .
Returns
sigma : array , shape... | p = len ( S )
assert S . shape == ( p , p )
alpha = ( n - 2 ) / ( n * ( n + 2 ) )
beta = ( ( p + 1 ) * n - 2 ) / ( n * ( n + 2 ) )
trace_S2 = np . sum ( S * S )
# np . trace ( S . dot ( S ) )
U = ( ( p * trace_S2 / np . trace ( S ) ** 2 ) - 1 )
rho = min ( alpha + beta / U , 1 )
F = ( np . trace ( S ) / p ) * np . eye ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.