code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def _normpath(self, pathname):
"Return path normalized for duscan usage: no trailing slash."
if pathname == :
pathname =
elif pathname.endswith():
pathname = pathname[:-1]
assert not pathname.endswith(), pathname
return pathname | Return path normalized for duscan usage: no trailing slash. |
def _displayattrs(attrib, expandattrs):
if not attrib:
return
if expandattrs:
alist = [ % item for item in sorted(attrib.items())]
else:
alist = list(attrib)
return % .join(alist) | Helper function to display the attributes of a Node object in lexicographic
order.
:param attrib: dictionary with the attributes
:param expandattrs: if True also displays the value of the attributes |
def parse_placeholder(parser, token):
bits = token.split_contents()
count = len(bits)
error_string = % bits[0]
if count <= 1:
raise TemplateSyntaxError(error_string)
name = bits[1]
remaining = bits[2:]
params = {}
simple_options = [, , ]
param_options = [, , ]
all_o... | Parse the `PlaceholderNode` parameters.
Return a tuple with the name and parameters. |
def write_fits(self, data, outfile, extname="SKYMAP", clobber=True):
hdu_prim = fits.PrimaryHDU()
hdu_hpx = self.make_hdu(data, extname=extname)
hl = [hdu_prim, hdu_hpx]
if self.conv.energy_hdu == :
hdu_energy = self.make_energy_bounds_hdu()
elif self.conv.en... | Write input data to a FITS file
data : The data begin stored
outfile : The name of the output file
extname : The HDU extension name
clobber : True -> overwrite existing files |
def _fullqualname_builtin_py2(obj):
if obj.__self__ is None:
module = obj.__module__
qualname = obj.__name__
else:
if inspect.isclass(obj.__self__):
cls = obj.__self__
else:
cls = obj.__self__.__class__
module = cls.__module... | Fully qualified name for 'builtin_function_or_method' objects
in Python 2. |
def reply(
self,
text: str,
quote: bool = None,
parse_mode: str = "",
disable_web_page_preview: bool = None,
disable_notification: bool = None,
reply_to_message_id: int = None,
reply_markup=None
) -> "Message":
if quote is None:
... | Bound method *reply* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_message(
chat_id=message.chat.id,
text="hello",
reply_to_message_id=message.message_id
)
Example:
... |
def sendmail_proxy(subject, email, template, **context):
sendmail.delay(subject.value, email, template, **context) | Cast the lazy_gettext'ed subject to string before passing to Celery |
def extract_references_from_fulltext(fulltext):
fulltext = remove_page_boundary_lines(fulltext)
status = 0
how_found_start = 0
ref_sect_start = get_reference_section_beginning(fulltext)
if ref_sect_start is None:
refs = []
status = 4
LOGGER.debug... | Locate and extract the reference section from a fulltext document.
Return the extracted reference section as a list of strings, whereby each
string in the list is considered to be a single reference line.
E.g. a string could be something like:
'[19] Wilson, A. Unpublished (1986).
@p... |
def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True):
if + TARIFAS[0] not in df.columns:
if convert_kwh:
cols_mwh = [c + t for c in COLS_PVPC for t in TARIFAS if c != ]
df[cols_mwh] = df[cols_mwh].applymap(lambda x: x / 1000.)
gb_t = df.group... | Procesa TCU, CP, FEU diario.
:param df:
:param verbose:
:param convert_kwh:
:return: |
async def async_set_config(self, data):
field = self.deconz_id +
await self._async_set_state_callback(field, data) | Set config of thermostat.
{
"mode": "auto",
"heatsetpoint": 180,
} |
def get_workspaces(self):
data = self.message(MessageType.GET_WORKSPACES, )
return json.loads(data, object_hook=WorkspaceReply) | Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`. |
def restore_region(self, region, bbox=None, xy=None):
if bbox is not None or xy is not None:
if bbox is None:
x1, y1, x2, y2 = region.get_extents()
elif isinstance(bbox, BboxBase):
x1, y1, x2, y2 = bbox.extents
else:
x1... | Restore the saved region. If bbox (instance of BboxBase, or
its extents) is given, only the region specified by the bbox
will be restored. *xy* (a tuple of two floasts) optionally
specifies the new position (the LLC of the original region,
not the LLC of the bbox) where the region will b... |
def _pfp__build(self, stream=None, save_offset=False):
max_size = -1
if stream is None:
core_stream = six.BytesIO()
new_stream = bitwrap.BitwrappedStream(core_stream)
else:
new_stream = stream
for child in self._pfp__children:
cur... | Build the union and write the result into the stream.
:stream: None
:returns: None |
def degrade_to_order(self, new_order):
shift = 2 * (AbstractMOC.HPY_MAX_NORDER - new_order)
ofs = (int(1) << shift) - 1
mask = ~ofs
adda = int(0)
addb = ofs
iv_set = []
for iv in self._interval_set._intervals:
a = (iv[0] + adda) & mask
... | Degrades the MOC instance to a new, less precise, MOC.
The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the
degraded MOC is set to ``new_order``.
Parameters
----------
new_order : int
Maximum depth of the output degra... |
def parse(self, xml_file):
"Get a list of parsed recipes from BeerXML input"
recipes = []
with open(xml_file, "rt") as f:
tree = ElementTree.parse(f)
for recipeNode in tree.iter():
if self.to_lower(recipeNode.tag) != "recipe":
continue
... | Get a list of parsed recipes from BeerXML input |
def getAllExportsAsDict(self, plugin_list=None):
if plugin_list is None:
plugin_list = self._plugins
return {p: self._plugins[p].get_export() for p in plugin_list} | Return all the stats to be exported (list).
Default behavor is to export all the stat
if plugin_list is provided, only export stats of given plugin (list) |
def insert_permission(
self,
file_id,
value,
perm_type,
role,
notify=True,
email_message=None,
with_link=False
):
url = .format(DRIVE_FILES_API_V2_URL, file_id)
payload = {
: value,
: perm_type,
... | Creates a new permission for a file.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str
:param value: user or group e-mail address, domain name
or None for 'default' type.
:type value: str, None
:param perm_type: (optional) The account type.... |
def write_bus_data(self, file):
report = CaseReport(self.case)
buses = self.case.buses
col_width = 8
col_width_2 = col_width * 2 + 1
col1_width = 6
sep = "=" * 6 + " " + ("=" * col_width + " ") * 6 + "\n"
file.write(sep)
file.write("Na... | Writes bus data to a ReST table. |
def http_post(self, path, query_data={}, post_data={}, files=None,
**kwargs):
result = self.http_request(, path, query_data=query_data,
post_data=post_data, files=files, **kwargs)
try:
if result.headers.get(, None) == :
... | Make a POST request to the Gitlab server.
Args:
path (str): Path or full URL to query ('/projects' or
'http://whatever/v4/api/projecs')
query_data (dict): Data to send as query parameters
post_data (dict): Data to send in the body (will be converted t... |
def apply(self, configuration, schema, args):
for name, path in self.arguments.items():
value = getattr(args, name.replace(, ))
if value is not None:
util.set_value(configuration, path, value)
return configuration | Apply the plugin to the configuration.
Inheriting plugins should implement this method to add additional functionality.
Parameters
----------
configuration : dict
configuration
schema : dict
JSON schema
args : argparse.NameSpace
parse... |
def chunkify(iterable, chunksize):
from .queryset import QuerySet
if hasattr(iterable, ) and not isinstance(iterable, QuerySet):
for i in range(0, len(iterable), chunksize):
yield iterable[i:i + chunksize]
else:
chunk = []
for i in iterable:
... | Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``. |
def find_hosts_that_use_template(self, tpl_name):
return [h.host_name for h in self if tpl_name in h.tags if hasattr(h, "host_name")] | Find hosts that use the template defined in argument tpl_name
:param tpl_name: the template name we filter or
:type tpl_name: str
:return: list of the host_name of the hosts that got the template tpl_name in tags
:rtype: list[str] |
def _execute(self, connection, query, fetch=True):
cursor = connection.cursor()
try:
cursor.execute(query)
except Exception as e:
from ambry.mprlib.exceptions import BadSQLError
raise BadSQLError("Failed to execute query: {}; {}".format(query, e))
... | Executes given query using given connection.
Args:
connection (apsw.Connection): connection to the sqlite db who stores mpr data.
query (str): sql query
fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch.
Returns:
... |
def screenshot(self, viewID, filename):
self._connection._sendStringCmd(
tc.CMD_SET_GUI_VARIABLE, tc.VAR_SCREENSHOT, viewID, filename) | screenshot(string, string) -> None
Save a screenshot for the given view to the given filename.
The fileformat is guessed from the extension, the available
formats differ from platform to platform but should at least
include ps, svg and pdf, on linux probably gif, png and jpg as well. |
def get_period_seconds(period):
if isinstance(period, six.string_types):
try:
name = + period.lower()
result = globals()[name]
except KeyError:
msg = "period not in (second, minute, hour, day, month, year)"
raise ValueError(msg)
elif isinstance(period, numbers.Number):
result = period
elif isins... | return the number of seconds in the specified period
>>> get_period_seconds('day')
86400
>>> get_period_seconds(86400)
86400
>>> get_period_seconds(datetime.timedelta(hours=24))
86400
>>> get_period_seconds('day + os.system("rm -Rf *")')
Traceback (most recent call last):
...
ValueError: period not in (secon... |
def parse_json_feed_bytes(data: bytes) -> JSONFeed:
try:
root = json.loads(data)
except json.decoder.JSONDecodeError:
raise FeedJSONError()
return parse_json_feed(root) | Parse a JSON feed from a byte-string containing JSON data. |
def receive_trial_result(self, parameter_id, parameters, value):
value = extract_scalar_reward(value)
if self.optimize_mode == OptimizeMode.Maximize:
value = -value
logger.info("Received trial result.")
logger.info("value is :" + str(value))
logger.info("par... | Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key. |
def get_config(self, config_filename):
x = pyini.Ini(lazy=True, basepath=os.path.join(self.project_dir, ))
for p in reversed(self.apps):
app_path = get_app_dir(p)
filename = os.path.join(app_path, config_filename)
if os.path.exists(filename):
... | Collection all config file in all available apps, and merge them into ini object
:return: ini object |
def parse_opml_bytes(data: bytes) -> OPML:
root = parse_xml(BytesIO(data)).getroot()
return _parse_opml(root) | Parse an OPML document from a byte-string containing XML data. |
def transformer_ffn_layer(x,
hparams,
pad_remover=None,
conv_padding="LEFT",
nonpadding_mask=None,
losses=None,
cache=None,
decode_loop_st... | Feed-forward layer in the transformer.
Args:
x: a Tensor of shape [batch_size, length, hparams.hidden_size]
hparams: hyperparameters for model
pad_remover: an expert_utils.PadRemover object tracking the padding
positions. If provided, when using convolutional settings, the padding
is removed ... |
def is_changed(self, start, end):
left, right = self._get_changed(start, end)
if left < right:
return True
return False | Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1. |
def get_best_fit_parameters_translated_grouped(self):
result_dict = dict()
result_dict[] = [parameters[] for parameters in
self.best_fit_parameters_translated]
result_dict[] = [parameters[] for parameters in
self.best_fit_parame... | Returns the parameters as a dictionary of the 'real units' for the best fit. |
def to_dict(self):
out_dict = {}
out_dict[] = self.commands
out_dict[] = self.configs
out_dict[] = self.name
out_dict[] = {
: self.module_version,
: self.api_version
}
return out_dict | Convert this object into a dictionary.
Returns:
dict: A dict with the same information as this object. |
def powerset(iterable):
"list(powerset([1,2,3])) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) | Calculate the powerset of any iterable.
For a range of integers up to the length of the given list,
make all possible combinations and chain them together as one object.
From https://docs.python.org/3/library/itertools.html#itertools-recipes |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
C = self.COEFFS[imt]
imean = (self._compute_magnitude(rup, C) +
self._compute_distance(rup, dists, C) +
self._get_site_amplification(sites, C) +
self._comp... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def update_state_changes(self, state_changes_data: List[Tuple[str, int]]) -> None:
cursor = self.conn.cursor()
cursor.executemany(
,
state_changes_data,
)
self.maybe_commit() | Given a list of identifier/data state tuples update them in the DB |
def get_form_errors(form):
return {
: form.non_field_errors(),
: OrderedDict(
(field, form.errors[field.name])
for field in form
if field.name in form.errors
)
} | Django form errors do not obey natural field order,
this template tag returns non-field and field-specific errors
:param form: the form instance |
def target_query(plugin, port, location):
return ((r.row[PLUGIN_NAME_KEY] == plugin) &
(r.row[PORT_FIELD] == port) &
(r.row[LOCATION_FIELD] == location)) | prepared ReQL for target |
def _Open(self, path_spec=None, mode=):
if not path_spec:
raise ValueError()
if path_spec.HasParent():
raise errors.PathSpecError()
location = getattr(path_spec, , None)
if location is None:
raise errors.PathSpecError()
self._current_offset = 0
self._size = len(self._fi... | Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like object could not be opened.
OSError: if the ... |
def _auto_positive_symbol(tokens, local_dict, global_dict):
result = []
tokens.append((None, None))
for tok, nextTok in zip(tokens, tokens[1:]):
tokNum, tokVal = tok
nextTokNum, nextTokVal = nextTok
if tokNum == token.NAME:
name = tokVal
if name in glo... | Inserts calls to ``Symbol`` for undefined variables.
Passes in positive=True as a keyword argument.
Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol |
def normalize_to_range(
values,
minimum = 0.0,
maximum = 1.0
):
normalized_values = []
minimum_value = min(values)
maximum_value = max(values)
for value in values:
numerator = value - minimum_value
denominator = maximum_value - minimum_value
value_normalize... | This function normalizes values of a list to a specified range and returns
the original object if the values are not of the types integer or float. |
def _parse(self):
parser = None
previous = None
for line in self.lines:
parser = self._get_mapping(line, parser, previous)
if parser:
parser(line)
previous = line | parse is the base function for parsing the Dockerfile, and extracting
elements into the correct data structures. Everything is parsed into
lists or dictionaries that can be assembled again on demand.
Environment: Since Docker also exports environment as we go,
... |
def share_file(comm, path):
localrank, _ = get_local_rank_size(comm)
if comm.Get_rank() == 0:
with open(path, ) as fh:
data = fh.read()
comm.bcast(data)
else:
data = comm.bcast(None)
if localrank == 0:
os.makedirs(os.path.dirname(path), exist_ok=T... | Copies the file from rank 0 to all other ranks
Puts it in the same place on all machines |
def update_model_cache(table_name):
model_cache_info = ModelCacheInfo(table_name, uuid.uuid4().hex)
model_cache_backend.share_model_cache_info(model_cache_info) | Updates model cache by generating a new key for the model |
def plot(self, series, series_diff=None, label=, color=None, style=None):
color = self.get_color(color)
if series_diff is None and self.autodiffs:
series_diff = series.diff()
if self.stacked:
series += self.running_sum
self.ax1.fill_between(series.ind... | :param pandas.Series series:
The series to be plotted, all values must be positive if stacked
is True.
:param pandas.Series series_diff:
The series representing the diff that will be plotted in the
bottom part.
:param string label:
The label fo... |
def apply_cmap(zs, cmap, vmin=None, vmax=None):
if vmin is None: vmin = np.min(zs)
if vmax is None: vmax = np.max(zs)
if pimms.is_str(cmap): cmap = matplotlib.cm.get_cmap(cmap)
return cmap((zs - vmin) / (vmax - vmin)) | apply_cmap(z, cmap) applies the given cmap to the values in z; if vmin and/or vmad are passed,
they are used to scale z. |
def add_log_file(logger, log_file, global_log_file=False):
if global_log_file:
add_root_log_file(log_file)
else:
hdlr = logging.FileHandler(log_file)
formatter = logging.Formatter(, datefmt=)
hdlr.setFormatter(formatter)
logger.addHan... | Add a log file to this logger. If global_log_file is true, log_file will be handed the root logger, otherwise it will only be used by this particular logger.
Parameters
----------
logger :obj:`logging.Logger`
The logger.
log_file :obj:`str`
The path to the log fi... |
def run_hooks(self, name, event=None, context=None):
hooks = {
"pre:setup": lambda p: p.pre_setup(self),
"post:setup": lambda p: p.post_setup(self),
"pre:invoke": lambda p: p.pre_invoke(event, context),
"post:invoke": lambda p: p.post_invoke(event, contex... | Runs plugin hooks for each registered plugin. |
def get_next_rngruns(self):
available_runs = [result[][] for result in
self.get_results()]
yield from DatabaseManager.get_next_values(available_runs) | Yield the next RngRun values that can be used in this campaign. |
def _set_vlan_and_bd(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=vlan_and_bd.vlan_and_bd, is_container=, presence=False, yang_name="vlan-and-bd", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths... | Setter method for vlan_and_bd, mapped from YANG variable /overlay_gateway/map/vlan_and_bd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan_and_bd is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... |
def _cleanRecursive(self, subSelf):
for key, item in list(subSelf.items()):
if self.isNestedDict(item):
if not item:
subSelf.pop(key)
else:
self._cleanRecursive(item) | Delete all NestedOrderedDict that haven't any entries. |
def resize_pty(self, width=80, height=24):
if self.closed or self.eof_received or self.eof_sent or not self.active:
raise SSHException()
m = Message()
m.add_byte(chr(MSG_CHANNEL_REQUEST))
m.add_int(self.remote_chanid)
m.add_string()
m.add_boolean(True... | Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous L{get_pty} call.
@param width: new width (in characters) of the terminal screen
@type width: int
@param height: new height (in characters) of the terminal screen
... |
def region_est_hull(self, level=0.95, modelparam_slice=None):
points = self.est_credible_region(
level=level,
modelparam_slice=modelparam_slice
)
hull = ConvexHull(points)
return points[hull.simplices], points[u.uniquify(hull.vertices.flatten())] | Estimates a credible region over models by taking the convex hull of
a credible subset of particles.
:param float level: The desired crediblity level (see
:meth:`SMCUpdater.est_credible_region`).
:param slice modelparam_slice: Slice over which model parameters
to conside... |
def _split_path(xj_path):
res = xj_path.rsplit(, 1)
root_key = res[0]
if len(res) > 1:
return root_key, res[1]
else:
if root_key and root_key != :
return None, root_key
else:
raise XJPathError(, (xj_path,)) | Extract the last piece of XJPath.
:param str xj_path: A XJPath expression.
:rtype: tuple[str|None, str]
:return: A tuple where first element is a root XJPath and the second is
a last piece of key. |
def _configure_pool(kwargs):
_pool_single_run.storage_service = kwargs[]
_configure_niceness(kwargs)
_configure_logging(kwargs, extract=False) | Configures the pool and keeps the storage service |
def _numeric_coercion(value,
coercion_function = None,
allow_empty = False,
minimum = None,
maximum = None):
if coercion_function is None:
raise errors.CoercionFunctionEmptyError()
elif not hasattr(coercion_func... | Validate that ``value`` is numeric and coerce using ``coercion_function``.
:param value: The value to validate.
:param coercion_function: The function to use to coerce ``value`` to the desired
type.
:type coercion_function: callable
:param allow_empty: If ``True``, returns :obj:`None <python:No... |
def removeUnreferencedIDs(referencedIDs, identifiedElements):
global _num_ids_removed
keepTags = []
num = 0
for id in identifiedElements:
node = identifiedElements[id]
if id not in referencedIDs and node.nodeName not in keepTags:
node.removeAttribute()
_num_i... | Removes the unreferenced ID attributes.
Returns the number of ID attributes removed |
def _load(self):
if self.is_exists():
return open(self._ref, "rb").read()
raise NotFoundError("File %s not found" % self._ref) | Function load.
:return: file contents
:raises: NotFoundError if file not found |
def do_your_job(self):
y,x = self.get_intended_direction()
if self.target_x == self.current_x and self.target_y == self.current_y:
if len(self.results) == 0:
self.results.append("TARGET ACQUIRED")
self.lg_mv(2, self.name + ": TARGET ACQ... | the goal of the explore agent is to move to the
target while avoiding blockages on the grid.
This function is messy and needs to be looked at.
It currently has a bug in that the backtrack oscillates
so need a new method of doing this - probably checking if
previously backtracked... |
def delete_payment_card_by_id(cls, payment_card_id, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._delete_payment_card_by_id_with_http_info(payment_card_id, **kwargs)
else:
(data) = cls._delete_payment_card_by_id_with_http_info(payment_card_id, **kwargs)... | Delete PaymentCard
Delete an instance of PaymentCard by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_payment_card_by_id(payment_card_id, async=True)
>>> result = thread.get()... |
def set_account_username(self, account, old_username, new_username):
self._delete_account(account, old_username)
self._save_account(account, new_username) | Account's username was changed. |
def fix_config(self, options):
options = super(FileOutputSink, self).fix_config(options)
opt = "output"
if opt not in options:
options[opt] = "."
if opt not in self.help:
self.help[opt] = "The file to write to (string)."
return options | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict |
def fix_path(path):
if in path:
path = path.replace(, )
path = os.path.normpath(path)
return path | Fix windows path's. Linux path's will remain unaltered
:param str path: The path to be fixed
:return: The fixed path
:rtype: str |
def getPluginActions(self, index):
index = self.data["proxies"]["plugin"].mapToSource(
self.data["proxies"]["plugin"].index(
index, 0, QtCore.QModelIndex())).row()
item = self.data["models"]["item"].items[index]
actions = [
dict(action,... | Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model |
def transitivity_wu(W):
triangles to triplets
K = np.sum(np.logical_not(W == 0), axis=1)
ws = cuberoot(W)
cyc3 = np.diag(np.dot(ws, np.dot(ws, ws)))
return np.sum(cyc3, axis=0) / np.sum(K * (K - 1), axis=0) | Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
T : int
transitivity scalar |
def pressure_series(self):
return [(tstamp, \
self._station_history.get_measurements()[tstamp][]) \
for tstamp in self._station_history.get_measurements()] | Returns the atmospheric pressure time series relative to the
meteostation, in the form of a list of tuples, each one containing the
couple timestamp-value
:returns: a list of tuples |
def string_to_datetime(self, obj):
if isinstance(obj, six.string_types) and len(obj) == 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
if isinstance(obj, six.string_types) and len(obj) > 19:
... | Decode a datetime string to a datetime object |
def union_q(token):
query = Q()
operation =
negation = False
for t in token:
if type(t) is ParseResults:
query &= union_q(t)
else:
if t in (, ):
operation = t
elif t == :
negation = True
else:
... | Appends all the Q() objects. |
def is_closed(self):
old_training_data = self.training_data
self.training_data = {x: [] for x in self.sm_vector}
for t in self.smi_vector:
src_state = t[:-1]
symbol = t[-1:]
found = False
for dst_state in self.sm_vector:
if... | _check if the observation table is closed.
Args:
None
Returns:
tuple (bool, str): True if the observation table is closed and false otherwise.
If the table is not closed the escaping string is returned. |
def add_answer_for_student(student_item, vote, rationale):
answers = get_answers_for_student(student_item)
answers.add_answer(vote, rationale)
sub_api.create_submission(student_item, {
ANSWER_LIST_KEY: answers.get_answers_as_list()
}) | Add an answer for a student to the backend
Args:
student_item (dict): The location of the problem this submission is
associated with, as defined by a course, student, and item.
vote (int): the option that student voted for
rationale (str): the reason why the student vote for the... |
def handle_flush_error(cls, exception):
trace = exception.args[0]
m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace)
if not m:
raise exception
entity = m.group()
eid = m.group()
raise AlreadyExistsError(entity=entity, eid=eid) | Handle flush error exceptions. |
def _decade_ranges_in_date_range(self, begin_date, end_date):
begin_dated = begin_date.year / 10
end_dated = end_date.year / 10
decades = []
for d in range(begin_dated, end_dated + 1):
decades.append(.format(d * 10, d * 10 + 9))
return decades | Return a list of decades which is covered by date range. |
def cv_precompute(self, mask, b):
m1 = self.get_masked_chunk(b)
flux = self.fraw[m1]
K = GetCovariance(self.kernel, self.kernel_params,
self.time[m1], self.fraw_err[m1])
med = np.nanmedian(flux)
M = lambda x, axis = 0: np.del... | Pre-compute the matrices :py:obj:`A` and :py:obj:`B`
(cross-validation step only)
for chunk :py:obj:`b`. |
def _get_output_nodes(self, output_path, error_path):
from pymatgen.io.nwchem import NwOutput
from aiida.orm.data.structure import StructureData
from aiida.orm.data.array.trajectory import TrajectoryData
ret_dict = []
nwo = NwOutput(output_path)
for out in nwo.d... | Extracts output nodes from the standard output and standard error
files. |
def Negative(other_param, mode="invert", reroll_count_max=2):
return ForceSign(
other_param=other_param,
positive=False,
mode=mode,
reroll_count_max=reroll_count_max
) | Converts another parameter's results to negative values.
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
Other parameter which's sampled values are to be
modified.
mode : {'invert', 'reroll'}, optional
How to change the signs. Valid values are ``invert... |
def step(self):
with self.__lock:
self.__value -= 1
if self.__value == 0:
self.__event.set()
return True
elif self.__value < 0:
raise ValueError("The counter has gone below 0")... | Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0 |
def write(self, filename):
with open(filename, ) as f:
f.write(self.ascii)
self.print("Detector file saved as ".format(filename)) | Save detx file. |
def follower_ids(self, user):
user = str(user)
user = user.lstrip()
url =
if re.match(r, user):
params = {: user, : -1}
else:
params = {: user, : -1}
while params[] != 0:
try:
resp = self.get(url, params=para... | Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id |
def main():
org = Organization(name=).create()
pprint(org.get_values())
org.delete() | Create an organization, print out its attributes and delete it. |
def from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs):
pdb = loader(path)
box = kwargs.pop(, pdb.topology.getPeriodicBoxVectors())
positions = kwargs.pop(, pdb.positions)
velocities = kwargs.pop(, getattr(pdb, , None))
if strict and not forcefi... | Loads topology, positions and, potentially, velocities and vectors,
from a PDB or PDBx file
Parameters
----------
path : str
Path to PDB/PDBx file
forcefields : list of str
Paths to FFXML and/or FRCMOD forcefields. REQUIRED.
Returns
-----... |
def normalize_scientific_notation(s, ignore_commas=True, verbosity=1):
s = s.lstrip(charlist.not_digits_nor_sign)
s = s.rstrip(charlist.not_digits)
num_strings = rex.scientific_notation_exponent.split(s, maxsplit=2)
s = rex.re.sub(r"[^.0-9-+" + "," * int(not ignore_commas) + r"]... | Produce a string convertable with float(s), if possible, fixing some common scientific notations
Deletes commas and allows addition.
>>> normalize_scientific_notation(' -123 x 10^-45 ')
'-123e-45'
>>> normalize_scientific_notation(' -1+1,234 x 10^-5,678 ')
'1233e-5678'
>>> normalize_scientific_... |
def mutable(function):
def wrapper(self, *args, **kwargs):
state = self._get_state()
return function(self, state, *args, **kwargs)
return wrapper | Add the instance internal state as the second parameter
of the decorated function. |
def dict_to_serialized_dict(ref, the_dict):
result = {}
for elt in list(the_dict.values()):
if not getattr(elt, , None):
continue
result[elt.uuid] = elt.serialize()
return result | Serialize the list of elements to a dictionary
Used for the retention store
:param ref: Not used
:type ref:
:param the_dict: dictionary to convert
:type the_dict: dict
:return: dict of serialized
:rtype: dict |
def loads(cls, pickle_string):
cls.load_counter_offset = StoreOptions.id_offset()
val = pickle.loads(pickle_string)
cls.load_counter_offset = None
return val | Equivalent to pickle.loads except that the HoloViews trees is
restored appropriately. |
def start(self, request: Request) -> Response:
if self._session_state != SessionState.ready:
raise RuntimeError()
response = Response()
yield from self._prepare_fetch(request, response)
response.file_transfer_size = yield from self._fetch_size(request)
if... | Start a file or directory listing download.
Args:
request: Request.
Returns:
A Response populated with the initial data connection reply.
Once the response is received, call :meth:`download`.
Coroutine. |
def _parse_status(self, status):
m = rented_regex.search(status)
if m:
self.status = HouseStatus.RENTED
self.owner = m.group("owner")
self.owner_sex = Sex.MALE if m.group("pronoun") == "He" else Sex.FEMALE
self.paid_until = parse_tibia_datetime(m.... | Parses the house's state description and applies the corresponding values
Parameters
----------
status: :class:`str`
Plain text string containing the current renting state of the house. |
def getmembers_runtime(self):
names = set()
for scope in self.scopes:
names.update(structured.getmembers_runtime(scope))
return names | Gets members (vars) from all scopes using ONLY runtime information.
You most likely want to use ScopeStack.getmembers instead.
Returns:
Set of available vars.
Raises:
NotImplementedError if any scope fails to implement 'getmembers'. |
def findAttr(self, svgNode, name):
if self.css_rules is not None and not svgNode.attrib.get(, False):
if isinstance(svgNode, NodeTracker):
svgNode.apply_rules(self.css_rules)
else:
ElementWrapper(svgNode).apply_rules(self.css_rules)
... | Search an attribute with some name in some node or above.
First the node is searched, then its style attribute, then
the search continues in the node's parent node. If no such
attribute is found, '' is returned. |
def _consolidate_elemental_array_(elemental_array):
condensed_array = []
for e in elemental_array:
exists = False
for k in condensed_array:
if k["symbol"] == e["symbol"]:
exists = True
k["occurances"] += e["occurances"]
break
... | Accounts for non-empirical chemical formulas by taking in the compositional array generated by _create_compositional_array_() and returning a consolidated array of dictionaries with no repeating elements
:param elemental_array: an elemental array generated from _create_compositional_array_()
:return: an array ... |
def parse_annotation(obj: dict) -> BioCAnnotation:
ann = BioCAnnotation()
ann.id = obj[]
ann.infons = obj[]
ann.text = obj[]
for loc in obj[]:
ann.add_location(BioCLocation(loc[], loc[]))
return ann | Deserialize a dict obj to a BioCAnnotation object |
def update_experiments(self):
for field in record_get_field_instances(self.record, ):
subs = field_get_subfields(field)
acc_experiment = subs.get("e", [])
if not acc_experiment:
acc_experiment = subs.get("a", [])
if not acc_ex... | Experiment mapping. |
def lines(self):
if self.cache_content and self.cached_content:
return self.cached_content.splitlines(True)
try:
with self._open_dockerfile() as dockerfile:
lines = [b2u(l) for l in dockerfile.readlines()]
if self.cache_content:
... | :return: list containing lines (unicode) from Dockerfile |
def set_chat_description(self, *args, **kwargs):
return set_chat_description(*args, **self._merge_overrides(**kwargs)).run() | See :func:`set_chat_description` |
def dispatch(self, request, environ):
try:
grant_type = self._determine_grant_type(request)
response = self.response_class()
grant_type.read_validate_params(request)
return grant_type.process(request, response, environ)
except OAuthInvalidNoRed... | Checks which Grant supports the current request and dispatches to it.
:param request: The incoming request.
:type request: :class:`oauth2.web.Request`
:param environ: Dict containing variables of the environment.
:type environ: dict
:return: An instance of ``oauth2.web.Response... |
def get_position(self):
reply = self._intf.query()[2:]
return [float(i) for i in reply.split()] | Read chuck position (x, y, z) |
def get_connections(app):
payload = {: app}
url = os.path.join(settings.HEROKU_CONNECT_API_ENDPOINT, )
response = requests.get(url, params=payload, headers=_get_authorization_headers())
response.raise_for_status()
return response.json()[] | Return all Heroku Connect connections setup with the given application.
For more details check the link -
https://devcenter.heroku.com/articles/heroku-connect-api#step-4-retrieve-the-new-connection-s-id
Sample response from the API call is below::
{
"count": 1,
"results":[... |
def _on_new_data_received(self, data: bytes):
if data == b:
self.callback.on_captcha_received(login.CaptchaElement(xml_element)) | Gets called whenever we get a whole new XML element from kik's servers.
:param data: The data received (bytes) |
def dragTo(x=None, y=None, duration=0.0, tween=linear, button=, pause=None, _pause=True, mouseDownUp=True):
_failSafeCheck()
x, y = _unpackXY(x, y)
if mouseDownUp:
mouseDown(button=button, _pause=False)
_mouseMoveDrag(, x, y, 0, 0, duration, tween, button)
if mouseDownUp:
mouse... | Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen.
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the screen, the event happens at edge... |
def CopyToDateTimeString(self):
if (self._timestamp is None or self._timestamp < 0 or
self._timestamp > self._UINT64_MAX):
return None
timestamp, remainder = divmod(self._timestamp, self._100NS_PER_SECOND)
number_of_days, hours, minutes, seconds = self._GetTimeValues(timestamp)
year... | Copies the FILETIME timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#######" or
None if the timestamp is missing or invalid. |
def add_service(self, service):
if (self.service is None):
self.service = service
elif (isinstance(self.service, dict)):
self.service = [self.service, service]
else:
self.service.append(service) | Add a service description.
Handles transition from self.service=None, self.service=dict for a
single service, and then self.service=[dict,dict,...] for multiple |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.