Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
374,500 | def find_copy_constructor(type_):
copy_ = type_.constructors(
lambda x: is_copy_constructor(x),
recursive=False,
allow_empty=True)
if copy_:
return copy_[0]
return None | Returns reference to copy constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the copy constructor |
374,501 | def get_stock_basicinfo(self, market, stock_type=SecurityType.STOCK, code_list=None):
param_table = {: market, : stock_type}
for x in param_table:
param = param_table[x]
if param is None or is_str(param) is False:
error_str = ERROR_STR_PREFIX + "the type ... | 获取指定市场中特定类型的股票基本信息
:param market: 市场类型,futuquant.common.constant.Market
:param stock_type: 股票类型, futuquant.common.constant.SecurityType
:param code_list: 如果不为None,应该是股票code的iterable类型,将只返回指定的股票信息
:return: (ret_code, content)
ret_code 等于RET_OK时, content为Pandas.DataFrame数据,... |
374,502 | def get_item_abspath(self, identifier):
admin_metadata = self.get_admin_metadata()
uuid = admin_metadata["uuid"]
dataset_cache_abspath = os.path.join(self._irods_cache_abspath, uuid)
mkdir_parents(dataset_cache_abspath)
irods_item_path = os.path.join(s... | Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed |
374,503 | def remove_relation(post_id, tag_id):
entry = TabPost2Tag.delete().where(
(TabPost2Tag.post_id == post_id) &
(TabPost2Tag.tag_id == tag_id)
)
entry.execute()
MCategory.update_count(tag_id) | Delete the record of post 2 tag. |
374,504 | def _perform_validation(self, path, value, results):
name = path if path != None else "value"
value = ObjectReader.get_value(value)
super(ArraySchema, self)._perform_validation(path, value, results)
if value == None:
return
if isinstance(value, list) or is... | Validates a given value against the schema and configured validation rules.
:param path: a dot notation path to the value.
:param value: a value to be validated.
:param results: a list with validation results to add new results. |
374,505 | def correlation(s, o):
if s.size == 0:
corr = np.NaN
else:
corr = np.corrcoef(o, s)[0, 1]
return corr | correlation coefficient
input:
s: simulated
o: observed
output:
correlation: correlation coefficient |
374,506 | def on_delete(resc, req, resp, rid):
signals.pre_req.send(resc.model)
signals.pre_req_delete.send(resc.model)
model = find(resc.model, rid)
goldman.sess.store.delete(model)
resp.status = falcon.HTTP_204
signals.post_req.send(resc.model)
signals.post_req_delete.send(resc.model) | Delete the single item
Upon a successful deletion an empty bodied 204
is returned. |
374,507 | def store_many_vectors(self, hash_name, bucket_keys, vs, data):
if data is None:
data = itertools.repeat(data)
for v, k, d in zip(vs, bucket_keys, data):
self.store_vector(hash_name, k, v, d) | Store a batch of vectors.
Stores vector and JSON-serializable data in bucket with specified key. |
374,508 | def extract_paths(self, paths, ignore_nopath):
try:
super().extract_paths(
paths=paths,
ignore_nopath=ignore_nopath,
)
except ExtractPathError as err:
LOGGER.debug(
, self.vm.name(), err.message
)
... | Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try extracting the
files with guestfs.
Args:
... |
374,509 | def get_default_query_from_module(module):
if isinstance(module, types.ModuleType):
return module.__dict__.get(_SQL_MODULE_LAST, None)
return None | Given a %%sql module return the default (last) query for the module.
Args:
module: the %%sql module.
Returns:
The default query associated with this module. |
374,510 | def has_equal_ast(state, incorrect_msg=None, code=None, exact=True, append=None):
if utils.v2_only():
state.assert_is_not(["object_assignments"], "has_equal_ast", ["check_object"])
state.assert_is_not(["function_calls"], "has_equal_ast", ["check_function"])
if code and incorrect_msg is Non... | Test whether abstract syntax trees match between the student and solution code.
``has_equal_ast()`` can be used in two ways:
* As a robust version of ``has_code()``. By setting ``code``, you can look for the AST representation of ``code`` in the student's submission.
But be aware that ``a`` and ``a = 1`... |
374,511 | def runGetOutput(cmd, raiseOnFailure=False, encoding=sys.getdefaultencoding()):
&&|s output will automatically be decoded using the provided codec (e.x. "utf-8" or "ascii").
If None or False-ish, data will not be decoded (i.e. in python3 will be "bytes" type)
If unsure, leave t... | runGetOutput - Simply runs a command and returns the output as a string. Use #runGetResults if you need something more complex.
@param cmd <str/list> - String of command and arguments, or list of command and arguments
If cmd is a string, the command will be executed as if ran exactly as wr... |
374,512 | def python_type(self):
from ambry.valuetype import resolve_value_type
if self.valuetype and resolve_value_type(self.valuetype):
return resolve_value_type(self.valuetype)._pythontype
elif self.datatype:
try:
return self.types[self.datatype][1]
... | Return the python type for the row, possibly getting it from a valuetype reference |
374,513 | def run(self, schedule_type, lookup_id, **kwargs):
log = self.get_logger(**kwargs)
log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id))
task_run = QueueTaskRun()
task_run.task_id = self.request.id or uuid4()
task_run.started_at = now()
tr_qs = QueueTaskRun... | Loads Schedule linked to provided lookup |
374,514 | def _make_meta(self, tracker_url, root_name, private, progress):
if self._fifo:
piece_size_exp = 20
else:
total_size = self._calc_size()
if total_size:
piece_size_exp = int(math.log(total_size) / math.log(2))... | Create torrent dict. |
374,515 | def start_runs(
logdir,
steps,
run_name,
thresholds,
mask_every_other_prediction=False):
tf.compat.v1.reset_default_graph()
tf.compat.v1.set_random_seed(42)
distribution = tf.compat.v1.distributions.Normal(loc=0., scale=142.)
examples = tf.concat([true_reds, tru... | Generate a PR curve with precision and recall evenly weighted.
Arguments:
logdir: The directory into which to store all the runs' data.
steps: The number of steps to run for.
run_name: The name of the run.
thresholds: The number of thresholds to use for PR curves.
mask_every_other_prediction: Whe... |
374,516 | def assign_edge_colors_and_widths(self):
if self.style.edge_widths is None:
if not self.style.edge_style["stroke-width"]:
self.style.edge_style.pop("stroke-width")
self.style.edge_style.pop("stroke")
self.edge_widths = [None... | Resolve conflict of 'node_color' and 'node_style['fill'] args which are
redundant. Default is node_style.fill unless user entered node_color.
To enter multiple colors user must use node_color not style fill.
Either way, we build a list of colors to pass to Drawing.node_colors
which is ... |
374,517 | def visit_tryexcept(self, node):
trys = ["try:\n%s" % self._stmt_list(node.body)]
for handler in node.handlers:
trys.append(handler.accept(self))
if node.orelse:
trys.append("else:\n%s" % self._stmt_list(node.orelse))
return "\n".join(trys) | return an astroid.TryExcept node as string |
374,518 | def peek_step(self, val: ArrayValue,
sn: "DataNode") -> Tuple[ObjectValue, "DataNode"]:
keys = self.parse_keys(sn)
for en in val:
flag = True
try:
for k in keys:
if en[k] != keys[k]:
flag = Fal... | Return the entry addressed by the receiver + its schema node.
Args:
val: Current value (array).
sn: Current schema node. |
374,519 | def clientConnected(self, proto):
proto.uniqueName = % (self.next_id,)
self.next_id += 1
self.clients[proto.uniqueName] = proto | Called when a client connects to the bus. This method assigns the
new connection a unique bus name. |
374,520 | def set_thresholds(self, touch, release):
assert touch >= 0 and touch <= 255,
assert release >= 0 and release <= 255,
for i in range(12):
self._i2c_retry(self._device.write8, MPR121_TOUCHTH_0 + 2*i, touch)
self._i2c_retry(self._device.write8, MPR121_RE... | Set the touch and release threshold for all inputs to the provided
values. Both touch and release should be a value between 0 to 255
(inclusive). |
374,521 | def page_uri_handler(context, content, pargs, kwargs):
uri = pargs[0]
return url_for(, uri=uri) | Shortcode for getting the link to internal pages using the flask `url_for`
method.
Activate with 'shortcodes' template filter. Within the content use the
chill page_uri shortcode: "[chill page_uri idofapage]". The argument is the
'uri' for a page that chill uses.
Does not verify the link to see if... |
374,522 | def _grab_history(self):
default_location = None
config = self.setup_cfg.config
if config and config.has_option(, ):
default_location = config.get(, )
history_file = self.vcs.history_file(location=default_location)
if not history_file:
logger.warn... | Calculate the needed history/changelog changes
Every history heading looks like '1.0 b4 (1972-12-25)'. Extract them,
check if the first one matches the version and whether it has a the
current date. |
374,523 | def health(self, session=None):
BJ = jobs.BaseJob
payload = {}
scheduler_health_check_threshold = timedelta(seconds=conf.getint(,
))
... | An endpoint helping check the health status of the Airflow instance,
including metadatabase and scheduler. |
374,524 | def apply_projection(projection, value):
if isinstance(value, Sequence):
return [
apply_projection(projection, item)
for item in value
]
elif not isinstance(value, Mapping):
return value
try:
current_projection = [p[0] for ... | Apply projection. |
374,525 | def find_neighbor_pores(self, pores, mode=, flatten=True,
include_input=False):
r
pores = self._parse_indices(pores)
if sp.size(pores) == 0:
return sp.array([], ndmin=1, dtype=int)
if not in self._am.keys():
self.get_adjacency_matrix(f... | r"""
Returns a list of pores that are direct neighbors to the given pore(s)
Parameters
----------
pores : array_like
Indices of the pores whose neighbors are sought
flatten : boolean
If ``True`` (default) the returned result is a compressed array of
... |
374,526 | def get_overridden_calculated_entry(self):
if not bool(self._my_map[]):
raise errors.IllegalState()
mgr = self._get_provider_manager()
if not mgr.supports_grade_entry_lookup():
raise errors.OperationFailed()
lookup_session = mgr.get_grade_entry_l... | Gets the calculated entry this entry overrides.
return: (osid.grading.GradeEntry) - the calculated entry
raise: IllegalState - ``overrides_calculated_entry()`` is
``false``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must b... |
374,527 | def is_applicable(self, date_string, strip_timezone=False, settings=None):
if strip_timezone:
date_string, _ = pop_tz_offset_from_string(date_string, as_offset=False)
date_string = self._translate_numerals(date_string)
if settings.NORMALIZE:
date_string = normal... | Check if the locale is applicable to translate date string.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param strip_timezone:
If True, timezone is stripped from date string.
:type str... |
374,528 | def clipValue(self, value, minValue, maxValue):
return min(max(value, minValue), maxValue) | Makes sure that value is within a specific range.
If not, then the lower or upper bounds is returned |
374,529 | def fit_classifier(self, name, analytes, method, samples=None,
subset=None, filt=True, sort_by=0, **kwargs):
if samples is not None:
subset = self.make_subset(samples)
self.get_focus(subset=subset, filt=filt)
c = classifier(analytes... | Create a clustering classifier based on all samples, or a subset.
Parameters
----------
name : str
The name of the classifier.
analytes : str or iterable
Which analytes the clustering algorithm should consider.
method : str
Which clustering al... |
374,530 | def nx_contracted_nodes(G, u, v, self_loops=True, inplace=False):
import itertools as it
if G.is_directed():
in_edges = ((w, u, d) for w, x, d in G.in_edges(v, data=True)
if self_loops or w != u)
out_edges = ((u, w, d) for x, w, d in G.out_edges(v, data=True)
... | copy of networkx function with inplace modification
TODO: commit to networkx |
374,531 | def aoi(self, **kwargs):
g = self._parse_geoms(**kwargs)
if g is None:
return self
else:
return self[g] | Subsets the Image by the given bounds
Args:
bbox (list): optional. A bounding box array [minx, miny, maxx, maxy]
wkt (str): optional. A WKT geometry string
geojson (str): optional. A GeoJSON geometry dictionary
Returns:
image: an image instance of the sa... |
374,532 | def poly(self, return_coeffs=False):
p = self.bpoints()
coeffs = (p[0] - 2*p[1] + p[2], 2*(p[1] - p[0]), p[0])
if return_coeffs:
return coeffs
else:
return np.poly1d(coeffs) | returns the quadratic as a Polynomial object. |
374,533 | def mosaic_inline(self, imagelist, bg_ref=None, trim_px=None,
merge=False, allow_expand=True, expand_pad_deg=0.01,
max_expand_pct=None,
update_minmax=True, suppress_callback=False):
header = self.get_header()
((xrot_ref,... | Drops new images into the current image (if there is room),
relocating them according the WCS between the two images. |
374,534 | def exceptions(self):
def make_param(text):
if in text and in text:
word_split = list(split_delimited(, , text))
if word_split[1] != :
text = .join([word_split[0], ] + word_split[1:])
else:
... | Returns a list of ParamDoc objects (with empty names) of the
exception tags for the function.
>>> comments = parse_comments_for_file('examples/module_closure.js')
>>> fn1 = FunctionDoc(comments[1])
>>> fn1.exceptions[0].doc
'Another exception'
>>> fn1.exceptions[1].doc
... |
374,535 | def copy_unit_properties(self, sorting, unit_ids=None):
if unit_ids is None:
unit_ids = sorting.get_unit_ids()
if isinstance(unit_ids, int):
curr_property_names = sorting.get_unit_property_names(unit_id=unit_ids)
for curr_property_name in curr_property_names:... | Copy unit properties from another sorting extractor to the current
sorting extractor.
Parameters
----------
sorting: SortingExtractor
The sorting extractor from which the properties will be copied
unit_ids: (array_like, int)
The list (or single value) of ... |
374,536 | def iter_links(operations, page):
for operation, ns, rule, func in operations:
yield Link.for_(
operation=operation,
ns=ns,
type=ns.subject_name,
qs=page.to_items(),
) | Generate links for an iterable of operations on a starting page. |
374,537 | def resume_transfer_operation(self, operation_name):
self.get_conn().transferOperations().resume(name=operation_name).execute(num_retries=self.num_retries) | Resumes an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None |
374,538 | def pid(self):
try:
return self._pid
except AttributeError:
self._pid = os.getpid()
return self._pid | The pid of the process associated to the scheduler. |
374,539 | def get_unique_families(hkls):
def is_perm(hkl1, hkl2):
h1 = np.abs(hkl1)
h2 = np.abs(hkl2)
return all([i == j for i, j in zip(sorted(h1), sorted(h2))])
unique = collections.defaultdict(list)
for hkl1 in hkls:
found = False
for hkl2 in unique.keys():
... | Returns unique families of Miller indices. Families must be permutations
of each other.
Args:
hkls ([h, k, l]): List of Miller indices.
Returns:
{hkl: multiplicity}: A dict with unique hkl and multiplicity. |
374,540 | def parse_config_h(fp, vars=None):
if vars is None:
vars = {}
define_rx = re.compile("
undef_rx = re.compile("/[*]
while True:
line = fp.readline()
if not line:
break
m = define_rx.match(line)
if m:
n, v = m.group(1, 2)
t... | Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary. |
374,541 | def replace_word_tokens(string, language):
words = mathwords.word_groups_for_language(language)
operators = words[].copy()
if in words:
operators.update(words[])
for operator in list(operators.keys()):
if operator in string:
string = string.replace(operator, oper... | Given a string and an ISO 639-2 language code,
return the string with the words replaced with
an operational equivalent. |
374,542 | def console(self, ttynum=-1, stdinfd=0, stdoutfd=1, stderrfd=2, escape=1):
if not self.running:
return False
return _lxc.Container.console(self, ttynum, stdinfd, stdoutfd,
stderrfd, escape) | Attach to console of running container. |
374,543 | def send(self,text):
self.s.write(text)
time.sleep(0.001*len(text)) | Send a string to the PiLite, can be simple text or a $$$ command |
374,544 | def add_json(self, json_obj, **kwargs):
return self.add_bytes(encoding.Json().encode(json_obj), **kwargs) | Adds a json-serializable Python dict as a json file to IPFS.
.. code-block:: python
>>> c.add_json({'one': 1, 'two': 2, 'three': 3})
'QmVz9g7m5u3oHiNKHj2CJX1dbG1gtismRS3g9NaPBBLbob'
Parameters
----------
json_obj : dict
A json-serializable Python di... |
374,545 | def load(obj, settings_module, identifier="py", silent=False, key=None):
mod, loaded_from = get_module(obj, settings_module, silent)
if mod and loaded_from:
obj.logger.debug("py_loader: {}".format(mod))
else:
obj.logger.debug(
"py_loader: %s (Ignoring, Not Found)", settings... | Tries to import a python module |
374,546 | def swap(self, fn, *args, **kwargs):
s current state, `args`,
and `kwargs`. The return value of this invocation becomes the new value
of the atom. Returns the new value.
:param fn: A function which will be passed the current state. Should
return a new state. This absolutely ... | Given a mutator `fn`, calls `fn` with the atom's current state, `args`,
and `kwargs`. The return value of this invocation becomes the new value
of the atom. Returns the new value.
:param fn: A function which will be passed the current state. Should
return a new state. This absolutel... |
374,547 | def set(self, obj, id, payload, action=, async=False):
self.url = .format(self.base_url, obj, id)
self.method =
if action:
self.url += .format(action)
self.payload = json.dumps(payload)
if async:
session = FuturesSession()
return sess... | Function set
Set an object by id
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@param action: specific action of an object ('power'...)
@param payload: the dict of the payload
@param async: should this request be async... |
374,548 | def profile_cancel(self, query_id, timeout=10):
result = Result(*self.perform_request(**{
: ,
: .format(query_id),
: {
: timeout
}
}))
return result | Cancel the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result |
374,549 | def OnExpandAll(self):
root = self.tree.GetRootItem()
fn = self.tree.Expand
self.traverse(root, fn)
self.tree.Expand(root) | expand all nodes |
374,550 | def onStart(self, event):
c = event.container
print * 5, , c
kv = lambda s: s.split(, 1)
env = {k: v for (k, v) in (kv(s) for s in c.attrs[][])}
print env | Display the environment of a started container |
374,551 | def fit(self, counts_df, val_set=None):
if self.stop_crit == :
if val_set is None:
raise ValueError("If is set to , must provide a validation set.")
if self.verbose:
self._print_st_msg()
self._process_data(counts_df)
if self.verbose:
self._print_data_info()
if (val_set is not None) an... | Fit Hierarchical Poisson Model to sparse count data
Fits a hierarchical Poisson model to count data using mean-field approximation with either
full-batch coordinate-ascent or mini-batch stochastic coordinate-ascent.
Note
----
DataFrames and arrays passed to '.fit' might be modified inplace - if this is a ... |
374,552 | def use_app(backend_name=None, call_reuse=True):
global default_app
if default_app is not None:
names = default_app.backend_name.lower().replace(, ).strip()
names = [name for name in names.split() if name]
if backend_name and backend_name.lower() not in names:
rais... | Get/create the default Application object
It is safe to call this function multiple times, as long as
backend_name is None or matches the already selected backend.
Parameters
----------
backend_name : str | None
The name of the backend application to use. If not specified, Vispy
tr... |
374,553 | def optimise_xy(xy, *args):
z, elements, coordinates = args
window_com = np.array([xy[0], xy[1], z])
return -pore_diameter(elements, coordinates, com=window_com)[0] | Return negative pore diameter for x and y coordinates optimisation. |
374,554 | def read(self, vals):
i = 0
if len(vals[i]) == 0:
self.leapyear_observed = None
else:
self.leapyear_observed = vals[i]
i += 1
if len(vals[i]) == 0:
self.daylight_saving_start_day = None
else:
self.daylight_saving_st... | Read values.
Args:
vals (list): list of strings representing values |
374,555 | def signin(request, auth_form=AuthenticationForm,
template_name=,
redirect_field_name=REDIRECT_FIELD_NAME,
redirect_signin_function=signin_redirect, extra_context=None):
form = auth_form()
if request.method == :
form = auth_form(request.POST, request.FILES)
... | Signin using email or username with password.
Signs a user in by combining email/username with password. If the
combination is correct and the user :func:`is_active` the
:func:`redirect_signin_function` is called with the arguments
``REDIRECT_FIELD_NAME`` and an instance of the :class:`User` who is is
... |
374,556 | def refitPrefixes(self):
for c in self.children:
c.refitPrefixes()
if self.prefix is not None:
ns = self.resolvePrefix(self.prefix)
if ns[1] is not None:
self.expns = ns[1]
self.prefix = None
self.nsprefixes = {}
return... | Refit namespace qualification by replacing prefixes
with explicit namespaces. Also purges prefix mapping table.
@return: self
@rtype: L{Element} |
374,557 | def switch(request, url):
app_label, model_name, object_id, field = url.split()
try:
from django.apps import apps
model = apps.get_model(app_label, model_name)
except ImportError:
from django.db.models import get_model
model = get_model(app_label, model... | Set/clear boolean field value for model object |
374,558 | def _resolve(self, name):
config = self._get_config(name)
if not config:
raise RuntimeError( % name)
if config[] in self._custom_creators:
repository = self._call_custom_creator(config)
else:
repository = getattr(self, % config[])(config)
... | Resolve the given store
:param name: The store to resolve
:type name: str
:rtype: Repository |
374,559 | def add(self, defn):
if defn.name not in self:
self[defn.name] = defn
else:
msg = "Duplicate packet name " % defn.name
log.error(msg)
raise util.YAMLError(msg) | Adds the given Packet Definition to this Telemetry Dictionary. |
374,560 | def downloadArchiveAction(self, request, queryset):
output = io.BytesIO()
z = zipfile.ZipFile(output, )
for sub in queryset:
sub.add_to_zipfile(z)
z.close()
output.seek(0)
response = HttpResponse(
output, content_type="applicati... | Download selected submissions as archive, for targeted correction. |
374,561 | def _dump_to_file(self, file):
xmltodict.unparse(self.object(), file, pretty=True) | dump to the file |
374,562 | def evaluate_stacked_ensemble(path, ensemble_id):
with functions.DBContextManager(path) as session:
stacked_ensemble = session.query(models.StackedEnsemble).filter_by(
id=ensemble_id).first()
if not stacked_ensemble:
raise exceptions.UserError(
... | Evaluates the ensemble and updates the database when finished/
Args:
path (str): Path to Xcessiv notebook
ensemble_id (str): Ensemble ID |
374,563 | def list_objects(self, bucket_name=None, **kwargs):
if not bucket_name: bucket_name = self.bucket_name
return self.client.list_objects(Bucket=bucket_name, **kwargs) | This method is primarily for illustration and just calls the
boto3 client implementation of list_objects but is a common task
for first time Predix BlobStore users. |
374,564 | def spreadsheet(service, id):
request = service.spreadsheets().get(spreadsheetId=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
else:
raise
return response | Fetch and return spreadsheet meta data with Google sheets API. |
374,565 | def status_bar(python_input):
TB =
@if_mousedown
def toggle_paste_mode(mouse_event):
python_input.paste_mode = not python_input.paste_mode
@if_mousedown
def enter_history(mouse_event):
python_input.enter_history()
def get_text_fragments():
python_buffer = python_... | Create the `Layout` for the status bar. |
374,566 | def handle_inittarget(
state_change: ActionInitTarget,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
block_number: BlockNumber,
) -> TransitionResult[TargetTransferState]:
transfer = state_change.transfer
route = state_change.route
assert c... | Handles an ActionInitTarget state change. |
374,567 | def create_secret(self, value, contributor, metadata=None, expires=None):
if metadata is None:
metadata = {}
secret = self.create(
value=value,
contributor=contributor,
metadata=metadata,
expires=expires,
)
return str(... | Create a new secret, returning its handle.
:param value: Secret value to store
:param contributor: User owning the secret
:param metadata: Optional metadata dictionary (must be JSON serializable)
:param expires: Optional date/time of expiry (defaults to None, which means that
... |
374,568 | def inception_v3(pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), ), **kwargs):
r
net = Inception3(**kwargs)
if pretrained:
from ..model_store import get_model_file
net.load_parameters(get_model_file(, root=root), ctx=ctx)
return net | r"""Inception v3 model from
`"Rethinking the Inception Architecture for Computer Vision"
<http://arxiv.org/abs/1512.00567>`_ paper.
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in ... |
374,569 | def call(method, *args, **kwargs):
napalm.callclicommandsshow versionshow chassis fan
kwargs_copy = {}
kwargs_copy.update(kwargs)
for karg, warg in six.iteritems(kwargs_copy):
if warg is None:
kwargs.pop(karg)
return salt.utils.napalm.call(NETWORK_DEVICE, method... | Calls a specific method from the network driver instance.
Please check the readthedocs_ page for the updated list of getters.
.. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix
:param method: specifies the name of the method to be called
:param params: c... |
374,570 | def _parse_one_event(self):
else:
if open_brace_idx > 0:
self._buf = self._buf[open_brace_idx:]
try:
event, idx = self._decoder.raw_decode(self._buf)
self._buf = self._buf[idx:]
return event
except ValueError:
... | Parse the stream buffer and return either a single event or None |
374,571 | def extract_lookups(value):
lookups = set()
if isinstance(value, basestring):
lookups = lookups.union(extract_lookups_from_string(value))
elif isinstance(value, list):
for v in value:
lookups = lookups.union(extract_lookups(v))
elif isinstance(value, dict):
for v... | Recursively extracts any stack lookups within the data structure.
Args:
value (one of str, list, dict): a structure that contains lookups to
output values
Returns:
list: list of lookups if any |
374,572 | def get_differing_atom_residue_ids(self, pdb_name, pdb_list):
assert(pdb_name in self.pdb_names)
assert(set(pdb_list).intersection(set(self.pdb_names)) == set(pdb_list))
differing_atom_residue_ids = set()
for other_pdb in pdb_list:
differing_atom_residue_ids = dif... | Returns a list of residues in pdb_name which differ from the pdbs corresponding to the names in pdb_list. |
374,573 | def _assertField(self, name):
if name not in self._names:
msg =
values = self._defn.name, name
raise AttributeError(msg % values) | Raise AttributeError when PacketHistory has no field with the given
name. |
374,574 | def get_or_guess_labels(model, x, **kwargs):
if in kwargs and in kwargs:
raise ValueError("Can not set both and .")
if in kwargs:
labels = kwargs[]
elif in kwargs and kwargs[] is not None:
labels = kwargs[]
else:
_, labels = torch.max(model(x), 1)
return labels | Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the l... |
374,575 | def get_sn(unit):
sn = 0
match_re = re.findall(str(sentence_delimiters), unit)
if match_re:
string = .join(match_re)
sn = len(string)
return int(sn) | 获取文本行的句子数量
Keyword arguments:
unit -- 文本行
Return:
sn -- 句数 |
374,576 | def run(cmd_str,cwd=,verbose=False):
bwd = os.getcwd()
os.chdir(cwd)
try:
exe_name = cmd_str.split()[0]
if "window" in platform.platform().lower():
if not exe_name.lower().endswith("exe"):
raw = cmd_str.split()
raw[0] = exe_name + ".exe"
... | an OS agnostic function to execute a command line
Parameters
----------
cmd_str : str
the str to execute with os.system()
cwd : str
the directory to execute the command in
verbose : bool
flag to echo to stdout complete cmd str
Note
----
uses platform to detect... |
374,577 | def parent(self):
if self._has_parent is None:
_parent = self._ctx.backend.get_parent(self._ctx.dev)
self._has_parent = _parent is not None
if self._has_parent:
self._parent = Device(_parent, self._ctx.backend)
else:
self._... | Return the parent device. |
374,578 | def find_optimal_allocation(self, tokens):
token_ranges = self.find_tracked_words(tokens)
token_ranges.sort()
for offset in range(1, len(token_ranges)):
to_be_removed = []
for candidate in token_ranges[offset:]:
for i in range(offset):
... | Finds longest, non-overlapping word-ranges of phrases in tokens stored in TokenTrie
:param tokens: tokens tokenize
:type tokens: list of str
:return: Optimal allocation of tokens to phrases
:rtype: list of TokenTrie.Token |
374,579 | def attended_by(self, email):
for attendee in self["attendees"] or []:
if (attendee["email"] == email
and attendee["responseStatus"] == "accepted"):
return True
return False | Check if user attended the event |
374,580 | def read_string(self, registeraddress, numberOfRegisters=16, functioncode=3):
_checkFunctioncode(functioncode, [3, 4])
_checkInt(numberOfRegisters, minvalue=1, description=)
return self._genericCommand(functioncode, registeraddress, \
numberOfRegisters=numberOfRegisters, pay... | Read a string from the slave.
Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits).
For example 16 consecutive registers can hold 32 characters (32 bytes).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex... |
374,581 | def get_dependencies(self):
return super().get_dependencies() + [
Data.collection_set,
Data.entity_set,
Data.parents,
] | Return dependencies, which should trigger updates of this model. |
374,582 | def validate_auth_mechanism(option, value):
if value not in MECHANISMS and value != :
raise ValueError("%s must be in %s" % (option, tuple(MECHANISMS)))
return value | Validate the authMechanism URI option. |
374,583 | def print_genl_msg(_, ofd, hdr, ops, payloadlen):
data = nlmsg_data(hdr)
if payloadlen.value < GENL_HDRLEN:
return data
print_genl_hdr(ofd, data)
payloadlen.value -= GENL_HDRLEN
data = bytearray_ptr(data, GENL_HDRLEN)
if ops:
hdrsize = ops.co_hdrsize - GENL_HDRLEN
... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L831.
Positional arguments:
_ -- unused.
ofd -- function to call with arguments similar to `logging.debug`.
hdr -- Netlink message header (nlmsghdr class instance).
ops -- cache operations (nl_cache_ops class instance).
payloadlen -- l... |
374,584 | def put(self, key):
self._consul_request(, self._key_url(key[]), json=key)
return key[] | Put and return the only unique identifier possible, its url |
374,585 | def _el_orb_tuple(string):
el_orbs = []
for split in string.split():
splits = split.split()
el = splits[0]
if len(splits) == 1:
el_orbs.append(el)
else:
el_orbs.append((el, tuple(splits[1:])))
return el_orbs | Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (`str`): The selected elements and orbitals in in the form:
`"Sn.s.p,O"`.
Returns:
A list of tuples specifying which... |
374,586 | def to_dict(self):
d = {: self.component_id,
: self.instance_name}
props = []
for name in self.properties:
p = {: name}
if self.properties[name]:
p[] = str(self.properties[name])
props.append(p)
if props:
... | Save this target component into a dictionary. |
374,587 | def stencils(self):
if not self._stencils:
self._stencils = self.manifest[]
return self._stencils | List of stencils. |
374,588 | def location(self, value):
warnings.warn(_LOCATION_SETTER_MESSAGE, DeprecationWarning, stacklevel=2)
self._location = value | (Deprecated) Set `Bucket.location`
This can only be set at bucket **creation** time.
See https://cloud.google.com/storage/docs/json_api/v1/buckets and
https://cloud.google.com/storage/docs/bucket-locations
.. warning::
Assignment to 'Bucket.location' is deprecated, as it ... |
374,589 | def _set_relative_pythonpath(self, value):
self.pythonpath = [osp.abspath(osp.join(self.root_path, path))
for path in value] | Set PYTHONPATH list relative paths |
374,590 | def sysinfo2float(version_info=sys.version_info):
vers_str = .join([str(v) for v in version_info[0:3]])
if version_info[3] != :
vers_str += + .join([str(i) for i in version_info[3:]])
if IS_PYPY:
vers_str +=
else:
try:
import platform
platform = pl... | Convert a sys.versions_info-compatible list into a 'canonic'
floating-point number which that can then be used to look up a
magic number. Note that this can only be used for released version
of C Python, not interim development versions, since we can't
represent that as a floating-point number.
Fo... |
374,591 | def route_handler(context, content, pargs, kwargs):
(node, rule_kw) = node_from_uri(pargs[0])
if node == None:
return u"<!-- 404 -->".format(pargs[0])
rule_kw.update( node )
values = rule_kw
values.update( request.form.to_dict(flat=True) )
values.update( request.args.to_dict(flat... | Route shortcode works a lot like rendering a page based on the url or
route. This allows inserting in rendered HTML within another page.
Activate it with the 'shortcodes' template filter. Within the content use
the chill route shortcode: "[chill route /path/to/something/]" where the
'[chill' and ']' a... |
374,592 | def get(key, default=-1):
if isinstance(key, int):
return ECDSA_LOW_Curve(key)
if key not in ECDSA_LOW_Curve._member_map_:
extend_enum(ECDSA_LOW_Curve, key, default)
return ECDSA_LOW_Curve[key] | Backport support for original codes. |
374,593 | def get_certificate_json(self, certificate_uid):
if certificate_uid.startswith(URN_UUID_PREFIX):
uid = certificate_uid[len(URN_UUID_PREFIX):]
elif certificate_uid.startswith():
last_slash = certificate_uid.rindex()
uid = certificate_uid[last_slash + 1:]
... | Returns certificate as json. Propagates KeyError if key isn't found
:param certificate_uid:
:return: |
374,594 | def process_am1(self, am1):
self.minw = min(map(lambda l: self.wght[l], am1))
self.core_sels, b = am1, len(am1) - 1
self.cost += b * self.minw
self.garbage = set()
self.process_sels()
self.topv += 1
... | Due to the solving process involving multiple optimization
levels to be treated individually, new soft clauses for
the detected intrinsic AtMost1 constraints should be
remembered. The method is a slightly modified version of
the base method :func:`RC2.process_am1` taking ... |
374,595 | def raw_file(client, src, dest, opt):
path, key = path_pieces(src)
resp = client.read(path)
if not resp:
client.revoke_self_token()
raise aomi.exceptions.VaultData("Unable to retrieve %s" % path)
else:
if in resp and key in resp[]:
secret = resp[][key]
... | Write the contents of a vault path/key to a file. Is
smart enough to attempt and handle binary files that are
base64 encoded. |
374,596 | def _report_external_dependencies(self, sect, _, _dummy):
dep_info = _make_tree_defs(self._external_dependencies_info().items())
if not dep_info:
raise EmptyReportError()
tree_str = _repr_tree_defs(dep_info)
sect.append(VerbatimText(tree_str)) | return a verbatim layout for displaying dependencies |
374,597 | def get_namespaces(namespace="", apiserver_url=None):
**
apiserver_url = _guess_apiserver(apiserver_url)
if apiserver_url is None:
return False
ret = _get_namespaces(apiserver_url, namespace)
return ret | .. versionadded:: 2016.3.0
Get one or all kubernetes namespaces.
If namespace parameter is omitted, all namespaces will be returned back to user, similar to following kubectl example:
.. code-block:: bash
kubectl get namespaces -o json
In case namespace is set by user, the output will be si... |
374,598 | def shutdown(at_time=None):
*
cmd = [, , (.format(at_time) if at_time else )]
ret = __salt__[](cmd, python_shell=False)
return ret | Shutdown a running system
at_time
The wait time in minutes before the system will be shutdown.
CLI Example:
.. code-block:: bash
salt '*' system.shutdown 5 |
374,599 | def hydrate_input_uploads(input_, input_schema, hydrate_values=True):
from resolwe.flow.managers import manager
files = []
for field_schema, fields in iterate_fields(input_, input_schema):
name = field_schema[]
value = fields[name]
if in field_schema:
if field_sche... | Hydrate input basic:upload types with upload location.
Find basic:upload fields in input.
Add the upload location for relative paths. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.