_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q265300 | LatexFixer._str_replacement | validation | def _str_replacement(self, target, replacement):
"""Replace target with replacement"""
self.data = self.data.replace(target, replacement) | python | {
"resource": ""
} |
q265301 | LatexFixer._regex_replacement | validation | def _regex_replacement(self, target, replacement):
"""Regex substitute target with replacement"""
match = re.compile(target)
self.data = match.sub(replacement, self.data) | python | {
"resource": ""
} |
q265302 | sphinx_make | validation | def sphinx_make(*targets):
"""Call the Sphinx Makefile with the specified targets.
`options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).
"""
sh('make %s' % ' '.join(targets), cwd=options.paved.docs.path) | python | {
"resource": ""
} |
q265303 | rsync_docs | validation | def rsync_docs():
"""Upload the docs to a remote location via rsync.
`options.paved.docs.rsync_location`: the target location to rsync files to.
`options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).
`options.paved.docs.build_rel`: the path of the documentation
build folder, relative to `options.paved.docs.path`.
"""
assert options.paved.docs.rsync_location, "Please specify an rsync location in options.paved.docs.rsync_location."
sh('rsync -ravz %s/ %s/' % (path(options.paved.docs.path) / options.paved.docs.build_rel,
options.paved.docs.rsync_location)) | python | {
"resource": ""
} |
q265304 | ghpages | validation | def ghpages():
'''Push Sphinx docs to github_ gh-pages branch.
1. Create file .nojekyll
2. Push the branch to origin/gh-pages
after committing using ghp-import_
Requirements:
- easy_install ghp-import
Options:
- `options.paved.docs.*` is not used
- `options.sphinx.docroot` is used (default=docs)
- `options.sphinx.builddir` is used (default=.build)
.. warning::
This will DESTROY your gh-pages branch.
If you love it, you'll want to take backups
before playing with this. This script assumes
that gh-pages is 100% derivative. You should
never edit files in your gh-pages branch by hand
if you're using this script because you will
lose your work.
.. _github: https://github.com
.. _ghp-import: https://github.com/davisp/ghp-import
'''
# copy from paver
opts = options
docroot = path(opts.get('docroot', 'docs'))
if not docroot.exists():
raise BuildFailure("Sphinx documentation root (%s) does not exist."
% docroot)
builddir = docroot / opts.get("builddir", ".build")
# end of copy
builddir=builddir / 'html'
if not builddir.exists():
raise BuildFailure("Sphinx build directory (%s) does not exist."
% builddir)
nojekyll = path(builddir) / '.nojekyll'
nojekyll.touch()
sh('ghp-import -p %s' % (builddir)) | python | {
"resource": ""
} |
q265305 | showhtml | validation | def showhtml():
"""Open your web browser and display the generated html documentation.
"""
import webbrowser
# copy from paver
opts = options
docroot = path(opts.get('docroot', 'docs'))
if not docroot.exists():
raise BuildFailure("Sphinx documentation root (%s) does not exist."
% docroot)
builddir = docroot / opts.get("builddir", ".build")
# end of copy
builddir=builddir / 'html'
if not builddir.exists():
raise BuildFailure("Sphinx build directory (%s) does not exist."
% builddir)
webbrowser.open(builddir / 'index.html') | python | {
"resource": ""
} |
q265306 | CssMinifier.minify | validation | def minify(self, css):
"""Tries to minimize the length of CSS code passed as parameter. Returns string."""
css = css.replace("\r\n", "\n") # get rid of Windows line endings, if they exist
for rule in _REPLACERS[self.level]:
css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rule[1], css)
return css | python | {
"resource": ""
} |
q265307 | IndexedOpen.get_or_create_index | validation | def get_or_create_index(self, index_ratio, index_width):
"""Return an open file-object to the index file"""
if not self.index_path.exists() or not self.filepath.stat().st_mtime == self.index_path.stat().st_mtime:
create_index(self.filepath, self.index_path, index_ratio=index_ratio, index_width=index_width)
return IndexFile(str(self.index_path)) | python | {
"resource": ""
} |
q265308 | MapRouletteTaskCollection.create | validation | def create(self, server):
"""Create the tasks on the server"""
for chunk in self.__cut_to_size():
server.post(
'tasks_admin',
chunk.as_payload(),
replacements={
'slug': chunk.challenge.slug}) | python | {
"resource": ""
} |
q265309 | MapRouletteTaskCollection.update | validation | def update(self, server):
"""Update existing tasks on the server"""
for chunk in self.__cut_to_size():
server.put(
'tasks_admin',
chunk.as_payload(),
replacements={
'slug': chunk.challenge.slug}) | python | {
"resource": ""
} |
q265310 | MapRouletteTaskCollection.reconcile | validation | def reconcile(self, server):
"""
Reconcile this collection with the server.
"""
if not self.challenge.exists(server):
raise Exception('Challenge does not exist on server')
existing = MapRouletteTaskCollection.from_server(server, self.challenge)
same = []
new = []
changed = []
deleted = []
# reconcile the new tasks with the existing tasks:
for task in self.tasks:
# if the task exists on the server...
if task.identifier in [existing_task.identifier for existing_task in existing.tasks]:
# and they are equal...
if task == existing.get_by_identifier(task.identifier):
# add to 'same' list
same.append(task)
# if they are not equal, add to 'changed' list
else:
changed.append(task)
# if the task does not exist on the server, add to 'new' list
else:
new.append(task)
# next, check for tasks on the server that don't exist in the new collection...
for task in existing.tasks:
if task.identifier not in [task.identifier for task in self.tasks]:
# ... and add those to the 'deleted' list.
deleted.append(task)
# update the server with new, changed, and deleted tasks
if new:
newCollection = MapRouletteTaskCollection(self.challenge, tasks=new)
newCollection.create(server)
if changed:
changedCollection = MapRouletteTaskCollection(self.challenge, tasks=changed)
changedCollection.update(server)
if deleted:
deletedCollection = MapRouletteTaskCollection(self.challenge, tasks=deleted)
for task in deletedCollection.tasks:
task.status = 'deleted'
deletedCollection.update(server)
# return same, new, changed and deleted tasks
return {'same': same, 'new': new, 'changed': changed, 'deleted': deleted} | python | {
"resource": ""
} |
q265311 | yn_prompt | validation | def yn_prompt(msg, default=True):
"""
Prompts the user for yes or no.
"""
ret = custom_prompt(msg, ["y", "n"], "y" if default else "n")
if ret == "y":
return True
return False | python | {
"resource": ""
} |
q265312 | custom_prompt | validation | def custom_prompt(msg, options, default):
"""
Prompts the user with custom options.
"""
formatted_options = [
x.upper() if x == default else x.lower() for x in options
]
sure = input("{0} [{1}]: ".format(msg, "/".join(formatted_options)))
if len(sure) == 0:
return default
for option in options:
if sure.upper() == option.upper():
return option
return default | python | {
"resource": ""
} |
q265313 | read | validation | def read(args):
"""Reading the configure file and adds non-existing attributes to 'args'"""
if args.config_file is None or not isfile(args.config_file):
return
logging.info("Reading configure file: %s"%args.config_file)
config = cparser.ConfigParser()
config.read(args.config_file)
if not config.has_section('lrcloud'):
raise RuntimeError("Configure file has no [lrcloud] section!")
for (name, value) in config.items('lrcloud'):
if value == "True":
value = True
elif value == "False":
value = False
if getattr(args, name) is None:
setattr(args, name, value) | python | {
"resource": ""
} |
q265314 | write | validation | def write(args):
"""Writing the configure file with the attributes in 'args'"""
logging.info("Writing configure file: %s"%args.config_file)
if args.config_file is None:
return
#Let's add each attribute of 'args' to the configure file
config = cparser.ConfigParser()
config.add_section("lrcloud")
for p in [x for x in dir(args) if not x.startswith("_")]:
if p in IGNORE_ARGS:
continue#We ignore some attributes
value = getattr(args, p)
if value is not None:
config.set('lrcloud', p, str(value))
with open(args.config_file, 'w') as f:
config.write(f) | python | {
"resource": ""
} |
q265315 | GameObject.new | validation | def new(self, mode):
"""
Create a new instance of a game. Note, a mode MUST be provided and MUST be of
type GameMode.
:param mode: <required>
"""
dw = DigitWord(wordtype=mode.digit_type)
dw.random(mode.digits)
self._key = str(uuid.uuid4())
self._status = ""
self._ttl = 3600
self._answer = dw
self._mode = mode
self._guesses_remaining = mode.guesses_allowed
self._guesses_made = 0 | python | {
"resource": ""
} |
q265316 | Version.bump | validation | def bump(self, target):
"""
Bumps the Version given a target
The target can be either MAJOR, MINOR or PATCH
"""
if target == 'patch':
return Version(self.major, self.minor, self.patch + 1)
if target == 'minor':
return Version(self.major, self.minor + 1, 0)
if target == 'major':
return Version(self.major + 1, 0, 0)
return self.clone() | python | {
"resource": ""
} |
q265317 | Tag.clone | validation | def clone(self):
"""
Returns a copy of this object
"""
t = Tag(self.version.major, self.version.minor, self.version.patch)
if self.revision is not None:
t.revision = self.revision.clone()
return t | python | {
"resource": ""
} |
q265318 | Tag.with_revision | validation | def with_revision(self, label, number):
"""
Returns a Tag with a given revision
"""
t = self.clone()
t.revision = Revision(label, number)
return t | python | {
"resource": ""
} |
q265319 | Tag.parse | validation | def parse(s):
"""
Parses a string into a Tag
"""
try:
m = _regex.match(s)
t = Tag(int(m.group('major')),
int(m.group('minor')),
int(m.group('patch')))
return t \
if m.group('label') is None \
else t.with_revision(m.group('label'), int(m.group('number')))
except AttributeError:
return None | python | {
"resource": ""
} |
q265320 | tile | validation | def tile():
"""Tiles open figures."""
figs = plt.get_fignums()
# Keep track of x, y, size for figures
x = 0
y = 0
# maxy = 0
toppad = 21
size = np.array([0, 0])
if ( len(figs) != 0 ):
fig = plt.figure(figs[0])
screen = fig.canvas.window.get_screen()
screenx = screen.get_monitor_geometry(screen.get_primary_monitor())
screenx = screenx[2]
fig = plt.figure(figs[0])
fig.canvas.manager.window.move(x, y)
maxy = np.array(fig.canvas.manager.window.get_position())[1]
size = np.array(fig.canvas.manager.window.get_size())
y = maxy
x += size[0]+1
for fig in figs[1:]:
fig = plt.figure(fig)
size = np.array(fig.canvas.manager.window.get_size())
if ( x+size[0] > screenx ):
x = 0
y = maxy
maxy = y+size[1]+toppad
else:
maxy = max(maxy, y+size[1]+toppad)
fig.canvas.manager.window.move(x, y)
x += size[0] + 1 | python | {
"resource": ""
} |
q265321 | update_time | validation | def update_time(sender, **kwargs):
"""
When a Comment is added, updates the Update to set "last_updated" time
"""
comment = kwargs['instance']
if comment.content_type.app_label == "happenings" and comment.content_type.name == "Update":
from .models import Update
item = Update.objects.get(id=comment.object_pk)
item.save() | python | {
"resource": ""
} |
q265322 | extra_context | validation | def extra_context(request):
"""Adds useful global items to the context for use in templates.
* *request*: the request object
* *HOST*: host name of server
* *IN_ADMIN*: True if you are in the django admin area
"""
host = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', None) \
or request.get_host()
d = {
'request':request,
'HOST':host,
'IN_ADMIN':request.path.startswith('/admin/'),
}
return d | python | {
"resource": ""
} |
q265323 | MapRouletteChallenge.create | validation | def create(self, server):
"""Create the challenge on the server"""
return server.post(
'challenge_admin',
self.as_payload(),
replacements={'slug': self.slug}) | python | {
"resource": ""
} |
q265324 | MapRouletteChallenge.update | validation | def update(self, server):
"""Update existing challenge on the server"""
return server.put(
'challenge_admin',
self.as_payload(),
replacements={'slug': self.slug}) | python | {
"resource": ""
} |
q265325 | MapRouletteChallenge.exists | validation | def exists(self, server):
"""Check if a challenge exists on the server"""
try:
server.get(
'challenge',
replacements={'slug': self.slug})
except Exception:
return False
return True | python | {
"resource": ""
} |
q265326 | Positions.get_position | validation | def get_position(self, position_id):
"""
Returns position data.
http://dev.wheniwork.com/#get-existing-position
"""
url = "/2/positions/%s" % position_id
return self.position_from_json(self._get_resource(url)["position"]) | python | {
"resource": ""
} |
q265327 | Positions.get_positions | validation | def get_positions(self):
"""
Returns a list of positions.
http://dev.wheniwork.com/#listing-positions
"""
url = "/2/positions"
data = self._get_resource(url)
positions = []
for entry in data['positions']:
positions.append(self.position_from_json(entry))
return positions | python | {
"resource": ""
} |
q265328 | Positions.create_position | validation | def create_position(self, params={}):
"""
Creates a position
http://dev.wheniwork.com/#create-update-position
"""
url = "/2/positions/"
body = params
data = self._post_resource(url, body)
return self.position_from_json(data["position"]) | python | {
"resource": ""
} |
q265329 | sloccount | validation | def sloccount():
'''Print "Source Lines of Code" and export to file.
Export is hudson_ plugin_ compatible: sloccount.sc
requirements:
- sloccount_ should be installed.
- tee and pipes are used
options.paved.pycheck.sloccount.param
.. _sloccount: http://www.dwheeler.com/sloccount/
.. _hudson: http://hudson-ci.org/
.. _plugin: http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin
'''
# filter out subpackages
setup = options.get('setup')
packages = options.get('packages') if setup else None
if packages:
dirs = [x for x in packages if '.' not in x]
else:
dirs = ['.']
# sloccount has strange behaviour with directories,
# can cause exception in hudson sloccount plugin.
# Better to call it with file list
ls=[]
for d in dirs:
ls += list(path(d).walkfiles())
#ls=list(set(ls))
files=' '.join(ls)
param=options.paved.pycheck.sloccount.param
sh('sloccount {param} {files} | tee sloccount.sc'.format(param=param, files=files)) | python | {
"resource": ""
} |
q265330 | pyflakes | validation | def pyflakes():
'''passive check of python programs by pyflakes.
requirements:
- pyflakes_ should be installed. ``easy_install pyflakes``
options.paved.pycheck.pyflakes.param
.. _pyflakes: http://pypi.python.org/pypi/pyflakes
'''
# filter out subpackages
packages = [x for x in options.setup.packages if '.' not in x]
sh('pyflakes {param} {files}'.format(param=options.paved.pycheck.pyflakes.param, files=' '.join(packages))) | python | {
"resource": ""
} |
q265331 | http_exception_error_handler | validation | def http_exception_error_handler(
exception):
"""
Handle HTTP exception
:param werkzeug.exceptions.HTTPException exception: Raised exception
A response is returned, as formatted by the :py:func:`response` function.
"""
assert issubclass(type(exception), HTTPException), type(exception)
assert hasattr(exception, "code")
assert hasattr(exception, "description")
return response(exception.code, exception.description) | python | {
"resource": ""
} |
q265332 | is_colour | validation | def is_colour(value):
"""Returns True if the value given is a valid CSS colour, i.e. matches one
of the regular expressions in the module or is in the list of
predetefined values by the browser.
"""
global PREDEFINED, HEX_MATCH, RGB_MATCH, RGBA_MATCH, HSL_MATCH, HSLA_MATCH
value = value.strip()
# hex match
if HEX_MATCH.match(value) or RGB_MATCH.match(value) or \
RGBA_MATCH.match(value) or HSL_MATCH.match(value) or \
HSLA_MATCH.match(value) or value in PREDEFINED:
return True
return False | python | {
"resource": ""
} |
q265333 | reynolds_number | validation | def reynolds_number(length, speed, temperature=25):
"""
Reynold number utility function that return Reynold number for vehicle at specific length and speed.
Optionally, it can also take account of temperature effect of sea water.
Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf
:param length: metres length of the vehicle
:param speed: m/s speed of the vehicle
:param temperature: degree C
:return: Reynolds number of the vehicle (dimensionless)
"""
kinematic_viscosity = interpolate.interp1d([0, 10, 20, 25, 30, 40],
np.array([18.54, 13.60, 10.50, 9.37, 8.42, 6.95]) / 10 ** 7)
# Data from http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf
Re = length * speed / kinematic_viscosity(temperature)
return Re | python | {
"resource": ""
} |
q265334 | froude_number | validation | def froude_number(speed, length):
"""
Froude number utility function that return Froude number for vehicle at specific length and speed.
:param speed: m/s speed of the vehicle
:param length: metres length of the vehicle
:return: Froude number of the vehicle (dimensionless)
"""
g = 9.80665 # conventional standard value m/s^2
Fr = speed / np.sqrt(g * length)
return Fr | python | {
"resource": ""
} |
q265335 | residual_resistance_coef | validation | def residual_resistance_coef(slenderness, prismatic_coef, froude_number):
"""
Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number.
:param slenderness: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displacement
:param prismatic_coef: Prismatic coefficient dimensionless :math:`∇/(L\cdot A_m)` where L is length of ship, ∇ is displacement Am is midsection area of the ship
:param froude_number: Froude number of the ship dimensionless
:return: Residual resistance of the ship
"""
Cr = cr(slenderness, prismatic_coef, froude_number)
if math.isnan(Cr):
Cr = cr_nearest(slenderness, prismatic_coef, froude_number)
# if Froude number is out of interpolation range, nearest extrapolation is used
return Cr | python | {
"resource": ""
} |
q265336 | Ship.dimension | validation | def dimension(self, length, draught, beam, speed,
slenderness_coefficient, prismatic_coefficient):
"""
Assign values for the main dimension of a ship.
:param length: metres length of the vehicle
:param draught: metres draught of the vehicle
:param beam: metres beam of the vehicle
:param speed: m/s speed of the vehicle
:param slenderness_coefficient: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship,
∇ is displacement
:param prismatic_coefficient: Prismatic coefficient dimensionless :math:`∇/(L\cdot A_m)` where L is length of ship,
∇ is displacement Am is midsection area of the ship
"""
self.length = length
self.draught = draught
self.beam = beam
self.speed = speed
self.slenderness_coefficient = slenderness_coefficient
self.prismatic_coefficient = prismatic_coefficient
self.displacement = (self.length / self.slenderness_coefficient) ** 3
self.surface_area = 1.025 * (1.7 * self.length * self.draught +
self.displacement / self.draught) | python | {
"resource": ""
} |
q265337 | Ship.resistance | validation | def resistance(self):
"""
Return resistance of the vehicle.
:return: newton the resistance of the ship
"""
self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \
residual_resistance_coef(self.slenderness_coefficient,
self.prismatic_coefficient,
froude_number(self.speed, self.length))
RT = 1 / 2 * self.total_resistance_coef * 1025 * self.surface_area * self.speed ** 2
return RT | python | {
"resource": ""
} |
q265338 | Ship.maximum_deck_area | validation | def maximum_deck_area(self, water_plane_coef=0.88):
"""
Return the maximum deck area of the ship
:param water_plane_coef: optional water plane coefficient
:return: Area of the deck
"""
AD = self.beam * self.length * water_plane_coef
return AD | python | {
"resource": ""
} |
q265339 | Ship.prop_power | validation | def prop_power(self, propulsion_eff=0.7, sea_margin=0.2):
"""
Total propulsion power of the ship.
:param propulsion_eff: Shaft efficiency of the ship
:param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave
:return: Watts shaft propulsion power of the ship
"""
PP = (1 + sea_margin) * self.resistance() * self.speed/propulsion_eff
return PP | python | {
"resource": ""
} |
q265340 | API.configure | validation | def configure(self, url=None, token=None, test=False):
"""
Configure the api to use given url and token or to get them from the
Config.
"""
if url is None:
url = Config.get_value("url")
if token is None:
token = Config.get_value("token")
self.server_url = url
self.auth_header = {"Authorization": "Basic {0}".format(token)}
self.configured = True
if test:
self.test_connection()
Config.set("url", url)
Config.set("token", token) | python | {
"resource": ""
} |
q265341 | API.send_zip | validation | def send_zip(self, exercise, file, params):
"""
Send zipfile to TMC for given exercise
"""
resp = self.post(
exercise.return_url,
params=params,
files={
"submission[file]": ('submission.zip', file)
},
data={
"commit": "Submit"
}
)
return self._to_json(resp) | python | {
"resource": ""
} |
q265342 | API._make_url | validation | def _make_url(self, slug):
"""
Ensures that the request url is valid.
Sometimes we have URLs that the server gives that are preformatted,
sometimes we need to form our own.
"""
if slug.startswith("http"):
return slug
return "{0}{1}".format(self.server_url, slug) | python | {
"resource": ""
} |
q265343 | API._to_json | validation | def _to_json(self, resp):
"""
Extract json from a response.
Assumes response is valid otherwise.
Internal use only.
"""
try:
json = resp.json()
except ValueError as e:
reason = "TMC Server did not send valid JSON: {0}"
raise APIError(reason.format(repr(e)))
return json | python | {
"resource": ""
} |
q265344 | safe_joinall | validation | def safe_joinall(greenlets, timeout=None, raise_error=False):
"""
Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it
joins for.
"""
greenlets = list(greenlets)
try:
gevent.joinall(greenlets, timeout=timeout, raise_error=raise_error)
except gevent.GreenletExit:
[greenlet.kill() for greenlet in greenlets if not greenlet.ready()]
raise
return greenlets | python | {
"resource": ""
} |
q265345 | error | validation | def error(code: int, *args, **kwargs) -> HedgehogCommandError:
"""
Creates an error from the given code, and args and kwargs.
:param code: The acknowledgement code
:param args: Exception args
:param kwargs: Exception kwargs
:return: the error for the given acknowledgement code
"""
# TODO add proper error code
if code == FAILED_COMMAND and len(args) >= 1 and args[0] == "Emergency Shutdown activated":
return EmergencyShutdown(*args, **kwargs)
return _errors[code](*args, **kwargs) | python | {
"resource": ""
} |
q265346 | HedgehogCommandError.to_message | validation | def to_message(self):
"""
Creates an error Acknowledgement message.
The message's code and message are taken from this exception.
:return: the message representing this exception
"""
from .messages import ack
return ack.Acknowledgement(self.code, self.args[0] if len(self.args) > 0 else '') | python | {
"resource": ""
} |
q265347 | clean | validation | def clean(options, info):
"""Clean up extra files littering the source tree.
options.paved.clean.dirs: directories to search recursively
options.paved.clean.patterns: patterns to search for and remove
"""
info("Cleaning patterns %s", options.paved.clean.patterns)
for wd in options.paved.clean.dirs:
info("Cleaning in %s", wd)
for p in options.paved.clean.patterns:
for f in wd.walkfiles(p):
f.remove() | python | {
"resource": ""
} |
q265348 | printoptions | validation | def printoptions():
'''print paver options.
Prettified by json.
`long_description` is removed
'''
x = json.dumps(environment.options,
indent=4,
sort_keys=True,
skipkeys=True,
cls=MyEncoder)
print(x) | python | {
"resource": ""
} |
q265349 | CommSide.parse | validation | def parse(self, data: RawMessage) -> Message:
"""\
Parses a binary protobuf message into a Message object.
"""
try:
return self.receiver.parse(data)
except KeyError as err:
raise UnknownCommandError from err
except DecodeError as err:
raise UnknownCommandError(f"{err}") from err | python | {
"resource": ""
} |
q265350 | Node.add_child | validation | def add_child(self, **kwargs):
"""Creates a new ``Node`` based on the extending class and adds it as
a child to this ``Node``.
:param kwargs:
arguments for constructing the data object associated with this
``Node``
:returns:
extender of the ``Node`` class
"""
data_class = self.graph.data_content_type.model_class()
node = Node.objects.create(graph=self.graph)
data_class.objects.create(node=node, **kwargs)
node.parents.add(self)
self.children.add(node)
return node | python | {
"resource": ""
} |
q265351 | Node.ancestors | validation | def ancestors(self):
"""Returns a list of the ancestors of this node."""
ancestors = set([])
self._depth_ascend(self, ancestors)
try:
ancestors.remove(self)
except KeyError:
# we weren't ancestor of ourself, that's ok
pass
return list(ancestors) | python | {
"resource": ""
} |
q265352 | Node.ancestors_root | validation | def ancestors_root(self):
"""Returns a list of the ancestors of this node but does not pass the
root node, even if the root has parents due to cycles."""
if self.is_root():
return []
ancestors = set([])
self._depth_ascend(self, ancestors, True)
try:
ancestors.remove(self)
except KeyError:
# we weren't ancestor of ourself, that's ok
pass
return list(ancestors) | python | {
"resource": ""
} |
q265353 | Node.descendents | validation | def descendents(self):
"""Returns a list of descendents of this node."""
visited = set([])
self._depth_descend(self, visited)
try:
visited.remove(self)
except KeyError:
# we weren't descendent of ourself, that's ok
pass
return list(visited) | python | {
"resource": ""
} |
q265354 | Node.can_remove | validation | def can_remove(self):
"""Returns True if it is legal to remove this node and still leave the
graph as a single connected entity, not splitting it into a forest.
Only nodes with no children or those who cause a cycle can be deleted.
"""
if self.children.count() == 0:
return True
ancestors = set(self.ancestors_root())
children = set(self.children.all())
return children.issubset(ancestors) | python | {
"resource": ""
} |
q265355 | Node.prune | validation | def prune(self):
"""Removes the node and all descendents without looping back past the
root. Note this does not remove the associated data objects.
:returns:
list of :class:`BaseDataNode` subclassers associated with the
removed ``Node`` objects.
"""
targets = self.descendents_root()
try:
targets.remove(self.graph.root)
except ValueError:
# root wasn't in the target list, no problem
pass
results = [n.data for n in targets]
results.append(self.data)
for node in targets:
node.delete()
for parent in self.parents.all():
parent.children.remove(self)
self.delete()
return results | python | {
"resource": ""
} |
q265356 | Node.prune_list | validation | def prune_list(self):
"""Returns a list of nodes that would be removed if prune were called
on this element.
"""
targets = self.descendents_root()
try:
targets.remove(self.graph.root)
except ValueError:
# root wasn't in the target list, no problem
pass
targets.append(self)
return targets | python | {
"resource": ""
} |
q265357 | FlowNodeData._child_allowed | validation | def _child_allowed(self, child_rule):
"""Called to verify that the given rule can become a child of the
current node.
:raises AttributeError:
if the child is not allowed
"""
num_kids = self.node.children.count()
num_kids_allowed = len(self.rule.children)
if not self.rule.multiple_paths:
num_kids_allowed = 1
if num_kids >= num_kids_allowed:
raise AttributeError('Rule %s only allows %s children' % (
self.rule_name, self.num_kids_allowed))
# verify not a duplicate
for node in self.node.children.all():
if node.data.rule_label == child_rule.class_label:
raise AttributeError('Child rule already exists')
# check if the given rule is allowed as a child
if child_rule not in self.rule.children:
raise AttributeError('Rule %s is not a valid child of Rule %s' % (
child_rule.__name__, self.rule_name)) | python | {
"resource": ""
} |
q265358 | Locations.get_location | validation | def get_location(self, location_id):
"""
Returns location data.
http://dev.wheniwork.com/#get-existing-location
"""
url = "/2/locations/%s" % location_id
return self.location_from_json(self._get_resource(url)["location"]) | python | {
"resource": ""
} |
q265359 | Locations.get_locations | validation | def get_locations(self):
"""
Returns a list of locations.
http://dev.wheniwork.com/#listing-locations
"""
url = "/2/locations"
data = self._get_resource(url)
locations = []
for entry in data['locations']:
locations.append(self.location_from_json(entry))
return locations | python | {
"resource": ""
} |
q265360 | LinLsqFit.chisq_red | validation | def chisq_red(self):
"""
The reduced chi-square of the linear least squares
"""
if self._chisq_red is None:
self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False)
return self._chisq_red | python | {
"resource": ""
} |
q265361 | MapRouletteTask.create | validation | def create(self, server):
"""Create the task on the server"""
if len(self.geometries) == 0:
raise Exception('no geometries')
return server.post(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
'identifier': self.identifier}) | python | {
"resource": ""
} |
q265362 | MapRouletteTask.update | validation | def update(self, server):
"""Update existing task on the server"""
return server.put(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
'identifier': self.identifier}) | python | {
"resource": ""
} |
q265363 | MapRouletteTask.from_server | validation | def from_server(cls, server, slug, identifier):
"""Retrieve a task from the server"""
task = server.get(
'task',
replacements={
'slug': slug,
'identifier': identifier})
return cls(**task) | python | {
"resource": ""
} |
q265364 | formatter | validation | def formatter(color, s):
""" Formats a string with color """
if no_coloring:
return s
return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET) | python | {
"resource": ""
} |
q265365 | Users.get_user | validation | def get_user(self, user_id):
"""
Returns user profile data.
http://dev.wheniwork.com/#get-existing-user
"""
url = "/2/users/%s" % user_id
return self.user_from_json(self._get_resource(url)["user"]) | python | {
"resource": ""
} |
q265366 | Users.get_users | validation | def get_users(self, params={}):
"""
Returns a list of users.
http://dev.wheniwork.com/#listing-users
"""
param_list = [(k, params[k]) for k in sorted(params)]
url = "/2/users/?%s" % urlencode(param_list)
data = self._get_resource(url)
users = []
for entry in data["users"]:
users.append(self.user_from_json(entry))
return users | python | {
"resource": ""
} |
q265367 | _setVirtualEnv | validation | def _setVirtualEnv():
"""Attempt to set the virtualenv activate command, if it hasn't been specified.
"""
try:
activate = options.virtualenv.activate_cmd
except AttributeError:
activate = None
if activate is None:
virtualenv = path(os.environ.get('VIRTUAL_ENV', ''))
if not virtualenv:
virtualenv = options.paved.cwd
else:
virtualenv = path(virtualenv)
activate = virtualenv / 'bin' / 'activate'
if activate.exists():
info('Using default virtualenv at %s' % activate)
options.setdotted('virtualenv.activate_cmd', 'source %s' % activate) | python | {
"resource": ""
} |
q265368 | update | validation | def update(dst, src):
"""Recursively update the destination dict-like object with the source dict-like object.
Useful for merging options and Bunches together!
Based on:
http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1
"""
stack = [(dst, src)]
def isdict(o):
return hasattr(o, 'keys')
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if isdict(current_src[key]) and isdict(current_dst[key]):
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst | python | {
"resource": ""
} |
q265369 | pip_install | validation | def pip_install(*args):
"""Send the given arguments to `pip install`.
"""
download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else ''
shv('pip install %s%s' % (download_cache, ' '.join(args))) | python | {
"resource": ""
} |
q265370 | WhenIWork._get_resource | validation | def _get_resource(self, url, data_key=None):
"""
When I Work GET method. Return representation of the requested
resource.
"""
headers = {"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().getURL(url, headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | {
"resource": ""
} |
q265371 | WhenIWork._put_resource | validation | def _put_resource(self, url, body):
"""
When I Work PUT method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().putURL(url, headers, json.dumps(body))
if not (response.status == 200 or response.status == 201 or
response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | {
"resource": ""
} |
q265372 | WhenIWork._post_resource | validation | def _post_resource(self, url, body):
"""
When I Work POST method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().postURL(url, headers, json.dumps(body))
if not (response.status == 200 or response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | {
"resource": ""
} |
q265373 | WhenIWork._delete_resource | validation | def _delete_resource(self, url):
"""
When I Work DELETE method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().deleteURL(url, headers)
if not (response.status == 200 or response.status == 201 or
response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | {
"resource": ""
} |
q265374 | Shifts.create_shift | validation | def create_shift(self, params={}):
"""
Creates a shift
http://dev.wheniwork.com/#create/update-shift
"""
url = "/2/shifts/"
body = params
data = self._post_resource(url, body)
shift = self.shift_from_json(data["shift"])
return shift | python | {
"resource": ""
} |
q265375 | Shifts.delete_shifts | validation | def delete_shifts(self, shifts):
"""
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
"""
url = "/2/shifts/?%s" % urlencode(
{'ids': ",".join(str(s) for s in shifts)})
data = self._delete_resource(url)
return data | python | {
"resource": ""
} |
q265376 | Event.all_comments | validation | def all_comments(self):
"""
Returns combined list of event and update comments.
"""
ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='event')
update_ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='update')
update_ids = self.update_set.values_list('id', flat=True)
return Comment.objects.filter(
Q(content_type=ctype.id, object_pk=self.id) |
Q(content_type=update_ctype.id, object_pk__in=update_ids)
) | python | {
"resource": ""
} |
q265377 | Event.get_all_images | validation | def get_all_images(self):
"""
Returns chained list of event and update images.
"""
self_imgs = self.image_set.all()
update_ids = self.update_set.values_list('id', flat=True)
u_images = UpdateImage.objects.filter(update__id__in=update_ids)
return list(chain(self_imgs, u_images)) | python | {
"resource": ""
} |
q265378 | Event.get_all_images_count | validation | def get_all_images_count(self):
"""
Gets count of all images from both event and updates.
"""
self_imgs = self.image_set.count()
update_ids = self.update_set.values_list('id', flat=True)
u_images = UpdateImage.objects.filter(update__id__in=update_ids).count()
count = self_imgs + u_images
return count | python | {
"resource": ""
} |
q265379 | Event.get_top_assets | validation | def get_top_assets(self):
"""
Gets images and videos to populate top assets.
Map is built separately.
"""
images = self.get_all_images()[0:14]
video = []
if supports_video:
video = self.eventvideo_set.all()[0:10]
return list(chain(images, video))[0:15] | python | {
"resource": ""
} |
q265380 | Spinner.decorate | validation | def decorate(msg="", waitmsg="Please wait"):
"""
Decorated methods progress will be displayed to the user as a spinner.
Mostly for slower functions that do some network IO.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
spin = Spinner(msg=msg, waitmsg=waitmsg)
spin.start()
a = None
try:
a = func(*args, **kwargs)
except Exception as e:
spin.msg = "Something went wrong: "
spin.stop_spinning()
spin.join()
raise e
spin.stop_spinning()
spin.join()
return a
return wrapper
return decorator | python | {
"resource": ""
} |
q265381 | Menu.launch | validation | def launch(title, items, selected=None):
"""
Launches a new menu. Wraps curses nicely so exceptions won't screw with
the terminal too much.
"""
resp = {"code": -1, "done": False}
curses.wrapper(Menu, title, items, selected, resp)
return resp | python | {
"resource": ""
} |
q265382 | RankedModel.save | validation | def save(self, *args, **kwargs):
"""Overridden method that handles that re-ranking of objects and the
integrity of the ``rank`` field.
:param rerank:
Added parameter, if True will rerank other objects based on the
change in this save. Defaults to True.
"""
rerank = kwargs.pop('rerank', True)
if rerank:
if not self.id:
self._process_new_rank_obj()
elif self.rank == self._rank_at_load:
# nothing changed
pass
else:
self._process_moved_rank_obj()
super(RankedModel, self).save(*args, **kwargs) | python | {
"resource": ""
} |
q265383 | RankedModel.repack | validation | def repack(self):
"""Removes any blank ranks in the order."""
items = self.grouped_filter().order_by('rank').select_for_update()
for count, item in enumerate(items):
item.rank = count + 1
item.save(rerank=False) | python | {
"resource": ""
} |
q265384 | get_field_names | validation | def get_field_names(obj, ignore_auto=True, ignore_relations=True,
exclude=[]):
"""Returns the field names of a Django model object.
:param obj: the Django model class or object instance to get the fields
from
:param ignore_auto: ignore any fields of type AutoField. Defaults to True
:param ignore_relations: ignore any fields that involve relations such as
the ForeignKey or ManyToManyField
:param exclude: exclude anything in this list from the results
:returns: generator of found field names
"""
from django.db.models import (AutoField, ForeignKey, ManyToManyField,
ManyToOneRel, OneToOneField, OneToOneRel)
for field in obj._meta.get_fields():
if ignore_auto and isinstance(field, AutoField):
continue
if ignore_relations and (isinstance(field, ForeignKey) or
isinstance(field, ManyToManyField) or
isinstance(field, ManyToOneRel) or
isinstance(field, OneToOneRel) or
isinstance(field, OneToOneField)):
# optimization is killing coverage measure, have to put no-op that
# does something
a = 1; a
continue
if field.name in exclude:
continue
yield field.name | python | {
"resource": ""
} |
q265385 | register | validation | def register(
app):
"""
Register all HTTP error code error handlers
Currently, errors are handled by the JSON error handler.
"""
# Pick a handler based on the requested format. Currently we assume the
# caller wants JSON.
error_handler = json.http_exception_error_handler
@app.errorhandler(400)
def handle_bad_request(
exception):
return error_handler(exception)
@app.errorhandler(404)
def handle_not_found(
exception):
return error_handler(exception)
@app.errorhandler(405)
def handle_method_not_allowed(
exception):
return error_handler(exception)
@app.errorhandler(422)
def handle_unprocessable_entity(
exception):
return error_handler(exception)
@app.errorhandler(500)
def handle_internal_server_error(
exception):
return error_handler(exception) | python | {
"resource": ""
} |
q265386 | plot | validation | def plot(*args, ax=None, **kwargs):
"""
Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to :meth:`matplotlib.axis.Axis.plot`.
"""
if ax is None:
fig, ax = _setup_axes()
pl = ax.plot(*args, **kwargs)
if _np.shape(args)[0] > 1:
if type(args[1]) is not str:
min_x = min(args[0])
max_x = max(args[0])
ax.set_xlim((min_x, max_x))
return pl | python | {
"resource": ""
} |
q265387 | linspacestep | validation | def linspacestep(start, stop, step=1):
"""
Create a vector of values over an interval with a specified step size.
Parameters
----------
start : float
The beginning of the interval.
stop : float
The end of the interval.
step : float
The step size.
Returns
-------
vector : :class:`numpy.ndarray`
The vector of values.
"""
# Find an integer number of steps
numsteps = _np.int((stop-start)/step)
# Do a linspace over the new range
# that has the correct endpoint
return _np.linspace(start, start+step*numsteps, numsteps+1) | python | {
"resource": ""
} |
q265388 | selected_course | validation | def selected_course(func):
"""
Passes the selected course as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
course = Course.get_selected()
return func(course, *args, **kwargs)
return inner | python | {
"resource": ""
} |
q265389 | selected_exercise | validation | def selected_exercise(func):
"""
Passes the selected exercise as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
exercise = Exercise.get_selected()
return func(exercise, *args, **kwargs)
return inner | python | {
"resource": ""
} |
q265390 | false_exit | validation | def false_exit(func):
"""
If func returns False the program exits immediately.
"""
@wraps(func)
def inner(*args, **kwargs):
ret = func(*args, **kwargs)
if ret is False:
if "TMC_TESTING" in os.environ:
raise TMCExit()
else:
sys.exit(-1)
return ret
return inner | python | {
"resource": ""
} |
q265391 | configure | validation | def configure(server=None, username=None, password=None, tid=None, auto=False):
"""
Configure tmc.py to use your account.
"""
if not server and not username and not password and not tid:
if Config.has():
if not yn_prompt("Override old configuration", False):
return False
reset_db()
if not server:
while True:
server = input("Server url [https://tmc.mooc.fi/mooc/]: ").strip()
if len(server) == 0:
server = "https://tmc.mooc.fi/mooc/"
if not server.endswith('/'):
server += '/'
if not (server.startswith("http://")
or server.startswith("https://")):
ret = custom_prompt(
"Server should start with http:// or https://\n" +
"R: Retry, H: Assume http://, S: Assume https://",
["r", "h", "s"], "r")
if ret == "r":
continue
# Strip previous schema
if "://" in server:
server = server.split("://")[1]
if ret == "h":
server = "http://" + server
elif ret == "s":
server = "https://" + server
break
print("Using URL: '{0}'".format(server))
while True:
if not username:
username = input("Username: ")
if not password:
password = getpass("Password: ")
# wow, such security
token = b64encode(
bytes("{0}:{1}".format(username, password), encoding='utf-8')
).decode("utf-8")
try:
api.configure(url=server, token=token, test=True)
except APIError as e:
print(e)
if auto is False and yn_prompt("Retry authentication"):
username = password = None
continue
return False
break
if tid:
select(course=True, tid=tid, auto=auto)
else:
select(course=True) | python | {
"resource": ""
} |
q265392 | download | validation | def download(course, tid=None, dl_all=False, force=False, upgradejava=False,
update=False):
"""
Download the exercises from the server.
"""
def dl(id):
download_exercise(Exercise.get(Exercise.tid == id),
force=force,
update_java=upgradejava,
update=update)
if dl_all:
for exercise in list(course.exercises):
dl(exercise.tid)
elif tid is not None:
dl(int(tid))
else:
for exercise in list(course.exercises):
if not exercise.is_completed:
dl(exercise.tid)
else:
exercise.update_downloaded() | python | {
"resource": ""
} |
q265393 | skip | validation | def skip(course, num=1):
"""
Go to the next exercise.
"""
sel = None
try:
sel = Exercise.get_selected()
if sel.course.tid != course.tid:
sel = None
except NoExerciseSelected:
pass
if sel is None:
sel = course.exercises.first()
else:
try:
sel = Exercise.get(Exercise.id == sel.id + num)
except peewee.DoesNotExist:
print("There are no more exercises in this course.")
return False
sel.set_select()
list_all(single=sel) | python | {
"resource": ""
} |
q265394 | run | validation | def run(exercise, command):
"""
Spawns a process with `command path-of-exercise`
"""
Popen(['nohup', command, exercise.path()], stdout=DEVNULL, stderr=DEVNULL) | python | {
"resource": ""
} |
q265395 | select | validation | def select(course=False, tid=None, auto=False):
"""
Select a course or an exercise.
"""
if course:
update(course=True)
course = None
try:
course = Course.get_selected()
except NoCourseSelected:
pass
ret = {}
if not tid:
ret = Menu.launch("Select a course",
Course.select().execute(),
course)
else:
ret["item"] = Course.get(Course.tid == tid)
if "item" in ret:
ret["item"].set_select()
update()
if ret["item"].path == "":
select_a_path(auto=auto)
# Selects the first exercise in this course
skip()
return
else:
print("You can select the course with `tmc select --course`")
return
else:
selected = None
try:
selected = Exercise.get_selected()
except NoExerciseSelected:
pass
ret = {}
if not tid:
ret = Menu.launch("Select an exercise",
Course.get_selected().exercises,
selected)
else:
ret["item"] = Exercise.byid(tid)
if "item" in ret:
ret["item"].set_select()
print("Selected {}".format(ret["item"])) | python | {
"resource": ""
} |
q265396 | submit | validation | def submit(course, tid=None, pastebin=False, review=False):
"""
Submit the selected exercise to the server.
"""
if tid is not None:
return submit_exercise(Exercise.byid(tid),
pastebin=pastebin,
request_review=review)
else:
sel = Exercise.get_selected()
if not sel:
raise NoExerciseSelected()
return submit_exercise(sel, pastebin=pastebin, request_review=review) | python | {
"resource": ""
} |
q265397 | paste | validation | def paste(tid=None, review=False):
"""
Sends the selected exercise to the TMC pastebin.
"""
submit(pastebin=True, tid=tid, review=False) | python | {
"resource": ""
} |
q265398 | update | validation | def update(course=False):
"""
Update the data of courses and or exercises from server.
"""
if course:
with Spinner.context(msg="Updated course metadata.",
waitmsg="Updating course metadata."):
for course in api.get_courses():
old = None
try:
old = Course.get(Course.tid == course["id"])
except peewee.DoesNotExist:
old = None
if old:
old.details_url = course["details_url"]
old.save()
continue
Course.create(tid=course["id"], name=course["name"],
details_url=course["details_url"])
else:
selected = Course.get_selected()
# with Spinner.context(msg="Updated exercise metadata.",
# waitmsg="Updating exercise metadata."):
print("Updating exercise data.")
for exercise in api.get_exercises(selected):
old = None
try:
old = Exercise.byid(exercise["id"])
except peewee.DoesNotExist:
old = None
if old is not None:
old.name = exercise["name"]
old.course = selected.id
old.is_attempted = exercise["attempted"]
old.is_completed = exercise["completed"]
old.deadline = exercise.get("deadline")
old.is_downloaded = os.path.isdir(old.path())
old.return_url = exercise["return_url"]
old.zip_url = exercise["zip_url"]
old.submissions_url = exercise["exercise_submissions_url"]
old.save()
download_exercise(old, update=True)
else:
ex = Exercise.create(tid=exercise["id"],
name=exercise["name"],
course=selected.id,
is_attempted=exercise["attempted"],
is_completed=exercise["completed"],
deadline=exercise.get("deadline"),
return_url=exercise["return_url"],
zip_url=exercise["zip_url"],
submissions_url=exercise[("exercise_"
"submissions_"
"url")])
ex.is_downloaded = os.path.isdir(ex.path())
ex.save() | python | {
"resource": ""
} |
q265399 | determine_type | validation | def determine_type(x):
"""Determine the type of x"""
types = (int, float, str)
_type = filter(lambda a: is_type(a, x), types)[0]
return _type(x) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.