code
stringlengths
1
18.2k
def merge_down_loci(self): """Called internally to make loci overlapping into one set""" old_locus_size = -1 z = 0 while len(self.loci) != old_locus_size: z+=1 old_locus_size = len(self.loci) locus_size = len(self.loci) if self.verbose: sys.stderr.write(str(locus_size)+" Combining down loci step "+str(z)+" \r") combine...
def push(collector, image, **kwargs): """Push an image""" if not image.image_index: raise BadOption("The chosen image does not have a image_index configuration", wanted=image.name) tag = kwargs["artifact"] if tag is NotSpecified: tag = collector.configuration["harpoon"].tag if tag is not NotSpecified: image.tag = tag B...
def push_all(collector, **kwargs): """Push all the images""" configuration = collector.configuration configuration["harpoon"].do_push = True configuration["harpoon"].only_pushable = True make_all(collector, **kwargs)
def pull_arbitrary(collector, image, **kwargs): """Pull an arbitrary image""" image_index_of = lambda image: urlparse("https://{0}".format(image)).netloc if image.startswith("file://"): parsed = urlparse(image) filename = parsed.netloc + parsed.path if not os.path.exists(filename): raise HarpoonError("Provided file doe...
def pull(collector, image, **kwargs): """Pull an image""" if not image.image_index: raise BadOption("The chosen image does not have a image_index configuration", wanted=image.name) tag = kwargs["artifact"] if tag is NotSpecified: collector.configuration["harpoon"].tag if tag is not NotSpecified: image.tag = tag log.inf...
def pull_dependencies(collector, image, **kwargs): """Pull an image's dependent images""" for dep in image.commands.dependent_images: kwargs["image"] = dep pull_arbitrary(collector, **kwargs)
def pull_parent(collector, image, **kwargs): """DEPRECATED - use pull_dependencies instead""" log.warning("DEPRECATED - use pull_dependencies instead") pull_dependencies(collector, image, **kwargs)
def pull_all(collector, image, **kwargs): """Pull all the images""" images = collector.configuration["images"] for layer in Builder().layered(images, only_pushable=True): for image_name, image in layer: log.info("Pulling %s", image_name) pull(collector, image, **kwargs)
def pull_all_external(collector, **kwargs): """Pull all the external dependencies of all the images""" deps = set() images = collector.configuration["images"] for layer in Builder().layered(images): for image_name, image in layer: for dep in image.commands.external_dependencies: deps.add(dep) for dep in sorted(deps): k...
def make(collector, image, **kwargs): """Just create an image""" tag = kwargs.get("artifact", NotSpecified) if tag is NotSpecified: tag = collector.configuration["harpoon"].tag if tag is not NotSpecified: image.tag = tag Builder().make_image(image, collector.configuration["images"]) print("Created image {0}".format(ima...
def make_all(collector, **kwargs): """Creates all the images in layered order""" configuration = collector.configuration push = configuration["harpoon"].do_push only_pushable = configuration["harpoon"].only_pushable if push: only_pushable = True tag = kwargs.get("artifact", NotSpecified) if tag is NotSpecified: tag = c...
def make_pushable(collector, **kwargs): """Make only the pushable images and their dependencies""" configuration = collector.configuration configuration["harpoon"].do_push = True configuration["harpoon"].only_pushable = True make_all(collector, **kwargs)
def list_tasks(collector, tasks, **kwargs): """List the available_tasks""" print("Available tasks to choose from are:") print("Use the --task option to choose one") print("") keygetter = lambda item: item[1].label tasks = sorted(tasks.items(), key=keygetter) for label, items in itertools.groupby(tasks, keygetter): prin...
def delete_untagged(collector, **kwargs): """Find the untagged images and remove them""" configuration = collector.configuration docker_api = configuration["harpoon"].docker_api images = docker_api.images() found = False for image in images: if image["RepoTags"] == ["<none>:<none>"]: found = True image_id = image["Id"]...
def show(collector, **kwargs): """Show what images we have""" configuration = collector.configuration flat = configuration.get("harpoon.flat", False) only_pushable = configuration.get("harpoon.only_pushable", False) for index, layer in enumerate(Builder().layered(configuration["images"], only_pushable=only_pushable)): ...
def show_pushable(collector, **kwargs): """Show what images we have""" collector.configuration['harpoon'].only_pushable = True show(collector, **kwargs)
def print_all_dockerfiles(collector, **kwargs): """Print all the dockerfiles""" for name, image in collector.configuration["images"].items(): print("{0}".format(name)) print("-" * len(name)) kwargs["image"] = image print_dockerfile(collector, **kwargs)
def read_login(collector, image, **kwargs): """Login to a docker registry with read permissions""" docker_api = collector.configuration["harpoon"].docker_api collector.configuration["authentication"].login(docker_api, image, is_pushing=False, global_docker=True)
def write_login(collector, image, **kwargs): """Login to a docker registry with write permissions""" docker_api = collector.configuration["harpoon"].docker_api collector.configuration["authentication"].login(docker_api, image, is_pushing=True, global_docker=True)
def untag(collector, image, artifact, **kwargs): """Tag an image!""" if artifact in (None, "", NotSpecified): artifact = collector.configuration["harpoon"].tag if artifact is NotSpecified: raise BadOption("Please specify a tag using the artifact or tag options") image.tag = artifact image_name = image.image_name_with_t...
def tag(collector, image, artifact, **kwargs): """Tag an image!""" if artifact in (None, "", NotSpecified): raise BadOption("Please specify a tag using the artifact option") if image.image_index in (None, "", NotSpecified): raise BadOption("Please specify an image with an image_index option") tag = image.image_name if ...
def retrieve(collector, image, artifact, **kwargs): """Retrieve a file/folder from an image""" if artifact in (None, "", NotSpecified): raise BadOption("Please specify what to retrieve using the artifact option") if collector.configuration["harpoon"].tag is not NotSpecified: image.tag = collector.configuration["harpoon...
def get_salt(request): """ return the user password salt. If the user doesn't exist return a pseudo salt. """ try: username = request.POST["username"] except KeyError: # log.error("No 'username' in POST data?!?") return HttpResponseBadRequest() try: request.server_challenge = request.session[SERVER_CHALLENGE_KEY] excep...
@TimingAttackPreventer # log.debug("\nsend init_pbkdf2_salt %r to client.", init_pbkdf2_salt) return response
def display_login_info(sender, user, request, **kwargs): """ Create a message, after login. Because this signal receiver will be called **after** auth.models.update_last_login(), the user.last_login information was updated before! As a work-a-round, we add **user.previous_login** in forms.SecureLoginForm.clean() """ if...
def _get_parameter_symbols(self, n_counter, k_counter): r""" Calculates parameters Y expressions and beta coefficients in :math:`X = {A(\beta_0,\beta_1\ldots \beta_n) \cdot Y}` :param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments :type n_counter: list[:class:`~means.core.de...
= sp.Matrix([sum(symbolic_species[i,:]) for i in range(n_species)]) else : # In univariate case, only the diagonal elements are needed beta_in_matrix = sp.Matrix([symbolic_species[i,i] for i in range(n_species)]) # Covariance symbols are read into a matrix. Variances are the diagonal elements covariance_matrix = sp.Mat...
alpha_exprs[sp_idx,sp_idx]=0 alpha_exprs[sp_idx,sp_idx]=alpha_bar_exprs[sp_idx]-sum(alpha_exprs[sp_idx,:]) # Each row in moment matrix contains the exponents of Xs for a given moment # Each row in Y_exprs and beta_multipliers has elements on the appropriate power # determined by the corresponding row in the moment matr...
higher order moments :math: `\mathbb{E}(Y_{ij}^n) \rightarrow (\alpha_{ij})_n` alpha_m = [self._gamma_factorial(a,n) for n in range(2, n_moment+1)] # Substitute alpha term for symbolic species subs_pairs += zip(Y_to_substitute, alpha_m) subs_pairs.append((symbolic_species[i], a)) # Add first order expression to the end...
def _compute_raw_moments(self, n_counter, k_counter): r""" Compute :math:`X_i` Gamma type 1: :math:`X_i = \frac {\beta_i}{\beta_0}Y_0 + Y_i` Gamma type 2: :math:`X_i = \sum_{k=0}^{i} \frac {\beta_i}{\beta_k}Y_k` :param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments :type n_c...
def _gamma_factorial(self, expr, n): r""" Compute :math:`\frac {(\alpha)_m = (\alpha + m - 1)!}{(\alpha - 1)!}` See Eq. 3 in Gamma moment closure Lakatos 2014 unpublished :param expr: a symbolic expression :type expr: :param n: :type n: `int` :return: a symbolic expression """ if n == 0: return 1 return product([expr+i...
def _get_covariance_symbol(self, q_counter, sp1_idx, sp2_idx): r""" Compute second order moments i.e. variances and covariances Covariances equal to 0 in univariate case :param q_counter: moment matrix :param sp1_idx: index of one species :param sp2_idx: index of another species :return: second order moments matrix of ...
def throttle_login(request): """Throttles a client by keeping track of the number of failed login attempts. If the user succeeds at a login before the max attempts has been reached, the attempts are reset. """ email = request.POST['email'] password = request.POST['password'] # if the form is not filled out completely, ...
attempts >= MAX_LOGIN_ATTEMPTS: # once the max attempts has been reached, deactive the account # and email the admins user_already_inactive = False try: user = User.objects.get(username=email) except User.DoesNotExist: user = None if user: if user.is_active: user.is_active = False user.save() # this condition tells me ...
uses a different browser, this # flag will be gone, but the next login attempt will be caught again by # the above logic request.session['login_allowed'] = login_allowed return login_allowed
def list_js_files(dir): """ Generator for all JavaScript files in the directory, recursively >>> 'examples/module.js' in list(list_js_files('examples')) True """ for dirpath, dirnames, filenames in os.walk(dir): for filename in filenames: if is_js_file(filename): yield os.path.join(dirpath, filename)
def save_file(path, text): """ Save a string to a file. If the containing directory(ies) doesn't exist, this creates it. """ dir = os.path.dirname(path) if not os.path.exists(dir): os.makedirs(dir) fd = open(path, 'w') try: fd.write(text) finally: fd.close()
def split_delimited(delimiters, split_by, text): """ Generator that walks the ``text`` and splits it into an array on ``split_by``, being careful not to break inside a delimiter pair. ``delimiters`` should be an even-length string with each pair of matching delimiters listed together, open first. >>> list(split_delimit...
c in '[]{}, ', '[{foo,[bar, baz]}]')) ['', '', 'foo', '', 'bar', '', 'baz', '', '', ''] """ delims = [0] * (old_div(len(delimiters), 2)) actions = {} for i in range(0, len(delimiters), 2): actions[delimiters[i]] = (old_div(i, 2), 1) actions[delimiters[i + 1]] = (old_div(i, 2), -1) if isinstance(split_by, str): def spli...
def get_doc_comments(text): r""" Return a list of all documentation comments in the file text. Each comment is a pair, with the first element being the comment text and the second element being the line after it, which may be needed to guess function & arguments. >>> get_doc_comments(read_file('examples/module.js'))[0]...
def split_tag(section): """ Split the JSDoc tag text (everything following the @) at the first whitespace. Returns a tuple of (tagname, body). """ splitval = re.split('\s+', section, 1) tag, body = len(splitval) > 1 and splitval or (splitval[0], '') return tag.strip(), body.strip()
def guess_function_name(next_line, regexps=FUNCTION_REGEXPS): """ Attempt to determine the function name from the first code line following the comment. The patterns recognized are described by `regexps`, which defaults to FUNCTION_REGEXPS. If a match is successful, returns the function name. Otherwise, returns None. "...
def guess_parameters(next_line): """ Attempt to guess parameters based on the presence of a parenthesized group of identifiers. If successful, returns a list of parameter names; otherwise, returns None. """ match = re.search('\(([\w\s,]+)\)', next_line) if match: return [arg.strip() for arg in match.group(1).split(',')...
def parse_comment(doc_comment, next_line): r""" Split the raw comment text into a dictionary of tags. The main comment body is included as 'doc'. >>> comment = get_doc_comments(read_file('examples/module.js'))[4][0] >>> parse_comment(strip_stars(comment), '')['doc'] 'This is the documentation for the fourth function.\n...
else: tags[tag] = body return tags
def parse_comments_for_file(filename): """ Return a list of all parsed comments in a file. Mostly for testing & interactive use. """ return [parse_comment(strip_stars(comment), next_line) for comment, next_line in get_doc_comments(read_file(filename))]
def build_dependency_graph(start_nodes, js_doc): """ Build a graph where nodes are filenames and edges are reverse dependencies (so an edge from jquery.js to jquery.dimensions.js indicates that jquery.js must be included before jquery.dimensions.js). The graph is represented as a dictionary from filename to (in-degree,...
def topological_sort(dependencies, start_nodes): """ Perform a topological sort on the dependency graph `dependencies`, starting from list `start_nodes`. """ retval = [] def edges(node): return dependencies[node][1] def in_degree(node): return dependencies[node][0] def remove_incoming(node): dependencies[node][0] = in_...
def make_index(css_class, entities): """ Generate the HTML index (a short description and a link to the full documentation) for a list of FunctionDocs or ClassDocs. """ def make_entry(entity): return ('<dt><a href = "%(url)s">%(name)s</a></dt>\n' + '<dd>%(doc)s</dd>') % { 'name': entity.name, 'url': entity.url, 'doc': ...
def htmlize_paragraphs(text): """ Convert paragraphs delimited by blank lines into HTML text enclosed in <p> tags. """ paragraphs = re.split('(\r?\n)\s*(\r?\n)', text) return '\n'.join('<p>%s</p>' % paragraph for paragraph in paragraphs)
def get_path_list(opts): """ Return a list of all root paths where JS files can be found, given the command line options (in dict form) for this script. """ paths = [] for opt, arg in list(opts.items()): if opt in ('-p', '--jspath'): paths.append(arg) return paths or [os.getcwd()]
def run_and_exit_if(opts, action, *names): """ Run the no-arg function `action` if any of `names` appears in the option dict `opts`. """ for name in names: if name in opts: action() sys.exit(0)
def main(args=sys.argv): """ Main command-line invocation. """ try: opts, args = getopt.gnu_getopt(args[1:], 'p:o:jdt', [ 'jspath=', 'output=', 'private', 'json', 'dependencies', 'test', 'help']) opts = dict(opts) except getopt.GetoptError: usage() sys.exit(2) run_and_exit_if(opts, run_doctests, '--test') run_and_exit_...
def _build_dependencies(self): """ >>> CodeBaseDoc(['examples'])['subclass.js'].module.all_dependencies ['module.js', 'module_closure.js', 'class.js', 'subclass.js'] """ for module in list(self.values()): module.set_all_dependencies(find_dependencies([module.name], self))
def _build_superclass_lists(self): """ >>> CodeBaseDoc(['examples']).all_classes['MySubClass'].all_superclasses[0].name 'MyClass' """ cls_dict = self.all_classes for cls in list(cls_dict.values()): cls.all_superclasses = [] superclass = cls.superclass try: while superclass: superclass_obj = cls_dict[superclass] cls.all...
def translate_ref_to_url(self, ref, in_comment=None): """ Translates an @see or @link reference to a URL. If the ref is of the form #methodName, it looks for a method of that name on the class `in_comment` or parent class of method `in_comment`. In this case, it returns a local hash URL, since the method is guaranteed ...
= self.all_classes[in_comment.member] elif isinstance(in_comment, ClassDoc): search_in = in_comment else: search_in = None try: return search_in.get_method(method_name).url except AttributeError: pass def lookup_ref(file_doc): for fn in file_doc.functions: if fn.name == method_name: return fn.url return None elif '#' i...
def translate_links(self, text, in_comment=None): """ Turn all @link tags in `text` into HTML anchor tags. `in_comment` is the `CommentDoc` that contains the text, for relative method lookups. """ def replace_link(matchobj): ref = matchobj.group(1) return '<a href = "%s">%s</a>' % ( self.translate_ref_to_url(ref, in_co...
def to_dict(self, files=None): """ Converts the CodeBaseDoc into a dictionary containing the to_dict() representations of each contained file. The optional `files` list lets you restrict the dict to include only specific files. >>> CodeBaseDoc(['examples']).to_dict(['class.js']).get('module.js') >>> CodeBaseDoc(['examp...
def save_docs(self, files=None, output_dir=None): """ Save documentation files for codebase into `output_dir`. If output dir is None, it'll refrain from building the index page and build the file(s) in the current directory. If `files` is None, it'll build all files in the codebase. """ if output_dir: try: os.mkdir(out...
def functions(self): """ Returns a generator of all standalone functions in the file, in textual order. >>> file = FileDoc('module.js', read_file('examples/module.js')) >>> list(file.functions)[0].name 'the_first_function' >>> list(file.functions)[3].name 'not_auto_discovered' """ def is_function(comment): return isins...
def methods(self): """ Returns a generator of all member functions in the file, in textual order. >>> file = FileDoc('class.js', read_file('examples/class.js')) >>> file.methods.next().name 'first_method' """ def is_method(comment): return isinstance(comment, FunctionDoc) and comment.member return self._filtered_iter(i...
def get_as_list(self, tag_name): """ Return the value of a tag, making sure that it's a list. Absent tags are returned as an empty-list; single tags are returned as a one-element list. The returned list is a copy, and modifications do not affect the original object. """ val = self.get(tag_name, []) if isinstance(val, l...
def to_dict(self): """ Return this ModuleDoc as a dict. In addition to `CommentDoc` defaults, this has: - **name**: The module name. - **dependencies**: A list of immediate dependencies. - **all_dependencies**: A list of all dependencies. """ vars = super(ModuleDoc, self).to_dict() vars['dependencies'] = self.dependenc...
def to_html(self, codebase): """ Convert this to HTML. """ html = '' def build_line(key, include_pred, format_fn): val = getattr(self, key) if include_pred(val): return '<dt>%s</dt><dd>%s</dd>\n' % (printable(key), format_fn(val)) else: return '' def build_dependency(val): return ', '.join('<a href = "%s.html">%s</a>' ...
def params(self): """ Returns a ParamDoc for each parameter of the function, picking up the order from the actual parameter list. >>> comments = parse_comments_for_file('examples/module_closure.js') >>> fn2 = FunctionDoc(comments[2]) >>> fn2.params[0].name 'elem' >>> fn2.params[1].type 'Function(DOM)' >>> fn2.params[2]...
def return_val(self): """ Returns the return value of the function, as a ParamDoc with an empty name: >>> comments = parse_comments_for_file('examples/module_closure.js') >>> fn1 = FunctionDoc(comments[1]) >>> fn1.return_val.name '' >>> fn1.return_val.doc 'Some value' >>> fn1.return_val.type 'String' >>> fn2 = Function...
def exceptions(self): """ Returns a list of ParamDoc objects (with empty names) of the exception tags for the function. >>> comments = parse_comments_for_file('examples/module_closure.js') >>> fn1 = FunctionDoc(comments[1]) >>> fn1.exceptions[0].doc 'Another exception' >>> fn1.exceptions[1].doc 'A fake exception' >>> f...
def to_dict(self): """ Convert this FunctionDoc to a dictionary. In addition to `CommentDoc` keys, this adds: - **name**: The function name - **params**: A list of parameter dictionaries - **options**: A list of option dictionaries - **exceptions**: A list of exception dictionaries - **return_val**: A dictionary descri...
def to_html(self, codebase): """ Convert this `FunctionDoc` to HTML. """ body = '' for section in ('params', 'options', 'exceptions'): val = getattr(self, section) if val: body += '<h5>%s</h5>\n<dl class = "%s">%s</dl>' % ( printable(section), section, '\n'.join(param.to_html() for param in val)) body += codebase.build...
def get_method(self, method_name, default=None): """ Returns the contained method of the specified name, or `default` if not found. """ for method in self.methods: if method.name == method_name: return method return default
def to_dict(self): """ Convert this ClassDoc to a dict, such as if you want to use it in a template or string interpolation. Aside from the basic `CommentDoc` fields, this also contains: - **name**: The class name - **method**: A list of methods, in their dictionary form. """ vars = super(ClassDoc, self).to_dict() vars...
def to_html(self, codebase): """ Convert this ClassDoc to HTML. This returns the default long-form HTML description that's used when the full docs are built. """ return ('<a name = "%s" />\n<div class = "jsclass">\n' + '<h3>%s</h3>\n%s\n<h4>Methods</h4>\n%s</div>') % ( self.name, self.name, htmlize_paragraphs(codebase....
def to_html(self, css_class=''): """ Returns the parameter as a dt/dd pair. """ if self.name and self.type: header_text = '%s (%s)' % (self.name, self.type) elif self.type: header_text = self.type else: header_text = self.name return '<dt>%s</dt><dd>%s</dd>' % (header_text, self.doc)
def has_max_attempts(self): """stub""" if 'maxAttempts' not in self.my_osid_object._my_map or \ self.my_osid_object._my_map['maxAttempts'] is None: return False return True
def _init_map(self): """stub""" self.my_osid_object_form._my_map['reviewOptions'] = \ dict(self._review_options_metadata['default_object_values'][0]) self.my_osid_object_form._my_map['reviewOptions']['whetherCorrect'] = \ dict(self._whether_correct_metadata['default_object_values'][0]) self.my_osid_object_form._my_map[...
def _init_metadata(self): """stub""" self._review_options_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'review_options'), 'element_label': 'Review Options', 'instructions': 'Choose various Review Options', 'required': False, 'read_only': False, 'linked': False,...
True, 'array': False, 'default_boolean_values': [True], 'syntax': 'BOOLEAN', } self._after_attempt_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'during-attempt'), 'element_label': 'During Attempt', 'instructions': 'accepts a boolean (True/False) value', 'requir...
[None], 'syntax': 'INTEGER', 'minimum_integer': self._min_max_attempts_value, 'maximum_integer': self._max_max_attempts_value, 'integer_set': [] }
def set_review_whether_correct(self, during_attempt=None, after_attempt=None, before_deadline=None, after_deadline=None): """stub""" whether_correct = self.my_osid_object_form._my_map['reviewOptions']['whetherCorrect'] if during_attempt is not None: whether_correct['duringAttempt'] = bool(during_attempt) if after_attem...
def set_review_solution(self, during_attempt=None, after_attempt=None, before_deadline=None, after_deadline=None): """stub""" solution = self.my_osid_object_form._my_map['reviewOptions']['solution'] if during_attempt is not None: solution['duringAttempt'] = bool(during_attempt) if after_attempt is not None: solution['a...
def set_max_attempts(self, value): """stub""" if value is None: raise InvalidArgument('value must be an integer') if value is not None and not isinstance(value, int): raise InvalidArgument('value is not an integer') if not self.my_osid_object_form._is_valid_integer(value, self.get_max_attempts_metadata()): raise Invali...
def clear_max_attempts(self): """stub""" if (self.get_max_attempts_metadata().is_read_only() or self.get_max_attempts_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['maxAttempts'] = \ list(self._max_attempts_metadata['default_integer_values'])[0]
def can_review_whether_correct(self): """stub""" ao = self.my_osid_object.get_assessment_offered() attempt_complete = self.my_osid_object.has_ended() if ao.can_review_whether_correct_during_attempt() and not attempt_complete: return True if ao.can_review_whether_correct_after_attempt and attempt_complete: return True r...
def mangle_scope_tree(root, toplevel): """Walk over a scope tree and mangle symbol names. Args: toplevel: Defines if global scope should be mangled or not. """ def mangle(scope): # don't mangle global scope if not specified otherwise if scope.get_enclosing_scope() is None and not toplevel: return for name in scope.symb...
def _fill_scope_refs(name, scope): """Put referenced name in 'ref' dictionary of a scope. Walks up the scope tree and adds the name to 'ref' of every scope up in the tree until a scope that defines referenced name is reached. """ symbol = scope.resolve(name) if symbol is None: return orig_scope = symbol.scope scope.ref...
def visit_Identifier(self, node): """Mangle names.""" if not self._is_mangle_candidate(node): return name = node.value symbol = node.scope.resolve(node.value) if symbol is None: return mangled = symbol.scope.mangled.get(name) if mangled is not None: node.value = mangled
def run(self): """For each file in noseOfYeti/specs, output nodes to represent each spec file""" tokens = [] section = nodes.section() section['ids'].append("available-tasks") title = nodes.title() title += nodes.Text("Default tasks") section += title task_finder = TaskFinder(Collector()) for name, task in sorted(task_...
def resource_definition(resource): """ Generate a `Swagger Definitions Object <http://swagger.io/specification/#definitionsObject>`_ from a resource. """ meta = getmeta(resource) definition = { 'type': "object", 'properties': {} } for field in meta.all_fields: field_definition = {} type_def = map_field_to_type(field) i...
def cenancestor(self): """ Last universal ancestor (or the top level of the API structure). """ ancestor = parent = self.parent while parent: ancestor = parent parent = getattr(parent, 'parent', None) return ancestor
def base_path(self): """ Calculate the APIs base path """ path = UrlPath() # Walk up the API to find the base object parent = self.parent while parent: path_prefix = getattr(parent, 'path_prefix', NoPath) path = path_prefix + path parent = getattr(parent, 'parent', None) return path
def parse_operations(self): """ Flatten routes into a path -> method -> route structure """ resource_defs = { getmeta(resources.Error).resource_name: resource_definition(resources.Error), getmeta(resources.Listing).resource_name: resource_definition(resources.Listing), } paths = collections.OrderedDict() for path, oper...
# Add parameters parameters = self.generate_parameters(path) if parameters: path_spec['parameters'] = parameters # Add methods for method in operation.methods: path_spec[method.value.lower()] = operation.to_swagger() return paths, resource_defs
def get_swagger(self, request): """ Generate this document. """ api_base = self.parent paths, definitions = self.parse_operations() codecs = getattr(self.cenancestor, 'registered_codecs', CODECS) # type: dict return dict_filter({ 'swagger': '2.0', 'info': { 'title': self.title, 'version': str(getattr(api_base, 'version...
def get_ui(self, _): """ Load the Swagger UI interface """ if not self._ui_cache: content = self.load_static('ui.html') if isinstance(content, binary_type): content = content.decode('UTF-8') self._ui_cache = content.replace(u"{{SWAGGER_PATH}}", str(self.swagger_path)) return HttpResponse(self._ui_cache, headers={ 'Cont...
def get_static(self, _, file_name=None): """ Get static content for UI. """ content_type = { 'ss': 'text/css', 'js': 'application/javascript', }.get(file_name[-2:]) if not content_type: raise HttpError(HTTPStatus.NOT_FOUND, 42) return HttpResponse(self.load_static(file_name), headers={ 'Content-Type': content_type, 'Co...
def perturbed_trajectory(trajectory, sensitivity_trajectory, delta=1e-4): """ Slightly perturb trajectory wrt the parameter specified in sensitivity_trajectory. :param trajectory: the actual trajectory for an ODE term :type trajectory: :class:`Trajectory` :param sensitivity_trajectory: sensitivity trajectory (dy/dpi fo...
def to_csv(self, file): """ Write this trajectory to a csv file with the headers 'time' and 'value'. :param file: a file object to write to :type file: :class:`file` :return: """ file.write("time,value\n") for t,v in self: file.write("%f,%f\n"% (t, v))
def resample(self, new_timepoints, extrapolate=False): """ Use linear interpolation to resample trajectory values. The new values are interpolated for the provided time points. This is generally before comparing or averaging trajectories. :param new_timepoints: the new time points :param extrapolate: whether extrapolat...
self.description)