INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Set up FN to only run once within an interpreter instance | def onlyOnce(fn):
'Set up FN to only run once within an interpreter instance'
def wrap(*args, **kwargs):
if hasattr(fn, 'called'):
return
fn.called = 1
return fn(*args, **kwargs)
util.mergeFunctionMetadata(fn, wrap)
return wrap |
return the full spec of the connector as a list of dicts | def allEndpoints(self):
"""return the full spec of the connector as a list of dicts
"""
paths = []
for k, v in sorted(self.matcher.iterPatterns()):
paths.append(dict(path="/".join(k),
plural=str(v.rtype.plural),
type... |
Validate master ( - m -- master ) command line option. | def validateMasterOption(master):
"""
Validate master (-m, --master) command line option.
Checks that option is a string of the 'hostname:port' form, otherwise
raises an UsageError exception.
@type master: string
@param master: master option
@raise usage.UsageError: on invalid master opt... |
concat a path for this name | def addEnvPath(env, name, value):
""" concat a path for this name """
try:
oldval = env[name]
if not oldval.endswith(';'):
oldval = oldval + ';'
except KeyError:
oldval = ""
if not value.endswith(';'):
value = value + ';'
env[name] = oldval + value |
Ping the worker to make sure it is still there. Returns a Deferred that fires with True if it is. | def ping(self, status=None):
"""Ping the worker to make sure it is still there. Returns a Deferred
that fires with True if it is.
@param status: if you point this at a BuilderStatus, a 'pinging'
event will be pushed.
"""
newping = not self.ping_watchers
... |
Call me at checkConfig time to properly report config error if neither txrequests or treq is installed | def checkAvailable(from_module):
"""Call me at checkConfig time to properly report config error
if neither txrequests or treq is installed
"""
if txrequests is None and treq is None:
config.error("neither txrequests nor treq is installed, but {} is requiring it\n\n{}".form... |
Generator for a list/ tuple that potentially contains nested/ lists/ tuples of arbitrary nesting that returns every individual non - list/ tuple element. In other words [ ( 5 6 [ 8 3 ] ) 2 [ 2 1 ( 3 4 ) ]] will yield 5 6 8 3 2 2 1 3 4 | def flattened_iterator(l, types=(list, tuple)):
"""
Generator for a list/tuple that potentially contains nested/lists/tuples of arbitrary nesting
that returns every individual non-list/tuple element. In other words, [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]]
will yield 5, 6, 8, 3, 2, 2, 1, 3, 4
This is s... |
Given a list/ tuple that potentially contains nested lists/ tuples of arbitrary nesting flatten into a single dimension. In other words turn [ ( 5 6 [ 8 3 ] ) 2 [ 2 1 ( 3 4 ) ]] into [ 5 6 8 3 2 2 1 3 4 ] | def flatten(l, types=(list, )):
"""
Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting,
flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]]
into [5, 6, 8, 3, 2, 2, 1, 3, 4]
This is safe to call on something not a list/tuple -... |
Return a string of human readable time delta. | def human_readable_delta(start, end):
"""
Return a string of human readable time delta.
"""
start_date = datetime.datetime.fromtimestamp(start)
end_date = datetime.datetime.fromtimestamp(end)
delta = end_date - start_date
result = []
if delta.days > 0:
result.append('%d days' % ... |
decorate a function by running it with maybeDeferred in a reactor | def in_reactor(f):
"""decorate a function by running it with maybeDeferred in a reactor"""
def wrap(*args, **kwargs):
from twisted.internet import reactor, defer
result = []
def _async():
d = defer.maybeDeferred(f, *args, **kwargs)
@d.addErrback
def ... |
merges dictionary b into a Like dict. update but recursive | def dictionary_merge(a, b):
"""merges dictionary b into a
Like dict.update, but recursive
"""
for key, value in b.items():
if key in a and isinstance(a[key], dict) and isinstance(value, dict):
dictionary_merge(a[key], b[key])
continue
a[key] = b[key]
return... |
Create nice summary logs. | def createSummary(self, log):
"""
Create nice summary logs.
@param log: log to create summary off of.
"""
warnings = self.obs.warnings
errors = []
if warnings:
self.addCompleteLog('%d Warnings' % len(warnings), "\n".join(warnings))
if errors:
... |
Returns the submitted_at of the oldest unclaimed build request for this builder or None if there are no build requests. | def getOldestRequestTime(self):
"""Returns the submitted_at of the oldest unclaimed build request for
this builder, or None if there are no build requests.
@returns: datetime instance or None, via Deferred
"""
bldrid = yield self.getBuilderId()
unclaimed = yield self.mas... |
Returns the complete_at of the latest completed build request for this builder or None if there are no such build requests. | def getNewestCompleteTime(self):
"""Returns the complete_at of the latest completed build request for
this builder, or None if there are no such build requests.
@returns: datetime instance or None, via Deferred
"""
bldrid = yield self.getBuilderId()
completed = yield sel... |
This is invoked by the Worker when the self. workername bot registers their builder. | def attached(self, worker, commands):
"""This is invoked by the Worker when the self.workername bot
registers their builder.
@type worker: L{buildbot.worker.Worker}
@param worker: the Worker that represents the worker as a whole
@type commands: dict: string -> string, or None
... |
This is called when the connection to the bot is lost. | def detached(self, worker):
"""This is called when the connection to the bot is lost."""
for wfb in self.attaching_workers + self.workers:
if wfb.worker == worker:
break
else:
log.msg("WEIRD: Builder.detached(%s) (%s)"
" not in attachin... |
This is called when the Build has finished ( either success or failure ). Any exceptions during the build are reported with results = FAILURE not with an errback. | def buildFinished(self, build, wfb):
"""This is called when the Build has finished (either success or
failure). Any exceptions during the build are reported with
results=FAILURE, not with an errback."""
# by the time we get here, the Build has already released the worker,
# whic... |
Helper function to determine which collapseRequests function to use from L { _collapseRequests } or None for no merging | def getCollapseRequestsFn(self):
"""Helper function to determine which collapseRequests function to use
from L{_collapseRequests}, or None for no merging"""
# first, seek through builder, global, and the default
collapseRequests_fn = self.config.collapseRequests
if collapseReques... |
private implementation of reactor. spawnProcess to allow use of L { ProcGroupProcess } | def _spawnProcess(self, processProtocol, executable, args=(), env=None,
path=None, uid=None, gid=None, usePTY=False, childFDs=None):
"""private implementation of reactor.spawnProcess, to allow use of
L{ProcGroupProcess}"""
if env is None:
env = {}
# use... |
A cheat that routes around the impedance mismatch between twisted and cmd. exe with respect to escaping quotes | def _spawnAsBatch(self, processProtocol, executable, args, env,
path, usePTY):
"""A cheat that routes around the impedance mismatch between
twisted and cmd.exe with respect to escaping quotes"""
# NamedTemporaryFile differs in PY2 and PY3.
# In PY2, it needs encode... |
limit the chunks that we send over PB to 128k since it has a hardwired string - size limit of 640k. | def _chunkForSend(self, data):
"""
limit the chunks that we send over PB to 128k, since it has a hardwired
string-size limit of 640k.
"""
LIMIT = self.CHUNK_LIMIT
for i in range(0, len(data), LIMIT):
yield data[i:i + LIMIT] |
Take msg which is a dictionary of lists of output chunks and concatenate all the chunks into a single string | def _collapseMsg(self, msg):
"""
Take msg, which is a dictionary of lists of output chunks, and
concatenate all the chunks into a single string
"""
retval = {}
for logname in msg:
data = u""
for m in msg[logname]:
m = bytes2unicode(... |
Collapse and send msg to the master | def _sendMessage(self, msg):
"""
Collapse and send msg to the master
"""
if not msg:
return
msg = self._collapseMsg(msg)
self.sendStatus(msg) |
Send all the content in our buffers. | def _sendBuffers(self):
"""
Send all the content in our buffers.
"""
msg = {}
msg_size = 0
lastlog = None
logdata = []
while self.buffered:
# Grab the next bits from the buffer
logname, data = self.buffered.popleft()
# ... |
Add data to the buffer for logname Start a timer to send the buffers if BUFFER_TIMEOUT elapses. If adding data causes the buffer size to grow beyond BUFFER_SIZE then the buffers will be sent. | def _addToBuffers(self, logname, data):
"""
Add data to the buffer for logname
Start a timer to send the buffers if BUFFER_TIMEOUT elapses.
If adding data causes the buffer size to grow beyond BUFFER_SIZE, then
the buffers will be sent.
"""
n = len(data)
... |
This gets invoked by L { buildbot. process. step. RemoteCommand. start } as part of various master - side BuildSteps to start various commands that actually do the build. I return nothing. Eventually I will call. commandComplete () to notify the master - side RemoteCommand that I m done. | def remote_startCommand(self, stepref, stepId, command, args):
"""
This gets invoked by L{buildbot.process.step.RemoteCommand.start}, as
part of various master-side BuildSteps, to start various commands
that actually do the build. I return nothing. Eventually I will call
.command... |
Halt the current step. | def remote_interruptCommand(self, stepId, why):
"""Halt the current step."""
log.msg("asked to interrupt current command: {0}".format(why))
self.activity()
if not self.command:
# TODO: just log it, a race could result in their interrupting a
# command that wasn't ... |
Make any currently - running command die with no further status output. This is used when the worker is shutting down or the connection to the master has been lost. Interrupt the command silence it and then forget about it. | def stopCommand(self):
"""Make any currently-running command die, with no further status
output. This is used when the worker is shutting down or the
connection to the master has been lost. Interrupt the command,
silence it, and then forget about it."""
if not self.command:
... |
This sends the status update to the master - side L { buildbot. process. step. RemoteCommand } object giving it a sequence number in the process. It adds the update to a queue and asks the master to acknowledge the update so it can be removed from that queue. | def sendUpdate(self, data):
"""This sends the status update to the master-side
L{buildbot.process.step.RemoteCommand} object, giving it a sequence
number in the process. It adds the update to a queue, and asks the
master to acknowledge the update so it can be removed from that
qu... |
This command retrieves data from the files in WORKERDIR/ info/ * and sends the contents to the buildmaster. These are used to describe the worker and its configuration and should be created and maintained by the worker administrator. They will be retrieved each time the master - worker connection is established. | def remote_getWorkerInfo(self):
"""This command retrieves data from the files in WORKERDIR/info/* and
sends the contents to the buildmaster. These are used to describe
the worker and its configuration, and should be created and
maintained by the worker administrator. They will be retriev... |
Record my hostname in twistd. hostname for user convenience | def recordHostname(self, basedir):
"Record my hostname in twistd.hostname, for user convenience"
log.msg("recording hostname in twistd.hostname")
filename = os.path.join(basedir, "twistd.hostname")
try:
hostname = os.uname()[1] # only on unix
except AttributeError:
... |
walk upwards from the current directory until we find this topfile | def getTopdir(topfile, start=None):
"""walk upwards from the current directory until we find this topfile"""
if not start:
start = os.getcwd()
here = start
toomany = 20
while toomany > 0:
if os.path.exists(os.path.join(here, topfile)):
return here
next = os.path.d... |
This accepts the arguments of a command without the actual command itself. | def dovc(self, cmd):
"""This accepts the arguments of a command, without the actual
command itself."""
env = os.environ.copy()
env['LC_ALL'] = "C"
d = utils.getProcessOutputAndValue(self.exe, cmd, env=env,
path=self.treetop)
d.ad... |
Return a Deferred that fires with a SourceStamp instance. | def get(self):
"""Return a Deferred that fires with a SourceStamp instance."""
d = self.getBaseRevision()
d.addCallback(self.getPatch)
d.addCallback(self.done)
return d |
Version of check_output which does not throw error | def check_output(cmd):
"""Version of check_output which does not throw error"""
popen = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
out = popen.communicate()[0].strip()
if not isinstance(out, str):
out = out.decode(sys.stdout.encoding)
return out |
Extract the tag if a source is from git archive. | def getVersionFromArchiveId(git_archive_id='$Format:%ct %d$'):
""" Extract the tag if a source is from git archive.
When source is exported via `git archive`, the git_archive_id init value is modified
and placeholders are expanded to the "archived" revision:
%ct: committer date, UNIX t... |
Return BUILDBOT_VERSION environment variable content of VERSION file git tag or latest | def getVersion(init_file):
"""
Return BUILDBOT_VERSION environment variable, content of VERSION file, git
tag or 'latest'
"""
try:
return os.environ['BUILDBOT_VERSION']
except KeyError:
pass
try:
cwd = os.path.dirname(os.path.abspath(init_file))
fn = os.path... |
Run command. | def run(self):
"""Run command."""
if self.already_run:
return
package = self.distribution.packages[0]
if os.path.exists("gulpfile.js") or os.path.exists("webpack.config.js"):
yarn_version = check_output("yarn --version")
npm_version = check_output("npm... |
: param repo: the repo full name { owner }/ { project }. e. g. buildbot/ buildbot | def _get_commit_msg(self, repo, sha):
'''
:param repo: the repo full name, ``{owner}/{project}``.
e.g. ``buildbot/buildbot``
'''
headers = {
'User-Agent': 'Buildbot'
}
if self._token:
headers['Authorization'] = 'token ' + self._token
... |
Consumes the JSON as a python object and actually starts the build. | def _process_change(self, payload, user, repo, repo_url, project, event,
properties):
"""
Consumes the JSON as a python object and actually starts the build.
:arguments:
payload
Python Object that represents the JSON sent by GitHub Service
... |
The message contains the skipping keyword no not. | def _has_skip(self, msg):
'''
The message contains the skipping keyword no not.
:return type: Bool
'''
for skip in self.skips:
if re.search(skip, msg):
return True
return False |
Create nice summary logs. | def createSummary(self, log):
"""
Create nice summary logs.
@param log: log to create summary off of.
"""
warnings = self.obs.warnings
errors = self.obs.errors
if warnings:
self.addCompleteLog('%d Warnings' % len(warnings), "\n".join(warnings))
... |
Write a block of data to the remote writer | def _writeBlock(self):
"""Write a block of data to the remote writer"""
if self.interrupted or self.fp is None:
if self.debug:
log.msg('WorkerFileUploadCommand._writeBlock(): end')
return True
length = self.blocksize
if self.remaining is not None... |
Read a block of data from the remote reader. | def _readBlock(self):
"""Read a block of data from the remote reader."""
if self.interrupted or self.fp is None:
if self.debug:
log.msg('WorkerFileDownloadCommand._readBlock(): end')
return True
length = self.blocksize
if self.bytes_remaining is ... |
Generate a buildbot mail message and return a dictionary containing the message body type and subject. | def formatMessageForBuildResults(self, mode, buildername, buildset, build, master, previous_results, blamelist):
"""Generate a buildbot mail message and return a dictionary
containing the message body, type and subject."""
ss_list = buildset['sourcestamps']
results = build['results']
... |
A full name intended to uniquely identify a parameter | def fullName(self):
"""A full name, intended to uniquely identify a parameter"""
# join with '_' if both are set (cannot put '.', because it is used as
# **kwargs)
if self.parentName and self.name:
return self.parentName + '_' + self.name
# otherwise just use the one ... |
Simple customization point for child classes that do not need the other parameters supplied to updateFromKwargs. Return the value for the property named self. name. | def getFromKwargs(self, kwargs):
"""Simple customization point for child classes that do not need the other
parameters supplied to updateFromKwargs. Return the value for the property
named 'self.name'.
The default implementation converts from a list of items, validates using
... |
Primary entry point to turn kwargs into properties | def updateFromKwargs(self, properties, kwargs, collector, **unused):
"""Primary entry point to turn 'kwargs' into 'properties'"""
properties[self.name] = self.getFromKwargs(kwargs) |
Secondary customization point called from getFromKwargs to turn a validated value into a single property value | def parse_from_args(self, l):
"""Secondary customization point, called from getFromKwargs to turn
a validated value into a single property value"""
if self.multiple:
return [self.parse_from_arg(arg) for arg in l]
return self.parse_from_arg(l[0]) |
Collapse the child values into a dictionary. This is intended to be called by child classes to fix up the fullName - > name conversions. | def collectChildProperties(self, kwargs, properties, collector, **kw):
"""Collapse the child values into a dictionary. This is intended to be
called by child classes to fix up the fullName->name conversions."""
childProperties = {}
for field in self.fields: # pylint: disable=not-an-... |
By default the child values will be collapsed into a dictionary. If the parent is anonymous this dictionary is the top - level properties. | def updateFromKwargs(self, kwargs, properties, collector, **kw):
"""By default, the child values will be collapsed into a dictionary. If
the parent is anonymous, this dictionary is the top-level properties."""
yield self.collectChildProperties(kwargs=kwargs, properties=properties,
... |
We check the parameters and launch the build if everything is correct | def force(self, owner, builderNames=None, builderid=None, **kwargs):
"""
We check the parameters, and launch the build, if everything is correct
"""
builderNames = yield self.computeBuilderNames(builderNames, builderid)
if not builderNames:
raise KeyError("builderName... |
get secrets from the provider defined in the secret using args and kwargs | def get(self, secret, *args, **kwargs):
"""
get secrets from the provider defined in the secret using args and
kwargs
@secrets: secrets keys
@type: string
@return type: SecretDetails
"""
for provider in self.services:
value = yield provider.get... |
save function | def save():
"""
save function
"""
results = {}
cpu_number = 0
while True:
try:
_file = open(
CPU_PREFIX + 'cpu{}/cpufreq/scaling_governor'.format(cpu_number))
except:
break
governor = _file.read().strip()
results.setdefaul... |
change function | def change(governor, freq=None):
"""
change function
"""
cpu_number = 0
while True:
try:
subprocess.check_output([
"sudo", "bash", "-c",
"echo {governor} > {CPU_PREFIX}cpu{cpu_number}/cpufreq/scaling_governor"
.format(governor=gove... |
function for checking available frequency | def available_freq():
"""
function for checking available frequency
"""
_file = open(CPU_PREFIX + 'cpu0/cpufreq/scaling_available_frequencies')
freq = [int(_file) for _file in _file.read().strip().split()]
_file.close()
return freq |
dump function | def dump():
"""
dump function
"""
try:
sensors = subprocess.check_output('sensors').decode('utf-8')
except (FileNotFoundError, subprocess.CalledProcessError):
print("Couldn't read CPU temp")
else:
cores = []
for line in sensors.splitlines():
if lin... |
Pads data to the multiplies of 8 bytes. | def padto8(data):
"""Pads data to the multiplies of 8 bytes.
This makes x86_64 faster and prevents
undefined behavior on other platforms"""
length = len(data)
return data + b'\xdb' * (roundto8(length) - length) |
Parse a Cookie HTTP header into a dict of name/ value pairs. This function attempts to mimic browser cookie parsing behavior ; it specifically does not follow any of the cookie - related RFCs ( because browsers don t either ). The algorithm used is identical to that used by Django version 1. 9. 10. | def parse_cookie(cookie):
"""Parse a ``Cookie`` HTTP header into a dict of name/value pairs.
This function attempts to mimic browser cookie parsing behavior;
it specifically does not follow any of the cookie-related RFCs
(because browsers don't either).
The algorithm used is identical to that used b... |
A heuristic to find out if a function is simple enough. | def is_simple(fun):
"""A heuristic to find out if a function is simple enough."""
seen_load_fast_0 = False
seen_load_response = False
seen_call_fun = False
for instruction in dis.get_instructions(fun):
if instruction.opname == 'LOAD_FAST' and instruction.arg == 0:
seen_load_fast... |
Return a list of variable names being rejected for high correlation with one of remaining variables. | def get_rejected_variables(self, threshold=0.9):
"""Return a list of variable names being rejected for high
correlation with one of remaining variables.
Parameters:
----------
threshold : float
Correlation value which is above the threshold are rejected
... |
Write the report to a file. By default a name is generated. | def to_file(self, outputfile=DEFAULT_OUTPUTFILE):
"""Write the report to a file.
By default a name is generated.
Parameters:
----------
outputfile : str
The name or the path of the file to generale including the extension (.html).
"""
if... |
Return a jinja template ready for rendering. If needed global variables are initialized. | def template(template_name):
"""Return a jinja template ready for rendering. If needed, global variables are initialized.
Parameters
----------
template_name: str, the name of the template as defined in the templates mapping
Returns
-------
The Jinja template ready for rendering
"""
... |
Generate a HTML report from summary statistics and a given sample. | def to_html(sample, stats_object):
"""Generate a HTML report from summary statistics and a given sample.
Parameters
----------
sample : DataFrame
the sample you want to print
stats_object : dict
Summary statistics. Should be generated with an appropriate describe() function
Ret... |
Compute summary statistics of a numerical ( TYPE_NUM ) variable ( a Series ). | def describe_numeric_1d(series, **kwargs):
"""Compute summary statistics of a numerical (`TYPE_NUM`) variable (a Series).
Also create histograms (mini an full) of its distribution.
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
T... |
Compute summary statistics of a date ( TYPE_DATE ) variable ( a Series ). | def describe_date_1d(series):
"""Compute summary statistics of a date (`TYPE_DATE`) variable (a Series).
Also create histograms (mini an full) of its distribution.
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of... |
Compute summary statistics of a categorical ( TYPE_CAT ) variable ( a Series ). | def describe_categorical_1d(series):
"""Compute summary statistics of a categorical (`TYPE_CAT`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats ke... |
Compute summary statistics of a boolean ( TYPE_BOOL ) variable ( a Series ). | def describe_boolean_1d(series):
"""Compute summary statistics of a boolean (`TYPE_BOOL`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys.
... |
Compute summary statistics of a constant ( S_TYPE_CONST ) variable ( a Series ). | def describe_constant_1d(series):
"""Compute summary statistics of a constant (`S_TYPE_CONST`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys... |
Compute summary statistics of a unique ( S_TYPE_UNIQUE ) variable ( a Series ). | def describe_unique_1d(series):
"""Compute summary statistics of a unique (`S_TYPE_UNIQUE`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys.
... |
Compute summary statistics of a supported variable ( a Series ). | def describe_supported(series, **kwargs):
"""Compute summary statistics of a supported variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys.
""... |
Compute summary statistics of a unsupported ( S_TYPE_UNSUPPORTED ) variable ( a Series ). | def describe_unsupported(series, **kwargs):
"""Compute summary statistics of a unsupported (`S_TYPE_UNSUPPORTED`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with ind... |
Compute summary statistics of a variable ( a Series ). | def describe_1d(data, **kwargs):
"""Compute summary statistics of a variable (a Series).
The description is different according to the type of the variable.
However a set of common stats is also computed.
Parameters
----------
series : Series
The variable to describe.
Returns
... |
Generates a dict containing summary statistics for a given dataset stored as a pandas DataFrame. | def describe(df, bins=10, check_correlation=True, correlation_threshold=0.9, correlation_overrides=None, check_recoded=False, pool_size=multiprocessing.cpu_count(), **kwargs):
"""Generates a dict containing summary statistics for a given dataset stored as a pandas `DataFrame`.
Used has is it will output its co... |
Plot an histogram from the data and return the AxesSubplot object. | def _plot_histogram(series, bins=10, figsize=(6, 4), facecolor='#337ab7'):
"""Plot an histogram from the data and return the AxesSubplot object.
Parameters
----------
series : Series
The data to plot
figsize : tuple
The size of the figure (width, height) in inches, default (6,4)
... |
Plot an histogram of the data. | def histogram(series, **kwargs):
"""Plot an histogram of the data.
Parameters
----------
series: Series
The data to plot.
Returns
-------
str
The resulting image encoded as a string.
"""
imgdata = BytesIO()
plot = _plot_histogram(series, **kwargs)
plot.figur... |
Plot a small ( mini ) histogram of the data. | def mini_histogram(series, **kwargs):
"""Plot a small (mini) histogram of the data.
Parameters
----------
series: Series
The data to plot.
Returns
-------
str
The resulting image encoded as a string.
"""
imgdata = BytesIO()
plot = _plot_histogram(series, figsize... |
Plot image of a matrix correlation. Parameters ---------- corrdf: DataFrame The matrix correlation to plot. title: str The matrix title Returns ------- str The resulting image encoded as a string. | def correlation_matrix(corrdf, title, **kwargs):
"""Plot image of a matrix correlation.
Parameters
----------
corrdf: DataFrame
The matrix correlation to plot.
title: str
The matrix title
Returns
-------
str, The resulting image encoded as a string.
"""
imgdata = ... |
Calculate value counts and distinct count of a variable ( technically a Series ). | def get_groupby_statistic(data):
"""Calculate value counts and distinct count of a variable (technically a Series).
The result is cached by column name in a global variable to avoid recomputing.
Parameters
----------
data : Series
The data type of the Series.
Returns
-------
l... |
Infer the type of a variable ( technically a Series ). | def get_vartype(data):
"""Infer the type of a variable (technically a Series).
The types supported are split in standard types and special types.
Standard types:
* Categorical (`TYPE_CAT`): the default type if no other one can be determined
* Numerical (`TYPE_NUM`): if it contains numbers
... |
Factory func for filters. | def factory(self, data, manager=None):
"""Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
"""
# Make the syntax a little nicer for common cases.
if isinstance(data, dict) and len(data) == 1 and 'type' not in data... |
Determine the immediate parent boolean operator for a filter | def get_block_operator(self):
"""Determine the immediate parent boolean operator for a filter"""
# Top level operator is `and`
block_stack = ['and']
for f in self.manager.iter_filters(block_end=True):
if f is None:
block_stack.pop()
continue
... |
Specific validation for resource_count type | def _validate_resource_count(self):
""" Specific validation for `resource_count` type
The `resource_count` type works a little differently because it operates
on the entire set of resources. It:
- does not require `key`
- `value` must be a number
- supports a subs... |
Given an inventory csv file return an iterator over keys | def load_manifest_file(client, bucket, schema, versioned, ifilters, key_info):
"""Given an inventory csv file, return an iterator over keys
"""
# To avoid thundering herd downloads, we do an immediate yield for
# interspersed i/o
yield None
# Inline these values to avoid the local var lookup, t... |
Given an inventory location for a bucket return an iterator over keys | def load_bucket_inventory(
client, inventory_bucket, inventory_prefix, versioned, ifilters):
"""Given an inventory location for a bucket, return an iterator over keys
on the most recent delivered manifest.
"""
now = datetime.datetime.now()
key_prefix = "%s/%s" % (inventory_prefix, now.strft... |
Generator to generate a set of keys from from a set of generators each generator is selected at random and consumed to exhaustion. | def random_chain(generators):
"""Generator to generate a set of keys from
from a set of generators, each generator is selected
at random and consumed to exhaustion.
"""
while generators:
g = random.choice(generators)
try:
v = g.next()
if v is None:
... |
Check a bucket for a named inventory and return the destination. | def get_bucket_inventory(client, bucket, inventory_id):
"""Check a bucket for a named inventory, and return the destination."""
inventories = client.list_bucket_inventory_configurations(
Bucket=bucket).get('InventoryConfigurationList', [])
inventories = {i['Id']: i for i in inventories}
found = ... |
You can customize the automated documentation by altering the code directly in this script or the associated jinja2 template | def create_html_file(config):
""" You can customize the automated documentation by altering
the code directly in this script or the associated jinja2 template
"""
logging.debug("Starting create_html_file")
logging.debug(
"\tjinja2_template_file = {}"
.format(config['jinja2_templa... |
Update this function to help build the link to your file | def get_file_url(path, config):
""" Update this function to help build the link to your file
"""
file_url_regex = re.compile(config['file_url_regex'])
new_path = re.sub(file_url_regex, config['file_url_base'], path)
return new_path |
Gather policy information from files | def gather_file_data(config):
""" Gather policy information from files
"""
file_regex = re.compile(config['file_regex'])
category_regex = re.compile(config['category_regex'])
policies = {}
for root, dirs, files in os.walk(config['c7n_policy_directory']):
for file in files:
i... |
Upload html file to S3 | def upload_to_s3(file_path, config):
""" Upload html file to S3
"""
logging.info("Uploading file to S3 bucket: %s", config['s3_bucket_name'])
s3 = boto3.resource('s3')
s3_filename = config['s3_bucket_path'] + config['rendered_filename']
s3.Bucket(config['s3_bucket_name']).upload_file(
fi... |
Return all github repositories in an organization. | def github_repos(organization, github_url, github_token):
"""Return all github repositories in an organization."""
# Get github repos
headers = {"Authorization": "token {}".format(github_token)}
next_cursor = None
while next_cursor is not False:
params = {'query': query, 'variables': {
... |
Stream changes for repos in a GitHub organization. | def org_stream(ctx, organization, github_url, github_token, clone_dir,
verbose, filter, exclude, stream_uri, assume):
"""Stream changes for repos in a GitHub organization.
"""
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and log... |
Checkout repositories from a GitHub organization. | def org_checkout(organization, github_url, github_token, clone_dir,
verbose, filter, exclude):
"""Checkout repositories from a GitHub organization."""
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and logging.DEBUG or logging.INFO)... |
Policy diff between two arbitrary revisions. | def diff(repo_uri, source, target, output, verbose):
"""Policy diff between two arbitrary revisions.
Revision specifiers for source and target can use fancy git refspec syntax
for symbolics, dates, etc.
See: https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection
Default revision selection is... |
Stream git history policy changes to destination. | def stream(repo_uri, stream_uri, verbose, assume, sort, before=None, after=None):
"""Stream git history policy changes to destination.
Default stream destination is a summary of the policy changes to stdout, one
per line. Also supported for stdout streaming is `jsonline`.
AWS Kinesis and SQS destinat... |
return the named subset of policies | def select(self, names):
"""return the named subset of policies"""
return PolicyCollection(
[p for p in self.policies if p.name in names], self.options) |
Show policies changes between arbitrary commits. | def delta_commits(self, baseline, target):
"""Show policies changes between arbitrary commits.
The common use form is comparing the heads of two branches.
"""
baseline_files = self._get_policy_fents(baseline.tree)
target_files = self._get_policy_fents(target.tree)
basel... |
Return an iterator of policy changes along a commit lineage in a repo. | def delta_stream(self, target='HEAD', limit=None,
sort=pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE,
after=None, before=None):
"""Return an iterator of policy changes along a commit lineage in a repo.
"""
if target == 'HEAD':
target = self.... |
Bookkeeping on internal data structures while iterating a stream. | def _process_stream_delta(self, delta_stream):
"""Bookkeeping on internal data structures while iterating a stream."""
for pchange in delta_stream:
if pchange.kind == ChangeType.ADD:
self.policy_files.setdefault(
pchange.file_path, PolicyCollection()).add(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.