Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
339,200 | def dump(self, indentlevel=0, target=sys.stdout):
self.__print(self, indentlevel, target=target)
indentlevel += 4
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
valu... | Display the command
Pretty printing of this command and its eventual arguments and
children. (recursively)
:param indentlevel: integer that indicates indentation level to apply |
339,201 | def check_pending_labels(ast):
result = True
visited = set()
pending = [ast]
while pending:
node = pending.pop()
if node is None or node in visited:
continue
visited.add(node)
for x in node.children:
pending.append(x)
if node.tok... | Iteratively traverses the node looking for ID with no class set,
marks them as labels, and check they've been declared.
This way we avoid stack overflow for high line-numbered listings. |
339,202 | def _build_exclusion_list(exclude):
mod_files = []
if exclude:
for mod in exclude:
mdir = None
mod_file = None
for token in mod.split("."):
try:
mfile, mdir, _ = imp.find_module(token, mdir and [mdir])
if mf... | Build file names list of modules to exclude from exception handling. |
339,203 | def get_installed_version_of(name, location=None):
if location:
locations = [location]
else:
locations = _data_dirs()
for loc in locations:
if name not in get_installed_daps(loc):
continue
meta = .format(d=loc, dap=name)
data = yaml.load(open(meta), ... | Gets the installed version of the given dap or None if not installed
Searches in all dirs by default, otherwise in the given one |
339,204 | def _get_balance(self):
response = self.session.get(self.balance_url, verify=False)
soup = BeautifulSoup(response.text, )
first_line = soup.select(
"table.data tr:nth-of-type(2)")[0].text.strip().split()
total, today = first_line[-2:]
logging.info(, today, to... | Get to know how much you totally have and how much you get today. |
339,205 | def copy(self, source, target, mpi=None, pos=0, chunk=0, part=0, delete_source=False):
if self.opt.dry_run:
message( % (source, target))
return
source_url = S3URL(source)
target_url = S3URL(target)
if not mpi:
obj = self.lookup(source_url)
fsize = int(obj[])
if fsi... | Copy a single file from source to target using boto S3 library. |
339,206 | def poll_queue(job_id, pid, poll_time):
if config.distribution.serialize_jobs:
first_time = True
while True:
jobs = logs.dbcmd(GET_JOBS)
failed = [job.id for job in jobs if not psutil.pid_exists(job.pid)]
if failed:
logs.dbcmd("UPDATE job SET ... | Check the queue of executing/submitted jobs and exit when there is
a free slot. |
339,207 | def normalize(data):
out_data = data.copy()
for i, sample in enumerate(out_data):
out_data[i] /= sum(out_data[i])
return out_data | Normalize the data to be in the [0, 1] range.
:param data:
:return: normalized data |
339,208 | def fit(self, analysis, grid_priors):
grid_priors = list(set(grid_priors))
results = []
lists = self.make_lists(grid_priors)
results_list = [list(map(self.variable.name_for_prior, grid_priors)) + ["figure_of_merit"]]
def write_results():
with open("{}/resul... | Fit an analysis with a set of grid priors. The grid priors are priors associated with the model mapper
of this instance that are replaced by uniform priors for each step of the grid search.
Parameters
----------
analysis: non_linear.Analysis
An analysis used to determine the... |
339,209 | def _set_hello_status(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 0}, u: {: 2}, u: {... | Setter method for hello_status, mapped from YANG variable /mpls_state/rsvp/interfaces/hello_status (feature-config-status)
If this variable is read-only (config: false) in the
source YANG file, then _set_hello_status is considered as a private
method. Backends looking to populate this variable should
do... |
339,210 | def get_nodes_from_ids(id_list: Iterable[str]) -> List[Node]:
node_list = []
for result in get_scigraph_nodes(id_list):
if in result:
label = result[]
else:
label = None
node_list.append(Node(result[], label))
return node_list | Given a list of ids return their types
:param id_list: list of ids
:return: dictionary where the id is the key and the value is a list of types |
339,211 | def run_to_rel_pos(self, **kwargs):
for key in kwargs:
setattr(self, key, kwargs[key])
self.command = self.COMMAND_RUN_TO_REL_POS | Run to a position relative to the current `position` value.
The new position will be current `position` + `position_sp`.
When the new position is reached, the motor will stop using
the action specified by `stop_action`. |
339,212 | def parse_line(self, line):
try:
tp = self.split_columns(line)
except CommentLine:
return
if tp[] == :
print "Reservation:", tp[], tp[]
p = Prefix()
p.schema = self.schema
p.prefix = tp... | Parse one line |
339,213 | def get_rate_for(self, currency: str, to: str, reverse: bool=False) -> Number:
if currency.upper() == to.upper():
return self._format_number()
base, quote = currency, to
if reverse:
base, quote = to, currency
try:
rate =... | Get current market rate for currency |
339,214 | def w():
*
def linux_w():
user_list = []
users = __salt__[]().splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {: comps[3],
: comps[4],
: comps[2],
... | Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w |
339,215 | def setValidityErrorHandler(self, err_func, warn_func, arg=None):
libxml2mod.xmlRelaxNGSetValidErrors(self._o, err_func, warn_func, arg) | Register error and warning handlers for RelaxNG validation.
These will be called back as f(msg,arg) |
339,216 | def _get_vi_mode(cli):
return {
InputMode.INSERT: ,
InputMode.NAVIGATION: ,
InputMode.REPLACE: ,
InputMode.INSERT_MULTIPLE:
}[cli.vi_state.input_mode] | Get the current vi mode for display. |
339,217 | def fsencoding(s, encoding=sys.getfilesystemencoding()):
if isinstance(s, unicode):
s = s.encode(encoding)
return s | Ensure the given argument is in filesystem encoding (not unicode) |
339,218 | def nl_cb_alloc(kind):
if kind < 0 or kind > NL_CB_KIND_MAX:
return None
cb = nl_cb()
cb.cb_active = NL_CB_TYPE_MAX + 1
for i in range(NL_CB_TYPE_MAX):
nl_cb_set(cb, i, kind, None, None)
nl_cb_err(cb, kind, None, None)
return cb | Allocate a new callback handle.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L201
Positional arguments:
kind -- callback kind to be used for initialization.
Returns:
Newly allocated callback handle (nl_cb class instance) or None. |
339,219 | def run_activity(self):
activity = self.current.activity
if activity:
if activity not in self.wf_activities:
self._load_activity(activity)
self.current.log.debug(
"Calling Activity %s from %s" % (activity, self.wf_activities[activity]))
... | runs the method that referenced from current task |
339,220 | def update_input(filelist, ivmlist=None, removed_files=None):
newfilelist = []
if removed_files == []:
return filelist, ivmlist
else:
sci_ivm = list(zip(filelist, ivmlist))
for f in removed_files:
result=[sci_ivm.remove(t) for t in sci_ivm if t[0] == f ]
ivm... | Removes files flagged to be removed from the input filelist.
Removes the corresponding ivm files if present. |
339,221 | def changeIndex(self, ind):
self.currentTab = self.tabWidget.currentWidget()
editBox = self.currentTab.editBox
previewState = self.currentTab.previewState
self.actionUndo.setEnabled(editBox.document().isUndoAvailable())
self.actionRedo.setEnabled(editBox.document().isRedoAvailable())
self.actionCopy.setE... | This function is called when a different tab is selected.
It changes the state of the window to mirror the current state
of the newly selected tab. Future changes to this state will be
done in response to signals emitted by the tab, to which the
window was subscribed when the tab was created. The window is
su... |
339,222 | def mounted(name,
device,
fstype,
mkmnt=False,
opts=,
dump=0,
pass_num=0,
config=,
persist=True,
mount=True,
user=None,
match_on=,
device_name_regex=None,
extra_mou... | Verify that a device is mounted
name
The path to the location where the device is to be mounted
device
The device name, typically the device node, such as ``/dev/sdb1``
or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314`` or ``LABEL=DATA``
fstype
The filesystem type, this will... |
339,223 | def _existing(self, email):
return self.store.findUnique(
EmailAddress,
EmailAddress.address == email,
default=None) | Return the existing L{EmailAddress} item with the given address, or
C{None} if there isn't one. |
339,224 | def callback_url(self, request):
service = self.service.split()[1].lower()
return_to = .format(service=service)
return % (request.scheme, request.get_host(), reverse(return_to)) | the url to go back after the external service call
:param request: contains the current session
:type request: dict
:rtype: string |
339,225 | def Likelihood(self, data, hypo):
mix = self.loci[hypo]
like = mix[data]
return like | The likelihood of the data under the hypothesis.
data: string cookie type
hypo: string bowl ID |
339,226 | def dump_json_file(json_data, pwd_dir_path, dump_file_name):
class PythonObjectEncoder(json.JSONEncoder):
def default(self, obj):
try:
return super().default(self, obj)
except TypeError:
return str(obj)
logs_dir_path = os.path.join(pwd_dir_pa... | dump json data to file |
339,227 | def _streamSSE(url, on_data=print, accrue=False):
messages = SSEClient(url)
if accrue:
ret = []
for msg in messages:
data = msg.data
on_data(json.loads(data))
if accrue:
ret.append(msg)
return ret | internal |
339,228 | def zip_result(zip_binary: bytes,
extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,
filename: str = None) -> WSGI_TUPLE_TYPE:
extraheaders = extraheaders or []
if filename:
extraheaders.append(
(, .format(filename))
)
contenttype =
if filena... | Returns ``(contenttype, extraheaders, data)`` tuple for a ZIP. |
339,229 | def get_train_dataflow():
roidbs = DetectionDataset().load_training_roidbs(cfg.DATA.TRAIN)
print_class_histogram(roidbs)
num = len(roidbs)
roidbs = list(filter(lambda img: len(img[][img[] == 0]) > 0, roidbs))
logger.info("Filtered {} images which contain no non-crowd groudtruth boxe... | Return a training dataflow. Each datapoint consists of the following:
An image: (h, w, 3),
1 or more pairs of (anchor_labels, anchor_boxes):
anchor_labels: (h', w', NA)
anchor_boxes: (h', w', NA, 4)
gt_boxes: (N, 4)
gt_labels: (N,)
If MODE_MASK, gt_masks: (N, h, w) |
339,230 | def listFileArray(self, **kwargs):
validParameters = [, , ,
, , ,
, ,
, , , , ]
requiredParameters = {: [, , ]}
if not in kwargs.keys():
kwargs[] = False
checkInputParameter(me... | API to list files in DBS. Non-wildcarded logical_file_name, non-wildcarded dataset, non-wildcarded block_name or non-wildcarded lfn list is required.
The combination of a non-wildcarded dataset or block_name with an wildcarded logical_file_name is supported.
* For lumi_list the following two json for... |
339,231 | def from_json(cls, json):
return cls(json[cls.BLOB_KEY_PARAM],
json[cls.START_INDEX_PARAM],
json[cls.END_INDEX_PARAM]) | Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json. |
339,232 | def from_directory(input_dir):
sub_d = {}
for fname, ftype in [("HEADER", Header), ("PARAMETERS", Tags)]:
fullzpath = zpath(os.path.join(input_dir, fname))
sub_d[fname.lower()] = ftype.from_file(fullzpath)
absorber_index = []
... | Read in a set of FEFF input files from a directory, which is
useful when existing FEFF input needs some adjustment. |
339,233 | def convert(text, code=True, tabsize=4):
output = []
in_span = False
compatible_text_styles = {
ANSI_TEXT_STYLES[]: {: },
ANSI_TEXT_STYLES[]: {: },
ANSI_TEXT_STYLES[]: {: },
}
for token in TOKEN_PATTERN.split(text):
if token.startswith((, , )):
... | Convert text with ANSI escape sequences to HTML.
:param text: The text with ANSI escape sequences (a string).
:param code: Whether to wrap the returned HTML fragment in a
``<code>...</code>`` element (a boolean, defaults
to :data:`True`).
:param tabsize: Refer to :func:`st... |
339,234 | def db_schema(db, table):
typedict = [(, int), (, float),
(, datetime),
(, date), (, dttime),
(, str), (, str)]
ret = {}
q =
for row in query(db, q, (table,)):
name, dtype = tuple( row[:2] )
name = str(name)
for tn, tt in typedict:
... | only works for postgres
@return dictionary of column name -> data type |
339,235 | def actions(self, state):
if len(state) == len(self.vars):
return []
else:
assignment = dict(state)
var = find_if(lambda v: v not in assignment, self.vars)
return [(var, val) for val in self.domains[var]
if self.nconflicts(var,... | Return a list of applicable actions: nonconflicting
assignments to an unassigned variable. |
339,236 | def env(var_name, default=False):
try:
value = os.environ[var_name]
if str(value).strip().lower() in [, , , , ]:
return None
return value
except:
from traceback import format_exc
msg = format_exc() + + "Unable to find the %s environment variable.\nUsing... | Get the environment variable or assume a default, but let the user know about the error. |
339,237 | def get_index_of_column(cls, column, file_path):
columns = cls.get_column_names_from_file(file_path)
if column in columns:
return columns.index(column) | Get index of a specific column name in a CTD file
:param column:
:param file_path:
:return: Optional[int] |
339,238 | def render(self):
self.update(self.axes.render())
encoder = Encoder(self._encoding, None, self._series)
if not in self:
self[] =
else:
size = self[].split()
assert len(size) == 2,
self.check_size(*map(int,size))
assert ... | Renders the chart context and axes into the dict data |
339,239 | def ArrayOf(klass, fixed_length=None, prototype=None):
global _array_of_map
global _array_of_classes, _sequence_of_classes
if issubclass(klass, Atomic):
if prototype is None:
pass
elif not klass.is_valid(prototype):
raise ValueError("prototype %r not valid ... | Function to return a class that can encode and decode a list of
some other type. |
339,240 | def binary(self):
dependencies = self.dependencies
if len(dependencies) != 1:
raise TargetDefinitionException(self,
.format(dependencies))
binary = dependencies[0]
if not isinstance(binary, self.binary_target_type()):
raise TargetDefinitionEx... | Returns the binary this target references. |
339,241 | def loadable_modules(self):
with self._mutex:
if not self._loadable_modules:
self._loadable_modules = []
for mp in self._obj.get_loadable_modules():
self._loadable_modules.append(utils.nvlist_to_dict(mp.properties))
return self._lo... | The list of loadable module profile dictionaries. |
339,242 | def check_page(fn):
"Decorator to protect drawing methods"
@wraps(fn)
def wrapper(self, *args, **kwargs):
if not self.page and not kwargs.get():
self.error("No page open, you need to call add_page() first")
else:
return fn(self, *args, **kw... | Decorator to protect drawing methods |
339,243 | def _get_new_msg_id(self):
now = time.time() + self.time_offset
nanoseconds = int((now - int(now)) * 1e+9)
new_msg_id = (int(now) << 32) | (nanoseconds << 2)
if self._last_msg_id >= new_msg_id:
new_msg_id = self._last_msg_id + 4
self._last_msg_id = new_msg_... | Generates a new unique message ID based on the current
time (in ms) since epoch, applying a known time offset. |
339,244 | def related(self):
return [ch for ch in self.sentence.chunks
if ch != self and intersects(unzip(0, ch.relations), unzip(0, self.relations))] | Yields a list of all chunks in the sentence with the same relation id. |
339,245 | def main():
usage = "usage: %(prog)s [options] "
description = "Merge a set of Fermi-LAT files."
parser = argparse.ArgumentParser(usage=usage, description=description)
parser.add_argument(, , default=None, type=str,
help=)
parser.add_argument(, default=False, action=,
... | Main function for command line usage |
339,246 | def create(cls, data):
try:
json_data = json.loads(data)
except ValueError as err:
logging.debug("Failed to load json data: %s: [%s]", str(err), data)
json_data = json.loads(ErrorEvent.error_json(err))
if "type" not in json_data:
raise Ge... | Create a new event instance.
Return an instance of the `GerritEvent` subclass after converting
`data` to json.
Raise GerritError if json parsed from `data` does not contain a `type`
key. |
339,247 | def format_vars(args):
variables = []
for key, value in args.items():
if value:
variables += [.format(key, value)]
return variables | Format the given vars in the form: 'flag=value |
339,248 | def check_section_unaligned(self):
file_alignment = self.pefile_handle.OPTIONAL_HEADER.FileAlignment
unaligned_sections = []
for section in self.pefile_handle.sections:
if section.PointerToRawData % file_alignment:
unaligned_sections.append(section.Name)
... | Checking if any of the sections are unaligned |
339,249 | def flatten_args(fn):
@wraps(fn)
def new_fn(*args):
args_flat, shapes = flatten(args)
result = fn(args_flat)
return unflatten(result, shapes=shapes)
return new_fn | Examples
--------
>>> @flatten_args
... def f(x):
... return 2*x
>>> x, y, z = f(np.array([1., 2.]), 3., np.array([[1., 2.],[.5, .9]]))
>>> x
array([ 2., 4.])
>>> y
6.0
>>> z
array([[ 2. , 4. ],
[ 1. , 1.8]]) |
339,250 | def generate_config_file(self):
lines = ["
lines.append()
lines.append()
lines.append()
for cls in self.classes:
lines.append(cls.class_config_section())
return .join(lines) | generate default config file from Configurables |
339,251 | def capitalize(
full_name,
articles=None,
separator_characters=None,
ignore_worls=None,
):
if articles is None:
articles = _ARTICLES
if separator_characters is None:
separator_characters = _SEPARATOR_CHARACTERS
if ignore_worls is None:
ignore_worls = _IGNORE_WORL... | Returns the correct writing of a compound name, respecting the
first letters of the names in upper case. |
339,252 | def delete_translations(sender, instance, **kwargs):
if issubclass(sender, (ModelMixin,)):
instance._linguist.decider.objects.filter(
identifier=instance.linguist_identifier, object_id=instance.pk
).delete() | Deletes related instance's translations when instance is deleted. |
339,253 | def _get_rest_key_parts(cls, attr_key):
rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key][])
return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] | Get the RestAPI key of this attr, split it and decode part
:param str attr_key: Attribute key must be in attribute_map.
:returns: A list of RestAPI part
:rtype: list |
339,254 | def create(self, list_id, data):
self.list_id = list_id
if not in data:
raise KeyError()
if not in data:
raise KeyError()
response = self._mc_client._post(url=self._build_path(list_id, ), data=data)
if response is not None:
self.merg... | Add a new merge field for a specific list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"type": string*
} |
339,255 | def pivot(X, a, b, Keep=None, NullVals=None, order = None, prefix=):
_
othernames = [o for o in X.dtype.names if o not in [a,b]]
for c in [a,b]:
assert c in X.dtype.names, + c +
[D,s] = fast.recarrayuniqify(X[[a,b]])
unique_ab = X[[a,b]][s[D.nonzero()[0]]]
assert len(X) == len(uniqu... | Implements pivoting on numpy ndarrays (with structured dtype) or recarrays.
See http://en.wikipedia.org/wiki/Pivot_table for information about pivot
tables.
Returns `X` pivoted on (a,b) with `a` as the row axis and `b` values as the
column axis.
So-called "nontrivial columns relative to `b`" in... |
339,256 | def get_next_job_record(self, process_name):
tree = self.get_tree(process_name)
node = tree.get_next_node(process_name)
if node.job_record is None:
self.assign_job_record(node)
return node.job_record | :returns: the next job record to work on for the given process |
339,257 | def timeago(seconds=0, accuracy=4, format=0, lang="en"):
assert format in [0, 1, 2], ValueError("format arg should be one of 0, 1, 2")
negative = "-" if seconds < 0 else ""
seconds = abs(seconds)
if lang == "en":
units = ("day", "hour", "minute", "second", "ms")
elif lang == "cn":
... | Translate seconds into human-readable.
:param seconds: seconds (float/int).
:param accuracy: 4 by default (units[:accuracy]), determine the length of elements.
:param format: index of [led, literal, dict].
:param lang: en or cn.
:param units: day, hour, minute, second, ms.
... |
339,258 | def calc_n_ints_in_file(filename):
h = read_header(filename)
n_bytes = int(h[b] / 8)
n_chans = h[b]
n_ifs = h[b]
idx_data = len_header(filename)
f = open(filename, )
f.seek(idx_data)
filesize = os.path.getsize(filename)
n_bytes_data = filesize - idx_data
if h[b] ==... | Calculate number of integrations in a given file |
339,259 | def _parse_uri_ssh(unt):
if in unt.netloc:
user, host_port = unt.netloc.split(, 1)
else:
user, host_port = None, unt.netloc
if in host_port:
host, port = host_port.split(, 1)
else:
host, port = host_port, None
if not user:
user = None
if not port:... | Parse a Uri from a urllib namedtuple. |
339,260 | def download(input, filename, representation, overwrite=False, resolvers=None, get3d=False, **kwargs):
result = resolve(input, representation, resolvers, get3d, **kwargs)
if not result:
log.debug()
return
if not overwrite and os.path.isfile(filename):
raise IOError("%s... | Convenience function to save a CIR response as a file.
This is just a simple wrapper around the resolve function.
:param string input: Chemical identifier to resolve
:param string filename: File path to save to
:param string representation: Desired output representation
:param bool overwrite: (Opt... |
339,261 | def chi_square_p_value(matrix):
try:
num_rows = len(matrix)
num_columns = len(matrix[0])
except TypeError:
return None
if num_rows != num_columns:
return None
if num_rows == 0:
return None
for row in matrix:
if len(row) != num_columns:
... | Accepts a matrix (an array of arrays, where each child array represents a row)
Example from http://math.hws.edu/javamath/ryan/ChiSquare.html:
Suppose you conducted a drug trial on a group of animals and you
hypothesized that the animals receiving the drug would survive better than
those that did not r... |
339,262 | def pop(self, key, default=None):
"Standard pop semantics for all mapping types"
if not isinstance(key, tuple): key = (key,)
return self.data.pop(key, default) | Standard pop semantics for all mapping types |
339,263 | def set_password(self, service, username, password):
assoc = self._generate_assoc(service, username)
password_encrypted = self.encrypt(password.encode(), assoc)
password_base64 = + encodebytes(password_encrypted).decode()
self._write_config_value(service, use... | Write the password in the file. |
339,264 | def get_packages():
packages = find_packages(exclude=[])
packages.append()
packages.append()
packages.append(LOCALES_DIRECTORY)
for directory in os.listdir(LOCALES_DIRECTORY):
packages.append(LOCALES_DIRECTORY + + directory)
return packages | Returns the packages used for HaTeMiLe for Python.
:return: The packages used for HaTeMiLe for Python.
:rtype: list(str) |
339,265 | def L(self):
m = len(self._tril1[0])
self._L[self._tril1] = self._Lu.value[:m]
self._L[self._diag] = exp(self._Lu.value[m:])
return self._L | Lower-triangular matrix L such that K = LLᵀ + ϵI.
Returns
-------
L : (d, d) ndarray
Lower-triangular matrix. |
339,266 | def handle(self, *app_labels, **options):
model_list = self._get_model_list(app_labels, exclude)
try:
serializers.get_serializer(format)
except KeyError:
raise CommandError("Unknown serialization format: %s" % format)
... | Serializes objects from the database.
Works much like Django's ``manage.py dumpdata``, except that it allows you to
limit and sort the apps that you're pulling in, as well as automatically follow
the dependency graph to pull in related objects. |
339,267 | def new_document(self, filename, url=None):
if not filename.endswith():
raise ValueError()
if os.path.isabs(filename):
raise ValueError()
if filename in self.documents:
raise ValueError(.format(filename))
if not url:
url = filename[:-3]
doc = Document(self, url)
se... | Create a new document.
# Arguments
filename (str): The filename of the document. Must end with `.md`.
url (str): The relative URL of the document. If omitted, will be
automatically deduced from *filename* (same without the `.md` suffix).
# Raises
ValueError: If *filename* does not end with `... |
339,268 | def overlay_gateway_attach_rbridge_id(self, **kwargs):
callback = kwargs.pop(, self._callback)
get_config = kwargs.pop(, False)
delete = kwargs.pop(, False)
if not get_config:
gw_name = kwargs.pop()
rbridge_id = kwargs.pop()
if delete is True... | Configure Overlay Gateway attach rbridge id
Args:
gw_name: Name of Overlay Gateway <WORD:1-32>
rbridge_id: Single or range of rbridge id to be added/removed
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the attached... |
339,269 | def _transform_from_pauli(data, num_qubits):
basis_mat = np.array(
[[1, 0, 0, 1], [0, 1, 1j, 0], [0, 1, -1j, 0], [1, 0j, 0, -1]],
dtype=complex)
cob = basis_mat
for _ in range(num_qubits - 1):
dim = int(np.sqrt(len(cob)))
cob = np.reshape(
np.t... | Change of basis of bipartite matrix represenation. |
339,270 | def add(self, id, obj, criteria={}, force=False, _check_id=True):
if not isinstance(obj, Component):
raise TypeError("can only add(%r), component is a %r" % (
Component, type(obj)
))
obj_data = obj.serialize()
q = tiny... | Add a :class:`Component <cqparts.Component>` instance to the database.
:param id: unique id of entry, can be anything
:type id: :class:`str`
:param obj: component to be serialized, then added to the catalogue
:type obj: :class:`Component <cqparts.Component>`
:param criteria: arb... |
339,271 | def push(self, id):
"Sends a message to the specified connection (id)"
conn = session[].get(id, None)
if conn:
msgs = simplejson.loads(request.body)
for msg in msgs:
try:
cmd = msg.pop(0).upper()
assert not ... | Sends a message to the specified connection (id) |
339,272 | def selectable_delete(self) -> Expectation:
self.cmd_sync()
self._count(2)
self.cmd_sync()
self.cmd_sync()
return self._count(0) | Remove two projects
by selecting them via `<space>` and pressing `d` |
339,273 | def pre_facet_sqs(self):
sqs = SearchQuerySet()
if self.query:
sqs = sqs.filter(
SQ(content=AutoQuery(self.query)) |
SQ(get_title=AutoQuery(self.query)) |
SQ(boosted_search_terms=AutoQuery(self.query))
)
retur... | Return the queryset used for generating facets, before any facets
are applied |
339,274 | def stop(self, id):
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) | stop the tracker. |
339,275 | def _zforce(self, R, z, phi=0., t=0.):
if not self.isNonAxi and phi is None:
phi= 0.
r, theta, phi = bovy_coords.cyl_to_spher(R,z,phi)
dr_dz = nu.divide(z,r); dtheta_dz = nu.divide(-R,r**2); dphi_dz = 0
return self._computeforceArray(dr_dz, dtheta_dz, dphi_d... | NAME:
_zforce
PURPOSE:
evaluate the vertical force at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
vertical force at (R,z, phi)
HISTORY:
2... |
339,276 | def domain_name():
result = random.choice(get_dictionary()).strip()
result += + top_level_domain()
return result.lower() | Return a random domain name.
Lowercased result of :py:func:`~forgery_py.forgery.name.company_name()`
plus :py:func:`~top_level_domain()`. |
339,277 | def native(self, value, context=None):
value = super().native(value, context)
if value is None: return
try:
return self.ingress(value)
except Exception as e:
raise Concern("Unable to transform incoming value: {0}", str(e)) | Convert a value from a foriegn type (i.e. web-safe) to Python-native. |
339,278 | def _get_read_names(self, search_result, max_range):
hit
splits = {}
spans = []
for result in search_result:
spans += list(
result.each(
[SequenceSearchResult.QUERY_ID_FIELD,
... | _get_read_names - loops through hmm hits and their alignment spans to
determine if they are potentially linked (for example, if one gene in a
contig hits a hmm more than once, in two different conserved regions
of that gene) and combines them into one 'hit' because they are
technically ... |
339,279 | def decrypt(data, digest=True):
alg, _, data = data.rpartition("$")
if not alg:
return data
data = _from_hex_digest(data) if digest else data
try:
return implementations["decryption"][alg](
data, implementations["get_key"]()
)
except KeyError:
raise C... | Decrypt provided data. |
339,280 | def parse_requirements(strs):
lines = iter(yield_lines(strs))
for line in lines:
if in line:
line = line[:line.find()]
if line.endswith():
line = line[:-2].strip()
try:
line += next(lines)
except StopIt... | Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof. |
339,281 | def delete(self, id ):
target_url = self.client.get_url(, , , {:id})
r = self.client.request(, target_url, headers={: })
r.raise_for_status() | Delete a token |
339,282 | def first_phase(invec, outvec, N1, N2):
global _theplan
if _theplan is None:
_theplan = plan_first_phase(N1, N2)
fexecute(_theplan, invec.ptr, outvec.ptr) | This implements the first phase of the FFT decomposition, using
the standard FFT many plans.
Parameters
-----------
invec : array
The input array.
outvec : array
The output array.
N1 : int
Number of rows.
N2 : int
Number of columns. |
339,283 | def _drop_diagonal(self):
self.network = self.network.where(
self.network[] != self.network[]).dropna()
self.network.reset_index(inplace=True, drop=True) | Drops self-contacts from the network dataframe. |
339,284 | def dense(x, units, **kwargs):
layer_collection = kwargs.pop("layer_collection", None)
activations = layers().Dense(units, **kwargs)(x)
if layer_collection:
layer_name = tf.get_variable_scope().name
if (not layer_name) or ("name" not in kwargs):
raise ValueError(
"Variabl... | Identical to layers.dense. |
339,285 | def fetch_hpo_files(hpogenes=False, hpoterms=False, phenotype_to_terms=False, hpodisease=False):
LOG.info("Fetching HPO information from http://compbio.charite.de")
base_url = (
)
hpogenes_url = base_url.format()
hpoterms_url= base_url.format()
hpo_phenotype_to_terms_url = bas... | Fetch the necessary mim files using a api key
Args:
api_key(str): A api key necessary to fetch mim data
Returns:
mim_files(dict): A dictionary with the neccesary files |
339,286 | def _unpack_args(args, nargs_spec):
args = deque(args)
nargs_spec = deque(nargs_spec)
rv = []
spos = None
def _fetch(c):
try:
if spos is None:
return c.popleft()
else:
return c.pop()
except IndexError:
return N... | Given an iterable of arguments and an iterable of nargs specifications,
it returns a tuple with all the unpacked arguments at the first index
and all remaining arguments as the second.
The nargs specification is the number of arguments that should be consumed
or `-1` to indicate that this position shou... |
339,287 | def sample_batch_transitions(self, batch_size, forward_steps=1):
results = []
for i in range(self.num_envs):
results.append(self.sample_frame_single_env(batch_size, forward_steps=forward_steps))
return np.stack(results, axis=-1) | Return indexes of next sample |
339,288 | def toggle_check_all_eventtype(self):
checklist = asarray([btn.isChecked for btn in self.idx_eventtype_list])
if not checklist.all():
self.check_all_eventtype.setChecked(False) | Check 'All' if all event types are checked in event type scroll. |
339,289 | def get(self):
values = [e.get() for e in self._entries]
if len(self._entries) == 1:
return values[0]
else:
return values | Returns the value for the slot.
:return: the entry value |
339,290 | def _check_state(self, state):
if not hasattr(state, ) or isinstance(state, six.string_types):
raise ValueError()
state_vars = {s.var for s in state}
if not state_vars == set(self.variables):
raise ValueError(
.format(svar=state_vars,... | Checks if a list representing the state of the variables is valid. |
339,291 | def add_entry(self, timestamp, data):
if not isinstance(data, list):
data = [data]
if len(data) != self._dimensionCount:
raise ValueError("data does contain %s instead of %s dimensions.\n %s" % (len(data), self._dimensionCount, data))
self._normalized = self.... | Adds a new data entry to the TimeSeries.
:param timestamp: Time stamp of the data.
This has either to be a float representing the UNIX epochs
or a string containing a timestamp in the given format.
:param list data: A list containing the actual dimension values.
:... |
339,292 | def start_check (aggregate, out):
t = threading.Thread(target=director.check_urls, args=(aggregate,))
t.start()
sleep_seconds = 2
run_seconds = 0
while not aggregate.is_finished():
yield out.get_data()
time.sleep(sleep_seconds)
run_seconds += sleep_seconds... | Start checking in background and write encoded output to out. |
339,293 | def print_markdown(data, title=None):
markdown = []
for key, value in data.items():
if isinstance(value, basestring_) and Path(value).exists():
continue
markdown.append("* **{}:** {}".format(key, unicode_(value)))
if title:
print("\n
print("\n{}\n".format("\n".jo... | Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2. |
339,294 | def compute_distances_dict(egg):
pres, rec, features, dist_funcs = parse_egg(egg)
pres_list = list(pres)
features_list = list(features)
distances = {}
for idx1, item1 in enumerate(pres_list):
distances[item1]={}
for idx2, item2 in enumerate(pres_list):
... | Creates a nested dict of distances |
339,295 | def computeCapacity(results, threshold):
closestBelow = None
closestAbove = None
for numObjects, accuracy in sorted(results):
if accuracy >= threshold:
if closestAbove is None or closestAbove[0] < numObjects:
closestAbove = (numObjects, accuracy)
closestBelow = None
else:
if... | Returns largest number of objects with accuracy above threshold. |
339,296 | def parse_link(html):
parser = AnchorParser()
parser.feed(html)
return parser.ParsedLink(parser.url, parser.text) | Parses an HTML anchor tag, returning the href and content text. Any
content before or after the anchor tag pair is ignored.
:param html:
Snippet of html to parse
:returns:
namedtuple('ParsedLink', ['url', 'text'])
Example:
.. code-block:: python
>>> parse_link('things <a... |
339,297 | def parse_bismark_bam2nuc(self, f):
if f[] in self.bismark_data[]:
log.debug("Duplicate deduplication sample log found! Overwriting: {}".format(f[]))
self.add_data_source(f, section=)
self.bismark_data[][f[]] = dict()
headers = None
for l in f[]:
... | Parse reports generated by Bismark bam2nuc |
339,298 | def run(self, command, name_addition=None, cmd_kwargs=None,
_cmd="sbatch", tries=1, depends_on=None):
if name_addition is None:
name_addition = hashlib.sha1(command.encode("utf-8")).hexdigest()
if self.date_in_name:
name_addition += "-" + str(datetime.date.t... | command: a bash command that you want to run
name_addition: if not specified, the sha1 of the command to run
appended to job name. if it is "date", the yyyy-mm-dd
date will be added to the job name.
cmd_kwargs: dict of extra arguments to fill in command
... |
339,299 | def read_value_from_path(value):
if value.startswith():
path = value.split(, 1)[1]
config_directory = get_config_directory()
relative_path = os.path.join(config_directory, path)
with open(relative_path) as read_file:
value = read_file.read()
return value | Enables translators to read values from files.
The value can be referred to with the `file://` prefix. ie:
conf_key: ${kms file://kms_value.txt} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.