Search is not available for this dataset
text
stringlengths
75
104k
def authenticate(username, password, service='login', encoding='utf-8', resetcred=True): """Returns True if the given username and password authenticate for the given service. Returns False otherwise. ``username``: the username to authenticate ``password``: the password in plain text...
def post(self, request): """ Save the provided data using the class' serializer. Args: request: The request being made. Returns: An ``APIResponse`` instance. If the request was successful the response will have a 200 status code and c...
def get_repr(self, obj, referent=None): """Return an HTML tree block describing the given object.""" objtype = type(obj) typename = str(objtype.__module__) + "." + objtype.__name__ prettytype = typename.replace("__builtin__.", "") name = getattr(obj, "__name__", "") if n...
def get_refkey(self, obj, referent): """Return the dict key or attribute name of obj which refers to referent.""" if isinstance(obj, dict): for k, v in obj.items(): if v is referent: return " (via its %r key)" % k for k in dir(obj) + ['__d...
def walk(self, maxresults=100, maxdepth=None): """Walk the object tree, ignoring duplicates and circular refs.""" log.debug("step") self.seen = {} self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore) # Ignore the calling frame, its builtins, globals and locals ...
def print_tree(self, maxresults=100, maxdepth=None): """Walk the object tree, pretty-printing each branch.""" self.ignore_caller() for depth, refid, rep in self.walk(maxresults, maxdepth): print(("%9d" % refid), (" " * depth * 2), rep)
def print_tree(self, maxresults=100, maxdepth=None): """Walk the object tree, pretty-printing each branch.""" self.ignore_caller() for trail in self.walk(maxresults, maxdepth): print(trail) if self.stops: print("%s paths stopped because max depth reached" % self.s...
def get_finders(): """ Set the media fixtures finders on settings.py. Example: MEDIA_FIXTURES_FILES_FINDERS = ( 'django_media_fixtures.finders.FileSystemFinder', 'django_media_fixtures.finders.AppDirectoriesFinder', # default ) """ if hasattr(settings, 'MEDI...
def get_finder(import_path): """ Imports the media fixtures files finder class described by import_path, where import_path is the full Python path to the class. """ Finder = import_string(import_path) if not issubclass(Finder, BaseFinder): raise ImproperlyConfigured('Finder "%s" is not a...
def find(self, path, all=False): """ Looks for files in the extra locations as defined in ``MEDIA_FIXTURES_FILES_DIRS``. """ matches = [] for prefix, root in self.locations: if root not in searched_locations: searched_locations.append(root) ...
def find_location(self, root, path, prefix=None): """ Finds a requested media file in a location, returning the found absolute path (or ``None`` if no match). """ if prefix: prefix = '%s%s' % (prefix, os.sep) if not path.startswith(prefix): ...
def list(self, ignore_patterns): """ List all files in all locations. """ for prefix, root in self.locations: storage = self.storages[root] for path in utils.get_files(storage, ignore_patterns): yield path, storage
def list(self, ignore_patterns): """ List all files in all app storages. """ for storage in six.itervalues(self.storages): if storage.exists(''): # check if storage location exists for path in utils.get_files(storage, ignore_patterns): yie...
def find(self, path, all=False): """ Looks for files in the app directories. """ matches = [] for app in self.apps: app_location = self.storages[app].location if app_location not in searched_locations: searched_locations.append(app_location...
def find_in_app(self, app, path): """ Find a requested media file in an app's media fixtures locations. """ storage = self.storages.get(app, None) if storage: # only try to find a file if the source dir actually exists if storage.exists(path): ...
def set_options(self, **options): """ Set instance variables based on an options dict """ self.interactive = options['interactive'] self.verbosity = options['verbosity'] self.symlink = options['link'] self.clear = options['clear'] self.dry_run = options['d...
def collect(self): """ Perform the bulk of the work of collectmedia. Split off from handle() to facilitate testing. """ if self.symlink and not self.local: raise CommandError("Can't symlink to a remote destination.") if self.clear: self.clear_dir...
def clear_dir(self, path): """ Deletes the given relative path using the destination storage backend. """ dirs, files = self.storage.listdir(path) for f in files: fpath = os.path.join(path, f) if self.dry_run: self.log("Pretending to delete...
def delete_file(self, path, prefixed_path, source_storage): """ Checks if the target file should be deleted if it already exists """ if self.storage.exists(prefixed_path): try: # When was the target file modified last time? target_last_modified...
def link_file(self, path, prefixed_path, source_storage): """ Attempt to link ``path`` """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: return self.log("Skipping '%s' (already linked earlier)" % path) # Delete the...
def copy_file(self, path, prefixed_path, source_storage): """ Attempt to copy ``path`` with storage """ # Skip this file if it was already copied earlier if prefixed_path in self.copied_files: return self.log("Skipping '%s' (already copied earlier)" % path) # ...
def reorderChild(self, parent, newitem): """Reorder a list to match target by moving a sequence at a time. Written for QtAbstractItemModel.moveRows. """ source = self.getItem(parent).childItems target = newitem.childItems i = 0 while i < len(source): ...
def moveRows(self, parent, index_to, index_from, length): """Move a sub sequence in a list index_to must be smaller than index_from """ source = self.getItem(parent).childItems self.beginMoveRows( parent, index_from, index_from + length - 1, parent, index_to ...
def cur_space(self, name=None): """Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned. """ if name is None: ...
def _baseattrs(self): """A dict of members expressed in literals""" result = super()._baseattrs result["spaces"] = self.spaces._baseattrs return result
def new_space(self, name=None, bases=None, formula=None, refs=None): """Create a child space. Args: name (str, optional): Name of the space. Defaults to ``SpaceN``, where ``N`` is a number determined automatically. bases (optional): A space or a sequence of space...
def import_module(self, module=None, recursive=False, **params): """Create a child space from an module. Args: module: a module object or name of the module object. recursive: Not yet implemented. **params: arguments to pass to ``new_space`` Returns: ...
def new_space_from_module(self, module, recursive=False, **params): """Create a child space from an module. Alias to :py:meth:`import_module`. Args: module: a module object or name of the module object. recursive: Not yet implemented. **params: arguments to ...
def new_space_from_excel( self, book, range_, sheet=None, name=None, names_row=None, param_cols=None, space_param_order=None, cells_param_order=None, transpose=False, names_col=None, param_rows=None, ): """Create...
def restore_state(self, system): """Called after unpickling to restore some attributes manually.""" for space in self._spaces.values(): space.restore_state(system)
def new_space( self, name=None, bases=None, formula=None, *, refs=None, source=None, is_derived=False, prefix="" ): """Create a new child space. Args: name (str): Name of the space. If omitted, the space is ...
def get_node(obj, args, kwargs): """Create a node from arguments and return it""" if args is None and kwargs is None: return (obj,) if kwargs is None: kwargs = {} return obj, _bind_args(obj, args, kwargs)
def node_get_args(node): """Return an ordered mapping from params to args""" obj = node[OBJ] key = node[KEY] boundargs = obj.formula.signature.bind(*key) boundargs.apply_defaults() return boundargs.arguments
def tuplize_key(obj, key, remove_extra=False): """Args""" paramlen = len(obj.formula.parameters) if isinstance(key, str): key = (key,) elif not isinstance(key, Sequence): key = (key,) if not remove_extra: return key else: arglen = len(key) if arglen: ...
def defcells(space=None, name=None, *funcs): """Decorator/function to create cells from Python functions. Convenience decorator/function to create new cells directly from function definitions or function objects substituting for calling :py:meth:`new_cells <modelx.core.space.StaticSpace.new_cells>` ...
def get_object(name: str): """Get a modelx object from its full name.""" # TODO: Duplicate of system.get_object elms = name.split(".") parent = get_models()[elms.pop(0)] while len(elms) > 0: obj = elms.pop(0) parent = getattr(parent, obj) return parent
def _get_node(name: str, args: str): """Get node from object name and arg string Not Used. Left for future reference purpose. """ obj = get_object(name) args = ast.literal_eval(args) if not isinstance(args, tuple): args = (args,) return obj.node(*args)
def cur_model(model=None): """Get and/or set the current model. If ``model`` is given, set the current model to ``model`` and return it. ``model`` can be the name of a model object, or a model object itself. If ``model`` is not given, the current model is returned. """ if model is None: ...
def cur_space(space=None): """Get and/or set the current space of the current model. If ``name`` is given, the current space of the current model is set to ``name`` and return it. If ``name`` is not given, the current space of the current model is returned. """ if space is None: if ...
def custom_showwarning( message, category, filename="", lineno=-1, file=None, line=None ): """Hook to override default showwarning. https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings """ if file is None: file = sys.stderr if file is None: ...
def custom_showtraceback( self, exc_tuple=None, filename=None, tb_offset=None, exception_only=False, running_compiled_code=False, ): """Custom showtraceback for monkey-patching IPython's InteractiveShell https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook """ ...
def excepthook(self, except_type, exception, traceback): """Not Used: Custom exception hook to replace sys.excepthook This is for CPython's default shell. IPython does not use sys.exepthook. https://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set """ if except_type i...
def tracemessage(self, maxlen=6): """ if maxlen > 0, the message is shortened to maxlen traces. """ result = "" for i, value in enumerate(self): result += "{0}: {1}\n".format(i, get_node_repr(value)) result = result.strip("\n") lines = result.split("\...
def setup_ipython(self): """Monkey patch shell's error handler. This method is to monkey-patch the showtraceback method of IPython's InteractiveShell to __IPYTHON__ is not detected when starting an IPython kernel, so this method is called from start_kernel in spyder-modelx. ...
def restore_ipython(self): """Restore default IPython showtraceback""" if not self.is_ipysetup: return shell_class = type(self.shell) shell_class.showtraceback = shell_class.default_showtraceback del shell_class.default_showtraceback self.is_ipysetup = False
def restore_python(self): """Restore Python settings to the original states""" orig = self.orig_settings sys.setrecursionlimit(orig["sys.recursionlimit"]) if "sys.tracebacklimit" in orig: sys.tracebacklimit = orig["sys.tracebacklimit"] else: if hasattr(sy...
def get_object(self, name): """Retrieve an object by its absolute name.""" parts = name.split(".") model_name = parts.pop(0) return self.models[model_name].get_object(".".join(parts))
def get_modeltree(model=None): """Alias to :func:`get_tree`.""" if model is None: model = mx.cur_model() treemodel = ModelTreeModel(model._baseattrs) view = QTreeView() view.setModel(treemodel) view.setWindowTitle("Model %s" % model.name) view.setAlternatingRowColors(True) return...
def show_tree(model=None): """Display the model tree window. Args: model: :class:`Model <modelx.core.model.Model>` object. Defaults to the current model. Warnings: For this function to work with Spyder, *Graphics backend* option of Spyder must be set to *inline*. ""...
def get_interfaces(impls): """Get interfaces from their implementations.""" if impls is None: return None elif isinstance(impls, OrderMixin): result = OrderedDict() for name in impls.order: result[name] = impls[name].interface return result elif isinstance(i...
def get_impls(interfaces): """Get impls from their interfaces.""" if interfaces is None: return None elif isinstance(interfaces, Mapping): return {name: interfaces[name]._impl for name in interfaces} elif isinstance(interfaces, Sequence): return [interfaces._impl for interfaces...
def update_lazyevals(self): """Update all LazyEvals in self self.lzy_evals must be set to LazyEval object(s) enough to update all owned LazyEval objects. """ if self.lazy_evals is None: return elif isinstance(self.lazy_evals, LazyEval): self.lazy_...
def evalrepr(self): """Evaluable repr""" if self.is_model(): return self.get_fullname() else: return self.parent.evalrepr + "." + self.name
def _baseattrs(self): """A dict of members expressed in literals""" result = { "type": type(self).__name__, "id": id(self), "name": self.name, "fullname": self.fullname, "repr": self._get_repr(), } return result
def _to_attrdict(self, attrs=None): """Get extra attributes""" result = self._baseattrs for attr in attrs: if hasattr(self, attr): result[attr] = getattr(self, attr)._to_attrdict(attrs) return result
def _baseattrs(self): """A dict of members expressed in literals""" result = {"type": type(self).__name__} try: result["items"] = { name: item._baseattrs for name, item in self.items() if name[0] != "_" } except: ...
def _update_data(self): """Update altfunc""" func = self.owner.formula.func codeobj = func.__code__ name = func.__name__ # self.cells.name # func.__name__ namespace_impl = self.owner._namespace_impl.get_updated() namespace = namespace_impl.interfaces selfnode ...
def convert_args(args, kwargs): """If args and kwargs contains Cells, Convert them to their values.""" found = False for arg in args: if isinstance(arg, Cells): found = True break if found: args = tuple( arg.value if isinstance(arg, Cells) else arg f...
def shareable_parameters(cells): """Return parameter names if the parameters are shareable among cells. Parameters are shareable among multiple cells when all the cells have the parameters in the same order if they ever have any. For example, if cells are foo(), bar(x), baz(x, y), then ('x', 'y') ...
def copy(self, space=None, name=None): """Make a copy of itself and return it.""" return Cells(space=space, name=name, formula=self.formula)
def node(self, *args, **kwargs): """Return a :class:`CellNode` object for the given arguments.""" return CellNode(get_node(self._impl, *convert_args(args, kwargs)))
def _baseattrs(self): """A dict of members expressed in literals""" result = super()._baseattrs result["params"] = ", ".join(self.parameters) return result
def value(self): """Return the value of the cells.""" if self.has_value: return self._impl[OBJ].get_value(self._impl[KEY]) else: raise ValueError("Value not found")
def _baseattrs(self): """A dict of members expressed in literals""" result = { "type": type(self).__name__, "obj": self.cells._baseattrs, "args": self.args, "value": self.value if self.has_value else None, "predslen": len(self.preds), ...
def reorder_list(source, targetorder): """Reorder a list to match target by moving a sequence at a time. Written for QtAbstractItemModel.moveRows. """ i = 0 while i < len(source): if source[i] == targetorder[i]: i += 1 continue else: i0 = i ...
def move_elements(source, index_to, index_from, length): """Move a sub sequence in a list""" sublist = [source.pop(index_from) for _ in range(length)] for _ in range(length): source.insert(index_to, sublist.pop())
def _get_col_index(name): """Convert column name to index.""" index = string.ascii_uppercase.index col = 0 for c in name.upper(): col = col * 26 + index(c) + 1 return col
def _get_range(book, range_, sheet): """Return a range as nested dict of openpyxl cells.""" filename = None if isinstance(book, str): filename = book book = opxl.load_workbook(book, data_only=True) elif isinstance(book, opxl.Workbook): pass else: raise TypeError ...
def read_range(filepath, range_expr, sheet=None, dict_generator=None): """Read values from an Excel range into a dictionary. `range_expr` ie either a range address string, such as "A1", "$C$3:$E$5", or a defined name string for a range, such as "NamedRange1". If a range address is provided, `sheet` arg...
def _get_namedrange(book, rangename, sheetname=None): """Get range from a workbook. A workbook can contain multiple definitions for a single name, as a name can be defined for the entire book or for a particular sheet. If sheet is None, the book-wide def is searched, otherwise sheet-local def ...
def get_mro(self, space): """Calculate the Method Resolution Order of bases using the C3 algorithm. Code modified from http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/ Args: bases: sequence of direct base spaces. Returns: mro as ...
def _alter_code(code, **attrs): """Create a new code object by altering some of ``code`` attributes Args: code: code objcect attrs: a mapping of names of code object attrs to their values """ PyCode_New = ctypes.pythonapi.PyCode_New PyCode_New.argtypes = ( ctypes.c_int, ...
def alter_freevars(func, globals_=None, **vars): """Replace local variables with free variables Warnings: This function does not work. """ if globals_ is None: globals_ = func.__globals__ frees = tuple(vars.keys()) oldlocs = func.__code__.co_names newlocs = tuple(name for ...
def fix_lamdaline(source): """Remove the last redundant token from lambda expression lambda x: return x) ^ Return string without irrelevant tokens returned from inspect.getsource on lamda expr returns """ # Using undocumented generate_tokens due to a tokenize.tokenize bug...
def find_funcdef(source): """Find the first FuncDef ast object in source""" try: module_node = compile( source, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST ) except SyntaxError: return find_funcdef(fix_lamdaline(source)) for node in ast.walk(module_node): ...
def extract_params(source): """Extract parameters from a function definition""" funcdef = find_funcdef(source) params = [] for node in ast.walk(funcdef.args): if isinstance(node, ast.arg): if node.arg not in params: params.append(node.arg) return params
def extract_names(source): """Extract names from a function definition Looks for a function definition in the source. Only the first function definition is examined. Returns: a list names(identifiers) used in the body of the function excluding function parameters. """ if sour...
def is_funcdef(src): """True if src is a function definition""" module_node = ast.parse(dedent(src)) if len(module_node.body) == 1 and isinstance( module_node.body[0], ast.FunctionDef ): return True else: return False
def remove_decorator(source: str): """Remove decorators from function definition""" lines = source.splitlines() atok = asttokens.ASTTokens(source, parse=True) for node in ast.walk(atok.tree): if isinstance(node, ast.FunctionDef): break if node.decorator_list: deco_first...
def replace_funcname(source: str, name: str): """Replace function name""" lines = source.splitlines() atok = asttokens.ASTTokens(source, parse=True) for node in ast.walk(atok.tree): if isinstance(node, ast.FunctionDef): break i = node.first_token.index for i in range(node....
def has_lambda(src): """True if only one lambda expression is included""" module_node = ast.parse(dedent(src)) lambdaexp = [node for node in ast.walk(module_node) if isinstance(node, ast.Lambda)] return bool(lambdaexp)
def _reload(self, module=None): """Reload the source function from the source module. **Internal use only** Update the source function of the formula. This method is used to updated the underlying formula when the source code of the module in which the source function is...
def get_description(): """Get long description from README.""" with open(path.join(here, 'README.rst'), 'r') as f: data = f.read() return data
def to_frame(self, *args): """Convert the cells in the view into a DataFrame object. If ``args`` is not given, this method returns a DataFrame that has an Index or a MultiIndex depending of the number of cells parameters and columns each of which corresponds to each cells includ...
def _baseattrs(self): """A dict of members expressed in literals""" result = super()._baseattrs result["static_spaces"] = self.static_spaces._baseattrs result["dynamic_spaces"] = self.dynamic_spaces._baseattrs result["cells"] = self.cells._baseattrs result["refs"] = self...
def new_cells(self, name=None, formula=None): """Create a cells in the space. Args: name: If omitted, the model is named automatically ``CellsN``, where ``N`` is an available number. func: The function to define the formula of the cells. Returns: ...
def import_funcs(self, module): """Create a cells from a module.""" # Outside formulas only newcells = self._impl.new_cells_from_module(module) return get_interfaces(newcells)
def new_cells_from_excel( self, book, range_, sheet=None, names_row=None, param_cols=None, param_order=None, transpose=False, names_col=None, param_rows=None, ): """Create multiple cells from an Excel range. This method...
def get_object(self, name): """Retrieve an object by a dotted name relative to the space.""" parts = name.split(".") child = parts.pop(0) if parts: return self.spaces[child].get_object(".".join(parts)) else: return self._namespace_impl[child]
def _get_dynamic_base(self, bases_): """Create or get the base space from a list of spaces if a direct base space in `bases` is dynamic, replace it with its base. """ bases = tuple( base.bases[0] if base.is_dynamic() else base for base in bases_ ) if...
def _new_dynspace( self, name=None, bases=None, formula=None, refs=None, arguments=None, source=None, ): """Create a new dynamic root space.""" if name is None: name = self.spacenamer.get_next(self.namespace) if name in se...
def get_dynspace(self, args, kwargs=None): """Create a dynamic root space Called from interface methods """ node = get_node(self, *convert_args(args, kwargs)) key = node[KEY] if key in self.param_spaces: return self.param_spaces[key] else: ...
def restore_state(self, system): """Called after unpickling to restore some attributes manually.""" super().restore_state(system) BaseSpaceContainerImpl.restore_state(self, system) for cells in self._cells.values(): cells.restore_state(system)
def new_cells_from_excel( self, book, range_, sheet=None, names_row=None, param_cols=None, param_order=None, transpose=False, names_col=None, param_rows=None, ): """Create multiple cells from an Excel range. Args: ...
def set_attr(self, name, value): """Implementation of attribute setting ``space.name = value`` by user script Called from ``Space.__setattr__`` """ if not is_valid_name(name): raise ValueError("Invalid name '%s'" % name) if name in self.namespace: ...
def del_attr(self, name): """Implementation of attribute deletion ``del space.name`` by user script Called from ``StaticSpace.__delattr__`` """ if name in self.namespace: if name in self.cells: self.del_cells(name) elif name in self.spaces...
def del_space(self, name): """Delete a space.""" if name not in self.spaces: raise ValueError("Space '%s' does not exist" % name) if name in self.static_spaces: space = self.static_spaces[name] if space.is_derived: raise ValueError( ...
def del_cells(self, name): """Implementation of cells deletion ``del space.name`` where name is a cells, or ``del space.cells['name']`` """ if name in self.cells: cells = self.cells[name] self.cells.del_item(name) self.inherit() se...
def evalrepr(self): """Evaluable repr""" args = [repr(arg) for arg in get_interfaces(self.argvalues)] param = ", ".join(args) return "%s(%s)" % (self.parent.evalrepr, param)
def cellsiter_to_dataframe(cellsiter, args, drop_allna=True): """Convert multiple cells to a frame. If args is an empty sequence, all values are included. If args is specified, cellsiter must have shareable parameters. Args: cellsiter: A mapping from cells names to CellsImpl objects. a...