_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q52400 | FieldIdItem.get_name | train | def get_name(self):
"""
Return the name of the field
:rtype: string
"""
if self.name_idx_value == None:
self.name_idx_value = self.CM.get_string(self.name_idx)
return self.name_idx_value | python | {
"resource": ""
} |
q52401 | EncodedField.get_access_flags_string | train | def get_access_flags_string(self):
"""
Return the access flags string of the field
:rtype: string
"""
if self.access_flags_string == None:
self.access_flags_string = get_access_flags_string(
self.get_access_flags())
if self.access... | python | {
"resource": ""
} |
q52402 | EncodedField.show_xref | train | def show_xref(self, f_a):
"""
Display where this field is read or written
"""
if f_a:
bytecode._PrintSubBanner("XREF Read")
xrefs_from = f_a.get_xref_read()
for ref_class, ref_method in xrefs_from:
bytecode._PrintDefault(ref_method.... | python | {
"resource": ""
} |
q52403 | EncodedMethod.show_info | train | def show_info(self):
"""
Display the basic information about the method
"""
bytecode._PrintSubBanner("Method Information")
bytecode._PrintDefault("%s->%s%s [access_flags=%s]\n" % (
self.get_class_name(), self.get_name(), self.get_descriptor(),
self.get... | python | {
"resource": ""
} |
q52404 | EncodedMethod.set_instructions | train | def set_instructions(self, instructions):
"""
Set the instructions
:param instructions: the list of instructions
:type instructions: a list of :class:`Instruction`
"""
if self.code == None:
return []
return self.code.get_bc().set_instructi... | python | {
"resource": ""
} |
q52405 | ClassDefItem.show_xref | train | def show_xref(self, c_a):
"""
Display where the method is called or which method is called
"""
if c_a:
ref_kind_map = {0: "Class instanciation", 1: "Class reference"}
bytecode._PrintSubBanner("XREF From")
xrefs_from = c_a.get_xref_from()
... | python | {
"resource": ""
} |
q52406 | MapList.get_item_type | train | def get_item_type(self, ttype):
"""
Get a particular item type
:param ttype: a string which represents the desired type
:rtype: None or the item object
"""
for i in self.map_item:
if TYPE_MAP_ITEM[i.get_type()] == ttype:
return i.... | python | {
"resource": ""
} |
q52407 | DalvikVMFormat.fix_checksums | train | def fix_checksums(self, buff):
"""
Fix a dex format buffer by setting all checksums
:rtype: string
"""
import zlib
import hashlib
signature = hashlib.sha1(buff[32:]).digest()
buff = buff[:12] + signature + buff[32:]
checksum = zlib.adler32(buf... | python | {
"resource": ""
} |
q52408 | DalvikOdexVMFormat.save | train | def save(self):
"""
Do not use !
"""
dex_raw = super(DalvikOdexVMFormat, self).save()
return self.magic + self.odex_header.get_raw(
) + dex_raw + self.dependencies.get_raw() + self.padding | python | {
"resource": ""
} |
q52409 | BasicAuthIdentityPolicy.identify | train | def identify(self, request):
"""Establish claimed identity using request.
:param request: Request to extract identity information from.
:type request: :class:`morepath.Request`.
:return: :class:`morepath.Identity` instance.
"""
try:
authorization = request.au... | python | {
"resource": ""
} |
q52410 | BaseUserSerializer.create | train | def create(self, validated_data):
'''We want to set the username to be the same as the email, and use
the correct create function to make use of password hashing.'''
validated_data['username'] = validated_data['email']
admin = validated_data.pop('is_superuser', None)
if admin is... | python | {
"resource": ""
} |
q52411 | BaseUserSerializer.update | train | def update(self, instance, validated_data):
'''We want to set all the required fields if admin is set, and we want
to use the password hashing method if password is set.'''
admin = validated_data.pop('is_superuser', None)
password = validated_data.pop('password', None)
if validat... | python | {
"resource": ""
} |
q52412 | Sessionizer.process | train | def process(self, user, timestamp, data=None):
"""
Processes a user event.
:Parameters:
user : `hashable`
A hashable value to identify a user (`int` or `str` are OK)
timestamp : :class:`mwtypes.Timestamp`
The timestamp of the event
... | python | {
"resource": ""
} |
q52413 | Sessionizer.get_active_sessions | train | def get_active_sessions(self):
"""
Retrieves the active, unexpired sessions.
:Returns:
A generator of :class:`~mwsessions.Session`
"""
for last_timestamp, i, events in self.recently_active:
yield Session(events[-1].user, unpack_events(events)) | python | {
"resource": ""
} |
q52414 | Context.values_for | train | def values_for(self, k):
"""
Each value with name `k`.
"""
return [getattr(frame, k) for frame in self.stack if hasattr(frame, k)] | python | {
"resource": ""
} |
q52415 | Context.reset | train | def reset(self):
"""
Used if you need to recursively parse forms.
"""
self.stack.append(Frame(src=None, src_path=None))
return Close(functools.partial(self.restore)) | python | {
"resource": ""
} |
q52416 | Context.rewind | train | def rewind(self, stop):
"""
Used if you need to rewind stack to a particular frame.
:param predicate: Callable used to stop unwind, e.g.:
.. code::
def stop(frame):
return True
:return: A context object used to restore the stack.
... | python | {
"resource": ""
} |
q52417 | Pytwis._is_loggedin | train | def _is_loggedin(self, auth_secret):
"""Check if a user is logged-in by verifying the input authentication secret.
Parameters
----------
auth_secret: str
The authentication secret of a logged-in user.
Returns
-------
bool
True if the auth... | python | {
"resource": ""
} |
q52418 | Pytwis.login | train | def login(self, username, password):
"""Log into a user.
Parameters
----------
username: str
The username.
password: str
The password.
Returns
-------
bool
True if the login is successful, False otherwise.
resu... | python | {
"resource": ""
} |
q52419 | Pytwis.logout | train | def logout(self, auth_secret):
"""Log out of a user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the logout is successful, False otherwise.
result
... | python | {
"resource": ""
} |
q52420 | Pytwis.post_tweet | train | def post_tweet(self, auth_secret, tweet):
"""Post a tweet.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
tweet: str
The tweet that will be posted.
Returns
-------
bool
True if ... | python | {
"resource": ""
} |
q52421 | Pytwis.get_followers | train | def get_followers(self, auth_secret):
"""Get the follower list of a logged-in user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the follower list is successfully obt... | python | {
"resource": ""
} |
q52422 | Pytwis.get_following | train | def get_following(self, auth_secret):
"""Get the following list of a logged-in user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the following list is successfully o... | python | {
"resource": ""
} |
q52423 | Pytwis._get_tweets | train | def _get_tweets(self, tweets_key, max_cnt_tweets):
"""Get at most `max_cnt_tweets` tweets from the Redis list `tweets_key`.
Parameters
----------
tweets_key: str
The key of the Redis list which stores the tweets.
max_cnt_tweets: int
The maximum number of ... | python | {
"resource": ""
} |
q52424 | Pytwis.get_timeline | train | def get_timeline(self, auth_secret, max_cnt_tweets):
"""Get the general or user timeline.
If an empty authentication secret is given, this method returns the general timeline.
If an authentication secret is given and it is valid, this method returns the user timeline.
If an authenticati... | python | {
"resource": ""
} |
q52425 | Pytwis.get_user_tweets | train | def get_user_tweets(self, auth_secret, username, max_cnt_tweets):
"""Get the tweets posted by one user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
username:
The name of the user who post the tweets and may not ... | python | {
"resource": ""
} |
q52426 | genKw | train | def genKw(w,msk,z):
"""
Generates key Kw using key-selector @w, master secret key @msk, and
table value @z.
@returns Kw as a BigInt.
"""
# Hash inputs into a string of bytes
b = hmac(msk, z + w, tag="TAG_PYTHIA_KW")
# Convert the string into a long value (no larger than the order of Gt)... | python | {
"resource": ""
} |
q52427 | wrap | train | def wrap(x):
"""
Wraps an element or integer type by serializing it and base64 encoding
the resulting bytes.
"""
# Detect the type so we can call the proper serialization routine
if isinstance(x, G1Element):
return _wrap(x, serializeG1)
elif isinstance(x, G2Element):
return... | python | {
"resource": ""
} |
q52428 | _wrap | train | def _wrap(x, serializeFunc, encodeFunc=base64.urlsafe_b64encode, compress=True):
"""
Wraps an element @x by serializing and then encoding the resulting bytes.
"""
return encodeFunc(serializeFunc(x, compress)) | python | {
"resource": ""
} |
q52429 | add_mapping | train | def add_mapping(agent, prefix, ip):
"""Adds a mapping with a contract.
It has high latency but gives some kind of guarantee."""
return _broadcast(agent, AddMappingManager, RecordType.record_A,
prefix, ip) | python | {
"resource": ""
} |
q52430 | remove_mapping | train | def remove_mapping(agent, prefix, ip):
"""Removes a mapping with a contract.
It has high latency but gives some kind of guarantee."""
return _broadcast(agent, RemoveMappingManager,
RecordType.record_A, prefix, ip) | python | {
"resource": ""
} |
q52431 | add_alias | train | def add_alias(agent, prefix, alias):
"""Adds an alias mapping with a contract.
It has high latency but gives some kind of guarantee."""
return _broadcast(agent, AddMappingManager, RecordType.record_CNAME,
prefix, alias) | python | {
"resource": ""
} |
q52432 | remove_alias | train | def remove_alias(agent, prefix, alias):
"""Removes an alias mapping with a contract.
It has high latency but gives some kind of guarantee."""
return _broadcast(agent, RemoveMappingManager, RecordType.record_CNAME,
prefix, alias) | python | {
"resource": ""
} |
q52433 | draw_pin | train | def draw_pin(text, background_color='green', font_color='white'):
'''Draws and returns a pin with the specified text and color scheme'''
image = Image.new('RGB', (120, 20))
draw = ImageDraw.Draw(image)
draw.rectangle([(1, 1), (118, 18)], fill=color(background_color))
draw.text((10, 4), text, fill=co... | python | {
"resource": ""
} |
q52434 | pin | train | def pin(value):
'''A small pin that represents the result of the build process'''
if value is False:
return draw_pin('Build Failed', 'red')
elif value is True:
return draw_pin('Build Passed')
elif value is NOT_FOUND:
return draw_pin('Build N / A', 'lightGray', 'black')
return... | python | {
"resource": ""
} |
q52435 | repository | train | def repository(namespace, name, branch='master'):
'''Returns a repository'''
with TemporaryDirectory() as download_path:
old_directory = str(pwd()).strip()
try:
git.clone('https://github.com/{0}/{1}.git'.format(namespace, name), download_path)
cd(download_path)
... | python | {
"resource": ""
} |
q52436 | ci_data | train | def ci_data(namespace, name, branch='master'):
'''Returns or starts the ci data collection process'''
with repository(namespace, name, branch) as (path, latest, cache):
if not path or not latest:
return {'build_success': NOT_FOUND, 'status': NOT_FOUND}
elif latest in cache:
... | python | {
"resource": ""
} |
q52437 | build_status | train | def build_status(namespace, name, branch='master') -> pin:
'''Returns the current status of the build'''
return ci_data(namespace, name, branch).get('build_success', None) | python | {
"resource": ""
} |
q52438 | worker | train | def worker(namespace, name, branch='master'):
'''The simple_ci background worker process'''
with repository(namespace, name, branch) as (path, latest, cache):
if cache.get(latest, None) and json.loads(cache[latest])['status'] != 'starting':
return 'Build already started'
data = {'st... | python | {
"resource": ""
} |
q52439 | DataPortConnector.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a data connector into this
object.
'''
self.connector_id = node.getAttributeNS(RTS_NS, 'connectorId')
self.name = node.getAttributeNS(RTS_NS, 'name')
self.data_type = node.getAttributeNS(RTS_NS,... | python | {
"resource": ""
} |
q52440 | DataPortConnector.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML specification of a data port connector into this
object.
'''
self.connector_id = y['connectorId']
self.name = y['name']
self.data_type = y['dataType']
self.interface_type = y['interfaceType']
self.data_flow_type = ... | python | {
"resource": ""
} |
q52441 | DataPortConnector.save_xml | train | def save_xml(self, doc, element):
'''Save this data port into an xml.dom.Element object.'''
element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:dataport_connector_ext')
element.setAttributeNS(RTS_NS, RTS_NS_S + 'connectorId',
self.connector_id)
elemen... | python | {
"resource": ""
} |
q52442 | DataPortConnector.to_dict | train | def to_dict(self):
'''Save this data port connector into a dictionary.'''
d = {'connectorId': self.connector_id,
'name': self.name,
'dataType': self.data_type,
'interfaceType': self.interface_type,
'dataflowType': self.data_flow_type,
... | python | {
"resource": ""
} |
q52443 | ServicePortConnector.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a service port connector into
this object.
'''
self.connector_id = node.getAttributeNS(RTS_NS, 'connectorId')
self.name = node.getAttributeNS(RTS_NS, 'name')
if node.hasAttributeNS(RTS_NS, 'tran... | python | {
"resource": ""
} |
q52444 | ServicePortConnector.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML specification of a service port connector into this
object.
'''
self.connector_id = y['connectorId']
self.name = y['name']
if 'transMethod' in y:
self.trans_method = y['transMethod']
else:
self.tran... | python | {
"resource": ""
} |
q52445 | ServicePortConnector.to_dict | train | def to_dict(self):
'''Save this service port connector into a dictionary.'''
d = {'connectorId': self.connector_id,
'name': self.name,
'sourceServicePort': self.source_service_port.to_dict(),
'targetServicePort': self.target_service_port.to_dict()}
... | python | {
"resource": ""
} |
q52446 | Document.render | train | def render(self, doc):
"""Render all elements using specified document.
@param doc: the writable document to render to.
@type doc: document.IWritableDocument
@return: a deferred fired with the specified document
when the rendering is done.
@rtype: defer.Deferred
... | python | {
"resource": ""
} |
q52447 | RelatedInjector.inject_to | train | def inject_to(self, objects, field_name, get_inject_object = lambda obj: obj,
select_related = None, **kwargs):
'''
``objects`` is an iterable. Related objects
will be attached to elements of this iterable.
``field_name`` is the attached object attribute name
... | python | {
"resource": ""
} |
q52448 | GenericModelManager.for_model | train | def for_model(self, model, content_type=None):
''' Returns all objects that are attached to given model '''
content_type = content_type or ContentType.objects.get_for_model(model)
kwargs = {
self.ct_field: content_type,
self.fk_field: model.pk
... | python | {
"resource": ""
} |
q52449 | extract_rows | train | def extract_rows(data, *rows):
"""Extract rows specified in the argument list.
>>> chart_data.extract_rows([[10,20], [30,40], [50,60]], 1, 2)
[[30,40],[50,60]]
"""
try:
# for python 2.2
# return [data[r] for r in rows]
out = []
for r in rows:
out.append(data[r])
... | python | {
"resource": ""
} |
q52450 | extract_columns | train | def extract_columns(data, *cols):
"""Extract columns specified in the argument list.
>>> chart_data.extract_columns([[10,20], [30,40], [50,60]], 0)
[[10],[30],[50]]
"""
out = []
try:
# for python 2.2:
# return [ [r[c] for c in cols] for r in data]
for r in data:
col = []... | python | {
"resource": ""
} |
q52451 | mean_samples | train | def mean_samples(data, xcol, ycollist):
"""Create a sample list that contains
the mean of the original list.
>>> chart_data.mean_samples([ [1, 10, 15], [2, 5, 10], [3, 8, 33] ], 0, (1, 2))
[(1, 12.5), (2, 7.5), (3, 20.5)]
"""
out = []
numcol = len(ycollist)
try:
for elem in data:
... | python | {
"resource": ""
} |
q52452 | do_kernel | train | def do_kernel(x0, x, l=1.0, kernel=epanechnikov):
"""
Calculate a kernel function on x in the neighborhood of x0
Parameters
----------
x: float array
All values of x
x0: float
The value of x around which we evaluate the kernel
l: float or float array (with shape = x.shape)
... | python | {
"resource": ""
} |
q52453 | bi_square | train | def bi_square(xx, idx=None):
"""
The bi-square weight function calculated over values of xx
Parameters
----------
xx: float array
Notes
-----
This is the first equation on page 831 of [Cleveland79].
"""
ans = np.zeros(xx.shape)
ans[idx] = (1-xx[idx]**2)**2
return ans | python | {
"resource": ""
} |
q52454 | lowess | train | def lowess(x, w, x0, kernel=epanechnikov, l=1, robust=False):
"""
Locally linear regression with the LOWESS algorithm.
Parameters
----------
x: float n-d array
Values of x for which f(x) is known (e.g. measured). The shape of this
is (n, j), where n is the number the dimensions of t... | python | {
"resource": ""
} |
q52455 | ols_matrix | train | def ols_matrix(A, norm_func=None):
"""
Generate the matrix used to solve OLS regression.
Parameters
----------
A: float array
The design matrix
norm: callable, optional
A normalization function to apply to the matrix, before extracting the
OLS matrix.
Notes
--... | python | {
"resource": ""
} |
q52456 | zero_pad | train | def zero_pad(ts, n_zeros):
"""
Pad a nitime.TimeSeries class instance with n_zeros before and after the
data
Parameters
----------
ts : a nitime.TimeSeries class instance
"""
zeros_shape = ts.shape[:-1] + (n_zeros,)
zzs = np.zeros(zeros_shape)
# Concatenate along the t... | python | {
"resource": ""
} |
q52457 | line_broadening | train | def line_broadening(ts, width):
"""
Apply line-broadening to a time-series
Parameters
----------
ts : a nitime.TimeSeries class instance
width : float
The exponential decay time-constant (in seconds)
Returns
-------
A nitime.TimeSeries class instance with windowed data
... | python | {
"resource": ""
} |
q52458 | ppm_idx | train | def ppm_idx(f_ppm, lb, ub):
"""
Create a slice object according to the ppm scale
Parameters
----------
f_ppm : float array
The frequency bins (in the ppm scale). Assumed to be descending
lb,ub : float
The lower/upper bounds for indexing
Returns
-------
idx ... | python | {
"resource": ""
} |
q52459 | phase_correct_zero | train | def phase_correct_zero(spec, phi):
"""
Correct the phases of a spectrum by phi radians
Parameters
----------
spec : float array of complex dtype
The spectrum to be corrected.
phi : float
Returns
-------
spec : float array
The phase corrected spectrum
... | python | {
"resource": ""
} |
q52460 | phase_correct_first | train | def phase_correct_first(spec, freq, k):
"""
First order phase correction.
Parameters
----------
spec : float array
The spectrum to be corrected.
freq : float array
The frequency axis.
k : float
The slope of the phase correction as a function of frequency.
Retu... | python | {
"resource": ""
} |
q52461 | lorentzian | train | def lorentzian(freq, freq0, area, hwhm, phase, offset, drift):
"""
Lorentzian line-shape function
Parameters
----------
freq : float or float array
The frequencies for which the function is evaluated
freq0 : float
The center frequency of the function
area : float
hwhm: float
... | python | {
"resource": ""
} |
q52462 | two_lorentzian | train | def two_lorentzian(freq, freq0_1, freq0_2, area1, area2, hwhm1, hwhm2, phase1,
phase2, offset, drift):
"""
A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and pha... | python | {
"resource": ""
} |
q52463 | gaussian | train | def gaussian(freq, freq0, sigma, amp, offset, drift):
"""
A Gaussian function with flexible offset, drift and amplitude
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return (amp * np.exp(- ((freq - freq0)**2) / (sigma**2) ) +
drift * freq + offset) | python | {
"resource": ""
} |
q52464 | two_gaussian | train | def two_gaussian(freq, freq0_1, freq0_2, sigma1, sigma2, amp1, amp2,
offset, drift):
"""
A two-Gaussian model.
This is simply the sum of two gaussian functions in some part of the
spectrum. Each individual gaussian has its own peak frequency, sigma,
and amp, but they share common offs... | python | {
"resource": ""
} |
q52465 | make_idx | train | def make_idx(f, lb, ub):
"""
This is a little utility function to replace an oft-called set of
operations
Parameters
----------
f : 1d array
A frequency axis along which we want to slice
lb : float
Defines the upper bound of slicing
ub : float
Defines the ... | python | {
"resource": ""
} |
q52466 | Field._compute | train | def _compute(self):
"""
Processes this fields `src` from `ctx.src`.
"""
src_path = self.ctx.src_path
if not src_path.exists:
return NONE
if src_path.is_null:
return None
try:
if self.parse:
value = self.parse(src... | python | {
"resource": ""
} |
q52467 | Field._resolve | train | def _resolve(self):
"""
Resolves this fields `src` with `ctx.src`.
"""
if self.src in (None, NONE):
return None
return self.ctx(src=self.src) | python | {
"resource": ""
} |
q52468 | Field._filter | train | def _filter(self, value):
"""
Predicate used to exclude, False, or include, True, a computed value.
"""
if self.ignores and value in self.ignores:
return False
return True | python | {
"resource": ""
} |
q52469 | Field._validate | train | def _validate(self, value):
"""
Predicate used to determine if a computed value is valid, True, or
not, False.
"""
if value is None and not self.nullable:
self.ctx.errors.invalid('not nullable')
return False
return True | python | {
"resource": ""
} |
q52470 | Field._munge | train | def _munge(self, value):
"""
Possibly munges a value.
"""
if self.translations and value in self.translations:
value = self.translations[value]
return value | python | {
"resource": ""
} |
q52471 | Field._default | train | def _default(self):
"""
Determines default.
"""
if self.ctx.ignore_default:
if not self.ctx.ignore_missing:
self.ctx.errors.missing()
return NOT_SET
if self.default is NOT_SET:
if not self.ctx.ignore_missing:
sel... | python | {
"resource": ""
} |
q52472 | Field.map | train | def map(self, value=NONE):
"""
Executes the steps used to "map" this fields value from `ctx.src` to a
value.
:param value: optional **pre-computed** value.
:return: The successfully mapped value or:
- NONE if one was not found
- ERROR if the field was p... | python | {
"resource": ""
} |
q52473 | String.format | train | def format(self, fmt, **kwargs):
"""
Hooks compute to generate a value from a format string.
"""
def compute(self):
values = {}
try:
for name, field in kwargs.iteritems():
values[name] = reduce(getattr, field.split('.'), self.c... | python | {
"resource": ""
} |
q52474 | String.capture | train | def capture(self, pattern, name=None):
"""
Hooks munge to capture a value based on a regex.
"""
if isinstance(pattern, basestring):
pattern = re.compile(pattern)
def munge(self, value):
match = pattern.match(value)
if not match:
... | python | {
"resource": ""
} |
q52475 | AgencyAgent.initiate | train | def initiate(self, **kwargs):
'''Establishes the connections to database and messaging platform,
taking into account that it might meen performing asynchronous job.'''
run_startup = kwargs.pop('run_startup', True)
setter = lambda value, name: setattr(self, name, value)
d = defe... | python | {
"resource": ""
} |
q52476 | AgencyAgent.snapshot_agent | train | def snapshot_agent(self):
'''Gives snapshot of everything related to the agent'''
protocols = [i.get_agent_side() for i in self._protocols.values()]
return (self.agent, protocols, ) | python | {
"resource": ""
} |
q52477 | AgencyAgent.create_binding | train | def create_binding(self, key, shard=None, public=False,
special_lobby_binding=False):
'''Used by Interest instances.'''
shard = shard or self.get_shard_id()
factory = recipient.Broadcast if public else recipient.Agent
recp = factory(key, shard)
binding = se... | python | {
"resource": ""
} |
q52478 | AgencyAgent._store_instance_id | train | def _store_instance_id(self):
'''
Run at the initialization before calling any code at agent-side.
Ensures that descriptor holds our value, this effectively creates a
lock on the descriptor - if other instance is running somewhere out
there it would get the notification update an... | python | {
"resource": ""
} |
q52479 | AgencyAgent._terminate | train | def _terminate(self):
'''Shutdown agent gently removing the descriptor and
notifying partners.'''
def generate_body():
d = defer.succeed(None)
d.addBoth(defer.drop_param, self.agent.shutdown_agent)
# Delete the descriptor
d.addBoth(lambda _: self.... | python | {
"resource": ""
} |
q52480 | Agency.initiate | train | def initiate(self, database=None, journaler=None, *backends):
'''
Asynchronous part of agency initialization. Needs to be called before
agency is used for anything.
'''
return self._initiate(database=database, journaler=journaler,
backends=backends) | python | {
"resource": ""
} |
q52481 | Agency.set_host_def | train | def set_host_def(self, hostdef):
'''
Sets the hostdef param which will get passed to the Host Agent which
the agency starts if it becomes the master.
'''
if self._hostdef is not None:
self.info("Overwriting previous hostdef, which was %r",
self._... | python | {
"resource": ""
} |
q52482 | Agency.find_agent | train | def find_agent(self, desc):
'''Gives medium class of the agent if the agency hosts it.'''
agent_id = (desc.doc_id
if IDocument.providedBy(desc)
else desc)
self.log("I'm trying to find the agent with id: %s", agent_id)
result = first(x for x in self... | python | {
"resource": ""
} |
q52483 | Agency.snapshot_agents | train | def snapshot_agents(self, force=False):
'''snapshot agents if number of entries from last snapshot if greater
than 1000. Use force=True to override.'''
for agent in self._agents:
agent.check_if_should_snapshot(force) | python | {
"resource": ""
} |
q52484 | Agency.list_agents | train | def list_agents(self):
'''List agents hosted by the agency.'''
t = text_helper.Table(fields=("Agent ID", "Agent class", "State"),
lengths=(40, 25, 15))
return t.render((a._descriptor.doc_id, a.log_category,
a._get_machine_state().name)
... | python | {
"resource": ""
} |
q52485 | Agency.host_agent_call | train | def host_agent_call(self, _method, *args, **kwargs):
'''Public method exposed to all the agency submodules, which need
to call the method on the host agent.
This works regardless if host agent already running or not. If
it is still being started the method will be called when he is ready... | python | {
"resource": ""
} |
q52486 | TargetComponent.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a target component into
this object.
'''
self.component_id = node.getAttributeNS(RTS_NS, 'componentId')
self.instance_name = node.getAttributeNS(RTS_NS, 'instanceName')
for c in node.getElements... | python | {
"resource": ""
} |
q52487 | TargetComponent.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML specification of a target component into this
object.
'''
self.component_id = y['componentId']
self.instance_name = y['instanceName']
if RTS_EXT_NS_YAML + 'properties' in y:
for p in y.get(RTS_EXT_NS_YAML + 'properties... | python | {
"resource": ""
} |
q52488 | TargetComponent.save_xml | train | def save_xml(self, doc, element):
'''Save this target component into an xml.dom.Element object.'''
element.setAttributeNS(RTS_NS, RTS_NS_S + 'componentId',
self.component_id)
element.setAttributeNS(RTS_NS, RTS_NS_S + 'instanceName',
s... | python | {
"resource": ""
} |
q52489 | TargetComponent.to_dict | train | def to_dict(self):
'''Save this target component into a dictionary.'''
d = {'componentId': self.component_id,
'instanceName': self.instance_name}
props = []
for name in self.properties:
p = {'name': name}
if self.properties[name]:
p... | python | {
"resource": ""
} |
q52490 | TargetPort.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a target port into this
object.
'''
super(TargetPort, self).parse_xml_node(node)
self.port_name = node.getAttributeNS(RTS_NS, 'portName')
return self | python | {
"resource": ""
} |
q52491 | TargetPort.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML specification of a target port into this object.'''
super(TargetPort, self).parse_yaml(y)
self.port_name = y['portName']
return self | python | {
"resource": ""
} |
q52492 | TargetPort.save_xml | train | def save_xml(self, doc, element):
'''Save this target port into an xml.dom.Element object.'''
super(TargetPort, self).save_xml(doc, element)
element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:target_port_ext')
element.setAttributeNS(RTS_NS, RTS_NS_S + 'portName', self.port_name) | python | {
"resource": ""
} |
q52493 | TargetPort.to_dict | train | def to_dict(self):
'''Save this target port into a dictionary.'''
d = super(TargetPort, self).to_dict()
d['portName'] = self.port_name
return d | python | {
"resource": ""
} |
q52494 | TargetExecutionContext.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a target execution context
into this object.
'''
super(TargetExecutionContext, self).parse_xml_node(node)
if node.hasAttributeNS(RTS_NS, 'id'):
self.id = node.getAttributeNS(RTS_NS, 'id')
... | python | {
"resource": ""
} |
q52495 | TargetExecutionContext.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML specification of a target execution context into this
object.
'''
super(TargetExecutionContext, self).parse_yaml(y)
if 'id' in y:
self.id = y['id']
else:
self.id = ''
return self | python | {
"resource": ""
} |
q52496 | TargetExecutionContext.save_xml | train | def save_xml(self, doc, element):
'''Save this target execution context into an xml.dom.Element
object.
'''
super(TargetExecutionContext, self).save_xml(doc, element)
element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id) | python | {
"resource": ""
} |
q52497 | TargetExecutionContext.to_dict | train | def to_dict(self):
'''Save this target execution context into a dictionary.'''
d = super(TargetExecutionContext, self).to_dict()
d['id'] = self.id
return d | python | {
"resource": ""
} |
q52498 | Commands.find_agency | train | def find_agency(self, agent_id):
"""
Returns the agency running the agent with agent_id or None.
"""
def has_agent(agency):
for agent in agency._agents:
if agent._descriptor.doc_id == agent_id:
return True
return False
... | python | {
"resource": ""
} |
q52499 | Commands.find_agent | train | def find_agent(self, agent_id):
"""
Return the medium class of the agent with agent_id if the one is
running in simulation.
"""
try:
recp = IRecipient(agent_id)
agent_id = recp.key
except TypeError:
pass
agency = self.find_agenc... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.