_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q250800
Tokenizer.reconstruct_text
train
def reconstruct_text(tokens: List[Token]) -> str: """ Given a list of tokens, reconstruct the original text with as much fidelity as possible. Args: [tokens]:
python
{ "resource": "" }
q250801
Engine._removecleaner
train
def _removecleaner(self, cleaner): """ Remove the cleaner from the list if it already exists. Returns True if the cleaner was removed. """ oldlen = len(self._old_cleaners) self._old_cleaners = [
python
{ "resource": "" }
q250802
add
train
def add(repo_path, dest_path): ''' Registers a git repository with homely so that it will run its `HOMELY.py` script on each invocation of `homely update`. `homely add` also immediately executes a `homely update` so that the dotfiles are installed straight away. If the git repository is hosted onlin...
python
{ "resource": "" }
q250803
forget
train
def forget(identifier): ''' Tells homely to forget about a dotfiles repository that was previously added. You can then run `homely update` to have homely perform automatic cleanup of anything that was installed by that dotfiles repo. REPO This should be the path to a local dotfiles reposito...
python
{ "resource": "" }
q250804
update
train
def update(identifiers, nopull, only): ''' Performs a `git pull` in each of the repositories registered with `homely add`, runs all of their HOMELY.py scripts, and then performs automatic cleanup as necessary. REPO This should be the path to a local dotfiles repository that has already ...
python
{ "resource": "" }
q250805
pipinstall
train
def pipinstall(packagename, pips=None, trypips=[], scripts=None): """ Install packages from pip. The primary advantage of using this function is that homely can automatically remove the package for you when you no longer want it. package: The name of the pip package to install pips: ...
python
{ "resource": "" }
q250806
getstatus
train
def getstatus(): """Get the status of the previous 'homely update', or any 'homely update' that may be running in another process. """ if exists(RUNFILE): mtime = os.stat(RUNFILE).st_mtime with open(SECTIONFILE) as f: section = f.read().strip() # what section? ...
python
{ "resource": "" }
q250807
RepoListConfig.find_by_any
train
def find_by_any(self, identifier, how): """ how should be a string with any or all of the characters "ilc" """ if "i" in how: match = self.find_by_id(identifier) if match: return match if "l" in how: match = self.find_by_localpa...
python
{ "resource": "" }
q250808
isOriginalLocation
train
def isOriginalLocation(attr): """ Attempt to discover if this appearance of a PythonAttribute representing a class refers to the module where that class was defined. """ sourceModule = inspect.getmodule(attr.load()) if sourceModule is None: return False currentModule = attr
python
{ "resource": "" }
q250809
Automaton.initialState
train
def initialState(self, state): """ Set this automaton's initial state. Raises a ValueError if this automaton already has an initial state. """ if self._initialState is not _NO_STATE:
python
{ "resource": "" }
q250810
Automaton.addTransition
train
def addTransition(self, inState, inputSymbol, outState, outputSymbols): """ Add the given transition to the outputSymbol. Raise ValueError if there is already a transition with the same inState and inputSymbol. """ # keeping self._transitions in a flat list makes addTransition ...
python
{ "resource": "" }
q250811
Automaton.outputAlphabet
train
def outputAlphabet(self): """ The full set of symbols which can be produced by this automaton. """ return set( chain.from_iterable( outputSymbols for
python
{ "resource": "" }
q250812
Automaton.states
train
def states(self): """ All valid states; "Q" in the mathematical description of a state machine. """ return frozenset( chain.from_iterable( (inState, outState)
python
{ "resource": "" }
q250813
Transitioner.transition
train
def transition(self, inputSymbol): """ Transition between states, returning any outputs. """ outState, outputSymbols = self._automaton.outputForInput(self._state, inputSymbol) outTracer = None if self._trace...
python
{ "resource": "" }
q250814
_getArgSpec
train
def _getArgSpec(func): """ Normalize inspect.ArgSpec across python versions and convert mutable attributes to immutable types. :param Callable func: A function. :return: The function's ArgSpec. :rtype: ArgSpec """ spec = getArgsSpec(func) return ArgSpec( args=tuple(spec.args...
python
{ "resource": "" }
q250815
_getArgNames
train
def _getArgNames(spec): """ Get the name of all arguments defined in a function signature. The name of * and ** arguments is normalized to "*args" and "**kwargs". :param ArgSpec spec: A function to interrogate for a signature. :return: The set of all argument names in `func`s signature. :rtype...
python
{ "resource": "" }
q250816
_keywords_only
train
def _keywords_only(f): """ Decorate a function so all its arguments must be passed by keyword. A useful utility for decorators that take arguments so that they don't accidentally get passed the thing they're decorating as their first
python
{ "resource": "" }
q250817
_filterArgs
train
def _filterArgs(args, kwargs, inputSpec, outputSpec): """ Filter out arguments that were passed to input that output won't accept. :param tuple args: The *args that input received. :param dict kwargs: The **kwargs that input received. :param ArgSpec inputSpec: The input's arg spec. :param ArgSp...
python
{ "resource": "" }
q250818
MethodicalMachine.state
train
def state(self, initial=False, terminal=False, serialized=None): """ Declare a state, possibly an initial state or a terminal state. This is a decorator for methods, but it will modify the method so as not to be callable any more. :param bool initial: is this stat...
python
{ "resource": "" }
q250819
MethodicalMachine.input
train
def input(self): """ Declare an input. This is a decorator for methods. """ def decorator(inputMethod): return MethodicalInput(automaton=self._automaton,
python
{ "resource": "" }
q250820
MethodicalMachine.output
train
def output(self): """ Declare an output. This is a decorator for methods. This method will be called when the state machine transitions to this state as specified in the decorated `output` method. """
python
{ "resource": "" }
q250821
elementMaker
train
def elementMaker(name, *children, **attrs): """ Construct a string from the HTML element description. """ formattedAttrs = ' '.join('{}={}'.format(key, _gvquote(str(value))) for key, value in sorted(attrs.items()))
python
{ "resource": "" }
q250822
tableMaker
train
def tableMaker(inputLabel, outputLabels, port, _E=elementMaker): """ Construct an HTML table to label a state transition. """ colspan = {} if outputLabels: colspan['colspan'] = str(len(outputLabels)) inputLabelCell = _E("td", _E("font", ...
python
{ "resource": "" }
q250823
preserveName
train
def preserveName(f): """ Preserve the name of the given function on the decorated function. """ def decorator(decorated): return copyfunction(decorated,
python
{ "resource": "" }
q250824
get_kafka_ssl_context
train
def get_kafka_ssl_context(): """ Returns an SSL context based on the certificate information in the Kafka config vars. """ # NOTE: We assume that Kafka environment variables are present. If using # Apache Kafka on Heroku, they will be available in your app configuration. # # 1. Write the PEM...
python
{ "resource": "" }
q250825
get_kafka_producer
train
def get_kafka_producer(acks='all', value_serializer=lambda v: json.dumps(v).encode('utf-8')): """ Return a KafkaProducer that uses the SSLContext created with create_ssl_context.
python
{ "resource": "" }
q250826
get_kafka_consumer
train
def get_kafka_consumer(topic=None, value_deserializer=lambda v: json.loads(v.decode('utf-8'))): """ Return a KafkaConsumer that uses the SSLContext created with create_ssl_context. """ # Create the KafkaConsumer connected to the specified brokers. Use the # SSLContext that is...
python
{ "resource": "" }
q250827
SgeBackend.replace_body_vars
train
def replace_body_vars(self, body): """Given a multiline string that is the body of the job script, replace the placeholders for environment variables with backend-specific
python
{ "resource": "" }
q250828
set_executable
train
def set_executable(filename): """Set the exectuable bit on the given filename""" st = os.stat(filename)
python
{ "resource": "" }
q250829
split_seq
train
def split_seq(seq, n_chunks): """Split the given sequence into `n_chunks`. Suitable for distributing an array of jobs over a fixed number of workers. >>> split_seq([1,2,3,4,5,6], 3) [[1, 2], [3, 4], [5, 6]] >>> split_seq([1,2,3,4,5,6], 2) [[1, 2, 3], [4, 5, 6]] >>> split_seq([1,2,3,4,5,6,7]...
python
{ "resource": "" }
q250830
AsyncResult.status
train
def status(self): """Return the job status as one of the codes defined in the `clusterjob.status` module. finished, communicate with the cluster to determine the job's status. """ if self._status >= COMPLETED: return self._status else: cmd = self.b...
python
{ "resource": "" }
q250831
AsyncResult.dump
train
def dump(self, cache_file=None): """Write dump out to file `cache_file`, defaulting to ``self.cache_file``""" if cache_file is None: cache_file = self.cache_file if cache_file is not None:
python
{ "resource": "" }
q250832
AsyncResult.load
train
def load(cls, cache_file, backend=None): """Instantiate AsyncResult from dumped `cache_file`. This is the inverse of :meth:`dump`. Parameters ---------- cache_file: str Name of file from which the run should be read. backend: clusterjob.backen...
python
{ "resource": "" }
q250833
AsyncResult.wait
train
def wait(self, timeout=None): """Wait until the result is available or until roughly timeout seconds pass.""" logger = logging.getLogger(__name__) if int(self.max_sleep_interval) < int(self._min_sleep_interval): self.max_sleep_interval = int(self._min_sleep_interval) ...
python
{ "resource": "" }
q250834
AsyncResult.successful
train
def successful(self): """Return True if the job finished with a COMPLETED status, False if it finished with a CANCELLED or FAILED status. Raise an `AssertionError` if the job has not completed"""
python
{ "resource": "" }
q250835
AsyncResult.cancel
train
def cancel(self): """Instruct the cluster to cancel the running job. Has no effect if job is not running""" if self.status > COMPLETED:
python
{ "resource": "" }
q250836
AsyncResult.run_epilogue
train
def run_epilogue(self): """Run the epilogue script in the current working directory. raises: subprocess.CalledProcessError: if the script does not finish with exit code zero. """ logger = logging.getLogger(__name__) if self.epilogue is not None: ...
python
{ "resource": "" }
q250837
JsonPathLexer.t_ID
train
def t_ID(self, t): r'[a-zA-Z_@][a-zA-Z0-9_@\-]*' t.type
python
{ "resource": "" }
q250838
JsonPathLexer.t_newline
train
def t_newline(self, t): r'\n' t.lexer.lineno += 1
python
{ "resource": "" }
q250839
DatumInContext.id_pseudopath
train
def id_pseudopath(self): """ Looks like a path, but with ids stuck in when available """ try: pseudopath = Fields(str(self.value[auto_id_field]))
python
{ "resource": "" }
q250840
bind
train
def bind(value, name): """A filter that prints %s, and stores the value in an array, so that it can be bound using a prepared statement This filter is automatically applied to every {{variable}} during the lexing stage, so developers can't forget to bind """ if isinstance(value, Markup): ...
python
{ "resource": "" }
q250841
inject
train
def inject(function): """Decorator declaring parameters to be injected. eg. >>> Sizes = Key('sizes') >>> Names = Key('names') >>> >>> class A: ... @inject ... def __init__(self, number: int, name: str, sizes: Sizes): ... print([number, name, sizes]) ... >>> ...
python
{ "resource": "" }
q250842
noninjectable
train
def noninjectable(*args): """Mark some parameters as not injectable. This serves as documentation for people reading the code and will prevent Injector from ever attempting to provide the parameters. For example: >>> class Service: ... pass ... >>> class SomeClass: ... @inj...
python
{ "resource": "" }
q250843
Binder.bind
train
def bind(self, interface, to=None, scope=None): """Bind an interface to an implementation. :param interface: Interface or :func:`Key` to bind. :param to: Instance or class to bind to, or an explicit :class:`Provider` subclass. :param scope: Optional :class:`Scope` in which ...
python
{ "resource": "" }
q250844
Binder.multibind
train
def multibind(self, interface, to, scope=None): """Creates or extends a multi-binding. A multi-binding maps from a key to a sequence, where each element in the sequence is provided separately. :param interface: :func:`MappingKey` or :func:`SequenceKey` to bind to. :param to: In...
python
{ "resource": "" }
q250845
Binder.install
train
def install(self, module): """Install a module into this binder. In this context the module is one of the following: * function taking the :class:`Binder` as it's only parameter :: def configure(binder): bind(str, to='s') binder.install(conf...
python
{ "resource": "" }
q250846
Injector.get
train
def get(self, interface: Type[T], scope=None) -> T: """Get an instance of the given interface. .. note:: Although this method is part of :class:`Injector`'s public interface it's meant to be used in limited set of circumstances. For example, to create some kind of ...
python
{ "resource": "" }
q250847
Injector.create_object
train
def create_object(self, cls: Type[T], additional_kwargs=None) -> T: """Create a new instance, satisfying any dependencies on cls.""" additional_kwargs = additional_kwargs or {} log.debug('%sCreating %r object with %r', self._log_prefix, cls, additional_kwargs) try: instance ...
python
{ "resource": "" }
q250848
Injector.call_with_injection
train
def call_with_injection(self, callable, self_=None, args=(), kwargs={}): """Call a callable and provide it's dependencies if needed. :param self_: Instance of a class callable belongs to if it's a method, None otherwise. :param args: Arguments to pass to callable. :param kwa...
python
{ "resource": "" }
q250849
Injector.args_to_inject
train
def args_to_inject(self, function, bindings, owner_key): """Inject arguments into a function. :param function: The function. :param bindings: Map of argument name to binding key to inject. :param owner_key: A key uniquely identifying the *scope* of this function. For a metho...
python
{ "resource": "" }
q250850
scrub_output_pre_save
train
def scrub_output_pre_save(model, **kwargs): """scrub output before saving notebooks""" # only run on notebooks if model['type'] != 'notebook': return
python
{ "resource": "" }
q250851
VariableInspector.close
train
def close(self): """Close and remove hooks.""" if not self.closed: self._ipython.events.unregister('post_run_cell',
python
{ "resource": "" }
q250852
VariableInspector._fill
train
def _fill(self): """Fill self with variable information.""" types_to_exclude = ['module', 'function', 'builtin_function_or_method', 'instance', '_Feature', 'type', 'ufunc'] values = self.namespace.who_ls() def eval(expr): return self.namespace.she...
python
{ "resource": "" }
q250853
set_var
train
def set_var(var, set_='""'): '''set var outside notebook''' if isinstance(set_, str): to_set = json.dumps(set_) elif isinstance(set_, dict) or isinstance(set_, list): try: to_set = json.dumps(set_) except ValueError:
python
{ "resource": "" }
q250854
get_var
train
def get_var(var, default='""'): '''get var inside notebook''' ret = os.environ.get('NBCONVERT_' + var) if
python
{ "resource": "" }
q250855
align_yaxis_np
train
def align_yaxis_np(axes): """Align zeros of the two axes, zooming them out by same ratio""" axes = np.array(axes) extrema = np.array([ax.get_ylim() for ax in axes]) # reset for divide by zero issues for i in range(len(extrema)): if np.isclose(extrema[i, 0], 0.0): extrema[i, 0] =...
python
{ "resource": "" }
q250856
make_dash_table
train
def make_dash_table(df): ''' Return a dash definitio of an HTML table for a Pandas dataframe ''' table = [] for index, row in df.iterrows(): html_row = [] for i in range(len(row)):
python
{ "resource": "" }
q250857
script_post_save
train
def script_post_save(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` """ from nbconvert.exporters.script import ScriptExporter if model['type'] != 'notebook': return global _script_export...
python
{ "resource": "" }
q250858
copy
train
def copy(string, xsel=False): """Copy given string into system clipboard. If 'xsel' is True, this will also copy into the primary x selection for middle click.""" try: _cmd = ["xclip", "-selection", "clipboard"] subprocess.Popen(_cmd, stdin=subprocess.PIPE).communicate( strin...
python
{ "resource": "" }
q250859
main
train
def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input
python
{ "resource": "" }
q250860
SerializeMixin.to_dict
train
def to_dict(self, nested=False): """Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict """ result = dict() for key in self.columns: result[key] = getattr(self, key) ...
python
{ "resource": "" }
q250861
InspectionMixin.primary_keys_full
train
def primary_keys_full(cls): """Get primary key properties for a SQLAlchemy cls. Taken from marshmallow_sqlalchemy """ mapper = cls.__mapper__ return [
python
{ "resource": "" }
q250862
ActiveRecordMixin.save
train
def save(self): """Saves the updated model to the current entity db. """
python
{ "resource": "" }
q250863
SessionManager.get
train
def get(self, name, default=None): ''' Gets the object for "name", or None if there's no such object. If
python
{ "resource": "" }
q250864
SessionManager.delete
train
def delete(self, *names): ''' Deletes the object with "name" from the session, if exists. ''' def change(session): keys = session.keys() names_in_common = [name for name in names if name
python
{ "resource": "" }
q250865
DateType.validate
train
def validate(self, obj, **kwargs): """Check if a thing is a valid date."""
python
{ "resource": "" }
q250866
DateType._clean_datetime
train
def _clean_datetime(self, obj): """Python objects want to be text.""" if isinstance(obj, datetime): # if it's not naive, put it on zulu time first: if obj.tzinfo is not None:
python
{ "resource": "" }
q250867
NIDMExporter.parse
train
def parse(self): """ Parse a result directory to extract the pieces information to be stored in NIDM-Results. """ try: # Methods: find_software, find_model_fitting, find_contrasts and # find_inferences should be defined in the children classes and ...
python
{ "resource": "" }
q250868
NIDMExporter.add_object
train
def add_object(self, nidm_object, export_file=True): """ Add a NIDMObject to a NIDM-Results export. """ if not export_file: export_dir = None else: export_dir = self.export_dir if not isinstance(nidm_object, NIDMFile): nidm_object.expo...
python
{ "resource": "" }
q250869
NIDMExporter._get_model_fitting
train
def _get_model_fitting(self, mf_id): """ Retreive model fitting with identifier 'mf_id' from the list of model fitting objects stored in self.model_fitting """ for model_fitting in self.model_fittings: if model_fitting.activity.id ==
python
{ "resource": "" }
q250870
NIDMExporter._get_contrast
train
def _get_contrast(self, con_id): """ Retreive contrast with identifier 'con_id' from the list of contrast objects stored in self.contrasts """ for contrasts in list(self.contrasts.values()): for contrast in contrasts: if
python
{ "resource": "" }
q250871
NIDMExporter._add_namespaces
train
def _add_namespaces(self): """ Add namespaces to NIDM document. """ self.doc.add_namespace(NIDM) self.doc.add_namespace(NIIRI)
python
{ "resource": "" }
q250872
NIDMExporter._create_bundle
train
def _create_bundle(self, version): """ Initialise NIDM-Results bundle. """ # *** Bundle entity if not hasattr(self, 'bundle_ent'): self.bundle_ent = NIDMResultsBundle(nidm_version=version['num']) self.bundle = ProvBundle(identifier=self.bundle_ent.id) ...
python
{ "resource": "" }
q250873
NIDMExporter._get_model_parameters_estimations
train
def _get_model_parameters_estimations(self, error_model): """ Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation. """ if error_model.dependance == NIDM_INDEPEDENT_ERROR:
python
{ "resource": "" }
q250874
NIDMExporter.save_prov_to_files
train
def save_prov_to_files(self, showattributes=False): """ Write-out provn serialisation to nidm.provn. """ self.doc.add_bundle(self.bundle) # provn_file = os.path.join(self.export_dir, 'nidm.provn') # provn_fid = open(provn_file, 'w') # # FIXME None # # prov...
python
{ "resource": "" }
q250875
PhoneType.clean_text
train
def clean_text(self, number, countries=None, country=None, **kwargs): """Parse a phone number and return in international format. If no valid phone number can be detected, None is returned. If a country code is supplied, this will be used to infer the prefix. https://github.com...
python
{ "resource": "" }
q250876
IpType.validate
train
def validate(self, ip, **kwargs): """Check to see if this is a valid ip address.""" if ip is None: return False ip = stringify(ip) if self.IPV4_REGEX.match(ip): try: socket.inet_pton(socket.AF_INET, ip) return True ...
python
{ "resource": "" }
q250877
NIDMFile.export
train
def export(self, nidm_version, export_dir, prepend_path): """ Copy file over of export_dir and create corresponding triples """ if self.path is not None: if export_dir is not None: # Copy file only if export_dir is not None new_file = os.path.j...
python
{ "resource": "" }
q250878
Image.export
train
def export(self, nidm_version, export_dir): """ Create prov entity. """ if self.file is
python
{ "resource": "" }
q250879
AddressType.normalize
train
def normalize(self, address, **kwargs): """Make the address more compareable.""" # TODO: normalize well-known parts like
python
{ "resource": "" }
q250880
UrlType.clean_text
train
def clean_text(self, url, **kwargs): """Perform intensive care on URLs, see `urlnormalizer`."""
python
{ "resource": "" }
q250881
CountryType.clean_text
train
def clean_text(self, country, guess=False, **kwargs): """Determine a two-letter country code based on an input. The input may be a country code, a country name, etc. """ code = country.lower().strip() if code in self.names:
python
{ "resource": "" }
q250882
EmailType.validate
train
def validate(self, email, **kwargs): """Check to see if this is a valid email address.""" email = stringify(email) if email is None: return if not self.EMAIL_REGEX.match(email):
python
{ "resource": "" }
q250883
EmailType.clean_text
train
def clean_text(self, email, **kwargs): """Parse and normalize an email address. Returns None if this is not an email address. """ if not self.EMAIL_REGEX.match(email): return None email = strip_quotes(email) mailbox, domain =
python
{ "resource": "" }
q250884
NIDMResults.fix_for_specific_versions
train
def fix_for_specific_versions(self, rdf_data, to_replace): """ Fixes of the RDF before loading the graph. All of these are workaround to circuvent known issues of the SPM and FSL exporters. """ # Load the graph as is so that we can query g = self.parse(rdf_data) ...
python
{ "resource": "" }
q250885
NIDMResults._get_model_fitting
train
def _get_model_fitting(self, con_est_id): """ Retreive model fitting that corresponds to contrast with identifier 'con_id' from the list of model fitting objects stored in self.model_fittings """ for (mpe_id, pe_ids), contrasts in self.contrasts.items(): for c...
python
{ "resource": "" }
q250886
ExactitudeType.validate
train
def validate(self, text, **kwargs): """Returns a boolean to indicate if this is a valid instance of the type."""
python
{ "resource": "" }
q250887
ExactitudeType.normalize
train
def normalize(self, text, cleaned=False, **kwargs): """Create a represenation ideal for comparisons, but not to be shown to the user."""
python
{ "resource": "" }
q250888
ExactitudeType.normalize_set
train
def normalize_set(self, items, **kwargs): """Utility to normalize a whole set of values and get unique
python
{ "resource": "" }
q250889
DomainType.validate
train
def validate(self, obj, **kwargs): """Check if a thing is a valid domain name.""" text = stringify(obj) if text is None: return False if '.' not in text:
python
{ "resource": "" }
q250890
DomainType.clean_text
train
def clean_text(self, domain, **kwargs): """Try to extract only the domain bit from the """ try: # handle URLs by extracting the domain name domain = urlparse(domain).hostname or domain
python
{ "resource": "" }
q250891
load
train
def load(filename, to_replace=dict()): ''' Load NIDM-Results file given filename, guessing if it is a NIDM-Results pack or a JSON file Parameters ---------- filename : string specification of file to load Returns ------- nidmres : ``NIDMResults`` NIDM-Results object ''...
python
{ "resource": "" }
q250892
_find
train
def _find(string, sub_string, start_index): """Return index of sub_string in string. Raise TokenError if sub_string is not found. """ result = string.find(sub_string, start_index)
python
{ "resource": "" }
q250893
builder_from_source
train
def builder_from_source(source, filename, system_includes, nonsystem_includes, quiet=False): """Utility method that returns an ASTBuilder from source code. Args: source: 'C++ source code' filename: 'file1' Returns: ASTBuilder """
python
{ "resource": "" }
q250894
VariableDeclaration.to_string
train
def to_string(self): """Return a string that tries to reconstitute the variable decl.""" suffix = '%s %s' % (self.type, self.name)
python
{ "resource": "" }
q250895
SymbolTable._lookup_namespace
train
def _lookup_namespace(self, symbol, namespace): """Helper for lookup_symbol that only looks up variables in a namespace. Args: symbol: Symbol namespace: pointer into self.namespaces """ for namespace_part in symbol.parts: namespace =
python
{ "resource": "" }
q250896
SymbolTable._lookup_global
train
def _lookup_global(self, symbol): """Helper for lookup_symbol that only looks up global variables. Args: symbol: Symbol """ assert symbol.parts namespace = self.namespaces if len(symbol.parts) == 1: # If there is only one part, look in globals. ...
python
{ "resource": "" }
q250897
SymbolTable._lookup_in_all_namespaces
train
def _lookup_in_all_namespaces(self, symbol): """Helper for lookup_symbol that looks for symbols in all namespaces. Args: symbol: Symbol """ namespace = self.namespaces # Create a stack of namespaces. namespace_stack = [] for current in symbol.namespace_...
python
{ "resource": "" }
q250898
SymbolTable.lookup_symbol
train
def lookup_symbol(self, name, namespace_stack): """Returns AST node and module for symbol if found. Args: name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'in', 'current', 'scope'] Returns: (ast.Node, module (ie, any object stored with ...
python
{ "resource": "" }
q250899
SymbolTable._add
train
def _add(self, symbol_name, namespace, node, module): """Helper function for adding symbols.
python
{ "resource": "" }