Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
372,600 | def alias_config_alias_name(self, **kwargs):
config = ET.Element("config")
alias_config = ET.SubElement(config, "alias-config", xmlns="urn:brocade.com:mgmt:brocade-aaa")
alias = ET.SubElement(alias_config, "alias")
name = ET.SubElement(alias, "name")
name.text = kwargs.p... | Auto Generated Code |
372,601 | def save_to_mat_file(self, parameter_space,
result_parsing_function,
filename, runs):
for key in parameter_space:
if not isinstance(parameter_space[key], list):
parameter_space[key] = [parameter_space[key]]
... | Return the results relative to the desired parameter space in the form
of a .mat file.
Args:
parameter_space (dict): dictionary containing
parameter/list-of-values pairs.
result_parsing_function (function): user-defined function, taking a
result d... |
372,602 | def group_membership_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/group_memberships
api_path = "/api/v2/group_memberships.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/group_memberships#create-membership |
372,603 | def render_unregistered(error=None):
return template(
read_index_template(),
registered=False,
error=error,
seeder_data=None,
url_id=None,
) | Render template file for the unregistered user.
Args:
error (str, default None): Optional error message.
Returns:
str: Template filled with data. |
372,604 | def generate_df(js_dict, naming, value="value"):
values = []
dimensions, dim_names = get_dimensions(js_dict, naming)
values = get_values(js_dict, value=value)
output = pd.DataFrame([category + [values[i]]
for i, category in
enumerate(get_df_row... | Decode JSON-stat dict into pandas.DataFrame object. Helper method \
that should be called inside from_json_stat().
Args:
js_dict(OrderedDict): OrderedDict with data in JSON-stat format, \
previously deserialized into a python object by \
json.loa... |
372,605 | def _handle_github(self):
value = click.prompt(
_BUG + click.style(
,
fg=,
) + click.style(
,
fg=,
) + click.style(
,
fg=,
) ... | Handle exception and submit it as GitHub issue. |
372,606 | def strip_to_chains(self, chains, break_at_endmdl = True):
if chains:
chains = set(chains)
self.lines = [l for l in self.lines if not(l.startswith() or l.startswith() or l.startswith() or l.startswith()) or l[21] in chains]
if break_at_end... | Throw away all ATOM/HETATM/ANISOU/TER lines for chains that are not in the chains list. |
372,607 | def update_module_item(self, id, course_id, module_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_module_id=None, module_item_new_tab=None, module_item_position=None, module_item_published=None, mod... | Update a module item.
Update and return an existing module item |
372,608 | def _set_boutons_interface(self, buttons):
for id_action, f, d, is_active in buttons:
icon = self.get_icon(id_action)
action = self.addAction(QIcon(icon), d)
action.setEnabled(is_active)
action.triggered.connect(f) | Display buttons given by the list of tuples (id,function,description,is_active) |
372,609 | def get_vlan_brief_output_vlan_interface_interface_name(self, **kwargs):
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan... | Auto Generated Code |
372,610 | def GenerateNetworkedConfigFile(load_hook, normal_class_load_hook, normal_class_dump_hook, **kwargs) -> NetworkedConfigObject:
def NetworkedConfigObjectGenerator(url, safe_load: bool=True):
cfg = NetworkedConfigObject(url=url, load_hook=load_hook, safe_load=safe_load,
... | Generates a NetworkedConfigObject using the specified hooks. |
372,611 | def get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs):
import mavutil
self = mavutil.mavfile_global
m = SERVO_OUTPUT_RAW
motor_pwm = m.servo1_raw + m.servo2_raw + m.servo3_raw + m.servo4_raw
motor_pwm *= 0.25
rc3_min = self.param(, 1100)
rc3_max = self.param(, 1900)
motor = (moto... | calculate magnetic field strength from raw magnetometer |
372,612 | def _apply_rate(self, max_rate, aggressive=False):
self.log(u"Called _apply_rate")
self.log([u" Aggressive: %s", aggressive])
self.log([u" Max rate: %.3f", max_rate])
regular_fragments = list(self.smflist.regular_fragments)
if len(regular_fragments) <= 1:
... | Try to adjust the rate (characters/second)
of the fragments of the list,
so that it does not exceed the given ``max_rate``.
This is done by testing whether some slack
can be borrowed from the fragment before
the faster current one.
If ``aggressive`` is ``True``,
... |
372,613 | def grow(files: hug.types.multiple, in_ext: hug.types.text="short", out_ext: hug.types.text="html",
out_dir: hug.types.text="", recursive: hug.types.smart_boolean=False):
if files == []:
print(text(sys.stdin.read()))
return
print(INTRO)
if recursive:
files = iter_sourc... | Grow up your markup |
372,614 | def for_kind(kind_map, type_, fallback_key):
if type_ not in kind_map:
if fallback_key not in kind_map:
raise ConfigException( % type_)
config = kind_map[fallback_key]
else:
config = kind_map[type_]
if isinstance(config, dict):
... | Create an Options object from any mapping. |
372,615 | def display_col_dp(dp_list, attr_name):
print()
print("---------- {:s} ----------".format(attr_name))
print([getattr(dp, attr_name) for dp in dp_list]) | show a value assocciated with an attribute for each
DataProperty instance in the dp_list |
372,616 | async def send_rpc(self, msg, _context):
service = msg.get()
rpc_id = msg.get()
payload = msg.get()
timeout = msg.get()
response_id = await self.service_manager.send_rpc_command(service, rpc_id, payload,
... | Send an RPC to a service on behalf of a client. |
372,617 | def get_beam(self, ra, dec):
if self.data is None:
return self.wcshelper.beam
else:
psf = self.get_psf_sky(ra, dec)
if not all(np.isfinite(psf)):
return None
return Beam(psf[0], psf[1], psf[2]) | Get the psf as a :class:`AegeanTools.fits_image.Beam` object.
Parameters
----------
ra, dec : float
The sky position (degrees).
Returns
-------
beam : :class:`AegeanTools.fits_image.Beam`
The psf at the given location. |
372,618 | def create_run(cmd, project, exp, grp):
from benchbuild.utils import schema as s
session = s.Session()
run = s.Run(
command=str(cmd),
project_name=project.name,
project_group=project.group,
experiment_name=exp,
run_group=str(grp),
experiment_group=projec... | Create a new 'run' in the database.
This creates a new transaction in the database and creates a new
run in this transaction. Afterwards we return both the transaction as
well as the run itself. The user is responsible for committing it when
the time comes.
Args:
cmd: The command that has ... |
372,619 | def update(self):
if len(self.__folder_list) == 0:
return self.__folder_list
for i in range(len(self.get())):
try:
self.__folder_list[i][] = self.__folder_size(self.path(i))
except OSError as e:
... | Update the command result attributed. |
372,620 | def clean_series(series, *args, **kwargs):
if not series.dtype == np.dtype():
return series
if any_generated((isinstance(v, datetime.datetime) for v in series)):
series = series.apply(clip_datetime)
if any_generated((isinstance(v, basestring) for v in series)):
series = series.a... | Ensure all datetimes are valid Timestamp objects and dtype is np.datetime64[ns]
>>> from datetime import timedelta
>>> clean_series(pd.Series([datetime.datetime(1, 1, 1), 9, '1942', datetime.datetime(1970, 10, 23)]))
0 1677-09-22 00:12:44+00:00
1 9
2 ... |
372,621 | def threenum(h5file, var, post_col=):
f = h5py.File(h5file, )
d = f[var]
w = f[post_col]
s = d.chunks[0]
n = d.shape[0]
maxval = -np.abs(d[0])
minval = np.abs(d[0])
total = 0
wsum = 0
for x in range(0, n, s):
aN = ~np.logical_or(np.isnan(d[x:x+s]), np.isinf(d[x:x+... | Calculates the three number summary for a variable.
The three number summary is the minimum, maximum and the mean
of the data. Traditionally one would summerise data with the
five number summary: max, min, 1st, 2nd (median), 3rd quartile.
But quantiles are hard to calculate without sorting the data
... |
372,622 | def build(cls, builder, *args, build_loop=None, **kwargs):
loop = asyncio.new_event_loop()
kwargs[] = loop
args = [arg for arg in args
if not isinstance(arg, asyncio.AbstractEventLoop)]
if asyncio.iscoroutinefunction(builder):
checked_loop = build_loo... | Build a hardware control API and initialize the adapter in one call
:param builder: the builder method to use (e.g.
:py:meth:`hardware_control.API.build_hardware_simulator`)
:param args: Args to forward to the builder method
:param kwargs: Kwargs to forward to the builde... |
372,623 | def rename(name, new_name):
id_ = inspect_container(name)[]
log.debug(%s\%s\,
name, id_, new_name)
_client_wrapper(, id_, new_name)
return inspect_container(new_name)[] == id_ | .. versionadded:: 2017.7.0
Renames a container. Returns ``True`` if successful, and raises an error if
the API returns one. If unsuccessful and the API returns no error (should
not happen), then ``False`` will be returned.
name
Name or ID of existing container
new_name
New name to... |
372,624 | def read_namespaced_replication_controller_status(self, name, namespace, **kwargs):
kwargs[] = True
if kwargs.get():
return self.read_namespaced_replication_controller_status_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_replic... | read_namespaced_replication_controller_status # noqa: E501
read status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replica... |
372,625 | def key(self, direction, mechanism, purviews=False, _prefix=None):
return "subsys:{}:{}:{}:{}:{}".format(
self.subsystem_hash, _prefix, direction, mechanism, purviews) | Cache key. This is the call signature of |Subsystem.find_mice()|. |
372,626 | def encode(self):
buf = bytearray()
for typ in sorted(self.format.keys()):
encoded = None
if typ != 0xFFFF:
(name, marshall) = self.format[typ]
value = getattr(self, name, None)
if value is not None:
tr... | Return binary string representation of object.
:rtype: str |
372,627 | def blocking_start(self, waiting_func=None):
try:
self.start()
self.wait_for_completion(waiting_func)
except KeyboardInterrupt:
while True:
try:
self.stop()
break
... | this function is just a wrapper around the start and
wait_for_completion methods. It starts the queuing thread and then
waits for it to complete. If run by the main thread, it will detect
the KeyboardInterrupt exception (which is what SIGTERM and SIGHUP
have been translated to) and wil... |
372,628 | def GetRunlevelsLSB(states):
if not states:
return set()
valid = set(["0", "1", "2", "3", "4", "5", "6"])
_LogInvalidRunLevels(states, valid)
return valid.intersection(set(states.split())) | Accepts a string and returns a list of strings of numeric LSB runlevels. |
372,629 | def merge_from(self, other):
if other.pattern is not None:
self.pattern = other.pattern
if other.format is not None:
self.format = other.format
self.leading_digits_pattern.extend(other.leading_digits_pattern)
if other.national_prefix_formatting_rule is no... | Merge information from another NumberFormat object into this one. |
372,630 | def _init_security(self):
if not self._starttls():
raise SecurityError("Could not start TLS connection")
self._ssl_handshake()
if not self._auth():
raise SecurityError("Could not authorize connection") | Initialize a secure connection to the server. |
372,631 | def get(self):
ret = {"clients": list(self.saltclients.keys()),
"return": "Welcome"}
self.write(self.serialize(ret)) | An endpoint to determine salt-api capabilities
.. http:get:: /
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000
.. c... |
372,632 | def paint(self, painter, option, index):
if option.state & QStyle.State_MouseOver:
styleSheet = self.__style.hover
elif option.state & QStyle.State_Selected:
styleSheet = self.__style.highlight
else:
styleSheet = self.__style.default
self.__... | Reimplements the :meth:`QStyledItemDelegate.paint` method. |
372,633 | def get_unique_sample_files(file_samples):
assert isinstance(file_samples, pd.DataFrame)
df = file_samples
df = df.sort_values()
logger.info(, len(df.index))
df.drop_duplicates(, keep=, inplace=True)
logger.info(
, len(df.index))
... | Filter file_sample data frame to only keep one file per sample.
Params
------
file_samples : `pandas.DataFrame`
A data frame containing a mapping between file IDs and sample barcodes.
This type of data frame is returned by :meth:`get_file_samples`.
Returns
-------
`... |
372,634 | def write(self, s):
b = s.encode(self.encoding)
return super(PtyProcessUnicode, self).write(b) | Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written. |
372,635 | def sphere_constrained_cubic(dr, a, alpha):
sqrt3 = np.sqrt(3)
b_coeff = a*0.5/sqrt3*(1 - 0.6*sqrt3*alpha)/(0.15 + a*a)
rscl = np.clip(dr, -0.5*sqrt3, 0.5*sqrt3)
a, d = rscl + 0.5*sqrt3, rscl - 0.5*sqrt3
return alpha*d*a*rscl + b_coeff*d*a - d/sqrt3 | Sphere generated by a cubic interpolant constrained to be (1,0) on
(r0-sqrt(3)/2, r0+sqrt(3)/2), the size of the cube in the (111) direction. |
372,636 | def clone(self, folder, git_repository):
os.makedirs(folder)
git.Git().clone(git_repository, folder) | Ensures theme destination folder and clone git specified repo in it.
:param git_repository: git url of the theme folder
:param folder: path of the git managed theme folder |
372,637 | def proximal_convex_conj_kl_cross_entropy(space, lam=1, g=None):
r
lam = float(lam)
if g is not None and g not in space:
raise TypeError(.format(g, space))
class ProximalConvexConjKLCrossEntropy(Operator):
def __init__(self, sigma):
self.sigma = floa... | r"""Proximal factory of the convex conj of cross entropy KL divergence.
Function returning the proximal factory of the convex conjugate of the
functional F, where F is the cross entropy Kullback-Leibler (KL)
divergence given by::
F(x) = sum_i (x_i ln(pos(x_i)) - x_i ln(g_i) + g_i - x_i) + ind_P(x)... |
372,638 | def put_content(self, content):
r = requests.request(self.method if self.method else , self.url, data=content, **self.storage_args)
if self.raise_for_status: r.raise_for_status() | Makes a ``PUT`` request with the content in the body.
:raise: An :exc:`requests.RequestException` if it is not 2xx. |
372,639 | def broker_metadata(self, broker_id):
return self._brokers.get(broker_id) or self._bootstrap_brokers.get(broker_id) | Get BrokerMetadata
Arguments:
broker_id (int): node_id for a broker to check
Returns:
BrokerMetadata or None if not found |
372,640 | def show_qt(qt_class, modal=False, onshow_event=None, force_style=False):
dialog = None
window = anchor()
for d in window.children():
if isinstance(d, qt_class):
dialog = d
if dialog is None:
dialog = qt_class(window)
if force_style:
set_style(... | Shows and raise a pyqt window ensuring it's not duplicated
(if it's duplicated then raise the old one).
qt_class argument should be a class/subclass of QMainWindow, QDialog or any
top-level widget.
onshow_event provides a way to pass a function to execute before the window
is showed on screen, it sh... |
372,641 | def get_cond_latents_at_level(cond_latents, level, hparams):
if cond_latents:
if hparams.latent_dist_encoder in ["conv_net", "conv3d_net"]:
return [cond_latent[level] for cond_latent in cond_latents]
elif hparams.latent_dist_encoder in ["pointwise", "conv_lstm"]:
return cond_latents[level] | Returns a single or list of conditional latents at level 'level'. |
372,642 | def timeit(unit=):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
start = time.time()
_result = func(*args, **kwargs)
_format(unit, time.time() - start, func.__name__ + )
return _result
return inner
return wrapper | 测试函数耗时
:param unit: 时间单位,有 's','m','h' 可选(seconds,minutes,hours) |
372,643 | def clear(self):
for f in [x[] for x in self.metadata.values()]:
os.remove(f)
self.metadata = {}
self._flush() | Remove all entries from the cache and delete all data.
:return: |
372,644 | def bind_column(model, name, column, force=False, recursive=False, copy=False) -> Column:
if not subclassof(model, BaseModel):
raise InvalidModel(f"{model} is not a subclass of BaseModel")
meta = model.Meta
if copy:
column = copyfn(column)
column._name = name
safe_repr = un... | Bind a column to the model with the given name.
This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily
attach a new column to an existing model:
.. code-block:: python
import bloop.models
class User(BaseModel):
id = Column(String, ... |
372,645 | def DeserializeExclusiveData(self, reader):
self.Type = TransactionType.ClaimTransaction
if self.Version != 0:
raise Exception()
numrefs = reader.ReadVarInt()
claims = []
for i in range(0, numrefs):
c = CoinReference()
c.Deserialize(... | Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: If the transaction type is incorrect or if there are no claims. |
372,646 | def install(*pkgs, **kwargs):
**
attributes = kwargs.get(, False)
if not pkgs:
return "Plese specify a package or packages to upgrade"
cmd = _quietnix()
cmd.append()
if kwargs.get(, False):
cmd.extend(_zip_flatten(, pkgs))
else:
cmd.extend(pkgs)
out = _run(cm... | Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
... |
372,647 | def inst(self, *instructions):
for instruction in instructions:
if isinstance(instruction, list):
self.inst(*instruction)
elif isinstance(instruction, types.GeneratorType):
self.inst(*instruction)
elif isinstance(instruction, tuple):
... | Mutates the Program object by appending new instructions.
This function accepts a number of different valid forms, e.g.
>>> p = Program()
>>> p.inst(H(0)) # A single instruction
>>> p.inst(H(0), H(1)) # Multiple instructions
>>> p.inst([H(0), H(1)]) # A list of ... |
372,648 | def reload(self):
if not self.fd.closed: self.fd.close()
self.fd = open(self.fd.name, )
self.load() | Automatically reloads the config file.
This is just an alias for self.load(). |
372,649 | def cressman_point(sq_dist, values, radius):
r
weights = tools.cressman_weights(sq_dist, radius)
total_weights = np.sum(weights)
return sum(v * (w / total_weights) for (w, v) in zip(weights, values)) | r"""Generate a Cressman interpolation value for a point.
The calculated value is based on the given distances and search radius.
Parameters
----------
sq_dist: (N, ) ndarray
Squared distance between observations and grid point
values: (N, ) ndarray
Observation values in same order ... |
372,650 | def set_dependent_orders(
self,
accountID,
tradeSpecifier,
**kwargs
):
request = Request(
,
)
request.set_path_param(
,
accountID
)
request.set_path_param(
,
t... | Create, replace and cancel a Trade's dependent Orders (Take Profit,
Stop Loss and Trailing Stop Loss) through the Trade itself
Args:
accountID:
Account Identifier
tradeSpecifier:
Specifier for the Trade
takeProfit:
The ... |
372,651 | def _remove_unicode_encoding(xml_file):
unicode
with salt.utils.files.fopen(xml_file, ) as f:
xml_content = f.read()
modified_xml = re.sub(r"]+unicode[\, , xml_content.decode(), count=1)
xmltree = lxml.etree.parse(six.StringIO(modified_xml))
return xmltree | attempts to remove the "encoding='unicode'" from an xml file
as lxml does not support that on a windows node currently
see issue #38100 |
372,652 | def _kl_half_normal_half_normal(a, b, name=None):
with tf.name_scope(name or "kl_half_normal_half_normal"):
return (tf.math.log(b.scale) - tf.math.log(a.scale) +
(a.scale**2 - b.scale**2) / (2 * b.scale**2)) | Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.
Args:
a: Instance of a `HalfNormal` distribution object.
b: Instance of a `HalfNormal` distribution object.
name: (optional) Name to use for created operations.
default is "kl_half_normal_half_normal".
Returns:
Batchwi... |
372,653 | def _evaluate_rhs(cls, funcs, nodes, problem):
evald_funcs = cls._evaluate_functions(funcs, nodes)
evald_rhs = problem.rhs(nodes, *evald_funcs, **problem.params)
return evald_rhs | Compute the value of the right-hand side of the system of ODEs.
Parameters
----------
basis_funcs : list(function)
nodes : numpy.ndarray
problem : TwoPointBVPLike
Returns
-------
evaluated_rhs : list(float) |
372,654 | def transfer(self, user):
r = self._h._http_resource(
method=,
resource=(, self.name),
data={: user}
)
return r.ok | Transfers app to given username's account. |
372,655 | def sensorupdate(self, data):
if not isinstance(data, dict):
raise TypeError()
msg =
for key in data.keys():
msg += % (self._escape(str(key)),
self._escape(str(data[key])))
self._send(msg) | Given a dict of sensors and values, updates those sensors with the
values in Scratch. |
372,656 | def SkipAhead(self, file_object, number_of_characters):
lines_size = len(self.lines)
while number_of_characters >= lines_size:
number_of_characters -= lines_size
self.lines =
self.ReadLines(file_object)
lines_size = len(self.lines)
if lines_size == 0:
return
sel... | Skips ahead a number of characters.
Args:
file_object (dfvfs.FileIO): file-like object.
number_of_characters (int): number of characters. |
372,657 | def seek_in_frame(self, pos, *args, **kwargs):
super().seek(self._total_offset + pos, *args, **kwargs) | Seeks relative to the total offset of the current contextual frames. |
372,658 | def get_thumbnail(original, size, **options):
engine = get_engine()
cache = get_cache_backend()
original = SourceFile(original)
crop = options.get(, None)
options = engine.evaluate_options(options)
thumbnail_name = generate_filename(original, size, crop)
if settings.THUMBNAIL_DUMMY:
... | Creates or gets an already created thumbnail for the given image with the given size and
options.
:param original: File-path, url or base64-encoded string of the image that you want an
thumbnail.
:param size: String with the wanted thumbnail size. On the form: ``200x200``, ``200`` or
... |
372,659 | def new(self):
if self._initialized:
raise pycdlibexception.PyCdlibInternalError()
self.char_set = _unicodecharset()
self.log_vol_ident = _ostaunicode_zero_pad(, 128)
self.lv_info1 = b * 36
self.lv_info2 = b * 36
self.lv_info3 = b * 36
... | A method to create a new UDF Implementation Use Volume Descriptor Implementation Use field.
Parameters:
None:
Returns:
Nothing. |
372,660 | def plotlyviz(
scomplex,
colorscale=None,
title="Kepler Mapper",
graph_layout="kk",
color_function=None,
color_function_name=None,
dashboard=False,
graph_data=False,
factor_size=3,
edge_linewidth=1.5,
node_linecolor="rgb(200,200,200)",
width=600,
height=5... | Visualizations and dashboards for kmapper graphs using Plotly. This method is suitable for use in Jupyter notebooks.
The generated FigureWidget can be updated (by performing a restyle or relayout). For example, let us add a title
to the colorbar (the name of the color function, if any),
... |
372,661 | def redefined_by_decorator(node):
if node.decorators:
for decorator in node.decorators.nodes:
if (
isinstance(decorator, astroid.Attribute)
and getattr(decorator.expr, "name", None) == node.name
):
return True
return False | return True if the object is a method redefined via decorator.
For example:
@property
def x(self): return self._x
@x.setter
def x(self, value): self._x = value |
372,662 | def nextLunarEclipse(date):
eclipse = swe.lunarEclipseGlobal(date.jd, backward=False)
return Datetime.fromJD(eclipse[], date.utcoffset) | Returns the Datetime of the maximum phase of the
next global lunar eclipse. |
372,663 | def recurse_taxonomy_map(tax_id_map, tax_id, parent=False):
if parent:
pass
else:
def _child_recurse(tax_id, visited):
try:
children = [tax_id] + list(tax_id_map[tax_id])
except KeyError:
children = [tax_id]
for... | Takes the output dict from make_taxonomy_map and an input tax_id
and recurses either up or down through the tree to get /all/ children
(or parents) of the given tax_id. |
372,664 | def escape_latex(text):
r
text = unicode(text.decode())
CHARS = {
: r,
: r,
: r,
: r,
: r,
: r,
: r,
: r,
: r,
: r,
}
escaped = "".join([CHARS.get(char, char) for char in text])
return escaped.encode() | r"""Escape characters of given text.
This function takes the given text and escapes characters
that have a special meaning in LaTeX: # $ % ^ & _ { } ~ \ |
372,665 | def import_sequence_flow_to_graph(diagram_graph, sequence_flows, process_id, flow_element):
flow_id = flow_element.getAttribute(consts.Consts.id)
name = flow_element.getAttribute(consts.Consts.name) if flow_element.hasAttribute(consts.Consts.name) else ""
source_ref = flow_element.getAt... | Adds a new edge to graph and a record to sequence_flows dictionary.
Input parameter is object of class xml.dom.Element.
Edges are identified by pair of sourceRef and targetRef attributes of BPMNFlow element. We also
provide a dictionary, that maps sequenceFlow ID attribute with its sourceRef and... |
372,666 | def collage(img_spec,
num_rows=2,
num_cols=6,
rescale_method=,
cmap=,
annot=None,
padding=5,
bkground_thresh=None,
output_path=None,
figsize=None,
**kwargs):
"Produces a collage of various slices ... | Produces a collage of various slices from different orientations in the given 3D image |
372,667 | def register(self, item):
if callable(item) and hasattr(item, ):
item = item.__orb__
key = item.name()
model = self.__model
if isinstance(item, orb.Index):
self.__indexes[key] = item
item.setSchema(self)
if model and no... | Registers a new orb object to this schema. This could be a column, index, or collector -- including
a virtual object defined through the orb.virtual decorator.
:param item: <variant>
:return: |
372,668 | def selected(self, sel):
ParameterItem.selected(self, sel)
if self.widget is None:
return
if sel and self.param.writable():
self.showEditor()
elif self.hideWidget:
self.hideEditor() | Called when this item has been selected (sel=True) OR deselected (sel=False) |
372,669 | def sizeof_fmt(num, suffix=):
precision = {: 0, : 0, : 0, : 3, : 6, : 9, : 12, : 15}
for unit in [, , , , , , , ]:
if abs(num) < 1024.0:
format_string = "{number:.%df} {unit}{suffix}" % precision[unit]
return format_string.format(number=num, unit=unit, suffix=suffix)
... | Adapted from https://stackoverflow.com/a/1094933
Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection |
372,670 | def update_nginx_from_config(nginx_config):
logging.info()
temp_dir = tempfile.mkdtemp()
os.mkdir(os.path.join(temp_dir, ))
_write_nginx_config(constants.NGINX_BASE_CONFIG, os.path.join(temp_dir, constants.NGINX_PRIMARY_CONFIG_NAME))
_write_nginx_config(nginx_config[], os.path.join(temp_dir, co... | Write the given config to disk as a Dusty sub-config
in the Nginx includes directory. Then, either start nginx
or tell it to reload its config to pick up what we've
just written. |
372,671 | def compute_edge_widths(self):
if type(self.edge_width) is str:
edges = self.graph.edges
self.edge_widths = [edges[n][self.edge_width] for n in self.edges]
else:
self.edge_widths = self.edge_width | Compute the edge widths. |
372,672 | def convertShape(shapeString):
cshape = []
for pointString in shapeString.split():
p = [float(e) for e in pointString.split(",")]
if len(p) == 2:
cshape.append((p[0], p[1], 0.))
elif len(p) == 3:
cshape.append(tuple(p))
else:
raise ValueE... | Convert xml shape string into float tuples.
This method converts the 2d or 3d shape string from SUMO's xml file
into a list containing 3d float-tuples. Non existant z coordinates default
to zero. If shapeString is empty, an empty list will be returned. |
372,673 | def _get_hourly_data(self, day_date, p_p_id):
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationHoraires",
"p_p_cachea... | Get Hourly Data. |
372,674 | def _is_chunk_markdown(source):
lines = source.splitlines()
if all(line.startswith() for line in lines):
source = .join(line[2:] for line in lines
if not line[2:].startswith())
if not source:
return True
return not ... | Return whether a chunk contains Markdown contents. |
372,675 | def cmd_notice(self, connection, sender, target, payload):
msg_target, topic, content = self.parse_payload(payload)
def callback(sender, payload):
logging.info("NOTICE ACK from %s: %s", sender, payload)
self.__herald.notice(msg_target, topic, content, callback) | Sends a message |
372,676 | def create_tasks(self, wfk_file, scr_input):
assert len(self) == 0
wfk_file = self.wfk_file = os.path.abspath(wfk_file)
shell_manager = self.manager.to_shell_manager(mpi_procs=1)
w = Work(workdir=self.tmpdir.path_join("_qptdm_run"), manager=shell_manager)
... | Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation. |
372,677 | def frame_iv(algorithm, sequence_number):
if sequence_number < 1 or sequence_number > MAX_FRAME_COUNT:
raise ActionNotAllowedError(
"Invalid frame sequence number: {actual}\nMust be between 1 and {max}".format(
actual=sequence_number, max=MAX_FRAME_COUNT
)
... | Builds the deterministic IV for a body frame.
:param algorithm: Algorithm for which to build IV
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int sequence_number: Frame sequence number
:returns: Generated IV
:rtype: bytes
:raises ActionNotAllowedError: if sequence number of o... |
372,678 | def _request_one_trial_job(self):
if not self.generated_hyper_configs:
ret = {
: ,
: ,
:
}
send(CommandType.NoMoreTrialJobs, json_tricks.dumps(ret))
return
assert self.generated_hyper_configs
... | get one trial job, i.e., one hyperparameter configuration.
If this function is called, Command will be sent by BOHB:
a. If there is a parameter need to run, will return "NewTrialJob" with a dict:
{
'parameter_id': id of new hyperparameter
'parameter_source': 'algorithm'... |
372,679 | def atstart(callback, *args, **kwargs):
s behavior, have it run automatically if
your object is instantiated or module imported.
This is not at all useful after your hook framework as been launched.
'
global _atstart
_atstart.append((callback, args, kwargs)) | Schedule a callback to run before the main hook.
Callbacks are run in the order they were added.
This is useful for modules and classes to perform initialization
and inject behavior. In particular:
- Run common code before all of your hooks, such as logging
the hook name or interesting ... |
372,680 | def delete_evpn_local(route_type, route_dist, **kwargs):
try:
tm = CORE_MANAGER.get_core_service().table_manager
tm.update_vrf_table(route_dist,
route_family=VRF_RF_L2_EVPN,
route_type=route_type, is_withdraw=True, **kwargs)
... | Deletes/withdraws EVPN route from VRF identified by *route_dist*. |
372,681 | def fastqWrite(fileHandleOrFile, name, seq, qualValues, mode="w"):
fileHandle = _getFileHandle(fileHandleOrFile, mode)
assert seq.__class__ == "".__class__
for i in seq:
if not ((i >= and i <= ) or (i >= and i <= ) or i == ):
raise RuntimeError("Invalid FASTQ character, ASCII cod... | Writes out fastq file. If qualValues is None or '*' then prints a '*' instead. |
372,682 | def filter_duplicate(self, url):
if self.filterDuplicate:
if url in self.historys:
raise Exception( % url)
else:
self.historys.add(url)
else:
pass | url去重 |
372,683 | def delete_Variable(self,name):
self.message(1,.format(name))
self.par_list=self.par_list[self.par_list != name]
return self.__dict__.pop(name) | pops a variable from class and delete it from parameter list
:parameter name: name of the parameter to delete |
372,684 | def tempfilename(**kwargs):
kwargs.update(delete=False)
try:
f = NamedTemporaryFile(**kwargs)
f.close()
yield f.name
except Exception:
if os.path.exists(f.name):
os.unlink(f.name)
raise | Reserve a temporary file for future use.
This is useful if you want to get a temporary file name, write to it in the
future and ensure that if an exception is thrown the temporary file is removed. |
372,685 | def delete_network(context, id):
LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id))
with context.session.begin():
net = db_api.network_find(context=context, limit=None, sorts=[],
marker=None, page_reverse=False, id=id,
... | Delete a network.
: param context: neutron api request context
: param id: UUID representing the network to delete. |
372,686 | def draw(self):
devs = normal(size=self._sig.shape[1])
p = inner(self._sig, devs) + self._mu
self._set_stochastics(p) | N.draw()
Sets all N's stochastics to random values drawn from
the normal approximation to the posterior. |
372,687 | def get_my_feed(self, limit=150, offset=20, sort="updated", nid=None):
r = self.request(
method="network.get_my_feed",
nid=nid,
data=dict(
limit=limit,
offset=offset,
sort=sort
)
)
return sel... | Get my feed
:type limit: int
:param limit: Number of posts from feed to get, starting from ``offset``
:type offset: int
:param offset: Offset starting from bottom of feed
:type sort: str
:param sort: How to sort feed that will be retrieved; only current
known... |
372,688 | def load_mayaplugins():
mpp = os.environ.get()
if mpp is not None:
.join([mpp, MAYA_PLUGIN_PATH])
else:
mpp = MAYA_PLUGIN_PATH
os.environ[] = MAYA_PLUGIN_PATH
cmds.loadPlugin(allPlugins=True)
os.environ[] = mpp | Loads the maya plugins (not jukebox plugins) of the pipeline
:returns: None
:rtype: None
:raises: None |
372,689 | def insert_inexistence(self, table, kwargs, condition):
sql = "insert into " + table + " ({}) "
select = "select {} "
condition = "where not exists (select 1 from " + table + "{} limit 1);".format( self.parse_condition(condition) )
keys, values = [], []
[ (keys.append(k)... | .. :py:method::
Usage::
>>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}, {'id': '12de3wrv'})
insert into hospital (id, province) select '12de3wrv', 'shanghai' where not exists (select 1 from hospital where id='12de3wrv' limit 1); |
372,690 | def search(self, search_phrase, limit=None):
from ambry.identity import ObjectNumber
from ambry.orm.exc import NotFoundError
from ambry.library.search_backends.base import SearchTermParser
results = []
stp = SearchTermParser()
parsed_terms = ... | Search for datasets, and expand to database records |
372,691 | def dump_registers_peek(registers, data, separator = , width = 16):
if None in (registers, data):
return
names = compat.keys(data)
names.sort()
result =
for reg_name in names:
tag = reg_name.lower()
dumped = HexDump.hexline(data... | Dump data pointed to by the given registers, if any.
@type registers: dict( str S{->} int )
@param registers: Dictionary mapping register names to their values.
This value is returned by L{Thread.get_context}.
@type data: dict( str S{->} str )
@param data: Dictionary mapp... |
372,692 | def _clean_tx(response_dict):
confirmed_txrefs = []
for confirmed_txref in response_dict.get(, []):
confirmed_txref[] = parser.parse(confirmed_txref[])
confirmed_txrefs.append(confirmed_txref)
response_dict[] = confirmed_txrefs
unconfirmed_txrefs = []
for unconfirmed_txref in r... | Pythonize a blockcypher API response |
372,693 | def setup(self, database):
self.db = database
self.hgnc_collection = database.hgnc_gene
self.user_collection = database.user
self.whitelist_collection = database.whitelist
self.institute_collection = database.institute
self.event_collection = database.event
... | Setup connection to database. |
372,694 | def pack(o, stream, **kwargs):
msgpack_module = kwargs.pop(, msgpack)
orig_enc_func = kwargs.pop(, lambda x: x)
def _enc_func(obj):
obj = ThreadLocalProxy.unproxy(obj)
return orig_enc_func(obj)
return msgpack_module.pack(o, stream, default=_enc_func, **kwargs) | .. versionadded:: 2018.3.4
Wraps msgpack.pack and ensures that the passed object is unwrapped if it is
a proxy.
By default, this function uses the msgpack module and falls back to
msgpack_pure, if the msgpack is not available. You can pass an alternate
msgpack module using the _msgpack_module argu... |
372,695 | def delete_instance(self, instance_id):
title = % self.__class__.__name__
input_fields = {
: instance_id
}
for key, value in input_fields.items():
object_title = % (title, key, str(value))
self.fields.validate(value, % key, object_t... | method for removing an instance from AWS EC2
:param instance_id: string of instance id on AWS
:return: string reporting state of instance |
372,696 | def train(self, recall=0.95, index_predicates=True):
examples, y = flatten_training(self.training_pairs)
self.classifier.fit(self.data_model.distances(examples), y)
self.predicates = self.active_learner.learn_predicates(
recall, index_predicates)
self.blocker = bl... | Keyword arguments:
maximum_comparisons -- The maximum number of comparisons a
blocking rule is allowed to make.
Defaults to 1000000
recall -- The proportion of true dupe pairs in our training
data that that we the learned... |
372,697 | def get_supported_filepaths(filepaths, supported_extensions, max_depth=float()):
supported_filepaths = []
for path in filepaths:
if os.name == and CYGPATH_RE.match(path):
path = convert_cygwin_path(path)
if os.path.isdir(path):
for root, __, files in walk_depth(path, max_depth):
for f in files:
... | Get filepaths with supported extensions from given filepaths.
Parameters:
filepaths (list or str): Filepath(s) to check.
supported_extensions (tuple or str): Supported file extensions or a single file extension.
max_depth (int): The depth in the directory tree to walk.
A depth of '0' limits the walk to the... |
372,698 | def PC_PI_calc(P, TOP, POP):
try:
result = 0
for i in P.keys():
result += ((P[i] + TOP[i]) / (2 * POP[i]))**2
return result
except Exception:
return "None" | Calculate percent chance agreement for Scott's Pi.
:param P: condition positive
:type P : dict
:param TOP: test outcome positive
:type TOP : dict
:param POP: population
:type POP:dict
:return: percent chance agreement as float |
372,699 | def pylint_amnesty(pylint_output):
errors = defaultdict(lambda: defaultdict(set))
for pylint_error in parse_pylint_output(pylint_output):
errors[pylint_error.filename][pylint_error.linenum].add(pylint_error)
for file_with_errors in sorted(errors):
try:
opened_file = open(fi... | Add ``# pylint: disable`` clauses to add exceptions to all existing pylint errors in a codebase. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.