_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q265300 | LatexFixer._str_replacement | validation | def _str_replacement(self, target, replacement):
"""Replace target with replacement"""
| python | {
"resource": ""
} |
q265301 | LatexFixer._regex_replacement | validation | def _regex_replacement(self, target, replacement):
"""Regex substitute target with replacement"""
| 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 | 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 | 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
''' | 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)
| 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 | 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 | 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',
| 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',
| 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:
| 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"], | 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 | 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 | 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 | 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 = ""
| 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':
| 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)
| python | {
"resource": ""
} |
q265318 | Tag.with_revision | validation | def with_revision(self, label, number):
"""
Returns a Tag with a given revision
"""
| 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 \ | 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
| 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 | 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 | python | {
"resource": ""
} |
q265323 | MapRouletteChallenge.create | validation | def create(self, server):
"""Create the challenge on the server"""
return server.post(
'challenge_admin',
| python | {
"resource": ""
} |
q265324 | MapRouletteChallenge.update | validation | def update(self, server):
"""Update existing challenge on the server"""
return server.put(
'challenge_admin',
| python | {
"resource": ""
} |
q265325 | MapRouletteChallenge.exists | validation | def exists(self, server):
"""Check if a challenge exists on the server"""
try:
server.get(
| python | {
"resource": ""
} |
q265326 | Positions.get_position | validation | def get_position(self, position_id):
"""
Returns position data.
http://dev.wheniwork.com/#get-existing-position
"""
url | 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 = []
| 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
| 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:
| 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
| 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), | 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()
| 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 | 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
| 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
| 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
""" | 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,
| 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 | 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
| 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")
| 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={
| 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.
"""
| 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()
| 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. | 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 | 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.
| 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 | python | {
"resource": ""
} |
q265348 | printoptions | validation | def printoptions():
'''print paver options.
Prettified by json.
`long_description` is removed
'''
x = json.dumps(environment.options,
indent=4,
| 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:
| 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
| 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:
| 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, | 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:
| 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:
| 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
| 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:
| 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():
| python | {
"resource": ""
} |
q265358 | Locations.get_location | validation | def get_location(self, location_id):
"""
Returns location data.
http://dev.wheniwork.com/#get-existing-location
"""
url | 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 = []
| 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 | 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(), | 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={
| 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={
| python | {
"resource": ""
} |
q265364 | formatter | validation | def formatter(color, s):
""" Formats a string with color """
if no_coloring: | 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 | 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 | 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', ''))
| 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:
| 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 | 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 | 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:
| 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))
| 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 | 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
| python | {
"resource": ""
} |
q265375 | Shifts.delete_shifts | validation | def delete_shifts(self, shifts):
"""
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
| 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)
| 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)
| 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)
| 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:
| 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:
| 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 | 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()
| 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 | 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
| 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(
| 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
| 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.
| 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):
| 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):
| 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" | 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:
| 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):
| 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:
| python | {
"resource": ""
} |
q265394 | run | validation | def run(exercise, command):
"""
Spawns a process with `command path-of-exercise`
"""
| 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:
| 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:
| python | {
"resource": ""
} |
q265397 | paste | validation | def paste(tid=None, review=False):
"""
Sends the selected exercise to the TMC pastebin.
| 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)
| python | {
"resource": ""
} |
q265399 | determine_type | validation | def determine_type(x):
"""Determine the type of x"""
types = (int, float, str)
_type | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.