_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q31100
infer_slice
train
def infer_slice(node, context=None): """Understand `slice` calls.""" args = node.args if not 0 < len(args) <= 3: raise UseInferenceDefault infer_func = partial(helpers.safe_infer, context=context) args = [infer_func(arg) for arg in args] for arg in args: if not arg or arg is uti...
python
{ "resource": "" }
q31101
infer_isinstance
train
def infer_isinstance(callnode, context=None): """Infer isinstance calls :param nodes.Call callnode: an isinstance call :param InferenceContext: context for call (currently unused but is a common interface for inference) :rtype nodes.Const: Boolean Const value of isinstance call :raises Use...
python
{ "resource": "" }
q31102
infer_len
train
def infer_len(node, context=None): """Infer length calls :param nodes.Call node: len call to infer :param context.InferenceContext: node context :rtype nodes.Const: a Const node with the inferred length, if possible """ call = arguments.CallSite.from_call(node) if call.keyword_arguments: ...
python
{ "resource": "" }
q31103
infer_dict_fromkeys
train
def infer_dict_fromkeys(node, context=None): """Infer dict.fromkeys :param nodes.Call node: dict.fromkeys() call to infer :param context.InferenceContext: node context :rtype nodes.Dict: a Dictionary containing the values that astroid was able to infer. In case the inference failed for ...
python
{ "resource": "" }
q31104
AsStringVisitor._stmt_list
train
def _stmt_list(self, stmts, indent=True): """return a list of nodes to string""" stmts = "\n".join(nstr for nstr in [n.accept(self) for n in stmts] if nstr)
python
{ "resource": "" }
q31105
AsStringVisitor._precedence_parens
train
def _precedence_parens(self, node, child, is_left=True): """Wrap child in parens only if required to keep
python
{ "resource": "" }
q31106
AsStringVisitor.visit_assert
train
def visit_assert(self, node): """return an astroid.Assert node as string""" if node.fail: return "assert %s, %s" % (node.test.accept(self),
python
{ "resource": "" }
q31107
AsStringVisitor.visit_assign
train
def visit_assign(self, node): """return an astroid.Assign node as string"""
python
{ "resource": "" }
q31108
AsStringVisitor.visit_augassign
train
def visit_augassign(self, node): """return an astroid.AugAssign node
python
{ "resource": "" }
q31109
AsStringVisitor.visit_annassign
train
def visit_annassign(self, node): """Return an astroid.AugAssign node as string""" target = node.target.accept(self)
python
{ "resource": "" }
q31110
AsStringVisitor.visit_binop
train
def visit_binop(self, node): """return an astroid.BinOp node as string""" left = self._precedence_parens(node, node.left) right = self._precedence_parens(node, node.right, is_left=False)
python
{ "resource": "" }
q31111
AsStringVisitor.visit_boolop
train
def visit_boolop(self, node): """return an astroid.BoolOp node as string"""
python
{ "resource": "" }
q31112
AsStringVisitor.visit_call
train
def visit_call(self, node): """return an astroid.Call node as string""" expr_str = self._precedence_parens(node, node.func) args = [arg.accept(self) for arg
python
{ "resource": "" }
q31113
AsStringVisitor.visit_classdef
train
def visit_classdef(self, node): """return an astroid.ClassDef node as string""" decorate = node.decorators.accept(self) if node.decorators else "" bases = ", ".join(n.accept(self) for n in node.bases) metaclass = node.metaclass() if metaclass and not node.has_metaclass_hack(): ...
python
{ "resource": "" }
q31114
AsStringVisitor.visit_compare
train
def visit_compare(self, node): """return an astroid.Compare node as string""" rhs_str = " ".join( [ "%s %s" % (op, self._precedence_parens(node, expr, is_left=False))
python
{ "resource": "" }
q31115
AsStringVisitor.visit_delete
train
def visit_delete(self, node): # XXX check if correct """return an astroid.Delete node as string"""
python
{ "resource": "" }
q31116
AsStringVisitor.visit_decorators
train
def visit_decorators(self, node): """return an astroid.Decorators node as string"""
python
{ "resource": "" }
q31117
AsStringVisitor.visit_dictcomp
train
def visit_dictcomp(self, node): """return an astroid.DictComp node as string""" return "{%s: %s %s}" % ( node.key.accept(self),
python
{ "resource": "" }
q31118
AsStringVisitor.visit_exec
train
def visit_exec(self, node): """return an astroid.Exec node as string""" if node.locals: return "exec %s in %s, %s" % ( node.expr.accept(self), node.locals.accept(self), node.globals.accept(self),
python
{ "resource": "" }
q31119
AsStringVisitor.visit_extslice
train
def visit_extslice(self, node): """return an astroid.ExtSlice node as string"""
python
{ "resource": "" }
q31120
AsStringVisitor.visit_for
train
def visit_for(self, node): """return an astroid.For node as string""" fors = "for %s in %s:\n%s" % ( node.target.accept(self), node.iter.accept(self), self._stmt_list(node.body), )
python
{ "resource": "" }
q31121
AsStringVisitor.visit_importfrom
train
def visit_importfrom(self, node): """return an astroid.ImportFrom node as string""" return "from %s import %s" % (
python
{ "resource": "" }
q31122
AsStringVisitor.visit_functiondef
train
def visit_functiondef(self, node): """return an astroid.Function node as string""" decorate = node.decorators.accept(self) if node.decorators else "" docs = self._docs_dedent(node.doc) if node.doc else "" trailer = ":" if node.returns: return_annotation = "->" + node....
python
{ "resource": "" }
q31123
AsStringVisitor.visit_generatorexp
train
def visit_generatorexp(self, node): """return an astroid.GeneratorExp node as string""" return "(%s %s)" % (
python
{ "resource": "" }
q31124
AsStringVisitor.visit_attribute
train
def visit_attribute(self, node): """return an astroid.Getattr node as string"""
python
{ "resource": "" }
q31125
AsStringVisitor.visit_if
train
def visit_if(self, node): """return an astroid.If node as string""" ifs = ["if %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))]
python
{ "resource": "" }
q31126
AsStringVisitor.visit_ifexp
train
def visit_ifexp(self, node): """return an astroid.IfExp node as string""" return "%s if %s else %s" % ( self._precedence_parens(node, node.body,
python
{ "resource": "" }
q31127
AsStringVisitor.visit_keyword
train
def visit_keyword(self, node): """return an astroid.Keyword node as string""" if node.arg is None:
python
{ "resource": "" }
q31128
AsStringVisitor.visit_lambda
train
def visit_lambda(self, node): """return an astroid.Lambda node as string""" args = node.args.accept(self) body = node.body.accept(self)
python
{ "resource": "" }
q31129
AsStringVisitor.visit_list
train
def visit_list(self, node): """return an astroid.List node as string"""
python
{ "resource": "" }
q31130
AsStringVisitor.visit_listcomp
train
def visit_listcomp(self, node): """return an astroid.ListComp node as string""" return "[%s %s]" % (
python
{ "resource": "" }
q31131
AsStringVisitor.visit_module
train
def visit_module(self, node): """return an astroid.Module node as string""" docs = '"""%s"""\n\n' % node.doc if node.doc else ""
python
{ "resource": "" }
q31132
AsStringVisitor.visit_print
train
def visit_print(self, node): """return an astroid.Print node as string""" nodes = ", ".join(n.accept(self) for n in node.values) if not node.nl: nodes = "%s," % nodes
python
{ "resource": "" }
q31133
AsStringVisitor.visit_return
train
def visit_return(self, node): """return an astroid.Return node as string""" if node.is_tuple_return() and len(node.value.elts) > 1:
python
{ "resource": "" }
q31134
AsStringVisitor.visit_set
train
def visit_set(self, node): """return an astroid.Set node as string"""
python
{ "resource": "" }
q31135
AsStringVisitor.visit_setcomp
train
def visit_setcomp(self, node): """return an astroid.SetComp node as string""" return "{%s %s}" % (
python
{ "resource": "" }
q31136
AsStringVisitor.visit_slice
train
def visit_slice(self, node): """return an astroid.Slice node as string""" lower = node.lower.accept(self) if node.lower else "" upper = node.upper.accept(self) if node.upper else "" step
python
{ "resource": "" }
q31137
AsStringVisitor.visit_subscript
train
def visit_subscript(self, node): """return an astroid.Subscript node as string""" idx = node.slice if idx.__class__.__name__.lower() == "index": idx = idx.value idxstr = idx.accept(self) if idx.__class__.__name__.lower() == "tuple" and idx.elts: # Remove p...
python
{ "resource": "" }
q31138
AsStringVisitor.visit_tryexcept
train
def visit_tryexcept(self, node): """return an astroid.TryExcept node as string""" trys = ["try:\n%s" % self._stmt_list(node.body)]
python
{ "resource": "" }
q31139
AsStringVisitor.visit_tryfinally
train
def visit_tryfinally(self, node): """return an astroid.TryFinally node as string""" return "try:\n%s\nfinally:\n%s" % (
python
{ "resource": "" }
q31140
AsStringVisitor.visit_tuple
train
def visit_tuple(self, node): """return an astroid.Tuple node as string""" if len(node.elts) == 1: return "(%s, )" %
python
{ "resource": "" }
q31141
AsStringVisitor.visit_unaryop
train
def visit_unaryop(self, node): """return an astroid.UnaryOp node as string""" if node.op == "not": operator = "not " else:
python
{ "resource": "" }
q31142
AsStringVisitor.visit_while
train
def visit_while(self, node): """return an astroid.While node as string""" whiles = "while %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body)) if node.orelse:
python
{ "resource": "" }
q31143
AsStringVisitor.visit_with
train
def visit_with(self, node): # 'with' without 'as' is possible """return an astroid.With node as string""" items = ", ".join( ("%s" % expr.accept(self)) + (vars and " as %s" % (vars.accept(self)) or "")
python
{ "resource": "" }
q31144
AsStringVisitor3.visit_yieldfrom
train
def visit_yieldfrom(self, node): """ Return an astroid.YieldFrom node as string. """ yi_val = (" " + node.value.accept(self)) if node.value else "" expr = "yield from" + yi_val
python
{ "resource": "" }
q31145
bind_context_to_node
train
def bind_context_to_node(context, node): """Give a context a boundnode to retrieve the correct function name or attribute value with from further inference. Do not use an existing context since the boundnode could then be incorrectly propagated higher up in the call stack. :param context: Cont...
python
{ "resource": "" }
q31146
InferenceContext.push
train
def push(self, node): """Push node into inference path :return: True if node is already in context path else False :rtype: bool Allows one to
python
{ "resource": "" }
q31147
InferenceContext.clone
train
def clone(self): """Clone inference path For example, each side of a binary operation (BinOp) starts with the same context but diverge as each side is inferred so the InferenceContext will need
python
{ "resource": "" }
q31148
InferenceContext.cache_generator
train
def cache_generator(self, key, generator): """Cache result of generator into dictionary Used to cache inference results""" results = [] for result in generator:
python
{ "resource": "" }
q31149
NestedViewSetMixin.get_queryset
train
def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() if hasattr(self.serializer_class, 'parent_lookup_kwargs'): orm_filte...
python
{ "resource": "" }
q31150
ReteMatcher.changes
train
def changes(self, adding=None, deleting=None): """Pass the given changes to the root_node.""" if deleting is not None: for deleted in deleting: self.root_node.remove(deleted) if adding is not None:
python
{ "resource": "" }
q31151
ReteMatcher.build_alpha_part
train
def build_alpha_part(ruleset, root_node): """ Given a set of already adapted rules, build the alpha part of the RETE network starting at `root_node`. """ # Adds a dummy rule with InitialFact as LHS for always generate # the alpha part matching InitialFact(). This is need...
python
{ "resource": "" }
q31152
ReteMatcher.build_beta_part
train
def build_beta_part(ruleset, alpha_terminals): """ Given a set of already adapted rules, and a dictionary of patterns and alpha_nodes, wire up the beta part of the RETE
python
{ "resource": "" }
q31153
ReteMatcher.print_network
train
def print_network(self): # pragma: no cover """ Generate a graphviz compatible graph. """ edges = set() def gen_edges(node): nonlocal edges name = str(id(node)) yield '{name} [label="{cls_name}"];'.format( name=name, ...
python
{ "resource": "" }
q31154
Node.reset
train
def reset(self): """Reset itself and recursively all its children.""" watchers.MATCHER.debug("Node <%s> reset", self)
python
{ "resource": "" }
q31155
OneInputNode.activate
train
def activate(self, token): """Make a copy of the received token and call `self._activate`.""" if watchers.worth('MATCHER', 'DEBUG'):
python
{ "resource": "" }
q31156
TwoInputNode.activate_left
train
def activate_left(self, token): """Make a copy of the received token and call `_activate_left`.""" watchers.MATCHER.debug(
python
{ "resource": "" }
q31157
TwoInputNode.activate_right
train
def activate_right(self, token): """Make a copy of the received token and call `_activate_right`.""" watchers.MATCHER.debug(
python
{ "resource": "" }
q31158
KnowledgeEngine.duplicate
train
def duplicate(self, template_fact, **modifiers): """Create a new fact from an existing one.""" newfact = template_fact.copy()
python
{ "resource": "" }
q31159
KnowledgeEngine.get_deffacts
train
def get_deffacts(self): """Return the existing deffacts sorted by the internal order"""
python
{ "resource": "" }
q31160
KnowledgeEngine.retract
train
def retract(self, idx_or_declared_fact): """ Retracts a specific fact, using its index .. note:: This updates the agenda """ self.facts.retract(idx_or_declared_fact) if not self.running:
python
{ "resource": "" }
q31161
KnowledgeEngine.run
train
def run(self, steps=float('inf')): """ Execute agenda activations """ self.running = True activation = None execution = 0 while steps > 0 and self.running: added, removed = self.get_activations() self.strategy.update_agenda(self.agenda, a...
python
{ "resource": "" }
q31162
KnowledgeEngine.__declare
train
def __declare(self, *facts): """ Internal declaration method. Used for ``declare`` and ``deffacts`` """ if any(f.has_field_constraints() for f in facts): raise TypeError( "Declared facts cannot contain conditional elements") elif any(f.has_nested_acces...
python
{ "resource": "" }
q31163
KnowledgeEngine.declare
train
def declare(self, *facts): """ Declare from inside a fact, equivalent to ``assert`` in clips. .. note:: This updates the agenda. """ if
python
{ "resource": "" }
q31164
REGEX
train
def REGEX(pattern, flags=0): """Regular expression
python
{ "resource": "" }
q31165
ILIKE
train
def ILIKE(pattern): """Unix shell-style wildcards. Case-insensitive"""
python
{ "resource": "" }
q31166
worth
train
def worth(what, level_name): """Returns `True` if the watcher `what` would log under `level_name`.""" return (logging.NOTSET
python
{ "resource": "" }
q31167
watch
train
def watch(*what, level=logging.DEBUG): """ Enable watchers. Defaults to enable all watchers, accepts a list names of watchers to enable. """ if not what: what = ALL
python
{ "resource": "" }
q31168
extract_facts
train
def extract_facts(rule): """Given a rule, return a set containing all rule LHS facts.""" def _extract_facts(ce): if isinstance(ce, Fact): yield ce elif isinstance(ce, TEST):
python
{ "resource": "" }
q31169
generate_checks
train
def generate_checks(fact): """Given a fact, generate a list of Check objects for checking it.""" yield TypeCheck(type(fact)) fact_captured = False for key, value in fact.items(): if (isinstance(key, str) and key.startswith('__') and key.endswith('__')): ...
python
{ "resource": "" }
q31170
BusNode.add
train
def add(self, fact): """Create a VALID token and send it to all children.""" token = Token.valid(fact)
python
{ "resource": "" }
q31171
BusNode.remove
train
def remove(self, fact): """Create an INVALID token and send it to all children.""" token = Token.invalid(fact)
python
{ "resource": "" }
q31172
OrdinaryMatchNode.__activation
train
def __activation(self, token, branch_memory, matching_memory, is_left=True): """ Node activation internal function. This is a generalization of both activation functions. The given token is added or removed from `branch_memory` depending of its tag. ...
python
{ "resource": "" }
q31173
OrdinaryMatchNode._activate_left
train
def _activate_left(self, token): """Node left activation.""" self.__activation(token, self.left_memory,
python
{ "resource": "" }
q31174
OrdinaryMatchNode._activate_right
train
def _activate_right(self, token): """Node right activation.""" self.__activation(token, self.right_memory,
python
{ "resource": "" }
q31175
ConflictSetNode._activate
train
def _activate(self, token): """Activate this node for the given token.""" info = token.to_info() activation = Activation( self.rule, frozenset(info.data), {k: v for k, v in info.context if isinstance(k, str)}) if token.is_valid(): if inf...
python
{ "resource": "" }
q31176
ConflictSetNode.get_activations
train
def get_activations(self): """Return a list of activations."""
python
{ "resource": "" }
q31177
NotNode._activate_left
train
def _activate_left(self, token): """ Activate from the left. In case of a valid token this activations test the right memory with the given token and looks for the number of matches. The token and the number of occurences are stored in the left memory. If the nu...
python
{ "resource": "" }
q31178
NotNode._activate_right
train
def _activate_right(self, token): """ Activate from the right. Go over the left memory and find matching data, when found update the counter (substracting if the given token is invalid and adding otherwise). Depending on the result of this operation a new token is genera...
python
{ "resource": "" }
q31179
FactList.retract
train
def retract(self, idx_or_fact): """ Retract a previously asserted fact. See `"Retract that fact" in Clips User Guide <http://clipsrules.sourceforge.net/doc\ umentation/v624/ug.htm#_Toc412126077>`_. :param idx: The index of the fact to retract in the factlist ...
python
{ "resource": "" }
q31180
FactList.changes
train
def changes(self): """ Return a tuple with the removed and added facts since last run. """ try: return self.added, self.removed
python
{ "resource": "" }
q31181
Rule.new_conditions
train
def new_conditions(self, *args): """ Generate a new rule with the same attributes but with the given conditions. """
python
{ "resource": "" }
q31182
Fact.as_dict
train
def as_dict(self): """Return a dictionary containing this `Fact` data.""" return {k: unfreeze(v)
python
{ "resource": "" }
q31183
Fact.copy
train
def copy(self): """Return a copy of this `Fact`.""" content = [(k, v) for k, v in self.items()] intidx = [(k, v) for k, v in content if isinstance(k, int)] args = [v for k, v in sorted(intidx)] kwargs = {k: v
python
{ "resource": "" }
q31184
AnyChild.add_child
train
def add_child(self, node, callback): """Add node and callback to the children
python
{ "resource": "" }
q31185
Token.valid
train
def valid(cls, data, context=None): """Shortcut to create a VALID Token."""
python
{ "resource": "" }
q31186
Token.invalid
train
def invalid(cls, data, context=None): """Shortcut to create an INVALID Token."""
python
{ "resource": "" }
q31187
Token.copy
train
def copy(self): """ Make a new instance of this Token. This method makes a copy of the mutable part of the token before making the instance.
python
{ "resource": "" }
q31188
parse
train
def parse(datetime_str, timezone=None, isofirst=True, dayfirst=True, yearfirst=True): """ Parses a datetime string and returns a `Delorean` object. :param datetime_str: The string to be interpreted into a `Delorean` object. :param timezone: Pass this parameter and the returned Delorean object will be n...
python
{ "resource": "" }
q31189
range_daily
train
def range_daily(start=None, stop=None, timezone='UTC', count=None): """ This an alternative way to generating sets of Delorean objects with DAILY stops """
python
{ "resource": "" }
q31190
range_hourly
train
def range_hourly(start=None, stop=None, timezone='UTC', count=None): """ This an alternative way to generating sets of Delorean objects with HOURLY stops """
python
{ "resource": "" }
q31191
range_monthly
train
def range_monthly(start=None, stop=None, timezone='UTC', count=None): """ This an alternative way to generating sets of Delorean objects with MONTHLY stops """
python
{ "resource": "" }
q31192
range_yearly
train
def range_yearly(start=None, stop=None, timezone='UTC', count=None): """ This an alternative way to generating sets of Delorean objects with YEARLY stops """
python
{ "resource": "" }
q31193
stops
train
def stops(freq, interval=1, count=None, wkst=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, timezone='UTC', start=None, stop=None): """ This will create a list of delorean ...
python
{ "resource": "" }
q31194
_move_datetime
train
def _move_datetime(dt, direction, delta): """ Move datetime given delta by given direction """ if direction == 'next':
python
{ "resource": "" }
q31195
move_datetime_month
train
def move_datetime_month(dt, direction, num_shifts): """ Move datetime 1 month in the chosen direction. unit is a no-op, to keep the API the same as the day case
python
{ "resource": "" }
q31196
move_datetime_week
train
def move_datetime_week(dt, direction, num_shifts): """ Move datetime 1 week in the chosen direction. unit is a no-op, to keep the API the same as the day case
python
{ "resource": "" }
q31197
move_datetime_year
train
def move_datetime_year(dt, direction, num_shifts): """ Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case
python
{ "resource": "" }
q31198
datetime_timezone
train
def datetime_timezone(tz): """ This method given a timezone returns a localized datetime object. """ utc_datetime_naive = datetime.utcnow() # return a localized datetime to UTC utc_localized_datetime = localize(utc_datetime_naive, 'UTC')
python
{ "resource": "" }
q31199
localize
train
def localize(dt, tz): """ Given a naive datetime object this method will return a localized datetime object """ if not
python
{ "resource": "" }