Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
356,400 | def device_id_partition_keygen(request_envelope):
try:
device_id = request_envelope.context.system.device.device_id
return device_id
except AttributeError:
raise PersistenceException("Couldn't retrieve device id from "
"request envelope, for p... | Retrieve device id from request envelope, to use as partition key.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_envelope: ask_sdk_model.RequestEnvelope
:return: Device Id retrieved from request envelope
:rtype: str
:raises: :py:class:`ask_sdk_core.e... |
356,401 | def read(self, size=1):
if self.is_closed_flag:
raise Exception("Unable to read - already closed!")
if self.get_remaining_size() < size:
raise Exception("Unable to read byte buffer - too short remaining data size!")
self.read_count += size
return self.fil... | Read byte buffer with specified size from input file.
Raise exception in two cases:
- File already closed.
- Not enough data to read.
Keyword arguments:
size -- size of buffer to read (default 1) |
356,402 | def compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix=, import_from=):
from PyQt5.QtCore import PYQT_VERSION_STR
try:
uifname = uifile.name
except AttributeError:
uifname = uifile
indenter.indentwidth = indent
pyfile.write(_header % (uifn... | compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.')
Creates a Python module from a Qt Designer .ui file.
uifile is a file name or file-like object containing the .ui file.
pyfile is the file-like object to which the Python code will be written... |
356,403 | def isActiveDashboardOverlay(self, ulOverlayHandle):
fn = self.function_table.isActiveDashboardOverlay
result = fn(ulOverlayHandle)
return result | returns true if the dashboard is visible and the specified overlay is the active system Overlay |
356,404 | def ParseArguments(self):
loggers.ConfigureLogging()
argument_parser = argparse.ArgumentParser(
description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False,
formatter_class=argparse.RawDescriptionHelpFormatter)
self.AddBasicOptions(argument_parser)
helpers_manager.ArgumentHe... | Parses the command line arguments.
Returns:
bool: True if the arguments were successfully parsed. |
356,405 | def response(credentials, password, request):
response = None
algorithm = credentials.get()
HA1_value = HA1(
credentials.get(),
credentials.get(),
password,
algorithm
)
HA2_value = HA2(credentials, request, algorithm)
if credentials.get() is None:
res... | Compile digest auth response
If the qop directive's value is "auth" or "auth-int" , then compute the response as follows:
RESPONSE = MD5(HA1:nonce:nonceCount:clienNonce:qop:HA2)
Else if the qop directive is unspecified, then compute the response as follows:
RESPONSE = MD5(HA1:nonce:HA2)
Argu... |
356,406 | def open(self):
handle = libusb1.libusb_device_handle_p()
mayRaiseUSBError(libusb1.libusb_open(self.device_p, byref(handle)))
result = USBDeviceHandle(self.__context, handle, self)
self.__close_set.add(result)
return result | Open device.
Returns an USBDeviceHandle instance. |
356,407 | def create_dashboards(resource_root, dashboard_list):
return call(resource_root.post, DASHBOARDS_PATH, ApiDashboard, \
ret_is_list=True, data=dashboard_list) | Creates the list of dashboards. If any of the dashboards already exist
this whole command will fail and no dashboards will be created.
@since: API v6
@return: The list of dashboards created. |
356,408 | def get_active_lineage():
lin_str =
for active_timer in f.timer_stack:
lin_str += "{}-->".format(active_timer.name)
try:
return lin_str[:-3]
except IndexError:
pass | Query the lineage of the current timer level. Provides only timer names,
not stamp names (as these have not been decided yet!).
Returns:
str: Formatted sequence of timer names in one string. |
356,409 | def cythonize(*args, **kwargs):
t write Cython extension,
you wont install Cython.
'
global cythonize
from Cython.Build import cythonize
return cythonize(*args, **kwargs) | dirty hack, only import cythonize at the time you use it.
if you don't write Cython extension,
you won't fail even if you don't install Cython. |
356,410 | def fetch(self, category=CATEGORY_EVENT, from_date=DEFAULT_DATETIME, to_date=None,
filter_classified=False):
if not from_date:
from_date = DEFAULT_DATETIME
from_date = datetime_to_utc(from_date)
kwargs = {"from_date": from_date, "to_date": to_date}
it... | Fetch the events from the server.
This method fetches those events of a group stored on the server
that were updated since the given date. Data comments and rsvps
are included within each event.
:param category: the category of items to fetch
:param from_date: obtain events upd... |
356,411 | def iter_window(iterable, size=2, step=1, wrap=False):
r
iter_list = it.tee(iterable, size)
if wrap:
iter_list = [iter_list[0]] + list(map(it.cycle, iter_list[1:]))
try:
for count, iter_ in enumerate(iter_list[1:], start=1):
for _ in range(count):
... | r"""
iterates through iterable with a window size
generalizeation of itertwo
Args:
iterable (iter): an iterable sequence
size (int): window size (default = 2)
wrap (bool): wraparound (default = False)
Returns:
iter: returns windows in a sequence
CommandLine:
... |
356,412 | def setdefault(self, key, default=None):
if key in self:
return self[key]
else:
self._setitem(key, default)
self._list_add(key)
return default | If *key* is in the dictionary, return its value. If not, insert *key*
with a value of *default* and return *default*. *default* defaults to
``None``. |
356,413 | def _delete_compressed(collection_name, spec, opts, flags, ctx):
op_delete, max_bson_size = _delete(collection_name, spec, opts, flags)
rid, msg = _compress(2006, op_delete, ctx)
return rid, msg, max_bson_size | Internal compressed unacknowledged delete message helper. |
356,414 | def asarray(arraylike, strict=True):
if isinstance(arraylike, np.ndarray):
return arraylike
elif isinstance(arraylike, list):
return np.asarray(arraylike, dtype=object)
elif not isinstance(arraylike, np.ndarray) and isinstance(arraylike, arraylike_types):
return arraylike.values... | Converts arraylike objects to NumPy ndarray types. Errors if
object is not arraylike and strict option is enabled. |
356,415 | def _import_classes(self, class_names):
classes = []
for name in class_names:
classes.extend(self._import_class_or_module(name))
return classes | Import a list of classes. |
356,416 | def _populate_cache(platform, pkg_cache, mount_dir):
if not pkg_cache:
return
if not os.path.isdir(pkg_cache):
return
if platform == :
cache_dir = .format(mount_dir)
__salt__[](cache_dir, , , )
__salt__[](pkg_cache, cache_dir, recurse=True, remove_existing=True) | If a ``pkg_cache`` directory is specified, then use it to populate the
disk image. |
356,417 | def get_top_artists(self, limit=None, cacheable=True):
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopArtists", params).execute(cacheable)
return _extract_top_artists(doc, self) | Returns the most played artists as a sequence of TopItem objects. |
356,418 | def calc_pident_ignore_gaps(a, b):
m = 0
mm = 0
for A, B in zip(list(a), list(b)):
if A == or A == or B == or B == :
continue
if A == B:
m += 1
else:
mm += 1
try:
return float(float(m)/float((m + mm))) * 100
except:
... | calculate percent identity |
356,419 | def parse_chain(*args):
items = []
for parser in args:
for element in parser(*items):
if element is None:
yield None
else:
items.append(element)
break
yield tuple(items) | Creates a new parser that executes the passed parsers (args) with the
previous results and yields a tuple of the results.
>>> list(parse_chain(lambda: (None, 1), lambda one: (None, 2)))
[None, None, (1, 2)]
@param args: parsers
@returns: parser |
356,420 | def get_polygons(self, by_spec=False, depth=None):
if not isinstance(self.ref_cell, Cell):
return dict() if by_spec else []
if self.rotation is not None:
ct = numpy.cos(self.rotation * numpy.pi / 180.0)
st = numpy.sin(self.rotation * numpy.pi / 180.0)
... | Returns a list of polygons created by this reference.
Parameters
----------
by_spec : bool
If ``True``, the return value is a dictionary with the
polygons of each individual pair (layer, datatype).
depth : integer or ``None``
If not ``None``, defines ... |
356,421 | def guided_registration(request, page_number=None):
PAGE_PROFILE = 1
PAGE_TICKET = 2
PAGE_PRODUCTS = 3
PAGE_PRODUCTS_MAX = 4
TOTAL_PAGES = 4
ticket_category = inventory.Category.objects.get(
id=settings.TICKET_PRODUCT_CATEGORY
)
cart = CartController.for_user(request.user)... | Goes through the registration process in order, making sure user sees
all valid categories.
The user must be logged in to see this view.
Parameter:
page_number:
1) Profile form (and e-mail address?)
2) Ticket type
3) Remaining products
4) Mark regist... |
356,422 | def to_credentials(arg):
keysecret:mykey:mysecret
if pimms.is_str(arg):
try: return load_credentials(arg)
except Exception: pass
try: return str_to_credentials(arg)
except Exception:
raise ValueError(
% arg)
elif pimms.is_map(arg) and... | to_credentials(arg) converts arg into a pair (key, secret) if arg can be coerced into such a
pair and otherwise raises an error.
Possible inputs include:
* A tuple (key, secret)
* A mapping with the keys 'key' and 'secret'
* The name of a file that can load credentials via the load_cred... |
356,423 | def status(self):
counts = {}
for bucket in self.buckets:
for x in bucket:
if not x in counts:
counts[x] = 0
counts[x] += bucket[x]
ret = ""
mtypes = counts.keys()
mtypes.sort()
for mtype in mtypes:... | returns rates |
356,424 | def cost_sampling(X, y, cost_mat, method=, oversampling_norm=0.1, max_wc=97.5):
cost_mis = cost_mat[:, 0]
cost_mis[y == 1] = cost_mat[y == 1, 1]
wc = np.minimum(cost_mis / np.percentile(cost_mis, max_wc), 1)
n_samples = X.shape[0]
filter_ = list(range(n_samples))
if met... | Cost-proportionate sampling.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y : array-like of shape = [n_samples]
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
Cost matrix ... |
356,425 | def get_signature_request(self, signature_request_id, ux_version=None):
request = self._get_request()
parameters = None
if ux_version is not None:
parameters = {
: ux_version
}
return request.get(self.SIGNATURE_REQUEST_INFO_URL + signat... | Get a signature request by its ID
Args:
signature_request_id (str): The id of the SignatureRequest to retrieve
ux_version (int): UX version, either 1 (default) or 2.
Returns:
A SignatureRequest object |
356,426 | def get_entity(self, entity_id, at=None):
if self._snapshot_strategy is not None:
snapshot = self._snapshot_strategy.get_snapshot(entity_id, lte=at)
else:
snapshot = None
if snapshot is None:
initial_state = None
... | Returns entity with given ID, optionally until position. |
356,427 | def AddGroupMemberships(self):
self.groups = {g.name: self._Members(g) for g in itervalues(self.groups)}
for g in itervalues(self.groups):
for user in g.members:
membership = self.memberships.setdefault(user, set())
membership.add(g.gid)
for user in itervalues(self.entry... | Adds aggregate group membership from group, gshadow and passwd. |
356,428 | def _declare_consumer(self, consumer, nowait=False):
if consumer.queue not in self._open_consumers:
callback = consumer.callbacks and \
consumer._receive_callback or self._receive_callback
self.backend.declare_consumer(queue=consumer.que... | Declare consumer so messages can be received from it using
:meth:`iterconsume`. |
356,429 | def create_logical_volume(lv_name, volume_group, size=None):
if size:
check_call([
,
,
,
.format(size),
, lv_name, volume_group
])
else:
check_call([
,
,
,
,
... | Create a new logical volume in an existing volume group
:param lv_name: str: name of logical volume to be created.
:param volume_group: str: Name of volume group to use for the new volume.
:param size: str: Size of logical volume to create (100% if not supplied)
:raises subprocess.CalledProcessError: i... |
356,430 | def getStuckRelayCheckEnabled(self):
command =
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0010) | Returns True if enabled, False if disabled |
356,431 | def create_installer(self, rpm_py_version, **kwargs):
return FedoraInstaller(rpm_py_version, self.python, self.rpm, **kwargs) | Create Installer object. |
356,432 | def pre_process_code_block(block):
if in block and block[]:
indent = r + block[]
block[] = re.sub(indent, , block[],
flags=re.MULTILINE) | Preprocess the content of a code block, modifying the code
block in place.
Just dedents indented code. |
356,433 | def _get_longest(value_lst: List) -> List:
value_lst.sort()
result = []
pivot = value_lst[0]
start, end = pivot[0], pivot[1]
pivot_e = end
pivot_s = start
for idx, (s, e, v, rule_id, _) in enumerate(value_lst):
if s == pivot_s and pivot_e < e... | Get the longest match for overlap
Args:
value_lst: List
Returns: List |
356,434 | def password_generator(length):
return .join(random.choice(string.ascii_lowercase + string.digits)
for _ in range(length)) | Generate a random password.
:param length: integer. |
356,435 | def on_get(self, req, resp, **kwargs):
return super().on_get(
req, resp, handler=self._retrieve, **kwargs
) | Respond on GET requests using ``self.retrieve()`` handler. |
356,436 | def network_create(request, **kwargs):
LOG.debug("network_create(): kwargs = %s", kwargs)
if not in kwargs:
kwargs[] = request.user.project_id
body = {: kwargs}
network = neutronclient(request).create_network(body=body).get()
return Network(network) | Create a network object.
:param request: request context
:param tenant_id: (optional) tenant id of the network created
:param name: (optional) name of the network created
:returns: Network object |
356,437 | def _repr_html_(self):
nbreset = f
resources = .join(map(str, self.resources))
return f | Jupyter Notebook hook to print this element as HTML. |
356,438 | def parse_pandoc(self, attrs):
id = attrs[0]
classes = attrs[1]
kvs = OrderedDict(attrs[2])
return id, classes, kvs | Read pandoc attributes. |
356,439 | def pesach_dow(self):
jdn = conv.hdate_to_jdn(HebrewDate(self.hdate.year, Months.Nisan, 15))
return (jdn + 1) % 7 + 1 | Return the first day of week for Pesach. |
356,440 | def validate_variable_type(var_name, var_type, value):
if isinstance(var_type, CFNType):
value = CFNParameter(name=var_name, value=value)
elif isinstance(var_type, TroposphereType):
try:
value = var_type.create(value)
except Exception as exc:
name = "{}.crea... | Ensures the value is the correct variable type.
Args:
var_name (str): The name of the defined variable on a blueprint.
var_type (type): The type that the value should be.
value (obj): The object representing the value provided for the
variable
Returns:
object: Retur... |
356,441 | def packages(self):
queue_list = []
for read in self.queued.splitlines():
read = read.lstrip()
if not read.startswith("
queue_list.append(read.replace("\n", ""))
return queue_list | Return queue list from /var/lib/queue/queue_list
file. |
356,442 | def walk_dict(d):
nested_keys = tuple(k for k in list(d.keys()) if isinstance(d[k], dict))
items = tuple((k, d[k]) for k in list(d.keys()) if k not in nested_keys)
yield (, [(k, d[k]) for k in nested_keys], items)
for k in nested_keys:
for res in walk_dict(d[k]):
... | Walk a tree (nested dicts).
For each 'path', or dict, in the tree, returns a 3-tuple containing:
(path, sub-dicts, values)
where:
* path is the path to the dict
* sub-dicts is a tuple of (key,dict) pairs for each sub-dict in this dict
* values is a tuple of (key,value) pairs for each (non-dict... |
356,443 | def alloc(subseqs):
print()
lines = Lines()
lines.add(1, )
for seq in subseqs:
lines.add(2, % seq.name)
lines.add(3, % seq.name)
lines.add(3,
% seq.name)
return lines | Allocate memory for 1-dimensional link sequences. |
356,444 | def find_changelog(session, repo_url, deep=True):
logger.debug("Trying to find changelog on repo {}".format(repo_url))
resp = session.get(repo_url)
if resp.status_code == 200:
if deep and not found:
for link in links:
sublink = False
... | Tries to find changelogs on the given `repo_url`.
:param session: requests Session instance
:param repo_url: str, URL to the repo
:param deep: bool, deep search
:return: str, URL to the raw changelog content |
356,445 | def to_header(self):
if self.star_tag:
return "*"
return ", ".join(
[ % x for x in self._strong] + [ % x for x in self._weak]
) | Convert the etags set into a HTTP header string. |
356,446 | def _setup_global_state_for_execution(laser_evm, transaction) -> None:
global_state = transaction.initial_global_state()
global_state.transaction_stack.append((transaction, None))
new_node = Node(
global_state.environment.active_account.contract_name,
function_name=global_state.en... | Sets up global state and cfg for a transactions execution.
:param laser_evm:
:param transaction: |
356,447 | def create_or_update(sysmeta_pyxb, sciobj_url=None):
pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier)
if sciobj_url is None:
sciobj_url = d1_gmn.app.sciobj_store.get_rel_sciobj_file_url_by_pid(pid)
try:
sci_model = d1_gmn.app.model_util.get_sci_model(pid)
except d1_g... | Create or update database representation of a System Metadata object and closely
related internal state.
- If ``sciobj_url`` is not passed on create, storage in the internal sciobj store
is assumed
- If ``sciobj_url`` is passed on create, it can reference a location in the
internal sciobj store... |
356,448 | def intercept_service(self, continuation, handler_call_details):
rpc_method_handler = self._get_rpc_handler(handler_call_details)
if rpc_method_handler.response_streaming:
if self._wrapped.is_streaming:
return self._wrapped.intercept_service(
... | Intercepts incoming RPCs before handing them over to a handler
See `grpc.ServerInterceptor.intercept_service`. |
356,449 | def user_delete(auth=None, **kwargs):
***
cloud = get_openstack_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_user(**kwargs) | Delete a user
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_delete name=user1
salt '*' keystoneng.user_delete name=user2 domain_id=b62e76fbeeff4e8fb77073f591cf211e
salt '*' keystoneng.user_delete name=a42cbbfa1e894e839fd0f584d22e321f |
356,450 | def radec2sky(ra, dec):
try:
sky = np.array(list(zip(ra, dec)))
except TypeError:
sky = np.array([(ra, dec)])
return sky | Convert [ra], [dec] to [(ra[0], dec[0]),....]
and also ra,dec to [(ra,dec)] if ra/dec are not iterable
Parameters
----------
ra, dec : float or iterable
Sky coordinates
Returns
-------
sky : numpy.array
array of (ra,dec) coordinates. |
356,451 | def execd_submodule_paths(command, execd_dir=None):
for module_path in execd_module_paths(execd_dir):
path = os.path.join(module_path, command)
if os.access(path, os.X_OK) and os.path.isfile(path):
yield path | Generate a list of full paths to the specified command within exec_dir. |
356,452 | def iter_gists(self, username=None, number=-1, etag=None):
if username:
url = self._build_url(, username, )
else:
url = self._build_url()
return self._iter(int(number), url, Gist, etag=etag) | If no username is specified, GET /gists, otherwise GET
/users/:username/gists
:param str login: (optional), login of the user to check
:param int number: (optional), number of gists to return. Default: -1
returns all available gists
:param str etag: (optional), ETag from a p... |
356,453 | def unfold(tensor, mode):
return np.moveaxis(tensor, mode, 0).reshape((tensor.shape[mode], -1)) | Returns the mode-`mode` unfolding of `tensor`.
Parameters
----------
tensor : ndarray
mode : int
Returns
-------
ndarray
unfolded_tensor of shape ``(tensor.shape[mode], -1)``
Author
------
Jean Kossaifi <https://github.com/tensorly> |
356,454 | def _read_arg(arg):
if arg is None:
arg_out = arg
else:
if len(arg) == 1 and os.path.exists(arg[0]):
arg_out = grp.read(arg[0])
else:
arg_out = arg
assert isinstance(arg_out, list), "arg_out must be a list."
assert ty... | If arg is a list with 1 element that corresponds to a valid file path, use
set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.
Args:
arg (list or None)
Returns:
arg_out (list or None) |
356,455 | def check_calendar_dates(
feed: "Feed", *, as_df: bool = False, include_warnings: bool = False
) -> List:
table = "calendar_dates"
problems = []
if feed.calendar_dates is None:
return problems
f = feed.calendar_dates.copy()
problems = check_for_required_columns(problems, tabl... | Analog of :func:`check_agency` for ``feed.calendar_dates``. |
356,456 | def get_in(keys, coll, default=None, no_default=False):
try:
return reduce(operator.getitem, keys, coll)
except (KeyError, IndexError, TypeError):
if no_default:
raise
return default | NB: This is a straight copy of the get_in implementation found in
the toolz library (https://github.com/pytoolz/toolz/). It works
with persistent data structures as well as the corresponding
datastructures from the stdlib.
Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys.
If c... |
356,457 | def _cell_magic(line, query):
args = magic_arguments.parse_argstring(_cell_magic, line)
params = []
if args.params is not None:
try:
params = _helpers.to_query_parameters(
ast.literal_eval("".join(args.params))
)
except Exception:
rai... | Underlying function for bigquery cell magic
Note:
This function contains the underlying logic for the 'bigquery' cell
magic. This function is not meant to be called directly.
Args:
line (str): "%%bigquery" followed by arguments as required
query (str): SQL query to run
Ret... |
356,458 | def _get_cgroup_from_proc(self, cgroup, pid, filename):
params = {
"file": filename,
}
return DockerUtil.find_cgroup_from_proc(self._mountpoints, pid, cgroup, self.docker_util._docker_root) % (params) | Find a specific cgroup file, containing metrics to extract. |
356,459 | def call_good_cb(self):
with LiveExecution.lock:
if self.good_cb and not self.good_cb():
self.good_cb = None | If good_cb returns True then keep it
:return: |
356,460 | def GetDataStreamByPathSpec(self, path_spec):
file_entry = self.GetFileEntryByPathSpec(path_spec)
if not file_entry:
return None
data_stream_name = getattr(path_spec, , None)
return file_entry.GetDataStream(data_stream_name) | Retrieves a data stream for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
DataStream: a data stream or None if not available. |
356,461 | def index():
logs = Table(, metadata, autoload=True)
criticals = logs.select().where(logs.c.log_level == 50).order_by(
, )
criticals_count = logs.count(logs.c.log_level == 50)
errors = logs.select().where(logs.c.log_level == 40).order_by(
, )
errors_count = logs.count(l... | Base testsuite view. |
356,462 | def datasets_upload_file(self, file_name, content_length, last_modified_date_utc, **kwargs):
kwargs[] = True
if kwargs.get():
return self.datasets_upload_file_with_http_info(file_name, content_length, last_modified_date_utc, **kwargs)
else:
(data) = self.data... | Get URL and token to start uploading a data file # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_upload_file(file_name, content_length, last_modified_date_utc, async_req=True)
... |
356,463 | def stem(self):
name = self.name
i = name.rfind()
if 0 < i < len(name) - 1:
return name[:i]
else:
return name | The final path component, minus its last suffix. |
356,464 | def get_sections(self, s, base, sections=[
, , ]):
return super(PsyplotDocstringProcessor, self).get_sections(s, base,
sections) | Extract the specified sections out of the given string
The same as the :meth:`docrep.DocstringProcessor.get_sections` method
but uses the ``'Possible types'`` section by default, too
Parameters
----------
%(DocstringProcessor.get_sections.parameters)s
Returns
-... |
356,465 | def frame(I=None, second=5, saveable=True, name=, cmap=None, fig_idx=12836):
import matplotlib.pyplot as plt
if saveable is False:
plt.ion()
plt.figure(fig_idx)
if len(I.shape) and I.shape[-1] == 1:
I = I[:, :, 0]
plt.imshow(I, cmap)
plt.title(name)
if s... | Display a frame. Make sure OpenAI Gym render() is disable before using it.
Parameters
----------
I : numpy.array
The image.
second : int
The display second(s) for the image(s), if saveable is False.
saveable : boolean
Save or plot the figure.
name : str
A name to... |
356,466 | def make_data():
T = 5
K = [1]
P = [1,2,3,4,5]
_,f,g,c,d,h,UB = multidict({
(1,1): [10, 1, 2, 0, 0.5, 24],
(1,2): [10, 1, 2, 0, 0.5, 24],
(1,3): [10, 1, 2, 0, 0.5, 24],
(1,4): [10, 1, 2, 0, 0.5, 24],
(1,5): [10, 1, 2, 0, 0.5, 24],
(2,1): [10, 1, 2, 0,... | 1..T: set of periods
K: set of resources
P: set of items
f[t,p]: set-up costs
g[t,p]: set-up times
c[t,p]: variable costs
d[t,p]: demand values
h[t,p]: holding costs
a[t,k,p]: amount of resource k for producing product p in period. t
M[t,k]: resource upper bounds
UB[t,p]: upper b... |
356,467 | def bytes_to_c_string(data):
rows = chunked_join(data, 20, 2, , , r + X)
logging.debug(_(), rows)
return .format(rows) | Convert the hexadecimal string in to C-style string. |
356,468 | def edit(id: int, parent: int, alloc: Decimal):
saved = False
app = AppAggregate()
item = app.get(id)
if not item:
raise KeyError("Asset Class with id %s not found.", id)
if parent:
assert parent != id, "Parent can not be set to self."
item.parentid = p... | Edit asset class |
356,469 | def compiler(self, target):
self._check_target(target)
return target.compiler or self._default_compiler | Returns the thrift compiler to use for the given target.
:param target: The target to extract the thrift compiler from.
:type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary`
:returns: The thrift compiler to use.
:rtype: string |
356,470 | def prepare_injection_directions(self):
if hasattr(self, ) and self.pop_injection_directions:
ValueError("Looks like a bug in calling order/logics")
ary = []
if (isinstance(self.adapt_sigma, CMAAdaptSigmaTPA) or
self.opts[]):
ary.append(s... | provide genotypic directions for TPA and selective mirroring,
with no specific length normalization, to be used in the
coming iteration.
Details:
This method is called in the end of `tell`. The result is
assigned to ``self.pop_injection_directions`` and used in
`ask_geno... |
356,471 | def get_assessment_parts_by_item(self, item_id):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
result = collection.find(
dict({: {: [str(item_id)]}},
... | Gets the assessment parts containing the given item.
In plenary mode, the returned list contains all known assessment
parts or an error results. Otherwise, the returned list may
contain only those assessment parts that are accessible through
this session.
arg: item_id (osid.... |
356,472 | def up(self, i):
x = self.heap[i]
while i > 1 and x < self.heap[i // 2]:
self.heap[i] = self.heap[i // 2]
self.rank[self.heap[i // 2]] = i
i //= 2
self.heap[i] = x
self.rank[x] = i | The value of heap[i] has decreased. Maintain heap invariant. |
356,473 | def get_subscribers(obj):
ctype = ContentType.objects.get_for_model(obj)
return Subscription.objects.filter(content_type=ctype, object_id=obj.pk) | Returns the subscribers for a given object.
:param obj: Any object. |
356,474 | def add_options(self):
self.add_bool_option("--reveal",
help="show full announce URL including keys")
self.add_bool_option("--raw",
help="print the metafile's raw content in all detail")
self.add_bool_option("-V", "--skip-validation",
help="show broke... | Add program options. |
356,475 | def get_mode(device_filter):
from .device_filters import IBeaconFilter, EddystoneFilter, BtAddrFilter, EstimoteFilter
if device_filter is None or len(device_filter) == 0:
return ScannerMode.MODE_ALL
mode = ScannerMode.MODE_NONE
for filtr in device_filter:
if isinstance(filtr, IBeac... | Determine which beacons the scanner should look for. |
356,476 | def sub_slots(x,match_fn,path=(),arr=None,match=False,recurse_into_matches=True):
if arr is None: arr=[]
if match and match_fn(x):
arr.append(path)
if not recurse_into_matches:
return arr
if isinstance(x, PathTree):
for attr in x.ATTRS:
val = getattr(x,attr)
if attr in x.VAR... | given a BaseX in x, explore its ATTRS (doing the right thing for VARLEN).
return a list of tree-paths (i.e. tuples) for tree children that match match_fn. The root elt won't match. |
356,477 | def bezout(a, b):
if b == 0:
return (1, 0)
else:
u, v = bezout(b, a % b)
return (v, u - (a // b) * v) | Bezout coefficients for a and b
:param a,b: non-negative integers
:complexity: O(log a + log b) |
356,478 | def simplify_text(text):
if isinstance(text, six.text_type):
if six.PY3:
text = text.translate(text.maketrans("", "", string.punctuation)).lower()
else:
text = six.text_type(text.encode().translate(string.maketrans("", ""), string.punctuation).lower(), )
else:
... | Simplify text to allow comparison.
>>> simplify_text("Awesome Coder wanted at Awesome Company")
'awesome coder wanted at awesome company'
>>> simplify_text("Awesome Coder, wanted at Awesome Company! ")
'awesome coder wanted at awesome company'
>>> simplify_text(u"Awesome Coder, wanted at Awesome ... |
356,479 | def print_col_perc_table(table, row_labels, col_labels):
r1c1, r1c2, r2c1, r2c2 = map(float, table)
col1 = r1c1 + r2c1
col2 = r1c2 + r2c2
blocks = [
(r1c1, col1),
(r1c2, col2),
(r2c1, col1),
(r2c2, col2)]
new_table = []
for cell, row in blocks:
tr... | given a table, print the cols as percentages |
356,480 | def download(self, remotepath = , localpath = ):
subr = self.get_file_info(remotepath)
if const.ENoError == subr:
if in self.__remote_json:
if self.__remote_json[]:
return self.downdir(remotepath, localpath)
else:
return self.downfile(remotepath, localpath)
else:
perr("Malformed path... | Usage: download [remotepath] [localpath] - \
download a remote directory (recursively) / file
remotepath - remote path at Baidu Yun (after app root directory), if not specified, it is set to the root directory at Baidu Yun
localpath - local path. if not specified, it is set to the current directory |
356,481 | def _on_loop_start(self, variables):
for callback in self.callbacks:
if hasattr(callback, ):
self.logs_[str(callback)].append(callback.on_loop_start(**variables)) | performs on-loop-start actions like callbacks
variables contains local namespace variables.
Parameters
---------
variables : dict of available variables
Returns
-------
None |
356,482 | def create_from_flux_points(cls, txtfile):
tab = Table.read(txtfile, format=)
dnde_unit = u.ph / (u.MeV * u.cm ** 2 * u.s)
loge = np.log10(np.array(tab[].to(u.MeV)))
norm = np.array(tab[].to(dnde_unit))
norm_errp = np.array(tab[].to(dnde_unit))
norm_errn = np.ar... | Create a Castro data object from a text file containing a
sequence of differential flux points. |
356,483 | def get_element_dos(self):
el_dos = {}
for site, atom_dos in self.pdos.items():
el = site.specie
for pdos in atom_dos.values():
if el not in el_dos:
el_dos[el] = pdos
else:
el_dos[el] = add_densitie... | Get element projected Dos.
Returns:
dict of {Element: Dos} |
356,484 | def scale_and_shift_cmap(self, scale_pct, shift_pct):
rgbmap = self.get_rgbmap()
rgbmap.scale_and_shift(scale_pct, shift_pct) | Stretch and/or shrink the color map.
See :meth:`ginga.RGBMap.RGBMapper.scale_and_shift`. |
356,485 | def ctcp_unpack_message(info):
verb = info[]
message = info[][1]
infos = []
X_QUOTE =
X_DELIM =
messages = str(message).split(X_DELIM)
for i in range(len(messages)):
msg = messages[i]
new_info = dict(info)
if i % 2 == 0:
... | Given a an input message (privmsg/pubmsg/notice), return events. |
356,486 | def _signal(self, sig, pid=None):
log = self._params.get(, self._discard)
if pid is None:
pids = self.get_pids()
else:
pids = [pid]
for pid in pids:
try:
os.kill(pid, sig)
log.debug("Signalled pid %d with %s", ... | Send a signal to one or all pids associated with this task. Never fails, but logs
signalling faults as warnings. |
356,487 | def set_network(self, machines, local_listen_port=12400,
listen_time_out=120, num_machines=1):
_safe_call(_LIB.LGBM_NetworkInit(c_str(machines),
ctypes.c_int(local_listen_port),
ctypes.c_int(listen_tim... | Set the network configuration.
Parameters
----------
machines : list, set or string
Names of machines.
local_listen_port : int, optional (default=12400)
TCP listen port for local machines.
listen_time_out : int, optional (default=120)
Socket t... |
356,488 | def is_between(self, low, high):
val_type = type(self.val)
self._validate_between_args(val_type, low, high)
if self.val < low or self.val > high:
if val_type is datetime.datetime:
self._err( % (self.val.strftime(), low.strftime(), high.strftime()))
... | Asserts that val is numeric and is between low and high. |
356,489 | def bind(self, __fun, *args, **kwargs):
with self._lock:
if self._running or self._completed or self._cancelled:
raise RuntimeError()
if self._worker:
raise RuntimeError()
self._worker = functools.partial(__fun, *args, **kwargs)
return self | Bind a worker function to the future. This worker function will be
executed when the future is executed. |
356,490 | def get_fields(self):
l = []
for i in self.classes.class_def:
for j in i.get_fields():
l.append(j)
return l | Return all field objects
:rtype: a list of :class:`EncodedField` objects |
356,491 | def tarFile(source):
target = source[0:source.rindex()] +
try:
with tarfile.open(target, "w:gz") as tar_file:
tar_file.add(source, arcname=source[source.startswith("/"):])
__cps_rate__(source, target)
except IOError as e:
logger.error(, source, str(e))
... | Compress file under tar mode
which type more popular use in Unix operating system
when compress failed with return source path
:param source: source file path
:return: zip file path |
356,492 | def run_suite(case, config, summary):
config["name"] = case
timing_data = dict()
model_dir = os.path.join(livvkit.model_dir, config[], case)
bench_dir = os.path.join(livvkit.bench_dir, config[], case)
plot_dir = os.path.join(livvkit.output_dir, "performance", "imgs")
model_cases = functions... | Run the full suite of performance tests |
356,493 | def _do_stack(self, cmd, args):
if not args:
self.__dump_stack()
return
if len(args) > 1:
self.stderr.write(.format(args))
return
try:
depth = int(args[0])
except ValueError:
self.stderr.write("stack: depth ... | \
Manage the shell stack.
stack Display the stack.
stack <depth> Exit to the stack by its depth. |
356,494 | def accept(self):
while 1:
try:
sock, addr = self._sock.accept()
return (type(self)(sock,
keyfile=self.keyfile,
certfile=self.certfile,
server_side=True,
cert_reqs=self.cert_reqs,... | accept a connection attempt from a remote client
returns a two-tuple with the ssl-context-wrapped connection,
and the address of the remote client |
356,495 | def _safe_get(self, revision, key):
if self.has_revision(revision):
return self.raw_answers[revision].get(key)
else:
return None | Get an answer data (vote or rationale) by revision
Args:
revision (int): the revision number for student answer, could be
0 (original) or 1 (revised)
key (str); key for retrieve answer data, could be VOTE_KEY or
RATIONALE_KEY
Returns:
... |
356,496 | def authenticate(username, password):
service = __opts__.get(, )
if isinstance(username, six.text_type):
username = username.encode(__salt_system_encoding__)
if isinstance(password, six.text_type):
password = password.encode(__salt_system_encoding__)
if isinstance(service, six.text... | Returns True if the given username and password authenticate for the
given service. Returns False otherwise
``username``: the username to authenticate
``password``: the password in plain text |
356,497 | def nvmlDeviceClearEccErrorCounts(handle, counterType):
r
fn = _nvmlGetFunctionPointer("nvmlDeviceClearEccErrorCounts")
ret = fn(handle, _nvmlEccCounterType_t(counterType))
_nvmlCheckReturn(ret)
return None | r"""
/**
* Clear the ECC error and other memory error counts for the device.
*
* For Kepler &tm; or newer fully supported devices.
* Only applicable to devices with ECC.
* Requires \a NVML_INFOROM_ECC version 2.0 or higher to clear aggregate location-based ECC counts.
* Requires \a NVM... |
356,498 | def load_all_methods(self):
r
methods = []
Tmins, Tmaxs = [], []
if self.CASRN in zabransky_dict_const_s:
methods.append(ZABRANSKY_SPLINE)
self.Zabransky_spline = zabransky_dict_const_s[self.CASRN]
if self.CASRN in zabransky_dict_const_p:
metho... | r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,
and :obj:`all_methods` as a set of methods for which the data exists for.
Called ... |
356,499 | def declare_consuming(self, exchange_name, routing_key, queue_name, callback):
self.bind_topic_exchange(exchange_name, routing_key, queue_name)
self.basic_consuming(
queue_name=queue_name,
callback=callback
) | 声明一个主题交换机队列,并且将队列和交换机进行绑定,同时监听这个队列
:param exchange_name:
:param routing_key:
:param queue_name:
:param callback:
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.