code stringlengths 1 18.2k |
|---|
def split_expression_by_path( where, schema, output=None, var_to_columns=None, lang=Language ): """ :param where: EXPRESSION TO INSPECT :param schema: THE SCHEMA :param output: THE MAP FROM PATH TO EXPRESSION WE WANT UPDATED :param var_to_columns: MAP FROM EACH VARIABLE NAME TO THE DEPTH :return: output: A MAP FROM PAT... |
split_expression_by_path(w, schema, output, var_to_columns, lang=lang) else: Log.error("Can not handle complex where clause") return output |
def _get_accept_languages_in_order(self): """ Reads an Accept HTTP header and returns an array of Media Type string in descending weighted order :return: List of URIs of accept profiles in descending request order :rtype: list """ try: # split the header into individual URIs, with weights still attached profiles = self... |
def readCfgJson(cls, working_path): """Read cmWalk configuration data of a working directory from a json file. :param working_path: working path for reading the configuration data. :return: the configuration data represented in a json object, None if the configuration files does not exist. """ cfg_json_filename = os.pa... |
def genTopLevelDirCMakeListsFile(self, working_path, subdirs, files, cfg): """ Generate top level CMakeLists.txt. :param working_path: current working directory :param subdirs: a list of subdirectories of current working directory. :param files: a list of files in current working directory. :return: the full path name ... |
def genSubDirCMakeListsFile(self, working_path, addToCompilerIncludeDirectories, subdirs, files): """ Generate CMakeLists.txt in subdirectories. :param working_path: current working directory :param subdirs: a list of subdirectories of current working directory. :param files: a list of files in current working director... |
def get_object(self, queryset=None): """ Returns the object the view is displaying. Copied from SingleObjectMixin except that this allows us to lookup preview objects. """ schema = manager.get_schema() vid = None if self.request.GET.get('vid') and self.request.user.is_staff and \ self.request.user.is_active: try: schem... |
%s must be called with " u"either an object pk or a slug." % self.__class__.__name__) try: obj = queryset.get() except queryset.model.DoesNotExist: raise http.Http404( u"No %(verbose_name)s found matching the query" % {'verbose_name': queryset.model._meta.verbose_name}) return obj |
def handle_exception(exc_info=None, source_hint=None, tb_override=_NO): """Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template. """ global _make_traceback if exc_info is None: # pragma: no cover exc_info = sys.exc_info() # the debugging... |
def _maybe_purge_cache(self): """ If enough time since last check has elapsed, check if any of the cached templates has changed. If any of the template files were deleted, remove that file only. If any were changed, then purge the entire cache. """ if self._last_reload_check + MIN_CHECK_INTERVAL > time.time(): return f... |
def load(self, name): """ If not yet in the cache, load the named template and compiles it, placing it into the cache. If in cache, return the cached template. """ if self.reload: self._maybe_purge_cache() template = self.cache.get(name) if template: return template path = self.resolve(name) if not path: raise OSError(... |
def send_email(self, from_address=None, to_address=None, subject=None, text_data=None, html_data=None ): """Sends an email. from_addr is an email address; to_addrs is a list of email adresses. Addresses can be plain (e.g. "jsmith@example.com") or with real names (e.g. "John Smith <jsmith@example.com>"). text_data and h... |
MIMEText(text_data) elif not text_data: msg = MIMEText(html_data, 'html') else: msg = MIMEMultipart('alternative') msg.attach(MIMEText(text_data, 'plain')) msg.attach(MIMEText(html_data, 'html')) msg['Subject'] = coalesce(subject, settings.subject) msg['From'] = from_address msg['To'] = ', '.join(to_address) if self.se... |
def _esfilter2sqlwhere(db, esfilter): """ CONVERT ElassticSearch FILTER TO SQL FILTER db - REQUIRED TO PROPERLY QUOTE VALUES AND COLUMN NAMES """ esfilter = wrap(esfilter) if esfilter is True: return SQL_TRUE elif esfilter["and"]: return sql_iso(SQL_AND.join([esfilter2sqlwhere(db, a) for a in esfilter["and"]])) elif es... |
" + quote_list(int_list) else: return esfilter2sqlwhere(db, filter) else: if has_null: return esfilter2sqlwhere(db, {"missing": col}) else: return "false" except Exception as e: e = Except.wrap(e) pass return quote_column(col) + " in " + quote_list(v) elif esfilter.script: return sql_iso(esfilter.script) elif esfilter.... |
if isinstance(esfilter.missing, text_type): return sql_iso(quote_column(esfilter.missing) + SQL_IS_NULL) else: return sql_iso(quote_column(esfilter.missing.field) + SQL_IS_NULL) elif esfilter.exists: if isinstance(esfilter.exists, text_type): return sql_iso(quote_column(esfilter.exists) + SQL_IS_NOT_NULL) else: return ... |
def query(self, query, stacked=False): """ TRANSLATE JSON QUERY EXPRESSION ON SINGLE TABLE TO SQL QUERY """ from jx_base.query import QueryOp query = QueryOp.wrap(query) sql, post = self._subquery(query, isolate=False, stacked=stacked) query.data = post(sql) return query.data |
def _aggop(self, query): """ SINGLE ROW RETURNED WITH AGGREGATES """ if isinstance(query.select, list): # RETURN SINGLE OBJECT WITH AGGREGATES for s in query.select: if s.aggregate not in aggregates: Log.error("Expecting all columns to have an aggregate: {{select}}", select=s) selects = FlatList() for s in query.select... |
sql, post |
def _setop(self, query): """ NO AGGREGATION, SIMPLE LIST COMPREHENSION """ if isinstance(query.select, list): # RETURN BORING RESULT SET selects = FlatList() for s in listwrap(query.select): if isinstance(s.value, Mapping): for k, v in s.value.items: selects.append(sql_alias(v, quote_column(s.name + "." + k))) if isins... |
r[s.name] = tuple(r[s.name + "," + str(i)] for i, ss in enumerate(s.value)) for i, ss in enumerate(s.value): r[s.name + "," + str(i)] = None expand_json(result) return result return sql, post_process # RETURN BORING RESULT SET else: # RETURN LIST OF VALUES if query.select.value == ".": select = "*" else: name = query.s... |
def _sort2sql(self, sort): """ RETURN ORDER BY CLAUSE """ if not sort: return "" return SQL_ORDERBY + sql_list([quote_column(o.field) + (" DESC" if o.sort == -1 else "") for o in sort]) |
def get_renderers(self): """ Instantiates and returns the list of renderers that this view can use. """ try: source = self.get_object() except (ImproperlyConfigured, APIException): self.renderer_classes = [RENDERER_MAPPING[i] for i in self.__class__.renderers] return [RENDERER_MAPPING[i]() for i in self.__class__.rende... |
def get_renderer_context(self): """ Returns a dict that is passed through to Renderer.render(), as the `renderer_context` keyword argument. """ # Note: Additionally 'response' will also be added to the context, # by the Response object. return { 'view': self, 'args': getattr(self, 'args', ()), 'kwargs': getattr(self, '... |
def rebuild(self): """Rebuild RIFF tree and index from streams.""" movi = self.riff.find('LIST', 'movi') movi.chunks = self.combine_streams() self.rebuild_index() |
def acquire(self, **kwargs): """ Aquire the lock. Returns True if the lock was acquired; False otherwise. timeout (int): Timeout to wait for the lock to change if it is already acquired. Defaults to what was provided during initialization, which will block and retry until acquired. """ token = str(uuid.uuid4()) attempt... |
self.renewSecondsPrior is not None: timer_ttl = self.ttl - self.renewSecondsPrior if timer_ttl > 0: def renew(): if self.renew(): Timer(timer_ttl, renew).start() Timer(timer_ttl, renew).start() else: def cleanup(): if self.token is token: self.token = None Timer(self.ttl, cleanup).start() return True |
def renew(self): """ Renew the lock if acquired. """ if self.token is not None: try: self.client.test_and_set(self.key, self.token, self.token, ttl=self.ttl) return True except ValueError, e: self.token = None return False |
def release(self): """ Release the lock if acquired. """ # TODO: thread safety (currently the lock may be acquired for one more TTL length) if self.token is not None: try: self.client.test_and_set(self.key, 0, self.token) except (ValueError, etcd.EtcdKeyError, etcd.EtcdKeyNotFound) as e: pass # the key already expired ... |
def deconstruct(self): """ Denormalize is always false migrations """ name, path, args, kwargs = super(AssetsFileField, self).deconstruct() kwargs['denormalize'] = False return name, path, args, kwargs |
def get_context_data(self, **kwargs): """ Hook for adding arguments to the context. """ context = {'obj': self.object } if 'queryset' in kwargs: context['conf_msg'] = self.get_confirmation_message(kwargs['queryset']) context.update(kwargs) return context |
def get_object(self): """ If a single object has been requested, will set `self.object` and return the object. """ queryset = None slug = self.kwargs.get(self.slug_url_kwarg, None) if slug is not None: queryset = self.get_queryset() slug_field = self.slug_field queryset = queryset.filter(**{slug_field: slug}) try: self... |
def get_done_url(self): """ Returns the url to redirect to after a successful update. The get_view_url will be called on the current bundle using `self.redirect_to_view` as the view name. """ data = dict(self.kwargs) data.pop(self.slug_url_kwarg, None) url = self.bundle.get_view_url(self.redirect_to_view, self.request.... |
def get_selected(self, request): """ Returns a queryset of the selected objects as specified by \ a GET or POST request. """ obj = self.get_object() queryset = None # if single-object URL not used, check for selected objects if not obj: if request.GET.get(CHECKBOX_NAME): selected = request.GET.get(CHECKBOX_NAME).split(... |
def get(self, request, *args, **kwargs): """ Method for handling GET requests. Calls the `render` method with the following items in context: * **queryset** - Objects to perform action on """ queryset = self.get_selected(request) return self.render(request, queryset = queryset) |
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Checks for a modify confirmation and performs the action by calling `process_action`. """ queryset = self.get_selected(request) if request.POST.get('modify'): response = self.process_action(request, queryset) if not response: url = self.ge... |
def process_action(self, request, queryset): """ Deletes the object(s). Successful deletes are logged. Returns a 'render redirect' to the result of the `get_done_url` method. If a ProtectedError is raised, the `render` method is called with message explaining the error added to the context as `protected`. """ count = 0... |
def get_object(self): """ Get the object for publishing Raises a http404 error if the object is not found. """ obj = super(PublishActionView, self).get_object() if obj: if not hasattr(obj, 'publish'): raise http.Http404 return obj |
def process_action(self, request, queryset): """ Publishes the selected objects by passing the value of \ 'when' to the object's publish method. The object's \ `purge_archives` method is also called to limit the number \ of old items that we keep around. The action is logged as \ either 'published' or 'scheduled' depen... |
message=message, collect_render_data=False) return self.render(request, queryset=queryset, publish_form=form, action='Publish') |
def process_action(self, request, queryset): """ Unpublishes the selected objects by calling the object's \ unpublish method. The action is logged and the user is \ notified with a message. Returns a 'render redirect' to the result of the \ `get_done_url` method. """ count = 0 for obj in queryset: count += 1 obj.unpubl... |
def get_object(self): """ Get the object for publishing Raises a http404 error if the object is not found. """ obj = super(PublishView, self).get_object() if not obj or not hasattr(obj, 'publish'): raise http.Http404 return obj |
def get_object_url(self): """ Returns the url to link to the object The get_view_url will be called on the current bundle using 'edit` as the view name. """ return self.bundle.get_view_url('edit', self.request.user, {}, self.kwargs) |
def get_done_url(self): """ Returns the url to redirect to after a successful update. The get_view_url will be called on the current bundle using `self.redirect_to_view` as the view name. """ url = self.bundle.get_view_url(self.redirect_to_view, self.request.user, {}, self.kwargs) return self.customized_return_url(url) |
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Publishes the object passing the value of 'when' to the object's publish method. The object's `purge_archives` method is also called to limit the number of old items that we keep around. The action is logged as either 'published' or 'sched... |
collect_render_data=False) return self.render(request, obj=self.object, form=form, done_url=url) |
def get(self, request, *args, **kwargs): """ Method for handling GET requests. Passes the following arguments to the context: * **obj** - The object to publish * **done_url** - The result of the `get_done_url` method """ self.object = self.get_object() return self.render(request, obj=self.object, done_url=self.get_done... |
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Unpublishes the the object by calling the object's unpublish method. The action is logged, the user is notified with a message. Returns a 'render redirect' to the result of the `get_done_url` method. """ self.object = self.get_object() url... |
def get_object(self): """ Get the object for previewing. Raises a http404 error if the object is not found. """ obj = super(DeleteView, self).get_object() if not obj: raise http.Http404 return obj |
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Deletes the object. Successful deletes are logged. Returns a 'render redirect' to the result of the `get_done_url` method. If a ProtectedError is raised, the `render` method is called with message explaining the error added to the context ... |
def expand(self, key_array): """ Expand the encryption key per AES key schedule specifications http://en.wikipedia.org/wiki/Rijndael_key_schedule# Key_schedule_description """ if len(key_array) != self._n: raise RuntimeError('expand(): key size ' + str(len(key_array)) + ' is invalid') # First n bytes are copied from ke... |
t = new_key[-4:] t = self._core(t, rcon_iteration) rcon_iteration += 1 t = self._xor_list(t, new_key[-self._n : -self._n + 4])# self._n_bytes_before(len_new_key, new_key)) new_key.extend(t) len_new_key += 4 # Run three passes of 4 byte expansion using copy of 4 byte tail of extended key # which is then xor'd with 4 byt... |
self._xor_list(t2, new_key[-self._n : -self._n + 4]) new_key.extend(t) len_new_key += 4 # If key length is 192 or 256 and key is not complete, run 2 or 3 passes respectively # of 4 byte tail of extended key xor with 4 bytes n bytes from end of extended key if self._key_length != 128 and len_new_key < self._b: if self._... |
def build_dot_value(key, value): """Build new dictionaries based off of the dot notation key. For example, if a key were 'x.y.z' and the value was 'foo', we would expect a return value of: ('x', {'y': {'z': 'foo'}}) Args: key (str): The key to build a dictionary off of. value: The value associated with the dot notation... |
value # otherwise, we will need to construct as many dictionaries # as there are dot components to hold the value. final_value = value reverse_split = key.split('.')[::-1] end = len(reverse_split) - 1 for idx, k in enumerate(reverse_split): if idx == end: return k, final_value final_value = {k: final_value} |
def _merge(d, u): """Merge two dictionaries (or DotDicts) together. Args: d: The dictionary/DotDict to merge into. u: The source of the data to merge. """ for k, v in u.items(): # if we have a mapping, recursively merge the values if isinstance(v, collections.Mapping): d[k] = _merge(d.get(k, {}), v) # if d (the dict to... |
the original value (`1`) overwritten # and would become: `{'foo': {'bar': 1}}` else: d = {k: v} return d |
def get(self, key, default=None): """Get a value from the `DotDict`. The `key` parameter can either be a regular string key, e.g. "foo", or it can be a string key with dot notation, e.g. "foo.bar.baz", to signify a nested lookup. The default value is returned if any level of the key's components are not found. Args: ke... |
corresponds to this # DotDict. the remainder components correspond to any nested # DotDicts. first, remainder = key.split('.', 1) if first in self: value = super(DotDict, self).get(first, default) # if the value for the key at this level is a dictionary, # then pass the remainder to that DotDict. if isinstance(value, (... |
def delete(self, key): """Remove a value from the `DotDict`. The `key` parameter can either be a regular string key, e.g. "foo", or it can be a string key with dot notation, e.g. "foo.bar.baz", to signify a nested element. If the key does not exist in the `DotDict`, it will continue silently. Args: key (str): The key t... |
from the default __getitem__ # implementation. else: dct = dct.__getitem__(k) if not isinstance(dct, (DotDict, dict)): raise KeyError( 'Subkey "{}" in "{}" invalid for deletion'.format(k, key) ) |
def make_extractor(non_default): """ Return us a function to extract options Anything not in non_default is wrapped in a "Default" object """ def extract_options(template, options): for option, val in normalise_options(template): name = option.replace('-', '_') value = getattr(options, name) if option not in non_defaul... |
def set_option(self, name, val, action=Empty, opts=Empty): """Determine which options were specified outside of the defaults""" if action is Empty and opts is Empty: self.specified.append(name) super(SpecRegister, self).set_option(name, val) else: super(SpecRegister, self).set_option(name, val, action, opts) |
def new_instance(type, frum, schema=None): """ Factory! """ if not type2container: _delayed_imports() if isinstance(frum, Container): return frum elif isinstance(frum, _Cube): return frum elif isinstance(frum, _Query): return _run(frum) elif is_many(frum): return _ListContainer(frum) elif is_text(frum): # USE DEFAULT S... |
def from_content(cls, content): """Parses a Tibia.com response into a House object. Parameters ---------- content: :class:`str` HTML content of the page. Returns ------- :class:`House` The house contained in the page, or None if the house doesn't exist. Raises ------ InvalidContent If the content is not the house secti... |
if beds_word == "no": house.beds = 0 else: house.beds = parse_number_words(beds_word) m = info_regex.search(info) if m: house.world = m.group("world") house.rent = int(m.group("rent")) house.size = int(m.group("size")) house._parse_status(state) return house |
def from_tibiadata(cls, content): """ Parses a TibiaData response into a House object. Parameters ---------- content: :class:`str` The JSON content of the TibiaData response. Returns ------- :class:`House` The house contained in the response, if found. Raises ------ InvalidContent If the content is not a house JSON res... |
def _parse_status(self, status): """Parses the house's state description and applies the corresponding values Parameters ---------- status: :class:`str` Plain text string containing the current renting state of the house. """ m = rented_regex.search(status) if m: self.status = HouseStatus.RENTED self.owner = m.group("o... |
def list_from_content(cls, content): """Parses the content of a house list from Tibia.com into a list of houses Parameters ---------- content: :class:`str` The raw HTML response from the house list. Returns ------- :class:`list` of :class:`ListedHouse` Raises ------ InvalidContent` Content is not the house list from Ti... |
= cols[2].text.replace('gold', '') house.rent = int(rent) status = cols[3].text.replace('\xa0', ' ') house._parse_status(status) id_input = cols[5].find("input", {'name': 'houseid'}) house.id = int(id_input["value"]) houses.append(house) return houses |
def list_from_tibiadata(cls, content): """Parses the content of a house list from TibiaData.com into a list of houses Parameters ---------- content: :class:`str` The raw JSON response from TibiaData Returns ------- :class:`list` of :class:`ListedHouse` Raises ------ InvalidContent` Content is not the house list from Ti... |
def get_list_url(cls, world, town, house_type: HouseType = HouseType.HOUSE): """ Gets the URL to the house list on Tibia.com with the specified parameters. Parameters ---------- world: :class:`str` The name of the world. town: :class:`str` The name of the town. house_type: :class:`HouseType` Whether to search for house... |
def get_list_url_tibiadata(cls, world, town, house_type: HouseType = HouseType.HOUSE): """ Gets the URL to the house list on Tibia.com with the specified parameters. Parameters ---------- world: :class:`str` The name of the world. town: :class:`str` The name of the town. house_type: :class:`HouseType` Whether to search... |
def _parse_status(self, status): """ Parses the status string found in the table and applies the corresponding values. Parameters ---------- status: :class:`str` The string containing the status. """ if "rented" in status: self.status = HouseStatus.RENTED else: m = list_auction_regex.search(status) if m: self.highest_b... |
def config(self): """Get the complete configuration where the default, config, environment, and override values are merged together. Returns: (DotDict): A dictionary of configuration values that allows lookups using dot notation. """ if self._full_config is None: self._full_config = DotDict() self._full_config.merge(se... |
def set(self, key, value): """Set a value in the `Bison` configuration. Args: key (str): The configuration key to set a new value for. value: The value to set. """ # the configuration changes, so we invalidate the cached config self._full_config = None self._override[key] = value |
def parse(self, requires_cfg=True): """Parse the configuration sources into `Bison`. Args: requires_cfg (bool): Specify whether or not parsing should fail if a config file is not found. (default: True) """ self._parse_default() self._parse_config(requires_cfg) self._parse_env() |
def _find_config(self): """Searches through the configured `config_paths` for the `config_name` file. If there are no `config_paths` defined, this will raise an error, so the caller should take care to check the value of `config_paths` first. Returns: str: The fully qualified path to the configuration that was found. R... |
def _parse_config(self, requires_cfg=True): """Parse the configuration file, if one is configured, and add it to the `Bison` state. Args: requires_cfg (bool): Specify whether or not parsing should fail if a config file is not found. (default: True) """ if len(self.config_paths) > 0: try: self._find_config() except Biso... |
def _parse_env(self): """Parse the environment variables for any configuration if an `env_prefix` is set. """ env_cfg = DotDict() # if the env prefix doesn't end with '_', we'll append it here if self.env_prefix and not self.env_prefix.endswith('_'): self.env_prefix = self.env_prefix + '_' # if there is no scheme, we w... |
def _parse_default(self): """Parse the `Schema` for the `Bison` instance to create the set of default values. If no defaults are specified in the `Schema`, the default dictionary will not contain anything. """ # the configuration changes, so we invalidate the cached config self._full_config = None if self.scheme: self.... |
def get_domain(self, value): """ RETURN domain FOR GIVEN CODOMAIN :param value: :return: """ return [k for k, v in self.all if v == value] |
def get_codomain(self, key): """ RETURN AN ARRAY OF OBJECTS THAT key MAPS TO """ return [v for k, v in self.all if k == key] |
def update(self, command): """ EXPECTING command == {"set":term, "clear":term, "where":where} THE set CLAUSE IS A DICT MAPPING NAMES TO VALUES THE where CLAUSE IS A JSON EXPRESSION FILTER """ command = wrap(command) command_clear = listwrap(command["clear"]) command_set = command.set.items() command_where = jx.get(comm... |
def get(self, select): """ :param select: the variable to extract from list :return: a simple list of the extraction """ if is_list(select): return [(d[s] for s in select) for d in self.data] else: return [d[select] for d in self.data] |
def timeout(self, value): """Sets a custom timeout value for this session""" if value == TIMEOUT_SESSION: self._config.timeout = None self._backend_client.expires = None else: self._config.timeout = value self._calculate_expires() |
def _calculate_expires(self): """Calculates the session expiry using the timeout""" self._backend_client.expires = None now = datetime.utcnow() self._backend_client.expires = now + timedelta(seconds=self._config.timeout) |
def _load_cookie(self): """Loads HTTP Cookie from environ""" cookie = SimpleCookie(self._environ.get('HTTP_COOKIE')) vishnu_keys = [key for key in cookie.keys() if key == self._config.cookie_name] # no session was started yet if not vishnu_keys: return morsel = cookie[vishnu_keys[0]] morsel_value = morsel.value if self... |
def header(self): """Generates HTTP header for this cookie.""" if self._send_cookie: morsel = Morsel() cookie_value = Session.encode_sid(self._config.secret, self._sid) if self._config.encrypt_key: cipher = AESCipher(self._config.encrypt_key) cookie_value = cipher.encrypt(cookie_value) if sys.version_info > (3, 0): coo... |
def encode_sid(cls, secret, sid): """Computes the HMAC for the given session id.""" secret_bytes = secret.encode("utf-8") sid_bytes = sid.encode("utf-8") sig = hmac.new(secret_bytes, sid_bytes, hashlib.sha512).hexdigest() return "%s%s" % (sig, sid) |
def is_signature_equal(cls, sig_a, sig_b): """Compares two signatures using a constant time algorithm to avoid timing attacks.""" if len(sig_a) != len(sig_b): return False invalid_chars = 0 for char_a, char_b in zip(sig_a, sig_b): if char_a != char_b: invalid_chars += 1 return invalid_chars == 0 |
def decode_sid(cls, secret, cookie_value): """Decodes a cookie value and returns the sid if value or None if invalid.""" if len(cookie_value) > SIG_LENGTH + SID_LENGTH: logging.warn("cookie value is incorrect length") return None cookie_sig = cookie_value[:SIG_LENGTH] cookie_sid = cookie_value[SIG_LENGTH:] secret_bytes... |
def terminate(self): """Terminates an active session""" self._backend_client.clear() self._needs_save = False self._started = False self._expire_cookie = True self._send_cookie = True |
def get(self, key): """Retrieve a value from the session dictionary""" self._started = self._backend_client.load() self._needs_save = True return self._backend_client.get(key) |
def cors_wrapper(func): """ Decorator for CORS :param func: Flask method that handles requests and returns a response :return: Same, but with permissive CORS headers set """ def _setdefault(obj, key, value): if value == None: return obj.setdefault(key, value) def output(*args, **kwargs): response = func(*args, **kwargs... |
def dockerflow(flask_app, backend_check): """ ADD ROUTING TO HANDLE DOCKERFLOW APP REQUIREMENTS (see https://github.com/mozilla-services/Dockerflow#containerized-app-requirements) :param flask_app: THE (Flask) APP :param backend_check: METHOD THAT WILL CHECK THE BACKEND IS WORKING AND RAISE AN EXCEPTION IF NOT :return:... |
def new_collection_percolator(target): """Create new percolator associated with the new collection. :param target: Collection where the percolator will be atached. """ query = IQ(target.dbquery) for name in current_search.mappings.keys(): if target.name and target.dbquery: current_search.client.index( index=name, doc_t... |
def delete_collection_percolator(target): """Delete percolator associated with the new collection. :param target: Collection where the percolator was attached. """ for name in current_search.mappings.keys(): if target.name and target.dbquery: current_search.client.delete( index=name, doc_type='.percolator', id='collect... |
def collection_updated_percolator(mapper, connection, target): """Create percolator when collection is created. :param mapper: Not used. It keeps the function signature. :param connection: Not used. It keeps the function signature. :param target: Collection where the percolator should be updated. """ delete_collection_... |
def _find_matching_collections_externally(collections, record): """Find matching collections with percolator engine. :param collections: set of collections where search :param record: record to match """ index, doc_type = RecordIndexer().record_to_index(record) body = {"doc": record.dumps()} results = current_search_cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.