Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
344,200 | def url_fix(s, charset=):
r
scheme, netloc, path, qs, anchor = url_parse(to_unicode(s, charset, ))
path = url_quote(path, charset, safe=(),:&%=+$!*\)
return to_native(url_unparse((scheme, netloc, path, qs, anchor))) | r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'ht... |
344,201 | def readconfig(self, configpath=None):
cfg = _open_bugzillarc(configpath or self.configpath)
if not cfg:
return
section = ""
log.debug("bugzillarc: Searching for config section matching %s",
self.url)
def _parse_hostname(_u):
... | :param configpath: Optional bugzillarc path to read, instead of
the default list.
This function is called automatically from Bugzilla connect(), which
is called at __init__ if a URL is passed. Calling it manually is
just for passing in a non-standard configpath.
The locatio... |
344,202 | def setup_client(self):
params = {
"authorization_redirect_uri": self.authorization_redirect_uri,
"oxd_rp_programming_language": "python",
}
for op in self.opt_params:
if self.config.get("client", op):
params[op] = self.c... | The command registers the client for communication protection. This
will be used to obtain an access token via the Get Client Token
command. The access token will be passed as a protection_access_token
parameter to other commands.
Note:
If you are using the oxd-https-extensi... |
344,203 | def read_input_file(filename, sep=, noquote=False):
output = []
stream = None
try:
stream = open(filename, )
for row in stream:
row = row.strip()
if noquote:
row = row.replace(, )
output.append(row.split(sep))
except IOError as err... | Reads a given inputfile (tab delimited) and returns a matrix
(list of list).
arg: filename, the complete path to the inputfile to read |
344,204 | def ext_pillar(minion_id,
pillar,
key=None,
only=()):
url = __opts__[]
user = __opts__[]
password = __opts__[]
api = __opts__[]
verify = __opts__[]
certfile = __opts__[]
keyfile = __opts__[]
cafile = __opts__[]
lookup_parameters = _... | Read pillar data from Foreman via its API. |
344,205 | def clear_matplotlib_ticks(ax=None, axis="both"):
if not ax:
return
if axis.lower() in ["both", "x", "horizontal"]:
ax.set_xticks([], [])
if axis.lower() in ["both", "y", "vertical"]:
ax.set_yticks([], []) | Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" or "horizontal", "y" or "vertical", or "both" |
344,206 | def _close(self):
if self.stream:
try:
if not self.stream.closed:
self.stream.flush()
self.stream.close()
finally:
self.stream = None | Close file stream. Unlike close(), we don't tear anything down, we
expect the log to be re-opened after rotation. |
344,207 | def get_full_filename(self, dataType, subjectArea):
return dataPath + os.sep + + os.sep + dataType + + subjectArea + | returns the file based on dataType and subjectArea |
344,208 | def unique(self):
new = self.__class__([])
for elem in self:
if elem not in new:
new.append(elem)
return new | Return a Cache which has every element of self, but without
duplication. Preserve order. Does not hash, so a bit slow. |
344,209 | def set(self, key, value, timeout=NotSet):
if not self.enabled:
return
if hasattr(value, ):
value = value()
if timeout == NotSet:
timeout = self.default_timeout
self._set(key, value, timeout)
return value | Set the given key to the given value in the cache.
A timeout may be provided, otherwise, the :py:attr:`Cache.default_timeout`
will be used.
:param key: the key to which the value will be bound
:type key: str
:param value: the value to store in the cache
:param timeout: t... |
344,210 | def getConnectionStats(self):
cur = self._conn.cursor()
cur.execute()
rows = cur.fetchall()
if rows:
return dict(rows)
else:
return {} | Returns dictionary with number of connections for each database.
@return: Dictionary of database connection statistics. |
344,211 | def load_cufflinks(self, filter_ok=True):
return \
pd.concat(
[self._load_single_patient_cufflinks(patient, filter_ok) for patient in self],
copy=False
) | Load a Cufflinks gene expression data for a cohort
Parameters
----------
filter_ok : bool, optional
If true, filter Cufflinks data to row with FPKM_status == "OK"
Returns
-------
cufflinks_data : Pandas dataframe
Pandas dataframe with Cufflinks d... |
344,212 | def start(self, exit=True):
on_start = self()
actor = arbiter()
if actor and on_start:
actor.start(exit=exit)
if actor.exit_code is not None:
return actor.exit_code
return on_start | Invoked the application callable method and start
the ``arbiter`` if it wasn't already started.
It returns a :class:`~asyncio.Future` called back once the
application/applications are running. It returns ``None`` if
called more than once. |
344,213 | def parse_pseudo_dir(self, sel, m, has_selector):
value = ct.SEL_DIR_LTR if util.lower(m.group()) == else ct.SEL_DIR_RTL
sel.flags |= value
has_selector = True
return has_selector | Parse pseudo direction. |
344,214 | def build(args, parser):
if args is None:
raise Exception("arguments not provided")
try:
json_spec = _parse_executable_spec(args.src_dir, "dxworkflow.json", parser)
workflow_id = _build_or_update_workflow(json_spec, args)
_print_output(workflow_id, args)
except Workflo... | Validates workflow source directory and creates a new (global) workflow based on it.
Raises: WorkflowBuilderException if the workflow cannot be created. |
344,215 | def deregister_webhook(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.deregister_webhook_with_http_info(**kwargs)
else:
(data) = self.deregister_webhook_with_http_info(**kwargs)
return data | Delete callback URL # noqa: E501
Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous H... |
344,216 | def Colebrook(Re, eD, tol=None):
rs `float`;
-1 to apply the Clamond solution where appropriate for greater speed
(Re > 10), [-]
Returns
-------
fd : float
Darcy friction factor [-]
Notes
-----
The solution is as follows:
.. math::
f_d = \frac{\ln(1... | r'''Calculates Darcy friction factor using the Colebrook equation
originally published in [1]_. Normally, this function uses an exact
solution to the Colebrook equation, derived with a CAS. A numerical can
also be used.
.. math::
\frac{1}{\sqrt{f}}=-2\log_{10}\left(\frac{\epsilon/D}{3.7}
... |
344,217 | def common_entitlements_options(f):
@click.option(
"--show-tokens",
default=False,
is_flag=True,
help="Show entitlement token string contents in output.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
return ctx.in... | Add common options for entitlement commands. |
344,218 | def fast_exponentiation(a, b, q):
assert a >= 0 and b >= 0 and q >= 1
result = 1
while b:
if b % 2 == 1:
result = (result * a) % q
a = (a * a) % q
b >>= 1
return result | Compute (a pow b) % q, alternative shorter implementation
:param int a b: non negative
:param int q: positive
:complexity: O(log b) |
344,219 | def DbGetDevicePropertyHist(self, argin):
self._log.debug("In DbGetDevicePropertyHist()")
device_name = argin[0]
prop_name = argin[1]
return self.db.get_device_property_hist(device_name, prop_name) | Retrieve device property history
:param argin: Str[0] = Device name
Str[1] = Property name
:type: tango.DevVarStringArray
:return: Str[0] = Property name
Str[1] = date
Str[2] = Property value number (array case)
Str[3] = Property value 1
Str[n] = Propert... |
344,220 | def update(self, f):
for p in self.__mapper__.attrs:
if p.key == :
continue
try:
setattr(self, p.key, getattr(f, p.key))
except AttributeError:
continue | Copy another files properties into this one. |
344,221 | def parse_parametrs(p):
ret = {}
while len(p) > 1 and p.count() > 0:
s = p.split()
l = int(s[0])
if l > 0:
p = p[len(s[0]) + 1:]
field_name = p.split()[0].split()[0]
field_value = p[len(field_name) + 1:l]
p = p[l + 1:]
re... | Parses the parameters given from POST or websocket reqs
expecting the parameters as: "11|par1='asd'|6|par2=1"
returns a dict like {par1:'asd',par2:1} |
344,222 | async def end_dialog(self, result: object = None):
await self.end_active_dialog(DialogReason.EndCalled)
if self.active_dialog != None:
dialog = await self.find_dialog(self.active_dialog.id)
if not dialog:
raise Exception("DialogCont... | Ends a dialog by popping it off the stack and returns an optional result to the dialog's
parent. The parent dialog is the dialog that started the dialog being ended via a call to
either "begin_dialog" or "prompt".
The parent dialog will have its `Dialog.resume_dialog()` method invoked with any r... |
344,223 | def finalize(self, neighbor_label_bags=None, walk_durations=None, departure_arrival_stop_pairs=None):
assert (not self._finalized)
if self._final_pareto_optimal_labels is None:
self._compute_real_connection_labels()
if neighbor_label_bags is not None:
assert (len... | Parameters
----------
neighbor_label_bags: list
each list element is a list of labels corresponding to a neighboring node
(note: only labels with first connection being a departure should be included)
walk_durations: list
departure_arrival_stop_pairs: list of tup... |
344,224 | def _dump(self, out_dir=):
with self.no_unpicklable_properties():
self.job_file = os.path.join(out_dir, )
if self.__module__ == :
d = pickle.dumps(self)
module_name = os.path.basename(sys.argv[0]).rsplit(, 1)[0]
d = d.replace(, "(c... | Dump instance to file. |
344,225 | def get_item_representations(self, features=None):
self._check_initialized()
if features is None:
return self.item_biases, self.item_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.item_biases, features * self.item_embeddi... | Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
... |
344,226 | def _get_image_numpy_dtype(self):
try:
ftype = self._info[]
npy_type = _image_bitpix2npy[ftype]
except KeyError:
raise KeyError("unsupported fits data type: %d" % ftype)
return npy_type | Get the numpy dtype for the image |
344,227 | def get_sql(self):
return .format(self.join_type, self.right_table.get_sql(), self.get_condition()) | Generates the JOIN sql for the join tables and join condition
:rtype: str
:return: the JOIN sql for the join tables and join condition |
344,228 | def validate(self):
if not isinstance(self.predicate, Expression):
raise TypeError(u.format(
type(self.predicate).__name__, self.predicate)) | Ensure that the Filter block is valid. |
344,229 | def vertically(value, num_blocks, val_min, color, args):
global maxi, value_list
value_list.append(str(value))
if maxi < num_blocks:
maxi = num_blocks
if num_blocks > 0:
vertical_list.append((TICK * num_blocks))
else:
vertical_list.append(SM_TICK)
... | Prepare the vertical graph.
The whole graph is printed through the print_vertical function. |
344,230 | def get_children_for(self, parent_alias=None, only_with_aliases=False):
self._cache_init()
child_ids = self.get_child_ids(parent_alias)
if only_with_aliases:
children = []
for cid in child_ids:
category = self.get_category_by_id(cid)
... | Returns a list with with categories under the given parent.
:param str|None parent_alias: Parent category alias or None for categories under root
:param bool only_with_aliases: Flag to return only children with aliases
:return: a list of category objects |
344,231 | def get_meteor_id(obj_or_model, obj_pk=None):
if obj_or_model is None:
return None
meta = obj_or_model._meta
model = meta.model
if model is ObjectMapping:
if isinstance(obj_or_model, model):
if isinstance(meta.pk, AleaIdField):
return obj... | Return an Alea ID for the given object. |
344,232 | def _stmt_graph_add_edge(self, src, dst, **edge_labels):
if src in self._stmt_graph and dst in self._stmt_graph[src]:
return
self._stmt_graph.add_edge(src, dst, **edge_labels) | Add an edge in the statement dependence graph from a program location `src` to another program location `dst`.
:param CodeLocation src: Source node.
:param CodeLocation dst: Destination node.
:param edge_labels: All labels associated with the edge.
:returns: None |
344,233 | def get_schema_func(self):
if self._get_schema_func is not None:
return self._get_schema_func
get_schema_macro = self.macro_manifest.find_macro_by_name(
,
self.root_project_config.project_name
)
if get_schema_macro is None:
get_sc... | The get_schema function is set by a few different things:
- if there is a 'generate_schema_name' macro in the root project,
it will be used.
- if that does not exist but there is a 'generate_schema_name'
macro in the 'dbt' internal project, that will be used
... |
344,234 | def mu(self, value):
_checkParam(, value, self.PARAMLIMITS, self.PARAMTYPES)
if value != self.mu:
self._cached = {}
self._mu = value | Set new `mu` value. |
344,235 | async def run(self):
logger.info(__(
"Starting Resolwe listener on channel .",
state.MANAGER_EXECUTOR_CHANNELS.queue
))
while not self._should_stop:
await self.push_stats()
ret = await self._call_redis(aioredis.Redis.blpop, state.MANAGER_E... | Run the main listener run loop.
Doesn't return until :meth:`terminate` is called. |
344,236 | def is_root(self):
sub_prefix = self.reddit_session.config.by_object[Submission]
return self.parent_id.startswith(sub_prefix) | Return True when the comment is a top level comment. |
344,237 | def parse_output(self, hostname, output):
if isinstance(output, bytes):
output = output.decode()
return output.split()[-1] | Parse plowup's output.
For now, we just return the last line.
:param hostname: Name of host you are working with.
:type hostname: str
:param output: Dictionary containing information about a plowshare
action.
:type output: dict
:returns: Parsed an... |
344,238 | def check_manifest ():
try:
f = open()
except Exception:
print()
return
try:
manifest = [l.strip() for l in f.readlines() if not l.startswith()]
finally:
f.close()
err = [line for line in manifest if not os.path.exists(line)]
if err:
n = len(m... | Snatched from roundup.sf.net.
Check that the files listed in the MANIFEST are present when the
source is unpacked. |
344,239 | def _get_enterprise_customer_users_batch(self, start, end):
LOGGER.info(, start, end)
return User.objects.filter(pk__in=self._get_enterprise_customer_user_ids())[start:end] | Returns a batched queryset of EnterpriseCustomerUser objects. |
344,240 | def get_resized_size(self):
f = self.fmt
iw, ih = self.image.size
if not f.stretch and iw <= self.fw and ih <= self.fh:
return
if self.image_ratio == self.format_ratio:
return (self.fw, self.fh)
elif self.image_ratio < self.format_... | Get target size for the stretched or shirnked image to fit within the
target dimensions. Do not stretch images if not format.stretch.
Note that this method is designed to operate on already cropped image. |
344,241 | def format_response(self, data):
self.count = self.max_count
return OrderedDict([
(, self.max_count),
(, self.total),
(, self.get_next_link()),
(, self.get_previous_link()),
(, data)
]) | replaces the `count` (the last queryset count) with the running `max_count` variable,
to ensure accurate link calculation |
344,242 | def shallow_reverse(g):
new_g = networkx.DiGraph()
new_g.add_nodes_from(g.nodes())
for src, dst, data in g.edges(data=True):
new_g.add_edge(dst, src, **data)
return new_g | Make a shallow copy of a directional graph and reverse the edges. This is a workaround to solve the issue that one
cannot easily make a shallow reversed copy of a graph in NetworkX 2, since networkx.reverse(copy=False) now returns
a GraphView, and GraphViews are always read-only.
:param networkx.DiGraph g:... |
344,243 | def pickAChannel(self, ra_deg, dec_deg):
cRa = self.currentRaDec[:, 3]
cDec = self.currentRaDec[:, 4]
dist = cRa * 0
for i in range(len(dist)):
dist[i] = gcircle.sphericalAngSep(cRa[i], cDec[i], ra_deg, dec_deg)
i = np.argmin(dist)
... | Returns the channel number closest to a given (ra, dec) coordinate. |
344,244 | def apply_config(self, applicator):
if type(self._path) == str:
self._path = applicator.apply(self._path)
for key in self._children:
self._children[key].apply_config(applicator) | Replace any config tokens with values from the config. |
344,245 | def mark_offer_as_unclear(self, offer_id):
return self._create_put_request(
resource=OFFERS,
billomat_id=offer_id,
command=UNCLEAR,
) | Mark offer as unclear
:param offer_id: the offer id
:return Response |
344,246 | def get_id_head(self):
id_head = None
for target_node in self:
if target_node.is_head():
id_head = target_node.get_id()
break
return id_head | Returns the id of the target that is set as "head"
@rtype: string
@return: the target id (or None) of the head target |
344,247 | def required_opts_multi_ifo(opt, parser, ifo, opt_list, required_by=None):
for name in opt_list:
attr = name[2:].replace(, )
try:
if getattr(opt, attr)[ifo] is None:
raise KeyError
except KeyError:
err_str = "%s is missing " % name
if ... | Check that all the opts are defined
Parameters
----------
opt : object
Result of option parsing
parser : object
OptionParser instance.
ifo : string
opt_list : list of strings
required_by : string, optional
the option that requires these options (if applicable) |
344,248 | def increase(self, ubound=1, top_id=None):
self.top_id = max(self.top_id, top_id if top_id != None else 0)
if ubound <= self.ubound or self.ubound >= len(self.lits):
self.nof_new = 0
return
else:
self.ubound = ubound
def_s... | Increases a potential upper bound that can be imposed on the
literals in the sum of an existing :class:`ITotalizer` object to a
new value.
:param ubound: a new upper bound.
:param top_id: a new top variable identifier.
:type ubound: int
:type top... |
344,249 | def ior_effect(durations, angle_diffs, length_diffs,
summary_stat=np.mean, parallel=True, min_samples=20):
raster = np.empty((len(e_dist) - 1, len(e_angle) - 1), dtype=object)
for a, (a_low, a_upp) in enumerate(zip(e_angle[:-1], e_angle[1:])):
for d, (d_low, d_upp) in enumerate(zip(e... | Computes a measure of fixation durations at delta angle and delta
length combinations. |
344,250 | def detect_Massimini2004(dat_orig, s_freq, time, opts):
if opts.invert:
dat_orig = -dat_orig
dat_det = transform_signal(dat_orig, s_freq, ,
opts.det_filt)
above_zero = detect_events(dat_det, , value=0.)
sw_in_chan = []
if above_zero is not None:
... | Slow wave detection based on Massimini et al., 2004.
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
time : ndarray (dtype='float')
vector with the time points for each sample
opts : instance... |
344,251 | def add_storage_controller(self, name, connection_type):
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
if not isinstance(connection_type, StorageBus):
raise TypeError("connection_type can only be an instance of ty... | Adds a new storage controller (SCSI, SAS or SATA controller) to the
machine and returns it as an instance of
:py:class:`IStorageController` .
@a name identifies the controller for subsequent calls such as
:py:func:`get_storage_controller_by_name` ,
:py:func:`get_storage_... |
344,252 | def gradient_n_pal(colors, values=None, name=):
if values is None:
colormap = mcolors.LinearSegmentedColormap.from_list(
name, colors)
else:
colormap = mcolors.LinearSegmentedColormap.from_list(
name, list(zip(values, colors)))
def _gradient_n_pal... | Create a n color gradient palette
Parameters
----------
colors : list
list of colors
values : list, optional
list of points in the range [0, 1] at which to
place each color. Must be the same size as
`colors`. Default to evenly space the colors
name : str
Name... |
344,253 | def handle(self, *args, **options):
user_model = get_user_model()
if len(args) == 0:
filters = [{"is_superuser": True}, {"is_staff": True}, {}]
user = None
for f in filters:
try:
user = user_model._default_man... | With no arguments, find the first user in the system with the
is_superuser or is_staff flag set to true, or just the first user in
the system period.
With a single argument, look for the user with that value as the
USERNAME_FIELD value.
When a user is found, print out a URL slu... |
344,254 | def _get_instances(self, page_number=None):
instances = []
uri = % self.guid
json_response = self.api.get(uri)
instances += json_response[]
while json_response[] is not None:
json_response = self.api.get(json_response[])
instances += json_respons... | Returns the service instances activated in this space. |
344,255 | def get_analyses_at(self, slot):
slot = to_int(slot)
if slot < 1:
return list()
analyses = list()
layout = self.getLayout()
for pos in layout:
layout_slot = to_int(pos[])
uid = pos[]
if layout_slot != slot or n... | Returns the list of analyses assigned to the slot passed in, sorted by
the positions they have within the slot.
:param slot: the slot where the analyses are located
:type slot: int
:return: a list of analyses |
344,256 | def msg(self, *args, **kwargs):
"Only execute callback when interval is reached."
if self.timestamp is None or self._interval_reached():
self.callback(*args, **kwargs)
self.reset() | Only execute callback when interval is reached. |
344,257 | def command_children(self, command):
if not len(self.nodes):
return
commands = []
for c in self.nodes:
commands.append(.format(c.id, command))
self._conn.command(.join(commands)) | Run a command on the direct children of the currently selected
container.
:rtype: List of CommandReply???? |
344,258 | def init_app(self, app):
self.init_blueprint(app)
if self.flaskcache is not None:
for func, extension_name in self.CACHED:
func = getattr(self._extensions[extension_name], func)
setattr(
self._extensions[extension_name],
... | Initiate the extension on the application
:param app: Flask Application
:return: Blueprint for Flask Nautilus registered in app
:rtype: Blueprint |
344,259 | def search_form(context, search_model_names=None):
template_vars = {
"request": context["request"],
}
if not search_model_names or not settings.SEARCH_MODEL_CHOICES:
search_model_names = []
elif search_model_names == "all":
search_model_names = list(settings.SEARCH_MODEL_CHO... | Includes the search form with a list of models to use as choices
for filtering the search by. Models should be a string with models
in the format ``app_label.model_name`` separated by spaces. The
string ``all`` can also be used, in which case the models defined
by the ``SEARCH_MODEL_CHOICES`` setting wi... |
344,260 | def _endian(self) -> str:
if (self._encoding == 1 or self._encoding == 2 or self._encoding == 5 or
self._encoding == 7 or self._encoding == 9 or self._encoding == 11 or
self._encoding == 12):
return
else:
return | Determines endianess of the CDF file
Only used in __init__ |
344,261 | def add_listener(self, event, callback, single=False, priority=1):
event_stack = self._events[event]
event_stack.append({
"callback": callback,
"single": single,
"priority": priority
})
event_stack.sort(key=lambda x: x[]) | Add a callback to an event list so it will be run at this event's
firing. If single is True, the event is auto-removed after the first
invocation. Priority can be used to jump ahead or behind other
callback invocations. |
344,262 | def loadExperimentDescriptionScriptFromDir(experimentDir):
descriptionScriptPath = os.path.join(experimentDir, "description.py")
module = _loadDescriptionFile(descriptionScriptPath)
return module | Loads the experiment description python script from the given experiment
directory.
:param experimentDir: (string) experiment directory path
:returns: module of the loaded experiment description scripts |
344,263 | def accounts(self) -> AccountsAggregate:
if not self.__accounts_aggregate:
self.__accounts_aggregate = AccountsAggregate(self.book)
return self.__accounts_aggregate | Returns the Accounts aggregate |
344,264 | def process_rpm_ql_line(line_str, allowed_keys):
try:
name, key_str = line_str.split(, 1)
except ValueError:
logger.error("Failed to split line Could not process line "{0}"{0}' ({1})".format(name, used_key))
return False | Checks single line of rpm-ql for correct keys
:param line_str: line to process
:param allowed_keys: list of allowed keys
:return: bool |
344,265 | def get_assigned_name(frame):
SEARCHING, MATCHED = 1, 2
state = SEARCHING
result =
stacksize = 0
for op in dis.get_instructions(frame.f_code):
if state == SEARCHING and op.offset == frame.f_lasti:
if not op.opname.startswith():
raise RuntimeError()
state = MATCHED
... | Checks the bytecode of *frame* to find the name of the variable a result is
being assigned to and returns that name. Returns the full left operand of the
assignment. Raises a #ValueError if the variable name could not be retrieved
from the bytecode (eg. if an unpack sequence is on the left side of the
assignmen... |
344,266 | def on_next_request(self, py_db, request):
arguments = request.arguments
thread_id = arguments.threadId
if py_db.get_use_libraries_filter():
step_cmd_id = CMD_STEP_OVER_MY_CODE
else:
step_cmd_id = CMD_STEP_OVER
self.api.request_step(py_db, thr... | :param NextRequest request: |
344,267 | def error_handler(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except BaseException as err:
if BOOTSTRAPPER_TEST_KEY in os.environ:
raise
if ERROR_HANDLER_DISABLED:
... | Decorator to error handling. |
344,268 | def detect_deprecated_references_in_node(self, node):
results = []
if node.expression:
results += self.detect_deprecation_in_expression(node.expression)
for dep_node in self.DEPRECATED_NODE_TYPES:
if node.type == dep_node[0]:
... | Detects if a node makes use of any deprecated standards.
Returns:
list of tuple: (detecting_signature, original_text, recommended_text) |
344,269 | def resource_api_version(self, resource_id):
namespace = ResourceIdParser.get_namespace(resource_id)
resource_type = ResourceIdParser.get_resource_type(resource_id)
cache_id = namespace + resource_type
if cache_id in self._provider_cache:
return self._provider_cac... | latest non-preview api version for resource |
344,270 | def cimtype(obj):
if isinstance(obj, CIMType):
return obj.cimtype
if isinstance(obj, bool):
return
if isinstance(obj, (six.binary_type, six.text_type)):
return
if isinstance(obj, list):
try:
obj = obj[0]
except IndexError:
... | Return the CIM data type name of a CIM typed object, as a string.
For an array, the type is determined from the first array element
(CIM arrays must be homogeneous w.r.t. the type of their elements).
If the array is empty, that is not possible and
:exc:`~py:exceptions.ValueError` is raised.
Note t... |
344,271 | def is_nonterminal(self, symbol: str) -> bool:
nonterminal_productions = self.get_nonterminal_productions()
return symbol in nonterminal_productions | Determines whether an input symbol is a valid non-terminal in the grammar. |
344,272 | def start(self):
| Start the scheduler threads. |
344,273 | def _get_ext_namespaces(config):
namespaces = {}
if not config:
return namespaces
for ns in config:
constraint_version = tuple(config[ns].get(, []))
if not constraint_version:
raise salt.exceptions.SaltSystemExit("An alternative version is configured, but not define... | Get namespaces from the existing configuration.
:param config:
:return: |
344,274 | def to_dict(self, *attributes, **options):
name = options.pop(, self.__class__.__name__)
save = options.pop(, False)
fields = OrderedDict()
fields[name] = OrderedDict()
if attributes:
field_getter = attrgetter(*attributes)
else:
... | Returns a **flatten** :class:`ordered dictionary <collections.OrderedDict>`
of ``{'field path': attribute}`` or ``{'field path': tuple(attributes)}``
pairs for each :class:`Field` *nested* in the `Container`.
:param str attributes: selected :class:`Field` attributes.
Fallback is the... |
344,275 | def get_bind_modules(verbose=False):
builtin_path = os.path.join(module_root_path, "bind")
searchpaths = config.bind_module_path + [builtin_path]
bindnames = {}
for path in searchpaths:
if verbose:
print "searching %s..." % path
if not os.path.isdir(path):
c... | Get available bind modules.
Returns:
dict: Map of (name, filepath) listing all bind modules. |
344,276 | def matches(self, mask):
return all(map(lambda m, c: not m.isdigit() or m == c, mask, self)) | :param mask: Template for comparision. If mask symbol is not digit
then it passes.
:type mask: :py:class:`str`
::
>>> Code("123").matches("1")
True
>>> Code("123").matches("1x3")
True |
344,277 | def list_parameters_as_df(self):
to_df = []
for i, e in enumerate(self.ext_params):
row = {}
row[] = e[]
row[] = "n/a"
row[] = e[]
row[] = "n/a"
to_df.append(row)
for pk in self.params:
p = self.param... | Only really useful when running from a jupyter notebook.
Lists the parameters in the model in a pandas dataframe
Columns: id, matrix coordinates, description, function |
344,278 | def signable(self, request, authheaders, response_body):
nonce = authheaders["nonce"]
timestamp = request.get_header("x-authorization-timestamp")
try:
body_str = response_body.decode()
except:
body_str = response_body
return .format(nonce, timesta... | Creates the signable string for a response and returns it.
Keyword arguments:
request -- A request object which can be consumed by this API.
authheaders -- A string-indexable object which contains the headers appropriate for this signature version.
response_body -- A string or bytes-lik... |
344,279 | def read(self, tid, length, offset, fh):
try:
return self.fds[fh].read(offset, length, fh)
except AttributeError:
if tid[1] not in (" next", " prev"):
raise FuseOSError(errno.EINVAL)
return self.__sh_script[offset:offset+length]
... | Read from a file. Data is obtained from ``YTStor`` object (which is kept under `fh` descriptor) using its
``read`` method.
Parameters
----------
tid : str
Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator.
length : int
... |
344,280 | def column_family_name(self, include_keyspace=True):
if include_keyspace:
return .format(self.keyspace, self.name)
else:
return self.name | Returns the column family name if it's been defined
otherwise, it creates it from the module and class name |
344,281 | def new(self, event):
self.grid.actions.clear(event.shape)
_grid_table = GridTable(self.grid, self.grid.code_array)
self.grid.SetTable(_grid_table, True)
self.grid.update_entry_line()
self.grid.update_attribute_toolbar() | Creates a new spreadsheet. Expects code_array in event. |
344,282 | def left_hash(msg, func="HS256"):
if func == :
return as_unicode(b64e(sha256_digest(msg)[:16]))
elif func == :
return as_unicode(b64e(sha384_digest(msg)[:24]))
elif func == :
return as_unicode(b64e(sha512_digest(msg)[:32])) | Calculate left hash as described in
https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
for at_hash and in
for c_hash
:param msg: The message over which the hash should be calculated
:param func: Which hash function that was used for the ID token |
344,283 | def dot_product_unmasked_self_attention_relative_2d(
q, k, v, bias, max_relative_position=None, dropout_rate=0.0,
image_shapes=None, name=None, make_image_summary=True,
dropout_broadcast_dims=None, heads_share_relative_embedding=False,
add_relative_to_values=False):
if not max_relative_position:
... | Calculate relative position unmasked dot-product self-attention 2d.
The attention calculation is augmented with learned representations for the
relative position between each element in q and each element in k and v in
height and width dimensions. for query index (i,j) and key index (l, m),
the logit is q_i k... |
344,284 | def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
{Objects: [Key: myobject]}
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocati... | Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}' |
344,285 | def iteritems(self):
for key in self:
vals = _dict_getitem(self, key)
for val in vals[1:]:
yield vals[0], val | Iterate over all header lines, including duplicate ones. |
344,286 | def closest_hexameter_patterns(self, scansion: str) -> List[str]:
return self._closest_patterns(self.VALID_HEXAMETERS, scansion) | Find the closest group of matching valid hexameter patterns.
:return: list of the closest valid hexameter patterns; only candidates with a matching
length/number of syllables are considered.
>>> print(MetricalValidator().closest_hexameter_patterns('-UUUUU-----UU--'))
['-UU-UU-----UU--'... |
344,287 | def _parse_from_file(self, file_path):
file_path = abspath(file_path)
if not isfile(file_path):
raise MarkovTextExcept("Передан не файл.")
with open(file_path, "rb") as txt_file:
for line in txt_file:
text = line.decode("utf-8", "ignore").strip()
... | см. описание _parse_from_text.
Только на вход подаётся не текст, а путь к файлу. |
344,288 | def base_app(import_name, instance_path=None, static_folder=None,
static_url_path=, template_folder=,
instance_relative_config=True, app_class=Flask):
configure_warnings()
app = app_class(
import_name,
instance_path=instance_path,
instance_relative_co... | Invenio base application factory.
If the instance folder does not exists, it will be created.
:param import_name: The name of the application package.
:param env_prefix: Environment variable prefix.
:param instance_path: Instance path for Flask application.
:param static_folder: Static folder path... |
344,289 | def delete_cfg_template(template_name, auth, url):
CW7SNMP.cfgCW7SNMP.cfgtemplate not found
file_id = get_template_id(template_name, auth, url)
delete_cfg_template_url = "/imcrs/icc/confFile/"+str(file_id)
f_url = url + delete_cfg_template_url
r = requests.delete(f_url, auth=auth, headers=HEADE... | Uses the get_template_id() funct to gather the template_id to craft a url which is sent to the IMC server using
a Delete Method
:param template_name: str containing the entire contents of the configuration segment
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:par... |
344,290 | def release(self):
self._lock.release()
with self._stat_lock:
self._locked = False
self._last_released = datetime.now() | Wraps Lock.release |
344,291 | def init_remotes(self, remotes, per_remote_overrides=(),
per_remote_only=PER_REMOTE_ONLY,
global_only=GLOBAL_ONLY):
override_params = copy.deepcopy(per_remote_overrides)
global_auth_params = [
.format(self... | Initialize remotes |
344,292 | def on_click(self, event):
if event[] == 1 and in self.options:
subprocess.call(self.options[].split())
elif event[] == 2 and in self.options:
subprocess.call(self.options[].split())
elif event[] == 3 and in self.options:
subprocess.call(self.optio... | A function that should be overwritten by a plugin that wishes to react
to events, if it wants to perform any action other than running the
supplied command related to a button.
event: A dictionary passed from i3bar (after being decoded from JSON)
that has the folowing format:
e... |
344,293 | def setCurrentQuery( self, query ):
self.clear()
for entry in query:
self.addLineWidget(entry)
for i in range(self.minimumCount() - len(query)):
self.addLineWidget() | Sets the query for this system to the inputed query.
:param query | [(<str> term, <str> operator, <str> value), ..] |
344,294 | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
logging.debug(, epoch_id, self._file_path)
if not self._header_written:
self._write_header(epoch_data=epoch_data)
self._write_row(epoch_id=epoch_id, epoch_data=epoch_data) | Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged |
344,295 | def do_status(self, _):
server_status = self.server.is_server_running()
if server_status == :
print + colorize(, )
elif server_status == :
print + colorize(, )
elif server_status == :
print + colorize(, )
elif server_status == :
... | Notify user of server status. |
344,296 | def restart_required(self):
response = self.get("messages").body.read()
messages = data.load(response)[]
if not in messages:
result = False
else:
if isinstance(messages[], dict):
titles = [messages[][]]
else:
t... | Indicates whether splunkd is in a state that requires a restart.
:return: A ``boolean`` that indicates whether a restart is required. |
344,297 | def extrapolate_coverage(lines_w_status):
lines = []
prev_lineno = 0
prev_status = True
for lineno, status in lines_w_status:
while (lineno - prev_lineno) > 1:
prev_lineno += 1
if prev_status is status:
lines.append((prev_lineno, status))
... | Given the following input:
>>> lines_w_status = [
(1, True),
(4, True),
(7, False),
(9, False),
]
Return expanded lines with their extrapolated line status.
>>> extrapolate_coverage(lines_w_status) == [
(1, True),
(2, True),
(3, True),
(... |
344,298 | def discard_events(library, session, event_type, mechanism):
return library.viDiscardEvents(session, event_type, mechanism) | Discards event occurrences for specified event types and mechanisms in a session.
Corresponds to viDiscardEvents function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param event_type: Logical event identifier.
:p... |
344,299 | def get_closest_clusters(cluster_id, cluster_ids, sim_func, max_n=None):
l = [(_as_scalar(candidate), _as_scalar(sim_func(cluster_id, candidate)))
for candidate in _as_scalars(cluster_ids)]
l = sorted(l, key=itemgetter(1), reverse=True)
max_n = None or len(l)
return l[:max_n] | Return a list of pairs `(cluster, similarity)` sorted by decreasing
similarity to a given cluster. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.