_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q24200 | Map._draw_lines_internal | train | def _draw_lines_internal(self, coords, colour, bg):
"""Helper to draw lines connecting a set of nodes that are scaled for the Screen."""
for i, (x, y) in enumerate(coords):
if i == 0:
| python | {
"resource": ""
} |
q24201 | Map._draw_polygons | train | def _draw_polygons(self, feature, bg, colour, extent, polygons, xo, yo):
"""Draw a set of polygons from a vector tile."""
coords = []
for polygon in polygons:
coords.append([self._scale_coords(x, y, extent, xo, yo) for x, y in polygon])
# Polygons are expensive to draw and th... | python | {
"resource": ""
} |
q24202 | Map._draw_lines | train | def _draw_lines(self, bg, colour, extent, line, xo, yo):
"""Draw a set of lines from a vector tile.""" | python | {
"resource": ""
} |
q24203 | Map._draw_feature | train | def _draw_feature(self, feature, extent, colour, bg, xo, yo):
"""Draw a single feature from a layer in a vector tile."""
geometry = feature["geometry"]
if geometry["type"] == "Polygon":
self._draw_polygons(feature, bg, colour, extent, geometry["coordinates"], xo, yo)
elif fea... | python | {
"resource": ""
} |
q24204 | Map._draw_tile_layer | train | def _draw_tile_layer(self, tile, layer_name, c_filters, colour, t_filters, x, y, bg):
"""Draw the visible geometry in the specified map tile."""
# Don't bother rendering if the tile is not visible
left = (x + self._screen.width // 4) * 2
top = y + self._screen.height // 2
if (lef... | python | {
"resource": ""
} |
q24205 | Map._draw_satellite_tile | train | def _draw_satellite_tile(self, tile, x, y):
"""Draw a satellite image tile to screen."""
image, colours = tile.rendered_text
for (i, line) in enumerate(image):
| python | {
"resource": ""
} |
q24206 | Map._draw_tiles | train | def _draw_tiles(self, x_offset, y_offset, bg):
"""Render all visible tiles a layer at a time."""
count = 0
for layer_name, c_filters, t_filters in self._get_features():
colour = (self._256_PALETTE[layer_name]
if self._screen.colours >= 256 else self._16_PALETTE[... | python | {
"resource": ""
} |
q24207 | Map._move_to_desired_location | train | def _move_to_desired_location(self):
"""Animate movement to desired location on map."""
self._next_update = 100000
x_start = self._convert_longitude(self._longitude)
y_start = self._convert_latitude(self._latitude)
x_end = self._convert_longitude(self._desired_longitude)
... | python | {
"resource": ""
} |
q24208 | Map.process_event | train | def process_event(self, event):
"""User input for the main map view."""
if isinstance(event, KeyboardEvent):
if event.key_code in [Screen.ctrl("m"), Screen.ctrl("j")]:
self._scene.add_effect(
EnterLocation(
self._screen, self._longi... | python | {
"resource": ""
} |
q24209 | Map._on_new_location | train | def _on_new_location(self, form):
"""Set a new desired location entered in the pop-up form."""
self._desired_longitude = float(form.data["long"])
| python | {
"resource": ""
} |
q24210 | cli | train | def cli(location, **kwargs):
"""Geocode an arbitrary number of strings from Command Line."""
locations = []
# Read Standard Input
# $ cat foo.txt | geocode
try:
for line in fileinput.input():
locations.append(line.strip())
except:
pass
# Read multiple files & u... | python | {
"resource": ""
} |
q24211 | GeonamesQuery._build_params | train | def _build_params(self, location, provider_key, **kwargs):
"""Will be overridden according to the targetted web service"""
base_kwargs = {
'q': location,
'fuzzy': kwargs.get('fuzzy', 1.0),
'username': provider_key,
'maxRows': kwargs.get('maxRows', 1),
... | python | {
"resource": ""
} |
q24212 | BaiduQuery._sign_url | train | def _sign_url(self, base_url, params, security_key):
"""
Signs a request url with a security key.
"""
import hashlib
if six.PY3:
from urllib.parse import urlencode, quote, quote_plus
else:
from urllib import urlencode, quote, quote_plus
i... | python | {
"resource": ""
} |
q24213 | MultipleResultsQuery._is_valid_url | train | def _is_valid_url(url):
""" Helper function to validate that URLs are well formed, i.e that it contains a valid
protocol and a valid domain. It does not actually check if the URL exists
"""
try:
| python | {
"resource": ""
} |
q24214 | OsmQuery._before_initialize | train | def _before_initialize(self, location, **kwargs):
""" Check if specific URL has not been provided, otherwise, use cls._URL"""
| python | {
"resource": ""
} |
q24215 | haversine | train | def haversine(point1, point2, **kwargs):
""" Calculate the great-circle distance bewteen two points on the Earth surface.
:input: two 2-tuples, containing the latitude and longitude of each point
in decimal degrees.
Example: haversine((45.7597, 4.8422), (48.8567, 2.3508))
:output: Returns the dis... | python | {
"resource": ""
} |
q24216 | get_gif | train | def get_gif(api_key, gif_id):
'''Returns dict with gif informations from the API.'''
url = 'http://api.giphy.com/v1/gifs/{}?api_key={}'.format(gif_id, | python | {
"resource": ""
} |
q24217 | create_html | train | def create_html(api_key, attrs):
'''Returns complete html tag string.'''
gif = get_gif(api_key, attrs['gif_id'])
if 'alt' not in attrs.keys():
attrs['alt'] = 'source: {}'.format(gif['data']['source'])
html_out = '<a href="{}">'.format(gif['data']['url'])
html_out += '<img | python | {
"resource": ""
} |
q24218 | main | train | def main(api_key, markup):
'''Doing the regex parsing and running the create_html function.'''
match = GIPHY.search(markup)
attrs = None
if match:
attrs = dict(
[(key, value.strip())
for (key, value) in match.groupdict().items() if value])
| python | {
"resource": ""
} |
q24219 | filetime_from_git | train | def filetime_from_git(content, git_content):
'''
Update modification and creation times from git
'''
if not content.settings['GIT_FILETIME_FROM_GIT']:
# Disabled for everything
return
if not string_to_bool(content.metadata.get('gittime', 'yes')):
# Disable for this content
... | python | {
"resource": ""
} |
q24220 | git_sha_metadata | train | def git_sha_metadata(content, git_content):
'''
Add sha metadata to content
'''
if not content.settings['GIT_SHA_METADATA']:
return
if not git_content.is_committed():
| python | {
"resource": ""
} |
q24221 | update_hash_from_str | train | def update_hash_from_str(hsh, str_input):
"""
Convert a str to object supporting buffer | python | {
"resource": ""
} |
q24222 | git_permalink | train | def git_permalink(content, git_content):
'''
Add git based permalink id to content metadata
'''
if not content.settings['GIT_GENERATE_PERMALINK']:
return
if not string_to_bool(content.metadata.get('git_permalink', 'yes')):
# Disable for this content
return
if not git_co... | python | {
"resource": ""
} |
q24223 | process_summary | train | def process_summary(article):
"""Ensures summaries are not cut off. Also inserts
mathjax script so that math will be rendered"""
summary = article.summary
summary_parsed = BeautifulSoup(summary, 'html.parser')
math = summary_parsed.find_all(class_='math')
if len(math) > 0:
last_math_te... | python | {
"resource": ""
} |
q24224 | configure_typogrify | train | def configure_typogrify(pelicanobj, mathjax_settings):
"""Instructs Typogrify to ignore math tags - which allows Typogrify
to play nicely with math related content"""
# If Typogrify is not being used, then just exit
if not pelicanobj.settings.get('TYPOGRIFY', False):
return
try:
im... | python | {
"resource": ""
} |
q24225 | process_mathjax_script | train | def process_mathjax_script(mathjax_settings):
"""Load the mathjax script template from file, and render with the settings"""
# Read the mathjax javascript template from file
with open (os.path.dirname(os.path.realpath(__file__))
| python | {
"resource": ""
} |
q24226 | mathjax_for_markdown | train | def mathjax_for_markdown(pelicanobj, mathjax_script, mathjax_settings):
"""Instantiates a customized markdown extension for handling mathjax
related content"""
# Create the configuration for the markdown template
config = {}
config['mathjax_script'] = mathjax_script
config['math_tag_class'] = '... | python | {
"resource": ""
} |
q24227 | mathjax_for_rst | train | def mathjax_for_rst(pelicanobj, mathjax_script, mathjax_settings):
"""Setup math for RST"""
docutils_settings = pelicanobj.settings.get('DOCUTILS_SETTINGS', {})
docutils_settings.setdefault('math_output', 'MathJax %s' % | python | {
"resource": ""
} |
q24228 | pelican_init | train | def pelican_init(pelicanobj):
"""
Loads the mathjax script according to the settings.
Instantiate the Python markdown extension, passing in the mathjax
script as config parameter.
"""
# Process settings, and set global var
mathjax_settings = process_settings(pelicanobj)
# Generate math... | python | {
"resource": ""
} |
q24229 | rst_add_mathjax | train | def rst_add_mathjax(content):
"""Adds mathjax script for reStructuredText"""
# .rst is the only valid extension for reStructuredText files
_, ext = os.path.splitext(os.path.basename(content.source_path))
if ext != '.rst':
return
# If math class is present in text, add the javascript
| python | {
"resource": ""
} |
q24230 | process_rst_and_summaries | train | def process_rst_and_summaries(content_generators):
"""
Ensure mathjax script is applied to RST and summaries are
corrected if specified in user settings.
Handles content attached to ArticleGenerator and PageGenerator objects,
since the plugin doesn't know how to handle other Generator types.
F... | python | {
"resource": ""
} |
q24231 | get_permalink_ids_iter | train | def get_permalink_ids_iter(self):
'''
Method to get permalink ids from content. To be bound to the class last
thing.
'''
permalink_id_key = self.settings['PERMALINK_ID_METADATA_KEY']
permalink_ids = self.metadata.get(permalink_id_key, | python | {
"resource": ""
} |
q24232 | get_permalink_path | train | def get_permalink_path(self):
"""Get just path component of permalink."""
try:
first_permalink_id = next(self.get_permalink_ids_iter())
except StopIteration:
return None
| python | {
"resource": ""
} |
q24233 | add_permalink_methods | train | def add_permalink_methods(content_inst):
'''
Add permalink methods to object
'''
for permalink_method in PERMALINK_METHODS:
| python | {
"resource": ""
} |
q24234 | PermalinkGenerator.generate_output | train | def generate_output(self, writer=None):
'''
Generate redirect files
'''
logger.info(
'Generating permalink files in %r', self.permalink_output_path)
clean_output_dir(self.permalink_output_path, [])
mkdir_p(self.permalink_output_path)
for content in it... | python | {
"resource": ""
} |
q24235 | getText | train | def getText(node, recursive=False):
"""Get all the text associated with this node.
With recursive == True, all text from child nodes is retrieved."""
L = [u'']
| python | {
"resource": ""
} |
q24236 | datetime_from_timestamp | train | def datetime_from_timestamp(timestamp, content):
"""
Helper function to add timezone information to datetime,
so that datetime is comparable to other datetime objects in recent versions
that now also have timezone information.
| python | {
"resource": ""
} |
q24237 | get_info | train | def get_info(photo_id, api_key):
''' Get photo informations from flickr api. '''
query = urlencode({
'method': 'flickr.photos.getInfo',
'api_key': api_key,
'photo_id': photo_id,
| python | {
"resource": ""
} |
q24238 | source_url | train | def source_url(farm, server, id, secret, size):
''' Url for direct jpg use. '''
if size == 'small':
img_size = 'n'
elif size == 'medium':
img_size = 'c'
elif size == 'large':
img_size = 'b'
| python | {
"resource": ""
} |
q24239 | generate_html | train | def generate_html(attrs, api_key):
''' Returns html code. '''
# getting flickr api data
flickr_data = get_info(attrs['photo_id'], api_key)
# if size is not defined it will use large as image size
if 'size' not in attrs.keys():
attrs['size'] = 'large'
# if no alt is defined it will use ... | python | {
"resource": ""
} |
q24240 | create_gzip_file | train | def create_gzip_file(filepath, overwrite):
'''Create a gzipped file in the same directory with a filepath.gz name.
:param filepath: A file to compress
:param overwrite: Whether the original file should be overwritten
'''
compressed_path = filepath + '.gz'
with open(filepath, 'rb') as uncompres... | python | {
"resource": ""
} |
q24241 | GitContentAdapter.get_oldest_filename | train | def get_oldest_filename(self):
'''
Get the original filename of this content. Implies follow
'''
commit_and_name_iter = self.git.get_commits_and_names_iter(
| python | {
"resource": ""
} |
q24242 | GitContentAdapter.get_oldest_commit_date | train | def get_oldest_commit_date(self):
'''
Get datetime of oldest commit involving this file
:returns: Datetime of oldest commit
'''
| python | {
"resource": ""
} |
q24243 | GitContentAdapter.get_newest_commit_date | train | def get_newest_commit_date(self):
'''
Get datetime of newest commit involving this file
:returns: Datetime of newest commit
'''
| python | {
"resource": ""
} |
q24244 | keyboard_role | train | def keyboard_role(name, rawtext, text, lineno, inliner,
options={}, content=[]):
"""
This function creates an inline console input block as defined in the twitter bootstrap documentation
| python | {
"resource": ""
} |
q24245 | glyph_role | train | def glyph_role(name, rawtext, text, lineno, inliner,
options={}, content=[]):
"""
This function defines a glyph inline role that show a glyph icon from the
twitter bootstrap framework
*Usage:*
:glyph:`<glyph_name>`
*Example:*
Love this musi... | python | {
"resource": ""
} |
q24246 | TextileReader.read | train | def read(self, source_path):
"""Parse content and metadata of textile files."""
with pelican_open(source_path) as text:
parts = text.split('----', 1)
if len(parts) == 2:
headerlines = parts[0].splitlines()
headerpairs = map(lambda l: l.split(':', ... | python | {
"resource": ""
} |
q24247 | optimize_images | train | def optimize_images(pelican):
"""
Optimized jpg and png images
:param pelican: The Pelican instance
"""
for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
for name in filenames:
| python | {
"resource": ""
} |
q24248 | optimize | train | def optimize(dirpath, filename):
"""
Check if the name is a type of file that should be optimized.
And optimizes it if required.
:param dirpath: Path of the file to be optimzed
:param name: A file name to be optimized | python | {
"resource": ""
} |
q24249 | add_libravatar | train | def add_libravatar (generator, metadata):
"""Article generator connector for the Libravatar plugin"""
missing = generator.settings.get ('LIBRAVATAR_MISSING')
size = generator.settings.get ('LIBRAVATAR_SIZE')
## Check the presence of the Email header
if 'email' not in metadata.keys ():
try:
... | python | {
"resource": ""
} |
q24250 | get_diag | train | def get_diag(code, command):
""" Generate diagramm and return data """
import tempfile
import shutil
code = code + u'\n'
try:
tmpdir = tempfile.mkdtemp()
fd, diag_name = tempfile.mkstemp(dir=tmpdir)
f = os.fdopen(fd, "w")
f.write(code.encode('utf-8'))
f.clos... | python | {
"resource": ""
} |
q24251 | fetch_github_activity | train | def fetch_github_activity(gen, metadata):
"""
registered handler for the github activity plugin
it puts in generator.context the html needed to be displayed on a
template
| python | {
"resource": ""
} |
q24252 | GitHubActivity.fetch | train | def fetch(self):
"""
returns a list of html snippets fetched from github actitivy feed
"""
entries = []
for activity in self.activities['entries']:
entries.append(
[element | python | {
"resource": ""
} |
q24253 | RdfReader.read | train | def read(self, source_path):
"""Parse content and metadata of an rdf file"""
logger.debug("Loading graph described in "+source_path)
graph = rdflib.Graph()
graph.load(source_path)
meta = {}
queries = [
f for f in listdir(self.settings["VOC_QUERIES_PATH"])
... | python | {
"resource": ""
} |
q24254 | _get_file | train | def _get_file(src):
""" Return content from local or remote file. """
try:
if '://' in src or src[0:2] == '//': # Most likely this is remote file
response = urllib2.urlopen(src)
return response.read()
else:
| python | {
"resource": ""
} |
q24255 | pelican_init | train | def pelican_init(pelicanobj):
global global_siteurl
global_siteurl = pelicanobj.settings['SITEURL']
""" Prepare configurations for the MD plugin """
try:
import markdown
from .plantuml_md import PlantUMLMarkdownExtension
except:
# Markdown not available
logger.debug... | python | {
"resource": ""
} |
q24256 | LiquidTags.register | train | def register(cls, tag):
"""Decorator to register a new include tag"""
def dec(func):
if tag in _LiquidTagsPreprocessor._tags:
warnings.warn("Enhanced Markdown: | python | {
"resource": ""
} |
q24257 | git_wrapper | train | def git_wrapper(path):
'''
Get appropriate wrapper factory and cache instance for path
'''
path = os.path.abspath(path)
if path not in _wrapper_cache:
if hasattr(Repo, 'commits'):
| python | {
"resource": ""
} |
q24258 | _GitWrapperCommon.get_commits_and_names_iter | train | def get_commits_and_names_iter(self, path):
'''
Get all commits including a given path following renames
'''
log_result = self.git.log(
| python | {
"resource": ""
} |
q24259 | _GitWrapperCommon.get_commits | train | def get_commits(self, path, follow=False):
'''
Get all commits including path
:param path: Path which we will find commits for
:param bool follow: If | python | {
"resource": ""
} |
q24260 | _GitWrapperLegacy.get_commit_date | train | def get_commit_date(commit, tz_name):
'''
Get datetime of commit comitted_date
| python | {
"resource": ""
} |
q24261 | temporary_locale | train | def temporary_locale(temp_locale=None):
'''Enable code to run in a context with a temporary locale
Resets the locale back when exiting context.
Can set a temporary locale if provided
'''
orig_locale = locale.setlocale(locale.LC_ALL) | python | {
"resource": ""
} |
q24262 | initialize_dbs | train | def initialize_dbs(settings):
'''Initialize internal DBs using the Pelican settings dict
This clears the DBs for e.g. autoreload mode to work
'''
global _MAIN_SETTINGS, _MAIN_SITEURL, _MAIN_LANG, _SUBSITE_QUEUE
_MAIN_SETTINGS = settings
_MAIN_LANG = settings['DEFAULT_LANG']
_MAIN_SITEURL = ... | python | {
"resource": ""
} |
q24263 | prepare_site_db_and_overrides | train | def prepare_site_db_and_overrides():
'''Prepare overrides and create _SITE_DB
_SITE_DB.keys() need to be ready for filter_translations
'''
_SITE_DB.clear()
_SITE_DB[_MAIN_LANG] = _MAIN_SITEURL
# make sure it works for both root-relative and absolute
main_siteurl = '/' if _MAIN_SITEURL == ''... | python | {
"resource": ""
} |
q24264 | relpath_to_site | train | def relpath_to_site(lang, target_lang):
'''Get relative path from siteurl of lang to siteurl of base_lang
the output is cached in _SITES_RELPATH_DB
'''
path = _SITES_RELPATH_DB.get((lang, target_lang), None)
if path is None:
siteurl = _SITE_DB.get(lang, _MAIN_SITEURL)
target_siteurl... | python | {
"resource": ""
} |
q24265 | article2draft | train | def article2draft(article):
'''Transform an Article to Draft'''
draft = Draft(article._content, article.metadata, article.settings,
| python | {
"resource": ""
} |
q24266 | filter_contents_translations | train | def filter_contents_translations(generator):
'''Filter the content and translations lists of a generator
Filters out
1) translations which will be generated in a different site
2) content that is not in the language of the currently
generated site but in that of a different site, conten... | python | {
"resource": ""
} |
q24267 | install_templates_translations | train | def install_templates_translations(generator):
'''Install gettext translations in the jinja2.Environment
Only if the 'jinja2.ext.i18n' jinja2 extension is enabled
the translations for the current DEFAULT_LANG are installed.
'''
if 'JINJA_ENVIRONMENT' in generator.settings: # pelican 3.7+
ji... | python | {
"resource": ""
} |
q24268 | add_variables_to_context | train | def add_variables_to_context(generator):
'''Adds useful iterable variables to template context'''
context = generator.context # minimize attr lookup
context['relpath_to_site'] = relpath_to_site
context['main_siteurl'] = _MAIN_SITEURL
context['main_lang'] = _MAIN_LANG
| python | {
"resource": ""
} |
q24269 | interlink_translations | train | def interlink_translations(content):
'''Link content to translations in their main language
so the URL (including localized month names) of the different subsites
will be honored
'''
lang = content.lang
| python | {
"resource": ""
} |
q24270 | interlink_translated_content | train | def interlink_translated_content(generator):
'''Make translations link to the native locations
for generators that | python | {
"resource": ""
} |
q24271 | interlink_removed_content | train | def interlink_removed_content(generator):
'''For all contents removed from generation queue update interlinks
link to the native location
'''
current_lang = generator.settings['DEFAULT_LANG']
for content in _GENERATOR_DB[generator]:
url | python | {
"resource": ""
} |
q24272 | interlink_static_files | train | def interlink_static_files(generator):
'''Add links to static files in the main site if necessary'''
if generator.settings['STATIC_PATHS'] != []:
return # customized STATIC_PATHS
try: # minimize attr lookup
static_content = generator.context['static_content']
... | python | {
"resource": ""
} |
q24273 | update_generators | train | def update_generators():
'''Update the context of all generators
Ads useful variables and translations into the template context
and interlink translations
'''
for generator in _GENERATOR_DB.keys():
install_templates_translations(generator)
| python | {
"resource": ""
} |
q24274 | get_pelican_cls | train | def get_pelican_cls(settings):
'''Get the Pelican class requested in settings'''
cls = settings['PELICAN_CLASS']
if isinstance(cls, six.string_types):
module, cls_name = | python | {
"resource": ""
} |
q24275 | create_next_subsite | train | def create_next_subsite(pelican_obj):
'''Create the next subsite using the lang-specific config
If there are no more subsites in the generation queue, update all
the generators (interlink translations and removed content, add
variables and translations to template context). Otherwise get the
langua... | python | {
"resource": ""
} |
q24276 | register | train | def register():
'''Register the plugin only if required signals are available'''
for sig_name in _SIGNAL_HANDLERS_DB.keys():
if not hasattr(signals, sig_name):
_LOGGER.error((
'The i18n_subsites plugin requires the {} '
'signal available for sure in Pelican 3.... | python | {
"resource": ""
} |
q24277 | GeneratorInspector.translations_lists | train | def translations_lists(self):
'''Iterator over lists of content translations'''
return | python | {
"resource": ""
} |
q24278 | GeneratorInspector.contents_list_pairs | train | def contents_list_pairs(self):
'''Iterator over pairs of normal and hidden contents'''
return | python | {
"resource": ""
} |
q24279 | GeneratorInspector.untranslated_policy | train | def untranslated_policy(self, default):
'''Get the policy for untranslated content'''
return | python | {
"resource": ""
} |
q24280 | GeneratorInspector.all_contents | train | def all_contents(self):
'''Iterator over all contents'''
translations_iterator = chain(*self.translations_lists())
| python | {
"resource": ""
} |
q24281 | CodeInclude.run | train | def run(self):
"""Include a file as part of the content of this reST file."""
if not self.state.document.settings.file_insertion_enabled:
raise self.warning('"%s" directive disabled.' % self.name)
source = self.state_machine.input_lines.source(
self.lineno - self.state_ma... | python | {
"resource": ""
} |
q24282 | parse_article | train | def parse_article(generator, metadata):
"""Collect articles metadata to be used for building the event calendar
:returns: None
"""
if 'event-start' not in metadata:
return
dtstart = parse_tstamp(metadata, 'event-start')
if 'event-end' in metadata:
dtend = parse_tstamp(metadata... | python | {
"resource": ""
} |
q24283 | generate_ical_file | train | def generate_ical_file(generator):
"""Generate an iCalendar file
"""
global events
ics_fname = generator.settings['PLUGIN_EVENTS']['ics_fname']
if not ics_fname:
return
ics_fname = os.path.join(generator.settings['OUTPUT_PATH'], ics_fname)
log.debug("Generating calendar at %s with %... | python | {
"resource": ""
} |
q24284 | generate_localized_events | train | def generate_localized_events(generator):
""" Generates localized events dict if i18n_subsites plugin is active """
if "i18n_subsites" in generator.settings["PLUGINS"]:
if not os.path.exists(generator.settings['OUTPUT_PATH']):
os.makedirs(generator.settings['OUTPUT_PATH'])
for e in... | python | {
"resource": ""
} |
q24285 | generate_events_list | train | def generate_events_list(generator):
"""Populate the event_list variable to be used in jinja templates"""
if not localized_events:
generator.context['events_list'] = sorted(events, reverse = True,
| python | {
"resource": ""
} |
q24286 | register | train | def register():
"""
Calls the shots, based on signals
"""
signals.article_generator_finalized.connect(link_source_files)
| python | {
"resource": ""
} |
q24287 | CreoleReader.read | train | def read(self, source_path):
"""Parse content and metadata of creole files"""
self._metadata = {}
with pelican_open(source_path) as text:
content = creole2html(text, macros={'header': | python | {
"resource": ""
} |
q24288 | generate_thumbnail_download_link_vimeo | train | def generate_thumbnail_download_link_vimeo(video_id_from_shortcode):
"""Thumbnail URL generator for Vimeo videos."""
# Following the Vimeo API at https://developer.vimeo.com/api#video-request, we need to request the video's metadata and get the thumbnail from that. First, then, we'll get the metadata in JSON format... | python | {
"resource": ""
} |
q24289 | IdenticonRendererBase.render | train | def render(self, size):
"""
render identicon to PIL.Image
@param size identicon patchsize. (image size is 3 * [size])
@return PIL.Image
"""
# decode the code
middle, corner, side, foreColor, backColor = self.decode(self.code)
size = int(size)
# m... | python | {
"resource": ""
} |
q24290 | make_posts | train | def make_posts(generator, metadata, url):
"""
Make posts on reddit if it's not a draft, on whatever subs are specified
"""
reddit = generator.get_reddit()
title = lxml.html.fromstring(metadata['title']).text_content()
if reddit is None:
log.info("Reddit plugin not enabled")
retu... | python | {
"resource": ""
} |
q24291 | init_reddit | train | def init_reddit(generator):
"""
this is a hack to make sure the reddit object keeps track of a session
trough article scanning, speeding up networking as the connection can be
kept alive.
"""
auth_dict = generator.settings.get('REDDIT_POSTER_AUTH')
if auth_dict is None:
| python | {
"resource": ""
} |
q24292 | ReduceOpacity | train | def ReduceOpacity(im, opacity):
"""Reduces Opacity.
Returns an image with reduced opacity.
Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
"""
assert opacity >= 0 and opacity <= 1
if isalpha(im):
im = im.copy()
| python | {
"resource": ""
} |
q24293 | detect_images_and_galleries | train | def detect_images_and_galleries(generators):
"""Runs generator on both pages and articles."""
for generator in generators:
if isinstance(generator, ArticlesGenerator):
for article in itertools.chain(generator.articles, generator.translations, generator.drafts):
detect_image(g... | python | {
"resource": ""
} |
q24294 | add_jinja2_ext | train | def add_jinja2_ext(pelican):
"""Add Webassets to Jinja2 extensions in Pelican settings."""
if 'JINJA_ENVIRONMENT' in pelican.settings: # pelican 3.7+
| python | {
"resource": ""
} |
q24295 | create_assets_env | train | def create_assets_env(generator):
"""Define the assets environment and pass it to the generator."""
theme_static_dir = generator.settings['THEME_STATIC_DIR']
assets_destination = os.path.join(generator.output_path, theme_static_dir)
generator.env.assets_environment = Environment(
assets_destina... | python | {
"resource": ""
} |
q24296 | run_pygal | train | def run_pygal(data, options=[], format='svg'):
""" Runs pygal programs and returns image data
"""
import pygal
chart_title = data.get('title', None)
chart_type = data.get('type', '').lower()
# Config options are pretty much proxied straight through from the JSON dict into the object
config ... | python | {
"resource": ""
} |
q24297 | pygal_parser | train | def pygal_parser(preprocessor, tag, markup):
""" Simple pygal parser """
# Find JSON payload
data = loads(markup)
if tag == 'pygal' and data is not None:
# Run generation of chart
| python | {
"resource": ""
} |
q24298 | resize_thumbnails | train | def resize_thumbnails(pelican):
""" Resize a directory tree full of images into thumbnails
:param pelican: The pelican instance
:return: None
"""
global enabled
if not enabled:
return
in_path = _image_path(pelican)
include_regex = pelican.settings.get('THUMBNAIL_INCLUDE_REGEX'... | python | {
"resource": ""
} |
q24299 | expand_gallery | train | def expand_gallery(generator, metadata):
""" Expand a gallery tag to include all of the files in a specific directory under IMAGE_PATH
:param pelican: The pelican instance
:return: None
"""
if "gallery" not in metadata or metadata['gallery'] is None:
return # If no gallery specified, we do... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.