_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q260200 | events.drag | validation | def drag(self, node):
""" Drags given node to mouse location.
"""
dx = self.mouse.x - self.graph.x
dy = self.mouse.y - self.graph.y
# A dashed line indicates the drag vector.
s = self.graph.styles.default
self._ctx.nofill()
self._ctx.nostroke()
... | python | {
"resource": ""
} |
q260201 | events.hover | validation | def hover(self, node):
""" Displays a popup when hovering over a node.
"""
if self.popup == False: return
if self.popup == True or self.popup.node != node:
if self.popup_text.has_key(node.id):
texts = self.popup_text[node.id]
else... | python | {
"resource": ""
} |
q260202 | popup.textpath | validation | def textpath(self, i):
""" Returns a cached textpath of the given text in queue.
"""
if len(self._textpaths) == i:
self._ctx.font(self.font, self.fontsize)
txt = self.q[i]
if len(self.q) > 1:
# Indicate current text (e.g. 5/13... | python | {
"resource": ""
} |
q260203 | popup.update | validation | def update(self):
""" Rotates the queued texts and determines display time.
"""
if self.delay > 0:
# It takes a while for the popup to appear.
self.delay -= 1; return
if self.fi == 0:
# Only one text in queue, displayed i... | python | {
"resource": ""
} |
q260204 | popup.draw | validation | def draw(self):
""" Draws a popup rectangle with a rotating text queue.
"""
if len(self.q) > 0:
self.update()
if self.delay == 0:
# Rounded rectangle in the given background color.
p,... | python | {
"resource": ""
} |
q260205 | write_main | validation | def write_main(argv):
"""
write FILENAME
Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.
"""
if len(argv) != 1:
print("Please provide the name of a file to write.")
return 1
filename = argv[0]
resource_name = "files/" + filename
tweaks_name = a... | python | {
"resource": ""
} |
q260206 | amend_filename | validation | def amend_filename(filename, amend):
"""Amend a filename with a suffix.
amend_filename("foo.txt", "_tweak") --> "foo_tweak.txt"
"""
base, ext = os.path.splitext(filename)
amended_name = base + amend + ext
return amended_name | python | {
"resource": ""
} |
q260207 | check_main | validation | def check_main(argv):
"""
check FILENAME
Check that FILENAME has not been edited since writing.
"""
if len(argv) != 1:
print("Please provide the name of a file to check.")
return 1
filename = argv[0]
if os.path.exists(filename):
print(u"Checking existing copy of... | python | {
"resource": ""
} |
q260208 | merge_configs | validation | def merge_configs(main, tweaks):
"""Merge tweaks into a main config file."""
for section in tweaks.sections():
for option in tweaks.options(section):
value = tweaks.get(section, option)
if option.endswith("+"):
option = option[:-1]
value = main.get... | python | {
"resource": ""
} |
q260209 | TamperEvidentFile.write | validation | def write(self, text, hashline=b"# {}"):
u"""
Write `text` to the file.
Writes the text to the file, with a final line checksumming the
contents. The entire file must be written with one `.write()` call.
The last line is written with the `hashline` format string, which can
... | python | {
"resource": ""
} |
q260210 | TamperEvidentFile.validate | validation | def validate(self):
"""
Check if the file still has its original contents.
Returns True if the file is unchanged, False if it has been tampered
with.
"""
with open(self.filename, "rb") as f:
text = f.read()
start_last_line = text.rfind(b"\n", 0, -1)... | python | {
"resource": ""
} |
q260211 | check_visitors | validation | def check_visitors(cls):
"""Check that a checker's visitors are correctly named.
A checker has methods named visit_NODETYPE, but it's easy to mis-name
a visit method, and it will never be called. This decorator checks
the class to see that all of its visitors are named after an existing
node class... | python | {
"resource": ""
} |
q260212 | usable_class_name | validation | def usable_class_name(node):
"""Make a reasonable class name for a class node."""
name = node.qname()
for prefix in ["__builtin__.", "builtins.", "."]:
if name.startswith(prefix):
name = name[len(prefix):]
return name | python | {
"resource": ""
} |
q260213 | parse_pylint_output | validation | def parse_pylint_output(pylint_output):
"""
Parse the pylint output-format=parseable lines into PylintError tuples.
"""
for line in pylint_output:
if not line.strip():
continue
if line[0:5] in ("-"*5, "*"*5):
continue
parsed = PYLINT_PARSEABLE_REGEX.sear... | python | {
"resource": ""
} |
q260214 | main | validation | def main(argv=None):
"""The edx_lint command entry point."""
if argv is None:
argv = sys.argv[1:]
if not argv or argv[0] == "help":
show_help()
return 0
elif argv[0] == "check":
return check_main(argv[1:])
elif argv[0] == "list":
return list_main(argv[1:])
... | python | {
"resource": ""
} |
q260215 | show_help | validation | def show_help():
"""Print the help string for the edx_lint command."""
print("""\
Manage local config files from masters in edx_lint.
Commands:
""")
for cmd in [write_main, check_main, list_main]:
print(cmd.__doc__.lstrip("\n")) | python | {
"resource": ""
} |
q260216 | trans_new | validation | def trans_new(name, transform, inverse, breaks=None,
minor_breaks=None, _format=None,
domain=(-np.inf, np.inf), doc='', **kwargs):
"""
Create a transformation class object
Parameters
----------
name : str
Name of the transformation
transform : callable ``f(x)... | python | {
"resource": ""
} |
q260217 | gettrans | validation | def gettrans(t):
"""
Return a trans object
Parameters
----------
t : str | callable | type | trans
name of transformation function
Returns
-------
out : trans
"""
obj = t
# Make sure trans object is instantiated
if isinstance(obj, str):
name = '{}_trans'... | python | {
"resource": ""
} |
q260218 | trans.breaks | validation | def breaks(self, limits):
"""
Calculate breaks in data space and return them
in transformed space.
Expects limits to be in *transform space*, this
is the same space as that where the domain is
specified.
This method wraps around :meth:`breaks_` to ensure
... | python | {
"resource": ""
} |
q260219 | datetime_trans.transform | validation | def transform(x):
"""
Transform from date to a numerical format
"""
try:
x = date2num(x)
except AttributeError:
# numpy datetime64
# This is not ideal because the operations do not
# preserve the np.datetime64 type. May be need
... | python | {
"resource": ""
} |
q260220 | rescale | validation | def rescale(x, to=(0, 1), _from=None):
"""
Rescale numeric vector to have specified minimum and maximum.
Parameters
----------
x : array_like | numeric
1D vector of values to manipulate.
to : tuple
output range (numeric vector of length two)
_from : tuple
input range... | python | {
"resource": ""
} |
q260221 | rescale_mid | validation | def rescale_mid(x, to=(0, 1), _from=None, mid=0):
"""
Rescale numeric vector to have specified minimum, midpoint,
and maximum.
Parameters
----------
x : array_like | numeric
1D vector of values to manipulate.
to : tuple
output range (numeric vector of length two)
_from :... | python | {
"resource": ""
} |
q260222 | rescale_max | validation | def rescale_max(x, to=(0, 1), _from=None):
"""
Rescale numeric vector to have specified maximum.
Parameters
----------
x : array_like | numeric
1D vector of values to manipulate.
to : tuple
output range (numeric vector of length two)
_from : tuple
input range (numeri... | python | {
"resource": ""
} |
q260223 | squish_infinite | validation | def squish_infinite(x, range=(0, 1)):
"""
Truncate infinite values to a range.
Parameters
----------
x : array_like
Values that should have infinities squished.
range : tuple
The range onto which to squish the infinites.
Must be of size 2.
Returns
-------
ou... | python | {
"resource": ""
} |
q260224 | squish | validation | def squish(x, range=(0, 1), only_finite=True):
"""
Squish values into range.
Parameters
----------
x : array_like
Values that should have out of range values squished.
range : tuple
The range onto which to squish the values.
only_finite: boolean
When true, only squis... | python | {
"resource": ""
} |
q260225 | _censor_with | validation | def _censor_with(x, range, value=None):
"""
Censor any values outside of range with ``None``
"""
return [val if range[0] <= val <= range[1] else value
for val in x] | python | {
"resource": ""
} |
q260226 | zero_range | validation | def zero_range(x, tol=np.finfo(float).eps * 100):
"""
Determine if range of vector is close to zero.
Parameters
----------
x : array_like | numeric
Value(s) to check. If it is an array_like, it
should be of length 2.
tol : float
Tolerance. Default tolerance is the `machi... | python | {
"resource": ""
} |
q260227 | expand_range | validation | def expand_range(range, mul=0, add=0, zero_width=1):
"""
Expand a range with a multiplicative or additive constant
Parameters
----------
range : tuple
Range of data. Size 2.
mul : int | float
Multiplicative constant
add : int | float | timedelta
Additive constant
... | python | {
"resource": ""
} |
q260228 | expand_range_distinct | validation | def expand_range_distinct(range, expand=(0, 0, 0, 0), zero_width=1):
"""
Expand a range with a multiplicative or additive constants
Similar to :func:`expand_range` but both sides of the range
expanded using different constants
Parameters
----------
range : tuple
Range of data. Size... | python | {
"resource": ""
} |
q260229 | trans_minor_breaks._extend_breaks | validation | def _extend_breaks(self, major):
"""
Append 2 extra breaks at either end of major
If breaks of transform space are non-equidistant,
:func:`minor_breaks` add minor breaks beyond the first
and last major breaks. The solutions is to extend those
breaks (in transformed space... | python | {
"resource": ""
} |
q260230 | timedelta_helper.best_units | validation | def best_units(self, sequence):
"""
Determine good units for representing a sequence of timedeltas
"""
# Read
# [(0.9, 's'),
# (9, 'm)]
# as, break ranges between 0.9 seconds (inclusive)
# and 9 minutes are represented in seconds. And so on.
t... | python | {
"resource": ""
} |
q260231 | timedelta_helper.scaled_limits | validation | def scaled_limits(self):
"""
Minimum and Maximum to use for computing breaks
"""
_min = self.limits[0]/self.factor
_max = self.limits[1]/self.factor
return _min, _max | python | {
"resource": ""
} |
q260232 | timedelta_helper.numeric_to_timedelta | validation | def numeric_to_timedelta(self, numerics):
"""
Convert sequence of numerics to timedelta
"""
if self.package == 'pandas':
return [self.type(int(x*self.factor), units='ns')
for x in numerics]
else:
return [self.type(seconds=x*self.factor)... | python | {
"resource": ""
} |
q260233 | timedelta_helper.to_numeric | validation | def to_numeric(self, td):
"""
Convert timedelta to a number corresponding to the
appropriate units. The appropriate units are those
determined with the object is initialised.
"""
if self.package == 'pandas':
return td.value/NANOSECONDS[self.units]
else... | python | {
"resource": ""
} |
q260234 | round_any | validation | def round_any(x, accuracy, f=np.round):
"""
Round to multiple of any number.
"""
if not hasattr(x, 'dtype'):
x = np.asarray(x)
return f(x / accuracy) * accuracy | python | {
"resource": ""
} |
q260235 | min_max | validation | def min_max(x, na_rm=False, finite=True):
"""
Return the minimum and maximum of x
Parameters
----------
x : array_like
Sequence
na_rm : bool
Whether to remove ``nan`` values.
finite : bool
Whether to consider only finite values.
Returns
-------
out : tup... | python | {
"resource": ""
} |
q260236 | precision | validation | def precision(x):
"""
Return the precision of x
Parameters
----------
x : array_like | numeric
Value(s) whose for which to compute the precision.
Returns
-------
out : numeric
The precision of ``x`` or that the values in ``x``.
Notes
-----
The precision is ... | python | {
"resource": ""
} |
q260237 | multitype_sort | validation | def multitype_sort(a):
"""
Sort elements of multiple types
x is assumed to contain elements of different types, such that
plain sort would raise a `TypeError`.
Parameters
----------
a : array-like
Array of items to be sorted
Returns
-------
out : list
Items sor... | python | {
"resource": ""
} |
q260238 | nearest_int | validation | def nearest_int(x):
"""
Return nearest long integer to x
"""
if x == 0:
return np.int64(0)
elif x > 0:
return np.int64(x + 0.5)
else:
return np.int64(x - 0.5) | python | {
"resource": ""
} |
q260239 | is_close_to_int | validation | def is_close_to_int(x):
"""
Check if value is close to an integer
Parameters
----------
x : float
Numeric value to check
Returns
-------
out : bool
"""
if not np.isfinite(x):
return False
return abs(x - nearest_int(x)) < 1e-10 | python | {
"resource": ""
} |
q260240 | same_log10_order_of_magnitude | validation | def same_log10_order_of_magnitude(x, delta=0.1):
"""
Return true if range is approximately in same order of magnitude
For example these sequences are in the same order of magnitude:
- [1, 8, 5] # [1, 10)
- [35, 20, 80] # [10 100)
- [232, 730] # [100, 1000)
Parameters
... | python | {
"resource": ""
} |
q260241 | _format | validation | def _format(formatter, x):
"""
Helper to format and tidy up
"""
# For MPL to play nice
formatter.create_dummy_axis()
# For sensible decimal places
formatter.set_locs([val for val in x if ~np.isnan(val)])
try:
oom = int(formatter.orderOfMagnitude)
except AttributeError:
... | python | {
"resource": ""
} |
q260242 | log_format._tidyup_labels | validation | def _tidyup_labels(self, labels):
"""
Make all labels uniform in format and remove redundant zeros
for labels in exponential format.
Parameters
----------
labels : list-like
Labels to be tidied.
Returns
-------
out : list-like
... | python | {
"resource": ""
} |
q260243 | hls_palette | validation | def hls_palette(n_colors=6, h=.01, l=.6, s=.65):
"""
Get a set of evenly spaced colors in HLS hue space.
h, l, and s should be between 0 and 1
Parameters
----------
n_colors : int
number of colors in the palette
h : float
first hue
l : float
lightness
s : f... | python | {
"resource": ""
} |
q260244 | husl_palette | validation | def husl_palette(n_colors=6, h=.01, s=.9, l=.65):
"""
Get a set of evenly spaced colors in HUSL hue space.
h, s, and l should be between 0 and 1
Parameters
----------
n_colors : int
number of colors in the palette
h : float
first hue
s : float
saturation
l ... | python | {
"resource": ""
} |
q260245 | grey_pal | validation | def grey_pal(start=0.2, end=0.8):
"""
Utility for creating continuous grey scale palette
Parameters
----------
start : float
grey value at low end of palette
end : float
grey value at high end of palette
Returns
-------
out : function
Continuous color palett... | python | {
"resource": ""
} |
q260246 | hue_pal | validation | def hue_pal(h=.01, l=.6, s=.65, color_space='hls'):
"""
Utility for making hue palettes for color schemes.
Parameters
----------
h : float
first hue. In the [0, 1] range
l : float
lightness. In the [0, 1] range
s : float
saturation. In the [0, 1] range
color_spac... | python | {
"resource": ""
} |
q260247 | brewer_pal | validation | def brewer_pal(type='seq', palette=1):
"""
Utility for making a brewer palette
Parameters
----------
type : 'sequential' | 'qualitative' | 'diverging'
Type of palette. Sequential, Qualitative or
Diverging. The following abbreviations may
be used, ``seq``, ``qual`` or ``div``... | python | {
"resource": ""
} |
q260248 | gradient_n_pal | validation | def gradient_n_pal(colors, values=None, name='gradientn'):
"""
Create a n color gradient palette
Parameters
----------
colors : list
list of colors
values : list, optional
list of points in the range [0, 1] at which to
place each color. Must be the same size as
`... | python | {
"resource": ""
} |
q260249 | cmap_pal | validation | def cmap_pal(name=None, lut=None):
"""
Create a continuous palette using an MPL colormap
Parameters
----------
name : str
Name of colormap
lut : None | int
This is the number of entries desired in the lookup table.
Default is ``None``, leave it up Matplotlib.
Return... | python | {
"resource": ""
} |
q260250 | cmap_d_pal | validation | def cmap_d_pal(name=None, lut=None):
"""
Create a discrete palette using an MPL Listed colormap
Parameters
----------
name : str
Name of colormap
lut : None | int
This is the number of entries desired in the lookup table.
Default is ``None``, leave it up Matplotlib.
... | python | {
"resource": ""
} |
q260251 | desaturate_pal | validation | def desaturate_pal(color, prop, reverse=False):
"""
Create a palette that desaturate a color by some proportion
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
prop : float
saturation channel of color will be multiplied by
this value
... | python | {
"resource": ""
} |
q260252 | manual_pal | validation | def manual_pal(values):
"""
Create a palette from a list of values
Parameters
----------
values : sequence
Values that will be returned by the palette function.
Returns
-------
out : function
A function palette that takes a single
:class:`int` parameter ``n`` an... | python | {
"resource": ""
} |
q260253 | cubehelix_pal | validation | def cubehelix_pal(start=0, rot=.4, gamma=1.0, hue=0.8,
light=.85, dark=.15, reverse=False):
"""
Utility for creating continuous palette from the cubehelix system.
This produces a colormap with linearly-decreasing (or increasing)
brightness. That means that information will be preserve... | python | {
"resource": ""
} |
q260254 | scale_continuous.apply | validation | def apply(cls, x, palette, na_value=None, trans=None):
"""
Scale data continuously
Parameters
----------
x : array_like
Continuous values to scale
palette : callable ``f(x)``
Palette to use
na_value : object
Value to use for mi... | python | {
"resource": ""
} |
q260255 | scale_continuous.map | validation | def map(cls, x, palette, limits, na_value=None, oob=censor):
"""
Map values to a continuous palette
Parameters
----------
x : array_like
Continuous values to scale
palette : callable ``f(x)``
palette to use
na_value : object
Va... | python | {
"resource": ""
} |
q260256 | scale_discrete.map | validation | def map(cls, x, palette, limits, na_value=None):
"""
Map values to a discrete palette
Parameters
----------
palette : callable ``f(x)``
palette to use
x : array_like
Continuous values to scale
na_value : object
Value to use for... | python | {
"resource": ""
} |
q260257 | EnvConfig.parse | validation | def parse(type: Type):
"""
Register a parser for a attribute type.
Parsers will be used to parse `str` type objects from either
the commandline arguments or environment variables.
Args:
type: the type the decorated function will be responsible
for pa... | python | {
"resource": ""
} |
q260258 | _patched_run_hook | validation | def _patched_run_hook(hook_name, project_dir, context):
"""Used to patch cookiecutter's ``run_hook`` function.
This patched version ensures that the temple.yaml file is created before
any cookiecutter hooks are executed
"""
if hook_name == 'post_gen_project':
with temple.utils.cd(project_di... | python | {
"resource": ""
} |
q260259 | _generate_files | validation | def _generate_files(repo_dir, config, template, version):
"""Uses cookiecutter to generate files for the project.
Monkeypatches cookiecutter's "run_hook" to ensure that the temple.yaml file is
generated before any hooks run. This is important to ensure that hooks can also
perform any actions involving ... | python | {
"resource": ""
} |
q260260 | setup | validation | def setup(template, version=None):
"""Sets up a new project from a template
Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration
of this function.
Args:
template (str): The git SSH path to a template
version (str, optional): The version of the template ... | python | {
"resource": ""
} |
q260261 | _parse_link_header | validation | def _parse_link_header(headers):
"""Parses Github's link header for pagination.
TODO eventually use a github client for this
"""
links = {}
if 'link' in headers:
link_headers = headers['link'].split(', ')
for link_header in link_headers:
(url, rel) = link_header.split(';... | python | {
"resource": ""
} |
q260262 | _code_search | validation | def _code_search(query, github_user=None):
"""Performs a Github API code search
Args:
query (str): The query sent to Github's code search
github_user (str, optional): The Github user being searched in the query string
Returns:
dict: A dictionary of repository information keyed on t... | python | {
"resource": ""
} |
q260263 | ls | validation | def ls(github_user, template=None):
"""Lists all temple templates and packages associated with those templates
If ``template`` is None, returns the available templates for the configured
Github org.
If ``template`` is a Github path to a template, returns all projects spun
up with that template.
... | python | {
"resource": ""
} |
q260264 | update | validation | def update(check, enter_parameters, version):
"""
Update package with latest template. Must be inside of the project
folder to run.
Using "-e" will prompt for re-entering the template parameters again
even if the project is up to date.
Use "-v" to update to a particular version of a template.
... | python | {
"resource": ""
} |
q260265 | ls | validation | def ls(github_user, template, long_format):
"""
List packages created with temple. Enter a github user or
organization to list all templates under the user or org.
Using a template path as the second argument will list all projects
that have been started with that template.
Use "-l" to print th... | python | {
"resource": ""
} |
q260266 | switch | validation | def switch(template, version):
"""
Switch a project's template to a different template.
"""
temple.update.update(new_template=template, new_version=version) | python | {
"resource": ""
} |
q260267 | _in_git_repo | validation | def _in_git_repo():
"""Returns True if inside a git repo, False otherwise"""
ret = temple.utils.shell('git rev-parse', stderr=subprocess.DEVNULL, check=False)
return ret.returncode == 0 | python | {
"resource": ""
} |
q260268 | _has_branch | validation | def _has_branch(branch):
"""Return True if the target branch exists."""
ret = temple.utils.shell('git rev-parse --verify {}'.format(branch),
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
check=False)
return ret.re... | python | {
"resource": ""
} |
q260269 | not_has_branch | validation | def not_has_branch(branch):
"""Raises `ExistingBranchError` if the specified branch exists."""
if _has_branch(branch):
msg = 'Cannot proceed while {} branch exists; remove and try again.'.format(branch)
raise temple.exceptions.ExistingBranchError(msg) | python | {
"resource": ""
} |
q260270 | has_env_vars | validation | def has_env_vars(*env_vars):
"""Raises `InvalidEnvironmentError` when one isnt set"""
for env_var in env_vars:
if not os.environ.get(env_var):
msg = (
'Must set {} environment variable. View docs for setting up environment at {}'
).format(env_var, temple.constants... | python | {
"resource": ""
} |
q260271 | is_temple_project | validation | def is_temple_project():
"""Raises `InvalidTempleProjectError` if repository is not a temple project"""
if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE):
msg = 'No {} file found in repository.'.format(temple.constants.TEMPLE_CONFIG_FILE)
raise temple.exceptions.InvalidTempleProjectErro... | python | {
"resource": ""
} |
q260272 | _get_current_branch | validation | def _get_current_branch():
"""Determine the current git branch"""
result = temple.utils.shell('git rev-parse --abbrev-ref HEAD', stdout=subprocess.PIPE)
return result.stdout.decode('utf8').strip() | python | {
"resource": ""
} |
q260273 | clean | validation | def clean():
"""Cleans up temporary resources
Tries to clean up:
1. The temporary update branch used during ``temple update``
2. The primary update branch used during ``temple update``
"""
temple.check.in_git_repo()
current_branch = _get_current_branch()
update_branch = temple.constan... | python | {
"resource": ""
} |
q260274 | _cookiecutter_configs_have_changed | validation | def _cookiecutter_configs_have_changed(template, old_version, new_version):
"""Given an old version and new version, check if the cookiecutter.json files have changed
When the cookiecutter.json files change, it means the user will need to be prompted for
new context
Args:
template (str): The g... | python | {
"resource": ""
} |
q260275 | _apply_template | validation | def _apply_template(template, target, *, checkout, extra_context):
"""Apply a template to a temporary directory and then copy results to target."""
with tempfile.TemporaryDirectory() as tempdir:
repo_dir = cc_main.cookiecutter(
template,
checkout=checkout,
no_input=Tr... | python | {
"resource": ""
} |
q260276 | up_to_date | validation | def up_to_date(version=None):
"""Checks if a temple project is up to date with the repo
Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'update' for the duration of this
function.
Args:
version (str, optional): Update against this git SHA or branch of the template
Returns:
... | python | {
"resource": ""
} |
q260277 | _needs_new_cc_config_for_update | validation | def _needs_new_cc_config_for_update(old_template, old_version, new_template, new_version):
"""
Given two templates and their respective versions, return True if a new cookiecutter
config needs to be obtained from the user
"""
if old_template != new_template:
return True
else:
ret... | python | {
"resource": ""
} |
q260278 | shell | validation | def shell(cmd, check=True, stdin=None, stdout=None, stderr=None):
"""Runs a subprocess shell with check=True by default"""
return subprocess.run(cmd, shell=True, check=check, stdin=stdin, stdout=stdout, stderr=stderr) | python | {
"resource": ""
} |
q260279 | read_temple_config | validation | def read_temple_config():
"""Reads the temple YAML configuration file in the repository"""
with open(temple.constants.TEMPLE_CONFIG_FILE) as temple_config_file:
return yaml.load(temple_config_file, Loader=yaml.SafeLoader) | python | {
"resource": ""
} |
q260280 | write_temple_config | validation | def write_temple_config(temple_config, template, version):
"""Writes the temple YAML configuration"""
with open(temple.constants.TEMPLE_CONFIG_FILE, 'w') as temple_config_file:
versioned_config = {
**temple_config,
**{'_version': version, '_template': template},
}
... | python | {
"resource": ""
} |
q260281 | get_cookiecutter_config | validation | def get_cookiecutter_config(template, default_config=None, version=None):
"""Obtains the configuration used for cookiecutter templating
Args:
template: Path to the template
default_config (dict, optional): The default configuration
version (str, optional): The git SHA or branch to use w... | python | {
"resource": ""
} |
q260282 | set_cmd_env_var | validation | def set_cmd_env_var(value):
"""Decorator that sets the temple command env var to value"""
def func_decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
previous_cmd_env_var = os.getenv(temple.constants.TEMPLE_ENV_VAR)
os.environ[temple.constants.T... | python | {
"resource": ""
} |
q260283 | GithubClient._call_api | validation | def _call_api(self, verb, url, **request_kwargs):
"""Perform a github API call
Args:
verb (str): Can be "post", "put", or "get"
url (str): The base URL with a leading slash for Github API (v3)
auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object
... | python | {
"resource": ""
} |
q260284 | deploy | validation | def deploy(target):
"""Deploys the package and documentation.
Proceeds in the following steps:
1. Ensures proper environment variables are set and checks that we are on Circle CI
2. Tags the repository with the new version
3. Creates a standard distribution and a wheel
4. Updates version.py to... | python | {
"resource": ""
} |
q260285 | DSStoreChecker.run | validation | def run(self):
"""
Finds .DS_Store files into path
"""
filename = ".DS_Store"
command = "find {path} -type f -name \"{filename}\" ".format(path = self.path, filename = filename)
cmd = CommandHelper(command)
cmd.execute()
files = cmd.output.split("\n")
for f in files:
if not f.endswith(filename):
... | python | {
"resource": ""
} |
q260286 | HttpReport.run | validation | def run(self):
"""
Method executed dynamically by framework. This method will do a http request to
endpoint setted into config file with the issues and other data.
"""
options = {}
if bool(self.config['use_proxy']):
options['proxies'] = {"http": self.config['proxy'], "https": self.config['proxy']}
opt... | python | {
"resource": ""
} |
q260287 | GenericChecker.path | validation | def path(self, value):
"""
Setter for 'path' property
Args:
value (str): Absolute path to scan
"""
if not value.endswith('/'):
self._path = '{v}/'.format(v=value)
else:
self._path = value | python | {
"resource": ""
} |
q260288 | GenericChecker.parseConfig | validation | def parseConfig(cls, value):
"""
Parse the config values
Args:
value (dict): Dictionary which contains the checker config
Returns:
dict: The checker config with parsed values
"""
if 'enabled' in value:
value['enabled'] = bool(value['enabled'])
if 'exclude_paths' in value:
value['exclude_pat... | python | {
"resource": ""
} |
q260289 | CommandHelper.getOSName | validation | def getOSName(self):
"""
Get the OS name. If OS is linux, returns the Linux distribution name
Returns:
str: OS name
"""
_system = platform.system()
if _system in [self.__class__.OS_WINDOWS, self.__class__.OS_MAC, self.__class__.OS_LINUX]:
if _system == self.__class__.OS_LINUX:
_dist = platform.li... | python | {
"resource": ""
} |
q260290 | CommandHelper.execute | validation | def execute(self, shell = True):
"""
Executes the command setted into class
Args:
shell (boolean): Set True if command is a shell command. Default: True
"""
process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell)
self.output, self.errors = process.communicate() | python | {
"resource": ""
} |
q260291 | AtomShieldsScanner._debug | validation | def _debug(message, color=None, attrs=None):
"""
Print a message if the class attribute 'verbose' is enabled
Args:
message (str): Message to print
"""
if attrs is None:
attrs = []
if color is not None:
print colored(message, color, attrs=attrs)
else:
if len(attrs) > 0:
print colored(messa... | python | {
"resource": ""
} |
q260292 | AtomShieldsScanner.setup | validation | def setup():
"""
Creates required directories and copy checkers and reports.
"""
# # Check if dir is writable
# if not os.access(AtomShieldsScanner.HOME, os.W_OK):
# AtomShieldsScanner.HOME = os.path.expanduser("~/.atomshields")
# AtomShieldsScanner.CHECKERS_DIR = os.path.join(AtomShieldsScanner.HOME... | python | {
"resource": ""
} |
q260293 | AtomShieldsScanner._addConfig | validation | def _addConfig(instance, config, parent_section):
"""
Writes a section for a plugin.
Args:
instance (object): Class instance for plugin
config (object): Object (ConfigParser) which the current config
parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports'
"""
try:
section... | python | {
"resource": ""
} |
q260294 | AtomShieldsScanner.getConfig | validation | def getConfig(self, section = None):
"""
Returns a dictionary which contains the current config. If a section is setted,
only will returns the section config
Args:
section (str): (Optional) Section name.
Returns:
dict: Representation of current config
"""
data = {}
if section is None:
for s i... | python | {
"resource": ""
} |
q260295 | AtomShieldsScanner._getClassInstance | validation | def _getClassInstance(path, args=None):
"""
Returns a class instance from a .py file.
Args:
path (str): Absolute path to .py file
args (dict): Arguments passed via class constructor
Returns:
object: Class instance or None
"""
if not path.endswith(".py"):
return None
if args is None:
args... | python | {
"resource": ""
} |
q260296 | AtomShieldsScanner._executeMassiveMethod | validation | def _executeMassiveMethod(path, method, args=None, classArgs = None):
"""
Execute an specific method for each class instance located in path
Args:
path (str): Absolute path which contains the .py files
method (str): Method to execute into class instance
Returns:
dict: Dictionary which contains the re... | python | {
"resource": ""
} |
q260297 | AtomShieldsScanner.run | validation | def run(self):
"""
Run a scan in the path setted.
"""
self.checkProperties()
self.debug("[*] Iniciando escaneo de AtomShields con las siguientes propiedades. . . ")
self.showScanProperties()
self.loadConfig()
# Init time counter
init_ts = datetime.now()
# Execute plugins
cwd = os.getcwd()
... | python | {
"resource": ""
} |
q260298 | RetireJSChecker.install | validation | def install():
"""
Install all the dependences
"""
cmd = CommandHelper()
cmd.install("npm")
cmd = CommandHelper()
cmd.install("nodejs-legacy")
# Install retre with npm
cmd = CommandHelper()
cmd.command = "npm install -g retire"
cmd.execute()
if cmd.errors:
from termcolor import colored
... | python | {
"resource": ""
} |
q260299 | Issue.potential | validation | def potential(self, value):
"""
Setter for 'potential' property
Args:
value (bool): True if a potential is required. False else
"""
if value:
self._potential = True
else:
self._potential = False | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.