code
stringlengths
1
18.2k
def register(self, slug, bundle, order=1, title=None): """ Registers the bundle for a certain slug. If a slug is already registered, this will raise AlreadyRegistered. :param slug: The slug to register. :param bundle: The bundle instance being registered. :param order: An integer that controls where this bundle's \ das...
def unregister(self, slug): """ Unregisters the given url. If a slug isn't already registered, this will raise NotRegistered. """ if slug not in self._registry: raise NotRegistered('The slug %s is not registered' % slug) bundle = self._registry[slug] if bundle._meta.model and bundle._meta.primary_model_bundle: self.unr...
def password_change(self, request): """ Handles the "change password" task -- both form display and validation. Uses the default auth views. """ from django.contrib.auth.views import password_change url = reverse('admin:cms_password_change_done') defaults = { 'post_change_redirect': url, 'template_name': 'cms/password_...
def password_change_done(self, request, extra_context=None): """ Displays the "success" page after a password change. """ from django.contrib.auth.views import password_change_done defaults = { 'extra_context': extra_context or {}, 'template_name': 'cms/password_change_done.html', } if self.password_change_done_templat...
def logout(self, request, extra_context=None): """ Logs out the user for the given HttpRequest. This should *not* assume the user is already logged in. """ from django.contrib.auth.views import logout defaults = { 'extra_context': extra_context or {}, 'template_name': 'cms/logged_out.html', } if self.logout_template is...
def login(self, request, extra_context=None): """ Displays the login form for the given HttpRequest. """ from django.contrib.auth.views import login context = { 'title': _('Log in'), 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: request.get_full_path(), } context.update(extra_context or {}) defaults = { 'ex...
def _get_allowed_sections(self, dashboard): """ Get the sections to display based on dashboard """ allowed_titles = [x[0] for x in dashboard] allowed_sections = [x[2] for x in dashboard] return tuple(allowed_sections), tuple(allowed_titles)
def index(self, request, extra_context=None): """ Displays the dashboard. Includes the main navigation that the user has permission for as well as the cms log for those sections. The log list can be filtered by those same sections and is paginated. """ dashboard = self.get_dashboard_urls(request) dash_blocks = self.get...
form},)
def register_models(self, *models, **kwargs): """ Register multiple models with the same arguments. Calls register for each argument passed along with all keyword arguments. """ for model in models: self.register(model, **kwargs)
def register(self, model, values=None, instance_values=None): """ Registers a model with this group. :param values: A list of values that should be incremented \ whenever invalidate_cache is called for a instance or class \ of this type. :param instance_values: A list of attribute names that will \ be looked up on the ...
def invalidate_cache(self, klass, instance=None, extra=None, force_all=False): """ Use this method to invalidate keys related to a particular model or instance. Invalidating a cache is really just incrementing the version for the right key(s). :param klass: The model class you are invalidating. If the given \ class was...
values == CacheConfig.ALL: self._increment_version() elif values: for value in values: self._increment_version(extra=value)
def get_version(self, extra=None): """ This will return a string that can be used as a prefix for django's cache key. Something like key.1 or key.1.2 If a version was not found '1' will be stored and returned as the number for that key. If extra is given a version will be returned for that value. Otherwise the major ve...
def add_routes(meteor_app, url_path=''): """ Adds search and retrieval routes to a :class:`meteorpi_server.MeteorServer` instance :param MeteorApp meteor_app: The :class:`meteorpi_server.MeteorApp` to which routes should be added :param string url_path: The base path used for the query routes, defaults to '' """ from m...
= 0 results = db.con.fetchall() if results: first_seen = results[0]['time'] db.con.execute("SELECT m.time FROM archive_metadata m " "INNER JOIN archive_observatories l ON m.observatory = l.uid " "AND l.publicId = %s AND m.time>0 " "ORDER BY m.time DESC LIMIT 1", (o,)) last_seen = 0 results = db.con.fetchall() if result...
a particular time @app.route('{0}/obstory/<obstory_id>/statusdict'.format(url_path), methods=['GET']) @app.route('{0}/obstory/<obstory_id>/statusdict/<unix_time>'.format(url_path), methods=['GET']) def get_obstory_status_by_time(obstory_id, unix_time=None): db = meteor_app.get_db() if unix_time is None: unix_time = tim...
Return a list of sky clarity measurements for a particular observatory (scale 0-100) @app.route('{0}/skyclarity/<obstory_id>/<utc_min>/<utc_max>/<period>'.format(url_path), methods=['GET']) def get_skyclarity(obstory_id, utc_min, utc_max, period): db = meteor_app.get_db() utc_min = float(utc_min) utc_max = float(utc_ma...
b)) results = db.con.fetchall() if len(results) > 0: output.append(sum([i['floatValue'] for i in results]) / len(results)) else: output.append(0) if b >= utc_max: break db.close_db() return jsonify(output) # Return a list of the number of observations of a particular type in a sequence # of time intervals between utc_m...
AND o.obsTime<%s LIMIT 1", (obstory_id, semantic_type, a, b)) output.append(db.con.fetchone()['COUNT(*)']) if b >= utc_max: break db.close_db() return jsonify({"activity": output}) # Return a thumbnail version of an image @app.route('{0}/thumbnail/<file_id>/<file_name>'.format(url_path), methods=['GET']) def get_thumbn...
g[1]: byte2 = int(g[1]) length = size - byte1 if byte2 is not None: length = byte2 - byte1 + 1 with open(filename_or_fp, 'rb') as f: f.seek(byte1) data = f.read(length) rv = Response(data, 206, mimetype=mimetype, direct_passthrough=True) rv.headers.add('Content-Range', 'bytes {0}-{1}/{2}'.format(byte1, byte1 + length -...
def es_query_template(path): """ RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE :param path: THE NESTED PATH (NOT INCLUDING TABLE NAME) :return: (es_query, es_filters) TUPLE """ if not is_text(path): Log.error("expecting path to be a string") if path != ".": f0 = {} f1 = {} output = wrap({ "query": es_and([ f0, {"nest...
def _ancestors(collection): """Get the ancestors of the collection.""" for index, c in enumerate(collection.path_to_root()): if index > 0 and c.dbquery is not None: raise StopIteration yield c.name raise StopIteration
def _build_cache(): """Preprocess collection queries.""" query = current_app.config['COLLECTIONS_DELETED_RECORDS'] for collection in Collection.query.filter( Collection.dbquery.isnot(None)).all(): yield collection.name, dict( query=query.format(dbquery=collection.dbquery), ancestors=set(_ancestors(collection)), ) raise...
def _find_matching_collections_internally(collections, record): """Find matching collections with internal engine. :param collections: set of collections where search :param record: record to match """ for name, data in iteritems(collections): if _build_query(data['query']).match(record): yield data['ancestors'] raise ...
def get_record_collections(record, matcher): """Return list of collections to which record belongs to. :param record: Record instance. :param matcher: Function used to check if a record belongs to a collection. :return: list of collection names. """ collections = current_collections.collections if collections is None: ...
def dfs(graph, func, head, reverse=None): """ DEPTH FIRST SEARCH IF func RETURNS FALSE, THEN PATH IS NO LONGER TAKEN IT'S EXPECTED func TAKES 3 ARGUMENTS node - THE CURRENT NODE IN THE path - PATH FROM head TO node graph - THE WHOLE GRAPH """ todo = deque() todo.append(head) path = deque() done = set() while todo: node...
def bfs(graph, func, head, reverse=None): """ BREADTH FIRST SEARCH IF func RETURNS FALSE, THEN NO MORE PATHS DOWN THE BRANCH ARE TAKEN IT'S EXPECTED func TAKES THESE ARGUMENTS: node - THE CURRENT NODE IN THE path - PATH FROM head TO node graph - THE WHOLE GRAPH todo - WHAT'S IN THE QUEUE TO BE DONE """ todo = deque() #...
def dominator_tree(graph): """ RETURN DOMINATOR FOREST THERE ARE TWO TREES, "ROOTS" and "LOOPS" ROOTS HAVE NO PARENTS LOOPS ARE NODES THAT ARE A MEMBER OF A CYCLE THAT HAS NO EXTRNAL PARENT roots = dominator_tree(graph).get_children(ROOTS) """ todo = Queue() done = set() dominator = Tree(None) nodes = list(graph.nodes)...
ALL PARENTS ARE PART OF A CYCLE, MAKE node A ROOT done.add(node) dominator.add_edge(Edge(LOOPS, node)) else: # DO THE PARENTS BEFORE node todo.push(node) for p in more_todo: todo.push(p) continue # WE CAN GET THE DOMINATORS FOR ALL parents if len(parents) == 1: # SHORTCUT dominator.add_edge(Edge(list(parents)[0], node)...
BE REACHED FROM MORE THAN ONE LOOP, PICK ONE TO BLAME dom = paths_from_roots[0][-1] break else: # ALL PATHS IDENTICAL dom = paths_from_roots[0][-1] dominator.add_edge(Edge(dom, node)) done.add(node) return dominator
def get_schema_from_list(table_name, frum): """ SCAN THE LIST FOR COLUMN TYPES """ columns = UniqueIndex(keys=("name",)) _get_schema_from_list(frum, ".", parent=".", nested_path=ROOT_PATH, columns=columns) return Schema(table_name=table_name, columns=list(columns))
def _get_schema_from_list(frum, table_name, parent, nested_path, columns): """ :param frum: The list :param table_name: Name of the table this list holds records for :param parent: parent path :param nested_path: each nested array, in reverse order :param columns: map from full name to column definition :return: """ fo...
if is_container(value): # GET TYPE OF MULTIVALUE v = list(value) if len(v) == 0: this_type = none_type.__name__ elif len(v) == 1: this_type = v[0].__class__.__name__ else: this_type = reduce( _merge_python_type, (vi.__class__.__name__ for vi in value) ) else: this_type = value.__class__.__name__ column.es_type = _merge...
def _add(self, column): """ :param column: ANY COLUMN OBJECT :return: None IF column IS canonical ALREADY (NET-ZERO EFFECT) """ columns_for_table = self.data.setdefault(column.es_index, {}) existing_columns = columns_for_table.setdefault(column.name, []) for canonical in existing_columns: if canonical is column: return...
def denormalized(self): """ THE INTERNAL STRUCTURE FOR THE COLUMN METADATA IS VERY DIFFERENT FROM THE DENORMALIZED PERSPECITVE. THIS PROVIDES THAT PERSPECTIVE FOR QUERIES """ with self.locker: self._update_meta() output = [ { "table": c.es_index, "name": untype_path(c.name), "cardinality": c.cardinality, "es_column": c...
def normalize_sort(sort=None): """ CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE """ if not sort: return Null output = FlatList() for s in listwrap(sort): if is_text(s) or mo_math.is_integer(s): output.append({"value": s, "sort": 1}) elif not s.field and not s.value and s.sort==None: #ASSUME {name: sort} FO...
def parse_tibia_datetime(datetime_str) -> Optional[datetime.datetime]: """Parses date and time from the format used in Tibia.com Accepted format: - ``MMM DD YYYY, HH:mm:ss ZZZ``, e.g. ``Dec 10 2018, 21:53:37 CET``. Parameters ------------- datetime_str: :class:`str` The date and time as represented in Tibia.com Returns...
def parse_tibia_date(date_str) -> Optional[datetime.date]: """Parses a date from the format used in Tibia.com Accepted format: - ``MMM DD YYYY``, e.g. ``Jul 23 2015`` Parameters ----------- date_str: :class:`str` The date as represented in Tibia.com Returns ----------- :class:`datetime.date`, optional The represented d...
def parse_tibiadata_datetime(date_dict) -> Optional[datetime.datetime]: """Parses time objects from the TibiaData API. Time objects are made of a dictionary with three keys: date: contains a string representation of the time timezone: a string representation of the timezone the date time is based on timezone_type: the ...
def try_datetime(obj) -> Optional[datetime.datetime]: """Attempts to convert an object into a datetime. If the date format is known, it's recommended to use the corresponding function This is meant to be used in constructors. Parameters ---------- obj: :class:`str`, :class:`dict`, :class:`datetime.datetime` The object ...
def try_date(obj) -> Optional[datetime.date]: """Attempts to convert an object into a date. If the date format is known, it's recommended to use the corresponding function This is meant to be used in constructors. Parameters ---------- obj: :class:`str`, :class:`datetime.datetime`, :class:`datetime.date` The object to ...
def parse_tibiacom_content(content, *, html_class="BoxContent", tag="div", builder="lxml"): """Parses HTML content from Tibia.com into a BeautifulSoup object. Parameters ---------- content: :class:`str` The raw HTML content from Tibia.com html_class: :class:`str` The HTML class of the parsed element. The default value ...
def try_enum(cls: Type[T], val, default: D = None) -> Union[T, D]: """Attempts to convert a value into their enum value Parameters ---------- cls: :class:`Enum` The enum to convert to. val: The value to try to convert to Enum default: optional The value to return if no enum value is found. Returns ------- obj: The enum...
def parse_json(content): """Tries to parse a string into a json object. This also performs a trim of all values, recursively removing leading and trailing whitespace. Parameters ---------- content: A JSON format string. Returns ------- obj: The object represented by the json string. Raises ------ InvalidContent If the ...
def get_social_share_link(context, share_link, object_url, object_title): """ Construct the social share link for the request object. """ request = context['request'] url = unicode(object_url) if 'http' not in object_url.lower(): full_path = ''.join(('http', ('', 's')[request.is_secure()], '://', request.META['HTTP_HOS...
def get_family(self, node): """ RETURN ALL ADJACENT NODES """ return set(p if c == node else c for p, c in self.get_edges(node))
def choices(self, cl): """ Take choices from field's 'choices' attribute for 'ChoicesField' and use 'flatchoices' as usual for other fields. """ #: Just tidy up standard implementation for the sake of DRY principle. def _choice_item(is_selected, query_string, title): return { 'selected': is_selected, 'query_string': qu...
def page_factory(request): """ Page factory. Config models example: .. code-block:: python models = { '': [WebPage, CatalogResource], 'catalogue': CatalogResource, 'news': NewsResource, } """ prefix = request.matchdict['prefix'] # /{prefix}/page1/page2/page3... settings = request.registry.settings dbsession = settings[...
resources in the tree for resource in resources: table = None if not hasattr(resource, '__table__')\ and hasattr(resource, 'model'): table = resource.model else: table = resource if not hasattr(table, 'slug'): continue nodes = dbsession.query(table) if hasattr(table, 'parent_id'): nodes = nodes.filter(or_( table.parent...
def register_views(*args): """ Registration view for each resource from config. """ config = args[0] settings = config.get_settings() pages_config = settings[CONFIG_MODELS] resources = resources_of_config(pages_config) for resource in resources: if hasattr(resource, '__table__')\ and not hasattr(resource, 'model'): con...
def accumulate_nested_doc(nested_path, expr=IDENTITY): """ :param nested_path: THE PATH USED TO EXTRACT THE NESTED RECORDS :param expr: FUNCTION USED ON THE NESTED OBJECT TO GET SPECIFIC VALUE :return: THE DE_TYPED NESTED OBJECT ARRAY """ name = literal_field(nested_path) def output(doc): acc = [] for h in doc.inner_hi...
def es_query_proto(path, selects, wheres, schema): """ RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE :param path: THE NESTED PATH (NOT INCLUDING TABLE NAME) :param wheres: MAP FROM path TO LIST OF WHERE CONDITIONS :return: (es_query, filters_map) TUPLE """ output = None last_where = MATCH_ALL for p in reversed(sorted...
output
def add_phase(self): """Context manager for when adding all the tokens""" # add stuff yield self # Make sure we output eveything self.finish_hanging() # Remove trailing indents and dedents while len(self.result) > 1 and self.result[-2][0] in (INDENT, ERRORTOKEN, NEWLINE): self.result.pop(-2)
def next_token(self, tokenum, value, scol): """Determine what to do with the next token""" # Make self.current reflect these values self.current.set(tokenum, value, scol) # Determine indent_type based on this token if self.current.tokenum == INDENT and self.current.value: self.indent_type = self.current.value[0] # Only...
self.result and not self.is_space and self.inserted_line: if self.current.tokenum != COMMENT: self.result.append((OP, ';')) self.inserted_line = False # Progress the tracker self.progress() # Add a newline if we just skipped a single if self.single and self.single.skipped: self.single.skipped = False self.result.append...
def progress(self): """ Deal with next token Used to create, fillout and end groups and singles As well as just append everything else """ tokenum, value, scol = self.current.values() # Default to not appending anything just_append = False # Prevent from group having automatic pass given to it # If it already has a pas...
# Modify super class for group self.groups.modify_kls(value) elif tokenum == NEWLINE: # Premature end of group self.add_tokens_for_group(with_pass=True) elif tokenum == OP and value == ":": # Proper end of group self.add_tokens_for_group() elif self.groups.starting_single: # Inside single signature, add to it if tokenu...
be able to interpret our special blocks with_async = self.after_an_async if not self.after_an_async and value == "async": self.after_an_async = True else: self.after_an_async = False if value in ('describe', 'context'): created_group = True # add pass to previous group if nothing added between then and now if self.grou...
Just append if token should be if just_append: self.result.append([tokenum, value])
def reset_indentation(self, amount): """Replace previous indentation with desired amount""" while self.result and self.result[-1][0] == INDENT: self.result.pop() self.result.append((INDENT, amount))
def ignore_token(self): """Determine if we should ignore current token""" def get_next_ignore(remove=False): """Get next ignore from ignore_next and remove from ignore_next""" next_ignore = self.ignore_next # Just want to return it, don't want to remove yet if not remove: if type(self.ignore_next) in (list, tuple): nex...
that the next ignorable token can be considered get_next_ignore(remove=True) return True else: # If not a wildcard, then return now if type(next_ignore) is not WildCard: return False # Go through tokens untill we find one that isn't a wildcard while type(next_ignore) == WildCard: next_ignore = get_next_ignore(remove=Tr...
def wrapped_setups(self): """Create tokens for Described.setup = noy_wrap_setup(Described, Described.setup) for setup/teardown""" lst = [] for group in self.all_groups: if not group.root: if group.has_after_each: lst.extend(self.tokens.wrap_after_each(group.kls_name, group.async_after_each)) if group.has_before_each: l...
def make_method_names(self): """Create tokens for setting __testname__ on functions""" lst = [] for group in self.all_groups: for single in group.singles: name, english = single.name, single.english if english[1:-1] != name.replace('_', ' '): lst.extend(self.tokens.make_name_modifier(not group.root, single.identifier, ...
def make_describe_attrs(self): """Create tokens for setting is_noy_spec on describes""" lst = [] if self.all_groups: lst.append((NEWLINE, '\n')) lst.append((INDENT, '')) for group in self.all_groups: if group.name: lst.extend(self.tokens.make_describe_attr(group.kls_name)) return lst
def forced_insert(self): """ Insert tokens if self.insert_till hasn't been reached yet Will respect self.inserted_line and make sure token is inserted before it Returns True if it appends anything or if it reached the insert_till token """ # If we have any tokens we are waiting for if self.insert_till: # Determine wher...
def add_tokens_for_pass(self): """Add tokens for a pass to result""" # Make sure pass not added to group again self.groups.empty = False # Remove existing newline/indentation while self.result[-1][0] in (INDENT, NEWLINE): self.result.pop() # Add pass and indentation self.add_tokens( [ (NAME, 'pass') , (NEWLINE, '\n') ,...
def add_tokens_for_group(self, with_pass=False): """Add the tokens for the group signature""" kls = self.groups.super_kls name = self.groups.kls_name # Reset indentation to beginning and add signature self.reset_indentation('') self.result.extend(self.tokens.make_describe(kls, name)) # Add pass if necessary if with_pas...
def add_tokens_for_single(self, ignore=False): """Add the tokens for the single signature""" args = self.single.args name = self.single.python_name # Reset indentation to proper amount and add signature self.reset_indentation(self.indent_type * self.single.indent) self.result.extend(self.tokens.make_single(name, args))...
def finish_hanging(self): """Add tokens for hanging singature if any""" if self.groups.starting_signature: if self.groups.starting_group: self.add_tokens_for_group(with_pass=True) elif self.groups.starting_single: self.add_tokens_for_single(ignore=True)
def determine_if_whitespace(self): """ Set is_space if current token is whitespace Is space if value is: * Newline * Empty String * Something that matches regexes['whitespace'] """ value = self.current.value if value == '\n': self.is_space = True else: self.is_space = False if (value == '' or regexes['whitespace'].matc...
def determine_inside_container(self): """ Set self.in_container if we're inside a container * Inside container * Current token starts a new container * Current token ends all containers """ tokenum, value = self.current.tokenum, self.current.value ending_container = False starting_container = False if tokenum == OP: # ...
def determine_indentation(self): """Reset indentation for current token and in self.result to be consistent and normalized""" # Ensuring NEWLINE tokens are actually specified as such if self.current.tokenum != NEWLINE and self.current.value == '\n': self.current.tokenum = NEWLINE # I want to change dedents into indents...
== INDENT and not self.groups.root: self.current.value = self.current.value[self.groups.level:]
def convert_dedent(self): """Convert a dedent into an indent""" # Dedent means go back to last indentation if self.indent_amounts: self.indent_amounts.pop() # Change the token tokenum = INDENT # Get last indent amount last_indent = 0 if self.indent_amounts: last_indent = self.indent_amounts[-1] # Make sure we don't hav...
def lookupAll(data, configFields, lookupType, db, histObj={}): """ Return a record after having cleaning rules of specified type applied to all fields in the config :param dict data: single record (dictionary) to which cleaning rules should be applied :param dict configFields: "fields" object from DWM config (see DataD...
elif lookupType=='normIncludes': fieldValNew, histObj, checkMatch = IncludesLookup(fieldVal=data[field], lookupType='normIncludes', db=db, fieldName=field, histObj=histObj) data[field] = fieldValNew return data, histObj
def DeriveDataLookupAll(data, configFields, db, histObj={}): """ Return a record after performing derive rules for all fields, based on config :param dict data: single record (dictionary) to which cleaning rules should be applied :param dict configFields: "fields" object from DWM config (see DataDictionary) :param Mong...
if set.issubset(set(deriveSetConfig['fieldSet']), data.keys()): deriveInput = {} # sorting here to ensure subdocument match from query for val in deriveSetConfig['fieldSet']: deriveInput[val] = data[val] if deriveSetConfig['type']=='deriveValue': fieldValNew, histObj, checkMatch = DeriveDataLookup(fieldName=field, db=d...
def _get_generators(self): """Get installed banana plugins. :return: dictionary of installed generators name: distribution """ # on using entrypoints: # http://stackoverflow.com/questions/774824/explain-python-entry-points # TODO: make sure we do not have conflicting generators installed! generators = [ep.name for ep i...
def _get_generator(self, name): """Load the generator plugin and execute its lifecycle. :param dist: distribution """ for ep in pkg_resources.iter_entry_points(self.group, name=None): if ep.name == name: generator = ep.load() return generator
def execute(self, name): """Orchestrate the work of the generator plugin. It is split into multiple phases: * initializing * prompting * configuring * writing :param gen: the generator you want to run :return: """ generator = self._get_generator(name) generator.initializing() answers = generator.prompting(create_store_...
def parse_args(self, doc, argv): """Parse ba arguments :param args: sys.argv[1:] :return: arguments """ # first a little sneak peak if we have a generator arguments = docopt(doc, argv=argv, help=False) if arguments.get('<generator>'): name = arguments['<generator>'] generator = self._get_generator(name) if hasattr(gene...
return arguments
def navigate(self, name, *args): """Navigate to a route * * @param {String} name Route name * @param {*} arg A single argument to pass to the route handler */ """ if name not in self.routes: raise Exception('invalid route name \'%s\'' % name) elif callable(self.routes[name]): return self.routes[name](self, *args) raise...
def register_route(self, name, route): """Register a route handler :param name: Name of the route :param route: Route handler """ try: self.routes[name] = route.handle except Exception as e: print('could not import handle, maybe something wrong ', 'with your code?') print(e)
def box(script): """ :param es_script: :return: TEXT EXPRESSION WITH NON OBJECTS BOXED """ if script.type is BOOLEAN: return "Boolean.valueOf(" + text_type(script.expr) + ")" elif script.type is INTEGER: return "Integer.valueOf(" + text_type(script.expr) + ")" elif script.type is NUMBER: return "Double.valueOf(" + text...
def add(self, full_name, repetition_type, type): """ :param full_name: dot delimited path to the property (use dot (".") for none) :param repetition_type: one of OPTIONAL or NESTED (REQUIRED is not possible) :param json_type: the json type to store :return: """ base_name = self.element.name simple_name = relative_field...
def get_parquet_metadata( self, path='.' ): """ OUTPUT PARQUET METADATA COLUMNS :param path: FOR INTERNAL USE :return: LIST OF SchemaElement """ children = [] for name, child_schema in sort_using_key(self.more.items(), lambda p: p[0]): children.extend(child_schema.get_parquet_metadata(concat_field(path, name))) if path...
def to_json(self, *, indent=None, sort_keys = False): """Gets the object's JSON representation. Parameters ---------- indent: :class:`int`, optional Number of spaces used as indentation, ``None`` will return the shortest possible string. sort_keys: :class:`bool`, optional Whether keys should be sorted alphabetically or...
def url(self): """:class:`str`: The URL to the Tibia.com page of the house.""" return self.get_url(self.id, self.world) if self.id and self.world else None
def url_tibiadata(self): """:class:`str`: The URL to the TibiaData.com page of the house.""" return self.get_url_tibiadata(self.id, self.world) if self.id and self.world else None
def get_tuid(self, branch, revision, file): """ :param branch: BRANCH TO FIND THE REVISION/FILE :param revision: THE REVISION NUNMBER :param file: THE FULL PATH TO A SINGLE FILE :return: A LIST OF TUIDS """ service_response = wrap(self.get_tuids(branch, revision, [file])) for f, t in service_response.items(): return t
def get_tuids(self, branch, revision, files): """ GET TUIDS FROM ENDPOINT, AND STORE IN DB :param branch: BRANCH TO FIND THE REVISION/FILE :param revision: THE REVISION NUNMBER :param files: THE FULL PATHS TO THE FILES :return: MAP FROM FILENAME TO TUID LIST """ # SCRUB INPUTS revision = revision[:12] files = [file.lst...
{"path": remaining}}, {"eq": {"branch": branch}} ]}, "branch": branch, "meta": { "format": "list", "request_time": Date.now() } }) if self.push_queue is not None: if DEBUG: Log.note("record tuid request to SQS: {{timestamp}}", timestamp=request.meta.request_time) self.push_queue.add(request) else: if DEBUG: Log.note("n...
"502 Bad Gateway" in e: self.enabled = False Log.error("TUID service has problems.", cause=e) elif self.num_bad_requests >= MAX_BAD_REQUESTS: self.enabled = False Log.error("TUID service has problems.", cause=e) else: Log.warning("TUID service has problems.", cause=e) Till(seconds=SLEEP_ON_ERROR).wait() return found
def add_routes(meteor_app, url_path='/importv2'): """ Add two routes to the specified instance of :class:`meteorpi_server.MeteorApp` to implement the import API and allow for replication of data to this server. :param meteorpi_server.MeteorApp meteor_app: The :class:`meteorpi_server.MeteorApp` to which import routes sh...
has the 'import' role. """ app = meteor_app.app @app.route(url_path, methods=['POST']) @meteor_app.requires_auth(roles=['import']) def import_entities(): """ Receive an entity import request, using :class:`meteorpi_server.import_api.ImportRequest` to parse it, then passing the parsed request on to an instance of :class...