_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 ...
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...
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." ...
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(rul...
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_wid...
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 = [] ...
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 ...
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 ...
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("...
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....
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.mino...
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 \ ...
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_sc...
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...
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 reque...
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_j...
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/ ....
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 opti...
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)...
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_Seawat...
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 ...
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 displace...
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 b...
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 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 pow...
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={ "submission[file]": ('submission.zip', file) }, data={ ...
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_...
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}" ...
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_erro...
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 """ # TOD...
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 ...
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.d...
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: r...
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``...
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(...
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: ...
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(vis...
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: r...
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. """ targ...
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 ...
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) ...
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_j...
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, ...
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 = [] ...
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)] ...
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().getU...
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, hea...
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, ...
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, ...
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...
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_i...
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() coun...
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, vid...
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): ...
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. """ ...
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 :pa...
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...
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...
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 --...
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.e...
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 Fa...
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=u...
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: tr...
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: ...
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. """ 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 ...
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": "" }