Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
342,500 | def delete(self):
self._check_write_access()
filepath = self._getFilePath()
commands.remove(self.provider.ui, self.provider.repo, filepath, force=True) | Remove this resource (recursive). |
342,501 | def spectrum_to_xyz100(spectrum, observer):
lambda_o, data_o = observer
lambda_s, data_s = spectrum
lmbda = numpy.sort(numpy.unique(numpy.concatenate([lambda_o, lambda_s])))
assert lmbda[0] < 361e-9
assert lmbda[-1] > 829e-9
idata_o = numpy.array([numpy.interp(lm... | Computes the tristimulus values XYZ from a given spectrum for a given
observer via
X_i = int_lambda spectrum_i(lambda) * observer_i(lambda) dlambda.
In section 7, the technical report CIE Standard Illuminants for
Colorimetry, 1999, gives a recommendation on how to perform the
computation. |
342,502 | def create_dvs(dvs_dict, dvs_name, service_instance=None):
*
log.trace(%s\, dvs_name, dvs_dict)
proxy_type = get_proxy_type()
if proxy_type == :
datacenter = __salt__[]()[]
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == :
datacenter = __salt__[]()[]
d... | Creates a distributed virtual switch (DVS).
Note: The ``dvs_name`` param will override any name set in ``dvs_dict``.
dvs_dict
Dict representation of the new DVS (example in salt.states.dvs)
dvs_name
Name of the DVS to be created.
service_instance
Service instance (vim.Service... |
342,503 | def get_parsl_logger(
logger_name=,
is_logging_server=False,
monitoring_config=None,
**kwargs):
logger = logging.getLogger(logger_name)
if monitoring_config is None:
logger.addHandler(NullHandler())
return logger
... | Parameters
----------
logger_name : str, optional
Name of the logger to use. Prevents adding repeat handlers or incorrect handlers
is_logging_server : Bool, optional
Used internally to determine which handler to return when using local db logging
monitoring_config : MonitoringConfig, opt... |
342,504 | def calc_complex(mag, pha):
complx = [10 ** m * math.e ** (1j * p / 1e3) for m, p in zip(mag, pha)]
real = [math.log10((1 / c).real) for c in complx]
imag = []
for c in complx:
if ((1 / c).imag) == 0:
imag.append(math.nan)
else:
i = math.log10(abs((1 / c).ima... | Calculate real and imaginary part of the complex conductivity from
magnitude and phase in log10. |
342,505 | def do_measurement(self, qubit: int) -> int:
if self.rs is None:
raise ValueError("You have tried to perform a stochastic operation without setting the "
"random state of the simulator. Might I suggest using a PyQVM object?")
measurement_probs ... | Measure a qubit, collapse the wavefunction, and return the measurement result.
:param qubit: Index of the qubit to measure.
:return: measured bit |
342,506 | async def receive(self, parameters: RTCRtpReceiveParameters):
if not self.__started:
for codec in parameters.codecs:
self.__codecs[codec.payloadType] = codec
for encoding in parameters.encodings:
if encoding.rtx:
self.__rtx_ssr... | Attempt to set the parameters controlling the receiving of media.
:param: parameters: The :class:`RTCRtpParameters` for the receiver. |
342,507 | def _peek(self, size=-1):
with self._seek_lock:
seek = self._seek
with handle_os_exceptions():
return self._read_range(seek, seek + size) | Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read |
342,508 | def _compute_errors(self):
try:
coeffs = fit_first_and_second_harmonics(self.sample.values[0],
self.sample.values[2])
covariance = coeffs[1]
coeffs = coeffs[0]
model = first_and_second_harmonic_function... | Compute parameter errors based on the diagonal of the covariance
matrix of the four harmonic coefficients for harmonics n=1 and
n=2. |
342,509 | def _findNearest(arr, value):
arr = np.array(arr)
idx = (abs(arr-value)).argmin()
return arr[idx] | Finds the value in arr that value is closest to |
342,510 | def add(self,dist):
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key,[])
if dist not in dists:
dists.append(dist)
if dist.key in self._cache:
_sort_dists(self._cache[dist.key]) | Add `dist` if we ``can_add()`` it and it isn't already added |
342,511 | def sendRobust(
signal=Any,
sender=Anonymous,
*arguments, **named
):
responses = []
for receiver in liveReceivers(getAllReceivers(sender, signal)):
try:
response = robustApply(
receiver,
signal=signal,
sender=sender... | Send signal from sender to all connected receivers catching errors
signal -- (hashable) signal value, see connect for details
sender -- the sender of the signal
if Any, only receivers registered for Any will receive
the message.
if Anonymous, only receivers registered to rece... |
342,512 | def run(self):
from pyoko.lib.utils import get_object_from_path
from zengine.config import settings
model = get_object_from_path(settings.PERMISSION_MODEL)
perm_provider = get_object_from_path(settings.PERMISSION_PROVIDER)
existing_perms = []
new_perms = []
... | Creates new permissions. |
342,513 | def daisy_chains(self, kih, max_path_length=None):
if max_path_length is None:
max_path_length = len(self.ampal_parent)
g = self.daisy_chain_graph
paths = networkx.all_simple_paths(g, source=kih.knob, target=kih.knob, cutoff=max_path_length)
return paths | Generator for daisy chains (complementary kihs) associated with a knob.
Notes
-----
Daisy chain graph is the directed graph with edges from knob residue to each hole residue for each KnobIntoHole
in self.
Given a KnobIntoHole, the daisy chains are non-trivial paths in this grap... |
342,514 | def _get_memory_contents(self):
if self._memory_contents is not None:
return self._memory_contents
schedule = scheduler.minimize_peak_memory(self._graph, self._scheduler_alg)
self._memory_contents = self._graph.compute_memory_contents_under_schedule(
schedule)
return self._memory_co... | Runs the scheduler to determine memory contents at every point in time.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
GetAllOperationNames()). |
342,515 | def set_flow(self, flow):
if not hasattr(self, "_flow"):
self._flow = flow
else:
if self._flow != flow:
raise ValueError("self._flow != flow") | Set the flow associated to this :class:`Work`. |
342,516 | def connected_socket(address, timeout=3):
sock = socket.create_connection(address, timeout)
yield sock
sock.close() | yields a connected socket |
342,517 | def unregister_message_handler(self, target_or_handler):
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._... | Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered. |
342,518 | def do_import(self, line):
line = line.split()
if line and line[0] == "starter-pack":
actions.action_bootstrap()
elif line and line[0] == "uri":
self._print(
"------------------\nEnter a valid graph URI: (e.g. http://www.w3.org/2009/08/skos-ref... | Import an ontology |
342,519 | def _auto_install(self):
template = Template(template=self.manifest)
sections = template.sections()
images = self.d_client.images.list(filters={: })
add_sections = []
status = (True, None)
for image in images:
ignore = False
if ( in image.... | Automatically detects images and installs them in the manifest if they
are not there already |
342,520 | def delete_device_subscriptions(self, device_id):
api = self._get_api(mds.SubscriptionsApi)
return api.delete_endpoint_subscriptions(device_id) | Removes a device's subscriptions
:param device_id: ID of the device (Required)
:returns: None |
342,521 | def obfn_cns(self):
r
Y = self.obfn_gvar()
return np.linalg.norm((self.Pcn(Y) - Y)) | r"""Compute constraint violation measure :math:`\| P(\mathbf{y})
- \mathbf{y}\|_2`. |
342,522 | def process_input(self, data, input_prompt, lineno):
decorator, input, rest = data
image_file = None
image_directive = None
is_verbatim = decorator== or self.is_verbatim
is_doctest = decorator== or self.is_doctest
is_suppress = decorator== or self.is_sup... | Process data block for INPUT token. |
342,523 | def process_block(self, block):
ret = []
output = None
input_lines = None
lineno = self.IP.execution_count
input_prompt = self.promptin % lineno
output_prompt = self.promptout % lineno
image_file = None
image_directive = None
for token, ... | process block from the block_parser and return a list of processed lines |
342,524 | def get_all_attributes(klass_or_instance):
pairs = list()
for attr, value in inspect.getmembers(
klass_or_instance, lambda x: not inspect.isroutine(x)):
if not (attr.startswith("__") or attr.endswith("__")):
pairs.append((attr, value))
return pairs | Get all attribute members (attribute, property style method). |
342,525 | def on_mouse_click(self, widget, event):
import rafcon.gui.helpers.state_machine as gui_helper_state_machine
if self.view.get_path_at_pos(int(event.x), int(event.y)) is not None \
and len(self.view.get_selected_items()) > 0:
return gui_helper_state_machine.insert_sta... | state insertion on mouse click
:param widget:
:param Gdk.Event event: mouse click event |
342,526 | def ulogin_response(self, token, host):
response = requests.get(
settings.TOKEN_URL,
params={
: token,
: host
})
content = response.content
if sys.version_info >= (3, 0):
content = content.decode()
... | Makes a request to ULOGIN |
342,527 | async def _send_generic_template(self, request: Request, stack: Stack):
gt = stack.get_layer(GenericTemplate)
payload = await gt.serialize(request)
msg = {
: {
: ,
: payload
}
}
await self._add_qr(stack, msg, req... | Generates and send a generic template. |
342,528 | def set_digit_raw(self, pos, bitmask):
if pos < 0 or pos > 3:
return
offset = 0 if pos < 2 else 1
if self.invert:
pos = 4-(pos+offset)
else:
pos = pos+offset
self.buffer[pos*2] = bitmask & 0xFF | Set digit at position to raw bitmask value. Position should be a value
of 0 to 3 with 0 being the left most digit on the display. |
342,529 | def getConfigFile():
fileName =
home = os.environ.get()
if home:
return os.path.join(os.path.expanduser(home), fileName)
return os.path.join(os.path.expanduser(), fileName) | Returns the config file location.
If $WAKATIME_HOME env varialbe is defined, returns
$WAKATIME_HOME/.wakatime.cfg, otherwise ~/.wakatime.cfg. |
342,530 | def make_dir_path(project_dir, root, project_name):
root = root.replace(, project_name)
real_dir = path.realpath(project_dir)
return path.join(real_dir, root) | Generates the target path for a directory |
342,531 | def eval_xof_pattern(node, pattern):
xof_pattern = r"^(-?\d+%?),*(-?\d*%?),*(-?\d*%?) *of: *(.+)"
regex = re.compile(xof_pattern)
matches = regex.search(pattern)
if matches is not None:
node.operand =
groups = matches.groups()
mu... | Parse a X of pattern
* Set is_of_mul attribute
* Set of_values attribute
:param node: node to edit
:type node:
:param pattern: line to match
:type pattern: str
:return: end of the line (without X of :)
:rtype: str |
342,532 | def train(dataset, nef, ndf, ngf, nc, batch_size, Z, lr, beta1, epsilon, ctx, check_point, g_dl_weight, output_path, checkpoint_path, data_path, activation,num_epoch, save_after_every, visualize_after_every, show_after_every):
z_mu, z_lv, z = encoder(nef, Z, batch_size)
symE = mx.sym.Group([z_mu, z_l... | adversarial training of the VAE |
342,533 | def to_api_data(self, restrict_keys=None):
cc = self._cc
data = {
cc(): self._column_width,
cc(): self._horizontal_alignment,
cc(): self._row_height,
cc(): self._vertical_alignment,
cc(): self._wrap_text,
}
if restri... | Returns a dict to communicate with the server
:param restrict_keys: a set of keys to restrict the returned data to
:rtype: dict |
342,534 | def impute_using_statistics(df, method=):
sf = SimpleFill(method)
imputed_matrix = sf.complete(df.values)
imputed_df = pd.DataFrame(imputed_matrix, df.index, df.columns)
return imputed_df | Imputes the missing values by the selected statistical property of each column
:param df: The input dataframe that contains missing values
:param method: The imputation method (min by default)
"zero": fill missing entries with zeros
"mean": fill with column means
"me... |
342,535 | def bootstrap_params(rv_cont, data, n_iter=5, **kwargs):
fit_res = []
for _ in range(n_iter):
params = rv_cont.fit(resample_1d(data, **kwargs))
fit_res.append(params)
fit_res = np.array(fit_res)
return fit_res | Bootstrap the fit params of a distribution.
Parameters
==========
rv_cont: scipy.stats.rv_continuous instance
The distribution which to fit.
data: array-like, 1d
The data on which to fit.
n_iter: int [default=10]
Number of bootstrap iterations. |
342,536 | def raw_data_engine(**kwargs):
logger.debug("cycles_engine")
raise NotImplementedError
experiments = kwargs["experiments"]
farms = []
barn = "raw_dir"
for experiment in experiments:
farms.append([])
return farms, barn | engine to extract raw data |
342,537 | def sendToSbs(self, challenge_id, item_id):
method =
url = % challenge_id
squad = self.sbsSquad(challenge_id)
players = []
moved = False
n = 0
for i in squad[][]:
if i[][] == item_id:
return False
if i... | Send card FROM CLUB to first free slot in sbs squad. |
342,538 | def description(self, value):
if value is not None:
assert type(value) is unicode, " attribute: type is not !".format(
"description", value)
self.__description = value | Setter for **self.__description** attribute.
:param value: Attribute value.
:type value: unicode |
342,539 | def close(self):
if self._closing:
return
log.info(, os.getpid())
self._closing = True
if getattr(self, , None) is not None:
self._monitor.stop()
self._monitor = None
if getattr(self, , None) is not None:
self._w_m... | Cleanly shutdown the router socket |
342,540 | def put_item(self, fpath, relpath):
fname = generate_identifier(relpath)
dest_path = os.path.join(self._data_abspath, fname)
_cp(fpath, dest_path)
_put_metadata(dest_path, "handle", relpath)
return relpath | Put item with content from fpath at relpath in dataset.
Missing directories in relpath are created on the fly.
:param fpath: path to the item on local disk
:param relpath: relative path name given to the item in the dataset as
a handle |
342,541 | def get_caller(skip=None):
import inspect
from fnmatch import fnmatch
try:
stack = inspect.stack()
except:
stack = [None, inspect.currentframe()]
if len(stack) > 1:
stack.pop(0)
if skip and not isinstance(skip, (list, tuple)):
skip = [skip]
e... | Get the caller information, it'll return: module, filename, line_no |
342,542 | def getOffset(self, loc):
return Location(loc.x - self.x, loc.y - self.y) | Returns the offset between the given point and this point |
342,543 | def simplify_dicts( index, shared, simplify_dicts=SIMPLIFY_DICTS, always_compress=ALWAYS_COMPRESS_DICTS ):
to_delete = set()
for to_simplify in iterindex(index):
if to_simplify[] in to_delete:
continue
if to_simplify[] in simplify_dicts and not in to_simpli... | Eliminate "noise" dictionary records from the index
index -- overall index of objects (including metadata such as type records)
shared -- parent-count mapping for records in index
module/type/class dictionaries |
342,544 | def community_responsify(schema_class, mimetype):
def view(data, code=200, headers=None, links_item_factory=None,
page=None, urlkwargs=None, links_pagination_factory=None):
if isinstance(data, Community):
last_modified = data.updated
response_data = schema_... | Create a community response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response. |
342,545 | def _load_module(path):
module_name = os.path.splitext(os.path.basename(path))[0]
module = None
if sys.version_info.minor < 5:
loader = importlib.machinery.SourceFileLoader(module_name, path)
module = loader.load_module()
else:
spec = importlib.util.spec_from_fil... | Helper to load a Python file at path and return as a module |
342,546 | def register_mapper(self, mapper, content_type, shortname=None):
self._check_mapper(mapper)
cont_type_names = self._get_content_type_names(content_type, shortname)
self._datamappers.update(dict([(name, mapper) for name in cont_type_names])) | Register new mapper.
:param mapper: mapper object needs to implement ``parse()`` and
``format()`` functions. |
342,547 | def sigma(self):
rwater
return self.SurfaceTensionMixture(self.T, self.P, self.zs, self.ws) | r'''Surface tension of the mixture at its current temperature and
composition, in units of [N/m].
For calculation of this property at other temperatures,
or specifying manually the method used to calculate it, and more - see
the object oriented interface :obj:`thermo.interface.SurfaceTe... |
342,548 | def transfer(self, to, amount, asset, memo="", account=None, **kwargs):
from .memo import Memo
if not account:
if "default_account" in self.config:
account = self.config["default_account"]
if not account:
raise ValueError("You need to provide an ... | Transfer an asset to another account.
:param str to: Recipient
:param float amount: Amount to transfer
:param str asset: Asset to transfer
:param str memo: (optional) Memo, may begin with `#` for encrypted
messaging
:param str account: (option... |
342,549 | def set_room_alias(self, room_id, room_alias):
data = {
"room_id": room_id
}
return self._send("PUT", "/directory/room/{}".format(quote(room_alias)),
content=data) | Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name. |
342,550 | def get_all_dbsnapshots(self, snapshot_id=None, instance_id=None,
max_records=None, marker=None):
params = {}
if snapshot_id:
params[] = snapshot_id
if instance_id:
params[] = instance_id
if max_records:
params[] = ... | Get information about DB Snapshots.
:type snapshot_id: str
:param snapshot_id: The unique identifier of an RDS snapshot.
If not provided, all RDS snapshots will be returned.
:type instance_id: str
:param instance_id: The identifier of a DBInstance. If provi... |
342,551 | def read(self, symbol, date_range=None, columns=None, include_images=False, allow_secondary=None,
_target_tick_count=0):
perf_start = dt.now()
rtn = {}
column_set = set()
multiple_symbols = not isinstance(symbol, string_types)
date_range = to_pandas_closed... | Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
symbol name for the item
date_range : `date.DateRange`
Returns ticks in the specified DateRange
... |
342,552 | def xpath(self, xpath, dom=None):
if dom is None:
dom = self.browser
return expect(dom.find_by_xpath, args=[xpath]) | xpath find function abbreviation |
342,553 | def libvlc_media_library_new(p_instance):
f = _Cfunctions.get(, None) or \
_Cfunction(, ((1,),), class_result(MediaLibrary),
ctypes.c_void_p, Instance)
return f(p_instance) | Create an new Media Library object.
@param p_instance: the libvlc instance.
@return: a new object or NULL on error. |
342,554 | def get_yaml_dict(yaml_file):
try:
with open(yaml_file, ) as file_:
yaml_dict = yaml.safe_load(file_.read()) or {}
return yaml_dict
except FileNotFoundError:
return {} | Return a yaml_dict from reading yaml_file. If yaml_file is empty or
doesn't exist, return an empty dict instead. |
342,555 | def import_key(key_name, public_key_material, region=None, key=None,
keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.import_key_pair(key_name, public_key_material)
log.debug("the key to return is : %s", key)
... | Imports the public key from an RSA key pair that you created with a third-party tool.
Supported formats:
- OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)
- Base64 encoded DER format
- SSH public key file format as specified in RFC4716
- DSA keys are not supported. Make sure y... |
342,556 | def concat_same_type(self, to_concat, placement=None):
values = self._holder._concat_same_type(
[blk.values for blk in to_concat])
placement = placement or slice(0, len(values), 1)
return self.make_block_same_class(values, ndim=self.ndim,
... | Concatenate list of single blocks of the same type. |
342,557 | def run_conf(self):
run_conf = namedtuple(, field_names=self._run_conf.keys())
return run_conf(**self._run_conf) | Run configuration (namedtuple) |
342,558 | def check_cert(certfile):
cmd = .format(certfile)
out = subprocess.check_output(cmd, shell=True)
return out | output the text format of the certificate
:param filepath: file path to the ssl certificate
:returns: string |
342,559 | def _run_nucmer(self, ref, qry, outfile):
n = pymummer.nucmer.Runner(
ref,
qry,
outfile,
min_id=self.nucmer_min_id,
min_length=self.nucmer_min_length,
diagdiff=self.nucmer_diagdiff,
maxmatch=True,
breaklen=s... | Run nucmer of new assembly vs original assembly |
342,560 | def _parse_normalizations(self, normalizations):
parsed_normalizations = []
if isinstance(normalizations, list):
for item in normalizations:
normalization = self._parse_normalization(item)
if normalization:
parsed_normalizations.a... | Returns a list of parsed normalizations.
Iterates over a list of normalizations, removing those
not correctly defined. It also transform complex items
to have a common format (list of tuples and strings).
Args:
normalizations: List of normalizations to parse.
Retur... |
342,561 | def path_splitter(s, _d_match=re.compile(r"\.\d").match):
if has_pathlib and isinstance(s, PurePath):
s = py23_str(s)
path_parts = deque()
p_appendleft = path_parts.appendleft
path_location = s
while path_location != os_curdir and path_location != os_pardir:
parent_pat... | Split a string into its path components.
Assumes a string is a path or is path-like.
Parameters
----------
s : str | pathlib.Path
Returns
-------
split : tuple
The path split by directory components and extensions.
Examples
--------
>>> tuple(path_splitter("this/... |
342,562 | def cli(env, identifier, passwords, price):
hardware = SoftLayer.HardwareManager(env.client)
table = formatting.KeyValueTable([, ])
table.align[] =
table.align[] =
hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, )
result = hardware.get_hardware(hardware_id)
resul... | Get details for a hardware device. |
342,563 | def restores(self):
if not self.__restores:
self.__restores = Restores(self.__connection)
return self.__restores | Gets the Restores API client.
Returns:
Restores: |
342,564 | def replace_audit_sink(self, name, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.replace_audit_sink_with_http_info(name, body, **kwargs)
else:
(data) = self.replace_audit_sink_with_http_info(name, body, **kwargs)
return data | replace the specified AuditSink
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_audit_sink(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:para... |
342,565 | def get_ca_certs(environ=os.environ):
cert_paths = environ.get("TXAWS_CERTS_PATH", DEFAULT_CERTS_PATH).split(":")
certificate_authority_map = {}
for path in cert_paths:
if not path:
continue
for cert_file_name in glob(os.path.join(path, "*.pem")):
if... | Retrieve a list of CAs at either the DEFAULT_CERTS_PATH or the env
override, TXAWS_CERTS_PATH.
In order to find .pem files, this function checks first for presence of the
TXAWS_CERTS_PATH environment variable that should point to a directory
containing cert files. In the absense of this variable, the m... |
342,566 | def BitVecVal(value: int, size: int, annotations: Annotations = None) -> BitVec:
raw = z3.BitVecVal(value, size)
return BitVec(raw, annotations) | Creates a new bit vector with a concrete value. |
342,567 | def increment_filename(self, basename):
i = 0
while True:
name = u % (basename,i)
path = self.get_path_by_name(name)
if not os.path.isfile(path):
break
else:
i = i+1
return path, name | Return a non-used filename of the form basename<int>.
This searches through the filenames (basename0, basename1, ...)
until is find one that is not already being used. It is used to
create Untitled and Copy names that are unique. |
342,568 | def parse_descriptor(descriptor: str) -> list:
state = 10
tokens = []
token = []
dimensions = 0
for char in descriptor:
if state == 10 and char == :
state = 20
elif state == 10 and char == :
dimensions += 1
elif state == 10:
... | Uses a tiny state machine to parse JVM descriptors. To get useful wrappers
around the results, use :py:func:`jawa.core.descriptor.method_descriptor`
or :py:func:`jawa.core.descriptor.field_descriptor`. |
342,569 | def _do_config_proposal_vote(args):
signer = _read_signer(args.key)
rest_client = RestClient(args.url)
proposals = _get_proposals(rest_client)
proposal = None
for candidate in proposals.candidates:
if candidate.proposal_id == args.proposal_id:
proposal = candidate
... | Executes the 'proposal vote' subcommand. Given a key file, a proposal
id and a vote value, it generates a batch of sawtooth_settings transactions
in a BatchList instance. The BatchList is file or submitted to a
validator. |
342,570 | def verify_claims(app_req, issuer=None):
if not issuer:
issuer = _get_issuer(app_req=app_req)
try:
float(str(app_req.get()))
float(str(app_req.get()))
except ValueError:
_re_raise_as(InvalidJWT,
% (app_req.get(), app_req.get()),... | Verify JWT claims.
All times must be UTC unix timestamps.
These claims will be verified:
- iat: issued at time. If JWT was issued more than an hour ago it is
rejected.
- exp: expiration time.
All exceptions are derived from
:class:`mozpay.exc.InvalidJWT`.
For expirations a
:cla... |
342,571 | def get_column(self, column_name):
with log_start_finish(
.format(
column_name, self.name),
logger):
extra_cols = _columns_for_table(self.name)
if column_name in extra_cols:
with log_start_finish(
... | Returns a column as a Series.
Parameters
----------
column_name : str
Returns
-------
column : pandas.Series |
342,572 | def outer_product_sum(A, B=None):
if B is None:
B = A
outer = np.einsum(, A, B)
return np.sum(outer, axis=0) | Computes the sum of the outer products of the rows in A and B
P = \Sum {A[i] B[i].T} for i in 0..N
Notionally:
P = 0
for y in A:
P += np.outer(y, y)
This is a standard computation for sigma points used in the UKF, ensemble
Kalman filter, etc., where A would be the... |
342,573 | def _set_selected_action(self, action):
assert action in self._action_sets
if self._selected_action is not None:
raise ValueError("The action has already been selected.")
self._selected_action = action | Setter method for the selected_action property. |
342,574 | def dump_report_content(self, request, result):
output = StringIO()
writer = csv.writer(output, **self.csv_kwargs)
writer.writerows([result.headers] + result.values)
return output.getvalue() | Dumps the content to a string, suitable to being written on a file.
:param result: The result being processed.
:return: string |
342,575 | def program_word(self, offset, word):
if(offset >= self.size):
raise AddressError("Offset({}) not in address space({})".format(offset, self.size))
self.repr_[offset].setvalue(word) | .. _program_word:
Write the word ``word`` to the memory at offset ``offset``.
Used to write the boot code.
Might raise AddressError_, if the offset exceeds the address space. |
342,576 | def _remove_features(layer):
layer_purpose = layer.keywords[]
layer_subcategory = layer.keywords.get(layer_purpose)
compulsory_field = get_compulsory_fields(layer_purpose, layer_subcategory)
inasafe_fields = layer.keywords[]
field_names = inasafe_fields.get(compulsory_field[])
... | Remove features which do not have information for InaSAFE or an invalid
geometry.
:param layer: The vector layer.
:type layer: QgsVectorLayer |
342,577 | def invalidate(*tables, **kwargs):
backend = get_backend()
db = kwargs.get(, )
if backend._patched:
for t in map(resolve_table, tables):
backend.keyhandler.invalidate_table(t, db) | Invalidate the current generation for one or more tables. The arguments
can be either strings representing database table names or models. Pass in
kwarg ``using`` to set the database. |
342,578 | def purge_portlets(portal):
logger.info("Purging portlets ...")
def remove_portlets(context_portlet):
mapping = portal.restrictedTraverse(context_portlet)
for key in mapping.keys():
if key not in PORTLETS_TO_PURGE:
logger.info("Skipping portlet: ".format(key))
... | Remove old portlets. Leave the Navigation portlet only |
342,579 | def trim(s, prefix=None, suffix=None, strict=False):
ensure_string(s)
has_prefix = prefix is not None
has_suffix = suffix is not None
if has_prefix == has_suffix:
raise ValueError(
"exactly one of either prefix or suffix must be provided")
if has_prefix:
ensure_str... | Trim a string, removing given prefix or suffix.
:param s: String to trim
:param prefix: Prefix to remove from ``s``
:param suffix: Suffix to remove from ``s``
:param strict: Whether the prefix or suffix must be present in ``s``.
By default, if the infix is not found, function will si... |
342,580 | def get_git_version(path):
branch_name = get_git_cleaned_branch_name(path)
mods = run_cmd(path, , , , )
dirty = if mods else
git_output = run_cmd(path, , , )
commits = git_output.strip().replace(, ).split()
num_commits_since_branch = len(commits)
short_commit_name ... | Get the GIT version. |
342,581 | def _getTotalLineCount(self):
if self._mode == self._FILE_WRITE_MODE:
self._file.flush()
return sum(1 for line in open(self._filename, self._FILE_READ_MODE)) | Returns: count of ALL lines in dataset, including header lines |
342,582 | def update_orders(self, market_id, instructions, customer_ref=None):
return self.make_api_request(
,
,
utils.get_kwargs(locals()),
model=models.UpdateExecutionReport,
) | Update non-exposure changing fields.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of `UpdateInstruction` objects
:param str customer_ref: Optional order identifier string |
342,583 | def show_linkinfo_output_show_link_info_linkinfo_version(self, **kwargs):
config = ET.Element("config")
show_linkinfo = ET.Element("show_linkinfo")
config = show_linkinfo
output = ET.SubElement(show_linkinfo, "output")
show_link_info = ET.SubElement(output, "show-link-in... | Auto Generated Code |
342,584 | async def debug(self, conn_id, name, cmd_args):
progress_callback = functools.partial(_on_progress, self, , conn_id)
resp = await self._execute(self._adapter.debug_sync, conn_id, name, cmd_args, progress_callback)
_raise_error(conn_id, , resp)
return resp.get() | Send a debug command to a device.
See :meth:`AbstractDeviceAdapter.debug`. |
342,585 | def draw_image(pixelmap, img):
for item in pixelmap:
color = item[2]
pixelbox = (item[0][0], item[0][1], item[1][0], item[1][1])
draw = ImageDraw.Draw(img)
draw.rectangle(pixelbox, fill=color) | Draws the image based on the given pixelmap. |
342,586 | def map_ipa_string(self, ipa_string, ignore=False, return_as_list=False, return_can_map=False):
acc = []
can_map = True
canonical = [(c.canonical_representation, ) for c in ipa_string]
split = split_using_dictionary(canonical, self, self.max_key_length, single_char_parsing=False... | Convert the given IPAString to a string
containing the corresponding ASCII IPA representation.
:param IPAString ipa_string: the IPAString to be parsed
:param bool ignore: if ``True``, ignore Unicode characters that are not IPA valid
:param bool return_as_list: if ``True``, return as a l... |
342,587 | def _apply_2d(self, func, axis):
ndim = self.ndim
axis = [self._get_axis_number(a) for a in axis]
indexer_axis = list(range(ndim))
for a in axis:
indexer_axis.remove(a)
indexer_axis = indexer_axis[0]
slicer = [slice(None, None)] * ndim
... | Handle 2-d slices, equiv to iterating over the other axis. |
342,588 | def p_dynamic_fixed_type(p):
reps = int(p[3])
base_type = p[1]
p[0] = (, reps, base_type) | T : T LBRAKET NUMBER RBRAKET |
342,589 | def fetch(self):
if self._newflg:
self._newflg = False
temp_dtgram = copy.deepcopy(self._dtgram)
for (bufid, buffer) in self._buffer.items():
temp_dtgram += self.submit(buffer, bufid=bufid)
return tuple(temp_dtgram)
return tuple(se... | Fetch datagram. |
342,590 | def name_of_the_nearest_place(feature, parent):
_ = feature, parent
layer = exposure_summary_layer()
if not layer:
return None
index = layer.fields().lookupField(
exposure_name_field[])
if index < 0:
return None
feature = next(layer.getFeatures())
return fea... | If the impact layer has a distance field, it will return the name
of the nearest place.
e.g. name_of_the_nearest_place() -> Tokyo |
342,591 | def request(self, cmds):
if isinstance(cmds, list):
cmd = .join(cmds)
elif isinstance(cmds, str) or isinstance(cmds, unicode):
cmd = cmds
node = etree.Element(qualify(, BASE_NS_1_0))
etree.SubElement(node, qualify(,
... | Single Execution element is permitted.
cmds can be a list or single command |
342,592 | def secure(self, targets, recursive):
for target in targets:
if os.path.isfile(target):
path, name = os.path.split(os.path.realpath(target))
target = Target(name, path)
target.secure()
else:
targets += self._fetchF... | Saves information about each target file and/or folder and
creates a hard link from the file(s) to the vault directory |
342,593 | def later(timeout, actor, method, *args, **kwargs):
call = getattr(actor, method, None)
if not callable(call):
raise IntervalError("later: The actor %s does not have the method \
%s." % (actor.get_id(), method))
if call.__class__.__name__ in ["TellWrapper", "TellRef... | Sets a timer that will call the *method* of the *actor* past *timeout*
seconds.
See example in :ref:`sample_inter`
:param int timeout: seconds until the method is called.
:param Proxy actor: actor to which make the call after *time* seconds.
:param Str. method: method of the *actor* to be called.
... |
342,594 | def getall(self, key, default=[]):
return self.data[key] if key in self.data else default | Return the list of all values for the specified key.
Arguments:
key (object): Key
default (list): Default value to return if the key does not
exist, defaults to ``[]``, i.e. an empty list.
Returns:
list: List of all values for the specified key if the key
... |
342,595 | def _load_stop_words(self, language=None):
self._logger.debug()
loaded = False
if language:
file_path = + language
loaded = self._parse_stop_words_file(os.path.join(PATH, file_path))
else:
for file in os.listdir(os.path.join(PATH, )):
... | Load stop words into __stop_words set.
Stop words will be loaded according to the language code
received during instantiation.
Args:
language: Language code.
Returns:
A boolean indicating whether a file was loaded. |
342,596 | def SetCacheMode(mode):
global cache_mode
if mode == "auto":
cache_mode = AUTO
elif mode == "force":
cache_mode = FORCE
elif mode == "cache":
cache_mode = CACHE
else:
raise ValueError("SCons.SConf.SetCacheMode: Unknown mode " + mode) | Set the Configure cache mode. mode must be one of "auto", "force",
or "cache". |
342,597 | def sign(privkey_bundle, plaintext):
if virtualchain.is_singlesig(privkey_bundle):
return sign_singlesig(privkey_bundle, plaintext)
elif virtualchain.is_multisig(privkey_bundle):
return sign_multisig(privkey_bundle, plaintext)
else:
raise ValueError("private key bundle is neithe... | Sign a subdomain plaintext with a private key bundle
Returns the base64-encoded scriptsig |
342,598 | def find_anomalies(errors, index, z_range=(0, 10)):
threshold = find_threshold(errors, z_range)
sequences = find_sequences(errors, threshold)
anomalies = list()
denominator = errors.mean() + errors.std()
for start, stop in sequences:
max_error = errors[start:stop + 1].max()
sc... | Find sequences of values that are anomalous.
We first find the ideal threshold for the set of errors that we have,
and then find the sequences of values that are above this threshold.
Lastly, we compute a score proportional to the maximum error in the
sequence, and finally return the index pairs that ... |
342,599 | def _input_as_multiline_string(self, data):
if data:
self.Parameters[]\
.on(super(Clearcut,self)._input_as_multiline_string(data))
return | Writes data to tempfile and sets -infile parameter
data -- list of lines |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.