_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q11100
InstanceAssertionsMixin.assert_instance_created
train
def assert_instance_created(self, model_class, **kwargs): """ Checks if a model instance was created in the database. For example:: >>> with self.assert_instance_created(Article, slug='lorem-ipsum'):
python
{ "resource": "" }
q11101
InstanceAssertionsMixin.assert_instance_deleted
train
def assert_instance_deleted(self, model_class, **kwargs): """ Checks if the model instance was deleted from the database. For example:: >>> with self.assert_instance_deleted(Article, slug='lorem-ipsum'):
python
{ "resource": "" }
q11102
_split_into_mimetype_and_priority
train
def _split_into_mimetype_and_priority(x): """Split an accept header item into mimetype and priority. >>> _split_into_mimetype_and_priority('text/*') ('text/*', 1.0) >>> _split_into_mimetype_and_priority('application/json;q=0.5') ('application/json', 0.5) """ if ';' in x: content_type, priority = x.split(';')
python
{ "resource": "" }
q11103
_parse_and_sort_accept_header
train
def _parse_and_sort_accept_header(accept_header): """Parse and sort the accept header items. >>> _parse_and_sort_accept_header('application/json;q=0.5, text/*') [('text/*', 1.0), ('application/json', 0.5)] """
python
{ "resource": "" }
q11104
accept_best_match
train
def accept_best_match(accept_header, mimetypes): """Return a mimetype best matched the accept headers. >>> accept_best_match('application/json, text/html', ['application/json', 'text/plain']) 'application/json' >>> accept_best_match('application/json;q=0.5, text/*', ['application/json', 'text/plain']) 'text/plain' """
python
{ "resource": "" }
q11105
match_url_vars_type
train
def match_url_vars_type(url_vars, type_hints): """ Match types of url vars. >>> match_url_vars_type({'user_id': '1'}, {'user_id': int}) (True, {'user_id': 1}) >>> match_url_vars_type({'user_id': 'foo'}, {'user_id': int}) (False, {})
python
{ "resource": "" }
q11106
match_path
train
def match_path(rule, path): """ Match path. >>> match_path('/foo', '/foo') (True, {}) >>> match_path('/foo', '/bar') (False, {}) >>> match_path('/users/{user_id}', '/users/1') (True, {'user_id': '1'}) >>> match_path('/users/{user_id}', '/users/not-integer') (True, {'user_id': 'not-integer'}) """ split_rule = split_by_slash(rule) split_path = split_by_slash(path) url_vars = {}
python
{ "resource": "" }
q11107
Router.match
train
def match(self, path, method): """ Get callback and url_vars. >>> from kobin import Response >>> r = Router() >>> def view(user_id: int) -> Response: ... return Response(f'You are {user_id}') ... >>> r.add('/users/{user_id}', 'GET', 'user-detail', view) >>> callback, url_vars = r.match('/users/1', 'GET') >>> url_vars {'user_id': 1} >>> response = callback(**url_vars) >>> response.body [b'You are 1'] >>> callback, url_vars = r.match('/notfound', 'GET') Traceback (most recent call last): ... kobin.responses.HTTPError """ if path != '/': path = path.rstrip('/') method = method.upper() status = 404 for p, n, m in self.endpoints: matched, url_vars = match_path(p, path) if not matched: # path: not matched
python
{ "resource": "" }
q11108
Router.reverse
train
def reverse(self, name, **kwargs): """ Reverse routing. >>> from kobin import Response >>> r = Router() >>> def view(user_id: int) -> Response: ... return Response(f'You are
python
{ "resource": "" }
q11109
synchronized
train
def synchronized(fn): ''' A decorator which acquires a lock before attempting to execute its wrapped function. Releases the lock in a finally clause. :param fn: The function to wrap. ''' lock = threading.Lock() @functools.wraps(fn) def decorated(*args, **kwargs):
python
{ "resource": "" }
q11110
ARef.notify_watches
train
def notify_watches(self, oldval, newval): ''' Passes `oldval` and `newval` to each `fn` in the watches dictionary, passing along its respective key and the reference to this object. :param oldval: The old value which will be passed to the watch. :param newval: The new value which will be passed to the watch.
python
{ "resource": "" }
q11111
Atom.swap
train
def swap(self, fn, *args, **kwargs): ''' Given a mutator `fn`, calls `fn` with the atom's current state, `args`, and `kwargs`. The return value of this invocation becomes the new value of the atom. Returns the new value. :param fn: A function which will be passed the current state. Should return a new state. This absolutely *MUST NOT* mutate the reference to the current state! If it does, this function may loop indefinitely. :param \*args: Arguments to be passed to `fn`. :param \*\*kwargs: Keyword arguments to
python
{ "resource": "" }
q11112
Atom.reset
train
def reset(self, newval): ''' Resets the atom's value to `newval`, returning `newval`. :param newval: The
python
{ "resource": "" }
q11113
Atom.compare_and_set
train
def compare_and_set(self, oldval, newval): ''' Given `oldval` and `newval`, sets the atom's value to `newval` if and only if `oldval` is the atom's current value. Returns `True` upon success, otherwise `False`. :param oldval: The old expected value. :param newval: The new value which will be set if and only
python
{ "resource": "" }
q11114
find_conda
train
def find_conda(): """ Try to find conda on the system """ USER_HOME = os.path.expanduser('~') CONDA_HOME = os.environ.get('CONDA_HOME', '') PROGRAMDATA = os.environ.get('PROGRAMDATA', '') # Search common install paths and sys path search_paths = [ # Windows join(PROGRAMDATA, 'miniconda2', 'scripts'), join(PROGRAMDATA, 'miniconda3', 'scripts'), join(USER_HOME, 'miniconda2', 'scripts'), join(USER_HOME, 'miniconda3', 'scripts'), join(CONDA_HOME, 'scripts'), # Linux join(USER_HOME, 'miniconda2', 'bin'), join(USER_HOME, 'miniconda3', 'bin'), join(CONDA_HOME, 'bin'),
python
{ "resource": "" }
q11115
cp
train
def cp(src, dst): """ Like cp -R src dst """ print("[DEBUG]: -> copying {} to {}".format(src, dst)) if os.path.isfile(src): if not exists(dirname(dst)):
python
{ "resource": "" }
q11116
find_commands
train
def find_commands(cls): """ Finds commands by finding the subclasses of Command""" cmds = [] for subclass in cls.__subclasses__():
python
{ "resource": "" }
q11117
Link.link
train
def link(self, path, pkg): """ Link the package in the current directory. """ # Check if a custom linker exists to handle linking this package #for ep in pkg_resources.iter_entry_points(group="enaml_native_linker"): # if ep.name.replace("-", '_') == pkg.replace("-", '_'): # linker = ep.load() # print("Custom linker {} found for '{}'. Linking...".format( # linker, pkg)) # if linker(self.ctx, path): # return
python
{ "resource": "" }
q11118
Link.is_app_linked
train
def is_app_linked(source, pkg, java_package): """ Returns true if the compile project line exists exists in the file """ for line in source.split("\n"):
python
{ "resource": "" }
q11119
Unlink.run
train
def run(self, args=None): """ The name IS required here. """ print(Colors.BLUE+"[INFO] Unlinking {}...".format( args.names)+Colors.RESET)
python
{ "resource": "" }
q11120
Unlink.unlink
train
def unlink(self, path, pkg): """ Unlink the package in the current directory. """ #: Check if a custom unlinker exists to handle unlinking this package for ep in pkg_resources.iter_entry_points( group="enaml_native_unlinker"): if ep.name.replace("-", '_') == pkg.replace("-", '_'): unlinker = ep.load() print("Custom unlinker {} found for '{}'. " "Unlinking...".format(unlinker, pkg)) if unlinker(self.ctx, path):
python
{ "resource": "" }
q11121
Server.run_tornado
train
def run_tornado(self, args): """ Tornado dev server implementation """ server = self import tornado.ioloop import tornado.web import tornado.websocket ioloop = tornado.ioloop.IOLoop.current() class DevWebSocketHandler(tornado.websocket.WebSocketHandler): def open(self): super(DevWebSocketHandler, self).open() server.on_open(self) def on_message(self, message): server.on_message(self, message) def on_close(self): super(DevWebSocketHandler, self).on_close() server.on_close(self)
python
{ "resource": "" }
q11122
Server.run_twisted
train
def run_twisted(self, args): """ Twisted dev server implementation """ server = self from twisted.internet import reactor from twisted.web import resource from twisted.web.static import File from twisted.web.server import Site from autobahn.twisted.websocket import (WebSocketServerFactory, WebSocketServerProtocol) from autobahn.twisted.resource import WebSocketResource class DevWebSocketHandler(WebSocketServerProtocol): def onConnect(self, request): super(DevWebSocketHandler, self).onConnect(request) server.on_open(self) def onMessage(self, payload, isBinary): server.on_message(self, payload) def onClose(self, wasClean, code, reason): super(DevWebSocketHandler,self).onClose(wasClean, code, reason) server.on_close(self) def write_message(self, message, binary=False): self.sendMessage(message, binary) #: Set the call later method server.call_later = reactor.callLater
python
{ "resource": "" }
q11123
Server.on_message
train
def on_message(self, handler, msg): """ In remote debugging mode this simply acts as a forwarding proxy for the two clients. """ if self.remote_debugging: #: Forward to other clients
python
{ "resource": "" }
q11124
Server.send_message
train
def send_message(self, msg): """ Send a message to the client. This should not be used in remote debugging mode. """ if not self.handlers:
python
{ "resource": "" }
q11125
EnamlNativeCli._default_commands
train
def _default_commands(self): """ Build the list of CLI commands by finding subclasses of the Command class Also allows commands to be installed using the "enaml_native_command" entry point. This entry point should return a Command subclass """ commands = [c() for c in find_commands(Command)] #: Get commands installed via entry points for ep in pkg_resources.iter_entry_points( group="enaml_native_command"): c = ep.load() if
python
{ "resource": "" }
q11126
EnamlNativeCli._default_ctx
train
def _default_ctx(self): """ Return the package config or context and normalize some of the values """ if not self.in_app_directory: print("Warning: {} does not exist. Using the default.".format( self.package)) ctx = {} else: with open(self.package) as f: ctx = dict(yaml.load(f, Loader=yaml.RoundTripLoader)) if self.in_app_directory: # Update the env for each platform excluded = list(ctx.get('excluded', [])) for env in [ctx['ios'], ctx['android']]:
python
{ "resource": "" }
q11127
EnamlNativeCli._default_parser
train
def _default_parser(self): """ Generate a parser using the command list """ parser = ArgumentParser(prog='enaml-native') #: Build commands by name cmds = {c.title: c for c in self.commands} #: Build parser, prepare commands
python
{ "resource": "" }
q11128
EnamlNativeCli.start
train
def start(self): """ Run the commands""" self.check_dependencies() self.args = self.parser.parse_args() # Python 3 doesn't set the cmd if no args are given if not hasattr(self.args, 'cmd'): self.parser.print_help() return cmd = self.args.cmd try: if cmd.app_dir_required and not self.in_app_directory: raise EnvironmentError(
python
{ "resource": "" }
q11129
find_data
train
def find_data(folder): """ Include everything in the folder """ for (path, directories, filenames) in os.walk(folder):
python
{ "resource": "" }
q11130
generate
train
def generate(number=4, choice=SystemRandom().choice, words=words, joiner=" "): """ Generate a random passphrase from the GSL. """
python
{ "resource": "" }
q11131
Trk.write_meta_info
train
def write_meta_info(self, byte1, byte2, data): "Worker method for writing meta info" write_varlen(self.data, 0) # tick write_byte(self.data, byte1)
python
{ "resource": "" }
q11132
how_long
train
def how_long(length=4, choices=len(words), speed=1000 * 1000 * 1000 * 1000, optimism=2): """ How long might it take to guess a password? @param length: the number of words that we're going to choose. @type length: L{int} @param choice: the number of words we might choose between. @type choice: L{int} @param speed: the speed of our hypothetical password guesser, in guesses per second. @type speed: L{int}
python
{ "resource": "" }
q11133
SeqBase.zip
train
def zip(self, other): """ zips two sequences unifying the corresponding points. """
python
{ "resource": "" }
q11134
SeqBase.display
train
def display(self, format="png"): """ Return an object that can be used to display this sequence. This is used for IPython Notebook. :param format: "png" or "svg" """ from sebastian.core.transforms import lilypond seq = HSeq(self) | lilypond() lily_output = write_lilypond.lily_format(seq) if not lily_output.strip(): #In the case of empty lily outputs, return self to get a textual display return self if format == "png": suffix = ".preview.png" args = ["lilypond", "--png", "-dno-print-pages", "-dpreview"] elif format == "svg":
python
{ "resource": "" }
q11135
HSeq.append
train
def append(self, point): """ appends a copy of the given point to this sequence """
python
{ "resource": "" }
q11136
HSeq.repeat
train
def repeat(self, count): """ repeat sequence given number of times to produce a new
python
{ "resource": "" }
q11137
arpeggio
train
def arpeggio(pattern, point): """ turns each subsequence into an arpeggio matching the given ``pattern``. """
python
{ "resource": "" }
q11138
fill
train
def fill(duration, point): """ fills the subsequence of the point with repetitions of its subsequence and sets the ``duration`` of each point. """ point['sequence'] =
python
{ "resource": "" }
q11139
expand
train
def expand(sequence): """ expands a tree of sequences into a single, flat sequence, recursively. """ expanse = [] for point in sequence: if 'sequence' in point:
python
{ "resource": "" }
q11140
debug
train
def debug(sequence): """ adds information to the sequence for better debugging, currently only an index property on each point in
python
{ "resource": "" }
q11141
transform_sequence
train
def transform_sequence(f): """ A decorator to take a function operating on a point and turn it into a function returning a callable operating on a sequence. The functions passed to this decorator must define a kwarg called "point", or have point be the last positional argument """ @wraps(f) def wrapper(*args, **kwargs): #The arguments here are the arguments
python
{ "resource": "" }
q11142
subseq
train
def subseq(start_offset=0, end_offset=None): """ Return a portion of the input sequence """ def _(sequence):
python
{ "resource": "" }
q11143
lilypond
train
def lilypond(point): """ Generate lilypond representation for a point """ #If lilypond already computed, leave as is if "lilypond" in point: return point #Defaults: pitch_string = "" octave_string = "" duration_string = "" preamble = "" dynamic_string = "" if "pitch" in point: octave = point["octave"] pitch = point["pitch"] if octave > 4: octave_string = "'" * (octave - 4) elif octave < 4: octave_string = "," * (4 - octave) else: octave_string = "" m = modifiers(pitch) if m > 0: modifier_string = "is" * m elif m < 0: modifier_string = "es" * -m else: modifier_string = "" pitch_string = letter(pitch).lower() + modifier_string if DURATION_64 in point: duration = point[DURATION_64] if duration > 0: if duration % 3 == 0: # dotted note duration_string = str(192 // (2 * duration)) + "." else:
python
{ "resource": "" }
q11144
dynamics
train
def dynamics(start, end=None): """ Apply dynamics to a sequence. If end is specified, it will crescendo or diminuendo linearly from start to end dynamics. You can pass any of these strings as dynamic markers: ['pppppp', 'ppppp', 'pppp', 'ppp', 'pp', 'p', 'mp', 'mf', 'f', 'ff', 'fff', ''ffff] Args: start: beginning dynamic marker, if no end is specified all notes will get this marker end: ending dynamic marker, if unspecified the entire sequence will get the start dynamic marker Example usage: s1 | dynamics('p') # play a sequence in piano s2 | dynamics('p', 'ff') # crescendo from p to ff s3 | dynamics('ff', 'p') # diminuendo from ff to p """ def _(sequence): if start in _dynamic_markers_to_velocity: start_velocity = _dynamic_markers_to_velocity[start] start_marker = start else: raise ValueError("Unknown start dynamic: %s, must be in %s" % (start, _dynamic_markers_to_velocity.keys())) if end is None: end_velocity = start_velocity end_marker = start_marker elif end in _dynamic_markers_to_velocity: end_velocity = _dynamic_markers_to_velocity[end] end_marker = end else: raise ValueError("Unknown end dynamic: %s, must be in
python
{ "resource": "" }
q11145
query_revisions_by_revids
train
def query_revisions_by_revids(session, revids, **params): """ Gets a set of revisions by their IDs by repeatedly querying in batches. If an ID cannot be found, it is ignored. """ doc = session.get(action='query', prop='revisions', revids=revids, **params) for page_doc in doc['query'].get('pages', {}).values():
python
{ "resource": "" }
q11146
load_metafile
train
def load_metafile(filepath): """ Load a metadata file from the filesystem """ try: with open(filepath, 'r', encoding='utf-8') as file: return email.message_from_file(file) except FileNotFoundError: logger.warning("Category
python
{ "resource": "" }
q11147
Category.name
train
def name(self): """ Get the display name of the category """ if self._meta and self._meta.get('name'): # get it from the meta file return self._meta.get('name')
python
{ "resource": "" }
q11148
Category.description
train
def description(self): """ Get the textual description of the category """ if self._meta and
python
{ "resource": "" }
q11149
Category.breadcrumb
train
def breadcrumb(self): """ Get the category hierarchy leading up to this category, including root and self. For example, path/to/long/category will return a list containing Category('path'), Category('path/to'), and Category('path/to/long'). """ ret = []
python
{ "resource": "" }
q11150
Category.sort_name
train
def sort_name(self): """ Get the sorting name of this category """ if self._record and self._record.sort_name:
python
{ "resource": "" }
q11151
Category.parent
train
def parent(self): """ Get the parent category """ if self.path: return
python
{ "resource": "" }
q11152
Category._get_subcats
train
def _get_subcats(self, recurse=False): """ Get the subcategories of this category recurse -- whether to include their subcategories as well """ if recurse: # No need to filter return sorted([Category(e) for e in self._subcats_recursive], key=lambda c: c.sort_breadcrumb) # get all the subcategories, with only the first subdir added # number of path components to ingest parts = len(self.path.split('/')) + 1 if self.path else 1 # convert the subcategories into separated pathlists with only 'parts' # parts
python
{ "resource": "" }
q11153
Category._first
train
def _first(self, **spec): """ Get the earliest entry in this category, optionally including subcategories """ for record in self._entries(spec).order_by(model.Entry.local_date,
python
{ "resource": "" }
q11154
Category._last
train
def _last(self, **spec): """ Get the latest entry in this category, optionally including subcategories """ for record in self._entries(spec).order_by(orm.desc(model.Entry.local_date),
python
{ "resource": "" }
q11155
static_url
train
def static_url(path, absolute=False): """ Shorthand for returning a URL for the requested static file. Arguments: path -- the path to the file (relative to the
python
{ "resource": "" }
q11156
make_tag
train
def make_tag(name, attrs, start_end=False): """ Build an HTML tag from the given name and attributes. Arguments: name -- the name of the tag (p, div, etc.) attrs -- a dict of attributes to apply to the tag start_end -- whether this tag should be self-closing """ text = '<' + name if isinstance(attrs, dict):
python
{ "resource": "" }
q11157
file_fingerprint
train
def file_fingerprint(fullpath): """ Get a metadata fingerprint for a file """ stat = os.stat(fullpath)
python
{ "resource": "" }
q11158
remap_args
train
def remap_args(input_args, remap): """ Generate a new argument list by remapping keys. The 'remap' dict maps from destination key -> priority list of source keys """ out_args = input_args for dest_key, src_keys in remap.items(): remap_value = None if isinstance(src_keys, str): src_keys = [src_keys] for key in src_keys: if key in input_args:
python
{ "resource": "" }
q11159
remap_link_target
train
def remap_link_target(path, absolute=False): """ remap a link target to a static URL if it's prefixed with @ """ if path.startswith('@'): # static resource return static_url(path[1:], absolute=absolute) if absolute:
python
{ "resource": "" }
q11160
get_category
train
def get_category(filename): """ Get a default category name from a filename in a cross-platform manner """
python
{ "resource": "" }
q11161
CallableProxy._default
train
def _default(self): """ Get the default function return """ if self._default_args: return self._func( *self._default_args,
python
{ "resource": "" }
q11162
setup
train
def setup(): """ Set up the database """ try: db.bind(**config.database_config) except OSError: # Attempted to connect to a file-based database where the file didn't # exist db.bind(**config.database_config, create_db=True) rebuild = True try: db.generate_mapping(create_tables=True) with orm.db_session: version = GlobalConfig.get(key='schema_version') if version and version.int_value != SCHEMA_VERSION: logger.info("Existing database has schema version %d", version.int_value) else: rebuild = False except: # pylint:disable=bare-except logger.exception("Error mapping schema") if rebuild: logger.info("Rebuilding schema") try: db.drop_all_tables(with_all_data=True) db.create_tables() except:
python
{ "resource": "" }
q11163
Entry.visible
train
def visible(self): """ Returns true if the entry should be viewable """ return self.status
python
{ "resource": "" }
q11164
extract_card
train
def extract_card(text, config, image_search_path): """ Extract card data based on the provided texts. """ card = CardData() parser = CardParser(card, config, image_search_path)
python
{ "resource": "" }
q11165
CardParser.paragraph
train
def paragraph(self, content): """ Turn the first paragraph of text into the summary
python
{ "resource": "" }
q11166
CardParser.image
train
def image(self, raw_url, title='', alt=''): ''' extract the images ''' max_images = self._config.get('count') if max_images is not None and len(self._out.images) >= max_images: # We already have enough images, so bail out return ' ' image_specs = raw_url
python
{ "resource": "" }
q11167
CardParser._render_image
train
def _render_image(self, spec, alt=''): """ Given an image spec, try to turn it into a card image per the configuration """ # pylint: disable=unused-argument try: path, image_args, _ = image.parse_image_spec(spec) except Exception as err: #
python
{ "resource": "" }
q11168
publ
train
def publ(name, cfg): """ Create a Flask app and configure it for use with Publ """ config.setup(cfg) app = _PublApp(name, template_folder=config.template_folder, static_folder=config.static_folder, static_url_path=config.static_url_path) for route in [ '/', '/<path:category>/', '/<template>', '/<path:category>/<template>', ]: app.add_url_rule(route, 'category', rendering.render_category) for route in [ '/<int:entry_id>', '/<int:entry_id>-', '/<int:entry_id>-<slug_text>', '/<path:category>/<int:entry_id>', '/<path:category>/<int:entry_id>-', '/<path:category>/<int:entry_id>-<slug_text>', ]: app.add_url_rule(route, 'entry', rendering.render_entry) app.add_url_rule('/<path:path>.PUBL_PATHALIAS', 'path_alias', rendering.render_path_alias) app.add_url_rule('/_async/<path:filename>', 'async', image.get_async) app.add_url_rule('/_', 'chit', rendering.render_transparent_chit) app.add_url_rule('/_file/<path:filename>', 'asset', rendering.retrieve_asset) app.config['TRAP_HTTP_EXCEPTIONS'] = True app.register_error_handler( werkzeug.exceptions.HTTPException, rendering.render_exception) app.jinja_env.globals.update( # pylint: disable=no-member get_view=view.get_view, arrow=arrow, static=utils.static_url, get_template=rendering.get_template ) caching.init_app(app) maint = maintenance.Maintenance() if config.index_rescan_interval:
python
{ "resource": "" }
q11169
startup
train
def startup(): """ Startup routine for initiating the content indexer """ model.setup()
python
{ "resource": "" }
q11170
set_cache_expiry
train
def set_cache_expiry(response): """ Set the cache control headers """ if response.cache_control.max_age is None and 'CACHE_DEFAULT_TIMEOUT' in config.cache:
python
{ "resource": "" }
q11171
_PublApp.path_alias_regex
train
def path_alias_regex(self, regex): """ A decorator that adds a path-alias regular expression; calls add_path_regex """ def decorator(func):
python
{ "resource": "" }
q11172
_PublApp.get_path_regex
train
def get_path_regex(self, path): """ Evaluate the registered path-alias regular expressions """ for regex, func in self._regex_map:
python
{ "resource": "" }
q11173
guess_title
train
def guess_title(basename): """ Attempt to guess the title from the filename """ base, _
python
{ "resource": "" }
q11174
get_entry_id
train
def get_entry_id(entry, fullpath, assign_id): """ Get or generate an entry ID for an entry """ warn_duplicate = False if 'Entry-ID' in entry: entry_id = int(entry['Entry-ID']) else: entry_id = None # See if we've inadvertently duplicated an entry ID if entry_id: try: other_entry = model.Entry.get(id=entry_id) if (other_entry and os.path.isfile(other_entry.file_path) and not os.path.samefile(other_entry.file_path, fullpath)): warn_duplicate = entry_id entry_id = None except FileNotFoundError: # the other file doesn't exist, so just let it go pass # Do we need to assign a new ID? if not entry_id and not assign_id: # We're not assigning IDs yet return None if not entry_id: # See if we already have an entry with this file path by_filepath = model.Entry.get(file_path=fullpath) if by_filepath: entry_id = by_filepath.id if not entry_id: # We still don't have an ID; generate one pseudo-randomly, based on the # entry file path. This approach averages around 0.25 collisions per ID # generated while keeping the entry ID reasonably short. In general,
python
{ "resource": "" }
q11175
save_file
train
def save_file(fullpath, entry): """ Save a message file out, without mangling the headers """ with tempfile.NamedTemporaryFile('w', delete=False) as file: tmpfile = file.name # we can't just use file.write(str(entry)) because otherwise the # headers "helpfully" do MIME encoding normalization. # str(val) is necessary to get around email.header's encoding
python
{ "resource": "" }
q11176
expire_file
train
def expire_file(filepath): """ Expire a record for a missing file """ load_message.cache_clear() orm.delete(pa for pa in model.PathAlias if pa.entry.file_path == filepath)
python
{ "resource": "" }
q11177
expire_record
train
def expire_record(record): """ Expire a record for a missing entry """ load_message.cache_clear() # This entry no longer exists so delete it, and anything that references it # SQLite doesn't support cascading deletes so let's
python
{ "resource": "" }
q11178
Entry._link
train
def _link(self, *args, **kwargs): """ Returns a link, potentially pre-redirected """ if self._record.redirect_url: return links.resolve(self._record.redirect_url,
python
{ "resource": "" }
q11179
Entry._permalink
train
def _permalink(self, absolute=False, expand=True, **kwargs): """ Returns a canonical URL for the item """ return flask.url_for('entry', entry_id=self._record.id,
python
{ "resource": "" }
q11180
Entry.search_path
train
def search_path(self): """ The relative image search path for this entry """
python
{ "resource": "" }
q11181
Entry._message
train
def _message(self): """ get the message payload """ filepath = self._record.file_path try: return load_message(filepath) except FileNotFoundError:
python
{ "resource": "" }
q11182
Entry.body
train
def body(self): """ Get the above-the-fold entry body text """ body, _, is_markdown = self._entry_content return TrueCallableProxy(
python
{ "resource": "" }
q11183
Entry.more
train
def more(self): """ Get the below-the-fold entry body text """ _, more, is_markdown = self._entry_content return TrueCallableProxy(
python
{ "resource": "" }
q11184
Entry.card
train
def card(self): """ Get the entry's OpenGraph card """ body, more, is_markdown = self._entry_content return TrueCallableProxy(
python
{ "resource": "" }
q11185
Entry.summary
train
def summary(self): """ Get the entry's summary text """ if self.get('Summary'): return self.get('Summary') body, more, is_markdown = self._entry_content
python
{ "resource": "" }
q11186
Entry.last_modified
train
def last_modified(self): """ Get the date of last file modification """ if self.get('Last-Modified'):
python
{ "resource": "" }
q11187
Entry._get_markup
train
def _get_markup(self, text, is_markdown, **kwargs): """ get the rendered markup for an entry is_markdown -- whether the entry is formatted as Markdown kwargs -- parameters to pass to the Markdown processor """ if is_markdown: return markdown.to_html( text, config=kwargs,
python
{ "resource": "" }
q11188
Entry._get_summary
train
def _get_summary(self, text, **kwargs): """ Render out just the summary """ card
python
{ "resource": "" }
q11189
Entry._previous
train
def _previous(self, **kwargs): """ Get the previous item in any particular category """ spec = self._pagination_default_spec(kwargs) spec.update(kwargs) query = queries.build_query(spec) query = queries.where_before_entry(query, self._record)
python
{ "resource": "" }
q11190
Entry._next
train
def _next(self, **kwargs): """ Get the next item in any particular category """ spec = self._pagination_default_spec(kwargs) spec.update(kwargs) query = queries.build_query(spec) query = queries.where_after_entry(query, self._record)
python
{ "resource": "" }
q11191
setup
train
def setup(cfg): """ set up the global configuration from an object """ # copy the necessary configuration values
python
{ "resource": "" }
q11192
mime_type
train
def mime_type(template): """ infer the content-type from the extension """ _, ext = os.path.splitext(template.filename)
python
{ "resource": "" }
q11193
map_template
train
def map_template(category, template_list): """ Given a file path and an acceptable list of templates, return the best-matching template's path relative to the configured template directory. Arguments: category -- The path to map template_list -- A template to look up (as a string), or a list of templates. """ if isinstance(template_list, str): template_list = [template_list] for template in template_list: path = os.path.normpath(category) while path is not None: for extension in ['', '.html', '.htm', '.xml', '.json']: candidate =
python
{ "resource": "" }
q11194
get_template
train
def get_template(template, relation): """ Given an entry or a category, return the path to a related template """ if isinstance(relation, Entry):
python
{ "resource": "" }
q11195
image_function
train
def image_function(template=None, entry=None, category=None): """ Get a function that gets an image """ path = [] if entry is not None: path += entry.search_path if category is not None: # Since the category might be different than the entry's category we add # this too path += category.search_path
python
{ "resource": "" }
q11196
render_publ_template
train
def render_publ_template(template, **kwargs): """ Render out a template, providing the image function based on the args. Returns tuple of (rendered text, etag) """ text = render_template( template.filename, template=template, image=image_function(
python
{ "resource": "" }
q11197
render_error
train
def render_error(category, error_message, error_codes, exception=None): """ Render an error page. Arguments: category -- The category of the request error_message -- The message to provide to the error template error_codes -- The applicable HTTP error code(s). Will usually be an integer or a list of integers; the HTTP error response will always be the first error code in the list, and the others are alternates for looking up the error template to use. exception -- Any exception that led to this error page """ if isinstance(error_codes, int): error_codes = [error_codes] error_code = error_codes[0] template_list = [str(code) for code in error_codes] template_list.append(str(int(error_code / 100) * 100)) template_list.append('error')
python
{ "resource": "" }
q11198
render_exception
train
def render_exception(error): """ Catch-all renderer for the top-level exception handler """ _, _, category = str.partition(request.path, '/') qsize = index.queue_length() if isinstance(error, http_error.NotFound) and qsize: response = flask.make_response(render_error( category, "Site reindex in progress (qs={})".format(qsize), 503))
python
{ "resource": "" }
q11199
render_category
train
def render_category(category='', template=None): """ Render a category page. Arguments: category -- The category to render template -- The template to render it with """ # pylint:disable=too-many-return-statements # See if this is an aliased path redir = get_redirect() if redir: return redir # Forbidden template types if template and template.startswith('_'): raise http_error.Forbidden("Template is private") if template in ['entry', 'error']: raise http_error.BadRequest("Invalid view requested") if category: # See if there's any entries for the view... if not orm.select(e for e in model.Entry if e.category == category or e.category.startswith(category + '/')): raise http_error.NotFound("No such category") if not template: template = Category(category).get('Index-Template') or 'index' tmpl = map_template(category, template) if not tmpl: # this might actually be a malformed category URL test_path = '/'.join((category, template)) if category else template logger.debug("Checking for malformed category %s", test_path) record = orm.select( e for e in model.Entry if e.category == test_path).exists() if record:
python
{ "resource": "" }