Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
355,900 | def add_colorbar(self, **kwargs):
kwargs = kwargs.copy()
if self._cmap_extend is not None:
kwargs.setdefault(, self._cmap_extend)
if not in kwargs:
kwargs.setdefault(, label_from_attrs(self.data))
self.cbar = self.fig.colorbar(self._mappables[-1],
... | Draw a colorbar |
355,901 | def _execute(self, session=None):
ti_status = BackfillJob._DagRunTaskStatus()
start_date = self.bf_start_date
run_dates = self.dag.get_run_dates(start_date=start_date,
end_date=self.bf_end_date)
if self.run_backwards:
... | Initializes all components required to run a dag for a specified date range and
calls helper method to execute the tasks. |
355,902 | def selectedLogs(self):
mcclogs = []
physlogs = []
for i in range(len(self.logMenus)):
logType = self.logMenus[i].selectedType()
log = self.logMenus[i].selectedProgram()
if logType == "MCC":
if log not in mcclogs:
m... | Return selected log books by type. |
355,903 | def smart_search_vrf(self, auth, query_str, search_options=None, extra_query=None):
if search_options is None:
search_options = {}
self._logger.debug("smart_search_vrf query string: %s" % query_str)
success, query = self._parse_vrf_query(query_str)
if not success:... | Perform a smart search on VRF list.
* `auth` [BaseAuth]
AAA options.
* `query_str` [string]
Search string
* `search_options` [options_dict]
Search options. See :func:`search_vrf`.
* `extra_query` [dict_to_sql]
... |
355,904 | def delete(self, endpoint: str, **kwargs) -> dict:
return self._request(, endpoint, **kwargs) | HTTP DELETE operation to API endpoint. |
355,905 | def substitute(progression, substitute_index, depth=0):
res = []
simple_substitutions = [
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
]
p = progression[substitute_index]
(roman, acc, suff) = parse_string(p)
... | Give a list of possible substitutions for progression[substitute_index].
If depth > 0 the substitutions of each result will be recursively added
as well.
Example:
>>> substitute(['I', 'IV', 'V', 'I'], 0)
['III', 'III7', 'VI', 'VI7', 'I7'] |
355,906 | def photos(self, query, page=1, per_page=10):
url = "/search/photos"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = PhotoModel.parse_list(data.get("results"))
return data | Get a single page of photo results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u're... |
355,907 | def _get_result_paths(self,data):
_treeinfo_formats = {:,
:,
:}
result = {}
par = self.Parameters
abs = self._absolute
if par[].isOn():
prefix = par[].Value.rsplit(, 1)[0]
... | Return dict of {key: ResultPath} |
355,908 | def _handle_redirect(self, redirect, preload, query, page):
if redirect:
redirects = query["redirects"][0]
if "normalized" in query:
normalized = query["normalized"][0]
if normalized["from"] != self.title:
raise MediaWikiExcep... | handle redirect |
355,909 | def build_keys(request, database_name, collection_name):
build_keys_with_mapreduce(database_name, collection_name)
messages.success(request, _(
"Successfully completed MapReduce operation. "
"Key rebuild for custom report complete."))
return HttpResponseRedirect(reverse("djmongo_show_db... | Perform the map/reduce to refresh the keys form.
The display the custom report screen |
355,910 | def abort(err):
if _debug: abort._debug("abort %r", err)
global local_controllers
for controller in local_controllers.values():
controller.abort(err) | Abort everything, everywhere. |
355,911 | def pwm(host, seq, m1, m2, m3, m4):
at(host, , seq, [m1, m2, m3, m4]) | Sends control values directly to the engines, overriding control loops.
Parameters:
seq -- sequence number
m1 -- Integer: front left command
m2 -- Integer: front right command
m3 -- Integer: back right command
m4 -- Integer: back left command |
355,912 | def get_varied_cfg_lbls(cfg_list, default_cfg=None, mainkey=,
checkname=False):
r
import utool as ut
try:
cfgname_list = [cfg[mainkey] for cfg in cfg_list]
except KeyError:
cfgname_list = [] * len(cfg_list)
varied_cfg_list = partition_varied_cfg_list(cfg_list,... | r"""
Args:
cfg_list (list):
default_cfg (None): (default = None)
checkname (bool): if True removes names if they are all the same.
Returns:
list: cfglbl_list
CommandLine:
python -m utool.util_gridsearch --exec-get_varied_cfg_lbls
Example:
>>> # ENABLE_D... |
355,913 | def set_color(fg=None, bg=None):
if fg or bg:
_color_manager.set_color(fg, bg)
else:
_color_manager.set_defaults() | Set the current colors.
If no arguments are given, sets default colors. |
355,914 | def write_directory(self, directory: str) -> bool:
current_md5_hash = self.get_namespace_hash()
md5_hash_path = os.path.join(directory, f)
if not os.path.exists(md5_hash_path):
old_md5_hash = None
else:
with open(md5_hash_path) as file:
o... | Write a BEL namespace for identifiers, names, name hash, and mappings to the given directory. |
355,915 | def clean_perms(self):
self.log.debug()
sesh = self.get_session
pvms = (
sesh.query(sqla_models.PermissionView)
.filter(or_(
sqla_models.PermissionView.permission == None,
sqla_models.PermissionView.view_menu == None,
... | FAB leaves faulty permissions that need to be cleaned up |
355,916 | def post(self, data, request, id):
if id:
| Create a new resource using POST |
355,917 | def force_log_type_flags(self, logType, stdoutFlag, fileFlag):
self.force_log_type_stdout_flag(logType, stdoutFlag)
self.force_log_type_file_flag(logType, fileFlag) | Force a logtype logging flags.
:Parameters:
#. logType (string): A defined logging type.
#. stdoutFlag (None, boolean): The standard output logging flag.
If None, logtype stdoutFlag forcing is released.
#. fileFlag (None, boolean): The file logging flag.
... |
355,918 | def action_notify(self, action):
message = json.dumps({
: ,
: action.as_action_description(),
})
for subscriber in list(self.subscribers):
try:
subscriber.write_message(message)
except tornado.websocket.WebSocketClosedErro... | Notify all subscribers of an action status change.
action -- the action whose status changed |
355,919 | def get_drive_api_from_client_secrets(path, reset_creds=False):
storage = keyring_storage.Storage(, getpass.getuser())
credentials = None
if not reset_creds:
credentials = storage.get()
if path and not credentials:
flow = client.flow_from_clientsecrets(path, scope=OAUTH_SCOPE)
... | Reads the local client secrets file if available (otherwise, opens a
browser tab to walk through the OAuth 2.0 process, and stores the client
secrets for future use) and then authorizes those credentials. Returns a
Google Drive API service object. |
355,920 | def draw_texture(tex):
from .program import Program
program = Program(vert_draw, frag_draw)
program[] = tex
program[] = [[-1., -1.], [-1., 1.], [1., -1.], [1., 1.]]
program[] = [[0., 1.], [0., 0.], [1., 1.], [1., 0.]]
program.draw() | Draw a 2D texture to the current viewport
Parameters
----------
tex : instance of Texture2D
The texture to draw. |
355,921 | def read_string_table(xml_source):
strings = []
src = _get_xml_iter(xml_source)
for _, node in iterparse(src):
if node.tag == % SHEET_MAIN_NS:
text = Text.from_tree(node).content
text = text.replace(, )
strings.append(text)
node.clear()
r... | Read in all shared strings in the table |
355,922 | def incr(self, conn, key, increment=1):
assert self._validate_key(key)
resp = yield from self._incr_decr(
conn, b, key, increment)
return resp | Command is used to change data for some item in-place,
incrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param increment: ``int``, is the amount by ... |
355,923 | def printTPRegionParams(tpregion):
tm = tpregion.getSelf()._tfdr
print "------------PY TemporalMemory Parameters ------------------"
print "numberOfCols =", tm.getColumnDimensions()
print "cellsPerColumn =", tm.getCellsPerColumn()
print "minThreshold =", tm.getMinThreshol... | Note: assumes we are using TemporalMemory/TPShim in the TPRegion |
355,924 | def get_json_lines(annotation: ResourceAnnotation, field: str, route: str,
request: bool = False) -> List:
url_params = URL_PARAMS_RE.findall(route)
if not request:
return_type = annotation.logic._doctor_signature.return_annotation
if issubclass... | Generate documentation lines for the given annotation.
This only documents schemas of type "object", or type "list" where each
"item" is an object. Other types are ignored (but a warning is logged).
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler ... |
355,925 | def get_bank_query_session(self):
if not self.supports_bank_query():
raise errors.Unimplemented()
return sessions.BankQuerySession(runtime=self._runtime) | Gets the OsidSession associated with the bank query service.
return: (osid.assessment.BankQuerySession) - a
``BankQuerySession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bank_query() is false``
*compliance: optional -- This ... |
355,926 | def _marker_line(self):
output =
for col in sorted(self.col_widths):
line = self.COLUMN_MARK + (self.DASH * (self.col_widths[col] + self.PADDING * 2))
output += line
output += self.COLUMN_MARK +
return output | Generate a correctly sized marker line.
e.g.
'+------------------+---------+----------+---------+'
:return: str |
355,927 | def dimensions_unit(self, dimensions_unit):
allowed_values = ["inch", "cm", "foot", "meter"]
if dimensions_unit is not None and dimensions_unit not in allowed_values:
raise ValueError(
"Invalid value for `dimensions_unit` ({0}), must be one of {1}"
... | Sets the dimensions_unit of this MeasurementSettings.
:param dimensions_unit: The dimensions_unit of this MeasurementSettings.
:type: str |
355,928 | def evaluated_variants(self, case_id):
query = {
: [
{: case_id},
{
: [
{: {: True}},
{: {: True}},
{: {: True}},
]
}
... | Returns variants that has been evaluated
Return all variants, snvs/indels and svs from case case_id
which have a entry for 'acmg_classification', 'manual_rank', 'dismiss_variant'
or if they are commented.
Args:
case_id(str)
Returns:
variants(iterable(Va... |
355,929 | def merge_strings_files(old_strings_file, new_strings_file):
old_localizable_dict = generate_localization_key_to_entry_dictionary_from_file(old_strings_file)
output_file_elements = []
f = open_strings_file(new_strings_file, "r+")
for header_comment, comments, key, value in extract_header_comment_... | Merges the old strings file with the new one.
Args:
old_strings_file (str): The path to the old strings file (previously produced, and possibly altered)
new_strings_file (str): The path to the new strings file (newly produced). |
355,930 | def Get(self):
try:
with io.open(self.logfile, "rb") as fd:
data = fd.read(self.max_log_size)
except (IOError, OSError):
return
try:
if data:
return rdf_flows.GrrMessage.FromSerializedString(data)
except (message.Error, rdfvalue.Error):
return | Return a GrrMessage instance from the transaction log or None. |
355,931 | def needle(reference, query, gap_open=-15, gap_extend=0,
matrix=submat.DNA_SIMPLE):
aligned_ref, aligned_res = aligner(str(reference),
str(query),
gap_open=gap_open,
gap_extend=g... | Do a Needleman-Wunsch alignment.
:param reference: Reference sequence.
:type reference: coral.DNA
:param query: Sequence to align against the reference.
:type query: coral.DNA
:param gapopen: Penalty for opening a gap.
:type gapopen: float
:param gapextend: Penalty for extending a gap.
... |
355,932 | def getExtensionList(self,extensions):
basicList = extensions.split()
extensionList = []
for ext in basicList:
if ext == MapConstants.placeholderNoExtensionFilter:
extensionList.append()
elif ext != :
... | This is an internal method that transforms the comma-separated extensions string
into a list of extensions, e.g., "ext1,ext2,ext3" gets turned into ['.ext1','.ext2','.ext3'].
If MapConstants.placeholderNoExtensionFilter is part of the string, the resulting list
will also contain '', i.e., files ... |
355,933 | def execute_shell(self, shell=None, parent_environ=None, rcfile=None,
norc=False, stdin=False, command=None, quiet=False,
block=None, actions_callback=None, post_actions_callback=None,
context_filepath=None, start_new_session=False, detached=False,
... | Spawn a possibly-interactive shell.
Args:
shell: Shell type, for eg 'bash'. If None, the current shell type
is used.
parent_environ: Environment to run the shell process in, if None
then the current environment is used.
rcfile: Specify a file ... |
355,934 | def _expand_dims(x, input_shape, output_shape):
verify_no_new_dims([output_shape], input_shape)
if input_shape == output_shape or input_shape.ndims == 0:
return x
perm = [input_shape.dims.index(d) for d in output_shape.dims
if d in input_shape.dims]
x = tf.transpose(x, perm)
for i, d in enume... | Expand dimensions and transpose if necessary.
Args:
x: a tf.Tensor
input_shape: a Shape
output_shape: a Shape whose dimensions are a superset of
those in input_shape
Returns:
a tf.Tensor |
355,935 | def _parse_kraken_output(out_dir, db, data):
in_file = os.path.join(out_dir, "kraken_out")
stat_file = os.path.join(out_dir, "kraken_stats")
out_file = os.path.join(out_dir, "kraken_summary")
kraken_cmd = config_utils.get_program("kraken-report", data["config"])
classify = unclassify = None
... | Parse kraken stat info comming from stderr,
generating report with kraken-report |
355,936 | def modify_agent_property(self, agent_id, key, value):
my_agent_idagent_new_propertyagent value
return self._call_rest_api(, +agent_id+, data={key: value}, error=%(agent_id,key)) | modify_agent_property(self, agent_id, key, value)
Modifies a single single property of an agent. If the property does not exists then it is created as a custom property.
:Parameters:
* *agent_id* (`string`) -- Identifier of an existing agent
* *key* (`string`) -- Key of a property to c... |
355,937 | def q(self, val):
self._q = np.asarray(val)
self.Q = cumsum(val) | Setter method for q. |
355,938 | def npinterpn(*args, **kw):
method = kw.pop(, )
if kw:
raise ValueError("Unknown arguments: " % kw.keys())
nd = (len(args)-1)//2
if len(args) != 2*nd+1:
raise ValueError("Wrong number of arguments")
q = args[:nd]
qi = args[nd+1:]
a = args[nd]
for j in range(nd):
a = interp(q[j], a, axis=j, kind=metho... | Interpolation on N-D.
ai = interpn(x, y, z, ..., a, xi, yi, zi, ...)
where the arrays x, y, z, ... define a rectangular grid
and a.shape == (len(x), len(y), len(z), ...) are the values
interpolate at xi, yi, zi, ... |
355,939 | def register():
assert isinstance(request.json, dict),
required_attributes = [, , , , , ,
]
required_metadata_base_attributes = [, , , ,
, , , ]
data = request.json
if not data:
logger.error(f)
return 400
m... | Register DDO of a new asset
---
tags:
- ddo
consumes:
- application/json
parameters:
- in: body
name: body
required: true
description: DDO of the asset.
schema:
type: object
required:
- "@context"
- id
... |
355,940 | def connect_ssh(*args, **kwds):
if "device_params" in kwds:
device_params = kwds["device_params"]
del kwds["device_params"]
else:
device_params = None
device_handler = make_device_handler(device_params)
device_handler.add_additional_ssh_connect_params(kwds)
... | Initialize a :class:`Manager` over the SSH transport.
For documentation of arguments see :meth:`ncclient.transport.SSHSession.connect`.
The underlying :class:`ncclient.transport.SSHSession` is created with
:data:`CAPABILITIES`. It is first instructed to
:meth:`~ncclient.transport.SSHSession.loa... |
355,941 | def close(self, destroy=False, sync=False, timeout=None):
_SharedPV.close(self, destroy)
if sync:
self._queue.sync()
self._disconnected.wait() | Close PV, disconnecting any clients.
:param bool destroy: Indicate "permanent" closure. Current clients will not see subsequent open().
:param bool sync: When block until any pending onLastDisconnect() is delivered (timeout applies).
:param float timeout: Applies only when sync=True. None for... |
355,942 | def output(self, args):
print("SensuPlugin: {}".format(.join(str(a) for a in args))) | Print the output message. |
355,943 | def verify_request(self, query, binding):
resp_args = {}
if not query:
logger.info("Missing QUERY")
resp = Unauthorized("Unknown user")
return resp_args, resp(self.environ, self.start_response)
if not self.req_info:
self.req_info = IDP.pa... | :param query: The SAML query, transport encoded
:param binding: Which binding the query came in over |
355,944 | def hosts(self):
network = int(self.network_address)
broadcast = int(self.broadcast_address)
for x in long_range(1, broadcast - network + 1):
yield self._address_class(network + x) | Generate Iterator over usable hosts in a network.
This is like __iter__ except it doesn't return the
Subnet-Router anycast address. |
355,945 | def check_reachable(self, forced=False, test=False):
all_ok = True
self.not_configured = []
for daemon_link in self.all_daemons_links:
if daemon_link == self.arbiter_link:
continue
if not daemon_link.active:
... | Check all daemons state (reachable or not)
If test parameter is True, do not really send but simulate only for testing purpose...
The update_infos function returns None when no ping has been executed
(too early...), or True / False according to the real ping and get managed
configurati... |
355,946 | def make_code_obsolete(code):
fs = FileSystem(code=code)
if os.path.exists(fs.parent_dir):
destination_dir = os.path.join(fs._data_dir, , code[1:3], code)
if os.path.exists(destination_dir):
shutil.rmtree(destination_dir)
shutil.move(fs.parent_dir, destination_d... | Moves folders associated with PDB code to obsolete folder in global_settings["database_dir"]
Parameters
----------
code : str
PDB accession code
Returns
-------
None |
355,947 | def delta_ps(prev, curr, counters):
counter = get_counter(counters)
pv = getattr(prev, counter)
cv = getattr(curr, counter)
return minus(cv, pv) | calculate the delta per second of one counter
formula: (curr - prev) / delta_time
:param prev: previous resource
:param curr: current resource
:param counters: the counter to do delta and per second, one only
:return: value, NaN if invalid. |
355,948 | def load_swagger_config(name, base_url, config):
if isinstance(config, collections.abc.Mapping):
pass
elif isinstance(config, str):
with pathlib.Path(config).open() as infile:
config = yaml.load(infile)
elif isinstance(config, pathlib.Path):
with config.open() as infile:
... | Load a restful service specified by some YAML file at config_path.
:param config_path: A pathlib Path object that points to the yaml
config
:returns: A python module containing a Client class, call factory,
and the definition of each of the APIs defined by the config. |
355,949 | def merge(self, dest, *others):
items = [self.key]
items.extend([other.key for other in others])
self.database.pfmerge(dest, *items)
return HyperLogLog(self.database, dest) | Merge one or more :py:class:`HyperLogLog` instances.
:param dest: Key to store merged result.
:param others: One or more ``HyperLogLog`` instances. |
355,950 | def validate(self, data):
for v in self.validators:
v(self, data)
return data | Runs all field validators. |
355,951 | def update(self, byts):
self.size += len(byts)
[h[1].update(byts) for h in self.hashes] | Update all the hashes in the set with the given bytes. |
355,952 | def get(self, index, n_cols=70):
if index < 0:
raise IndexError
nsfw_count = 0
while index >= len(self._submission_data):
try:
with self._loader():
submission = next(self._submissions)
if self._loader.exceptio... | Grab the `i`th submission, with the title field formatted to fit inside
of a window of width `n_cols` |
355,953 | def _api_path(self, item):
if self.base_url is None:
raise NotImplementedError("base_url not set")
path = "/".join([x.blob["id"] for x in item.path])
return "/".join([self.base_url, path]) | Get the API path for the current cursor position. |
355,954 | def send_notifications(self, notification_data):
content = self._serialize.body(notification_data, )
self._send(http_method=,
location_id=,
version=,
content=content) | SendNotifications.
[Preview API] Send Notification
:param :class:`<NotificationsData> <azure.devops.v5_1.gallery.models.NotificationsData>` notification_data: Denoting the data needed to send notification |
355,955 | def mark_failed_exc(self, e_val=None, e_ty=None):
_error_from_exc(self.nsdk, self.handle, e_val, e_ty) | Marks the tracer as failed with the given exception :code:`e_val` of
type :code:`e_ty` (defaults to the current exception).
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this does not end the tracer! Once a
tracer is marked as ... |
355,956 | def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine=,
saltenv=,
template_hash=None,
template_hash_name=None,
skip_verify=Fa... | Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the... |
355,957 | def get_line(self, text, on_unicode_error=):
def check(entry):
if entry.find() != -1:
raise ValueError(
"get_line processes one line at a time (remove \)"
)
entry += "\n"
return entry
if type(text) == list... | Split a line of text into words and labels. Labels must start with
the prefix used to create the model (__label__ by default). |
355,958 | def json_safe(string, content_type=):
try:
string = string.decode()
json.dumps(string)
return string
except (ValueError, TypeError):
return b.join([
b,
content_type.encode(),
b,
base64.b64encode(string)
]).decode() | Returns JSON-safe version of `string`.
If `string` is a Unicode string or a valid UTF-8, it is returned unmodified,
as it can safely be encoded to JSON string.
If `string` contains raw/binary data, it is Base64-encoded, formatted and
returned according to "data" URL scheme (RFC2397). Since JSON is not... |
355,959 | def run_command(command, capture=None, check=False, encoding=, shell=False, env=None):
if shell == :
shell = NEED_SHELL
if isinstance(command, string_types) and not ON_WINDOWS:
command = shlex.split(command)
if capture:
if capture is True or capture == :
stdout, st... | This function provides a convenient API wrapping subprocess.Popen. Captured output
is guaranteed not to deadlock, but will still reside in memory in the end.
:param command: The command to run in a subprocess.
:type command: ``str`` or ``list`` of ``str``
:param capture: The method of output capture:
... |
355,960 | def transform(images, out_dir, fname):
from PIL import Image as PILImage
base = os.path.join(out_dir, "media", "images")
width, height = images[0].image.size
num_images_to_log = len(images)
if num_images_to_log > Image.MAX_IMAGES:
logging.warn(
... | Combines a list of images into a single sprite returning meta information |
355,961 | def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False):
assert format in [None, , ]
if format is None:
dump_fn = dumps
else:
from zmq_ops import dump_arrays
dump_fn = dump_arrays
ctx = zmq.Context()
socket = ctx.socket(zmq.PUSH)
socket.set_hwm(hwm)
if ... | Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
addr: a ZMQ socket endpoint.
hwm (int): ZMQ high-water mark (buffe... |
355,962 | def draw_circle(ctx, x, y, radius, cairo_color):
ctx.new_path()
ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)
ctx.arc(x, y, radius, 0, 2 * pi)
ctx.fill() | Draw a circle.
:param radius: radius in pixels
:param cairo_color: normalized rgb color |
355,963 | def run_simulation(projectname: str, xmlfile: str):
write = commandtools.print_textandtime
hydpy.pub.options.printprogress = False
write(f)
hp = hydpytools.HydPy(projectname)
write(f)
interface = XMLInterface(xmlfile)
write()
interface.update_options()
hydpy.pub.options.printpro... | Perform a HydPy workflow in agreement with the given XML configuration
file available in the directory of the given project. ToDo
Function |run_simulation| is a "script function" and is normally used as
explained in the main documentation on module |xmltools|. |
355,964 | def _neg(node):
if node is BDDNODEZERO:
return BDDNODEONE
elif node is BDDNODEONE:
return BDDNODEZERO
else:
return _bddnode(node.root, _neg(node.lo), _neg(node.hi)) | Return the inverse of *node*. |
355,965 | def collect(self):
metrics = {}
if in self.config:
for ld in os.listdir(self.config[]):
if in ld:
self.read_values(ld, self.config[], metrics)
for oid, files in self.config.iteritems():
if oid[:3] == :
self... | Overrides the Collector.collect method |
355,966 | def double(window, config):
cordx = round(config.get(, 0))
color = config.get(, red)
icon = config.get(, )
width = config.get(, window.width)
title = config.get(, .center(width - 2))
back = config.get(, )
align = config.get(, )
term = window.term
line = color(icon * width)
... | Double theme
==================
= Header =
==================
= items =
==================
= footer =
================== |
355,967 | def remove_lower_overlapping(current, higher):
for (match, h_start, h_end) in higher:
overlaps = list(overlapping_at(h_start, h_end, current))
for overlap in overlaps:
del current[overlap]
if len(overlaps) > 0:
current.insert(overlaps[0], (match, h_s... | >>> remove_lower_overlapping([], [('a', 0, 5)])
[('a', 0, 5)]
>>> remove_lower_overlapping([('z', 0, 4)], [('a', 0, 5)])
[('a', 0, 5)]
>>> remove_lower_overlapping([('z', 5, 6)], [('a', 0, 5)])
[('z', 5, 6), ('a', 0, 5)] |
355,968 | def get_config(name=):
*
try:
config = snapper.GetConfig(name)
return config
except dbus.DBusException as exc:
raise CommandExecutionError(
.format(_dbus_exception_to_reason(exc, locals()))
) | Retrieves all values from a given configuration
CLI example:
.. code-block:: bash
salt '*' snapper.get_config |
355,969 | def _inv_sqrtm(x):
vals, vecs = np.linalg.eigh(x)
return (vecs / np.sqrt(vals)).dot(vecs.T) | Computes x^(-1/2) |
355,970 | def is_timestamp_valid(self, timestamp):
try:
timestamp_server = datetime.utcnow()
timestamp_client = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")
d1_ts = time.mktime(timestamp_client.timetuple())
d2_ts = time.mktime(timestamp_server.timetuple())
... | Timestamp must be string in %Y-%m-%dT%H:%M:%S. format |
355,971 | def get_caller_name(N=0, strict=True):
if isinstance(N, (list, tuple)):
name_list = []
for N_ in N:
try:
name_list.append(get_caller_name(N_))
except AssertionError:
name_list.append()
return + .join(name_list) +
parent_... | Standalone version of get_caller_name |
355,972 | def multikey_sort(items, columns):
comparers = [
((itemgetter(col[1:].strip()), -1) if col.startswith() else (itemgetter(col.strip()), 1))
for col in columns
]
def cmp(a, b):
return (a > b) - (a < b)
def comparer(left, right):
comparer_iter = (
cmp(fn(l... | Source: https://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys |
355,973 | def choose_coord_units(header):
cunit = header[]
match = re.match(r, cunit)
if match:
return
| Return the appropriate key code for the units value for the axes by
examining the FITS header. |
355,974 | def text_index(self):
i = self.tags.get(TextElement, 0)
if self.last_tag is not TextElement:
i += 1
return i | Returns the one-based index of the current text node. |
355,975 | def follow(self):
data = json.dumps({"action": "follow"})
r = requests.post(
"https://kippt.com/api/users/%s/relationship" % (self.id),
headers=self.kippt.header,
data=data
)
return (r.json()) | Follow a user." |
355,976 | def add_physical_item(self, instance, item):
(name, dev_type) = self.device_typename(item)
self.topology[][name] = {}
self.topology[][name][] = self.hv_id
self.topology[][name][] = self.nid
self.topology[][name][] = dev_type[]
self.topology[][name][] = dev_type[]... | Add a physical item e.g router, cloud etc
:param instance: Hypervisor instance
:param item: Item to add |
355,977 | def pl (listoflists):
for row in listoflists:
if row[-1] == :
print(row, end=)
else:
print(row)
return None | Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None |
355,978 | def branches(self):
for branch in self._grid.graph_edges():
if branch[].ring == self:
yield branch | #TODO: description |
355,979 | def createProduct(self, powerups):
types = [qual(powerup).decode()
for powerup in powerups]
for p in self.store.parent.query(Product):
for t in types:
if t in p.types:
raise ValueError("%s is already included in a Product" %... | Create a new L{Product} instance which confers the given
powerups.
@type powerups: C{list} of powerup item types
@rtype: L{Product}
@return: The new product instance. |
355,980 | def _rel(self, copy=False):
rel = {}
for key, obj in vars(self).items():
if not isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)) and not key.startswith():
if copy and not in key:
rel[key] = deepcopy(obj)
... | Get descriptive kwargs of the container (e.g. name, description, meta). |
355,981 | def relative_symlink(target, link_name):
link_name = os.path.abspath(link_name)
abs_target = os.path.abspath(target)
rel_target = os.path.relpath(target, os.path.dirname(link_name))
if os.path.exists(link_name):
os.remove(link_name)
os.symlink(rel_target, link_name) | Make a symlink to target using the shortest possible relative path. |
355,982 | def verify_client(endpoint_context, request, authorization_info):
if not authorization_info:
if in request and in request:
auth_info = ClientSecretPost(endpoint_context).verify(request)
auth_info[] =
elif in request:
auth_info = JWSAuthnMethod(endpoint_c... | Initiated Guessing !
:param endpoint_context: SrvInfo instance
:param request: The request
:param authorization_info: Client authentication information
:return: dictionary containing client id, client authentication method and
possibly access token. |
355,983 | def RequestPacket(self):
attr = self._PktEncodeAttributes()
if self.authenticator is None:
self.authenticator = self.CreateAuthenticator()
if self.id is None:
self.id = self.CreateID()
header = struct.pack(, self.code, self.id,
(20 + len(at... | Create a ready-to-transmit authentication request packet.
Return a RADIUS packet which can be directly transmitted
to a RADIUS server.
:return: raw packet
:rtype: string |
355,984 | def _populate_ha_information(self, context, router):
r_r_b = self._get_redundancy_router_bindings(
context, redundancy_router_id=router[])
if not r_r_b:
if router[ha.ENABLED]:
user_router_id = router[]
fips = []
... | To be called when router information, including router interface
list, (for the l3_cfg_agent) has been collected so it is extended
with ha information. |
355,985 | def add_app_template_filter(self, f, name=None):
def register_template(state):
state.app.jinja_env.filters[name or f.__name__] = f
self.record_once(register_template) | Register a custom template filter, available application wide. Like
:meth:`Flask.add_template_filter` but for a blueprint. Works exactly
like the :meth:`app_template_filter` decorator.
:param name: the optional name of the filter, otherwise the
function name will be used. |
355,986 | def identify_and_tag_URLs(line):
line_pre_url_check = line
found_url_full_matchlen = {}
found_url_urlstring = {}
found_url_urldescr = {}
identified_urls = []
m_tagged_url_iter = re_html_tagged_url.finditer(line)
for m_tagged_url in m_tagged_url_iter:
startp... | Given a reference line, identify URLs in the line, record the
information about them, and replace them with a "<cds.URL />" tag.
URLs are identified in 2 forms:
+ Raw: http://invenio-software.org/
+ HTML marked-up: <a href="http://invenio-software.org/">CERN Document
Server Softw... |
355,987 | def is_suspicious( pe ):
relocations_overlap_entry_point = False
sequential_relocs = 0
warnings_while_parsing = False
warnings = pe.get_warnings()
if warnings:
warnings_while_parsing
pass | unusual locations of import tables
non recognized section names
presence of long ASCII strings |
355,988 | def diff_values(value_a, value_b, raw=False):
if not raw:
value_a = _process_value(value_a)
value_b = _process_value(value_b)
if value_a == value_b:
return None
diffs = []
diffs.append((value_a, value_b))
return diffs | Returns a human-readable diff between two values
:param value_a: First value to compare
:param value_b: Second value to compare
:param raw: True to compare the raw values, e.g. UIDs
:returns a list of diff tuples |
355,989 | def dSbr_dV(Yf, Yt, V, buses, branches):
nl = len(branches)
nb = len(V)
f = matrix([l.from_bus._i for l in branches])
t = matrix([l.to_bus._i for l in branches])
If = Yf * V
It = Yt * V
Vnorm = div(V, abs(V))
diagVf = spdiag(V[f])
diagIf = spdiag(If)
diagVt = spdiag... | Computes the branch power flow vector and the partial derivative of
branch power flow w.r.t voltage. |
355,990 | def plot_resp_slow(signal, rect_signal, sample_rate):
signal = numpy.array(signal) - numpy.average(signal)
rect_signal = numpy.array(rect_signal)
time = numpy.linspace(0, len(signal) / sample_rate, len(signal))
rect_signal_rev = rect_signal - numpy.average(rect_signal)
inhal_segment... | -----
Brief
-----
Figure intended to represent the acquired RIP signal together with a rectangular signal defining
inhalation and exhalation periods.
-----------
Description
-----------
Function design to generate a Bokeh figure containing the evolution of RIP signal, when
slow resp... |
355,991 | def _compute_mean(self, C, A1, A2, A3, A4, A5, A6, mag, hypo_depth,
rrup, mean, idx):
mean[idx] = (A1 + A2 * mag + C[] + C[] * (A3 - mag) ** 3 +
C[] * np.log(rrup[idx] + A4 * np.exp(A5 * mag)) +
A6 * hypo_depth) | Compute mean for subduction interface events, as explained in table 2,
page 67. |
355,992 | def do_get_page(parser, token):
bits = token.split_contents()
if 4 != len(bits):
raise TemplateSyntaxError( % bits[0])
if bits[-2] != :
raise TemplateSyntaxError(
% bits[0])
page_filter = parser.compile_filter(bits[1])
varname = bits[-1]
return GetPageNode(page_... | Retrieve a page and insert into the template's context.
Example::
{% get_page "news" as news_page %}
:param page: the page object, slug or id
:param name: name of the context variable to store the page in |
355,993 | async def login(self, user=DEFAULT_USER, password=DEFAULT_PASSWORD,
account=DEFAULT_ACCOUNT):
code, info = await self.command("USER " + user, ("230", "33x"))
while code.matches("33x"):
if code == "331":
cmd = "PASS " + password
elif co... | :py:func:`asyncio.coroutine`
Server authentication.
:param user: username
:type user: :py:class:`str`
:param password: password
:type password: :py:class:`str`
:param account: account (almost always blank)
:type account: :py:class:`str`
:raises aioftp... |
355,994 | def search(cls, args):
safe_shell_pat = re.escape(args[]).replace(r, )
pat_str = .format(safe_shell_pat)
pattern = re.compile(pat_str, re.IGNORECASE)
remote_json = NAppsManager.search(pattern)
remote = set()
for napp in remote_json:
... | Search for NApps in NApps server matching a pattern. |
355,995 | def logger(self):
if not self.is_main:
return self.main.logger
try:
return self._logger
except AttributeError:
name = % (self.__module__, self.__class__.__name__,
self.num)
self._logger = logging.getLogger... | :class:`logging.Logger` of this instance |
355,996 | def downloadarchive(self, project, targetfile, archiveformat = ):
if isinstance(targetfile,str) or (sys.version < and isinstance(targetfile,unicode)):
targetfile = open(targetfile,)
r = requests.get(self.url + project + + archiveformat,**self.initrequest())
CHUNK = 16 * 1... | Download all output files as a single archive:
* *targetfile* - path for the new local file to be written
* *archiveformat* - the format of the archive, can be 'zip','gz','bz2'
Example::
client.downloadarchive("myproject","allresults.zip","zip") |
355,997 | def _timestep_cull(self, timestep):
new_values = []
new_datetimes = []
mins_per_step = int(60 / timestep)
for i, date_t in enumerate(self.datetimes):
if date_t.moy % mins_per_step == 0:
new_datetimes.append(date_t)
new_values.append(se... | Cull out values that do not fit a timestep. |
355,998 | def set_session_data(self, session_data):
if session_data:
for field in self._fields:
if isinstance(field, (Container, Dynamic)):
field.set_session_data(session_data) | Set session data in the container enclosed fields
:param session_data: dictionary of session data |
355,999 | def signal(*args, **kwargs):
from .core import Signal
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return Signal(fvalidation=args[0])
else:
sig = Signal(*args, **kwargs)
def wrapper(fvalidation):
sig._set_fvalidation(fvalidation)
return s... | A signal decorator designed to work both in the simpler way, like:
.. code:: python
@signal
def validation_function(arg1, ...):
'''Some doc'''
and also as a double-called decorator, like
.. code:: python
@signal(SignalOptions.EXEC_CONCURRENT)
def validation_function(ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.