Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
364,200 | def load(fp: Union[TextIO, str], load_module: types.ModuleType, **kwargs):
if isinstance(fp, str):
with open(fp) as f:
return loads(f.read(), load_module, **kwargs)
else:
return loads(fp.read(), load_module, **kwargs) | Convert a file name or file-like object containing stringified JSON into a JSGObject
:param fp: file-like object to deserialize
:param load_module: module that contains declarations for types
:param kwargs: arguments see: json.load for details
:return: JSGObject representing the json string |
364,201 | def reassign_proficiency_to_objective_bank(self, objective_id, from_objective_bank_id, to_objective_bank_id):
self.assign_objective_to_objective_bank(objective_id, to_objective_bank_id)
try:
self.unassign_objective_from_objective_bank(objective_id, from_objective_b... | Moves an ``Objective`` from one ``ObjectiveBank`` to another.
Mappings to other ``ObjectiveBanks`` are unaffected.
arg: objective_id (osid.id.Id): the ``Id`` of the
``Objective``
arg: from_objective_bank_id (osid.id.Id): the ``Id`` of the
current ``Objecti... |
364,202 | def map(cls, x, palette, limits, na_value=None):
n = len(limits)
pal = palette(n)[match(x, limits)]
try:
pal[pd.isnull(x)] = na_value
except TypeError:
pal = [v if not pd.isnull(v) else na_value for v in pal]
return pal | Map values to a discrete palette
Parameters
----------
palette : callable ``f(x)``
palette to use
x : array_like
Continuous values to scale
na_value : object
Value to use for missing values.
Returns
-------
out : array... |
364,203 | def _add_spin_magnitudes(self, structure):
for idx, site in enumerate(structure):
if getattr(site.specie, , None):
spin = site.specie._properties.get(, None)
sign = int(spin) if spin else 0
if spin:
new_properties = site.sp... | Replaces Spin.up/Spin.down with spin magnitudes specified
by mag_species_spin.
:param structure:
:return: |
364,204 | def _updateConstructorAndMembers(self):
syntheticMetaData = self._syntheticMetaData()
constructor = self._constructorFactory.makeConstructor(syntheticMetaData.originalConstructor(),
syntheticMetaData.syntheticMemberList(),
... | We overwrite constructor and accessors every time because the constructor might have to consume all
members even if their decorator is below the "synthesizeConstructor" decorator and it also might need to update
the getters and setters because the naming convention has changed. |
364,205 | def space_new(args):
r = fapi.create_workspace(args.project, args.workspace,
args.authdomain, dict())
fapi._check_response_code(r, 201)
if fcconfig.verbosity:
eprint(r.content)
return 0 | Create a new workspace. |
364,206 | def _set_cfm_detail(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=cfm_detail.cfm_detail, is_container=, presence=False, yang_name="cfm-detail", rest_name="cfm-detail", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register... | Setter method for cfm_detail, mapped from YANG variable /cfm_state/cfm_detail (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cfm_detail is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_cfm_de... |
364,207 | def fire(self, exclude=None, delay=True):
if delay:
else:
self._fire_task(self, exclude=exclude) | Notify everyone watching the event.
We are explicit about sending notifications; we don't just key off
creation signals, because the receiver of a ``post_save`` signal has no
idea what just changed, so it doesn't know which notifications to send.
Also, we could easily send mail accident... |
364,208 | def from_conll(this_class, stream):
stream = iter(stream)
sentence = this_class()
for line in stream:
line = line.strip()
if line:
sentence.append(Token.from_conll(line))
elif sentence:
return sentence
return se... | Construct a Sentence. stream is an iterable over strings where
each string is a line in CoNLL-X format. If there are multiple
sentences in this stream, we only return the first one. |
364,209 | def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message... | Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool |
364,210 | def find_region_end(self, lines):
if self.metadata and in self.metadata:
self.cell_type = self.metadata.pop()
else:
self.cell_type =
parser = StringParser(self.language or self.default_language)
for i, line in enumerate(lines):
... | Find the end of the region started with start and end markers |
364,211 | def days_to_liquidate_positions(positions, market_data,
max_bar_consumption=0.2,
capital_base=1e6,
mean_volume_window=5):
DV = market_data[] * market_data[]
roll_mean_dv = DV.rolling(window=mean_volume_window,
... | Compute the number of days that would have been required
to fully liquidate each position on each day based on the
trailing n day mean daily bar volume and a limit on the proportion
of a daily bar that we are allowed to consume.
This analysis uses portfolio allocations and a provided capital base
r... |
364,212 | def writeCmdMsg(self, msg):
ekm_log("(writeCmdMsg | " + self.getContext() + ") " + msg)
self.m_command_msg = msg | Internal method to set the command result string.
Args:
msg (str): Message built during command. |
364,213 | def listify(val, return_type=tuple):
if val is None:
return return_type()
elif isiterable(val):
return return_type(val)
else:
return return_type((val, )) | Examples:
>>> listify('abc', return_type=list)
['abc']
>>> listify(None)
()
>>> listify(False)
(False,)
>>> listify(('a', 'b', 'c'), return_type=list)
['a', 'b', 'c'] |
364,214 | def original_query_sequence_length(self):
if not self.is_aligned() or not self.entries.cigar:
return self.query_sequence_length
return sum([x[0] for x in self.cigar_array if re.match(,x[1])]) | Similar to get_get_query_sequence_length, but it also includes
hard clipped bases
if there is no cigar, then default to trying the sequence
:return: the length of the query before any clipping
:rtype: int |
364,215 | def quote_by_instruments(cls, client, ids):
base_url = "https://api.robinhood.com/instruments"
id_urls = ["{}/{}/".format(base_url, _id) for _id in ids]
return cls.quotes_by_instrument_urls(client, id_urls) | create instrument urls, fetch, return results |
364,216 | def user_absent(name, channel=14, **kwargs):
ret = {: name, : False, : , : {}}
user_id_list = __salt__[](name, channel, **kwargs)
if not user_id_list:
ret[] = True
ret[] =
return ret
if __opts__[]:
ret[] =
ret[] = None
ret[] = {: user_id_list}
... | Remove user
Delete all user (uid) records having the matching name.
name
string name of user to delete
channel
channel to remove user access from defaults to 14 for auto.
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- ... |
364,217 | def show_lowstate(**kwargs):
*
__opts__[] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__[])
st_.push_active()
chunks = st_.compile_low_chunks()... | List out the low data that will be applied to this minion
CLI Example:
.. code-block:: bash
salt '*' state.show_lowstate |
364,218 | def _mirror_penalized(self, f_values, idx):
assert len(f_values) >= 2 * len(idx)
m = np.max(np.abs(f_values))
for i in len(idx):
if f_values[idx[i]] > f_values[-1 - i]:
f_values[idx[i]] += m
else:
f_values[-1 - i] += m
retu... | obsolete and subject to removal (TODO),
return modified f-values such that for each mirror one becomes worst.
This function is useless when selective mirroring is applied with no
more than (lambda-mu)/2 solutions.
Mirrors are leading and trailing values in ``f_values``. |
364,219 | def file_like(name):
return (os.path.exists(name)
or os.path.dirname(name)
or name.endswith()
or not ident_re.match(os.path.splitext(name)[0])) | A name is file-like if it is a path that exists, or it has a
directory part, or it ends in .py, or it isn't a legal python
identifier. |
364,220 | def confirm(text, default=False, abort=False, prompt_suffix=,
show_default=True, err=False):
prompt = _build_prompt(text, prompt_suffix, show_default,
default and or )
while 1:
try:
echo(prompt, nl=False, err=err)
... | Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this
function will catch it and raise a :exc:`Abort` exception.
.. versionadded:: 4.0
Added the `err` parameter.
:param text: the question to ask.
:param default: the default for the prom... |
364,221 | def get_vulnerability(
source,
sink,
triggers,
lattice,
cfg,
interactive,
blackbox_mapping
):
nodes_in_constraint = [
secondary
for secondary in reversed(source.secondary_nodes)
if lattice.in_constraint(
secondary,
sink.cfg_node
... | Get vulnerability between source and sink if it exists.
Uses triggers to find sanitisers.
Note: When a secondary node is in_constraint with the sink
but not the source, the secondary is a save_N_LHS
node made in process_function in expr_visitor.
Args:
source(TriggerNod... |
364,222 | def _init_trace_logging(self, app):
enabled = not app.config.get(CONF_DISABLE_TRACE_LOGGING, False)
if not enabled:
return
self._trace_log_handler = LoggingHandler(
self._key, telemetry_channel=self._channel)
app.logger.addHandler(self._trace_log_handl... | Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. |
364,223 | def present(
name,
user=None,
fingerprint=None,
key=None,
port=None,
enc=None,
config=None,
hash_known_hosts=True,
timeout=5,
fingerprint_hash_type=None):
s home
directory, defaults to ".ssh/known_hosts". If no user is specified... | Verifies that the specified host is known by the specified user
On many systems, specifically those running with openssh 4 or older, the
``enc`` option must be set, only openssh 5 and above can detect the key
type.
name
The name of the remote host (e.g. "github.com")
Note that only a s... |
364,224 | def get_subdomain_DID_info(fqn, db_path=None, zonefiles_dir=None):
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
log.warn("Subdomain support is disabled")
return None
if db_path is None:
db_path = opts[]
if zonefiles_dir is None:
zonefiles_dir = ... | Get a subdomain's DID info.
Return None if not found |
364,225 | def predict(self, data):
self.assert_fitted()
with log_start_finish(.format(self.name), logger):
return predict(
data, self.predict_filters, self.model_fit, self.ytransform) | Predict a new data set based on an estimated model.
Parameters
----------
data : pandas.DataFrame
Data to use for prediction. Must contain all the columns
referenced by the right-hand side of the `model_expression`.
Returns
-------
result : panda... |
364,226 | def _copy_from(self, rhs):
self._manager = rhs._manager
self._rlist = type(rhs._rlist)(rhs._rlist)
self._region = rhs._region
self._ofs = rhs._ofs
self._size = rhs._size
for region in self._rlist:
region.increment_client_count()
if self._reg... | Copy all data from rhs into this instance, handles usage count |
364,227 | def OnCellFontSize(self, event):
with undo.group(_("Font size")):
self.grid.actions.set_attr("pointsize", event.size)
self.grid.ForceRefresh()
self.grid.update_attribute_toolbar()
event.Skip() | Cell font size event handler |
364,228 | def transpose_list(list_of_dicts):
res = {}
for d in list_of_dicts:
for k, v in d.items():
if k in res:
res[k].append(v)
else:
res[k] = [v]
return res | Transpose a list of dicts to a dict of lists
:param list_of_dicts: to transpose, as in the output from a parse call
:return: Dict of lists |
364,229 | def run(cmd, *args, **kwargs):
log.info( + list2cmdline(cmd))
kwargs.setdefault(, here)
kwargs.setdefault(, sys.platform == )
if not isinstance(cmd, list):
cmd = cmd.split()
return check_call(cmd, *args, **kwargs) | Echo a command before running it. Defaults to repo as cwd |
364,230 | def _sig(self, name, dtype=BIT, defVal=None):
if isinstance(dtype, HStruct):
if defVal is not None:
raise NotImplementedError()
container = dtype.fromPy(None)
for f in dtype.fields:
if f.name is not None:
r = self._... | Create signal in this unit |
364,231 | def run(data, samples, force, ipyclient):
data.dirs.outfiles = os.path.join(data.dirs.project, data.name+"_outfiles")
if not os.path.exists(data.dirs.outfiles):
os.mkdir(data.dirs.outfiles)
data.database = os.path.join(data.dirs.outfiles, data.name+".hdf5")
init_arrays(data... | Check all samples requested have been clustered (state=6), make output
directory, then create the requested outfiles. Excluded samples are already
removed from samples. |
364,232 | def convert_bam_to_bed(in_bam, out_file):
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
subprocess.check_call(["bamToBed", "-i", in_bam, "-tag", "NM"],
stdout=out_handle)
return out_file | Convert BAM to bed file using BEDTools. |
364,233 | def read(self, size=None):
if size is not None:
return self.__sf.read(size)
block_size = self.__class__.__block_size
b = bytearray()
received_bytes = 0
while 1:
partial = self.__sf.read(block_size)
b.extend(partial)
r... | Read a length of bytes. Return empty on EOF. If 'size' is omitted,
return whole file. |
364,234 | def probability_density(self, X):
self.check_fit()
U, V = self.split_matrix(X)
if self.theta == 0:
return np.multiply(U, V)
else:
num = np.multiply(np.multiply(-self.theta, self._g(1)), 1 + self._g(np.add(U, V)))
aux = np.multiply(self._g(U... | Compute density function for given copula family.
Args:
X: `np.ndarray`
Returns:
np.array: probability density |
364,235 | def _request_prepare(self, three_pc_key: Tuple[int, int],
recipients: List[str] = None,
stash_data: Optional[Tuple[str, str, str]] = None) -> bool:
if recipients is None:
recipients = self.node.nodestack.connecteds.copy()
primary... | Request preprepare |
364,236 | def hide_file(path):
__import__()
SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
SetFileAttributes.restype = ctypes.wintypes.BOOL
FILE_ATTRIBUTE_HIDDEN = 0x02
ret = SetFileAttributes(path, FILE_ATTRI... | Set the hidden attribute on a file or directory.
From http://stackoverflow.com/questions/19622133/
`path` must be text. |
364,237 | def ServiceWorker_startWorker(self, scopeURL):
assert isinstance(scopeURL, (str,)
), "Argument must be of type str. Received type: " % type(
scopeURL)
subdom_funcs = self.synchronous_command(,
scopeURL=scopeURL)
return subdom_funcs | Function path: ServiceWorker.startWorker
Domain: ServiceWorker
Method name: startWorker
Parameters:
Required arguments:
'scopeURL' (type: string) -> No description
No return value. |
364,238 | def leagues(self, year=2019):
if year not in self._leagues:
self._leagues[year] = leagues(year)
return self._leagues[year] | Return all leagues in dict {id0: league0, id1: league1}.
:params year: Year. |
364,239 | def minimal_selector(self, complete_selector):
if complete_selector not in self._selector_map:
raise KeyError("No value with selector .".format(complete_selector))
selector_components = complete_selector.split()
node = self._selector_tree
start = None
for i, component in enumerate(rever... | Returns the minimal selector that uniquely matches `complete_selector`.
Args:
complete_selector: A complete selector stored in the map.
Returns:
A partial selector that unambiguously matches `complete_selector`.
Raises:
KeyError: If `complete_selector` is not in the map. |
364,240 | def get_annotation_urls_and_checksums(species, release=None, ftp=None):
assert isinstance(species, (str, _oldstr)) or isinstance(species, Iterable)
if release is not None:
assert isinstance(release, int)
if ftp is not None:
assert isinstance(ftp, ftplib.FTP)
close_connect... | Get FTP URLs and checksums for Ensembl genome annotations.
Parameters
----------
species : str or list of str
The species or list of species for which to get genome annotations
(e.g., "Homo_sapiens").
release : int, optional
The release number to look up. If `None`, use late... |
364,241 | def list_categories(self, package_keyname, **kwargs):
get_kwargs = {}
get_kwargs[] = kwargs.get(, CATEGORY_MASK)
if in kwargs:
get_kwargs[] = kwargs[]
package = self.get_package_by_key(package_keyname, mask=)
categories = self.package_svc.getConfiguration(... | List the categories for the given package.
:param str package_keyname: The package for which to get the categories.
:returns: List of categories associated with the package |
364,242 | def log_estimator_evaluation_result(self, eval_results):
if not isinstance(eval_results, dict):
tf.logging.warning("eval_results should be directory for logging. Got %s",
type(eval_results))
return
global_step = eval_results[tf.GraphKeys.GLOBAL_STEP]
for key in sort... | Log the evaluation result for a estimator.
The evaluate result is a directory that contains metrics defined in
model_fn. It also contains a entry for global_step which contains the value
of the global step when evaluation was performed.
Args:
eval_results: dict, the result of evaluate() from a e... |
364,243 | def read(self, *args, **kwargs):
with self.open() as f:
return f.read(*args, **kwargs) | Reads the node as a file |
364,244 | def load_df_state(path_csv: Path)->pd.DataFrame:
df_state = pd.read_csv(
path_csv,
header=[0, 1],
index_col=[0, 1],
parse_dates=True,
infer_datetime_format=True,
)
return df_state | load `df_state` from `path_csv`
Parameters
----------
path_csv : Path
path to the csv file that stores `df_state` produced by a supy run
Returns
-------
pd.DataFrame
`df_state` produced by a supy run |
364,245 | def impact_path(self, value):
self._impact_path = value
if value is None:
self.action_show_report.setEnabled(False)
self.action_show_log.setEnabled(False)
self.report_path = None
self.log_path = None
else:
self.action_show_repo... | Setter to impact path.
:param value: The impact path.
:type value: str |
364,246 | def parse_words(self):
phones = self.parse_phones()
words = []
for i in self.word_intervals:
start = float(i[i.index()+7:
i.index()+12].strip().strip())
end = float(i[i.index()+7:
i.index()+12].strip(... | Parse TextGrid word intervals.
This method parses the word intervals in a TextGrid to extract each
word and each word's start and end times in the audio recording. For
each word, it instantiates the class Word(), with the word and its
start and end times as attributes of that cl... |
364,247 | def get_power_state(self, userid):
LOG.debug( % userid)
requestData = "PowerVM " + userid + " status"
action = "query power state of " % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
results = self._request(requestData)
with zvmutils.expect... | Get power status of a z/VM instance. |
364,248 | def output_file(self):
out_files = self.output_files
if len(out_files) != 1:
err_msg = "output_file property is only valid if there is a single"
err_msg += " output file. Here there are "
err_msg += "%d output files." %(len(out_files))
raise Value... | If only one output file return it. Otherwise raise an exception. |
364,249 | def _get_substitute_element(head, elt, ps):
if not isinstance(head, ElementDeclaration):
return None
return ElementDeclaration.getSubstitutionElement(head, elt, ps) | if elt matches a member of the head substitutionGroup, return
the GED typecode.
head -- ElementDeclaration typecode,
elt -- the DOM element being parsed
ps -- ParsedSoap Instance |
364,250 | def setTimer(self, timeout, description=None):
self.timerId += 1
timer = Timer(timeout, self.__timeoutHandler, (self.timerId, description))
timer.start()
self.timers[self.timerId] = timer
return self.timerId | Sets a timer.
:param description:
:param timeout: timeout in seconds
:return: the timerId |
364,251 | def get_activity_query_session(self):
if not self.supports_activity_query():
raise errors.Unimplemented()
return sessions.ActivityQuerySession(runtime=self._runtime) | Gets the ``OsidSession`` associated with the activity query service.
return: (osid.learning.ActivityQuerySession) - a
``ActivityQuerySession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_activity_query()`` is
``false``
... |
364,252 | def _combine(self, x, y):
if x is None or y is None:
return x or y
if x != y:
raise ValueError()
return x | Combines two constraints, raising an error if they are not compatible. |
364,253 | def validate_password_confirmation(self, value):
if value != self.initial_data[]:
raise serializers.ValidationError(_())
return value | password_confirmation check |
364,254 | def greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd):
r
for TM in [True, False]:
if TM:
e_zH, e_zV, z_eH = etaH, etaV, zetaH
else:
e_zH, e_zV, z_eH = zetaH, zetaV, etaH
Gam = np.sqrt((e_zH/e_zV)[:, None, ... | r"""Calculate Green's function for TM and TE.
This is a modified version of empymod.kernel.greenfct(). See the original
version for more information. |
364,255 | def graphcut_subprocesses(graphcut_function, graphcut_arguments, processes = None):
logger = Logger.getInstance()
if not processes: processes = multiprocessing.cpu_count()
if not int == type(processes) or processes <= 0: raise ArgumentError()
logger.debug(.format(multiprocessing... | Executes multiple graph cuts in parallel.
This can result in a significant speed-up.
Parameters
----------
graphcut_function : function
The graph cut to use (e.g. `graphcut_stawiaski`).
graphcut_arguments : tuple
List of arguments to pass to the respective subprocesses resp. the... |
364,256 | def update_scale(self, overflow):
iter_since_rescale = self._num_steps - self._last_rescale_iter
if overflow:
self._last_overflow_iter = self._num_steps
self._overflows_since_rescale += 1
percentage = self._overflows_since_rescale / float(iter_since_rescale)
... | dynamically update loss scale |
364,257 | def category(self, categories):
if isinstance(categories, list):
for c in categories:
self.add_category(c)
else:
self.add_category(categories) | Add categories assigned to this message
:rtype: list(Category) |
364,258 | def _find_package(self, root_package):
package = self.path.replace(root_package, "")
if package.endswith(".py"):
package = package[:-3]
package = package.replace(os.path.sep, MODULE_SEP)
root_package = get_folder_name(root_package)
package = root_package +... | Finds package name of file
:param root_package: root package
:return: package name |
364,259 | def compile_rcc(self, namespace, unknown):
rccfile = namespace.rccfile.name
qtcompile.compile_rcc(rccfile) | Compile qt resource files
:param namespace: namespace containing arguments from the launch parser
:type namespace: Namespace
:param unknown: list of unknown arguments
:type unknown: list
:returns: None
:rtype: None
:raises: None |
364,260 | def set_level(self, level):
return H2OFrame._expr(expr=ExprNode("setLevel", self, level), cache=self._ex._cache) | A method to set all column values to one of the levels.
:param str level: The level at which the column will be set (a string)
:returns: H2OFrame with entries set to the desired level. |
364,261 | def flatten(x):
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, (binary, unicode)):
for els in flatten(el):
yield els
else:
yield el | flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10... |
364,262 | def _place_ticks_vertical(self):
for tick, label in zip(self.ticks, self.ticklabels):
y = self.convert_to_pixels(tick)
label.place_configure(y=y) | Display the ticks for a vertical slider. |
364,263 | def hdrval(cls):
hdrmap = {: }
hdrmap.update(cls.hdrval_objfun)
hdrmap.update({: , : , u(): })
return hdrmap | Construct dictionary mapping display column title to
IterationStats entries. |
364,264 | def engine_from_environment() -> Engine:
api_key = os.environ.get(ENV_API_KEY)
if not api_key:
raise EnvironmentError(
.format(ENV_API_KEY))
default_project_id = os.environ.get(ENV_DEFAULT_PROJECT_ID)
return Engine(api_key=api_key, default_project_id=default_project_id) | Returns an Engine instance configured using environment variables.
If the environment variables are set, but incorrect, an authentication
failure will occur when attempting to run jobs on the engine.
Required Environment Variables:
QUANTUM_ENGINE_PROJECT: The name of a google cloud project, with t... |
364,265 | def reduce_hierarchy(x, depth):
_x = x.split()
depth = len(_x) + depth - 1 if depth < 0 else depth
return .join(_x[0:(depth + 1)]) | Reduce the hierarchy (depth by `|`) string to the specified level |
364,266 | def unpack_rsp(cls, rsp_pb):
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
raw_order_list = rsp_pb.s2c.orderList
order_list = [OrderListQuery.parse_order(rsp_pb, order) for order in raw_order_list]
return RET_OK, "", order_list | Convert from PLS response to user response |
364,267 | def append_item(self, item):
did_remove = self.remove_exit()
item.menu = self
self.items.append(item)
if did_remove:
self.add_exit() | Add an item to the end of the menu before the exit item.
Args:
item (MenuItem): The item to be added. |
364,268 | def _updateMinDutyCycles(self):
if self._globalInhibition or self._inhibitionRadius > self._numInputs:
self._updateMinDutyCyclesGlobal()
else:
self._updateMinDutyCyclesLocal() | Updates the minimum duty cycles defining normal activity for a column. A
column with activity duty cycle below this minimum threshold is boosted. |
364,269 | def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
if assoc_handle is None:
raise ValueError("assoc_handle must not be None")
if dumb:
key = self._dumb_key
else:
key = self._normal_key
assoc = self.store.getAssociat... | Get the association with the specified handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with that
handle was found.
@returntype: L{openid.association.As... |
364,270 | def get_urls(self):
ret = super(SimpleRouter, self).get_urls()
for router in self.nested_routers:
ret.extend(router.get_urls())
return ret | Returns a list of urls including all NestedSimpleRouter urls |
364,271 | def generate_obj(self):
secret_obj = {}
if self.existing:
secret_obj = deepcopy(self.existing)
for key in self.keys:
key_name = key[]
if self.existing and \
key_name in self.existing and \
not key.get():
... | Generates the secret object, respecting existing information
and user specified options |
364,272 | def decrypt(receiver_prvhex: str, msg: bytes) -> bytes:
pubkey = msg[0:65]
encrypted = msg[65:]
sender_public_key = hex2pub(pubkey.hex())
private_key = hex2prv(receiver_prvhex)
aes_key = derive(private_key, sender_public_key)
return aes_decrypt(aes_key, encrypted) | Decrypt with eth private key
Parameters
----------
receiver_pubhex: str
Receiver's ethereum private key hex string
msg: bytes
Data to decrypt
Returns
-------
bytes
Plain text |
364,273 | def get_constant_state(self):
ret = self.constant_states[self.next_constant_state]
self.next_constant_state += 1
return ret | Read state that was written in "first_part" mode.
Returns:
a structure |
364,274 | def _extract_number_of_taxa(self):
n_taxa = dict()
for i in self.seq_records:
if i.gene_code not in n_taxa:
n_taxa[i.gene_code] = 0
n_taxa[i.gene_code] += 1
number_taxa = sorted([i for i in n_taxa.values()], reverse=True)[0]
self.number_ta... | sets `self.number_taxa` to the number of taxa as string |
364,275 | def cur_space(self, name=None):
if name is None:
return self._impl.model.currentspace.interface
else:
self._impl.model.currentspace = self._impl.spaces[name]
return self.cur_space() | Set the current space to Space ``name`` and return it.
If called without arguments, the current space is returned.
Otherwise, the current space is set to the space named ``name``
and the space is returned. |
364,276 | def app_restart(name, profile, **kwargs):
ctx = Context(**kwargs)
ctx.execute_action(, **{
: ctx.repo.create_secure_service(),
: ctx.locator,
: name,
: profile,
}) | Restart application.
Executes ```cocaine-tool app pause``` and ```cocaine-tool app start``` sequentially.
It can be used to quickly change application profile. |
364,277 | def put(self):
try:
_import_templates(force=True)
return self.make_response()
except:
self.log.exception()
return self.make_response(, HTTP.SERVER_ERROR) | Re-import all templates, overwriting any local changes made |
364,278 | def axis_angle(self):
qw, qx, qy, qz = self.quaternion
theta = 2 * np.arccos(qw)
omega = np.array([1,0,0])
if theta > 0:
rx = qx / np.sqrt(1.0 - qw**2)
ry = qy / np.sqrt(1.0 - qw**2)
rz = qz / np.sqrt(1.0 - qw**2)
omega = np.array(... | :obj:`numpy.ndarray` of float: The axis-angle representation for the rotation. |
364,279 | def extract_interesting_date_ranges(returns):
returns_dupe = returns.copy()
returns_dupe.index = returns_dupe.index.map(pd.Timestamp)
ranges = OrderedDict()
for name, (start, end) in PERIODS.items():
try:
period = returns_dupe.loc[start:end]
if len(period) == 0:
... | Extracts returns based on interesting events. See
gen_date_range_interesting.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
ranges : OrderedDict
Date r... |
364,280 | def get(self, endpoint=, url=, params=None, use_api_key=False):
return self._request(, endpoint, url, params=params, use_api_key=use_api_key) | Perform a get for a json API endpoint.
:param string endpoint: Target endpoint. (Optional).
:param string url: Override the endpoint and provide the full url (eg for pagination). (Optional).
:param dict params: Provide parameters to pass to the request. (Optional).
:return: Response jso... |
364,281 | def read_zipfile(self, encoding=):
from zipfile import ZipFile
with ZipFile(self.abspath) as zipped:
for num, zip_name in enumerate(zipped.namelist()):
return zipped.open(zip_name).read().decode(encoding) | READ FIRST FILE IN ZIP FILE
:param encoding:
:return: STRING |
364,282 | def report_many(self, event_list, metadata=None, block=None):
failed_list = []
for index, event in enumerate(event_list):
queued_successfully = self.report(event, metadata, block)
if not queued_successfully:
failed_list.append((index, event))
retu... | Reports all the given events to Alooma by formatting them properly and
placing them in the buffer to be sent by the Sender instance
:param event_list: A list of dicts / strings representing events
:param metadata: (Optional) A dict with extra metadata to be attached to
t... |
364,283 | def _f_gene(sid, prefix="G_"):
sid = sid.replace(SBML_DOT, ".")
return _clip(sid, prefix) | Clips gene prefix from id. |
364,284 | def _recurse(data, obj):
content = _ContentManager()
for child in obj.get_children():
if isinstance(child, mpl.spines.Spine):
continue
if isinstance(child, mpl.axes.Axes):
ax = axes.Axes(data, child)
if ax.is_colorbar:
... | Iterates over all children of the current object, gathers the contents
contributing to the resulting PGFPlots file, and returns those. |
364,285 | def patch_api_service(self, name, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.patch_api_service_with_http_info(name, body, **kwargs)
else:
(data) = self.patch_api_service_with_http_info(name, body, **kwargs)
return data | patch_api_service # noqa: E501
partially update the specified APIService # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_api_service(name, body, async_req=True)
>>> re... |
364,286 | def mixin_function_or_method(target, routine, name=None, isbound=False):
function = None
if isfunction(routine):
function = routine
elif ismethod(routine):
function = get_method_function(routine)
else:
raise Mixin.MixInError(
... | Mixin a routine into the target.
:param routine: routine to mix in target.
:param str name: mixin name. Routine name by default.
:param bool isbound: If True (False by default), the mixin result is a
bound method to target. |
364,287 | def set_tag(self, ip_dest, next_hop, **kwargs):
return self._set_route(ip_dest, next_hop, **kwargs) | Set the tag value for the specified route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
dest... |
364,288 | def get_submissions(self, url):
response = self.client.get(url, params={: self.options[]})
submissions = [x[] for x in response.json()[][]]
return submissions | Connects to Reddit and gets a JSON representation of submissions.
This JSON data is then processed and returned.
url: A url that requests for submissions should be sent to. |
364,289 | def distortImage(self, image):
correct
image = imread(image)
(imgHeight, imgWidth) = image.shape[:2]
mapx, mapy = self.getDistortRectifyMap(imgWidth, imgHeight)
return cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
borderValue=(0, 0, 0)) | opposite of 'correct' |
364,290 | def peek_step(self, val: ArrayValue,
sn: "DataNode") -> Tuple[Optional[Value], "DataNode"]:
try:
return val[self.index], sn
except (IndexError, KeyError, TypeError):
return None, sn | Return entry value addressed by the receiver + its schema node.
Args:
val: Current value (array).
sn: Current schema node. |
364,291 | def untag(name, tag_name):
with LOCK:
by_tag = TAGS.get(tag_name, None)
if not by_tag:
return False
try:
by_tag.remove(name)
if not by_tag:
TAGS.pop(tag_name)
return True
except KeyError:
... | Remove the given tag from the given metric.
Return True if the metric was tagged, False otherwise |
364,292 | def _compute_subplot_domains(widths, spacing):
widths_sum = float(sum(widths))
total_spacing = (len(widths) - 1) * spacing
widths = [(w / widths_sum)*(1-total_spacing) for w in widths]
domains = []
for c in range(len(widths)):
domain_start = c * spacing + sum(widths[:c])
d... | Compute normalized domain tuples for a list of widths and a subplot
spacing value
Parameters
----------
widths: list of float
List of the desired withs of each subplot. The length of this list
is also the specification of the number of desired subplots
spacing: float
Spacing... |
364,293 | def indication(self, pdu):
if _debug: Node._debug("indication(%s) %r", self.name, pdu)
if not self.lan:
raise ConfigurationError("unbound node")
if pdu.pduSource is None:
pdu.pduSource = self.address
elif (not self.spoofing) a... | Send a message. |
364,294 | def add(self, child):
if isinstance(child, FatComponent):
self.add_child_component(child)
else:
Fat.add(self, child) | Adds a typed child object to the component type.
@param child: Child object to be added. |
364,295 | def gene_filter(self, query, mongo_query):
LOG.debug()
gene_query = []
if query.get() and query.get():
gene_query.append({: {: query[]}})
gene_query.append({: {: query[]}})
mongo_query[]=gene_query
else:
if query.get():
... | Adds gene-related filters to the query object
Args:
query(dict): a dictionary of query filters specified by the users
mongo_query(dict): the query that is going to be submitted to the database
Returns:
mongo_query(dict): returned object contains gene and panel-relat... |
364,296 | def start(self):
if self.stream is None:
from pyaudio import PyAudio, paInt16
self.pa = PyAudio()
self.stream = self.pa.open(
16000, 1, paInt16, True, frames_per_buffer=self.chunk_size
)
self._wrap_stream_read(self.stream)
... | Start listening from stream |
364,297 | def about_axis(cls, center, angle, axis, invert=False):
return Translation(center) * \
Rotation.from_properties(angle, axis, invert) * \
Translation(-center) | Create transformation that represents a rotation about an axis
Arguments:
| ``center`` -- Point on the axis
| ``angle`` -- Rotation angle
| ``axis`` -- Rotation axis
| ``invert`` -- When True, an inversion rotation is constructed
... |
364,298 | def par_y1step(i):
r
global mp_Y1
grpind = slice(mp_grp[i], mp_grp[i+1])
XU1 = mp_X[grpind] + 1/mp_alpha*mp_U1[grpind]
if mp_wl1.shape[mp_axisM] is 1:
gamma = mp_lmbda/(mp_alpha**2*mp_rho)*mp_wl1
else:
gamma = mp_lmbda/(mp_alpha**2*mp_rho)*mp_wl1[grpind]
Y1 = sp.prox_l1(XU1,... | r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}_{1,G_i}`, one of the disjoint problems of
optimizing :math:`\mathbf{y}_1`.
Parameters
----------
i : int
Index of grouping to update |
364,299 | def pot_for_component(pot, q, component=1, reverse=False):
if component==1:
return pot
elif component==2:
if reverse:
return pot/q + 0.5*(q-1)/q
else:
return q*pot - 0.5 * (q-1)
else:
raise NotImplementedError | q for secondaries should already be flipped (via q_for_component) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.