Best Python code snippet using Kiwi_python
markdown.py
Source:markdown.py
...13from markdown.util import etree14from ..models import Comment15register = template.Library()16class EscapeHtml(Extension):17 def extendMarkdown(self, md, md_globals):18 del md.preprocessors['html_block']19 del md.inlinePatterns['html']20class RestrictImageHosts(Extension):21 class ImageHostFilter(Treeprocessor):22 def __init__(self, md, patterns):23 super(RestrictImageHosts.ImageHostFilter, self).__init__(md)24 self.patterns = patterns25 def run(self, root):26 for image in root.findall('.//img'):27 link = image.get('src')28 if not any((pattern.match(link) for pattern in self.patterns)) and\29 'smiley' not in image.get('class', []):30 image.tag = 'a'31 image.attrib.pop('src')32 image.attrib.pop('alt')33 image.text = link34 image.set('href', link)35 def __init__(self, allowed_hosts_list):36 self.patterns = [re.compile(pattern) for pattern in allowed_hosts_list]37 super(RestrictImageHosts, self).__init__()38 def extendMarkdown(self, md, md_globals):39 md.treeprocessors.add('imagefilter', self.ImageHostFilter(md, self.patterns), '_end')40class Smileys(Extension):41 class SmileysPattern(Pattern):42 def __init__(self):43 Pattern.__init__(self, '')44 def getCompiledRegExp(self):45 self.smileys = cache.get('smiley_list')46 return re.compile(r'^(.*?):(?P<smiley>' + '|'.join(self.smileys.keys()) + '):(.*?)$')47 def handleMatch(self, m):48 smiley_name = m.group('smiley')49 el = etree.Element('img', src=self.smileys[smiley_name])50 el.set('class', 'smiley')51 return el52 def extendMarkdown(self, md, md_globals):53 md.inlinePatterns.add('smileys', self.SmileysPattern(), '_end')54 md.ESCAPED_CHARS.append(':')55class Spoilers(Extension):56 class SpoilerPattern(Pattern):57 def __init__(self):58 Pattern.__init__(self, r'(%{2})(?P<contents>.+?)\2')59 def handleMatch(self, m):60 el = etree.Element('span')61 el.set('class', 'spoiler')62 el.text = m.group('contents')63 return el64 def extendMarkdown(self, md, md_globals):65 md.inlinePatterns.add('spoilers', self.SpoilerPattern(), '_end')66 md.ESCAPED_CHARS.append('%')67class CommentRefs(Extension):68 class CommentRefPattern(Pattern):69 def __init__(self):70 Pattern.__init__(self, r'(>{2})(?P<comment_id>\d+)')71 def handleMatch(self, m):72 comment_id = int(m.group('comment_id'))73 try:74 comment = Comment.objects.get(pk=comment_id)75 el = etree.Element('a')76 el.set('href', '{}#{}'.format(77 reverse('onechan:show_post', kwargs={78 'post_id': comment.post_id79 }),80 comment_id81 ))82 el.set('class', 'comment-ref')83 el.set('data-comment-url',84 reverse('onechan:get_comment', kwargs={'comment_id': comment_id})85 )86 el.text = '>>{}'.format(comment_id)87 return el88 except Exception:89 return '>>{}'.format(comment_id)90 def extendMarkdown(self, md, md_globals):91 md.inlinePatterns.add('comment_refs', self.CommentRefPattern(), '_end')92class Autolinks(Extension):93 class LinkPreprocessor(Preprocessor):94 LINK_RE = re.compile(r'(https?://\S+)')95 def run(self, lines):96 return [self.LINK_RE.sub(r'[\1](\1)', line) for line in lines]97 def extendMarkdown(self, md, md_globals):98 md.preprocessors.add('autolinks', self.LinkPreprocessor(), '_end')99class YoutubeEmbedder(Extension):100 class YoutubeProcessor(Treeprocessor):101 YOUTUBE_RE = re.compile(r'''102 https?://(?:www\.)? # scheme and optional www prefix103 (?: # then either104 youtube\.com/watch\?.*v= # traditional url with any query args before v=<id>105 | # or106 youtu\.be/ # new 'share' url107 )108 (?P<id>[^&]+).* # finally, capture the video id and ignore irrelevant shit109 ''',110 re.VERBOSE111 )112 def run(self, root):113 for link in root.findall('.//a'):114 href = link.get('href')115 match = self.YOUTUBE_RE.match(href)116 if match:117 link.tag = 'div'118 link.attrib.pop('href')119 link.set('class', 'youtube-container')120 link.set('data-video-id', match.group('id'))121 link.text = ''122 img = etree.Element('img',123 src='https://img.youtube.com/vi/{}/mqdefault.jpg'.format(match.group('id')))124 link.append(img)125 def extendMarkdown(self, md, md_globals):126 md.treeprocessors.add('youtube', self.YoutubeProcessor(), '_end')127md = Markdown(extensions=[128 EscapeHtml(),129 RestrictImageHosts(settings.ALLOWED_IMAGE_PATTERNS),130 Smileys(),131 Spoilers(),132 CommentRefs(),133 Autolinks(),134 YoutubeEmbedder(),135])136# sorry mommy i am a dirty monkey patcher137md.parser.blockprocessors['quote'].RE = re.compile(r'(^|\n)[ ]{0,3}>(?!\>\d)[ ]?(.*)')138@register.filter139@stringfilter...
__init__.py
Source:__init__.py
...53 # it's a dict54 items = items.items()55 for key, value in items:56 self.setConfig(key, value)57 def _extendMarkdown(self, *args):58 """ Private wrapper around extendMarkdown. """59 md = args[0]60 try:61 self.extendMarkdown(md)62 except TypeError as e:63 if "missing 1 required positional argument" in str(e):64 # Must be a 2.x extension. Pass in a dumby md_globals.65 self.extendMarkdown(md, {})66 warnings.warn(67 "The 'md_globals' parameter of '{}.{}.extendMarkdown' is "68 "deprecated.".format(self.__class__.__module__, self.__class__.__name__),69 category=DeprecationWarning,70 stacklevel=271 )72 else:73 raise74 def extendMarkdown(self, md):75 """76 Add the various proccesors and patterns to the Markdown Instance.77 This method must be overriden by every extension.78 Keyword arguments:79 * md: The Markdown instance.80 * md_globals: Global variables in the markdown module namespace.81 """82 raise NotImplementedError(83 'Extension "%s.%s" must define an "extendMarkdown"'84 'method.' % (self.__class__.__module__, self.__class__.__name__)...
CacheLoader.js
Source:CacheLoader.js
1'use strict'2/**3 * Module dependencies.4 */5const {6 path, toAbsolutePath, chalk, logger,7 datatypes: { isString, isBoolean }8} = require('@vuepress/shared-utils')9/**10 * Get cache directory and cache identifier via config.11 * @param {object} siteConfig12 * @param {object} options13 */14exports.getCacheLoaderOptions = function (siteConfig, options, cwd, isProd) {15 const defaultCacheDirectory = path.resolve(__dirname, '../../node_modules/.cache/vuepress')16 let cache = options.cache || siteConfig.cache || defaultCacheDirectory17 if (isBoolean(cache)) {18 if (cache === true) {19 cache = defaultCacheDirectory20 }21 } else if (!isString(cache)) {22 throw new Error(`expected cache option to be string or boolean, but got ${typeof cache}`)23 }24 const cacheDirectory = toAbsolutePath(cache, cwd)25 const cacheIdentifier = JSON.stringify({26 vuepress: require('../../package.json').version,27 'cache-loader': require('cache-loader/package.json').version,28 'vue-loader': require('cache-loader/package.json').version,29 isProd,30 config: (31 (32 siteConfig.markdown33 ? JSON.stringify(siteConfig.markdown)34 : ''35 )36 + (37 siteConfig.markdown && siteConfig.markdown.extendMarkdown38 ? siteConfig.markdown.extendMarkdown.toString()39 : ''40 )41 + (42 siteConfig.extendMarkdown43 ? siteConfig.extendMarkdown.toString()44 : ''45 )46 + (siteConfig.chainWebpack || '').toString()47 + (siteConfig.configureWebpack || '').toString()48 )49 })50 logger.debug('Cache directory: ' + chalk.gray(cacheDirectory))51 logger.debug('Cache identifier : ' + chalk.gray(cacheIdentifier))52 return { cacheDirectory, cacheIdentifier }...
createMarkdown.js
Source:createMarkdown.js
...13 chainMarkdown && chainMarkdown(config)14 ctx.pluginAPI.applySyncOption('chainMarkdown', config)15 }16 const afterInstantiate = md => {17 extendMarkdown && extendMarkdown(md)18 ctx.pluginAPI.applySyncOption('extendMarkdown', md)19 }20 return createMarkdown(21 Object.assign(markdownConfig, {22 beforeInstantiate,23 afterInstantiate24 })25 )...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!