Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
349,500 | def ossos_release_with_metadata():
discoveries = []
observations = ossos_discoveries()
for obj in observations:
discov = [n for n in obj[0].mpc_observations if n.discovery.is_discovery][0]
tno = parameters.tno()
tno.dist = obj[1].distance
tno.ra_discov = discov.coor... | Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines |
349,501 | def ipv6_hdr_len(ipv6):
hdr_len = ipv6.__hdr_len__
for code in (0, 60, 43):
ext_hdr = ipv6.extension_hdrs.get(code)
if ext_hdr is not None:
hdr_len += ext_hdr.length
return hdr_len | Calculate length of headers before IPv6-Frag |
349,502 | def get_magnitude_of_effect_from_spin_config(motif, spin_config):
magnitude = "none"
if motif == "oct":
e_g = spin_config["e_g"]
t_2g = spin_config["t_2g"]
if (e_g % 2 != 0) or (t_2g % 3 != 0):
magnitude = "weak"
if e_g % 2 == ... | Roughly, the magnitude of Jahn-Teller distortion will be:
* in octahedral environments, strong if e_g orbitals
unevenly occupied but weak if t_2g orbitals unevenly
occupied
* in tetrahedral environments always weaker
:param motif (str): "oct" or "tet"
:param spin_config (... |
349,503 | def load_bookmarks(filename):
bookmarks = _load_all_bookmarks()
return {k: v for k, v in bookmarks.items() if v[0] == filename} | Load all bookmarks for a specific file from config. |
349,504 | def memoize(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
cache = args[0].memoized
refresh = args[0].refresh_interval
use_cache = args[0].use_cache
if use_cache is False:
return func(*args, **kwargs)
if func.__name__ not... | quick memoize decorator for class instance methods
NOTE: this assumes that the class that the functions to be
memoized already has a memoized and refresh_interval
property |
349,505 | def _process(self, data):
"Process a single packet and update the internal tables."
parts = data.split()
if self._debug:
self.error( % data)
if not parts:
return
stats = self._stats
key = parts[0].translate(KEY_TABLE, KEY_DELETIONS)
... | Process a single packet and update the internal tables. |
349,506 | def assign_activity_to_objective_bank(self, activity_id, objective_bank_id):
mgr = self._get_provider_manager(, local=True)
lookup_session = mgr.get_objective_bank_lookup_session(proxy=self._proxy)
lookup_session.get_objective_bank(objective_bank_id)
self._as... | Adds an existing ``Activity`` to a ``ObjectiveBank``.
arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity``
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
``ObjectiveBank``
raise: AlreadyExists - ``activity_id`` already mapped to
``objectiv... |
349,507 | def get_cards(self, list_id):
params = {: }
member = self.config.get(, None)
unassigned = self.config.get(, False, asbool)
if member is not None:
params[] =
params[] =
cards = self.api_request(
"/1/lists/{list_id}/cards/open".format(... | Returns an iterator for the cards in a given list, filtered
according to configuration values of trello.only_if_assigned and
trello.also_unassigned |
349,508 | def get_version(package_name, version_file=):
filename = os.path.join(os.path.dirname(__file__), package_name, version_file)
with open(filename, ) as fp:
return fp.read().decode().split()[1].strip(" \n'") | Retrieve the package version from a version file in the package root. |
349,509 | def cov2corr(cov):
assert cov.ndim == 2,
inv_sd = 1 / np.sqrt(np.diag(cov))
corr = cov * inv_sd[None, :] * inv_sd[:, None]
return corr | Calculate the correlation matrix based on a
covariance matrix
Parameters
----------
cov: 2D array
Returns
-------
corr: 2D array
correlation converted from the covarince matrix |
349,510 | def main(pattern_filename, input_filenames, pattern_format,
output_filename,
encoding, words, by_line, slow, verbose, quiet):
set_log_level(verbose, quiet)
if slow:
by_line = True
by_line = True
LOGGER.info(.format(pattern_filename,
... | Search and replace on INPUT_FILE(s) (or standard input), with
matching on fixed strings. |
349,511 | def parse_request():
find = None
if request.endpoint is not None:
find = PATTERN_ENDPOINT.findall(request.endpoint)
if not find:
raise ValueError("invalid endpoint %s" % request.endpoint)
__, resource, action_name = find[0]
if action_name:
action = request.method.lower()... | Parse request endpoint and return (resource, action) |
349,512 | def second_order_moments_u(adata):
if not in adata.uns:
raise ValueError()
connectivities = get_connectivities(adata)
u = csr_matrix(adata.layers[])
Muu = csr_matrix.dot(connectivities, u.multiply(u)).astype(np.float32).A
return Muu | Computes second order moments for stochastic velocity estimation.
Arguments
---------
adata: `AnnData`
Annotated data matrix.
Returns
-------
Muu: Second order moments for unspliced abundances |
349,513 | def is_int(value):
ensure_instance(value, (int, str, bytes, float, Decimal))
if isinstance(value, int):
return True
elif isinstance(value, float):
return False
elif isinstance(value, Decimal):
return str(value).isdigit()
elif isinstance(value, (str, bytes)):
retu... | Check if value is an int
:type value: int, str, bytes, float, Decimal
>>> is_int(123), is_int('123'), is_int(Decimal('10'))
(True, True, True)
>>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1'))
(False, False, False)
>>> is_int(object)
Traceback (most recent call last):
TypeError: |
349,514 | def get(self, lengths: Union[mx.nd.NDArray, int, float]) -> Union[mx.nd.NDArray, float]:
return self.hybrid_forward(None, lengths) | Calculate the length penalty for the given vector of lengths.
:param lengths: A scalar or a matrix of sentence lengths of dimensionality (batch_size, 1).
:return: The length penalty. A scalar or a matrix (batch_size, 1) depending on the input. |
349,515 | def case_genelist(self, case_obj):
list_id = "{}-HPO".format(case_obj.case_id)
gene_list = self.gene_list(list_id)
if gene_list is None:
gene_list = GeneList(list_id=list_id)
case_obj.gene_lists.append(gene_list)
self.session.add(gene_list)
... | Get or create a new case specific gene list record. |
349,516 | def get_eids(self, num_rlzs):
num_events = self.n_occ if self.samples > 1 else self.n_occ * num_rlzs
return TWO32 * U64(self.serial) + numpy.arange(num_events, dtype=U64) | :param num_rlzs: the number of realizations for the given group
:returns: an array of event IDs |
349,517 | def file_list(saltenv=, backend=None):
fileserver = salt.fileserver.Fileserver(__opts__)
load = {: saltenv, : backend}
return fileserver.file_list(load=load) | Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the ... |
349,518 | def release(self, message_id, reservation_id, delay=0):
url = "queues/%s/messages/%s/release" % (self.name, message_id)
body = {: reservation_id}
if delay > 0:
body[] = delay
body = json.dumps(body)
response = self.client.post(url, body=body,
... | Release locked message after specified time. If there is no message with such id on the queue.
Arguments:
message_id -- The ID of the message.
reservation_id -- Reservation Id of the message.
delay -- The time after which the message will be released. |
349,519 | def grains():
if not DETAILS.get(, {}):
DETAILS[] = GRAINS_CACHE
try:
compute_rack = get_config_resolver_class(, False)
DETAILS[] = compute_rack[][]
except salt.exceptions.CommandExecutionError:
pass
except Exception as err:
log.er... | Get the grains from the proxied device |
349,520 | def remove_in_progress_check(self, check):
if check in self.checks_in_progress:
self.checks_in_progress.remove(check)
self.update_in_checking() | Remove check from check in progress
:param check: Check to remove
:type check: alignak.objects.check.Check
:return: None |
349,521 | def pretty_date(the_datetime):
diff = datetime.utcnow() - the_datetime
if diff.days > 7 or diff.days < 0:
return the_datetime.strftime()
elif diff.days == 1:
return
elif diff.days > 1:
return .format(diff.days)
elif diff.seconds <= 1:
return
elif ... | Attempt to return a human-readable time delta string. |
349,522 | def image_files_download(self, image_id):
img = self.image_files_get(image_id)
if img is None:
return None
else:
return FileInfo(
img.image_file,
img.properties[datastore.PROPERTY_MIMETYPE],
... | Get data file for image with given identifier.
Parameters
----------
image_id : string
Unique image identifier
Returns
-------
FileInfo
Information about image file on disk or None if identifier
is unknown |
349,523 | def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
... | A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify... |
349,524 | def settings(self, key=None, section=None):
if not self._settings:
self._settings = self.default_settings.copy()
section = section or self._settings[]
try:
if section in self.settings_parser.sections():
for option in self.settings_... | The settings overridden from the wandb/settings file.
Args:
key (str, optional): If provided only this setting is returned
section (str, optional): If provided this section of the setting file is
used, defaults to "default"
Returns:
A dict with the curre... |
349,525 | def releaseInterface(self):
r
util.release_interface(self.dev, self.__claimed_interface)
self.__claimed_interface = -1 | r"""Release an interface previously claimed with claimInterface. |
349,526 | def confirm_push(self, coord, version):
if not self.get_options().prompt:
return True
try:
isatty = os.isatty(sys.stdin.fileno())
except ValueError:
isatty = False
if not isatty:
return True
push = input(.format(
coord, version
))
print()
return ... | Ask the user if a push should be done for a particular version of a
particular coordinate. Return True if the push should be done |
349,527 | async def send(self, messages, message_timeout=0, session=None, **kwargs):
async with self.get_sender(message_timeout=message_timeout, session=session, **kwargs) as sender:
if isinstance(messages, Message):
sender.queue_message(messages)
else:
try... | Send one or more messages to the current entity.
This operation will open a single-use connection, send the supplied messages, and close
connection. If the entity requires sessions, a session ID must be either
provided here, or set on each outgoing message.
:param messages: One or more... |
349,528 | def quasi_newton_uniform(points, cells, *args, **kwargs):
def get_new_points(mesh):
x = mesh.node_coords.copy()
cells = mesh.cells["nodes"]
jac_x = jac_uniform(x, cells)
x -= solve_hessian_approx_uniform(x, cells, jac_x)
return x
mesh = MeshTri(po... | Like linear_solve above, but assuming rho==1. Note that the energy gradient
\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) \\int_{tau_j} rho
becomes
\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.
Because of the dependence of |tau_j| on the point coordinates, ... |
349,529 | def get_3_3_tuple(self,obj,default=None):
if is_sequence2(obj):
ret = []
for i in range(3):
if i<len(obj):
ret.append(self.get_3_tuple(obj[i],default))
else:
ret.append(self.get_3_tuple(default,default))
... | Return tuple of 3-tuples |
349,530 | def get(method, hmc, uri, uri_parms, logon_required):
cpc_oid = uri_parms[0]
query_str = uri_parms[1]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid)
except KeyError:
raise InvalidResourceError(method, uri)
result_adapters = []
if cpc.dpm_enabl... | Operation: List Adapters of a CPC (empty result if not in DPM
mode). |
349,531 | def client_seed(a=random.randrange(0, 1 << SRP_KEY_SIZE)):
if DEBUG:
a = DEBUG_PRIVATE_KEY
N, g, k = get_prime()
A = pow(g, a, N)
if DEBUG_PRINT:
print(, binascii.b2a_hex(long2bytes(a)), end=)
print(, binascii.b2a_hex(long2bytes(A)), end=)
return A, a | A: Client public key
a: Client private key |
349,532 | def time_stamp():
fmt =
date = datetime.datetime
date_delta = datetime.timedelta
now = datetime.datetime.utcnow()
return fmt, date, date_delta, now | Setup time functions
:returns: ``tuple`` |
349,533 | def get_vars(n):
op = n[0]
if op.startswith() and op.endswith():
op = op.strip()
if op == :
return [n[1]]
return []
else:
ret = []
for c in n[1:]:
vs = get_vars(c)
if vs:
ret.extend(vs)
return ret | extract variables from expression node
defined by tuple-pair: (_var_, [variable name]) |
349,534 | def set_data(self, source_data):
self.zpid = source_data.get(, None)
self.similarity_score = source_data.get(, None)
self.links.set_data(source_data[])
self.full_address.set_data(source_data[])
self.zestimate.set_data(source_data[])
self.local_realestate.set_dat... | :source_data": Data from data.get('SearchResults:searchresults', None)['response']['results']['result']
:param source_data:
:return: |
349,535 | def file_found(filename,force):
if os.path.exists(filename) and not force:
logger.info("Found %s; skipping..."%filename)
return True
else:
return False | Check if a file exists |
349,536 | def pad_if_need(sz_atleast, img, mode=):
imsz = img.shape[:2]
padneed = np.asarray((sz_atleast[0] - imsz[0], sz_atleast[1] - imsz[1]))
if np.any(padneed > 0):
padding = np.zeros((img.ndim, 2), dtype=)
padneed = np.maximum(padneed, 0)
padding[:2, 0] = padneed... | pad img if need to guarantee minumum size
:param sz_atleast: [H,W] at least
:param img: image np.array [H,W, ...]
:param mode: str, padding mode
:return: padded image or asis if enought size |
349,537 | def remove_filtered_nodes(graph, node_predicates=None):
nodes = list(filter_nodes(graph, node_predicates=node_predicates))
graph.remove_nodes_from(nodes) | Remove nodes passing the given node predicates.
:param pybel.BELGraph graph: A BEL graph
:type node_predicates: None or ((pybel.BELGraph, tuple) -> bool) or iter[(pybel.BELGraph, tuple) -> bool)] |
349,538 | def append(self, event, force = False):
if self.tree is None:
if self.parent is None:
raise IndexError()
else:
return self.parent.parent.append(event, force)
q = self.tree.matchfirst(event)
return q.append(event, force) | Append an event to queue. The events are classified and appended to sub-queues
:param event: input event
:param force: if True, the event is appended even if the queue is full
:returns: None if appended successfully, or a matcher to match a QueueCanWriteEvent otherwise |
349,539 | def summarizeFailedRuns():
global g_summary_dict_all
onlyFiles = [x for x in listdir(g_test_root_dir) if isfile(join(g_test_root_dir, x))]
for f in onlyFiles:
for fileStart in g_file_start:
if (fileStart in f) and (os.path.getsize(f) > 10):
fFullPath = os.path... | This function will look at the local directory and pick out files that have the correct start name and
summarize the results into one giant dict.
:return: None |
349,540 | def coercion_error(
message: str,
blame_node: Node = None,
path: Path = None,
sub_message: str = None,
original_error: Exception = None,
) -> GraphQLError:
if path:
path_str = print_path(path)
message += f" at {path_str}"
message += f"; {sub_message}" if sub_message else... | Return a GraphQLError instance |
349,541 | def _fnmatch(self, filename, patterns, default=True):
if not patterns:
return default
return any(fnmatch.fnmatch(filename, pattern) for pattern in patterns) | Wrap :func:`fnmatch.fnmatch` to add some functionality.
:param str filename:
Name of the file we're trying to match.
:param list patterns:
Patterns we're using to try to match the filename.
:param bool default:
The default value if patterns is empty
:... |
349,542 | def _get_rev_num(self, rev=None):
cmd = [, ]
cmd.extend([, ])
if rev:
cmd.extend([, rev])
res = self._invoke(*cmd)
return res.strip() | Determine the revision number for a given revision specifier. |
349,543 | def get_access_token(self) -> str:
if self._service_token:
return self._service_token
if self._app_id and self._login and self._password:
try:
if self.login():
url_params = self.auth_oauth2()
if in url_params:
... | Returns the access token in case of successful authorization |
349,544 | def get_escape_code(self, codetype, value):
valuefmt = str(value).lower()
code = codes[codetype].get(valuefmt, None)
if code:
return code
named_funcs = {
: format_fore,
: format_back,
: format_style,
}
... | Convert user arg to escape code. |
349,545 | def array(self) -> numpy.ndarray:
array = numpy.full(self.shape, fillvalue, dtype=float)
for idx, subarray in enumerate(self.arrays.values()):
array[self.get_timeplaceslice(idx)] = subarray
return array | The aggregated data of all logged |IOSequence| objects contained
in one single |numpy.ndarray| object.
The documentation on |NetCDFVariableAgg.shape| explains how
|NetCDFVariableAgg.array| is structured. This first example
confirms that, under default configuration (`timeaxis=1`),
... |
349,546 | def pop(self, key):
arr = dict.pop(self, key).copy()
self.remover(key)
return arr | Get and remove an element by key name |
349,547 | def scatter_group(ax, key, imask, adata, Y, projection=, size=3, alpha=None):
mask = adata.obs[key].cat.categories[imask] == adata.obs[key].values
color = adata.uns[key + ][imask]
if not isinstance(color[0], str):
from matplotlib.colors import rgb2hex
color = rgb2hex(adata.uns[key + ][i... | Scatter of group using representation of data Y. |
349,548 | def get_assignees(self):
return github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
self.url + "/assignees",
None
) | :calls: `GET /repos/:owner/:repo/assignees <http://developer.github.com/v3/issues/assignees>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` |
349,549 | def _setState(self, name, value):
"private wrapper around C{self.db.state.setState}"
d = self.getObjectId()
@d.addCallback
def set(objectid):
return self.db.state.setState(objectid, name, value)
return d | private wrapper around C{self.db.state.setState} |
349,550 | def run(*args, **kwargs):
*****
puppet = _Puppet()
buildargs = ()
for arg in range(len(args)):
if args[arg] in [, ]:
puppet.subcmd = args[arg]
else:
buildargs += (args[arg],)
puppet.arguments(buildargs)
puppet.kwargs.... | Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword arguments.
Tags are specified by a t... |
349,551 | def autodetect(self):
for device_type, autodetect_dict in SSH_MAPPER_BASE.items():
tmp_dict = autodetect_dict.copy()
call_method = tmp_dict.pop("dispatch")
autodetect_method = getattr(self, call_method)
accuracy = autodetect_method(**tmp_dict)
... | Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE
Returns
-------
best_match : str or None
The device type that is currently the best to use to interact with the device |
349,552 | def _set_lsp_frr(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=lsp_frr.lsp_frr, is_container=, presence=True, yang_name="lsp-frr", rest_name="frr", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensi... | Setter method for lsp_frr, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_lsp_frr is considered as a private
method. Backends looking to populate this variable should
do so via c... |
349,553 | def content_edge_check(self, url):
prefixes = ["http://", "https://"]
for prefix in prefixes:
if url.startswith(prefix):
url = url[len(prefix):]
break
content = self._fetch("/content/edge_check/%s" % url)
return content | Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server. |
349,554 | def extract(self, document, context=None):
if context:
self.selector_handler.context = context
return self._extract(self.parselet_tree, document) | Extract values as a dict object following the structure
of the Parsley script (recursive)
:param document: lxml-parsed document
:param context: user-supplied context that will be passed to custom XPath extensions (as first argument)
:rtype: Python *dict* object with mapped extracted con... |
349,555 | def fsroot(self):
if self.osname == :
return .format(
self._handler.inspect_get_drive_mappings(self._root)[0][0])
else:
return self._handler.inspect_get_mountpoints(self._root)[0][0] | Returns the file system root. |
349,556 | def get_run_number():
try:
f = open(os.path.join(os.getenv(, "."), ), )
num = int(f.read())
f.close()
except Exception:
num = 1
f = open(os.path.join(os.getenv(, "."), ), )
f.write(str(num + 1))
f.close()
return num | Get a run number for this execution of the model system, for
identifying the output hdf5 files).
Returns
-------
The integer number for this run of the model system. |
349,557 | def from_molfile(cls, molfile, data=None):
if not data:
data = OrderedDict()
if not isinstance(molfile, Molfile):
raise ValueError(.format(type(molfile)))
if not isinstance(data, dict):
raise ValueError(.format(type(data)))
sdfile = cls()
... | Construct new ``SDfile`` object from ``Molfile`` object.
:param molfile: ``Molfile`` object.
:type molfile: :class:`~ctfile.ctfile.Molfile`.
:return: ``SDfile`` object.
:rtype: :class:`~ctfile.ctfile.SDfile`. |
349,558 | def _set_interface_reverse_metric(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=interface_reverse_metric.interface_reverse_metric, is_container=, presence=True, yang_name="interface-reverse-metric", rest_name="reverse-metric", parent=self, path_help... | Setter method for interface_reverse_metric, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_reverse_metric (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_reverse_metric is considered as a private
method. Backen... |
349,559 | def returner(ret):
_options = _get_options(ret)
webhook = _options.get(, None)
show_tasks = _options.get()
author_icon = _options.get()
if not webhook or webhook is :
log.error(, __virtualname__)
return
report = _generate_report(ret, show_tasks)
if report.get():
... | Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post |
349,560 | def ServiceWorker_deliverPushMessage(self, origin, registrationId, data):
assert isinstance(origin, (str,)
), "Argument must be of type str. Received type: " % type(
origin)
assert isinstance(registrationId, (str,)
), "Argument must be of type str. Received type: " % type(
registrationI... | Function path: ServiceWorker.deliverPushMessage
Domain: ServiceWorker
Method name: deliverPushMessage
Parameters:
Required arguments:
'origin' (type: string) -> No description
'registrationId' (type: string) -> No description
'data' (type: string) -> No description
No return value. |
349,561 | def orphan_instance(self, rval: RawValue) -> "ObjectMember":
val = self.from_raw(rval)
return ObjectMember(self.iname(), {}, val, None, self, datetime.now()) | Return an isolated instance of the receiver.
Args:
rval: Raw value to be used for the returned instance. |
349,562 | def get_value(self, name, data):
if name in data:
return data.get(name)
if self.default:
if callable(self.default):
return self.default()
return self.default
return None | Get the value of this field from the data.
If there is a problem with the data, raise ValidationError.
:param name: Name of this field (to retrieve from data).
:param data: Dictionary of data for all fields.
:raises: ValidationError
:return: The value of this field.
:rty... |
349,563 | def get_type(self, name):
if name.lower() == :
return FilesystemOnionService
return type(self.parsers[name]) | return the type of a config key.
:param: name the key
FIXME can we do something more-clever than this for client
code to determine what sort of thing a key is? |
349,564 | def wall_time_str(self, wall_time):
days = int(wall_time // 1440)
hours = int((wall_time - days * 1440) // 60)
minutes = int(math.floor(wall_time - days * 1440 - hours * 60))
seconds = int((wall_time - math.floor(wall_time)) * 60)
return "{}-{:0>2}:{:0>2}:{:0>2}".format(... | Returns the wall time in the format required for the sbatch script |
349,565 | def transformer_tall_train_uniencdec():
hparams = transformer_tall()
hparams.max_input_seq_length = 750
hparams.max_target_seq_length = 100
hparams.optimizer = "true_adam"
hparams.learning_rate_schedule = ("linear_warmup*constant*cosdecay")
hparams.learning_rate_decay_steps = 150000
hparams.learning_ra... | Train CNN/DM with a unidirectional encoder and decoder. |
349,566 | def get_weights_from_kmodel(kmodel):
layers_with_weights = [layer for layer in kmodel.layers if layer.weights]
bweights = []
for klayer in layers_with_weights:
bws = WeightsConverter.get_bigdl_weights_from_klayer(klayer)
for w in bws:
... | Convert kmodel's weights to bigdl format.
We are supposing the order is the same as the execution order.
:param kmodel: keras model
:return: list of ndarray |
349,567 | def find1(self, kw: YangIdentifier, arg: str = None,
pref: YangIdentifier = None,
required: bool = False) -> Optional["Statement"]:
for sub in self.substatements:
if (sub.keyword == kw and sub.prefix == pref and
(arg is None or sub.argument ==... | Return first substatement with the given parameters.
Args:
kw: Statement keyword (local part for extensions).
arg: Argument (all arguments will match if ``None``).
pref: Keyword prefix (``None`` for built-in statements).
required: Should an exception be raised on... |
349,568 | def clean_parameters(self, params):
return {k: v for k, v in params.items() if k in self.adapter.facets} | Only keep known parameters |
349,569 | def main():
options = optionsParser().parse_args()
params = getSelectionParams(options)
if options.list or options.details:
specifiedMaps = filterMapNames(
options.mapname,
records = filterMapAttrs(**params),
excludeRegex=options.exclude,
closest... | PURPOSE: command-line interface for map information |
349,570 | def qstring(option):
if (re.match(NODE_ATTR_RE, option) is None and
re.match(CHEF_CONST_RE, option) is None):
return "" % option
else:
return option | Custom quoting method for jinja. |
349,571 | def duration(self):
try:
start, end = self.hmget(, )
return parse(end) - parse(start)
except:
return None | If the start and end times of the job are defined, return a timedelta,
else return None |
349,572 | def frommembers(cls, members=()):
return cls.fromint(sum(map(cls._map.__getitem__, set(members)))) | Create a set from an iterable of members. |
349,573 | def cat_core(list_of_columns, sep):
list_with_sep = [sep] * (2 * len(list_of_columns) - 1)
list_with_sep[::2] = list_of_columns
return np.sum(list_with_sep, axis=0) | Auxiliary function for :meth:`str.cat`
Parameters
----------
list_of_columns : list of numpy arrays
List of arrays to be concatenated with sep;
these arrays may not contain NaNs!
sep : string
The separator string for concatenating the columns
Returns
-------
nd.arra... |
349,574 | def _set_cfp2(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=cfp2.cfp2, is_container=, presence=False, yang_name="cfp2", rest_name="cfp2", parent=self, choice=(u, u), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, e... | Setter method for cfp2, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/cfp2 (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cfp2 is considered as a private
method. Backends looking to populate this variable should
do so... |
349,575 | def render3d(self,view=None):
for actor in self.actors.values():
actor.render(view) | Renders the world in 3d-mode.
If you want to render custom terrain, you may override this method. Be careful that you still call the original method or else actors may not be rendered. |
349,576 | def start_and_end_of_reference_axis(chains):
coords = [numpy.array(chains[0].primitive.coordinates)]
orient_vector = polypeptide_vector(chains[0])
for i, c in enumerate(chains[1:]):
if is_acute(polypeptide_vector(c), orient_vector):
coords.append(numpy.array(c.primitive.coordin... | Get start and end coordinates that approximate the reference axis for a collection of chains
(not necessarily all the same length).
Parameters
----------
chains : [Polypeptide]
Returns
-------
start, end : numpy.array
3D start and end coordinates for defining the reference axis. |
349,577 | def create_legend(info, c, option="clean", use_index=False):
logging.debug(" - creating legends")
mass, loading, label = info.loc[c, ["masses", "loadings", "labels"]]
if use_index or not label:
label = c.split("_")
label = "_".join(label[1:])
if option == "clean":
retu... | creating more informative legends |
349,578 | def refresh_cache(self, if_want_update=False):
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update() | Update all threads currently stored in our cache. |
349,579 | def maybeStartBuildsOn(self, new_builders):
if not self.running:
return
d = self._maybeStartBuildsOn(new_builders)
self._pendingMSBOCalls.append(d)
try:
yield d
except Exception as e:
log.err(e, "while starting builds on {0}".forma... | Try to start any builds that can be started right now. This function
returns immediately, and promises to trigger those builders
eventually.
@param new_builders: names of new builders that should be given the
opportunity to check for new requests. |
349,580 | def pythonize(line, fn=, subdir=):
global array_seen, nl, sd
if in line:
return
if in line:
return
line = line.strip()
if in line and not line.startswith():
array_seen = True
line = re.sub(, , line)
if line and re.search(r, line):
l... | Convert a line of BMPM code from PHP to Python.
Parameters
----------
line : str
A line of code
fn : str
A filename
subdir : str
The file's subdirectory
Returns
-------
The code in Python |
349,581 | def quaternion_from_axis_angle(v):
theta = np.linalg.norm(v)
if theta > 0:
v = v / np.linalg.norm(v)
ax, ay, az = v
qx = ax * np.sin(0.5 * theta)
qy = ay * np.sin(0.5 * theta)
qz = az * np.sin(0.5 * theta)
qw = np.cos(0.5 * theta)
... | Convert axis-angle representation to a quaternion vector.
Parameters
----------
v : :obj:`numpy.ndarray` of float
An axis-angle representation.
Returns
-------
:obj:`numpy.ndarray` of float
A quaternion vector from the axis-angle vector. |
349,582 | def reverse_action(self, action):
FUNCTIONS = actions.FUNCTIONS
aif = self._agent_interface_format
def func_call_ability(ability_id, cmd_type, *args):
if ability_id not in actions.ABILITY_IDS:
logging.warning("Unknown ability_id: %s. This is probably dance or "
... | Transform an SC2-style action into an agent-style action.
This should be the inverse of `transform_action`.
Args:
action: a `sc_pb.Action` to be transformed.
Returns:
A corresponding `actions.FunctionCall`.
Raises:
ValueError: if it doesn't know how to transform this action. |
349,583 | def pre_save(cls, sender, instance, *args, **kwargs):
instance.constant_contact_id = str(instance.data[]) | Pull constant_contact_id out of data. |
349,584 | def reset_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> int:
attempts = filter_user_attempts(request, credentials)
count, _ = attempts.delete()
log.info(, count)
return count | Reset all user attempts that match the given request and credentials. |
349,585 | def create_channel(self, name, traces=None,
main=False, kpi=False, kpiTrace=0, max_optimization=True,
type=JobChannel.NUMBER,
xaxis=None, yaxis=None, layout=None):
return JobChannel(self, name, traces, main, kpi, kpiTrace, max_optimiz... | :param name: str
:param traces: None|list : per default create a trace based on "name".
:param main: bool : whether this channel is visible in the job list as column for better comparison.
:param kpi: bool : whether this channel is the KPI (key performance indicator).
... |
349,586 | def _convert_angle_to_pypot(angle, joint, **kwargs):
angle_deg = (angle * 180 / np.pi)
if joint["orientation-convention"] == "indirect":
angle_deg = -1 * angle_deg
if joint["name"].startswith("l_shoulder_x"):
angle_deg = -1 * angle_deg
angle_pypot = angle_deg - joint["offset... | Converts an angle to a PyPot-compatible format |
349,587 | def clean_build(self, arch=None):
if arch is None:
base_dir = join(self.ctx.build_dir, , self.name)
else:
base_dir = self.get_build_container_dir(arch)
dirs = glob.glob(base_dir + )
if exists(base_dir):
dirs.append(base_dir)
if not dir... | Deletes all the build information of the recipe.
If arch is not None, only this arch dir is deleted. Otherwise
(the default) all builds for all archs are deleted.
By default, this just deletes the main build dir. If the
recipe has e.g. object files biglinked, or .so files stored
... |
349,588 | def tshift(self, periods=1, freq=None, axis=0):
index = self._get_axis(axis)
if freq is None:
freq = getattr(index, , None)
if freq is None:
freq = getattr(index, , None)
if freq is None:
msg =
raise ValueError(msg)
if... | Shift the time index, using the index's frequency if available.
Parameters
----------
periods : int
Number of periods to move, can be positive or negative
freq : DateOffset, timedelta, or time rule string, default None
Increment to use from the tseries module or ... |
349,589 | def cli(env, group_id, name, description):
mgr = SoftLayer.NetworkManager(env.client)
data = {}
if name:
data[] = name
if description:
data[] = description
if not mgr.edit_securitygroup(group_id, **data):
raise exceptions.CLIAbort("Failed to edit security group") | Edit details of a security group. |
349,590 | def send(self, to, method, body=None):
self._assert_bound()
self._context.send(self.pid, to, method, body) | Send a message to another process.
Sending messages is done asynchronously and is not guaranteed to succeed.
Returns immediately.
:param to: The pid of the process to send a message.
:type to: :class:`PID`
:param method: The method/mailbox name of the remote method.
:type method: ``str``
... |
349,591 | def mergeWithLabels(json, firstField, firstFieldLabel, secondField, secondFieldLabel):
merged = []
for i in range(0, len(json[firstField])):
merged.append({ firstFieldLabel : json[firstField][i],
secondFieldLabel : json[secondField][i] })
return merged | merge two fields of a json into an array of { firstFieldLabel : firstFieldLabel, secondFieldLabel : secondField } |
349,592 | def download_session_video(self, scenario_name, timeout=5):
if (self.driver_wrapper.get_driver_platform().lower() != or
not self.driver_wrapper.config.getboolean_optional(, )):
return
path_file = os.path.join(self.videos_directory, % (scenario_name, MP4_E... | download the execution video file if the scenario fails or the video is enabled,
renaming the file to scenario name and removing the video file in the server.
GGR request: http://<username>:<password>@<ggr_host>:<ggr_port>/video/<session_id>
selenoid request: http://<username>:<password>@<g... |
349,593 | def all_events(cls):
all_evts = set()
for cls, evts in cls.__all_events__.items():
all_evts.update(evts)
return all_evts | Return all events that all subclasses have so far registered to publish. |
349,594 | def detectUbuntuPhone(self):
if UAgentInfo.deviceUbuntu in self.__userAgent \
and UAgentInfo.mobile in self.__userAgent:
return True
return False | Return detection of an Ubuntu Mobile OS phone
Detects a phone running the Ubuntu Mobile OS. |
349,595 | def mktemp_file(self):
if not(os.path.exists(self.__dirname)):
logging.debug("Creating directory {}".format(self.__dirname))
os.mkdir(self.__dirname)
elif not(os.path.isdir(self.__dirname)):
raise TempDirIsFileException(
"There is a file calle... | Create a temporary file in the '.faz' directory for
the code to feed to the interpreter. |
349,596 | def register(cls, name, encode, decode):
cls._codecs[name] = cls._codec(encode, decode) | Add a codec to the registry.
Registers a codec with the given `name` (a string) to be used with the
given `encode` and `decode` functions, which take a `bytes` object and
return another one. An existing codec is replaced.
>>> import binascii
>>> CodecReg.register('uu', binasci... |
349,597 | def get_nn_info(self, structure, n):
site = structure[n]
neighs_dists = structure.get_neighbors(site, self.cutoff)
siw = []
if self.get_all_sites == True:
for s, dist in neighs_dists:
w = dist
siw.append({: s,
... | Get all near-neighbor sites as well as the associated image locations
and weights of the site with index n using the closest neighbor
distance-based method.
Args:
structure (Structure): input structure.
n (integer): index of site for which to determine near
... |
349,598 | def signalcommand(func):
def inner(self, *args, **kwargs):
pre_command.send(self.__class__, args=args, kwargs=kwargs)
ret = func(self, *args, **kwargs)
post_command.send(self.__class__, args=args, kwargs=kwargs, outcome=ret)
return ret
return inner | Python decorator for management command handle defs that sends out a pre/post signal. |
349,599 | def chunks(iterable, size=50):
batch = []
for n in iterable:
batch.append(n)
if len(batch) % size == 0:
yield batch
batch = []
if batch:
yield batch | Break an iterable into lists of size |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.