code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def _parse(self, line):
try:
result = line.split(':', maxsplit=4)
filename, line_num_txt, column_txt, message_type, text = result
except ValueError:
return
try:
self.line_num = int(line_num_txt.strip())
self.column = int(column_txt.stri... | Parse the output line |
def content_type(self, data):
self._content_type = str(data)
self.add_header('Content-Type', str(data)) | The Content-Type header value for this request. |
def _construct_permission(self, function, source_arn=None, source_account=None, suffix="", event_source_token=None):
lambda_permission = LambdaPermission(self.logical_id + 'Permission' + suffix,
attributes=function.get_passthrough_resource_attributes())
try:
... | Constructs the Lambda Permission resource allowing the source service to invoke the function this event
source triggers.
:returns: the permission resource
:rtype: model.lambda_.LambdaPermission |
def validate_body(schema):
location = get_callsite_location()
def decorator(fn):
validate_schema(schema)
wrapper = wrap_request(fn, schema)
record_schemas(
fn, wrapper, location, request_schema=sort_schema(schema))
return wrapper
return decorator | Validate the body of incoming requests for a flask view.
An example usage might look like this::
from snapstore_schemas import validate_body
@validate_body({
'type': 'array',
'items': {
'type': 'object',
'properties': {
... |
def show_dependencies(self, stream=sys.stdout):
def child_iter(node):
return [d.node for d in node.deps]
def text_str(node):
return colored(str(node), color=node.status.color_opts["color"])
for task in self.iflat_tasks():
print(draw_tree(task, child_iter, text... | Writes to the given stream the ASCII representation of the dependency tree. |
def _prepareSubForm(self, liveForm):
liveForm = liveForm.asSubForm(self.name)
if self._parameterIsCompact:
liveForm.compact()
return liveForm | Utility for turning liveforms into subforms, and compacting them as
necessary.
@param liveForm: a liveform.
@type liveForm: L{LiveForm}
@return: a sub form.
@rtype: L{LiveForm} |
def srv_event(token, hits, url=RBA_URL):
if url is None:
log.error("Please provide a valid RainbowAlga URL.")
return
ws_url = url + '/message'
if isinstance(hits, pd.core.frame.DataFrame):
pos = [tuple(x) for x in hits[['x', 'y', 'z']].values]
time = list(hits['time'])
... | Serve event to RainbowAlga |
def nmf_tsne(data, k, n_runs=10, init='enhanced', **params):
clusters = []
nmf = NMF(k)
tsne = TSNE(2)
km = KMeans(k)
for i in range(n_runs):
w = nmf.fit_transform(data)
h = nmf.components_
tsne_wh = tsne.fit_transform(w.dot(h).T)
clust = km.fit_predict(tsne_wh)
... | runs tsne-consensus-NMF
1. run a bunch of NMFs, get W and H
2. run tsne + km on all WH matrices
3. run consensus clustering on all km results
4. use consensus clustering as initialization for a new run of NMF
5. return the W and H from the resulting NMF run |
def update_redirect(self):
page_history = Stack(session.get("page_history", []))
page_history.push(request.url)
session["page_history"] = page_history.to_json() | Call it on your own endpoint's to update the back history navigation.
If you bypass it, the next submit or back will go over it. |
def update(self, iteration, fobj):
self.bst.update(self.dtrain, iteration, fobj) | Update the boosters for one iteration |
def only_passed_and_wait(result):
verdict = result.get("verdict", "").strip().lower()
if verdict in Verdicts.PASS + Verdicts.WAIT:
return result
return None | Returns PASS and WAIT results only, skips everything else. |
def queue_bind(self, queue, exchange, routing_key, arguments=None):
return self.channel.queue_bind(queue=queue,
exchange=exchange,
routing_key=routing_key,
arguments=arguments) | Bind queue to an exchange using a routing key. |
def disable_snapshots(self, volume_id, schedule_type):
return self.client.call('Network_Storage', 'disableSnapshots',
schedule_type, id=volume_id) | Disables snapshots for a specific block volume at a given schedule
:param integer volume_id: The id of the volume
:param string schedule_type: 'HOURLY'|'DAILY'|'WEEKLY'
:return: Returns whether successfully disabled or not |
def rollaxis(vari, axis, start=0):
if isinstance(vari, Poly):
core_old = vari.A.copy()
core_new = {}
for key in vari.keys:
core_new[key] = rollaxis(core_old[key], axis, start)
return Poly(core_new, vari.dim, None, vari.dtype)
return numpy.rollaxis(vari, axis, start) | Roll the specified axis backwards, until it lies in a given position.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input array or polynomial.
axis (int):
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
... |
def format_endpoint(schema, addr, port, api_version):
return '{}://{}:{}/{}/'.format(schema, addr, port,
get_api_suffix(api_version)) | Return a formatted keystone endpoint
@param schema: http or https
@param addr: ipv4/ipv6 host of the keystone service
@param port: port of the keystone service
@param api_version: 2 or 3
@returns a fully formatted keystone endpoint |
def _set_final_freeness(self, flag):
if flag:
self.state.memory.store(self.heap_base + self.heap_size - self._chunk_size_t_size, ~CHUNK_P_MASK)
else:
self.state.memory.store(self.heap_base + self.heap_size - self._chunk_size_t_size, CHUNK_P_MASK) | Sets the freedom of the final chunk. Since no proper chunk follows the final chunk, the heap itself manages
this. Nonetheless, for now it is implemented as if an additional chunk followed the final chunk. |
def _create_filter_dsl(urlkwargs, definitions):
filters = []
for name, filter_factory in definitions.items():
values = request.values.getlist(name, type=text_type)
if values:
filters.append(filter_factory(values))
for v in values:
urlkwargs.add(name, v)
... | Create a filter DSL expression. |
def __generate_key(self, config):
cwd = config.get('ssh_path', self._install_directory())
if config.is_affirmative('create', default="yes"):
if not os.path.exists(cwd):
os.makedirs(cwd)
if not os.path.exists(os.path.join(cwd, config.get('keyname'))):
... | Generate the ssh key, and return the ssh config location |
def destroy(self):
self.stop()
if self.base_pathname is not None:
self._robust_remove(self.base_pathname) | Undo the effects of initdb.
Destroy all evidence of this DBMS, including its backing files. |
def _extract_image_urls(arg: Message_T) -> List[str]:
arg_as_msg = Message(arg)
return [s.data['url'] for s in arg_as_msg
if s.type == 'image' and 'url' in s.data] | Extract all image urls from a message-like object. |
def iterpackages(self):
pkgdir = os.path.join(self._path, self.PKG_DIR)
if not os.path.isdir(pkgdir):
return
for team in sub_dirs(pkgdir):
for user in sub_dirs(self.team_path(team)):
for pkg in sub_dirs(self.user_path(team, user)):
pkgp... | Return an iterator over all the packages in the PackageStore. |
def _handle_aui(self, data):
msg = AUIMessage(data)
self.on_aui_message(message=msg)
return msg | Handle AUI messages.
:param data: RF message to parse
:type data: string
:returns: :py:class`~alarmdecoder.messages.AUIMessage` |
def set_attributes(self, attr_obj=None, ns_uri=None, **attr_dict):
self._set_element_attributes(self.impl_node,
attr_obj=attr_obj, ns_uri=ns_uri, **attr_dict) | Add or update this element's attributes, where attributes can be
specified in a number of ways.
:param attr_obj: a dictionary or list of attribute name/value pairs.
:type attr_obj: dict, list, tuple, or None
:param ns_uri: a URI defining a namespace for the new attributes.
:type... |
def filter_content_types(self, content_type_qs):
valid_ct_ids = []
for ct in content_type_qs:
model = ct.model_class()
if model and issubclass(model, EventBase):
valid_ct_ids.append(ct.id)
return content_type_qs.filter(pk__in=valid_ct_ids) | Filter the content types selectable to only event subclasses |
def instances_changed(self):
value = bool(lib.EnvGetInstancesChanged(self._env))
lib.EnvSetInstancesChanged(self._env, int(False))
return value | True if any instance has changed. |
def on(self, event):
handler = self._handlers.get(event, None)
if not handler:
raise ValueError("Unknown event '{}'".format(event))
return handler.register | Returns a wrapper for the given event.
Usage:
@dispatch.on("my_event")
def handle_my_event(foo, bar, baz):
... |
def get_matrix_from_list(self, rows, columns, matrix_list, rowBased=True):
resultMatrix = Matrix(columns, rows, matrix_list, rowBased)
return resultMatrix | Create a new Matrix instance from a matrix_list.
:note: This method is used to create a Matrix instance using cpython.
:param integer rows: The height of the Matrix.
:param integer columns: The width of the Matrix.
:param matrix_list: A one dimensional list containing... |
def set_location(self, obj, cursor):
if (hasattr(cursor, 'location') and cursor.location is not None and
cursor.location.file is not None):
obj.location = (cursor.location.file.name, cursor.location.line)
return | Location is also used for codegeneration ordering. |
def render_template(process, template_string, context):
from resolwe.flow.managers import manager
expression_engine = process.requirements.get('expression-engine', None)
if not expression_engine:
return template_string
return manager.get_expression_engine(expression_engine).evaluate_block(templa... | Render template using the specified expression engine. |
def instance(cls, *args, **kwgs):
if not hasattr(cls, "_instance"):
cls._instance = cls(*args, **kwgs)
return cls._instance | Will be the only instance |
def findNestedNamespaces(self, lst):
if self.kind == "namespace":
lst.append(self)
for c in self.children:
c.findNestedNamespaces(lst) | Recursive helper function for finding nested namespaces. If this node is a
namespace node, it is appended to ``lst``. Each node also calls each of its
child ``findNestedNamespaces`` with the same list.
:Parameters:
``lst`` (list)
The list each namespace node is to ... |
def haversine(point1, point2, unit='km'):
AVG_EARTH_RADIUS_KM = 6371.0088
conversions = {'km': 1,
'm': 1000,
'mi': 0.621371192,
'nmi': 0.539956803,
'ft': 3280.839895013,
'in': 39370.078740158}
avg_earth_radius = A... | Calculate the great-circle distance between two points on the Earth surface.
:input: two 2-tuples, containing the latitude and longitude of each point
in decimal degrees.
Keyword arguments:
unit -- a string containing the initials of a unit of measurement (i.e. miles = mi)
default 'km' (ki... |
def get_urlhash(self, url, fmt):
with self.open(os.path.basename(url)) as f:
return {'url': fmt(url), 'sha256': filehash(f, 'sha256')} | Returns the hash of the file of an internal url |
def trigger_info(self, trigger=None, dump=False):
if dump:
return self._syntax
response = None
for category in self._syntax:
for topic in self._syntax[category]:
if trigger in self._syntax[category][topic]:
if response is None:
... | Get information about a trigger.
Pass in a raw trigger to find out what file name and line number it
appeared at. This is useful for e.g. tracking down the location of the
trigger last matched by the user via ``last_match()``. Returns a list
of matching triggers, containing their topics... |
def get_locator(self, dmin, dmax):
'Pick the best locator based on a distance.'
_check_implicitly_registered()
delta = relativedelta(dmax, dmin)
num_days = (delta.years * 12.0 + delta.months) * 31.0 + delta.days
num_sec = (delta.hours * 60.0 + delta.minutes) * 60.0 + delta.second... | Pick the best locator based on a distance. |
def endings(self):
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
return self.get_analysis_element(ENDING) | The list of word endings.
Ambiguous cases are separated with pipe character by default.
Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries. |
def update_is_start(self):
self.is_start = self.state.is_root_state or \
self.parent is None or \
isinstance(self.parent.state, LibraryState) or \
self.state.state_id == self.state.parent.start_state_id | Updates the `is_start` property of the state
A state is a start state, if it is the root state, it has no parent, the parent is a LibraryState or the state's
state_id is identical with the ContainerState.start_state_id of the ContainerState it is within. |
def probably_wkt(text):
valid = False
valid_types = set([
'POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT',
'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION',
])
matched = re.match(r'(\w+)\s*\([^)]+\)', text.strip())
if matched:
valid = matched.group(1).upper() in valid_t... | Quick check to determine if the provided text looks like WKT |
def show_config():
ret = {}
cmd = 'cpan -J'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if '=>' not in line:
continue
comps = line.split('=>')
key = comps[0].replace("'", '').strip()
val = comps[1].replace("',", '').replace("'", '').strip()
... | Return a dict of CPAN configuration values
CLI Example:
.. code-block:: bash
salt '*' cpan.show_config |
def load_or_create_client_key(pem_path):
acme_key_file = pem_path.asTextMode().child(u'client.key')
if acme_key_file.exists():
key = serialization.load_pem_private_key(
acme_key_file.getContent(),
password=None,
backend=default_backend())
else:
key = gener... | Load the client key from a directory, creating it if it does not exist.
.. note:: The client key that will be created will be a 2048-bit RSA key.
:type pem_path: ``twisted.python.filepath.FilePath``
:param pem_path: The certificate directory
to use, as with the endpoint. |
def get_data():
data, targets = make_classification(
n_samples=1000,
n_features=45,
n_informative=12,
n_redundant=7,
random_state=134985745,
)
return data, targets | Synthetic binary classification dataset. |
def _make_xml(self, endpoints):
root = ElementTree.Element(TAG_ENDPOINT_DESCRIPTIONS)
for endpoint in endpoints:
self._make_endpoint(root, endpoint)
self._indent(root)
return root | Converts the given endpoint description beans into an XML Element
:param endpoints: A list of EndpointDescription beans
:return: A string containing an XML document |
def is_free(self):
raise NotImplementedError("%s not implemented for %s" % (self.is_free.__func__.__name__,
self.__class__.__name__)) | Returns a concrete determination as to whether the chunk is free. |
def run_fn(self, name, *args, **kwds):
fn = None
to_check = [picardrun]
for ns in to_check:
try:
fn = getattr(ns, name)
break
except AttributeError:
pass
assert fn is not None, "Could not find function %s in %s" % (n... | Run pre-built functionality that used Broad tools by name.
See the gatkrun, picardrun module for available functions. |
def legacy_requests_view(request, rtype):
if not rtype in ['food', 'maintenance']:
raise Http404
requests_dict = []
requests = TeacherRequest.objects.filter(request_type=rtype)
request_count = requests.count()
paginator = Paginator(requests, 50)
page = request.GET.get('page')
try:
... | View to see legacy requests of rtype request type, which should be either
'food' or 'maintenance'. |
def initialize_variables(sess, saver, logdir, checkpoint=None, resume=None):
sess.run(tf.group(
tf.local_variables_initializer(),
tf.global_variables_initializer()))
if resume and not (logdir or checkpoint):
raise ValueError('Need to specify logdir to resume a checkpoint.')
if logdir:
state = ... | Initialize or restore variables from a checkpoint if available.
Args:
sess: Session to initialize variables in.
saver: Saver to restore variables.
logdir: Directory to search for checkpoints.
checkpoint: Specify what checkpoint name to use; defaults to most recent.
resume: Whether to expect recov... |
def upload_cart(cart, collection):
cart_cols = cart_db()
cart_json = read_json_document(cart.cart_file())
try:
cart_id = cart_cols[collection].save(cart_json)
except MongoErrors.AutoReconnect:
raise JuicerConfigError("Error saving cart to `cart_host`. Ensure that this node is the master.... | Connect to mongo and store your cart in the specified collection. |
def underlying_variable_ref(t):
while t.op.type in ["Identity", "ReadVariableOp", "Enter"]:
t = t.op.inputs[0]
op_type = t.op.type
if "Variable" in op_type or "VarHandle" in op_type:
return t
else:
return None | Find the underlying variable ref.
Traverses through Identity, ReadVariableOp, and Enter ops.
Stops when op type has Variable or VarHandle in name.
Args:
t: a Tensor
Returns:
a Tensor that is a variable ref, or None on error. |
def AddKeyByPath(self, key_path, registry_key):
if not key_path.startswith(definitions.KEY_PATH_SEPARATOR):
raise ValueError('Key path does not start with: {0:s}'.format(
definitions.KEY_PATH_SEPARATOR))
if not self._root_key:
self._root_key = FakeWinRegistryKey(self._key_path_prefix)
... | Adds a Windows Registry key for a specific key path.
Args:
key_path (str): Windows Registry key path to add the key.
registry_key (WinRegistryKey): Windows Registry key.
Raises:
KeyError: if the subkey already exists.
ValueError: if the Windows Registry key cannot be added. |
def stack_plot(self, *args, **kwargs):
df = self.as_pandas(with_metadata=True)
ax = plotting.stack_plot(df, *args, **kwargs)
return ax | Plot timeseries stacks of existing data
see pyam.plotting.stack_plot() for all available options |
def AUC_analysis(AUC):
try:
if AUC == "None":
return "None"
if AUC < 0.6:
return "Poor"
if AUC >= 0.6 and AUC < 0.7:
return "Fair"
if AUC >= 0.7 and AUC < 0.8:
return "Good"
if AUC >= 0.8 and AUC < 0.9:
return "Very ... | Analysis AUC with interpretation table.
:param AUC: area under the ROC curve
:type AUC : float
:return: interpretation result as str |
def normpath(path):
scheme, netloc, path_ = parse(path)
return unparse(scheme, netloc, os.path.normpath(path_)) | Normalize ``path``, collapsing redundant separators and up-level refs. |
def get_program_args(self):
ret = []
for arg in self.get_options().program_args:
ret.extend(safe_shlex_split(arg))
return ret | Get the program args to run this JVM with.
These are the arguments passed to main() and are program-specific. |
def _iter_bitmasks(eid):
bitmask = idaapi.get_first_bmask(eid)
yield bitmask
while bitmask != DEFMASK:
bitmask = idaapi.get_next_bmask(eid, bitmask)
yield bitmask | Iterate all bitmasks in a given enum.
Note that while `DEFMASK` indicates no-more-bitmasks, it is also a
valid bitmask value. The only way to tell if it exists is when iterating
the serials. |
def verify_module(self, filename, module, verify_signature):
with open(filename, 'rb') as f:
module_data = f.read()
self.verify_checksum(module_data, module['checksum'],
module['location'])
if self.gpg_verify:
signature_url = "{0}/{1}".format(... | Verify kernel module checksum and signature
:type filename: str
:param filename: downloaded kernel module path
:type module: dict
:param module: kernel module metadata
:type verify_signature: bool
:param verify_signature: enable/disable signature verification |
def get_highlights(self, user: Union[int, Profile]) -> Iterator[Highlight]:
userid = user if isinstance(user, int) else user.userid
data = self.context.graphql_query("7c16654f22c819fb63d1183034a5162f",
{"user_id": userid, "include_chaining": False, "include_reel... | Get all highlights from a user.
To use this, one needs to be logged in.
.. versionadded:: 4.1
:param user: ID or Profile of the user whose highlights should get fetched. |
def __get_indexer(in_fns, selected_type=None):
indexer = None
if selected_type is not None:
indexer = get_indexer_by_filetype(selected_type)
else:
if len(in_fns) == 0:
raise IndexError("reading from stdin, unable to guess input file " +
"type, use -t option to set manually.\n"... | Determine which indexer to use based on input files and type option. |
def forum_topic_list(self, title_matches=None, title=None,
category_id=None):
params = {
'search[title_matches]': title_matches,
'search[title]': title,
'search[category_id]': category_id
}
return self._get('forum_topics.json', par... | Function to get forum topics.
Parameters:
title_matches (str): Search body for the given terms.
title (str): Exact title match.
category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs & Features
respectively). |
def parse_time_step(time_step, target='s', units_ref=None):
log.info("Parsing time step %s", time_step)
value = re.findall(r'\d+', time_step)[0]
valuelen = len(value)
try:
value = float(value)
except:
HydraPluginError("Unable to extract number of time steps (%s) from time step %s" % ... | Read in the time step and convert it to seconds. |
def is_file_url(url):
from .misc import to_text
if not url:
return False
if not isinstance(url, six.string_types):
try:
url = getattr(url, "url")
except AttributeError:
raise ValueError("Cannot parse url from unknown type: {0!r}".format(url))
url = to_text... | Returns true if the given url is a file url |
def setup_logging(verbosity, formats=None):
if formats is None:
formats = {}
log_level = logging.INFO
log_format = formats.get("info", INFO_FORMAT)
if sys.stdout.isatty():
log_format = formats.get("color", COLOR_FORMAT)
if verbosity > 0:
log_level = logging.DEBUG
log_... | Configure a proper logger based on verbosity and optional log formats.
Args:
verbosity (int): 0, 1, 2
formats (dict): Optional, looks for `info`, `color`, and `debug` keys
which may override the associated default log formats. |
def run_step(context):
logger.debug("started")
format_expression = context.get('nowUtcIn', None)
if format_expression:
formatted_expression = context.get_formatted_string(format_expression)
context['nowUtc'] = datetime.now(
timezone.utc).strftime(formatted_expression)
else:
... | pypyr step saves current utc datetime to context.
Args:
context: pypyr.context.Context. Mandatory.
The following context key is optional:
- nowUtcIn. str. Datetime formatting expression. For full list
of possible expressions, check here:
... |
def encrypt_file(self,
path,
output_path=None,
overwrite=False,
enable_verbose=True):
path, output_path = files.process_dst_overwrite_args(
src=path, dst=output_path, overwrite=overwrite,
src_to_dst_func=... | Encrypt a file using rsa.
RSA for big file encryption is very slow. For big file, I recommend
to use symmetric encryption and use RSA to encrypt the password. |
def get_all_preordered_namespace_hashes( self ):
cur = self.db.cursor()
namespace_hashes = namedb_get_all_preordered_namespace_hashes( cur, self.lastblock )
return namespace_hashes | Get all oustanding namespace preorder hashes that have not expired.
Used for testing |
def set_asset_dir(self):
log = logging.getLogger(self.cls_logger + '.get_asset_dir')
try:
self.asset_dir = os.environ['ASSET_DIR']
except KeyError:
log.warn('Environment variable ASSET_DIR is not set!')
else:
log.info('Found environment variable ASSET_... | Returns the ASSET_DIR environment variable
This method gets the ASSET_DIR environment variable for the
current asset install. It returns either the string value if
set or None if it is not set.
:return: None |
def remove_column(conn, table, column_name, schema=None):
activity_table = get_activity_table(schema=schema)
remove = sa.cast(column_name, sa.Text)
query = (
activity_table
.update()
.values(
old_data=activity_table.c.old_data - remove,
changed_data=activity_t... | Removes given `activity` jsonb data column key. This function is useful
when you are doing schema changes that require removing a column.
Let's say you've been using PostgreSQL-Audit for a while for a table called
article. Now you want to remove one audited column called 'created_at' from
this table.
... |
def export(self, timestamp=None):
if self._timestamp is None:
raise Exception("No timestamp set. Has the archive been initialized?")
if self.skip_notebook_export:
super(NotebookArchive, self).export(timestamp=self._timestamp,
info={... | Get the current notebook data and export. |
def get_scheme_dirs():
scheme_glob = rel_to_cwd('schemes', '**', '*.yaml')
scheme_groups = glob(scheme_glob)
scheme_groups = [get_parent_dir(path) for path in scheme_groups]
return set(scheme_groups) | Return a set of all scheme directories. |
def walk(cls, top=".", ext=".abo"):
paths = []
for root, dirs, files in os.walk(top):
for f in files:
if f.endswith(ext):
paths.append(os.path.join(root, f))
parser = cls()
okfiles = parser.parse(paths)
return parser, paths, okfiles | Scan directory tree starting from top, look for files with extension `ext` and
parse timing data.
Return: (parser, paths, okfiles)
where `parser` is the new object, `paths` is the list of files found and `okfiles`
is the list of files that have been parsed successfully.
... |
def _as_log_entry(self, name, now):
d = {
u'http_response_code': self.response_code,
u'timestamp': time.mktime(now.timetuple())
}
severity = _SEVERITY.INFO
if self.response_code >= 400:
severity = _SEVERITY.ERROR
d[u'error_cause'] = self.er... | Makes a `LogEntry` from this instance for the given log_name.
Args:
rules (:class:`ReportingRules`): determines what labels, metrics and
logs to include in the report request.
now (:class:`datetime.DateTime`): the current time
Return:
a ``LogEntry`` generated ... |
def wrap_embedded_keyvalue(self, data):
if data is not None:
try:
data = u'{}'.format(data)
except UnicodeEncodeError:
pass
variables = []
for v in re.finditer(self._vars_keyvalue_embedded, data):
variables.append(v.... | Wrap keyvalue embedded variable in double quotes.
Args:
data (string): The data with embedded variables.
Returns:
(string): Results retrieved from DB |
def get_query_with_new_limit(self, new_limit):
if not self._limit:
return self.sql + ' LIMIT ' + str(new_limit)
limit_pos = None
tokens = self._parsed[0].tokens
for pos, item in enumerate(tokens):
if item.ttype in Keyword and item.value.lower() == 'limit':
... | returns the query with the specified limit |
def items(self):
if hasattr(self, '_items'):
return self.filter_items(self._items)
self._items = self.get_items()
return self.filter_items(self._items) | access for filtered items |
def replace_coord(self, i):
da = next(islice(self.data_iterator, i, i+1))
name, coord = self.get_alternative_coord(da, i)
other_coords = {key: da.coords[key]
for key in set(da.coords).difference(da.dims)}
ret = da.rename({da.dims[-1]: name}).assign_coords(
... | Replace the coordinate for the data array at the given position
Parameters
----------
i: int
The number of the data array in the raw data (if the raw data is
not an interactive list, use 0)
Returns
xarray.DataArray
The data array with the rep... |
def _error_result_to_exception(error_result):
reason = error_result.get("reason")
status_code = _ERROR_REASON_TO_EXCEPTION.get(
reason, http_client.INTERNAL_SERVER_ERROR
)
return exceptions.from_http_status(
status_code, error_result.get("message", ""), errors=[error_result]
) | Maps BigQuery error reasons to an exception.
The reasons and their matching HTTP status codes are documented on
the `troubleshooting errors`_ page.
.. _troubleshooting errors: https://cloud.google.com/bigquery\
/troubleshooting-errors
:type error_result: Mapping[str, str]
:param error_res... |
def install(self):
super(SystemD, self).install()
self.deploy_service_file(self.svc_file_path, self.svc_file_dest)
self.deploy_service_file(self.env_file_path, self.env_file_dest)
sh.systemctl.enable(self.name)
sh.systemctl('daemon-reload') | Install the service on the local machine
This is where we deploy the service files to their relevant
locations and perform any other required actions to configure
the service and make it ready to be `start`ed. |
def reset(self):
shutil.copy2(self.config_file + ".orig", self.config_file)
if filecmp.cmp(self.config_file + ".orig", self.config_file):
print("{0}The reset was done{1}".format(
self.meta.color["GREEN"], self.meta.color["ENDC"]))
else:
print("{0}Reset fai... | Reset slpkg.conf file with default values |
def xmlrpc_reschedule(self):
if not len(self.scheduled_tasks) == 0:
self.reschedule = list(self.scheduled_tasks.items())
self.scheduled_tasks = {}
return True | Reschedule all running tasks. |
def transport_jabsorbrpc(self):
self.context.install_bundle(
"pelix.remote.transport.jabsorb_rpc"
).start()
with use_waiting_list(self.context) as ipopo:
ipopo.add(
rs.FACTORY_TRANSPORT_JABSORBRPC_EXPORTER,
"pelix-jabsorbrpc-exporter",
... | Installs the JABSORB-RPC transport bundles and instantiates components |
def get(self):
frac, whole = modf(self.size * self.percent / 100.0)
ret = curses_bars[8] * int(whole)
if frac > 0:
ret += curses_bars[int(frac * 8)]
whole += 1
ret += self.__empty_char * int(self.size - whole)
if self.__with_text:
ret = '{}{:5.... | Return the bars. |
def keys(self, name_start, name_end, limit=10):
limit = get_positive_integer('limit', limit)
return self.execute_command('keys', name_start, name_end, limit) | Return a list of the top ``limit`` keys between ``name_start`` and
``name_end``
Similiar with **Redis.KEYS**
.. note:: The range is (``name_start``, ``name_end``]. ``name_start``
isn't in the range, but ``name_end`` is.
:param string name_start: The lower bound(not ... |
def items_to_extract(self, offset=0, length=None):
endoffset = length and offset + length
qs = self.origin_data()[offset:endoffset]
self.items_to_extract_length = qs.count()
return qs | Return an iterable of specific items to extract.
As a side-effect, set self.items_to_extract_length.
:param offset: where to start extracting
:param length: how many to extract
:return: An iterable of the specific |
def createCleanup(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: createCleanup(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx... | Finalize Managed Object Instance creation.
Implements the successful third step of the multi-step workflow similar to
the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third (successful) phase is to seal the new Managed Object
Instance. Once the system transi... |
def move_camera(action, action_space, minimap):
minimap.assign_to(spatial(action, action_space).camera_move.center_minimap) | Move the camera. |
def check_ttl_max_tries(tries, enqueued_at, max_tries, ttl):
if max_tries > 0 and tries >= max_tries:
raise FSQMaxTriesError(errno.EINTR, u'Max tries exceded:'\
u' {0} ({1})'.format(max_tries, tries))
if ttl > 0 and datetime.datetime.now() < enqueued_at + datetime.timedelt... | Check that the ttl for an item has not expired, and that the item has
not exceeded it's maximum allotted tries |
def _build_toctree_node(parent=None, entries=None, includefiles=None,
caption=None):
subnode = sphinx.addnodes.toctree()
subnode['parent'] = parent
subnode['entries'] = entries
subnode['includefiles'] = includefiles
subnode['caption'] = caption
subnode['maxdepth'] = 1
... | Factory for a toctree node. |
def create(graph, kmin=0, kmax=10, verbose=True):
from turicreate._cython.cy_server import QuietProgress
if not isinstance(graph, _SGraph):
raise TypeError('graph input must be a SGraph object.')
opts = {'graph': graph.__proxy__, 'kmin': kmin, 'kmax': kmax}
with QuietProgress(verbose):
p... | Compute the K-core decomposition of the graph. Return a model object with
total number of cores as well as the core id for each vertex in the graph.
Parameters
----------
graph : SGraph
The graph on which to compute the k-core decomposition.
kmin : int, optional
Minimum core id. Ve... |
def latex_name(self):
star = ('*' if self._star_latex_name else '')
if self._latex_name is not None:
return self._latex_name + star
return self.__class__.__name__.lower() + star | Return the name of the class used in LaTeX.
It can be `None` when the class doesn't have a name. |
def subscribe(self, *, create_task=True, **params):
if create_task and not self.task:
self.task = asyncio.ensure_future(self.run(**params))
return self.channel.subscribe() | Subscribes to the Docker events channel. Use the keyword argument
create_task=False to prevent automatically spawning the background
tasks that listen to the events.
This function returns a ChannelSubscriber object. |
def is_working_day(self, day,
extra_working_days=None, extra_holidays=None):
day = cleaned_date(day)
if extra_working_days:
extra_working_days = tuple(map(cleaned_date, extra_working_days))
if extra_holidays:
extra_holidays = tuple(map(cleaned_date,... | Return True if it's a working day.
In addition to the regular holidays, you can add exceptions.
By providing ``extra_working_days``, you'll state that these dates
**are** working days.
By providing ``extra_holidays``, you'll state that these dates **are**
holidays, even if not ... |
def import_tf_tensor(self, x, tf_x):
return self.LaidOutTensor(self.make_slices(tf_x, x.shape)) | Import a tf.Tensor, producing a LaidOutTensor.
Args:
x: a Tensor
tf_x: a tf.Tensor
Returns:
a LaidOutTensor |
def to_string(self, other):
arg = "%s/%s,%s" % (
self.ttl, self.get_remaining_ttl(current_time_millis()), other)
return DNSEntry.to_string(self, "record", arg) | String representation with addtional information |
def _terms(self):
res = []
for sign, terms in self.terms.items():
for ID, lon in terms.items():
res.append(self.T(ID, sign))
return res | Returns a list with the objects as terms. |
def merge_parts(self, version_id=None, **kwargs):
self.file.update_checksum(**kwargs)
with db.session.begin_nested():
obj = ObjectVersion.create(
self.bucket,
self.key,
_file_id=self.file_id,
version_id=version_id
)
... | Merge parts into object version. |
def parse_type_signature(sig):
match = TYPE_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Type signature invalid, got ' + sig)
groups = match.groups()
typ = groups[0]
generic_types = groups[1]
if not generic_types:
generic_types = []
else:
generic_types ... | Parse a type signature |
def vbd_list(name=None, call=None):
if call == 'function':
raise SaltCloudSystemExit(
'This function must be called with -a, --action argument.'
)
if name is None:
return 'A name kwarg is rquired'
ret = {}
data = {}
session = _get_session()
vms = session.xenap... | Get a list of VBDs on a VM
**requires**: the name of the vm with the vbd definition
.. code-block:: bash
salt-cloud -a vbd_list xenvm01 |
def apply_formatting_dict(obj: Any, formatting: Dict[str, Any]) -> Any:
new_obj = obj
if isinstance(obj, str):
if "$" not in obj:
new_obj = string.Formatter().vformat(obj, (), formatting_dict(**formatting))
elif isinstance(obj, dict):
new_obj = {}
for k, v in obj.items():... | Recursively apply a formatting dict to all strings in a configuration.
Note that it skips applying the formatting if the string appears to contain latex (specifically,
if it contains an "$"), since the formatting fails on nested brackets.
Args:
obj: Some configuration object to recursively applyin... |
def add_head(self, head):
if not isinstance(head, DependencyNode):
raise TypeError('"head" must be a DependencyNode')
self._heads.append(head) | Add head Node |
def add_method(info, target_cls, virtual=False, dont_replace=False):
name = escape_identifier(info.name)
if virtual:
name = "do_" + name
attr = VirtualMethodAttribute(info, target_cls, name)
else:
attr = MethodAttribute(info, target_cls, name)
if dont_replace and hasattr(target_c... | Add a method to the target class |
def set_(filename, section, parameter, value):
filename = _quote(filename)
section = _quote(section)
parameter = _quote(parameter)
value = _quote(six.text_type(value))
result = __salt__['cmd.run_all'](
'openstack-config --set {0} {1} {2} {3}'.format(
filename, section, pa... | Set a value in an OpenStack configuration file.
filename
The full path to the configuration file
section
The section in which the parameter will be set
parameter
The parameter to change
value
The value to set
CLI Example:
.. code-block:: bash
salt-c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.