code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def disable(self):
"""
Disable the button, if in non-expert mode.
"""
w.ActButton.disable(self)
g = get_root(self).globals
if self._expert:
self.config(bg=g.COL['start'])
else:
self.config(bg=g.COL['startD']) | Disable the button, if in non-expert mode. |
def discussion_is_still_open(self, discussion_type, auto_close_after):
"""
Checks if a type of discussion is still open
are a certain number of days.
"""
discussion_enabled = getattr(self, discussion_type)
if (discussion_enabled and isinstance(auto_close_after, int) and
... | Checks if a type of discussion is still open
are a certain number of days. |
def _check_stream_timeout(started, timeout):
"""Check if the timeout has been reached and raise a `StopIteration` if so.
"""
if timeout:
elapsed = datetime.datetime.utcnow() - started
if elapsed.seconds > timeout:
raise StopIteration | Check if the timeout has been reached and raise a `StopIteration` if so. |
def write_to_file(path, contents, file_type='text'):
"""Write ``contents`` to ``path`` with optional formatting.
Small helper function to write ``contents`` to ``file`` with optional formatting.
Args:
path (str): the path to write to
contents (str, object, or bytes): the contents to write ... | Write ``contents`` to ``path`` with optional formatting.
Small helper function to write ``contents`` to ``file`` with optional formatting.
Args:
path (str): the path to write to
contents (str, object, or bytes): the contents to write to the file
file_type (str, optional): the type of f... |
def _save_db():
"""Serializes the contents of the script db to JSON."""
from pyci.utility import json_serial
import json
vms("Serializing DB to JSON in {}".format(datapath))
with open(datapath, 'w') as f:
json.dump(db, f, default=json_serial) | Serializes the contents of the script db to JSON. |
def insertFile(self, qInserts=False):
"""
API to insert a list of file into DBS in DBS. Up to 10 files can be inserted in one request.
:param qInserts: True means that inserts will be queued instead of done immediately. INSERT QUEUE Manager will perform the inserts, within few minutes.
... | API to insert a list of file into DBS in DBS. Up to 10 files can be inserted in one request.
:param qInserts: True means that inserts will be queued instead of done immediately. INSERT QUEUE Manager will perform the inserts, within few minutes.
:type qInserts: bool
:param filesList: List of dic... |
async def _create_upstream_applications(self):
"""
Create the upstream applications.
"""
loop = asyncio.get_event_loop()
for steam_name, ApplicationsCls in self.applications.items():
application = ApplicationsCls(self.scope)
upstream_queue = asyncio.Queue(... | Create the upstream applications. |
def asBinary(self):
"""Get |ASN.1| value as a text string of bits.
"""
binString = binary.bin(self._value)[2:]
return '0' * (len(self._value) - len(binString)) + binString | Get |ASN.1| value as a text string of bits. |
def _make_methods():
"Automagically generates methods based on the API endpoints"
for k, v in PokeAPI().get_endpoints().items():
string = "\t@BaseAPI._memoize\n"
string += ("\tdef get_{0}(self, id_or_name='', limit=None,"
.format(k.replace('-', '_')) + ' offset=None):\n')
... | Automagically generates methods based on the API endpoints |
def _get_annual_data(self, p_p_id):
"""Get annual data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationAnnuelles"}
try:
... | Get annual data. |
def CrossEntropyFlat(*args, axis:int=-1, **kwargs):
"Same as `nn.CrossEntropyLoss`, but flattens input and target."
return FlattenedLoss(nn.CrossEntropyLoss, *args, axis=axis, **kwargs) | Same as `nn.CrossEntropyLoss`, but flattens input and target. |
def typeset(self, container, text_align, last_line=False):
"""Typeset the line in `container` below its current cursor position.
Advances the container's cursor to below the descender of this line.
`justification` and `line_spacing` are passed on from the paragraph
style. `last_descende... | Typeset the line in `container` below its current cursor position.
Advances the container's cursor to below the descender of this line.
`justification` and `line_spacing` are passed on from the paragraph
style. `last_descender` is the previous line's descender, used in the
vertical posi... |
def _create_identity(id_type=None, username=None, password=None, tenant_id=None,
tenant_name=None, api_key=None, verify_ssl=None,
return_context=False):
"""
Creates an instance of the current identity_class and assigns it to the
module-level name 'identity' by default. If 'return_con... | Creates an instance of the current identity_class and assigns it to the
module-level name 'identity' by default. If 'return_context' is True, the
module-level 'identity' is untouched, and instead the instance is returned. |
def _babi_parser(tmp_dir,
babi_task_id,
subset,
dataset_split,
joint_training=True):
"""Parsing the bAbi dataset (train and test).
Args:
tmp_dir: temp directory to download and extract the dataset
babi_task_id: babi task id
subset: bab... | Parsing the bAbi dataset (train and test).
Args:
tmp_dir: temp directory to download and extract the dataset
babi_task_id: babi task id
subset: babi subset
dataset_split: dataset split (train or eval)
joint_training: if training the model on all tasks.
Returns:
babi_instances: set of trai... |
def mmPrettyPrintTraces(traces, breakOnResets=None):
"""
Returns pretty-printed table of traces.
@param traces (list) Traces to print in table
@param breakOnResets (BoolsTrace) Trace of resets to break table on
@return (string) Pretty-printed table of traces.
"""
assert len(traces) > 0, "N... | Returns pretty-printed table of traces.
@param traces (list) Traces to print in table
@param breakOnResets (BoolsTrace) Trace of resets to break table on
@return (string) Pretty-printed table of traces. |
def get_jobs(plugin_name,
verify_job=True, conn=None):
"""
:param plugin_name: <str>
:param verify_job: <bool>
:param conn: <connection> or <NoneType>
:return: <generator> yields <dict>
"""
job_cur = _jobs_cursor(plugin_name).run(conn)
for job in job_cur:
if verify_j... | :param plugin_name: <str>
:param verify_job: <bool>
:param conn: <connection> or <NoneType>
:return: <generator> yields <dict> |
def shapefile(self, file):
"""
reprojette en WGS84 et recupere l'extend
"""
driver = ogr.GetDriverByName('ESRI Shapefile')
dataset = driver.Open(file)
if dataset is not None:
# from Layer
layer = dataset.GetLayer()
spatialRef ... | reprojette en WGS84 et recupere l'extend |
def commit(self):
"""
Insert the specified text in all selected lines, always
at the same column position.
"""
# Get the number of lines and columns in the last line.
last_line, last_col = self.qteWidget.getNumLinesAndColumns()
# If this is the first ever call t... | Insert the specified text in all selected lines, always
at the same column position. |
def profile_slope(self, kwargs_lens_list, lens_model_internal_bool=None, num_points=10):
"""
computes the logarithmic power-law slope of a profile
:param kwargs_lens_list: lens model keyword argument list
:param lens_model_internal_bool: bool list, indicate which part of the model to co... | computes the logarithmic power-law slope of a profile
:param kwargs_lens_list: lens model keyword argument list
:param lens_model_internal_bool: bool list, indicate which part of the model to consider
:param num_points: number of estimates around the Einstein radius
:return: |
def validate(self):
"""
Verify that the contents of the OpaqueObject are valid.
Raises:
TypeError: if the types of any OpaqueObject attributes are invalid.
"""
if not isinstance(self.value, bytes):
raise TypeError("opaque value must be bytes")
eli... | Verify that the contents of the OpaqueObject are valid.
Raises:
TypeError: if the types of any OpaqueObject attributes are invalid. |
def role_list(endpoint_id):
"""
Executor for `globus access endpoint-role-list`
"""
client = get_client()
roles = client.endpoint_role_list(endpoint_id)
resolved_ids = LazyIdentityMap(
x["principal"] for x in roles if x["principal_type"] == "identity"
)
def principal_str(role):... | Executor for `globus access endpoint-role-list` |
def make_url(self, returnURL, paymentReason, pipelineName,
transactionAmount, **params):
"""
Generate the URL with the signature required for a transaction
"""
# use the sandbox authorization endpoint if we're using the
# sandbox for API calls.
endpoint_... | Generate the URL with the signature required for a transaction |
def add_index(self, attribute, ordered=False):
"""
Adds an index to this map for the specified entries so that queries can run faster.
Example:
Let's say your map values are Employee objects.
>>> class Employee(IdentifiedDataSerializable):
>>> act... | Adds an index to this map for the specified entries so that queries can run faster.
Example:
Let's say your map values are Employee objects.
>>> class Employee(IdentifiedDataSerializable):
>>> active = false
>>> age = None
>>> ... |
def rebin_scale(a, scale=1):
"""Scale an array to a new shape."""
newshape = tuple((side * scale) for side in a.shape)
return rebin(a, newshape) | Scale an array to a new shape. |
def isscalar(cls, dataset, dim):
"""
Tests if dimension is scalar in each subpath.
"""
if not dataset.data:
return True
ds = cls._inner_dataset_template(dataset)
isscalar = []
for d in dataset.data:
ds.data = d
isscalar.append(d... | Tests if dimension is scalar in each subpath. |
def decode(self, s):
"""
Decode special characters encodings found in string I{s}.
@param s: A string to decode.
@type s: str
@return: The decoded string.
@rtype: str
"""
if isinstance(s, basestring) and '&' in s:
for x in self.decodings:
... | Decode special characters encodings found in string I{s}.
@param s: A string to decode.
@type s: str
@return: The decoded string.
@rtype: str |
def tag(self, *tag, **kwtags):
"""Tag a Property instance with metadata dictionary"""
if not tag:
pass
elif len(tag) == 1 and isinstance(tag[0], dict):
self._meta.update(tag[0])
else:
raise TypeError('Tags must be provided as key-word arguments or '
... | Tag a Property instance with metadata dictionary |
def close(self):
"""Close the file, and for mode "w" and "a" write the ending
records."""
if self.fp is None:
return
if self.mode in ("w", "a") and self._didModify: # write ending records
count = 0
pos1 = self.fp.tell()
for zinfo in self.f... | Close the file, and for mode "w" and "a" write the ending
records. |
def posterior(self, x, sigma=1.):
"""Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed"""
pr0 = 1. / self.scale**2 # prior precision
prd = x.size / sigma**2 # data precision
varp = 1. / (pr0 + prd) # posterior variance
mu = varp * (pr0 * self.loc + prd * x.mean... | Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed |
def set_filter(self, filter):
"""Sets the filter to be used for resizing when using this pattern.
See :ref:`FILTER` for details on each filter.
Note that you might want to control filtering
even when you do not have an explicit :class:`Pattern`,
(for example when using :meth:`Co... | Sets the filter to be used for resizing when using this pattern.
See :ref:`FILTER` for details on each filter.
Note that you might want to control filtering
even when you do not have an explicit :class:`Pattern`,
(for example when using :meth:`Context.set_source_surface`).
In th... |
def phase(args):
"""
%prog phase genbankfiles
Input has to be gb file. Search the `KEYWORDS` section to look for PHASE.
Also look for "chromosome" and "clone" in the definition line.
"""
p = OptionParser(phase.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) <... | %prog phase genbankfiles
Input has to be gb file. Search the `KEYWORDS` section to look for PHASE.
Also look for "chromosome" and "clone" in the definition line. |
def transformChildrenToNative(self):
"""
Recursively replace children with their native representation.
Sort to get dependency order right, like vtimezone before vevent.
"""
for childArray in (self.contents[k] for k in self.sortChildKeys()):
for child in childArray:
... | Recursively replace children with their native representation.
Sort to get dependency order right, like vtimezone before vevent. |
def convertDict2Attrs(self, *args, **kwargs):
"""The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Client object for each one, initializing them
one at a time, and changing the attrs attribute (which just
... | The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Client object for each one, initializing them
one at a time, and changing the attrs attribute (which just
holds a list of plain dictionaries) with a MambuC... |
def get_package_version(self, feed, group_id, artifact_id, version, show_deleted=None):
"""GetPackageVersion.
[Preview API] Get information about a package version.
:param str feed: Name or ID of the feed.
:param str group_id: Group ID of the package.
:param str artifact_id: Arti... | GetPackageVersion.
[Preview API] Get information about a package version.
:param str feed: Name or ID of the feed.
:param str group_id: Group ID of the package.
:param str artifact_id: Artifact ID of the package.
:param str version: Version of the package.
:param bool sho... |
def get_title(self, index):
"""Gets the title of a container pages.
Parameters
----------
index : int
Index of the container page
"""
# JSON dictionaries have string keys, so we convert index to a string
index = unicode_type(int(index))
if ind... | Gets the title of a container pages.
Parameters
----------
index : int
Index of the container page |
def _get_labels(self, y):
"""
Construct pylearn2 dataset labels.
Parameters
----------
y : array_like, optional
Labels.
"""
y = np.asarray(y)
if y.ndim == 1:
return y.reshape((y.size, 1))
assert y.ndim == 2
return y | Construct pylearn2 dataset labels.
Parameters
----------
y : array_like, optional
Labels. |
def get_online_date(self, **kwargs):
"""Get the online date from the meta creation date."""
qualifier = kwargs.get('qualifier', '')
content = kwargs.get('content', '')
# Handle meta-creation-date element.
if qualifier == 'metadataCreationDate':
date_match = META_CREAT... | Get the online date from the meta creation date. |
def pst_prior(pst,logger=None, filename=None, **kwargs):
""" helper to plot prior parameter histograms implied by
parameter bounds. Saves a multipage pdf named <case>.prior.pdf
Parameters
----------
pst : pyemu.Pst
logger : pyemu.Logger
filename : str
PDF filename to save plots to. ... | helper to plot prior parameter histograms implied by
parameter bounds. Saves a multipage pdf named <case>.prior.pdf
Parameters
----------
pst : pyemu.Pst
logger : pyemu.Logger
filename : str
PDF filename to save plots to. If None, return figs without saving. Default is None.
kwargs... |
def install_sql_hook():
"""If installed this causes Django's queries to be captured."""
try:
from django.db.backends.utils import CursorWrapper
except ImportError:
from django.db.backends.util import CursorWrapper
try:
real_execute = CursorWrapper.execute
real_executeman... | If installed this causes Django's queries to be captured. |
def cas2mach(Vcas, H):
"""Calibrated Airspeed to Mach number"""
Vtas = cas2tas(Vcas, H)
Mach = tas2mach(Vtas, H)
return Mach | Calibrated Airspeed to Mach number |
def __create(self, client_id, cc_number, cvv, expiration_month,
expiration_year, user_name, email, address, **kwargs):
"""Call documentation: `/credit_card/create
<https://www.wepay.com/developer/reference/credit_card#create>`_, plus
extra keyword parameter:
:ke... | Call documentation: `/credit_card/create
<https://www.wepay.com/developer/reference/credit_card#create>`_, plus
extra keyword parameter:
:keyword bool batch_mode: turn on/off the batch_mode, see
:class:`wepay.api.WePay`
:keyword str batch_reference_id: `reference_id... |
def combo_exhaustive_label_definition_check( self,
ontology: pd.DataFrame,
label_predicate:str,
definition_predicates:str,
d... | Combo of label & definition exhaustive check out of convenience
Args:
ontology: pandas DataFrame created from an ontology where the colnames are predicates
and if classes exist it is also thrown into a the colnames.
label_predicate: usually in qname form ... |
def check(self, item_id):
"""Check if an analysis is complete
:type item_id: int
:param item_id: task_id to check.
:rtype: bool
:return: Boolean indicating if a report is done or not.
"""
response = self._request("tasks/view/{id}".format(id=item_id))
... | Check if an analysis is complete
:type item_id: int
:param item_id: task_id to check.
:rtype: bool
:return: Boolean indicating if a report is done or not. |
def make_chunks_from_unused(self,length,trig_overlap,play=0,min_length=0,
sl=0,excl_play=0,pad_data=0):
"""
Create an extra chunk that uses up the unused data in the science segment.
@param length: length of chunk in seconds.
@param trig_overlap: length of time start generating triggers before the
... | Create an extra chunk that uses up the unused data in the science segment.
@param length: length of chunk in seconds.
@param trig_overlap: length of time start generating triggers before the
start of the unused data.
@param play:
- 1 : only generate chunks that overlap with S2 playground... |
def show_user(self, login=None, envs=[], query='/users/'):
"""
`login` - Login or username of user
Show user in specified environments
"""
juicer.utils.Log.log_debug("Show User: %s", login)
# keep track of which iteration of environment we're in
count = 0
... | `login` - Login or username of user
Show user in specified environments |
def safe_makedirs(path):
"""Safe makedirs.
Works in a multithreaded scenario.
"""
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError:
if not os.path.exists(path):
raise | Safe makedirs.
Works in a multithreaded scenario. |
def condition_details_has_owner(condition_details, owner):
"""Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True... | Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True if the public key is found in the condition details, False otherw... |
def cold_spell_days(tas, thresh='-10 degC', window=5, freq='AS-JUL'):
r"""Cold spell days
The number of days that are part of a cold spell, defined as five or more consecutive days with mean daily
temperature below a threshold in °C.
Parameters
----------
tas : xarrray.DataArray
Mean dai... | r"""Cold spell days
The number of days that are part of a cold spell, defined as five or more consecutive days with mean daily
temperature below a threshold in °C.
Parameters
----------
tas : xarrray.DataArray
Mean daily temperature [℃] or [K]
thresh : str
Threshold temperature bel... |
def get_gender(self, name, country=None):
"""Returns best gender for the given name and country pair"""
if not self.case_sensitive:
name = name.lower()
if name not in self.names:
return self.unknown_value
elif not country:
def counter(country_values):... | Returns best gender for the given name and country pair |
def p_statement_list_1(self, p):
'''statement_list : statement SEMICOLON statement_list'''
p[0] = p[3]
if p[1] is not None:
p[0].children.insert(0, p[1]) | statement_list : statement SEMICOLON statement_list |
def unhandle(self, handler):
""" unregister handler (removing callback function) """
with self._hlock:
try:
self._handler_list.remove(handler)
except ValueError:
raise ValueError("Handler is not handling this event, so cannot unhandle it.")
... | unregister handler (removing callback function) |
def average_repetitions(df, keys_mean):
"""average duplicate measurements. This requires that IDs and norrec labels
were assigned using the *assign_norrec_to_df* function.
Parameters
----------
df
DataFrame
keys_mean: list
list of keys to average. For all other keys the first en... | average duplicate measurements. This requires that IDs and norrec labels
were assigned using the *assign_norrec_to_df* function.
Parameters
----------
df
DataFrame
keys_mean: list
list of keys to average. For all other keys the first entry will be
used. |
def from_json_format(conf):
'''Convert fields of parsed json dictionary to python format'''
if 'fmode' in conf:
conf['fmode'] = int(conf['fmode'], 8)
if 'dmode' in conf:
conf['dmode'] = int(conf['dmode'], 8) | Convert fields of parsed json dictionary to python format |
def insert_object(self, db_object):
"""Create new entry in the database.
Parameters
----------
db_object : (Sub-class of)ObjectHandle
"""
# Create object using the to_dict() method.
obj = self.to_dict(db_object)
obj['active'] = True
self.collecti... | Create new entry in the database.
Parameters
----------
db_object : (Sub-class of)ObjectHandle |
def _copy_files(source, target):
"""
Copy all the files in source directory to target.
Ignores subdirectories.
"""
source_files = listdir(source)
if not exists(target):
makedirs(target)
for filename in source_files:
full_filename = join(source, filename)
if isfile(fu... | Copy all the files in source directory to target.
Ignores subdirectories. |
def _query(action=None,
command=None,
args=None,
method='GET',
header_dict=None,
data=None,
url='https://api.linode.com/'):
'''
Make a web call to the Linode API.
'''
global LASTCALL
vm_ = get_configured_provider()
ratelimit_slee... | Make a web call to the Linode API. |
def bind(function, *args, **kwargs):
"""
Wraps the given function such that when it is called, the given arguments
are passed in addition to the connection argument.
:type function: function
:param function: The function that's ought to be wrapped.
:type args: list
:param args: Passed on ... | Wraps the given function such that when it is called, the given arguments
are passed in addition to the connection argument.
:type function: function
:param function: The function that's ought to be wrapped.
:type args: list
:param args: Passed on to the called function.
:type kwargs: dict
... |
def clear(
self # type: ORMTask
):
"""Delete all objects created by this task.
Iterate over `self.object_classes` and delete all objects of the listed classes.
"""
# mark this task as incomplete
self.mark_incomplete()
# delete objects
for object... | Delete all objects created by this task.
Iterate over `self.object_classes` and delete all objects of the listed classes. |
def _group_until_different(items: Iterable[TIn],
key: Callable[[TIn], TKey],
value=lambda e: e):
"""Groups runs of items that are identical according to a keying function.
Args:
items: The items to group.
key: If two adjacent items produce t... | Groups runs of items that are identical according to a keying function.
Args:
items: The items to group.
key: If two adjacent items produce the same output from this function,
they will be grouped.
value: Maps each item into a value to put in the group. Defaults to the
... |
def get_instance(self, payload):
"""
Build an instance of ShortCodeInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.short_code.ShortCodeInstance
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance
"""
... | Build an instance of ShortCodeInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.short_code.ShortCodeInstance
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance |
def to_bytes(value):
"""Converts bytes, unicode, and C char arrays to bytes.
Unicode strings are encoded to UTF-8.
"""
if isinstance(value, text_type):
return value.encode('utf-8')
elif isinstance(value, ffi.CData):
return ffi.string(value)
elif isinstance(value, binary_type):
... | Converts bytes, unicode, and C char arrays to bytes.
Unicode strings are encoded to UTF-8. |
def get_current_channel(self):
"""Get the current tv channel."""
self.request(EP_GET_CURRENT_CHANNEL)
return {} if self.last_response is None else self.last_response.get('payload') | Get the current tv channel. |
def unwatch(value):
"""Return the :class:`Specatator` of a :class:`Watchable` instance."""
if not isinstance(value, Watchable):
raise TypeError("Expected a Watchable, not %r." % value)
spectator = watcher(value)
try:
del value._instance_spectator
except Exception:
pass
re... | Return the :class:`Specatator` of a :class:`Watchable` instance. |
def load_template_source(self, *ka):
"""
Backward compatible method for Django < 2.0.
"""
template_name = ka[0]
for origin in self.get_template_sources(template_name):
try:
return self.get_contents(origin), origin.name
except TemplateDoesNo... | Backward compatible method for Django < 2.0. |
def getChildren(self, name=None, ns=None):
"""
Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type n... | Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching c... |
def _server_response_handler(self, response: Dict[str, Any]):
"""处理100~199段状态码,针对不同的服务响应进行操作.
Parameters:
(response): - 响应的python字典形式数据
Return:
(bool): - 准确地说没有错误就会返回True
"""
code = response.get("CODE")
if code == 100:
if self.debug:... | 处理100~199段状态码,针对不同的服务响应进行操作.
Parameters:
(response): - 响应的python字典形式数据
Return:
(bool): - 准确地说没有错误就会返回True |
def make_repr(inst, attrs):
# type: (object, Sequence[str]) -> str
"""Create a repr from an instance of a class
Args:
inst: The class instance we are generating a repr of
attrs: The attributes that should appear in the repr
"""
arg_str = ", ".join(
"%s=%r" % (a, getattr(inst... | Create a repr from an instance of a class
Args:
inst: The class instance we are generating a repr of
attrs: The attributes that should appear in the repr |
def invalidate_cache(self, klass, instance=None, extra=None,
force_all=False):
"""
Use this method to invalidate keys related to a particular
model or instance. Invalidating a cache is really just
incrementing the version for the right key(s).
:param kla... | Use this method to invalidate keys related to a particular
model or instance. Invalidating a cache is really just
incrementing the version for the right key(s).
:param klass: The model class you are invalidating. If the given \
class was not registered with this group no action will be ... |
def enable_host_event_handler(self, host):
"""Enable event handlers for a host
Format of the line that triggers function call::
ENABLE_HOST_EVENT_HANDLER;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None
"""
if not... | Enable event handlers for a host
Format of the line that triggers function call::
ENABLE_HOST_EVENT_HANDLER;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None |
def activate():
"""
Activates the version specified in ``env.project_version`` if it is different
from the current active version.
An active version is just the version that is symlinked.
"""
env_path = '/'.join([deployment_root(),'env',env.project_fullname])
if not exists(env_path):
... | Activates the version specified in ``env.project_version`` if it is different
from the current active version.
An active version is just the version that is symlinked. |
def header(msg, *args, **kwargs):
'''Display an header'''
msg = ' '.join((yellow(HEADER), white(msg), yellow(HEADER)))
echo(msg, *args, **kwargs) | Display an header |
def setup_zmq(self):
"""Set up a PUSH and a PULL socket. The PUSH socket will push out
requests to the workers. The PULL socket will receive responses from
the workers and reply through the server socket."""
self.context = zmq.Context()
self.push = self.context.socket(zmq.PUSH)... | Set up a PUSH and a PULL socket. The PUSH socket will push out
requests to the workers. The PULL socket will receive responses from
the workers and reply through the server socket. |
def annotate(row, ax, x='x', y='y', text='name', xytext=(7, -5), textcoords='offset points', **kwargs):
"""Add a text label to the plot of a DataFrame indicated by the provided axis (ax).
Reference:
https://stackoverflow.com/a/40979683/623735
"""
# idx = row.name
text = row[text] if text in ... | Add a text label to the plot of a DataFrame indicated by the provided axis (ax).
Reference:
https://stackoverflow.com/a/40979683/623735 |
def bytes2guid(s):
"""Converts a serialized GUID to a text GUID"""
assert isinstance(s, bytes)
u = struct.unpack
v = []
v.extend(u("<IHH", s[:8]))
v.extend(u(">HQ", s[8:10] + b"\x00\x00" + s[10:]))
return "%08X-%04X-%04X-%04X-%012X" % tuple(v) | Converts a serialized GUID to a text GUID |
def ListComp(xp, fp, it, test=None):
"""A list comprehension of the form [xp for fp in it if test].
If test is None, the "if test" part is omitted.
"""
xp.prefix = u""
fp.prefix = u" "
it.prefix = u" "
for_leaf = Leaf(token.NAME, u"for")
for_leaf.prefix = u" "
in_leaf = Leaf(token.N... | A list comprehension of the form [xp for fp in it if test].
If test is None, the "if test" part is omitted. |
def GetCallingModuleObjectAndName():
"""Returns the module that's calling into this module.
We generally use this function to get the name of the module calling a
DEFINE_foo... function.
Returns:
The module object that called into this one.
Raises:
AssertionError: if no calling module could be iden... | Returns the module that's calling into this module.
We generally use this function to get the name of the module calling a
DEFINE_foo... function.
Returns:
The module object that called into this one.
Raises:
AssertionError: if no calling module could be identified. |
def extractSNPs(snpsToExtract, options):
"""Extract markers using Plink.
:param snpsToExtract: the name of the file containing markers to extract.
:param options: the options
:type snpsToExtract: str
:type options: argparse.Namespace
:returns: the prefix of the output files.
"""
outP... | Extract markers using Plink.
:param snpsToExtract: the name of the file containing markers to extract.
:param options: the options
:type snpsToExtract: str
:type options: argparse.Namespace
:returns: the prefix of the output files. |
def refresh(self, row=None):
"""Refresh widget"""
for widget in self.selection_widgets:
widget.setEnabled(self.listwidget.currentItem() is not None)
not_empty = self.listwidget.count() > 0
if self.sync_button is not None:
self.sync_button.setEnabled(not_empt... | Refresh widget |
def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None):
"""Translate method's return value for stripping off success flag.
There are a lot of methods which return a "success" boolean and have
several out arguments. Translate such a method to return the out arguments
on success and... | Translate method's return value for stripping off success flag.
There are a lot of methods which return a "success" boolean and have
several out arguments. Translate such a method to return the out arguments
on success and None on failure. |
def get(self):
"""Return form result"""
# It is import to avoid accessing Qt C++ object as it has probably
# already been destroyed, due to the Qt.WA_DeleteOnClose attribute
if self.outfile:
if self.result in ['list', 'dict', 'OrderedDict']:
fd = open(self.out... | Return form result |
def strace(device, trace_address, breakpoint_address):
"""Implements simple trace using the STrace API.
Args:
device (str): the device to connect to
trace_address (int): address to begin tracing from
breakpoint_address (int): address to breakpoint at
Returns:
``None``
"""
j... | Implements simple trace using the STrace API.
Args:
device (str): the device to connect to
trace_address (int): address to begin tracing from
breakpoint_address (int): address to breakpoint at
Returns:
``None`` |
def normpdf(x, mu, sigma):
"""
Describes the relative likelihood that a real-valued random variable X will
take on a given value.
http://en.wikipedia.org/wiki/Probability_density_function
"""
u = (x-mu)/abs(sigma)
y = (1/(math.sqrt(2*pi)*abs(sigma)))*math.exp(-u*u/2)
return y | Describes the relative likelihood that a real-valued random variable X will
take on a given value.
http://en.wikipedia.org/wiki/Probability_density_function |
def __find_incongruities(self, op, index):
"""
Private method. Finds gaps and overlaps in a striplog. Called by
find_gaps() and find_overlaps().
Args:
op (operator): ``operator.gt`` or ``operator.lt``
index (bool): If ``True``, returns indices of intervals with
... | Private method. Finds gaps and overlaps in a striplog. Called by
find_gaps() and find_overlaps().
Args:
op (operator): ``operator.gt`` or ``operator.lt``
index (bool): If ``True``, returns indices of intervals with
gaps after them.
Returns:
Strip... |
def __process_results(results):
"""Processes the result from __query to get valid json from every entry.
:param results: Results from __query
:type results: str
:returns: python list of dictionaries containing the relevant results.
:rtype: list
"""
if 'no match' in results and 'returning 0 ... | Processes the result from __query to get valid json from every entry.
:param results: Results from __query
:type results: str
:returns: python list of dictionaries containing the relevant results.
:rtype: list |
def all(cls, domain=None):
"""
Return all sites
@param domain: The domain to filter by
@type domain: Domain
@rtype: list of Site
"""
Site = cls
site = Session.query(Site)
if domain:
site.filter(Site.domain == domain)
return s... | Return all sites
@param domain: The domain to filter by
@type domain: Domain
@rtype: list of Site |
def compute_samples_displays(
self,
program: Union[circuits.Circuit, schedules.Schedule],
param_resolver: 'study.ParamResolverOrSimilarType' = None,
) -> study.ComputeDisplaysResult:
"""Computes SamplesDisplays in the supplied Circuit or Schedule.
Args:
... | Computes SamplesDisplays in the supplied Circuit or Schedule.
Args:
program: The circuit or schedule to simulate.
param_resolver: Parameters to run with the program.
Returns:
ComputeDisplaysResult for the simulation. |
def print_version(self, file=None):
"""
Outputs version information to the file if specified, or to
the io_manager's stdout if available, or to sys.stdout.
"""
optparse.OptionParser.print_version(self, file)
file.flush() | Outputs version information to the file if specified, or to
the io_manager's stdout if available, or to sys.stdout. |
def set_autoindent(self,value=None):
"""Set the autoindent flag, checking for readline support.
If called with no arguments, it acts as a toggle."""
if value != 0 and not self.has_readline:
if os.name == 'posix':
warn("The auto-indent feature requires the readline l... | Set the autoindent flag, checking for readline support.
If called with no arguments, it acts as a toggle. |
def distinct(self, *args, **_filter):
"""Return all the unique (distinct) values for the given ``columns``.
::
# returns only one row per year, ignoring the rest
table.distinct('year')
# works with multiple columns, too
table.distinct('year', 'country')
... | Return all the unique (distinct) values for the given ``columns``.
::
# returns only one row per year, ignoring the rest
table.distinct('year')
# works with multiple columns, too
table.distinct('year', 'country')
# you can also combine this with a fil... |
def list(payment):
"""
List all the refunds for a payment.
:param payment: The payment object or the payment id
:type payment: resources.Payment|string
:return: A collection of refunds
:rtype resources.APIResourceCollection
"""
if isinstance(payment, res... | List all the refunds for a payment.
:param payment: The payment object or the payment id
:type payment: resources.Payment|string
:return: A collection of refunds
:rtype resources.APIResourceCollection |
def make_model(self, add_indra_json=True):
"""Assemble the CX network from the collected INDRA Statements.
This method assembles a CX network from the set of INDRA Statements.
The assembled network is set as the assembler's cx argument.
Parameters
----------
add_indra_j... | Assemble the CX network from the collected INDRA Statements.
This method assembles a CX network from the set of INDRA Statements.
The assembled network is set as the assembler's cx argument.
Parameters
----------
add_indra_json : Optional[bool]
If True, the INDRA St... |
def make_dot(self, filename_or_stream, auts):
"""Create a graphviz .dot representation of the automaton."""
if isinstance(filename_or_stream, str):
stream = file(filename_or_stream, 'w')
else:
stream = filename_or_stream
dot = DotFile(stream)
... | Create a graphviz .dot representation of the automaton. |
def main():
"""
NAME
convert_samples.py
DESCRIPTION
takes an er_samples or magic_measurements format file and creates an orient.txt template
SYNTAX
convert_samples.py [command line options]
OPTIONS
-f FILE: specify input file, default is er_samples.txt
... | NAME
convert_samples.py
DESCRIPTION
takes an er_samples or magic_measurements format file and creates an orient.txt template
SYNTAX
convert_samples.py [command line options]
OPTIONS
-f FILE: specify input file, default is er_samples.txt
-F FILE: specify output ... |
def get_query_parameters(args, cell_body, date_time=datetime.datetime.now()):
"""Extract query parameters from cell body if provided
Also validates the cell body schema using jsonschema to catch errors before sending the http
request. This validation isn't complete, however; it does not validate recursive schemas... | Extract query parameters from cell body if provided
Also validates the cell body schema using jsonschema to catch errors before sending the http
request. This validation isn't complete, however; it does not validate recursive schemas,
but it acts as a good filter against most simple schemas
Args:
args: arg... |
def get_shortlink(self, shortlink_id_or_url):
"""Retrieve registered shortlink info
Arguments:
shortlink_id_or_url:
Shortlink id or url, assigned by mCASH
"""
if "://" not in shortlink_id_or_url:
shortlink_id_or_url = self.merchant_api_base_url + ... | Retrieve registered shortlink info
Arguments:
shortlink_id_or_url:
Shortlink id or url, assigned by mCASH |
def from_timestamp_pb(cls, stamp):
"""Parse RFC 3339-compliant timestamp, preserving nanoseconds.
Args:
stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message
Returns:
:class:`DatetimeWithNanoseconds`:
an instance matching the times... | Parse RFC 3339-compliant timestamp, preserving nanoseconds.
Args:
stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message
Returns:
:class:`DatetimeWithNanoseconds`:
an instance matching the timestamp message |
def get_module_uuid(plpy, moduleid):
"""Retrieve page uuid from legacy moduleid."""
plan = plpy.prepare("SELECT uuid FROM modules WHERE moduleid = $1;",
('text',))
result = plpy.execute(plan, (moduleid,), 1)
if result:
return result[0]['uuid'] | Retrieve page uuid from legacy moduleid. |
def apply_async(self, args, kwargs, **options):
"""
Put this task on the Celery queue as a singleton. Only one of this type
of task with its distinguishing args/kwargs will be allowed on the
queue at a time. Subsequent duplicate tasks called while this task is
still running will ... | Put this task on the Celery queue as a singleton. Only one of this type
of task with its distinguishing args/kwargs will be allowed on the
queue at a time. Subsequent duplicate tasks called while this task is
still running will just latch on to the results of the running task by
synchron... |
def _dbsetup(self):
""" Create/open local SQLite database
"""
self._dbconn = sqlite3.connect(self._db_file)
# Create table for multiplicons
sql = '''CREATE TABLE multiplicons
(id, genome_x, list_x, parent, genome_y, list_y, level,
number_of_anch... | Create/open local SQLite database |
def compute_alignments(self, prev_state, precomputed_values, mask=None):
"""
Compute the alignment weights based on the previous state.
"""
WaSp = T.dot(prev_state, self.Wa)
UaH = precomputed_values
# For test time the UaH will be (time, output_dim)
if UaH.ndim =... | Compute the alignment weights based on the previous state. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.