Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
17,300 | def load_data(cr, module_name, filename, idref=None, mode=):
if idref is None:
idref = {}
logger.info( % (module_name, filename))
_, ext = os.path.splitext(filename)
pathname = os.path.join(module_name, filename)
fp = tools.file_open(pathname)
try:
if ext == :
n... | Load an xml, csv or yml data file from your post script. The usual case for
this is the
occurrence of newly added essential or useful data in the module that is
marked with "noupdate='1'" and without "forcecreate='1'" so that it will
not be loaded by the usual upgrade mechanism. Leaving the 'mode' argum... |
17,301 | def set_beeper_mode(self, state):
values = {"desired_state": {"beeper_enabled": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param state: a boolean of ture (on) or false ('off')
:return: nothing |
17,302 | def validate_bands(bands):
if not isinstance(bands, list):
raise TypeError()
valid_bands = list(range(1, 12)) + []
for band in bands:
if band not in valid_bands:
raise InvalidBandError( % band) | Validate bands parameter. |
17,303 | def make_break(lineno, p):
global last_brk_linenum
if not OPTIONS.enableBreak.value or lineno == last_brk_linenum or is_null(p):
return None
last_brk_linenum = lineno
return make_sentence(, make_number(lineno, lineno, TYPE.uinteger)) | Checks if --enable-break is set, and if so, calls
BREAK keyboard interruption for this line if it has not been already
checked |
17,304 | def cache(self):
cache = self._cache or self.app.config.get()
return import_string(cache) if isinstance(cache, six.string_types) \
else cache | Return a cache instance. |
17,305 | def freqpoly_plot(data):
rel_data = OrderedDict()
for key, val in data.items():
tot = sum(val.values(), 0)
rel_data[key] = {k: v / tot for k, v in val.items()}
fplotconfig = {
: [
{: , : , : },
{: , : , : }
... | make freqpoly plot of merged read lengths |
17,306 | def datafield(*path, **kwargs):
if len(path) == 1 and isinstance(path[0], types.FunctionType):
return DataField(**kwargs)(*path)
else:
return DataField(*path, **kwargs) | A decorator that defines a field for data within a :class:`DataStruct`
The decorated function becomes the parser for a :class:`DataField` which
will be assigned to a data structure under the function's defined name.
Parameters
----------
path: tuple
The path to a value within a raw piece o... |
17,307 | def verify_sc_url(url: str) -> bool:
parsed = urlsplit(url)
scheme: str = parsed.scheme
netloc: str = parsed.netloc
path: str = parsed.path
try:
port = parsed.port
except ValueError:
port = None
result = (scheme.lower() == and
netloc.lower().split()[0] ... | Verify signature certificate URL against Amazon Alexa requirements.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances indexes in incoming batch are used as dialog IDs.
Args:
u... |
17,308 | def write_word(self, cmd, value):
self.bus.write_word_data(self.address, cmd, value)
self.log.debug(
"write_word: Wrote 0x%04X to command register 0x%02X" % (
value, cmd
)
) | Writes a 16-bit word to the specified command register |
17,309 | def encode(self, value):
kassert.is_of_types(value, Bits)
if len(value) % 8 != 0:
raise KittyException()
return self._encoder.encode(value.bytes) | :param value: value to encode |
17,310 | def split_list(alist, wanted_parts=1):
length = len(alist)
return [
alist[i * length // wanted_parts:(i + 1) * length // wanted_parts]
for i in range(wanted_parts)
] | A = [0,1,2,3,4,5,6,7,8,9]
print split_list(A, wanted_parts=1)
print split_list(A, wanted_parts=2)
print split_list(A, wanted_parts=8) |
17,311 | def child(self, offset256):
a = bytes(self) + offset256
s = hashlib.sha256(a).digest()
return self.add(s) | Derive new public key from this key and a sha256 "offset" |
17,312 | def render_svg(self, render_id, words, arcs):
self.levels = self.get_levels(arcs)
self.highest_level = len(self.levels)
self.offset_y = self.distance / 2 * self.highest_level + self.arrow_stroke
self.width = self.offset_x + len(words) * self.distance
self.height = self.o... | Render SVG.
render_id (int): Unique ID, typically index of document.
words (list): Individual words and their tags.
arcs (list): Individual arcs and their start, end, direction and label.
RETURNS (unicode): Rendered SVG markup. |
17,313 | def __imap_search(self, ** criteria_dict):
self.imap_connect()
criteria = []
for key in criteria_dict:
if criteria_dict[key] is True:
criteria.append( % key)
else:
criteria.append( % (key, criteria_dict[key]))
st... | Searches for query in the given IMAP criteria and returns
the message numbers that match as a list of strings.
Criteria without values (eg DELETED) should be keyword args
with KEY=True, or else not passed. Criteria with values should
be keyword args of the form KEY="VALUE" where KEY is ... |
17,314 | def inverted(self):
inverse_type = globals()[self._inverse_type]
return inverse_type(self._center_longitude, self._center_latitude,
self._resolution) | Return the inverse of the transform. |
17,315 | def get_volumes(self):
vols = [self.find_volume(name) for name in self.virsp.listVolumes()]
return vols | Return a list of all Volumes in this Storage Pool |
17,316 | def _determine_auth_mechanism(username, password, delegation):
if re.match(, username) is not None:
if delegation is True:
raise Exception()
else:
raise Exception()
legacy = re.match(, username)
if legacy is not None:
... | if the username contains at '@' sign we will use kerberos
if the username contains a '/ we will use ntlm
either NTLM or Kerberos. In fact its basically always Negotiate. |
17,317 | def markup_fragment(source, encoding=None):
s a byte string, not a Unicode object. You might also want to wrap it with amara.lib.inputsource.text if itXXX<html><body onload="" color="white"><p>Spam!<p>Eggs!</body></html>YYY
doc = parse(source, encoding=encoding)
frag = doc.html.body
return frag | Parse a fragment if markup in HTML mode, and return a bindery node
Warning: if you pass a string, you must make sure it's a byte string, not a Unicode object. You might also want to wrap it with amara.lib.inputsource.text if it's not obviously XML or HTML (for example it could be confused with a file name)
f... |
17,318 | def _validate_method_decoration(meta, class_):
super_mro = class_.__mro__[1:]
own_methods = ((name, member)
for name, member in class_.__dict__.items()
if is_method(member))
for name, method in own_metho... | Validate the usage of ``@override`` and ``@final`` modifiers
on methods of the given ``class_``. |
17,319 | def setmonitor(self, enable=True):
if enable:
res = self.setmode()
else:
res = self.setmode()
if not res:
log_runtime.error("Npcap WlanHelper returned with an error code !")
self.cache_mode = None
tmp = self.cache_mode = self.... | Alias for setmode('monitor') or setmode('managed')
Only available with Npcap |
17,320 | def login(config, username=None, password=None, email=None, url=None, client=None, *args, **kwargs):
try:
c = (_get_client(config) if not client else client)
lg = c.login(username, password, email, url)
print "%s logged to %s"%(username,(url if url else "default hub"))
except Except... | Wrapper to the docker.py login method |
17,321 | def update(self):
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data and (time.time() - self.__manual_update_time > 60):
if data[] != "Charging":
self.__charger_state = False
else:... | Update the charging state of the Tesla Vehicle. |
17,322 | def _apply_mt(self, doc_loader, parallelism, **kwargs):
if not Meta.postgres:
raise ValueError("Fonduer must use PostgreSQL as a database backend.")
def fill_input_queue(in_queue, doc_loader, terminal_signal):
for doc in doc_loader:
in_queue.put(doc)
... | Run the UDF multi-threaded using python multiprocessing |
17,323 | def artist_commentary_revert(self, id_, version_id):
params = {: version_id}
return self._get(.format(id_),
params, method=, auth=True) | Revert artist commentary (Requires login) (UNTESTED).
Parameters:
id_ (int): The artist commentary id.
version_id (int): The artist commentary version id to
revert to. |
17,324 | def getaccountaddress(self, user_id=""):
address = self.rpc.call("getaccountaddress", user_id)
self.logger.debug("Your", self.coin, "address is", address)
return address | Get the coin address associated with a user id.
If the specified user id does not yet have an address for this
coin, then generate one.
Args:
user_id (str): this user's unique identifier
Returns:
str: Base58Check address for this account |
17,325 | def config(name, reset=False, **kwargs):
*
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
{0}\.format(name)
)
pkg = next(iter(configuratio... | Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconf... |
17,326 | def validate_sceneInfo(self):
if self.sceneInfo.prefix not in self.__prefixesValid:
raise WrongSceneNameError(
% (self.sceneInfo.name, self.sceneInfo.prefix)) | Check whether sceneInfo is valid to download from AWS Storage. |
17,327 | def _responsify(api_spec, error, status):
result_json = api_spec.model_to_json(error)
r = jsonify(result_json)
r.status_code = status
return r | Take a bravado-core model representing an error, and return a Flask Response
with the given error code and error instance as body |
17,328 | def get_disabled():
*
services = []
for daemon, is_enabled in six.iteritems(_get_rc()):
if not is_enabled:
services.append(daemon)
return sorted(set(get_all()) & set(services)) | .. versionadded:: 2014.7.0
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled |
17,329 | def get_minimum_span(low, high, span):
if is_number(low) and low == high:
if isinstance(low, np.datetime64):
span = span * np.timedelta64(1, )
low, high = low-span, high+span
return low, high | If lower and high values are equal ensures they are separated by
the defined span. |
17,330 | def read_folder(folder):
recordings = []
for filename in glob.glob(os.path.join(folder, )):
recording = parse_scg_ink_file(filename)
recordings.append(recording)
return recordings | Read all files of `folder` and return a list of HandwrittenData
objects.
Parameters
----------
folder : string
Path to a folder
Returns
-------
list :
A list of all .ink files in the given folder. |
17,331 | def EXPGauss(w_F, compute_uncertainty=True, is_timeseries=False):
T = float(np.size(w_F))
var = np.var(w_F)
DeltaF = np.average(w_F) - 0.5 * var
result_vals = dict()
if compute_uncertainty:
g = 1.0
T_eff = T
if is_timeseries:
... | Estimate free energy difference using gaussian approximation to one-sided (unidirectional) exponential averaging.
Parameters
----------
w_F : np.ndarray, float
w_F[t] is the forward work value from snapshot t. t = 0...(T-1) Length T is deduced from vector.
compute_uncertainty : bool, optional... |
17,332 | def setup(self, redis_conn=None, host=, port=6379):
AbstractCounter.setup(self, redis_conn=redis_conn, host=host,
port=port)
self._threaded_start() | Set up the counting manager class
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port |
17,333 | def prepare_stack_for_update(self, stack, tags):
if self.is_stack_destroyed(stack):
return False
elif self.is_stack_completed(stack):
return True
stack_name = self.get_stack_name(stack)
stack_status = self.get_stack_status(stack)
if self.is_sta... | Prepare a stack for updating
It may involve deleting the stack if is has failed it's initial
creation. The deletion is only allowed if:
- The stack contains all the tags configured in the current context;
- The stack is in one of the statuses considered safe to re-create
-... |
17,334 | def u_shape(units: tf.Tensor,
n_hidden_list: List,
filter_width=7,
use_batch_norm=False,
training_ph=None):
units_for_skip_conn = []
conv_net_params = {: filter_width,
: use_batch_norm,
: training_ph}
... | Network architecture inspired by One Hundred layer Tiramisu.
https://arxiv.org/abs/1611.09326. U-Net like.
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
fil... |
17,335 | def deactivate(self):
if self._driver and self._driver.is_connected():
self._driver.deactivate() | Stop heating/cooling and turn off the fan |
17,336 | def _from_binary_objid(cls, binary_stream):
uid_size = ObjectID._UUID_SIZE
uids = [UUID(bytes_le=binary_stream[i*uid_size:(i+1)*uid_size].tobytes()) if i * uid_size < len(binary_stream) else None for i in range(0,4)]
_MOD_LOGGER.debug("Attempted to unpack OBJECT_ID Entry from \"%s\"\nResult:... | See base class. |
17,337 | def baseurl(url):
parsed_url = urlparse.urlparse(url)
if not parsed_url.netloc or parsed_url.scheme not in ("http", "https"):
raise ValueError()
service_url = "%s://%s%s" % (parsed_url.scheme, parsed_url.netloc, parsed_url.path.strip())
return service_url | return baseurl of given url |
17,338 | def _images_succeeded(cls, session):
for image, store in cls._deleted_images:
for stored_image, _ in cls._stored_images:
if stored_image.object_type == image.object_type and \
stored_image.object_id == image.object_id and \
stored_image.... | Clears the :attr:`_stored_images` set and deletes actual
files that are marked as deleted in the storage
if the ongoing transaction has committed. |
17,339 | def select(self, node):
child = self.translate(node.child)
return \
.format(op=latex_operator[node.operator],
conditions=node.conditions, child=child) | Translate a select node into a latex qtree node.
:param node: a treebrd node
:return: a qtree subtree rooted at the node |
17,340 | def GetValue(self, row, col, table=None):
if table is None:
table = self.grid.current_table
try:
cell_code = self.code_array((row, col, table))
except IndexError:
cell_code = None
maxlength = int(config["max_textctrl_length"])
... | Return the result value of a cell, line split if too much data |
17,341 | def unwrap(self, value, session=None):
self.validate_unwrap(value)
ret = {}
for value_dict in value:
k = value_dict[]
v = value_dict[]
ret[self.key_type.unwrap(k, session=session)] = self.value_type.unwrap(v, session=session)
return ret | Expects a list of dictionaries with ``k`` and ``v`` set to the
keys and values that will be unwrapped into the output python
dictionary should have. Validates the input and then constructs the
dictionary from the list. |
17,342 | def save(thing, url_or_handle, **kwargs):
is_handle = hasattr(url_or_handle, "write") and hasattr(url_or_handle, "name")
if is_handle:
_, ext = os.path.splitext(url_or_handle.name)
else:
_, ext = os.path.splitext(url_or_handle)
if not ext:
raise RuntimeError("No extension in... | Save object to file on CNS.
File format is inferred from path. Use save_img(), save_npy(), or save_json()
if you need to force a particular format.
Args:
obj: object to save.
path: CNS path.
Raises:
RuntimeError: If file extension not supported. |
17,343 | def _setup_crontab():
from crontab import CronTab
command = .format(settings.venv)
user = _get_real_user()
if args["nolive"]:
vms("Skipping cron tab configuration because enabled.")
return
cron = CronTab(user=user)
existing = False
possible = cron.fi... | Sets up the crontab if it hasn't already been setup. |
17,344 | def get_prefix_envname(self, name, log=False):
prefix = None
if name == :
prefix = self.ROOT_PREFIX
envs = self.get_envs()
for p in envs:
if basename(p) == name:
prefix = p
return prefix | Return full prefix path of environment defined by `name`. |
17,345 | async def run_task(self) -> None:
while self.running:
try:
Log.debug(, self.name)
before = self.time()
await self.run()
total = self.time() - before
Log.debug(,
self.name, total)
... | Execute the task inside the asyncio event loop. Track the time it
takes to run, and log when it starts/stops. After `INTERVAL` seconds,
if/once the task has finished running, run it again until `stop()`
is called. |
17,346 | def CheckGlobalStatic(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
if linenum + 1 < clean_lines.NumLines() and not Search(r, line):
line += clean_lines.elided[linenum + 1].strip()
match = Match(
r
r,
line)
... | Check for unsafe global or static objects.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. |
17,347 | def find_by_ids(self, _ids, projection=None, **kwargs):
id_list = [ObjectId(_id) for _id in _ids]
if len(_ids) == 0:
return []
if projection is not None and list(projection.keys()) == ["_id"]:
return [self({"_id": x}, fetched_fields={"_id":... | Does a big _id:$in query on any iterator |
17,348 | def delete(self, *args, **kwargs):
source_cache = self.get_source_cache()
self.delete_thumbnails(source_cache)
super(ThumbnailerFieldFile, self).delete(*args, **kwargs)
if source_cache and source_cache.pk is not None:
source_cache.delete() | Delete the image, along with any generated thumbnails. |
17,349 | def animation(self, animation):
self._animation = animation
self._text = self._get_text(self._text[]) | Setter for animation property.
Parameters
----------
animation: str
Defines the animation of the spinner |
17,350 | def _call_one_middleware(self, middleware):
args = {}
for arg in middleware[]:
if hasattr(self, arg):
args[arg] = reduce(getattr, arg.split(), self)
self.logger.debug(
.format(middleware[]))
middleware[](**ar... | Evaluate arguments and execute the middleware function |
17,351 | async def export_wallet(self, von_wallet: Wallet, path: str) -> None:
LOGGER.debug(, von_wallet, path)
if not von_wallet.handle:
LOGGER.debug(, von_wallet.name)
raise WalletState(.format(von_wallet.name))
await wallet.export_wallet(
von_wallet.hand... | Export an existing VON anchor wallet. Raise WalletState if wallet is closed.
:param von_wallet: open wallet
:param path: path to which to export wallet |
17,352 | def distance(self, clr):
coord = lambda a, d: (cos(radians(a)) * d, sin(radians(a)) * d)
x0, y0 = coord(self.h * 360, self.s)
x1, y1 = coord(clr.h * 360, clr.s)
z0 = self.brightness
z1 = clr.brightness
d = sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2 + (z1 - z0) ** 2)
... | Returns the Euclidean distance between two colors (0.0-1.0).
Consider colors arranged on the color wheel:
- hue is the angle of a color along the center
- saturation is the distance of a color from the center
- brightness is the elevation of a color from the center
(i.e. we're... |
17,353 | def reset(self):
logger.debug(
.format(self.__id, self.name))
self.base_url = .format(self.name)
logger.debug(
.format(self.__id, self.name)) | Reset the service to its' initial state. |
17,354 | def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL):
params = {
: self.api_key,
: ,
: self._coerce_point_to_string(query),
}
url = self._construct_url(params)
logger.debug("%s.reverse: %s", self.__class__.__name__, url)
... | Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longitude)``, or string as ``"%(latitude)s, %(longitude)s"``.
:pa... |
17,355 | def process_vts_params(self, scanner_vts):
vt_selection = {}
filters = list()
for vt in scanner_vts:
if vt.tag == :
vt_id = vt.attrib.get()
vt_selection[vt_id] = {}
for vt_value in vt:
if not vt_value.attrib... | Receive an XML object with the Vulnerability Tests an their
parameters to be use in a scan and return a dictionary.
@param: XML element with vt subelements. Each vt has an
id attribute. Optional parameters can be included
as vt child.
Example form:
... |
17,356 | def library_sequencing_results(self):
sres_ids = self.sequencing_result_ids
res = {}
for i in sres_ids:
sres = SequencingResult(i)
res[sres.library_id] = sres
return res | Generates a dict. where each key is a Library ID on the SequencingRequest and each value
is the associated SequencingResult. Libraries that aren't yet with a SequencingResult are
not inlcuded in the dict. |
17,357 | def closeSession(self):
rv = self.lib.C_CloseSession(self.session)
if rv != CKR_OK:
raise PyKCS11Error(rv) | C_CloseSession |
17,358 | def filter_resources(tables, relationships,
include_tables=None, include_columns=None,
exclude_tables=None, exclude_columns=None):
_tables = copy.deepcopy(tables)
_relationships = copy.deepcopy(relationships)
include_tables = include_tables or [t.name for t in... | Include the following:
1. Tables and relationships with tables present in the include_tables (lst of str, tables names)
2. Columns (of whichever table) present in the include_columns (lst of str, columns names)
Exclude the following:
1. Tables and relationships with tables present in the exc... |
17,359 | def add_to_capabilities(self, capabilities):
proxy_caps = {}
proxy_caps[] = self.proxyType[]
if self.autodetect:
proxy_caps[] = self.autodetect
if self.ftpProxy:
proxy_caps[] = self.ftpProxy
if self.httpProxy:
proxy_caps[] = self.httpP... | Adds proxy information as capability in specified capabilities.
:Args:
- capabilities: The capabilities to which proxy will be added. |
17,360 | def get_vmpolicy_macaddr_output_vmpolicy_macaddr_name(self, **kwargs):
config = ET.Element("config")
get_vmpolicy_macaddr = ET.Element("get_vmpolicy_macaddr")
config = get_vmpolicy_macaddr
output = ET.SubElement(get_vmpolicy_macaddr, "output")
vmpolicy_macaddr = ET.SubEl... | Auto Generated Code |
17,361 | def prior_names(self):
return list(self.prior_information.groupby(
self.prior_information.index).groups.keys()) | get the prior information names
Returns
-------
prior_names : list
a list of prior information names |
17,362 | def next_token(expected_type, data):
next_data = copy.copy(data)
next_type = TokenType.INVALID
if len(next_data) == 0 or next_data[0] == None:
next_type = TokenType.END
elif (expected_type == TokenType.DIGIT or expected_type == TokenType.DIGIT_OR_ZERO) and next_data[0].isalpha():
... | Based on the expected next type, consume the next token returning the type found and an updated buffer with the found token
removed
:param expected_type:
:param data:
:return: (TokenType, str) tuple where TokenType is the type of the next token expected |
17,363 | def getpaths(struct):
if isinstance(struct, Task):
return struct.output()
elif isinstance(struct, dict):
return struct.__class__((k, getpaths(v)) for k, v in six.iteritems(struct))
elif isinstance(struct, (list, tuple)):
return struct.__class__(getpaths(r) for r in struct)
e... | Maps all Tasks in a structured data object to their .output(). |
17,364 | def resplit_datasets(dataset, other_dataset, random_seed=None, split=None):
from torchnlp.datasets import Dataset
concat = dataset.rows + other_dataset.rows
shuffle(concat, random_seed=random_seed)
if split is None:
return Dataset(concat[:len(dataset)]), Dataset(concat[len(dataset):])... | Deterministic shuffle and split algorithm.
Given the same two datasets and the same ``random_seed``, the split happens the same exact way
every call.
Args:
dataset (lib.datasets.Dataset): First dataset.
other_dataset (lib.datasets.Dataset): Another dataset.
random_seed (int, option... |
17,365 | def validate_username_for_new_account(person, username):
query = Person.objects.filter(username__exact=username)
count = query.filter(pk=person.pk).count()
if count == 0 and account_exists(username):
raise UsernameTaken(
six.u()) | Validate the new username for a new account. If the username is invalid
or in use, raises :py:exc:`UsernameInvalid` or :py:exc:`UsernameTaken`.
:param person: Owner of new account.
:param username: Username to validate. |
17,366 | def read_from(self, provider, **options):
for item in self.values():
if is_mixin(item):
item.read_from(provider, **options) | All :class:`Pointer` fields in the `Structure` read the necessary
number of bytes from the data :class:`Provider` for their referenced
:attr:`~Pointer.data` object. Null pointer are ignored.
:param Provider provider: data :class:`Provider`.
:keyword bool nested: if ``True`` all :class:`... |
17,367 | def get_current_m2m_diff(self, instance, new_objects):
new_ids = self.pks_from_objects(new_objects)
relation_manager = self.__get__(instance)
filter = Q(**{relation_manager.source_field.attname: instance.pk})
qs = self.through.objects.current.filter(filter)
try:
... | :param instance: Versionable object
:param new_objects: objects which are about to be associated with
instance
:return: (being_removed id list, being_added id list)
:rtype : tuple |
17,368 | def group_add_user_action(model, request):
user_id = request.params.get()
if not user_id:
user_ids = request.params.getall()
else:
user_ids = [user_id]
try:
group = model.model
validate_add_users_to_groups(model, user_ids, [group.id])
for user_id in user_ids:... | Add user to group. |
17,369 | def fromBinaryString(value):
bitNo = 8
byte = 0
r = []
for v in value:
if bitNo:
bitNo -= 1
else:
bitNo = 7
r.append(byte)
byte = 0
if v in (, ):
v = int(v)
... | Create a |ASN.1| object initialized from a string of '0' and '1'.
Parameters
----------
value: :class:`str`
Text string like '1010111' |
17,370 | def cli(ctx, feature_id, start, end, organism="", sequence=""):
return ctx.gi.annotations.set_boundaries(feature_id, start, end, organism=organism, sequence=sequence) | Set the boundaries of a genomic feature
Output:
A standard apollo feature dictionary ({"features": [{...}]}) |
17,371 | def _sanitize_url_components(comp_list, field):
if not comp_list:
return
elif comp_list[0].startswith(.format(field)):
ret = .format(field)
comp_list.remove(comp_list[0])
return ret + _sanitize_url_components(comp_list, field)
else:
ret = .format(comp_list[0])
... | Recursive function to sanitize each component of the url. |
17,372 | def import_categories(self, category_nodes):
self.write_out(self.style.STEP())
categories = {}
for category_node in category_nodes:
title = category_node.find( % WP_NS).text[:255]
slug = category_node.find(
% WP_NS).text[:255]
try:
... | Import all the categories from 'wp:category' nodes,
because categories in 'item' nodes are not necessarily
all the categories and returning it in a dict for
database optimizations. |
17,373 | def sync(self, *sids):
if sids == ():
sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)]
for sid in sids:
self.dbcur.execute(SQL_TMPO_LAST, (sid,))
last = self.dbcur.fetchone()
if last:
rid, lvl, bid, ext = last
... | Synchronise data
Parameters
----------
sids : list of str
SensorIDs to sync
Optional, leave empty to sync everything |
17,374 | def get_avg_price_fifo(self) -> Decimal:
balance = self.get_quantity()
if not balance:
return Decimal(0)
paid = Decimal(0)
accounts = self.get_holding_accounts()
for account in accounts:
splits = self.get_available_splits_for_account(acc... | Calculates the average price paid for the security.
security = Commodity
Returns Decimal value. |
17,375 | def unit_is_related(self, location, worksheet):
same_worksheet = worksheet == self.worksheet
if isinstance(location, (tuple, list)):
return (location[0] >= self.start[0] and location[0] < self.end[0] and
location[1] >= self.start[1] and location[1] < self.end[1] ... | Checks for relationship between a unit location and this block.
Returns:
True if the location is related to this block. |
17,376 | def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs):
if ax == None:
ax = pl.gca()
if ax_channels is not None:
flip = self._find_orientation(ax_channels)
plot_func = ax.axes.axhline if flip else ax.axes.axvline
kwargs.setdefault(, )
... | {_gate_plot_doc} |
17,377 | def validate_steps(self, request, workflow, start, end):
errors = {}
for step in workflow.steps[start:end + 1]:
if not step.action.is_valid():
errors[step.slug] = dict(
(field, [six.text_type(error) for error in errors])
for (f... | Validates the workflow steps from ``start`` to ``end``, inclusive.
Returns a dict describing the validation state of the workflow. |
17,378 | def fcast(value: float) -> TensorLike:
newvalue = tf.cast(value, FTYPE)
if DEVICE == :
newvalue = newvalue.gpu()
return newvalue | Cast to float tensor |
17,379 | def contains (self, p):
inside = False
if p in self.bounds():
for s in self.segments():
if ((s.p.y > p.y) != (s.q.y > p.y) and
(p.x < (s.q.x - s.p.x) * (p.y - s.p.y) / (s.q.y - s.p.y) + s.p.x)):
inside = not inside
return inside | Returns True if point is contained inside this Polygon, False
otherwise.
This method uses the Ray Casting algorithm.
Examples:
>>> p = Polygon()
>>> p.vertices = [Point(1, 1), Point(1, -1), Point(-1, -1), Point(-1, 1)]
>>> p.contains( Point(0, 0) )
True
>>> p.contains( Point(2, ... |
17,380 | def import_medusa_data(mat_filename, config_file):
df_emd, df_md = _read_mat_mnu0(mat_filename)
if not isinstance(config_file, np.ndarray):
configs = np.loadtxt(config_file).astype(int)
else:
configs = config_file
print()
quadpole_list = []
if df_emd is not None... | Import measurement data (a .mat file) of the FZJ EIT160 system. This
data format is identified as 'FZJ-EZ-2017'.
Parameters
----------
mat_filename: string
filename to the .mat data file. Note that only MNU0 single-potentials
are supported!
config_file: string
filename for c... |
17,381 | def set_digital_latch(self, pin, threshold_type, cb=None):
if 0 <= threshold_type <= 1:
self._command_handler.set_digital_latch(pin, threshold_type, cb)
return True
else:
return False | This method "arms" a digital pin for its data to be latched and saved in the latching table
If a callback method is provided, when latching criteria is achieved, the callback function is called
with latching data notification. In that case, the latching table is not updated.
:param pin: Digital... |
17,382 | def surviors_are_inconsistent(survivor_mapping: Mapping[BaseEntity, Set[BaseEntity]]) -> Set[BaseEntity]:
victim_mapping = set()
for victim in itt.chain.from_iterable(survivor_mapping.values()):
if victim in survivor_mapping:
victim_mapping.add(victim)
return victim_mapping | Check that there's no transitive shit going on. |
17,383 | def get_outliers(self):
log.info("Clipping outliers...")
log.info( %
(0, self.oiter, len(self.outmask)))
def M(x): return np.delete(x, np.concatenate(
[self.nanmask, self.badmask, self.transitmask]), axis=0)
t = M(self.time)
outmask = [np.a... | Performs iterative sigma clipping to get outliers. |
17,384 | def initialize_renderer(extensions=None):
if extensions is None:
extensions = []
if isinstance(extensions, str):
extensions = [extension.strip() for extension in extensions.split()]
for extension in getattr(settings, , DEFAULT_MARKYMARK_EXTENSIONS):
extensions.append(extension... | Initializes the renderer by setting up the extensions (taking a comma separated
string or iterable of extensions). These extensions are added alongside with the
configured always-on extensions.
Returns a markdown renderer instance. |
17,385 | def delete_subscription(self, subscription_id):
self._validate_uuid(subscription_id)
url = "/notification/v1/subscription/{}".format(subscription_id)
response = NWS_DAO().deleteURL(url, self._write_headers())
if response.status != 204:
raise DataFailureException(ur... | Deleting an existing subscription
:param subscription_id: is the subscription the client wants to delete |
17,386 | def boolbox(msg="Shall I continue?", title=" ",
choices=("[Y]es", "[N]o"), image=None,
default_choice=, cancel_choice=):
if len(choices) != 2:
raise AssertionError(
)
reply = bb.buttonbox(msg=msg,
title=title,
... | Display a boolean msgbox.
The returned value is calculated this way::
if the first choice is chosen, or if the dialog is cancelled:
returns True
else:
returns False
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: ... |
17,387 | def set_computer_desc(desc=None):
minion-idThis computer belongs to Dave!
if six.PY2:
desc = _to_unicode(desc)
system_info = win32net.NetServerGetInfo(None, 101)
if desc is None:
return False
system_info[] = desc
try:
win32net.NetServerSetInfo(None... | Set the Windows computer description
Args:
desc (str):
The computer description
Returns:
str: Description if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' |
17,388 | def _expand_authorized_keys_path(path, user, home):
converted_path =
had_escape = False
for char in path:
if had_escape:
had_escape = False
if char == :
converted_path +=
elif char == :
converted_path += user
elif... | Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5) |
17,389 | def get_file_list():
if len(sys.argv) > 1:
file_list = list(sys.argv[1:])
else:
files_str = input(
re done: "", "") for f in file_list]
else:
file_list = shlex.split(files_str, posix=True)
for i in range(l... | Return a list of strings corresponding to file names supplied by drag and drop or standard input. |
17,390 | def local(self, *args, **kwargs):
s own CLI uses. Note the ``arg`` and ``kwarg``
parameters are sent down to the minion(s) and the given function,
``fun``, is called with those parameters.
:return: Returns the result from the execution module
'
local = salt.client.get_lo... | Run :ref:`execution modules <all-salt.modules>` synchronously
See :py:meth:`salt.client.LocalClient.cmd` for all available
parameters.
Sends a command from the master to the targeted minions. This is the
same interface that Salt's own CLI uses. Note the ``arg`` and ``kwarg``
pa... |
17,391 | def from_cif_file(cif_file, source=, comment=):
r = CifParser(cif_file)
structure = r.get_structures()[0]
return Header(structure, source, comment) | Static method to create Header object from cif_file
Args:
cif_file: cif_file path and name
source: User supplied identifier, i.e. for Materials Project this
would be the material ID number
comment: User comment that goes in header
Returns:
... |
17,392 | def shard_data(source_fnames: List[str],
target_fname: str,
source_vocabs: List[vocab.Vocab],
target_vocab: vocab.Vocab,
num_shards: int,
buckets: List[Tuple[int, int]],
length_ratio_mean: float,
length_ratio_std: f... | Assign int-coded source/target sentence pairs to shards at random.
:param source_fnames: The path to the source text (and optional token-parallel factor files).
:param target_fname: The file name of the target file.
:param source_vocabs: Source vocabulary (and optional source factor vocabularies).
:par... |
17,393 | def from_file(filename, use_cores=True, thresh=1.e-4):
with zopen(filename, "rt") as f:
return Xr.from_string(
f.read(), use_cores=use_cores,
thresh=thresh) | Reads an xr-formatted file to create an Xr object.
Args:
filename (str): name of file to read from.
use_cores (bool): use core positions and discard shell
positions if set to True (default). Otherwise,
use shell positions and discard core positio... |
17,394 | def get_synset_xml(self,syn_id):
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.debug:
printf( "cornettodb/views/query_remote_syn_id: db_opt: %s" % path )
output_opt = "plain"
... | call cdb_syn with synset identifier -> returns the synset xml; |
17,395 | def setDataFrame(self, dataFrame):
if not isinstance(dataFrame, pandas.core.frame.DataFrame):
raise TypeError()
self.layoutAboutToBeChanged.emit()
self._dataFrame = dataFrame
self.layoutChanged.emit() | setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFr... |
17,396 | def notch_fir(self, f1, f2, order, beta=5.0, remove_corrupted=True):
from pycbc.filter import notch_fir
ts = notch_fir(self, f1, f2, order, beta=beta)
if remove_corrupted:
ts = ts[order:len(ts)-order]
return ts | notch filter the time series using an FIR filtered generated from
the ideal response passed through a time-domain kaiser
window (beta = 5.0)
The suppression of the notch filter is related to the bandwidth and
the number of samples in the filter length. For a few Hz bandwidth,
a ... |
17,397 | def normalize(s, replace_spaces=True):
whitelist = ( + string.ascii_letters + string.digits)
if type(s) == six.binary_type:
s = six.text_type(s, , )
table = {}
for ch in [ch for ch in s if ch not in whitelist]:
if ch not in table:
try:
replacement = uni... | Normalize non-ascii characters to their closest ascii counterparts |
17,398 | def find_comp_by_target(self, target):
for comp in self._components:
if comp.id == target.component_id and \
comp.instance_name == target.instance_name:
return comp
raise MissingComponentError | Finds a component using a TargetComponent or one of its subclasses.
@param A @ref TargetComponent object or subclass of @ref
TargetComponent.
@return A Component object matching the target.
@raises MissingComponentError |
17,399 | def remove_thumbnail(self, thumbnail):
if thumbnail in self._thumbnails:
index = self._thumbnails.index(thumbnail)
self._thumbnails.remove(thumbnail)
self.layout().removeWidget(thumbnail)
thumbnail.deleteLater()
thumbnail.sig_canvas_clicked.disconnect()
... | Remove thumbnail. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.