_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q7500
CSSParser.parse_attribute_selector
train
def parse_attribute_selector(self, sel, m, has_selector, quirks): """Create attribute selector from the returned regex match.""" inverse = False op = m.group('cmp') case = util.lower(m.group('case')) if m.group('case') else None parts = [css_unescape(a) for a in m.group('ns_attr...
python
{ "resource": "" }
q7501
CSSParser.parse_tag_pattern
train
def parse_tag_pattern(self, sel, m, has_selector): """Parse tag pattern from regex match.""" parts = [css_unescape(x) for x in m.group(0).split('|')] if len(parts) > 1: prefix = parts[0] tag = parts[1] else: tag = parts[0] prefix = None ...
python
{ "resource": "" }
q7502
CSSParser.parse_pseudo_class_custom
train
def parse_pseudo_class_custom(self, sel, m, has_selector): """ Parse custom pseudo class alias. Compile custom selectors as we need them. When compiling a custom selector, set it to `None` in the dictionary so we can avoid an infinite loop. """ pseudo = util.lower(css_u...
python
{ "resource": "" }
q7503
CSSParser.parse_pseudo_nth
train
def parse_pseudo_nth(self, sel, m, has_selector, iselector): """Parse `nth` pseudo.""" mdict = m.groupdict() if mdict.get('pseudo_nth_child'): postfix = '_child' else: postfix = '_type' mdict['name'] = util.lower(css_unescape(mdict['name'])) conte...
python
{ "resource": "" }
q7504
CSSParser.parse_pseudo_open
train
def parse_pseudo_open(self, sel, name, has_selector, iselector, index): """Parse pseudo with opening bracket.""" flags = FLG_PSEUDO | FLG_OPEN if name == ':not': flags |= FLG_NOT if name == ':has': flags |= FLG_RELATIVE sel.selectors.append(self.parse_se...
python
{ "resource": "" }
q7505
CSSParser.parse_class_id
train
def parse_class_id(self, sel, m, has_selector): """Parse HTML classes and ids.""" selector = m.group(0) if selector.startswith('.'): sel.classes.append(css_unescape(selector[1:])) else: sel.ids.append(css_unescape(selector[1:])) has_selector = True ...
python
{ "resource": "" }
q7506
CSSParser.parse_pseudo_contains
train
def parse_pseudo_contains(self, sel, m, has_selector): """Parse contains.""" values = m.group('values') patterns = [] for token in RE_VALUES.finditer(values): if token.group('split'): continue value = token.group('value') if value.star...
python
{ "resource": "" }
q7507
CSSParser.parse_pseudo_lang
train
def parse_pseudo_lang(self, sel, m, has_selector): """Parse pseudo language.""" values = m.group('values') patterns = [] for token in RE_VALUES.finditer(values): if token.group('split'): continue value = token.group('value') if value.s...
python
{ "resource": "" }
q7508
CSSParser.parse_pseudo_dir
train
def parse_pseudo_dir(self, sel, m, has_selector): """Parse pseudo direction.""" value = ct.SEL_DIR_LTR if util.lower(m.group('dir')) == 'ltr' else ct.SEL_DIR_RTL sel.flags |= value has_selector = True return has_selector
python
{ "resource": "" }
q7509
CSSParser.selector_iter
train
def selector_iter(self, pattern): """Iterate selector tokens.""" # Ignore whitespace and comments at start and end of pattern m = RE_WS_BEGIN.search(pattern) index = m.end(0) if m else 0 m = RE_WS_END.search(pattern) end = (m.start(0) - 1) if m else (len(pattern) - 1) ...
python
{ "resource": "" }
q7510
CSSParser.process_selectors
train
def process_selectors(self, index=0, flags=0): """ Process selectors. We do our own selectors as BeautifulSoup4 has some annoying quirks, and we don't really need to do nth selectors or siblings or descendants etc. """ return self.parse_selectors(self.selector_i...
python
{ "resource": "" }
q7511
find_label
train
def find_label(label, label_color, label_description): """Find label.""" edit = None for name, values in label_list.items(): color, description = values if isinstance(name, tuple): old_name = name[0] new_name = name[1] else: old_name = name ...
python
{ "resource": "" }
q7512
update_labels
train
def update_labels(repo): """Update labels.""" updated = set() for label in repo.get_labels(): edit = find_label(label.name, label.color, label.description) if edit is not None: print(' Updating {}: #{} "{}"'.format(edit.new, edit.color, edit.description)) label.edi...
python
{ "resource": "" }
q7513
get_auth
train
def get_auth(): """Get authentication.""" import getpass user = input("User Name: ") # noqa pswd = getpass.getpass('Password: ') return Github(user, pswd)
python
{ "resource": "" }
q7514
parse_version
train
def parse_version(ver, pre=False): """Parse version into a comparable Version tuple.""" m = RE_VER.match(ver) # Handle major, minor, micro major = int(m.group('major')) minor = int(m.group('minor')) if m.group('minor') else 0 micro = int(m.group('micro')) if m.group('micro') else 0 # Hand...
python
{ "resource": "" }
q7515
Version._get_canonical
train
def _get_canonical(self): """Get the canonical output string.""" # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed.. if self.micro == 0: ver = "{}.{}".format(self.major, self.minor) else: ver = "{}.{}.{}".format(self.major, self....
python
{ "resource": "" }
q7516
Document.assert_valid_input
train
def assert_valid_input(cls, tag): """Check if valid input tag or document.""" # Fail on unexpected types. if not cls.is_tag(tag): raise TypeError("Expected a BeautifulSoup 'Tag', but instead recieved type {}".format(type(tag)))
python
{ "resource": "" }
q7517
Document.is_special_string
train
def is_special_string(obj): """Is special string.""" import bs4 return isinstance(obj, (bs4.Comment, bs4.Declaration, bs4.CData, bs4.ProcessingInstruction))
python
{ "resource": "" }
q7518
Document.is_iframe
train
def is_iframe(self, el): """Check if element is an `iframe`.""" return ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'iframe') and self.is_html_tag(el)
python
{ "resource": "" }
q7519
Document.is_root
train
def is_root(self, el): """ Return whether element is a root element. We check that the element is the root of the tree (which we have already pre-calculated), and we check if it is the root element under an `iframe`. """ root = self.root and self.root is el if n...
python
{ "resource": "" }
q7520
Document.get_contents
train
def get_contents(self, el, no_iframe=False): """Get contents or contents in reverse.""" if not no_iframe or not self.is_iframe(el): for content in el.contents: yield content
python
{ "resource": "" }
q7521
Document.get_descendants
train
def get_descendants(self, el, tags=True, no_iframe=False): """Get descendants.""" if not no_iframe or not self.is_iframe(el): next_good = None for child in el.descendants: if next_good is not None: if child is not next_good: ...
python
{ "resource": "" }
q7522
Document.get_parent
train
def get_parent(self, el, no_iframe=False): """Get parent.""" parent = el.parent if no_iframe and parent is not None and self.is_iframe(parent): parent = None return parent
python
{ "resource": "" }
q7523
Document.get_next_tag
train
def get_next_tag(cls, el): """Get next sibling tag.""" sibling = el.next_sibling while not cls.is_tag(sibling) and sibling is not None: sibling = sibling.next_sibling return sibling
python
{ "resource": "" }
q7524
Document.get_previous_tag
train
def get_previous_tag(cls, el): """Get previous sibling tag.""" sibling = el.previous_sibling while not cls.is_tag(sibling) and sibling is not None: sibling = sibling.previous_sibling return sibling
python
{ "resource": "" }
q7525
Document.get_attribute_by_name
train
def get_attribute_by_name(el, name, default=None): """Get attribute by name.""" value = default if el._is_xml: try: value = el.attrs[name] except KeyError: pass else: for k, v in el.attrs.items(): if uti...
python
{ "resource": "" }
q7526
Document.get_text
train
def get_text(self, el, no_iframe=False): """Get text.""" return ''.join( [node for node in self.get_descendants(el, tags=False, no_iframe=no_iframe) if self.is_content_string(node)] )
python
{ "resource": "" }
q7527
Inputs.validate_day
train
def validate_day(year, month, day): """Validate day.""" max_days = LONG_MONTH if month == FEB: max_days = FEB_LEAP_MONTH if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0) else FEB_MONTH elif month in MONTHS_30: max_days = SHORT_MONTH return ...
python
{ "resource": "" }
q7528
Inputs.validate_week
train
def validate_week(year, week): """Validate week.""" max_week = datetime.strptime("{}-{}-{}".format(12, 31, year), "%m-%d-%Y").isocalendar()[1] if max_week == 1: max_week = 53 return 1 <= week <= max_week
python
{ "resource": "" }
q7529
Inputs.parse_value
train
def parse_value(cls, itype, value): """Parse the input value.""" parsed = None if itype == "date": m = RE_DATE.match(value) if m: year = int(m.group('year'), 10) month = int(m.group('month'), 10) day = int(m.group('day'), 1...
python
{ "resource": "" }
q7530
CSSMatch.get_tag_ns
train
def get_tag_ns(self, el): """Get tag namespace.""" if self.supports_namespaces(): namespace = '' ns = el.namespace if ns: namespace = ns else: namespace = NS_XHTML return namespace
python
{ "resource": "" }
q7531
CSSMatch.get_tag
train
def get_tag(self, el): """Get tag.""" name = self.get_tag_name(el) return util.lower(name) if name is not None and not self.is_xml else name
python
{ "resource": "" }
q7532
CSSMatch.get_prefix
train
def get_prefix(self, el): """Get prefix.""" prefix = self.get_prefix_name(el) return util.lower(prefix) if prefix is not None and not self.is_xml else prefix
python
{ "resource": "" }
q7533
CSSMatch.find_bidi
train
def find_bidi(self, el): """Get directionality from element text.""" for node in self.get_children(el, tags=False): # Analyze child text nodes if self.is_tag(node): # Avoid analyzing certain elements specified in the specification. direction = D...
python
{ "resource": "" }
q7534
CSSMatch.match_attribute_name
train
def match_attribute_name(self, el, attr, prefix): """Match attribute name and return value if it exists.""" value = None if self.supports_namespaces(): value = None # If we have not defined namespaces, we can't very well find them, so don't bother trying. if ...
python
{ "resource": "" }
q7535
CSSMatch.match_namespace
train
def match_namespace(self, el, tag): """Match the namespace of the element.""" match = True namespace = self.get_tag_ns(el) default_namespace = self.namespaces.get('') tag_ns = '' if tag.prefix is None else self.namespaces.get(tag.prefix, None) # We must match the default...
python
{ "resource": "" }
q7536
CSSMatch.match_attributes
train
def match_attributes(self, el, attributes): """Match attributes.""" match = True if attributes: for a in attributes: value = self.match_attribute_name(el, a.attribute, a.prefix) pattern = a.xml_type_pattern if self.is_xml and a.xml_type_pattern else a...
python
{ "resource": "" }
q7537
CSSMatch.match_tagname
train
def match_tagname(self, el, tag): """Match tag name.""" name = (util.lower(tag.name) if not self.is_xml and tag.name is not None else tag.name) return not ( name is not None and name not in (self.get_tag(el), '*') )
python
{ "resource": "" }
q7538
CSSMatch.match_tag
train
def match_tag(self, el, tag): """Match the tag.""" match = True if tag is not None: # Verify namespace if not self.match_namespace(el, tag): match = False if not self.match_tagname(el, tag): match = False return match
python
{ "resource": "" }
q7539
CSSMatch.match_past_relations
train
def match_past_relations(self, el, relation): """Match past relationship.""" found = False if relation[0].rel_type == REL_PARENT: parent = self.get_parent(el, no_iframe=self.iframe_restrict) while not found and parent: found = self.match_selectors(parent,...
python
{ "resource": "" }
q7540
CSSMatch.match_future_child
train
def match_future_child(self, parent, relation, recursive=False): """Match future child.""" match = False children = self.get_descendants if recursive else self.get_children for child in children(parent, no_iframe=self.iframe_restrict): match = self.match_selectors(child, rel...
python
{ "resource": "" }
q7541
CSSMatch.match_future_relations
train
def match_future_relations(self, el, relation): """Match future relationship.""" found = False if relation[0].rel_type == REL_HAS_PARENT: found = self.match_future_child(el, relation, True) elif relation[0].rel_type == REL_HAS_CLOSE_PARENT: found = self.match_fut...
python
{ "resource": "" }
q7542
CSSMatch.match_relations
train
def match_relations(self, el, relation): """Match relationship to other elements.""" found = False if relation[0].rel_type.startswith(':'): found = self.match_future_relations(el, relation) else: found = self.match_past_relations(el, relation) return fo...
python
{ "resource": "" }
q7543
CSSMatch.match_id
train
def match_id(self, el, ids): """Match element's ID.""" found = True for i in ids: if i != self.get_attribute_by_name(el, 'id', ''): found = False break return found
python
{ "resource": "" }
q7544
CSSMatch.match_classes
train
def match_classes(self, el, classes): """Match element's classes.""" current_classes = self.get_classes(el) found = True for c in classes: if c not in current_classes: found = False break return found
python
{ "resource": "" }
q7545
CSSMatch.match_nth_tag_type
train
def match_nth_tag_type(self, el, child): """Match tag type for `nth` matches.""" return( (self.get_tag(child) == self.get_tag(el)) and (self.get_tag_ns(child) == self.get_tag_ns(el)) )
python
{ "resource": "" }
q7546
CSSMatch.match_nth
train
def match_nth(self, el, nth): """Match `nth` elements.""" matched = True for n in nth: matched = False if n.selectors and not self.match_selectors(el, n.selectors): break parent = self.get_parent(el) if parent is None: ...
python
{ "resource": "" }
q7547
CSSMatch.match_subselectors
train
def match_subselectors(self, el, selectors): """Match selectors.""" match = True for sel in selectors: if not self.match_selectors(el, sel): match = False return match
python
{ "resource": "" }
q7548
CSSMatch.match_contains
train
def match_contains(self, el, contains): """Match element if it contains text.""" match = True content = None for contain_list in contains: if content is None: content = self.get_text(el, no_iframe=self.is_html) found = False for text i...
python
{ "resource": "" }
q7549
CSSMatch.match_lang
train
def match_lang(self, el, langs): """Match languages.""" match = False has_ns = self.supports_namespaces() root = self.root has_html_namespace = self.has_html_namespace # Walk parents looking for `lang` (HTML) or `xml:lang` XML property. parent = el found...
python
{ "resource": "" }
q7550
CSSMatch.match_dir
train
def match_dir(self, el, directionality): """Check directionality.""" # If we have to match both left and right, we can't match either. if directionality & ct.SEL_DIR_LTR and directionality & ct.SEL_DIR_RTL: return False if el is None or not self.is_html_tag(el): ...
python
{ "resource": "" }
q7551
CSSMatch.match_range
train
def match_range(self, el, condition): """ Match range. Behavior is modeled after what we see in browsers. Browsers seem to evaluate if the value is out of range, and if not, it is in range. So a missing value will not evaluate out of range; therefore, value is in range. Personal...
python
{ "resource": "" }
q7552
CSSMatch.match_defined
train
def match_defined(self, el): """ Match defined. `:defined` is related to custom elements in a browser. - If the document is XML (not XHTML), all tags will match. - Tags that are not custom (don't have a hyphen) are marked defined. - If the tag has a prefix (without or w...
python
{ "resource": "" }
q7553
CSSMatch.match_selectors
train
def match_selectors(self, el, selectors): """Check if element matches one of the selectors.""" match = False is_not = selectors.is_not is_html = selectors.is_html # Internal selector lists that use the HTML flag, will automatically get the `html` namespace. if is_html: ...
python
{ "resource": "" }
q7554
CSSMatch.select
train
def select(self, limit=0): """Match all tags under the targeted tag.""" if limit < 1: limit = None for child in self.get_descendants(self.tag): if self.match(child): yield child if limit is not None: limit -= 1 ...
python
{ "resource": "" }
q7555
CSSMatch.filter
train
def filter(self): # noqa A001 """Filter tag's children.""" return [tag for tag in self.get_contents(self.tag) if not self.is_navigable_string(tag) and self.match(tag)]
python
{ "resource": "" }
q7556
SoupSieve.icomments
train
def icomments(self, tag, limit=0): """Iterate comments only.""" for comment in CommentsMatch(tag).get_comments(limit): yield comment
python
{ "resource": "" }
q7557
uord
train
def uord(c): """Get Unicode ordinal.""" if len(c) == 2: # pragma: no cover high, low = [ord(p) for p in c] ordinal = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000 else: ordinal = ord(c) return ordinal
python
{ "resource": "" }
q7558
warn_deprecated
train
def warn_deprecated(message, stacklevel=2): # pragma: no cover """Warn deprecated.""" warnings.warn( message, category=DeprecationWarning, stacklevel=stacklevel )
python
{ "resource": "" }
q7559
get_pattern_context
train
def get_pattern_context(pattern, index): """Get the pattern context.""" last = 0 current_line = 1 col = 1 text = [] line = 1 # Split pattern by newline and handle the text before the newline for m in RE_PATTERN_LINE_SPLIT.finditer(pattern): linetext = pattern[last:m.start(0)] ...
python
{ "resource": "" }
q7560
warn_quirks
train
def warn_quirks(message, recommend, pattern, index): """Warn quirks.""" import traceback import bs4 # noqa: F401 # Acquire source code line context paths = (MODULE, sys.modules['bs4'].__path__[0]) tb = traceback.extract_stack() previous = None filename = None lineno = None for...
python
{ "resource": "" }
q7561
compile
train
def compile(pattern, namespaces=None, flags=0, **kwargs): # noqa: A001 """Compile CSS pattern.""" if namespaces is not None: namespaces = ct.Namespaces(**namespaces) custom = kwargs.get('custom') if custom is not None: custom = ct.CustomSelectors(**custom) if isinstance(pattern, ...
python
{ "resource": "" }
q7562
match
train
def match(select, tag, namespaces=None, flags=0, **kwargs): """Match node.""" return compile(select, namespaces, flags, **kwargs).match(tag)
python
{ "resource": "" }
q7563
filter
train
def filter(select, iterable, namespaces=None, flags=0, **kwargs): # noqa: A001 """Filter list of nodes.""" return compile(select, namespaces, flags, **kwargs).filter(iterable)
python
{ "resource": "" }
q7564
select
train
def select(select, tag, namespaces=None, limit=0, flags=0, **kwargs): """Select the specified tags.""" return compile(select, namespaces, flags, **kwargs).select(tag, limit)
python
{ "resource": "" }
q7565
ListableApiResource.all
train
def all(cls, connection=None, **params): """ Returns first page if no params passed in as a list. """ request = cls._make_request('GET', cls._get_all_path(), connection, params=params) return cls._create_object(request, connection=connection)
python
{ "resource": "" }
q7566
ListableApiResource.iterall
train
def iterall(cls, connection=None, **kwargs): """ Returns a autopaging generator that yields each object returned one by one. """ try: limit = kwargs['limit'] except KeyError: limit = None try: page = kwargs['page'] except ...
python
{ "resource": "" }
q7567
Connection.update
train
def update(self, resource, rid, updates): """ Updates the resource with id 'rid' with the given updates dictionary. """ if resource[-1] != '/': resource += '/' resource += str(rid) return self.put(resource, data=updates)
python
{ "resource": "" }
q7568
Connection.delete
train
def delete(self, resource, rid=None): # note that rid can't be 0 - problem? """ Deletes the resource with given id 'rid', or all resources of given type if rid is not supplied. """ if rid: if resource[-1] != '/': resource += '/' resource += str(ri...
python
{ "resource": "" }
q7569
Connection.put
train
def put(self, url, data): """ Make a PUT request to save data. data should be a dictionary. """ response = self._run_method('PUT', url, data=data) log.debug("OUTPUT: %s" % response.content) return self._handle_response(url, response)
python
{ "resource": "" }
q7570
Connection.post
train
def post(self, url, data, headers={}): """ POST request for creating new objects. data should be a dictionary. """ response = self._run_method('POST', url, data=data, headers=headers) return self._handle_response(url, response)
python
{ "resource": "" }
q7571
Connection._handle_response
train
def _handle_response(self, url, res, suppress_empty=True): """ Returns parsed JSON or raises an exception appropriately. """ self._last_response = res result = {} if res.status_code in (200, 201, 202): try: result = res.json() excep...
python
{ "resource": "" }
q7572
OAuthConnection.fetch_token
train
def fetch_token(self, client_secret, code, context, scope, redirect_uri, token_url='https://login.bigcommerce.com/oauth2/token'): """ Fetches a token from given token_url, using given parameters, and sets up session headers for future requests. redirect_uri should be ...
python
{ "resource": "" }
q7573
OAuthConnection._handle_response
train
def _handle_response(self, url, res, suppress_empty=True): """ Adds rate limiting information on to the response object """ result = Connection._handle_response(self, url, res, suppress_empty) if 'X-Rate-Limit-Time-Reset-Ms' in res.headers: self.rate_limit = dict(ms_u...
python
{ "resource": "" }
q7574
escape_html
train
def escape_html(text, escape_slash=False): """ Binding for Hoedown's HTML escaping function. The implementation is inspired by the OWASP XSS Prevention recommendations: .. code-block:: none & --> &amp; < --> &lt; > --> &gt; " --> &quot; ' --> &#x27; / -...
python
{ "resource": "" }
q7575
html
train
def html(text, extensions=0, render_flags=0): """ Convert markdown text to HTML. ``extensions`` can be a list or tuple of extensions (e.g. ``('fenced-code', 'footnotes', 'strikethrough')``) or an integer (e.g. ``EXT_FENCED_CODE | EXT_FOOTNOTES | EXT_STRIKETHROUGH``). ``render_flags`` can be a ...
python
{ "resource": "" }
q7576
smartypants
train
def smartypants(text): """ Transforms sequences of characters into HTML entities. =================================== ===================== ========= Markdown HTML Result =================================== ===================== ========= ``'s``...
python
{ "resource": "" }
q7577
SaferHtmlRenderer.autolink
train
def autolink(self, raw_url, is_email): """ Filters links generated by the ``autolink`` extension. """ if self.check_url(raw_url): url = self.rewrite_url(('mailto:' if is_email else '') + raw_url) url = escape_html(url) return '<a href="%s">%s</a>' % (u...
python
{ "resource": "" }
q7578
SaferHtmlRenderer.image
train
def image(self, raw_url, title='', alt=''): """ Filters the ``src`` attribute of an image. Note that filtering the source URL of an ``<img>`` tag is only a very basic protection, and it's mostly useless in modern browsers (they block JavaScript in there by default). An example o...
python
{ "resource": "" }
q7579
SaferHtmlRenderer.link
train
def link(self, content, raw_url, title=''): """ Filters links. """ if self.check_url(raw_url): url = self.rewrite_url(raw_url) maybe_title = ' title="%s"' % escape_html(title) if title else '' url = escape_html(url) return ('<a href="%s"%s>...
python
{ "resource": "" }
q7580
SaferHtmlRenderer.check_url
train
def check_url(self, url, is_image_src=False): """ This method is used to check a URL. Returns :obj:`True` if the URL is "safe", :obj:`False` otherwise. The default implementation only allows HTTP and HTTPS links. That means no ``mailto:``, no ``xmpp:``, no ``ftp:``, etc. ...
python
{ "resource": "" }
q7581
SaferHtmlRenderer.rewrite_url
train
def rewrite_url(self, url, is_image_src=False): """ This method is called to rewrite URLs. It uses either ``self.link_rewrite`` or ``self.img_src_rewrite`` depending on the value of ``is_image_src``. The URL is returned unchanged if the corresponding attribute is :obj:`None`. ...
python
{ "resource": "" }
q7582
args_to_int
train
def args_to_int(mapping, argument): """ Convert list of strings to an int using a mapping. """ if isinstance(argument, int): if argument == 0: return 0 deprecation('passing extensions and flags as constants is deprecated') return argument elif isinstance(argument,...
python
{ "resource": "" }
q7583
_pack3
train
def _pack3(obj, fp, **options): """ Serialize a Python object into MessagePack bytes. Args: obj: a Python object fp: a .write()-supporting file-like object Kwargs: ext_handlers (dict): dictionary of Ext handlers, mapping a custom type to a callable ...
python
{ "resource": "" }
q7584
_get_task_target
train
def _get_task_target(): """Get the default target for a pipeline task. Current version id format is: user_defined_version.minor_version_number Current module id is just the module's name. It could be "default" Returns: A complete target name is of format version.module. If module is the default module, ...
python
{ "resource": "" }
q7585
is_generator_function
train
def is_generator_function(obj): """Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See isfunction.__doc__ for attributes listing. Adapted from Python 2.6. Args: obj: an object to test. Returns: true if the object i...
python
{ "resource": "" }
q7586
_register_json_primitive
train
def _register_json_primitive(object_type, encoder, decoder): """Extend what Pipeline can serialize. Args: object_type: type of the object. encoder: a function that takes in an object and returns a dict of json primitives. decoder: inverse function of encoder. """ global _TYPE_TO_ENCODER glo...
python
{ "resource": "" }
q7587
_JsonDecodeKey
train
def _JsonDecodeKey(d): """Json decode a ndb.Key object.""" k_c = d['key_string'] if isinstance(k_c, (list, tuple)): return ndb.Key(flat=k_c) return ndb.Key(urlsafe=d['key_string'])
python
{ "resource": "" }
q7588
JsonDecoder._dict_to_obj
train
def _dict_to_obj(self, d): """Converts a dictionary of json object to a Python object.""" if JsonEncoder.TYPE_ID not in d: return d type_name = d.pop(JsonEncoder.TYPE_ID) if type_name in _TYPE_NAME_TO_DECODER: decoder = _TYPE_NAME_TO_DECODER[type_name] return decoder(d) else: ...
python
{ "resource": "" }
q7589
_write_json_blob
train
def _write_json_blob(encoded_value, pipeline_id=None): """Writes a JSON encoded value to a Cloud Storage File. This function will store the blob in a GCS file in the default bucket under the appengine_pipeline directory. Optionally using another directory level specified by pipeline_id Args: encoded_valu...
python
{ "resource": "" }
q7590
_dereference_args
train
def _dereference_args(pipeline_name, args, kwargs): """Dereference a Pipeline's arguments that are slots, validating them. Each argument value passed in is assumed to be a dictionary with the format: {'type': 'value', 'value': 'serializable'} # A resolved value. {'type': 'slot', 'slot_key': 'str() on a db...
python
{ "resource": "" }
q7591
_generate_args
train
def _generate_args(pipeline, future, queue_name, base_path): """Generate the params used to describe a Pipeline's depedencies. The arguments passed to this method may be normal values, Slot instances (for named outputs), or PipelineFuture instances (for referring to the default output slot). Args: pipel...
python
{ "resource": "" }
q7592
_get_timestamp_ms
train
def _get_timestamp_ms(when): """Converts a datetime.datetime to integer milliseconds since the epoch. Requires special handling to preserve microseconds. Args: when: A datetime.datetime instance. Returns: Integer time since the epoch in milliseconds. If the supplied 'when' is None, the return val...
python
{ "resource": "" }
q7593
_get_internal_slot
train
def _get_internal_slot(slot_key=None, filler_pipeline_key=None, slot_dict=None): """Gets information about a _SlotRecord for display in UI. Args: slot_key: The db.Key of the slot to fetch. filler_pipeline_key: In the case the slot has not yet been filled, assum...
python
{ "resource": "" }
q7594
get_status_tree
train
def get_status_tree(root_pipeline_id): """Gets the full status tree of a pipeline. Args: root_pipeline_id: The pipeline ID to get status for. Returns: Dictionary with the keys: rootPipelineId: The ID of the root pipeline. slots: Mapping of slot IDs to result of from _get_internal_slot. ...
python
{ "resource": "" }
q7595
get_pipeline_names
train
def get_pipeline_names(): """Returns the class paths of all Pipelines defined in alphabetical order.""" class_path_set = set() for cls in _PipelineMeta._all_classes: if cls.class_path is not None: class_path_set.add(cls.class_path) return sorted(class_path_set)
python
{ "resource": "" }
q7596
get_root_list
train
def get_root_list(class_path=None, cursor=None, count=50): """Gets a list root Pipelines. Args: class_path: Optional. If supplied, only return root Pipelines with the given class_path. By default all root pipelines are returned. cursor: Optional. When supplied, the cursor returned from the last call ...
python
{ "resource": "" }
q7597
Slot.value
train
def value(self): """Returns the current value of this slot. Returns: The value of the slot (a serializable Python type). Raises: SlotNotFilledError if the value hasn't been filled yet. """ if not self.filled: raise SlotNotFilledError('Slot with name "%s", key "%s" not yet filled....
python
{ "resource": "" }
q7598
Slot.filler
train
def filler(self): """Returns the pipeline ID that filled this slot's value. Returns: A string that is the pipeline ID. Raises: SlotNotFilledError if the value hasn't been filled yet. """ if not self.filled: raise SlotNotFilledError('Slot with name "%s", key "%s" not yet filled.' ...
python
{ "resource": "" }
q7599
Slot.fill_datetime
train
def fill_datetime(self): """Returns when the slot was filled. Returns: A datetime.datetime. Raises: SlotNotFilledError if the value hasn't been filled yet. """ if not self.filled: raise SlotNotFilledError('Slot with name "%s", key "%s" not yet filled.' ...
python
{ "resource": "" }