signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def _determine_checkout_url(self, platform, action):
api_version = settings.API_CHECKOUT_VERSION<EOL>if platform == "<STR_LIT:test>":<EOL><INDENT>base_uri = settings.ENDPOINT_CHECKOUT_TEST<EOL><DEDENT>elif self.live_endpoint_prefix is not None and platform == "<STR_LIT>":<EOL><INDENT>base_uri = settings.ENDPOINT_CHECKOUT_LIVE_SUFFIX.format(<EOL>self.live_endpoint_prefix)...
This returns the Adyen API endpoint based on the provided platform, service and action. Args: platform (str): Adyen platform, ie 'live' or 'test'. action (str): the API action to perform.
f729:c1:m3
def call_api(self, request_data, service, action, idempotency=False,<EOL>**kwargs):
if not self.http_init:<EOL><INDENT>self.http_client = HTTPClient(self.app_name,<EOL>self.USER_AGENT_SUFFIX,<EOL>self.LIB_VERSION,<EOL>self.http_force)<EOL>self.http_init = True<EOL><DEDENT>if self.xapikey:<EOL><INDENT>xapikey = self.xapikey<EOL><DEDENT>elif '<STR_LIT>' in kwargs:<EOL><INDENT>xapikey = kwargs.pop("<STR_...
This will call the adyen api. username, password, merchant_account, and platform are pulled from root module level and or self object. AdyenResult will be returned on 200 response. Otherwise, an exception is raised. Args: request_data (dict): The dictionary of the request to...
f729:c1:m8
def call_hpp(self, message, action, hmac_key="<STR_LIT>", **kwargs):
if not self.http_init:<EOL><INDENT>self.http_client = HTTPClient(self.app_name,<EOL>self.USER_AGENT_SUFFIX,<EOL>self.LIB_VERSION,<EOL>self.http_force)<EOL>self.http_init = True<EOL><DEDENT>hmac = hmac_key<EOL>if self.hmac:<EOL><INDENT>hmac = self.hmac<EOL><DEDENT>elif not hmac:<EOL><INDENT>errorstring = """<STR_LIT>"""...
This will call the adyen hpp. hmac_key and platform are pulled from root module level and or self object. AdyenResult will be returned on 200 response. Otherwise, an exception is raised. Args: request_data (dict): The dictionary of the request to place. This ...
f729:c1:m9
def call_checkout_api(self, request_data, action, **kwargs):
if not self.http_init:<EOL><INDENT>self.http_client = HTTPClient(self.app_name,<EOL>self.USER_AGENT_SUFFIX,<EOL>self.LIB_VERSION,<EOL>self.http_force)<EOL>self.http_init = True<EOL><DEDENT>if self.xapikey:<EOL><INDENT>xapikey = self.xapikey<EOL><DEDENT>elif '<STR_LIT>' in kwargs:<EOL><INDENT>xapikey = kwargs.pop("<STR_...
This will call the checkout adyen api. xapi key merchant_account, and platform are pulled from root module level and or self object. AdyenResult will be returned on 200 response. Otherwise, an exception is raised. Args: request_data (dict): The dictionary of the request to p...
f729:c1:m10
def _handle_response(self, url, raw_response, raw_request,<EOL>status_code, headers, request_dict):
if status_code != <NUM_LIT:200>:<EOL><INDENT>response = {}<EOL>if raw_response:<EOL><INDENT>response = json_lib.loads(raw_response)<EOL><DEDENT>self._handle_http_error(url, response, status_code,<EOL>headers.get('<STR_LIT>'),<EOL>raw_request, raw_response,<EOL>headers, request_dict)<EOL>try:<EOL><INDENT>if response['<S...
This parses the content from raw communication, raising an error if anything other than 200 was returned. Args: url (str): URL where request was made raw_response (str): The raw communication sent to Adyen raw_request (str): The raw response returned by Adyen ...
f729:c1:m12
def _handle_http_error(self, url, response_obj, status_code, psp_ref,<EOL>raw_request, raw_response, headers, message):
if status_code == <NUM_LIT>:<EOL><INDENT>if url == self.merchant_specific_url:<EOL><INDENT>erstr = "<STR_LIT>""<STR_LIT>".format(url)<EOL>raise AdyenAPICommunicationError(erstr,<EOL>error_code=response_obj.get(<EOL>"<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>erstr = "<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>raise AdyenAPIC...
This function handles the non 200 responses from Adyen, raising an error that should provide more information. Args: url (str): url of the request response_obj (dict): Dict containing the parsed JSON response from Adyen status_code (int): HTTP status ...
f729:c1:m13
def _pycurl_post(self,<EOL>url,<EOL>json=None,<EOL>data=None,<EOL>username="<STR_LIT>",<EOL>password="<STR_LIT>",<EOL>headers={},<EOL>timeout=<NUM_LIT:30>):
response_headers = {}<EOL>curl = pycurl.Curl()<EOL>curl.setopt(curl.URL, url)<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stringbuffer = BytesIO()<EOL><DEDENT>else:<EOL><INDENT>stringbuffer = StringIO()<EOL><DEDENT>curl.setopt(curl.WRITEDATA, stringbuffer)<EOL>headers['<STR_LIT>'] = self.user_agent...
This function will POST to the url endpoint using pycurl. returning an AdyenResult object on 200 HTTP responce. Either json or data has to be provided. If username and password are provided, basic auth will be used. Args: url (str): url to send the POST json (di...
f733:c0:m1
def _requests_post(self, url,<EOL>json=None,<EOL>data=None,<EOL>username="<STR_LIT>",<EOL>password="<STR_LIT>",<EOL>xapikey="<STR_LIT>",<EOL>headers=None,<EOL>timeout=<NUM_LIT:30>):
if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>auth = None<EOL>if username and password:<EOL><INDENT>auth = requests.auth.HTTPBasicAuth(username, password)<EOL><DEDENT>elif xapikey:<EOL><INDENT>headers['<STR_LIT>'] = xapikey<EOL><DEDENT>headers['<STR_LIT>'] = self.user_agent<EOL>request = requests.post(url, a...
This function will POST to the url endpoint using requests. Returning an AdyenResult object on 200 HTTP response. Either json or data has to be provided. If username and password are provided, basic auth will be used. Args: url (str): url to send the POST json (...
f733:c0:m2
def _urllib_post(self, url,<EOL>json="<STR_LIT>",<EOL>data="<STR_LIT>",<EOL>username="<STR_LIT>",<EOL>password="<STR_LIT>",<EOL>headers=None,<EOL>timeout=<NUM_LIT:30>):
if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>raw_store = json<EOL>raw_request = json_lib.dumps(json) if json else urlencode(data)<EOL>url_request = Request(url, data=raw_request.encode('<STR_LIT:utf8>'))<EOL>if json:<EOL><INDENT>url_request.add_header('<STR_LIT:Content-Type>', '<STR_LIT:application/json>')<...
This function will POST to the url endpoint using urllib2. returning an AdyenResult object on 200 HTTP responce. Either json or data has to be provided. If username and password are provided, basic auth will be used. Args: url (str): url to send the POST ...
f733:c0:m3
def request(self, url,<EOL>json="<STR_LIT>",<EOL>data="<STR_LIT>",<EOL>username="<STR_LIT>",<EOL>password="<STR_LIT>",<EOL>headers=None,<EOL>timout=<NUM_LIT:30>):
raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>
This is overridden on module initialization. This function will make an HTTP POST to a given url. Either json/data will be what is posted to the end point. he HTTP request needs to be basicAuth when username and password are provided. a headers dict maybe provided, whatever the values ar...
f733:c0:m4
def get_github_content(repo,path,auth=None):
request = requests.get(file_url.format(repo=repo, path=path), auth=auth)<EOL>if not request.ok:<EOL><INDENT>print("<STR_LIT>")<EOL>print(file_url.format(repo=repo, path=path))<EOL>print(request.json())<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>if not request.json()['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>raise RuntimeError("<...
Retrieve text files from a github repo
f746:m0
def collect_reponames():
reponames = []<EOL>try:<EOL><INDENT>with open(os.devnull) as devnull:<EOL><INDENT>remote_data = subprocess.check_output(["<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"],stderr=devnull)<EOL><DEDENT>branches = {}<EOL>for line in remote_data.decode('<STR_LIT:utf-8>').split("<STR_LIT:\n>"):<EOL><INDENT>if line.strip() == ...
Try to figure out a list of repos to consider by default from the contents of the working directory.
f746:m3
def collect_github_config():
github_config = {}<EOL>for field in ["<STR_LIT:user>", "<STR_LIT>"]:<EOL><INDENT>try:<EOL><INDENT>github_config[field] = subprocess.check_output(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>".format(field)]).decode('<STR_LIT:utf-8>').strip()<EOL><DEDENT>except (OSError, subprocess.CalledProcessError):<EOL><INDENT>pass<EOL><DED...
Try load Github configuration such as usernames from the local or global git config
f746:m4
def yearplot(data, year=None, how='<STR_LIT>', vmin=None, vmax=None, cmap='<STR_LIT>',<EOL>fillcolor='<STR_LIT>', linewidth=<NUM_LIT:1>, linecolor=None,<EOL>daylabels=calendar.day_abbr[:], dayticks=True,<EOL>monthlabels=calendar.month_abbr[<NUM_LIT:1>:], monthticks=True, ax=None,<EOL>**kwargs):
if year is None:<EOL><INDENT>year = data.index.sort_values()[<NUM_LIT:0>].year<EOL><DEDENT>if how is None:<EOL><INDENT>by_day = data<EOL><DEDENT>else:<EOL><INDENT>if _pandas_18:<EOL><INDENT>by_day = data.resample('<STR_LIT:D>').agg(how)<EOL><DEDENT>else:<EOL><INDENT>by_day = data.resample('<STR_LIT:D>', how=how)<EOL><D...
Plot one year from a timeseries as a calendar heatmap. Parameters ---------- data : Series Data for the plot. Must be indexed by a DatetimeIndex. year : integer Only data indexed by this year will be plotted. If `None`, the first year for which there is data will be plotted. how : string Method for res...
f749:m0
def calendarplot(data, how='<STR_LIT>', yearlabels=True, yearascending=True, yearlabel_kws=None,<EOL>subplot_kws=None, gridspec_kws=None, fig_kws=None, **kwargs):
yearlabel_kws = yearlabel_kws or {}<EOL>subplot_kws = subplot_kws or {}<EOL>gridspec_kws = gridspec_kws or {}<EOL>fig_kws = fig_kws or {}<EOL>years = np.unique(data.index.year)<EOL>if not yearascending:<EOL><INDENT>years = years[::-<NUM_LIT:1>]<EOL><DEDENT>fig, axes = plt.subplots(nrows=len(years), ncols=<NUM_LIT:1>, s...
Plot a timeseries as a calendar heatmap. Parameters ---------- data : Series Data for the plot. Must be indexed by a DatetimeIndex. how : string Method for resampling data by day. If `None`, assume data is already sampled by day and don't resample. Otherwise, this is passed to Pandas `Series.resample`....
f749:m1
def mark_plot_labels(app, document):
for name, explicit in six.iteritems(document.nametypes):<EOL><INDENT>if not explicit:<EOL><INDENT>continue<EOL><DEDENT>labelid = document.nameids[name]<EOL>if labelid is None:<EOL><INDENT>continue<EOL><DEDENT>node = document.ids[labelid]<EOL>if node.tagname in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>for n in node:<EOL>...
To make plots referenceable, we need to move the reference from the "htmlonly" (or "latexonly") node to the actual figure node itself.
f750:m5
def split_code_at_show(text):
parts = []<EOL>is_doctest = contains_doctest(text)<EOL>part = []<EOL>for line in text.split("<STR_LIT:\n>"):<EOL><INDENT>if (not is_doctest and line.strip() == '<STR_LIT>') or(is_doctest and line.strip() == '<STR_LIT>'):<EOL><INDENT>part.append(line)<EOL>parts.append("<STR_LIT:\n>".join(part))<EOL>part = []<EOL><DEDENT...
Split code at plt.show()
f750:m9
def remove_coding(text):
sub_re = re.compile("<STR_LIT>", flags=re.MULTILINE)<EOL>return sub_re.sub("<STR_LIT>", text)<EOL>
Remove the coding comment, which six.exec_ doesn't like.
f750:m10
def out_of_date(original, derived):
return (not os.path.exists(derived) or<EOL>(os.path.exists(original) and<EOL>os.stat(derived).st_mtime < os.stat(original).st_mtime))<EOL>
Returns True if derivative is out-of-date wrt original, both of which are full file paths.
f750:m11
def run_code(code, code_path, ns=None, function_name=None):
<EOL>if six.PY2:<EOL><INDENT>pwd = os.getcwdu()<EOL><DEDENT>else:<EOL><INDENT>pwd = os.getcwd()<EOL><DEDENT>old_sys_path = list(sys.path)<EOL>if setup.config.plot_working_directory is not None:<EOL><INDENT>try:<EOL><INDENT>os.chdir(setup.config.plot_working_directory)<EOL><DEDENT>except OSError as err:<EOL><INDENT>rais...
Import a Python module from a path, and run the function given by name, if function_name is not None.
f750:m12
def render_figures(code, code_path, output_dir, output_base, context,<EOL>function_name, config, context_reset=False,<EOL>close_figs=False):
<EOL>default_dpi = {'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT:200>, '<STR_LIT>': <NUM_LIT:200>}<EOL>formats = []<EOL>plot_formats = config.plot_formats<EOL>if isinstance(plot_formats, six.string_types):<EOL><INDENT>plot_formats = plot_formats.split('<STR_LIT:U+002C>')<EOL><DEDENT>for fmt in plot_formats:<EOL><INDEN...
Run a pyplot script and save the low and high res PNGs and a PDF in *output_dir*. Save the images under *output_dir* with file names derived from *output_base*
f750:m14
def get_forwarders(resolv="<STR_LIT>"):
ns = []<EOL>if os.path.exists(resolv):<EOL><INDENT>for l in open(resolv):<EOL><INDENT>if l.startswith("<STR_LIT>"):<EOL><INDENT>address = l.strip().split("<STR_LIT:U+0020>", <NUM_LIT:2>)[<NUM_LIT:1>]<EOL>if not address.startswith("<STR_LIT>"):<EOL><INDENT>ns.append(address)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if not ns...
Find the forwarders in /etc/resolv.conf, default to 8.8.8.8 and 8.8.4.4
f753:m0
def spawn(opts, conf):
if opts.config is not None:<EOL><INDENT>os.environ["<STR_LIT>"] = opts.config<EOL><DEDENT>sys.argv[<NUM_LIT:1>:] = [<EOL>"<STR_LIT>", sibpath(__file__, "<STR_LIT>"),<EOL>"<STR_LIT>", conf['<STR_LIT>'],<EOL>"<STR_LIT>", conf['<STR_LIT>'],<EOL>]<EOL>twistd.run()<EOL>
Acts like twistd
f764:m0
def __init__(self, file_encoding=None, string_encoding=None,<EOL>decode_errors=None, search_dirs=None, file_extension=None,<EOL>escape=None, partials=None, missing_tags=None):
if decode_errors is None:<EOL><INDENT>decode_errors = defaults.DECODE_ERRORS<EOL><DEDENT>if escape is None:<EOL><INDENT>escape = defaults.TAG_ESCAPE<EOL><DEDENT>if file_encoding is None:<EOL><INDENT>file_encoding = defaults.FILE_ENCODING<EOL><DEDENT>if file_extension is None:<EOL><INDENT>file_extension = defaults.TEMPL...
Construct an instance. Arguments: file_encoding: the name of the encoding to use by default when reading template files. All templates are converted to unicode prior to parsing. Defaults to the package default. string_encoding: the name of the encoding to use when converting to unicode any byte str...
f766:c0:m0
@property<EOL><INDENT>def context(self):<DEDENT>
return self._context<EOL>
Return the current rendering context [experimental].
f766:c0:m1
def str_coerce(self, val):
return str(val)<EOL>
Coerce a non-string value to a string. This method is called whenever a non-string is encountered during the rendering process when a string is needed (e.g. if a context value for string interpolation is not a string). To customize string coercion, you can override this method.
f766:c0:m2
def _to_unicode_soft(self, s):
<EOL>if isinstance(s, unicode):<EOL><INDENT>return s<EOL><DEDENT>return self.unicode(s)<EOL>
Convert a basestring to unicode, preserving any unicode subclass.
f766:c0:m3
def _to_unicode_hard(self, s):
return unicode(self._to_unicode_soft(s))<EOL>
Convert a basestring to a string with type unicode (not subclass).
f766:c0:m4
def _escape_to_unicode(self, s):
return unicode(self.escape(self._to_unicode_soft(s)))<EOL>
Convert a basestring to unicode (preserving any unicode subclass), and escape it. Returns a unicode string (not subclass).
f766:c0:m5
def unicode(self, b, encoding=None):
if encoding is None:<EOL><INDENT>encoding = self.string_encoding<EOL><DEDENT>return unicode(b, encoding, self.decode_errors)<EOL>
Convert a byte string to unicode, using string_encoding and decode_errors. Arguments: b: a byte string. encoding: the name of an encoding. Defaults to the string_encoding attribute for this instance. Raises: TypeError: Because this method calls Python's built-in unicode() function, this method raise...
f766:c0:m6
def _make_loader(self):
return Loader(file_encoding=self.file_encoding, extension=self.file_extension,<EOL>to_unicode=self.unicode, search_dirs=self.search_dirs)<EOL>
Create a Loader instance using current attributes.
f766:c0:m7
def _make_load_template(self):
loader = self._make_loader()<EOL>def load_template(template_name):<EOL><INDENT>return loader.load_name(template_name)<EOL><DEDENT>return load_template<EOL>
Return a function that loads a template by name.
f766:c0:m8
def _make_load_partial(self):
if self.partials is None:<EOL><INDENT>return self._make_load_template()<EOL><DEDENT>partials = self.partials<EOL>def load_partial(name):<EOL><INDENT>template = partials.get(name)<EOL>if template is None:<EOL><INDENT>raise TemplateNotFoundError("<STR_LIT>" %<EOL>(repr(name), type(partials)))<EOL><DEDENT>return self._to_...
Return a function that loads a partial by name.
f766:c0:m9
def _is_missing_tags_strict(self):
val = self.missing_tags<EOL>if val == MissingTags.strict:<EOL><INDENT>return True<EOL><DEDENT>elif val == MissingTags.ignore:<EOL><INDENT>return False<EOL><DEDENT>raise Exception("<STR_LIT>" % repr(val))<EOL>
Return whether missing_tags is set to strict.
f766:c0:m10
def _make_resolve_partial(self):
load_partial = self._make_load_partial()<EOL>if self._is_missing_tags_strict():<EOL><INDENT>return load_partial<EOL><DEDENT>def resolve_partial(name):<EOL><INDENT>try:<EOL><INDENT>return load_partial(name)<EOL><DEDENT>except TemplateNotFoundError:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT><DEDENT>return resolve_parti...
Return the resolve_partial function to pass to RenderEngine.__init__().
f766:c0:m11
def _make_resolve_context(self):
if self._is_missing_tags_strict():<EOL><INDENT>return context_get<EOL><DEDENT>def resolve_context(stack, name):<EOL><INDENT>try:<EOL><INDENT>return context_get(stack, name)<EOL><DEDENT>except KeyNotFoundError:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT><DEDENT>return resolve_context<EOL>
Return the resolve_context function to pass to RenderEngine.__init__().
f766:c0:m12
def _make_render_engine(self):
resolve_context = self._make_resolve_context()<EOL>resolve_partial = self._make_resolve_partial()<EOL>engine = RenderEngine(literal=self._to_unicode_hard,<EOL>escape=self._escape_to_unicode,<EOL>resolve_context=resolve_context,<EOL>resolve_partial=resolve_partial,<EOL>to_str=self.str_coerce)<EOL>return engine<EOL>
Return a RenderEngine instance for rendering.
f766:c0:m13
def load_template(self, template_name):
load_template = self._make_load_template()<EOL>return load_template(template_name)<EOL>
Load a template by name from the file system.
f766:c0:m14
def _render_object(self, obj, *context, **kwargs):
loader = self._make_loader()<EOL>if isinstance(obj, TemplateSpec):<EOL><INDENT>loader = SpecLoader(loader)<EOL>template = loader.load(obj)<EOL><DEDENT>else:<EOL><INDENT>template = loader.load_object(obj)<EOL><DEDENT>context = [obj] + list(context)<EOL>return self._render_string(template, *context, **kwargs)<EOL>
Render the template associated with the given object.
f766:c0:m15
def render_name(self, template_name, *context, **kwargs):
loader = self._make_loader()<EOL>template = loader.load_name(template_name)<EOL>return self._render_string(template, *context, **kwargs)<EOL>
Render the template with the given name using the given context. See the render() docstring for more information.
f766:c0:m16
def render_path(self, template_path, *context, **kwargs):
loader = self._make_loader()<EOL>template = loader.read(template_path)<EOL>return self._render_string(template, *context, **kwargs)<EOL>
Render the template at the given path using the given context. Read the render() docstring for more information.
f766:c0:m17
def _render_string(self, template, *context, **kwargs):
<EOL>template = self._to_unicode_hard(template)<EOL>render_func = lambda engine, stack: engine.render(template, stack)<EOL>return self._render_final(render_func, *context, **kwargs)<EOL>
Render the given template string using the given context.
f766:c0:m18
def _render_final(self, render_func, *context, **kwargs):
stack = ContextStack.create(*context, **kwargs)<EOL>self._context = stack<EOL>engine = self._make_render_engine()<EOL>return render_func(engine, stack)<EOL>
Arguments: render_func: a function that accepts a RenderEngine and ContextStack instance and returns a template rendering as a unicode string.
f766:c0:m19
def render(self, template, *context, **kwargs):
if is_string(template):<EOL><INDENT>return self._render_string(template, *context, **kwargs)<EOL><DEDENT>if isinstance(template, ParsedTemplate):<EOL><INDENT>render_func = lambda engine, stack: template.render(engine, stack)<EOL>return self._render_final(render_func, *context, **kwargs)<EOL><DEDENT>return self._render_...
Render the given template string, view template, or parsed template. Returns a unicode string. Prior to rendering, this method will convert a template that is a byte string (type str in Python 2) to unicode using the string_encoding and decode_errors attributes. See the constructor docstring for more information. A...
f766:c0:m20
def parse(template, delimiters=None):
if type(template) is not str:<EOL><INDENT>raise Exception("<STR_LIT>" % type(template))<EOL><DEDENT>parser = _Parser(delimiters)<EOL>return parser.parse(template)<EOL>
Parse a unicode template string and return a ParsedTemplate instance. Arguments: template: a unicode template string. delimiters: a 2-tuple of delimiters. Defaults to the package default. Examples: >>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}") >>> print str(parsed).replace('u', '') # This is a hack to...
f767:m0
def _compile_template_re(delimiters):
<EOL>tag_types = "<STR_LIT>"<EOL>tag = r"""<STR_LIT>""" % {'<STR_LIT>': tag_types, '<STR_LIT>': re.escape(delimiters[<NUM_LIT:0>]), '<STR_LIT>': re.escape(delimiters[<NUM_LIT:1>])}<EOL>return re.compile(tag, re.VERBOSE)<EOL>
Return a regular expression object (re.RegexObject) instance.
f767:m1
def parse(self, template):
self._compile_delimiters()<EOL>start_index = <NUM_LIT:0><EOL>content_end_index, parsed_section, section_key = None, None, None<EOL>parsed_template = ParsedTemplate()<EOL>states = []<EOL>while True:<EOL><INDENT>match = self._template_re.search(template, start_index)<EOL>if match is None:<EOL><INDENT>break<EOL><DEDENT>ma...
Parse a template string starting at some index. This method uses the current tag delimiter. Arguments: template: a unicode string that is the template to parse. index: the index at which to start parsing. Returns: a ParsedTemplate instance.
f767:c8:m3
def _make_interpolation_node(self, tag_type, tag_key, leading_whitespace):
<EOL>if tag_type == '<STR_LIT:!>':<EOL><INDENT>return _CommentNode()<EOL><DEDENT>if tag_type == '<STR_LIT:=>':<EOL><INDENT>delimiters = tag_key.split()<EOL>self._change_delimiters(delimiters)<EOL>return _ChangeNode(delimiters)<EOL><DEDENT>if tag_type == '<STR_LIT>':<EOL><INDENT>return _EscapeNode(tag_key)<EOL><DEDENT>i...
Create and return a non-section node for the parse tree.
f767:c8:m4
def _make_section_node(self, template, tag_type, tag_key, parsed_section,<EOL>section_start_index, section_end_index):
if tag_type == '<STR_LIT:#>':<EOL><INDENT>return _SectionNode(tag_key, parsed_section, self._delimiters,<EOL>template, section_start_index, section_end_index)<EOL><DEDENT>if tag_type == '<STR_LIT>':<EOL><INDENT>return _InvertedNode(tag_key, parsed_section)<EOL><DEDENT>raise Exception("<STR_LIT>" % repr(tag_type))<EOL>
Create and return a section node for the parse tree.
f767:c8:m5
def mock_literal(s):
if isinstance(s, str):<EOL><INDENT>u = str(s)<EOL><DEDENT>else:<EOL><INDENT>u = str(s, encoding='<STR_LIT:ascii>')<EOL><DEDENT>return u.upper()<EOL>
For use as the literal keyword argument to the RenderEngine constructor. Arguments: s: a byte string or unicode string.
f768:m1
def _engine(self):
renderer = Renderer(string_encoding='<STR_LIT:utf-8>', missing_tags='<STR_LIT:strict>')<EOL>engine = renderer._make_render_engine()<EOL>return engine<EOL>
Create and return a default RenderEngine for testing.
f768:c1:m0
def _assert_render(self, expected, template, *context, **kwargs):
partials = kwargs.get('<STR_LIT>')<EOL>engine = kwargs.get('<STR_LIT>', self._engine())<EOL>if partials is not None:<EOL><INDENT>engine.resolve_partial = lambda key: str(partials[key])<EOL><DEDENT>context = ContextStack(*context)<EOL>actual = engine.render(str(template), context)<EOL>self.assertString(actual=actual, ex...
Test rendering the given template using the given context.
f768:c1:m1
def _make_specloader():
<EOL>def to_unicode(s, encoding=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>if encoding is None:<EOL><INDENT>encoding = '<STR_LIT:ascii>'<EOL><DEDENT>return unicode(s, encoding, '<STR_LIT:strict>')<EOL><DEDENT>loader = Loader(file_encoding='<STR_LIT:ascii>', to_unicode=to_unicode)<EOL>return SpecLoader(loader=loader)<EOL>
Return a default SpecLoader instance for testing purposes.
f769:m0
def setUp(self):
defaults = [<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'<EOL>]<EOL>self.saved = {}<EOL>for e in defaults:<EOL><INDENT>self.saved[e] = getattr(pystache.defaults, e)<EOL><DEDENT>
Save the defaults.
f771:c0:m0
def _make_renderer():
renderer = Renderer(string_encoding='<STR_LIT:ascii>', file_encoding='<STR_LIT:ascii>')<EOL>return renderer<EOL>
Return a default Renderer instance for testing purposes.
f772:m0
def _make_renderer(self):
return _make_renderer()<EOL>
Return a default Renderer instance for testing purposes.
f772:c2:m0
def assertNotFound(self, item, key):
self.assertIs(_get_value(item, key), _NOT_FOUND)<EOL>
Assert that a call to _get_value() returns _NOT_FOUND.
f773:c2:m0
def _assert_paths(self, actual, expected):
self.assertEqual(actual, expected)<EOL>
Assert that two paths are the same.
f775:c0:m2
def main(sys_argv):
<EOL>print("<STR_LIT>" % repr(sys_argv))<EOL>should_source_exist = False<EOL>spec_test_dir = None<EOL>project_dir = None<EOL>if len(sys_argv) > <NUM_LIT:1> and sys_argv[<NUM_LIT:1>] == FROM_SOURCE_OPTION:<EOL><INDENT>should_source_exist = True<EOL>sys_argv.pop(<NUM_LIT:1>)<EOL><DEDENT>try:<EOL><INDENT>project_dir = sys...
Run all tests in the project. Arguments: sys_argv: a reference to sys.argv.
f779:m2
def html_escape(u):
u = _DEFAULT_TAG_ESCAPE(u)<EOL>return u.replace("<STR_LIT:'>", '<STR_LIT>')<EOL>
An html escape function that behaves the same in both Python 2 and 3. This function is needed because single quotes are escaped in Python 3 (to '&#x27;'), but not in Python 2. The global defaults.TAG_ESCAPE can be set to this function in the setUp() and tearDown() of unittest test cases, for example, for consistent t...
f781:m1
def get_data_path(file_name=None):
if file_name is None:<EOL><INDENT>file_name = "<STR_LIT>"<EOL><DEDENT>return os.path.join(DATA_DIR, file_name)<EOL>
Return the path to a file in the test data directory.
f781:m2
def _find_files(root_dir, should_include):
paths = [] <EOL>is_module = lambda path: path.endswith("<STR_LIT>")<EOL>for dir_path, dir_names, file_names in os.walk(root_dir):<EOL><INDENT>new_paths = [os.path.join(dir_path, file_name) for file_name in file_names]<EOL>new_paths = list(filter(is_module, new_paths))<EOL>new_paths = list(filter(should_include, new_pa...
Return a list of paths to all modules below the given directory. Arguments: should_include: a function that accepts a file path and returns True or False.
f781:m3
def _make_module_names(package_dir, paths):
package_dir = os.path.abspath(package_dir)<EOL>package_name = os.path.split(package_dir)[<NUM_LIT:1>]<EOL>prefix_length = len(package_dir)<EOL>module_names = []<EOL>for path in paths:<EOL><INDENT>path = os.path.abspath(path) <EOL>rel_path = path[prefix_length:] <EOL>rel_path = os.path.splitext(rel_path)[<NUM_LIT:0>] ...
Return a list of fully-qualified module names given a list of module paths.
f781:m4
def get_module_names(package_dir=None, should_include=None):
if package_dir is None:<EOL><INDENT>package_dir = PACKAGE_DIR<EOL><DEDENT>if should_include is None:<EOL><INDENT>should_include = lambda path: True<EOL><DEDENT>paths = _find_files(package_dir, should_include)<EOL>names = _make_module_names(package_dir, paths)<EOL>names.sort()<EOL>return names<EOL>
Return a list of fully-qualified module names in the given package.
f781:m5
def assertString(self, actual, expected, format=None):
if format is None:<EOL><INDENT>format = "<STR_LIT:%s>"<EOL><DEDENT>details = """<STR_LIT>""" % (expected, actual, repr(expected), repr(actual))<EOL>def make_message(reason):<EOL><INDENT>description = details % reason<EOL>return format % description<EOL><DEDENT>self.assertEqual(actual, expected, make_message("<STR_LIT>"...
Assert that the given strings are equal and have the same type. Arguments: format: a format string containing a single conversion specifier %s. Defaults to "%s".
f781:c0:m0
def _convert_children(node):
if not isinstance(node, (list, dict)):<EOL><INDENT>return<EOL><DEDENT>if isinstance(node, list):<EOL><INDENT>for child in node:<EOL><INDENT>_convert_children(child)<EOL><DEDENT>return<EOL><DEDENT>for key in list(node.keys()):<EOL><INDENT>val = node[key]<EOL>if not isinstance(val, dict) or val.get('<STR_LIT>') != '<STR_...
Recursively convert to functions all "code strings" below the node. This function is needed only for the json format.
f799:m3
def parse(u):
<EOL>if yaml is None:<EOL><INDENT>return json.loads(u)<EOL><DEDENT>def code_constructor(loader, node):<EOL><INDENT>value = loader.construct_mapping(node)<EOL>return eval(value['<STR_LIT>'], {})<EOL><DEDENT>yaml.add_constructor('<STR_LIT>', code_constructor)<EOL>return yaml.load(u)<EOL>
Parse the contents of a spec test file, and return a dict. Arguments: u: a unicode string.
f799:m6
def _convert_2to3(path):
base, ext = os.path.splitext(path)<EOL>new_path = "<STR_LIT>" % (base, ext)<EOL>copyfile(path, new_path)<EOL>args = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', new_path]<EOL>lib2to3main("<STR_LIT>", args=args)<EOL>return new_path<EOL>
Convert the given file, and return the path to the converted files.
f802:m1
def _convert_paths(paths):
new_paths = []<EOL>for path in paths:<EOL><INDENT>new_path = _convert_2to3(path)<EOL>new_paths.append(new_path)<EOL><DEDENT>return new_paths<EOL>
Convert the given files, and return the paths to the converted files.
f802:m2
def _get_value(context, key):
if isinstance(context, dict):<EOL><INDENT>if key in context:<EOL><INDENT>return context[key]<EOL><DEDENT><DEDENT>elif type(context).__module__ != _BUILTIN_MODULE:<EOL><INDENT>try:<EOL><INDENT>attr = getattr(context, key)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if callable(attr)...
Retrieve a key's value from a context item. Returns _NOT_FOUND if the key does not exist. The ContextStack.get() docstring documents this function's intended behavior.
f803:m0
def __init__(self, *items):
self._stack = list(items)<EOL>
Construct an instance, and initialize the private stack. The *items arguments are the items with which to populate the initial stack. Items in the argument list are added to the stack in order so that, in particular, items at the end of the argument list are queried first when querying the stack. Caution: items shou...
f803:c2:m0
def __repr__(self):
return "<STR_LIT>" % (self.__class__.__name__, tuple(self._stack))<EOL>
Return a string representation of the instance. For example-- >>> context = ContextStack({'alpha': 'abc'}, {'numeric': 123}) >>> repr(context) "ContextStack({'alpha': 'abc'}, {'numeric': 123})"
f803:c2:m1
@staticmethod<EOL><INDENT>def create(*context, **kwargs):<DEDENT>
items = context<EOL>context = ContextStack()<EOL>for item in items:<EOL><INDENT>if item is None:<EOL><INDENT>continue<EOL><DEDENT>if isinstance(item, ContextStack):<EOL><INDENT>context._stack.extend(item._stack)<EOL><DEDENT>else:<EOL><INDENT>context.push(item)<EOL><DEDENT><DEDENT>if kwargs:<EOL><INDENT>context.push(kwa...
Build a ContextStack instance from a sequence of context-like items. This factory-style method is more general than the ContextStack class's constructor in that, unlike the constructor, the argument list can itself contain ContextStack instances. Here is an example illustrating various aspects of this method: >>> ob...
f803:c2:m2
def get(self, name):
if name == '<STR_LIT:.>':<EOL><INDENT>try:<EOL><INDENT>return self.top()<EOL><DEDENT>except IndexError:<EOL><INDENT>raise KeyNotFoundError("<STR_LIT:.>", "<STR_LIT>")<EOL><DEDENT><DEDENT>parts = name.split('<STR_LIT:.>')<EOL>try:<EOL><INDENT>result = self._get_simple(parts[<NUM_LIT:0>])<EOL><DEDENT>except KeyNotFoundEr...
Resolve a dotted name against the current context stack. This function follows the rules outlined in the section of the spec regarding tag interpolation. This function returns the value as is and does not coerce the return value to a string. Arguments: name: a dotted or non-dotted name. default: the value to r...
f803:c2:m3
def _get_simple(self, name):
for item in reversed(self._stack):<EOL><INDENT>result = _get_value(item, name)<EOL>if result is not _NOT_FOUND:<EOL><INDENT>return result<EOL><DEDENT><DEDENT>raise KeyNotFoundError(name, "<STR_LIT>")<EOL>
Query the stack for a non-dotted name.
f803:c2:m4
def push(self, item):
self._stack.append(item)<EOL>
Push an item onto the stack.
f803:c2:m5
def pop(self):
return self._stack.pop()<EOL>
Pop an item off of the stack, and return it.
f803:c2:m6
def top(self):
return self._stack[-<NUM_LIT:1>]<EOL>
Return the item last added to the stack.
f803:c2:m7
def copy(self):
return ContextStack(*self._stack)<EOL>
Return a copy of this instance.
f803:c2:m8
def context_get(stack, name):
return stack.get(name)<EOL>
Find and return a name from a ContextStack instance.
f805:m0
def __init__(self, literal=None, escape=None, resolve_context=None,<EOL>resolve_partial=None, to_str=None):
self.escape = escape<EOL>self.literal = literal<EOL>self.resolve_context = resolve_context<EOL>self.resolve_partial = resolve_partial<EOL>self.to_str = to_str<EOL>
Arguments: literal: the function used to convert unescaped variable tag values to unicode, e.g. the value corresponding to a tag "{{{name}}}". The function should accept a string of type str or unicode (or a subclass) and return a string of type unicode (but not a proper subclass of unicode). ...
f805:c0:m0
def fetch_string(self, context, name):
val = self.resolve_context(context, name)<EOL>if callable(val):<EOL><INDENT>return self._render_value(val(), context)<EOL><DEDENT>if not is_string(val):<EOL><INDENT>return self.to_str(val)<EOL><DEDENT>return val<EOL>
Get a value from the given context as a basestring instance.
f805:c0:m1
def fetch_section_data(self, context, name):
data = self.resolve_context(context, name)<EOL>if not data:<EOL><INDENT>data = []<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>iter(data)<EOL><DEDENT>except TypeError:<EOL><INDENT>data = [data]<EOL><DEDENT>else:<EOL><INDENT>if is_string(data) or isinstance(data, dict):<EOL><INDENT>data = [data]<EOL><DEDENT><DEDENT><D...
Fetch the value of a section as a list.
f805:c0:m2
def _render_value(self, val, context, delimiters=None):
if not is_string(val):<EOL><INDENT>val = self.to_str(val)<EOL><DEDENT>if type(val) is not unicode:<EOL><INDENT>val = self.literal(val)<EOL><DEDENT>return self.render(val, context, delimiters)<EOL>
Render an arbitrary value.
f805:c0:m3
def render(self, template, context_stack, delimiters=None):
parsed_template = parse(template, delimiters)<EOL>return parsed_template.render(self, context_stack)<EOL>
Render a unicode template string, and return as unicode. Arguments: template: a template string of type unicode (but not a proper subclass of unicode). context_stack: a ContextStack instance.
f805:c0:m4
def render(template, context=None, **kwargs):
renderer = Renderer()<EOL>return renderer.render(template, context, **kwargs)<EOL>
Return the given template string rendered using the given context.
f806:m0
def _find_relative(self, spec):
if spec.template_rel_path is not None:<EOL><INDENT>return os.path.split(spec.template_rel_path)<EOL><DEDENT>locator = self.loader._make_locator()<EOL>if spec.template_name is not None:<EOL><INDENT>template_name = spec.template_name<EOL><DEDENT>else:<EOL><INDENT>template_name = locator.make_template_name(spec)<EOL><DEDE...
Return the path to the template as a relative (dir, file_name) pair. The directory returned is relative to the directory containing the class definition of the given object. The method returns None for this directory if the directory is unknown without first searching the search directories.
f807:c0:m1
def _find(self, spec):
if spec.template_path is not None:<EOL><INDENT>return spec.template_path<EOL><DEDENT>dir_path, file_name = self._find_relative(spec)<EOL>locator = self.loader._make_locator()<EOL>if dir_path is None:<EOL><INDENT>path = locator.find_object(spec, self.loader.search_dirs, file_name=file_name)<EOL><DEDENT>else:<EOL><INDENT...
Find and return the path to the template associated to the instance.
f807:c0:m2
def load(self, spec):
if spec.template is not None:<EOL><INDENT>return self.loader.unicode(spec.template, spec.template_encoding)<EOL><DEDENT>path = self._find(spec)<EOL>return self.loader.read(path, spec.template_encoding)<EOL>
Find and return the template associated to a TemplateSpec instance. Returns the template as a unicode string. Arguments: spec: a TemplateSpec instance.
f807:c0:m3
def parse_args(sys_argv, usage):
args = sys_argv[<NUM_LIT:1>:]<EOL>parser = OptionParser(usage=usage)<EOL>options, args = parser.parse_args(args)<EOL>template, context = args<EOL>return template, context<EOL>
Return an OptionParser for the script.
f808:m0
def is_string(obj):
return isinstance(obj, _STRING_TYPES)<EOL>
Return whether the given object is a byte string or unicode string. This function is provided for compatibility with both Python 2 and 3 when using 2to3.
f811:m1
def read(path):
<EOL>f = open(path, '<STR_LIT:rb>')<EOL>try:<EOL><INDENT>return f.read()<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT>
Return the contents of a text file as a byte string.
f811:m2
def __init__(self, file_encoding=None, extension=None, to_unicode=None,<EOL>search_dirs=None):
if extension is None:<EOL><INDENT>extension = defaults.TEMPLATE_EXTENSION<EOL><DEDENT>if file_encoding is None:<EOL><INDENT>file_encoding = defaults.FILE_ENCODING<EOL><DEDENT>if search_dirs is None:<EOL><INDENT>search_dirs = defaults.SEARCH_DIRS<EOL><DEDENT>if to_unicode is None:<EOL><INDENT>to_unicode = _make_to_unico...
Construct a template loader instance. Arguments: extension: the template file extension, without the leading dot. Pass False for no extension (e.g. to use extensionless template files). Defaults to the package default. file_encoding: the name of the encoding to use when converting file contents to u...
f812:c0:m0
def unicode(self, s, encoding=None):
if isinstance(s, unicode):<EOL><INDENT>return unicode(s)<EOL><DEDENT>return self.to_unicode(s, encoding)<EOL>
Convert a string to unicode using the given encoding, and return it. This function uses the underlying to_unicode attribute. Arguments: s: a basestring instance to convert to unicode. Unlike Python's built-in unicode() function, it is okay to pass unicode strings to this function. (Passing a unicode stri...
f812:c0:m2
def read(self, path, encoding=None):
b = common.read(path)<EOL>if encoding is None:<EOL><INDENT>encoding = self.file_encoding<EOL><DEDENT>return self.unicode(b, encoding)<EOL>
Read the template at the given path, and return it as a unicode string.
f812:c0:m3
def load_file(self, file_name):
locator = self._make_locator()<EOL>path = locator.find_file(file_name, self.search_dirs)<EOL>return self.read(path)<EOL>
Find and return the template with the given file name. Arguments: file_name: the file name of the template.
f812:c0:m4
def load_name(self, name):
locator = self._make_locator()<EOL>path = locator.find_name(name, self.search_dirs)<EOL>return self.read(path)<EOL>
Find and return the template with the given template name. Arguments: name: the name of the template.
f812:c0:m5
def load_object(self, obj):
locator = self._make_locator()<EOL>path = locator.find_object(obj, self.search_dirs)<EOL>return self.read(path)<EOL>
Find and return the template associated to the given object. Arguments: obj: an instance of a user-defined class. search_dirs: the list of directories in which to search.
f812:c0:m6
def add(self, node):
self._parse_tree.append(node)<EOL>
Arguments: node: a unicode string or node object instance. See the class docstring for information.
f814:c0:m2
def render(self, engine, context):
<EOL>def get_unicode(node):<EOL><INDENT>if type(node) is unicode:<EOL><INDENT>return node<EOL><DEDENT>return node.render(engine, context)<EOL><DEDENT>parts = map(get_unicode, self._parse_tree)<EOL>s = '<STR_LIT>'.join(parts)<EOL>return unicode(s)<EOL>
Returns: a string of type unicode.
f814:c0:m3