Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
12,900 | def execute_pubsub(self, command, *channels):
conn, address = self.get_connection(command)
if conn is not None:
return conn.execute_pubsub(command, *channels)
else:
return self._wait_execute_pubsub(address, command, channels, {}) | Executes Redis (p)subscribe/(p)unsubscribe commands.
ConnectionsPool picks separate connection for pub/sub
and uses it until explicitly closed or disconnected
(unsubscribing from all channels/patterns will leave connection
locked for pub/sub use).
There is no auto-reconnect fo... |
12,901 | def projects_from_cli(args):
description = (
)
parser = argparse.ArgumentParser(description=description)
req_help =
parser.add_argument(, , nargs=, default=(),
help=req_help)
meta_help =
parser.add_argument(, , nargs=, default=(),
... | Take arguments through the CLI can create a list of specified projects. |
12,902 | def mod_aggregate(low, chunks, running):
rules = []
agg_enabled = [
,
,
]
if low.get() not in agg_enabled:
return low
for chunk in chunks:
tag = __utils__[](chunk)
if tag in running:
continue
if chunk.get() == :
... | The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data |
12,903 | def archive(cwd,
output,
rev=,
prefix=None,
git_opts=,
user=None,
password=None,
ignore_retcode=False,
output_encoding=None,
**kwargs):
s behavior
differs slightly from ``git archive`` in this res... | .. versionchanged:: 2015.8.0
Returns ``True`` if successful, raises an error if not.
Interface to `git-archive(1)`_, exports a tarball/zip file of the
repository
cwd
The path to be archived
.. note::
``git archive`` permits a partial archive to be created. Thus, this
... |
12,904 | def fso_rmtree(self, path, ignore_errors=False, onerror=None):
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
try:
if self.fso_islink(path):
raise OSError()
except OSError:
onerror(os.path.islink, p... | overlays shutil.rmtree() |
12,905 | def destroy_vm_vdis(name=None, session=None, call=None):
if session is None:
session = _get_session()
ret = {}
vms = session.xenapi.VM.get_by_name_label(name)
if len(vms) == 1:
vbds = session.xenapi.VM.get_VBDs(vms[0])
if vbds is not None:
x = 0
... | Get virtual block devices on VM
.. code-block:: bash
salt-cloud -a destroy_vm_vdis xenvm01 |
12,906 | def process_exception(self, request, exception):
if isinstance(exception, CasTicketException):
do_logout(request)
return HttpResponseRedirect(request.path)
else:
return None | When we get a CasTicketException, that is probably caused by the ticket timing out.
So logout/login and get the same page again. |
12,907 | def find_uncommitted_filefields(sender, instance, **kwargs):
uncommitted = instance._uncommitted_filefields = []
fields = sender._meta.fields
if kwargs.get(, None):
update_fields = set(kwargs[])
fields = update_fields.intersection(fields)
for field in fields:
if isinstance(... | A pre_save signal handler which attaches an attribute to the model instance
containing all uncommitted ``FileField``s, which can then be used by the
:func:`signal_committed_filefields` post_save handler. |
12,908 | def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning:
if isinstance(bins, int):
if range:
bins = np.linspace(range[0], range[1], bins + 1)
else:
start = data.min()
stop = data.max()
bins = np.linspace(start, stop, bins + 1... | Construct binning schema compatible with numpy.histogram
Parameters
----------
data: array_like, optional
This is optional if both bins and range are set
bins: int or array_like
range: Optional[tuple]
(min, max)
includes_right_edge: Optional[bool]
default: True
See ... |
12,909 | def dead_letter(self, description=None):
self._is_live()
details = {
: str(description) if description else "",
: str(description) if description else ""}
self._receiver._settle_deferred(
, [self.lock_token], dead_letter_details=details)
sel... | Move the message to the Dead Letter queue.
The Dead Letter queue is a sub-queue that can be
used to store messages that failed to process correctly, or otherwise require further inspection
or processing. The queue can also be configured to send expired messages to the Dead Letter queue.
... |
12,910 | def add_record(self, is_sslv2=None, is_tls13=None):
if is_sslv2 is None and is_tls13 is None:
v = (self.cur_session.tls_version or
self.cur_session.advertised_tls_version)
if v in [0x0200, 0x0002]:
is_sslv2 = True
elif v >= 0x0304:
... | Add a new TLS or SSLv2 or TLS 1.3 record to the packets buffered out. |
12,911 | def factorset_divide(factorset1, factorset2):
r
if not isinstance(factorset1, FactorSet) or not isinstance(factorset2, FactorSet):
raise TypeError("factorset1 and factorset2 must be FactorSet instances")
return factorset1.divide(factorset2, inplace=False) | r"""
Base method for dividing two factor sets.
Division of two factor sets :math:`\frac{\vec\phi_1}{\vec\phi_2}` basically translates to union of all the factors
present in :math:`\vec\phi_2` and :math:`\frac{1}{\phi_i}` of all the factors present in :math:`\vec\phi_2`.
Parameters
----------
f... |
12,912 | def encode(self, x):
n = self._outputSize
y = np.zeros(n)
Q = self._Q
W = self._W
t = self._t
lam = self._lambda
try:
y_star = np.random.sample(n)
y_star = fixed_point(lambda p: expit(lam * ( np.dot(Q,x) + np.dot(W,p... | Given an input array `x` it returns its associated encoding `y(x)`.
Please cf. the paper for more details.
Note that NO learning takes place. |
12,913 | def query_disease():
allowed_str_args = [, , , , , ]
args = get_args(
request_args=request.args,
allowed_str_args=allowed_str_args
)
return jsonify(query.disease(**args)) | Returns list of diseases by query parameters
---
tags:
- Query functions
parameters:
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: DI-03832
- name: ref_id
in: query
type: strin... |
12,914 | def hash_from_stream(n, hash_stream):
_to_int64 = to_int64
x = 0x345678
multiplied = _to_int64(1000003)
for n in range(n - 1, -1, -1):
h = next(hash_stream)
x = _to_int64((x ^ h) * multiplied)
multiplied += _to_int64(82520 + _to_int64(2 * n))
multiplied = _to_int64(m... | Not standard hashing algorithm!
Install NumPy for better hashing service.
>>> from Redy.Tools._py_hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, map(hash, s)) == hash((1, 2, 3)) |
12,915 | def join(self, *args):
call_args = list(args)
joiner = call_args.pop(0)
self.random.shuffle(call_args)
return joiner.join(call_args) | Returns the arguments in the list joined by STR.
FIRST,JOIN_BY,ARG_1,...,ARG_N
%{JOIN: ,A,...,F} -> 'A B C ... F' |
12,916 | def get_strategy_types():
def get_subtypes(type_):
subtypes = type_.__subclasses__()
for subtype in subtypes:
subtypes.extend(get_subtypes(subtype))
return subtypes
return get_subtypes(Strategy) | Get a list of all :class:`Strategy` subclasses. |
12,917 | def get_deployments(self, project, definition_id=None, definition_environment_id=None, created_by=None, min_modified_time=None, max_modified_time=None, deployment_status=None, operation_status=None, latest_attempts_only=None, query_order=None, top=None, continuation_token=None, created_for=None, min_started_time=None, ... | GetDeployments.
:param str project: Project ID or project name
:param int definition_id:
:param int definition_environment_id:
:param str created_by:
:param datetime min_modified_time:
:param datetime max_modified_time:
:param str deployment_status:
:param... |
12,918 | def reload_plugin(self, name, *args):
self._logger.debug("Reloading {}.".format(name))
self._logger.debug("Disabling {}.".format(name))
self.get_plugin(name).disable()
self._logger.debug("Removing plugin instance.")
del self._plugins[name]
self._logger.debug("... | Reloads a given plugin
:param name: The name of the plugin
:param args: The args to pass to the plugin |
12,919 | def set_org_disclaimer(self):
is_checked = self.custom_org_disclaimer_checkbox.isChecked()
if is_checked:
org_disclaimer = setting(
,
default=disclaimer(),
expected_type=str,
qsettings=self.settings)
... | Auto-connect slot activated when org disclaimer checkbox is toggled. |
12,920 | def ingest(self, text, logMessage=None):
http_args = {}
if logMessage:
http_args[] = logMessage
headers = {: }
url =
if isinstance(text, six.text_type):
text = bytes(text.encode())
return ... | Ingest a new object into Fedora. Returns the pid of the new object on success.
Return response should have a status of 201 Created on success, and
the content of the response will be the newly created pid.
Wrapper function for `Fedora REST API ingest <http://fedora-commons.org/confluence/displa... |
12,921 | def learn_transportation_mode(track, clf):
for segment in track.segments:
tmodes = segment.transportation_modes
points = segment.points
features = []
labels = []
for tmode in tmodes:
points_part = points[tmode[]:tmode[]]
if len(points_part) > 0:
... | Inserts transportation modes of a track into a classifier
Args:
track (:obj:`Track`)
clf (:obj:`Classifier`) |
12,922 | def parse_instance_count(instance_count, speaker_total_count):
result = copy.copy(speaker_total_count)
for speaker_id, count in instance_count.items():
speaker_id = str(speaker_id)
speaker_total = speaker_total_count.get(speaker_id, 0)
if type(count) == float and 0.0 <= count... | This parses the instance count dictionary
(that may contain floats from 0.0 to 1.0 representing a percentage)
and converts it to actual instance count. |
12,923 | def getScreenshotPropertyType(self, screenshotHandle):
fn = self.function_table.getScreenshotPropertyType
pError = EVRScreenshotError()
result = fn(screenshotHandle, byref(pError))
return result, pError | When your application receives a
VREvent_RequestScreenshot event, call these functions to get
the details of the screenshot request. |
12,924 | def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
r
return Differ(linejunk, charjunk).compare(a, b) | r"""
Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
Optional keyword parameters `linejunk` and `charjunk` are for filter
functions (or None):
- linejunk: A function that should accept a single string argument, and
return true iff the string is junk. The default is None, ... |
12,925 | def nonwhitelisted_allowed_principals(self, whitelist=None):
if not whitelist:
return []
nonwhitelisted = []
for statement in self.statements:
if statement.non_whitelisted_principals(whitelist) and statement.effect == "Allow":
nonwhitelisted.app... | Find non whitelisted allowed principals. |
12,926 | def network_from_df(self, df):
teneto.utils.check_TemporalNetwork_input(df, )
self.network = df
self._update_network() | Defines a network from an array.
Parameters
----------
array : array
Pandas dataframe. Should have columns: \'i\', \'j\', \'t\' where i and j are node indicies and t is the temporal index.
If weighted, should also include \'weight\'. Each row is an edge. |
12,927 | def get_action_side_effects(self):
result = SCons.Util.UniqueList([])
for target in self.get_action_targets():
result.extend(target.side_effects)
return result | Returns all side effects for all batches of this
Executor used by the underlying Action. |
12,928 | def query(conn_type, option, post_data=None):
if ticket is None or csrf is None or url is None:
log.debug()
_authenticate()
full_url = .format(url, port, option)
log.debug(, conn_type, full_url, post_data)
httpheaders = {: ,
: ,
: }
if c... | Execute the HTTP request to the API |
12,929 | def list_items(cls, repo, *args, **kwargs):
out_list = IterableList(cls._id_attribute_)
out_list.extend(cls.iter_items(repo, *args, **kwargs))
return out_list | Find all items of this type - subclasses can specify args and kwargs differently.
If no args are given, subclasses are obliged to return all items if no additional
arguments arg given.
:note: Favor the iter_items method as it will
:return:list(Item,...) list of item instances |
12,930 | def mem_extend(self, start: int, size: int) -> None:
m_extend = self.calculate_extension_size(start, size)
if m_extend:
extend_gas = self.calculate_memory_gas(start, size)
self.min_gas_used += extend_gas
self.max_gas_used += extend_gas
self.check_... | Extends the memory of this machine state.
:param start: Start of memory extension
:param size: Size of memory extension |
12,931 | def cmyk(self):
c, m, y = self.cmy
k = min(c, m, y)
if k != 1:
c = (c - k) / (1 - k)
m = (m - k) / (1 - k)
y = (y - k) / (1 - k)
else:
c, m, y = 1, 1, 1
cmyk = (c, m, y, k)
return tuple(map(lamb... | CMYK: all returned in range 0.0 - 1.0 |
12,932 | def indices(this, that, axis=semantics.axis_default, missing=):
this = as_index(this, axis=axis, lex_as_struct=True)
that = as_index(that, axis=axis, base=True, lex_as_struct=True)
insertion = np.searchsorted(this._keys, that._keys, sorter=this.sorter, side=)
indices = np.... | Find indices such that this[indices] == that
If multiple indices satisfy this condition, the first index found is returned
Parameters
----------
this : indexable object
items to search in
that : indexable object
items to search for
axis : int, optional
axis to operate on... |
12,933 | def get(self, entry):
try:
list = self.cache[entry.key]
return list[list.index(entry)]
except:
return None | Gets an entry by key. Will return None if there is no
matching entry. |
12,934 | def to_unicode(s):
if not isinstance(s, six.string_types):
raise ValueError("{} must be str or unicode.".format(s))
if not isinstance(s, six.text_type):
s = six.text_type(s, )
return s | Return the object as unicode (only matters for Python 2.x).
If s is already Unicode, return s as is.
Otherwise, assume that s is UTF-8 encoded, and convert to Unicode.
:param (basestring) s: a str, unicode or other basestring object
:return (unicode): the object as unicode |
12,935 | def enable_caching(self):
"Enable the cache of this object."
self.caching_enabled = True
for c in self.values():
c.enable_cacher() | Enable the cache of this object. |
12,936 | def handle_profile_delete(self, sender, instance, **kwargs):
try:
self.handle_save(instance.user.__class__, instance.user)
except (get_profile_model().DoesNotExist):
pass | Custom handler for user profile delete |
12,937 | def add(repo_path, dest_path):
mkcfgdir()
try:
repo = getrepohandler(repo_path)
except NotARepo as err:
echo("ERROR: {}: {}".format(ERR_NOT_A_REPO, err.repo_path))
sys.exit(1)
if repo.isremote:
localrepo, needpull = addfromremote(repo, dest_path)
elif dest_... | Registers a git repository with homely so that it will run its `HOMELY.py`
script on each invocation of `homely update`. `homely add` also immediately
executes a `homely update` so that the dotfiles are installed straight
away. If the git repository is hosted online, a local clone will be created
first.... |
12,938 | def _generate_autoscaling_metadata(self, cls, args):
assert isinstance(args, Mapping)
init_config = self._create_instance(
cloudformation.InitConfig,
args[][])
init = self._create_instance(
cloudformation.Init, {: init_config})
auth = None
... | Provides special handling for the autoscaling.Metadata object |
12,939 | def steal_docstring_from(obj):
def deco(fn):
docs = [obj.__doc__]
if fn.__doc__:
docs.append(fn.__doc__)
fn.__doc__ = .join(docs)
return fn
return deco | Decorator that lets you steal a docstring from another object
Example
-------
::
@steal_docstring_from(superclass.meth)
def meth(self, arg):
"Extra subclass documentation"
pass
In this case the docstring of the new 'meth' will be copied from superclass.meth, and
if an add... |
12,940 | def add_entity(self, rdf_type, superclass, label, definition=None):
t exist and has a usable
superclass ILX ID and rdf:type
owl:Classtermowl:Classtermcdeannotationrelationshipfderdf_type must be one of the following: {accepted_types}data{superclass} is does not exist and cannot be used as a ... | Adds entity as long as it doesn't exist and has a usable
superclass ILX ID and rdf:type |
12,941 | def ensure_directory(directory):
directory = os.path.expanduser(directory)
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise e | Create the directories along the provided directory path that do not exist. |
12,942 | def write_options_to_JSON(self, filename):
fd = open(filename, "w")
fd.write(json.dumps(_options_to_dict(self.gc), indent=2,
separators=(, )))
fd.close() | Writes the options in JSON format to a file.
:param str filename: Target file to write the options. |
12,943 | def size(self, destination):
if not destination in self.queue_metadata:
return 0
else:
return len(self.queue_metadata[destination][]) | Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int} |
12,944 | def json_serializer(pid, data, *args):
if data is not None:
response = Response(
json.dumps(data.dumps()),
mimetype=
)
else:
response = Response(mimetype=)
return response | Build a JSON Flask response using the given data.
:param pid: The `invenio_pidstore.models.PersistentIdentifier` of the
record.
:param data: The record metadata.
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Response`. |
12,945 | def as_proto(self):
if self._dims is None:
return tensor_shape_pb2.TensorShapeProto(unknown_rank=True)
else:
return tensor_shape_pb2.TensorShapeProto(
dim=[
tensor_shape_pb2.TensorShapeProto.Dim(
size=-1 if d.va... | Returns this shape as a `TensorShapeProto`. |
12,946 | def normalize(x:TensorImage, mean:FloatTensor,std:FloatTensor)->TensorImage:
"Normalize `x` with `mean` and `std`."
return (x-mean[...,None,None]) / std[...,None,None] | Normalize `x` with `mean` and `std`. |
12,947 | def sim(self, args):
if not self._started:
raise ApplicationNotStarted("BACnet stack not running - use startApp()")
args = args.split()
addr, obj_type, obj_inst, prop_id, value = args[:5]
if self.read("{} {} {} outOfService".format(addr, obj_type, ... | Simulate I/O points by setting the Out_Of_Service property, then doing a
WriteProperty to the point's Present_Value.
:param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ] |
12,948 | def Hk(self, k, m_pred, P_pred):
return self.H[:, :, int(self.index[self.H_time_var_index, k])] | function (k, m, P) return Jacobian of measurement function, it is
passed into p_h.
k (iteration number), starts at 0
m: point where Jacobian is evaluated
P: parameter for Jacobian, usually covariance matrix. |
12,949 | def wald_wolfowitz(sequence):
R = n_runs = sum(1 for s in groupby(sequence, lambda a: a))
n = float(sum(1 for s in sequence if s == sequence[0]))
m = float(sum(1 for s in sequence if s != sequence[0]))
ER = ((2 * n * m ) / (n + m)) + 1
VR = (2 * n * m * (2 * n * m - n - m )) / ((n +... | implements the wald-wolfowitz runs test:
http://en.wikipedia.org/wiki/Wald-Wolfowitz_runs_test
http://support.sas.com/kb/33/092.html
:param sequence: any iterable with at most 2 values. e.g.
'1001001'
[1, 0, 1, 0, 1]
'abaaabbba'
:rtype: a ... |
12,950 | def getSizeFromPage(rh, page):
rh.printSysLog("Enter generalUtils.getSizeFromPage")
bSize = float(page) * 4096
mSize = cvtToMag(rh, bSize)
rh.printSysLog("Exit generalUtils.getSizeFromPage, magSize: " + mSize)
return mSize | Convert a size value from page to a number with a magnitude appended.
Input:
Request Handle
Size in page
Output:
Converted value with a magnitude |
12,951 | def key56_to_key64(key):
if len(key) != 7:
raise ValueError("DES 7-byte key is not 7 bytes in length, "
"actual: %d" % len(key))
new_key = b""
for i in range(0, 8):
if i == 0:
new_value = struct.unpack("B", key[i:i+1]... | This takes in an a bytes string of 7 bytes and converts it to a bytes
string of 8 bytes with the odd parity bit being set to every 8 bits,
For example
b"\x01\x02\x03\x04\x05\x06\x07"
00000001 00000010 00000011 00000100 00000101 00000110 00000111
is converted to
b"\x01... |
12,952 | def getContactUIDForUser(self):
membership_tool = api.get_tool("portal_membership")
member = membership_tool.getAuthenticatedMember()
username = member.getUserName()
r = self.portal_catalog(
portal_type="Contact",
getUsername=username
)
if... | Get the UID of the user associated with the authenticated user |
12,953 | def get_value_tuple(self):
retval = tuple()
for val in self.VALUES:
retval += (getattr(self, val),)
return retval | Returns a tuple of the color's values (in order). For example,
an LabColor object will return (lab_l, lab_a, lab_b), where each
member of the tuple is the float value for said variable. |
12,954 | def blk_1d(blk, shape):
maxpix, rem = blk_coverage_1d(blk, shape)
for i in range(0, maxpix, blk):
yield slice(i, i + blk)
if rem != 0:
yield slice(maxpix, shape) | Iterate through the slices that recover a line.
This function is used by :func:`blk_nd` as a base 1d case.
The last slice is returned even if is lesser than blk.
:param blk: the size of the block
:param shape: the size of the array
:return: a generator that yields the slices |
12,955 | def unpack(self, buff, offset=0):
super().unpack(buff, offset)
self.version = self._version_ihl.value >> 4
self.ihl = self._version_ihl.value & 15
self.dscp = self._dscp_ecn.value >> 2
self.ecn = self._dscp_ecn.value & 3
self.length = self.length.value
s... | Unpack a binary struct into this object's attributes.
Return the values instead of the lib's basic types.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: If unpack fails. |
12,956 | def time2slurm(timeval, unit="s"):
d, h, m, s = 24*3600, 3600, 60, 1
timeval = Time(timeval, unit).to("s")
days, hours = divmod(timeval, d)
hours, minutes = divmod(hours, h)
minutes, secs = divmod(minutes, m)
return "%d-%d:%d:%d" % (days, hours, minutes, secs) | Convert a number representing a time value in the given unit (Default: seconds)
to a string following the slurm convention: "days-hours:minutes:seconds".
>>> assert time2slurm(61) == '0-0:1:1' and time2slurm(60*60+1) == '0-1:0:1'
>>> assert time2slurm(0.5, unit="h") == '0-0:30:0' |
12,957 | def visit_RETURN(self, node):
if len(node.children) == 2:
node.children[1] = (yield ToVisit(node.children[1]))
yield node | Visits only children[1], since children[0] points to
the current function being returned from (if any), and
might cause infinite recursion. |
12,958 | def add(self, opener):
index = len(self.openers)
self.openers[index] = opener
for name in opener.names:
self.registry[name] = index | Adds an opener to the registry
:param opener: Opener object
:type opener: Opener inherited object |
12,959 | def copy(self):
return _TimeAnchor(self.reading_id, self.uptime, self.utc, self.is_break, self.exact) | Return a copy of this _TimeAnchor. |
12,960 | def mask_unphysical(self, data):
if not self.valid_range:
return data
else:
return np.ma.masked_outside(data, np.min(self.valid_range),
np.max(self.valid_range)) | Mask data array where values are outside physically valid range. |
12,961 | def make_defaults_and_annotations(make_function_instr, builders):
n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_arg(
make_function_instr.arg
)
if n_annotations:
load_annotation_names = builders.pop()
annotations = dict(zip(
reversed... | Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`. |
12,962 | def show_top(queue=False, **kwargs):
*
if in kwargs:
kwargs.pop()
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
... | Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top |
12,963 | def getHTML(self):
root = self.getRoot()
if root is None:
raise ValueError()
if self.doctype:
doctypeStr = %(self.doctype)
else:
doctypeStr =
rootNode = self.getRoot()
if rootNode.tagName == INVIS... | getHTML - Get the full HTML as contained within this tree.
If parsed from a document, this will contain the original whitespacing.
@returns - <str> of html
@see getFormattedHTML
@see getMiniHTML |
12,964 | def getMaximinScores(profile):
elecType = profile.getElecType()
if elecType != "soc" and elecType != "toc":
print("ERROR: unsupported election type")
exit()
wmgMap = profile.getWmg()
maximinscores = {}
for cand in wmgMap.keys():
maximinscores[cand] = flo... | Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile. |
12,965 | def postprocess(x, n_bits_x=8):
x = tf.where(tf.is_finite(x), x, tf.ones_like(x))
x = tf.clip_by_value(x, -0.5, 0.5)
x += 0.5
x = x * 2**n_bits_x
return tf.cast(tf.clip_by_value(x, 0, 255), dtype=tf.uint8) | Converts x from [-0.5, 0.5], to [0, 255].
Args:
x: 3-D or 4-D Tensor normalized between [-0.5, 0.5]
n_bits_x: Number of bits representing each pixel of the output.
Defaults to 8, to default to 256 possible values.
Returns:
x: 3-D or 4-D Tensor representing images or videos. |
12,966 | def seek(self, offset, whence=os.SEEK_SET):
if not self._is_open:
raise IOError()
if self._current_offset < 0:
raise IOError(
.format(
self._current_offset))
if whence == os.SEEK_CUR:
offset += self._current_offset
elif whence == os.SEEK_END:
if se... | Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek.
whence (Optional[int]): value that indicates whether offset is an
absolute or relative position within the file.
Raises:
IOError: if the seek failed.
OSError: if the seek failed. |
12,967 | def commit_analyzer(commits, label_pattern, label_position="footer"):
pattern_string = re.escape(label_pattern)
action_cgp = r"(?P<type>\w+)"
scope_cgp = r"(?P<scope>\w*)"
subject_cgp = r"(?P<subject>.+)"
pattern_string = pattern_string.replace(r"\{type\}", action_cgp).replace(
... | Analyzes a list of :class:`~braulio.git.Commit` objects searching for
messages that match a given message convention and extract metadata from
them.
A message convention is determined by ``label_pattern``, which is not a
regular expression pattern. Instead it must be a string literals with
placehol... |
12,968 | def create_database(self, name):
statement = "CREATE DATABASE {0} DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci".format(wrap(name))
return self.execute(statement) | Create a new database. |
12,969 | def update_task(self, differences):
self.log(.format(differences))
object_name = .format(self.app_label, self.instance.master._meta.verbose_name)
lang = self.instance.language_code
object_pk = self.instance.master.pk
for field in differences:
value = getat... | Updates a task as done if we have a new value for this alternative language
:param differences:
:return: |
12,970 | def add_default_plugins(self, except_global=[], except_local=[]):
for spec in plugins:
ptype = spec.get(, )
if ptype == and spec.module not in except_global:
self.add_plugin_spec(spec)
if ptype == and spec.module not in except_local:
... | Add the ginga-distributed default set of plugins to the
reference viewer. |
12,971 | def locked_get(self):
credential = self._backend.locked_get(self._key)
if credential is not None:
credential.set_store(self)
return credential | Retrieves the current credentials from the store.
Returns:
An instance of :class:`oauth2client.client.Credentials` or `None`. |
12,972 | def get_value_for_expr(self, expr, target):
if expr in LOGICAL_OPERATORS.values():
return None
rvalue = expr[]
if rvalue == HISTORICAL:
history = self.history[target]
if len(history) < self.history_size:
return None
rvalue ... | I have no idea. |
12,973 | def get_message_handler(self, message_handlers):
encoder = self.options.encoder
try:
return message_handlers[encoder]
except KeyError:
raise NotImplementedError( % encoder) | Create a MessageHandler for the configured Encoder
:param message_handlers: a dictionart of MessageHandler keyed by encoder
:return: a MessageHandler |
12,974 | def jam_pack(jam, **kwargs):
foobar
if not hasattr(jam.sandbox, ):
jam.sandbox.muda = jams.Sandbox(**jam.sandbox.muda)
jam.sandbox.muda.update(**kwargs)
return jam | Pack data into a jams sandbox.
If not already present, this creates a `muda` field within `jam.sandbox`,
along with `history`, `state`, and version arrays which are populated by
deformation objects.
Any additional fields can be added to the `muda` sandbox by supplying
keyword arguments.
Param... |
12,975 | def get_observation_fields(search_query: str="", page: int=1) -> List[Dict[str, Any]]:
payload = {
: search_query,
: page
}
response = requests.get("{base_url}/observation_fields.json".format(base_url=INAT_BASE_URL), params=payload)
return response.json() | Search the (globally available) observation
:param search_query:
:param page:
:return: |
12,976 | def _learn_init_params(self, n_calib_beats=8):
if self.verbose:
print()
last_qrs_ind = -self.rr_max
qrs_inds = []
qrs_amps = []
noise_amps = []
ricker_wavelet = signal.ricker(self.qrs_radius * 2, 4).reshape(-1,1)
peak_inds_f = find... | Find a number of consecutive beats and use them to initialize:
- recent qrs amplitude
- recent noise amplitude
- recent rr interval
- qrs detection threshold
The learning works as follows:
- Find all local maxima (largest sample within `qrs_radius`
samples) of ... |
12,977 | def _convert_default_value(self, default):
if default is None:
return None
if isinstance(default, str):
if self.special_type == :
return default.encode() + b
raise DataError("You can only pass a unicode string if you are declaring a string ... | Convert the passed default value to binary.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
If you pass a bytes o... |
12,978 | def panels(self):
ax1 = self.fig.add_subplot(211)
ax2 = self.fig.add_subplot(212, sharex=ax1)
return (ax2, self.gene_panel), (ax1, self.signal_panel) | Add 2 panels to the figure, top for signal and bottom for gene models |
12,979 | def add_document(self, question, answer):
question = question.strip()
answer = answer.strip()
session = self.Session()
if session.query(Document) \
.filter_by(text=question, answer=answer).count():
logger.info(.format(question, answer))
... | Add question answer set to DB.
:param question: A question to an answer
:type question: :class:`str`
:param answer: An answer to a question
:type answer: :class:`str` |
12,980 | def should_execute(self, workload):
if not self._suspended.is_set():
return True
workload = unwrap_workload(workload)
return hasattr(workload, ) and getattr(workload, ) | If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy
value. See the docs on the suspend_signal_handler method of the io module for more information. |
12,981 | def _GetMemberDataTypeMaps(self, data_type_definition, data_type_map_cache):
if not data_type_definition:
raise errors.FormatError()
members = getattr(data_type_definition, , None)
if not members:
raise errors.FormatError()
data_type_maps = []
members_data_size = 0
for member... | Retrieves the member data type maps.
Args:
data_type_definition (DataTypeDefinition): data type definition.
data_type_map_cache (dict[str, DataTypeMap]): cached data type maps.
Returns:
list[DataTypeMap]: member data type maps.
Raises:
FormatError: if the data type maps cannot be ... |
12,982 | def make_rw(obj: Any):
if isinstance(obj, RoDict):
return {k: make_rw(v) for k, v in obj.items()}
elif isinstance(obj, RoList):
return [make_rw(x) for x in obj]
else:
return obj | Copy a RO object into a RW structure made with standard Python classes.
WARNING there is no protection against recursion. |
12,983 | def get_policy_config(platform,
filters=None,
prepend=True,
pillar_key=,
pillarenv=None,
saltenv=None,
merge_pillar=True,
only_lower_merge=False,
... | Return the configuration of the whole policy.
platform
The name of the Capirca platform.
filters
List of filters for this policy.
If not specified or empty, will try to load the configuration from the pillar,
unless ``merge_pillar`` is set as ``False``.
prepend: ``True``
... |
12,984 | def td_sp(points, speed_threshold):
if len(points) <= 2:
return points
else:
max_speed_threshold = 0
found_index = 0
for i in range(1, len(points)-1):
dt1 = time_dist(points[i], points[i-1])
if dt1 == 0:
dt1 = 0.000000001
v... | Top-Down Speed-Based Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
speed_threshold (float): max speed error, in km/h
Returns:
:obj:`list` of :ob... |
12,985 | def delete_bucket():
args = parser.parse_args
s3_bucket(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name)().delete() | Delete S3 Bucket |
12,986 | def construct(cls, name: str, declared_fields: typing.List[tuple]):
@classmethod
def from_dict(cls, adict):
invalid_req = InvalidRequestObject()
values = {}
for item in fields(cls):
value = None
if item.... | Utility method packaged along with the factory to be able to construct Request Object
classes on the fly.
Example:
.. code-block:: python
UserShowRequestObject = Factory.create_request_object(
'CreateRequestObject',
[('identifier', int, {'required':... |
12,987 | def get_type_properties(self, property_obj, name, additional_prop=False):
property_type, property_format, property_dict = \
super(Schema, self).get_type_properties(property_obj, name, additional_prop=additional_prop)
_schema = self.storage.get(property_type)
if _schema and (... | Extend parents 'Get internal properties of property'-method |
12,988 | def schemaValidateOneElement(self, elem):
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlSchemaValidateOneElement(self._o, elem__o)
return ret | Validate a branch of a tree, starting with the given @elem. |
12,989 | def _create_emitter(self, event):
if not hasattr(self, event):
setattr(self, event,
lambda *args, **kwargs: self.emit(event, *args, **kwargs)) | Create a method that emits an event of the same name. |
12,990 | def call(self, op, args):
converted = self.convert_list(args)
return self._call(op, converted) | Calls operation `op` on args `args` with this backend.
:return: A backend object representing the result. |
12,991 | def vinet_v(p, v0, k0, k0p, min_strain=0.01):
if isuncertainties([p, v0, k0, k0p]):
f_u = np.vectorize(uct.wrap(vinet_v_single), excluded=[1, 2, 3, 4])
return f_u(p, v0, k0, k0p, min_strain=min_strain)
else:
f_v = np.vectorize(vinet_v_single, excluded=[1, 2, 3, 4])
return f_... | find volume at given pressure
:param p: pressure in GPa
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at reference conditions
:param min_strain: defining minimum v/v0 value to search volume for
:return... |
12,992 | def popup(self, title, callfn, initialdir=None, filename=None):
self.cb = callfn
self.filew.set_title(title)
if initialdir:
self.filew.set_current_folder(initialdir)
if filename:
self.filew.set_current_name(filename)
self.filew.show... | Let user select and load file. |
12,993 | def web_services_from_str(
list_splitter_fn=ujson.loads,
):
def class_list_converter(collector_services_str):
if isinstance(collector_services_str, basestring):
all_collector_services = list_splitter_fn(collector_services_str)
else:
raise TypeError()
... | parameters:
list_splitter_fn - a function that will take the json compatible string
rerpesenting a list of mappings. |
12,994 | def args_ok(self, options, args):
for i in [, ]:
for j in [, , , ]:
if (i in options.actions) and (j in options.actions):
self.help_fn("You can%s%sexecuteannotatehtmldebugreportxmlexecute' in options.actions and not args:
self.help_fn("Nothing... | Check for conflicts and problems in the options.
Returns True if everything is ok, or False if not. |
12,995 | def from_config(self, k, v):
if k == "setup":
return from_commandline(v, classname=to_commandline(datagen.DataGenerator()))
return super(DataGenerator, self).from_config(k, v) | Hook method that allows converting values from the dictionary.
:param k: the key in the dictionary
:type k: str
:param v: the value
:type v: object
:return: the potentially parsed value
:rtype: object |
12,996 | def run_check200(_):
tstr =
idx = 1
for kind in config.router_post.keys():
posts = MPost.query_all(kind=kind, limit=20000)
for post in posts:
the_url0 = .format(
site_url=config.SITE_CFG[],
kind_url=config.router_post[post.kind],
... | Running the script. |
12,997 | def pool_full(self, session):
if not self.task.pool:
return False
pool = (
session
.query(Pool)
.filter(Pool.pool == self.task.pool)
.first()
)
if not pool:
return False
open_slots = pool.open_slots... | Returns a boolean as to whether the slot pool has room for this
task to run |
12,998 | def _instantiate_layers(self):
with self._enter_variable_scope(check_same_graph=False):
self._layers = tuple(conv.Conv2D(name="conv_2d_{}".format(i),
output_channels=self._output_channels[i],
kernel_... | Instantiates all the convolutional modules used in the network. |
12,999 | def find_global(self, pattern):
pos_s = self.reader.search(pattern)
if len(pos_s) == 0:
return -1
return pos_s[0] | Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.