code stringlengths 1 18.2k |
|---|
elif c == ord('f'): if self.current_pad == 'streams': self.filter_streams() elif c == ord('F'): if self.current_pad == 'streams': self.clear_filter() elif c == ord('g'): if self.got_g: self.move(0, absolute=True) self.got_g = False continue self.got_g = True elif c == ord('G'): self.move(len(self.filtered_streams)-1, a... |
ord('O'): self.check_online_streams() elif c == ord('h') or c == ord('?'): self.show_help() |
def set_screen_size(self): """ Setup screen size and padding We have need 2 free lines at the top and 2 free lines at the bottom """ height, width = self.getheightwidth() curses.resizeterm(height, width) self.pad_x = 0 self.max_y, self.max_x = (height-1, width-1) self.pad_h = height-3 self.pad_w = width-2*self.pad_x |
def set_title(self, msg): """ Set first header line text """ self.s.move(0, 0) self.overwrite_line(msg, curses.A_REVERSE) |
def set_header(self, msg): """ Set second head line text """ self.s.move(1, 0) self.overwrite_line(msg, attr=curses.A_NORMAL) |
def set_footer(self, msg, reverse=True): """ Set first footer line text """ self.s.move(self.max_y-1, 0) if reverse: self.overwrite_line(msg, attr=curses.A_REVERSE) else: self.overwrite_line(msg, attr=curses.A_NORMAL) |
def show_help(self): """ Redraw Help screen and wait for any input to leave """ self.s.move(1,0) self.s.clrtobot() self.set_header('Help'.center(self.pad_w)) self.set_footer(' ESC or \'q\' to return to main menu') self.s.refresh() self.current_pad = 'help' self.refresh_current_pad() |
def init_streams_pad(self, start_row=0): """ Create a curses pad and populate it with a line by stream """ y = 0 pad = curses.newpad(max(1,len(self.filtered_streams)), self.pad_w) pad.keypad(1) for s in self.filtered_streams: pad.addstr(y, 0, self.format_stream_line(s)) y+=1 self.offsets['streams'] = 0 pad.move(start_r... |
def move(self, direction, absolute=False, pad_name=None, refresh=True): """ Scroll the current pad direction : (int) move by one in the given direction -1 is up, 1 is down. If absolute is True, go to position direction. Behaviour is affected by cursor_line and scroll_only below absolute : (bool) """ # pad in this lists... |
offset if pad_name in scroll_only: if absolute: if direction > 0: new_offset = pad.getmaxyx()[0] - self.pad_h + 1 else: new_offset = 0 else: if direction > 0: new_offset = min(pad.getmaxyx()[0] - self.pad_h + 1, offset + self.pad_h) elif offset > 0: new_offset = max(0, offset - self.pad_h) else: if absolute and directi... |
pad.move(row, 0) pad.chgat(curses.A_NORMAL) self.offsets[pad_name] = new_offset pad.move(new_row, 0) if pad_name in cursor_line: pad.chgat(curses.A_REVERSE) if pad_name == 'streams': self.redraw_stream_footer() if refresh: self.refresh_current_pad() |
def redraw_current_line(self): """ Redraw the highlighted line """ if self.no_streams: return row = self.pads[self.current_pad].getyx()[0] s = self.filtered_streams[row] pad = self.pads['streams'] pad.move(row, 0) pad.clrtoeol() pad.addstr(row, 0, self.format_stream_line(s), curses.A_REVERSE) pad.chgat(curses.A_REVERSE... |
def stepThroughJsWaf_selenium_chromium(self, url, titleContains='', titleNotContains=''): ''' Use Selenium+SeleniumChromium to access a resource behind cloudflare protection. Params: ``url`` - The URL to access that is protected by cloudflare ``titleContains`` - A string that is in the title of the protected page, and ... |
(not titleNotContains): raise ValueError("You must pass either a string the title should contain, or a string the title shouldn't contain!") if titleContains and titleNotContains: raise ValueError("You can only pass a single conditional statement!") self.log.info("Attempting to access page through cloudflare browser ve... |
def scope(self, key, *tags, default=None): """Only apply tags and default for top-level key, effectively scoping the tags.""" scope = self._scopes[key] tags = self._ensure_exclamation(tags) default = default if not default or default.startswith("!") else "!" + default if scope: scope[0] = scope[0] + tags scope[1] = def... |
def load(self, content): """Parse yaml content.""" # Try parsing the YAML with global tags try: config = yaml.load(content, Loader=self._loader(self._global_tags)) except yaml.YAMLError: raise InvalidConfigError(_("Config is not valid yaml.")) # Try extracting just the tool portion try: config = config[self.tool] excep... |
else: config[key] = self._apply_default(config[key], self._global_default) self._validate(config) return config |
def _loader(self, tags): """Create a yaml Loader.""" class ConfigLoader(SafeLoader): pass ConfigLoader.add_multi_constructor("", lambda loader, prefix, node: TaggedValue(node.value, node.tag, *tags)) return ConfigLoader |
def _validate(self, config): """Check whether every TaggedValue has a valid tag, otherwise raise InvalidConfigError""" if isinstance(config, dict): # Recursively validate each item in the config for val in config.values(): self._validate(val) elif isinstance(config, list): # Recursively validate each item in the config... |
def _apply_default(self, config, default): """ Apply default value to every str in config. Also ensure every TaggedValue has default in .tags """ # No default, nothing to be done here if not default: return config # If the entire config is just a string, return default TaggedValue if isinstance(config, str): return Tag... |
def _apply_scope(self, config, tags): """Add locally scoped tags to config""" if isinstance(config, dict): # Recursively _apply_scope for each item in the config for val in config.values(): self._apply_scope(val, tags) elif isinstance(config, list): # Recursively _apply_scope for each item in the config for item in con... |
def has_args(): ''' returns true if the decorator invocation had arguments passed to it before being sent a function to decorate ''' no_args_syntax = '@overload' args_syntax = no_args_syntax + '(' args, no_args = [(-1,-1)], [(-1,-1)] for i, line in enumerate(Overload.traceback_lines()): if args_syntax in line: args.app... |
def identify(fn): ''' returns a tuple that is used to match functions to their neighbors in their resident namespaces ''' return ( fn.__globals__['__name__'], # module namespace getattr(fn, '__qualname__', getattr(fn, '__name__', '')) # class and function namespace ) def __init__(self, fn): self.validate_function(fn) s... |
def overload(fn, function_to_overload=None): ''' This function decorator allows you to overload already defined functions. The execution of overloaded functions is done by trying the original version first and if it fails, the variables are handed off to the overloading function. While this does seem like a sloppy way ... |
every single usage of the function. This approach rewards functions that are designed with proper input validation, which you should be adding anyways. #------------------------------------------------------------------------------ # Example Usage Below #-----------------------------------------------------------------... |
7=14 | 8=16 | 9=18 ''' if function_to_overload is None: if Overload.has_args(): return Overload.configured_decorator(fn) else: return Overload.default_decorator(fn) else: return Overload.configured_decorator(function_to_overload)(fn) |
def get_all_attributes(klass_or_instance): """Get all attribute members (attribute, property style method). """ pairs = list() for attr, value in inspect.getmembers( klass_or_instance, lambda x: not inspect.isroutine(x)): if not (attr.startswith("__") or attr.endswith("__")): pairs.append((attr, value)) return pairs |
def getResults(self, parFound = None): ''' Function to obtain the Dictionarythat represents this object. :param parFound: values to return. :return: The output format will be like: [{"type" : "i3visio.email", "value": "foo@bar.com", "attributes": [] }, {"type" : "i3visio.email", "value": "bar@foo.com", "attributes": []... |
def get_requirement_from_url(url): """Get a requirement from the URL, if possible. This looks for #egg in the URL""" link = Link(url) egg_info = link.egg_fragment if not egg_info: egg_info = splitext(link.filename)[0] return package_to_requirement(egg_info) |
def package_to_requirement(package_name): """Translate a name like Foo-1.2 to Foo==1.3""" match = re.search(r'^(.*?)-(dev|\d.*)', package_name) if match: name = match.group(1) version = match.group(2) else: name = package_name version = '' if version: return '%s==%s' % (name, version) else: return name |
def get_mirrors(hostname=None): """Return the list of mirrors from the last record found on the DNS entry:: >>> from pip.index import get_mirrors >>> get_mirrors() ['a.pypi.python.org', 'b.pypi.python.org', 'c.pypi.python.org', 'd.pypi.python.org'] Originally written for the distutils2 project by Alexis Metaireau. """ ... |
def string_range(last): """Compute the range of string between "a" and last. This works for simple "a to z" lists, but also for "a to zz" lists. """ for k in range(len(last)): for x in product(string.ascii_lowercase, repeat=k+1): result = ''.join(x) yield result if result == last: return |
def _sort_locations(locations): """ Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls) """ files = [] urls = [] # puts the url for the given file path into the appropriate # list def sort_path(path): url = path_to_url2(path) if mimetypes.guess_type(url, strict=False)[0] == 'text/... |
def _get_pages(self, locations, req): """Yields (page, page_url) from the given locations, skipping locations that have errors, and adding download/homepage links""" pending_queue = Queue() for location in locations: pending_queue.put(location) done = [] seen = set() threads = [] for i in range(min(10, len(locations)))... |
def _link_package_versions(self, link, search_name): """ Return an iterable of triples (pkg_resources_version_key, link, python_version) that can be extracted from the given link. Meant to be overridden by subclasses, not called by clients. """ if link.egg_fragment: egg_info = link.egg_fragment else: egg_info, ext = li... |
match: version = version[:match.start()] py_version = match.group(1) if py_version != sys.version[:3]: logger.debug('Skipping %s because Python version is incorrect' % link) return [] logger.debug('Found link %s, version: %s' % (link, version)) return [(pkg_resources.parse_version(version), link, version)] |
def _get_mirror_urls(self, mirrors=None, main_mirror_url=None): """Retrieves a list of URLs from the main mirror DNS entry unless a list of mirror URLs are passed. """ if not mirrors: mirrors = get_mirrors(main_mirror_url) # Should this be made "less random"? E.g. netselect like? random.shuffle(mirrors) mirror_urls = s... |
def _get_content_type(url): """Get the Content-Type of the given url, using a HEAD request""" scheme, netloc, path, query, fragment = urlparse.urlsplit(url) if not scheme in ('http', 'https', 'ftp', 'ftps'): ## FIXME: some warning or something? ## assertion error? return '' req = Urllib2HeadRequest(url, headers={'Host'... |
def links(self): """Yields all links in the page""" for match in self._href_re.finditer(self.content): url = match.group(1) or match.group(2) or match.group(3) url = self.clean_link(urlparse.urljoin(self.base_url, url)) yield Link(url, self) |
def explicit_rel_links(self, rels=('homepage', 'download')): """Yields all links with the given relations""" for match in self._rel_re.finditer(self.content): found_rels = match.group(1).lower().split() for rel in rels: if rel in found_rels: break else: continue match = self._href_re.search(match.group(0)) if not match... |
def _metahash(self): """Checksum hash of all the inputs to this rule. Output is invalid until collect_srcs and collect_deps have been run. In theory, if this hash doesn't change, the outputs won't change either, which makes it useful for caching. """ # BE CAREFUL when overriding/extending this method. You want to copy ... |
you are extending this function in a subclass, # here is where you do: # BaseBuilder._metahash(self) log.debug('[%s]: Metahash input: %s', self.address, unicode(self.address)) mhash = util.hash_str(unicode(self.address)) log.debug('[%s]: Metahash input: %s', self.address, self.rule.params) mhash = util.hash_str(str(sel... |
def collect_outs(self): """Collect and store the outputs from this rule.""" # TODO: this should probably live in CacheManager. for outfile in self.rule.output_files or []: outfile_built = os.path.join(self.buildroot, outfile) if not os.path.exists(outfile_built): raise error.TargetBuildFailed( self.address, 'Output fil... |
def is_cached(self): """Returns true if this rule is already cached.""" # TODO: cache by target+hash, not per file. try: for item in self.rule.output_files: log.info(item) self.cachemgr.in_cache(item, self._metahash()) except cache.CacheMiss: log.info('[%s]: Not cached.', self.address) return False else: log.info('[%s]... |
def get_from_cache(self): """See if this rule has already been built and cached.""" for item in self.rule.output_files: dstpath = os.path.join(self.buildroot, item) self.linkorcopy( self.cachemgr.path_in_cache(item, self._metahash()), dstpath) |
def linkorcopy(self, src, dst): """hardlink src file to dst if possible, otherwise copy.""" if os.path.isdir(dst): log.warn('linkorcopy given a directory as destination. ' 'Use caution.') log.debug('src: %s dst: %s', src, dst) elif os.path.exists(dst): os.unlink(dst) elif not os.path.exists(os.path.dirname(dst)): os.ma... |
def rulefor(self, addr): """Return the rule object for an address from our deps graph.""" return self.rule.subgraph.node[self.rule.makeaddress(addr)][ 'target_obj'] |
def validate_args(self): """Input validation!""" def validate_name(): allowed_re = '^[a-z](([a-z0-9_-]+)?([a-z0-9])?)?' assert isinstance(self.params['name'], basestring), ( 'Name must be a string, not %s' % repr(self.params['name'])) assert re.match(allowed_re, self.params['name']), ( 'Invalid rule name: %s. Must matc... |
def composed_deps(self): """Dependencies of this build target.""" if 'deps' in self.params: param_deps = self.params['deps'] or [] deps = [self.makeaddress(dep) for dep in param_deps] return deps else: return None |
def source_files(self): """This rule's source files.""" if 'srcs' in self.params and self.params['srcs'] is not None: return util.flatten(self.params['srcs']) |
def makeaddress(self, label): """Turn a label into an Address with current context. Adds repo and path if given a label that only has a :target part. """ addr = address.new(label) if not addr.repo: addr.repo = self.address.repo if not addr.path: addr.path = self.address.path return addr |
def get_queryset(self): """Return the allowed queryset for this sign or the default one.""" if 'sign' in self.request.query_params: try: filter_and_actions = unsign_filters_and_actions( self.request.query_params['sign'], '{}.{}'.format( self.queryset.model._meta.app_label, self.queryset.model._meta.model_name, ) ) exce... |
def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. """ value if allow_unicode: value = unicodedata.normalize('NFKC', ... |
def split_date(value): """ This method splits a date in a tuple. value: valid iso date ex: 2016-01-31: ('2016','01','01') 2016-01: ('2016','01','') 2016: ('2016','','') """ if not is_valid_date(value): return ('', '', '') splited = value.split('-') try: year = splited[0] except IndexError: year = '' try: month = splite... |
def items(self): """Settings as key-value pair. """ return [(section, dict(self.conf.items(section, raw=True))) for \ section in [section for section in self.conf.sections()]] |
def jarsign(storepass, keypass, keystore, source, alias, path=None): """ Uses Jarsign to sign an apk target file using the provided keystore information. :param storepass(str) - keystore storepass :param keypass(str) - keystore keypass :param keystore(str) - keystore file path :param source(str) - apk path :param alias... |
def zipalign(source, dist, build_tool=None, version='4', path=None): """ Uses zipalign based on a provided build tool version (defaulit is 23.0.2). :param source(str) - source apk file to be zipaligned :param dist(str) - zipaligned apk file path to be created :param build_tool(str) - build tool version to be used by zi... |
def get_default_keystore(prefix='AG_'): """ Gets the default keystore information based on environment variables and a prefix. $PREFIX_KEYSTORE_PATH - keystore file path, default is opt/digger/debug.keystore $PREFIX_KEYSTORE_STOREPASS - keystore storepass, default is android $PREFIX_KEYSTORE_KEYPASS - keystore keypass,... |
def get_highest_build_tool(sdk_version=None): """ Gets the highest build tool version based on major version sdk version. :param sdk_version(int) - sdk version to be used as the marjor build tool version context. Returns: A string containg the build tool version (default is 23.0.2 if none is found) """ if sdk_version i... |
def rename_file(self, instance, field_name): """ Renames a file and updates the model field to point to the new file. Returns True if a change has been made; otherwise False """ file = getattr(instance, field_name) if file: new_name = get_hashed_filename(file.name, file) if new_name != file.name: print(' Renaming "%s" ... |
def addServerResource(self, pluginSubPath: bytes, resource: BasicResource) -> None: """ Add Server Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. :return: None """ pluginSubPath = plu... |
def main(http_port, peer_name, node_name, app_id): """ Runs the framework :param http_port: HTTP port to listen to :param peer_name: Name of the peer :param node_name: Name (also, UID) of the node hosting the peer :param app_id: Application ID """ # Create the framework framework = pelix.framework.create_framework( ('p... |
def write(self, data: bytes) -> None: """ Write the data. """ if self.finished(): if self._exc: raise self._exc raise WriteAfterFinishedError if not data: return try: self._delegate.write_data(data, finished=False) except BaseWriteException as e: self._finished.set() if self._exc is None: self._exc = e raise |
async def flush(self) -> None: """ Give the writer a chance to flush the pending data out of the internal buffer. """ async with self._flush_lock: if self.finished(): if self._exc: raise self._exc return try: await self._delegate.flush_buf() except asyncio.CancelledError: # pragma: no cover raise except BaseWriteExcept... |
def finish(self, data: bytes=b"") -> None: """ Finish the stream. """ if self.finished(): if self._exc: raise self._exc if data: raise WriteAfterFinishedError return try: self._delegate.write_data(data, finished=True) except BaseWriteException as e: if self._exc is None: self._exc = e raise finally: self._finished.set(... |
def register(**kwargs): """Registers a notification_cls. """ def _wrapper(notification_cls): if not issubclass(notification_cls, (Notification,)): raise RegisterNotificationError( f"Wrapped class must be a 'Notification' class. " f"Got '{notification_cls.__name__}'" ) site_notifications.register(notification_cls=notifi... |
def recvall(self, timeout=0.5): """ Receive the RCON command response :param timeout: The timeout between consequent data receive :return str: The RCON command response with header stripped out """ response = '' self.socket.setblocking(False) start = time.time() while True: if response and time.time() - start > timeout... |
def send(self, data): """ Send a RCON command over the socket :param data: The command to send :raise RconError: When it's not possible to evaluate the command :return str: The server response to the RCON command """ try: if not data: raise RconError('no command supplied') with self.lock: self.socket.send(self._rconsen... |
def klass_to_pypath(klass): """when a class is defined within the module that is being executed as main, the module name will be specified as '__main__' even though the module actually had its own real name. This ends up being very confusing to Configman as it tries to refer to a class by its proper module name. This f... |
time for configman use that information as value source.""" if klass.__module__ == '__main__': module_path = ( sys.modules['__main__'] .__file__[:-3] ) module_name = '' for a_python_path in sys.path: tentative_pathname = module_path.replace(a_python_path, '') if tentative_pathname != module_path: module_name = ( tentat... |
def __parse_target(targetstr, current_repo=None): """Parse a build target string. General form: //repo[gitref]/dir/path:target. These are all valid: //repo //repo[a038fi31d9e8bc11582ef1b1b1982d8fc] //repo[a039aa30853298]:foo //repo/dir //repo[a037928734]/dir //repo/dir/path //repo/dir/path:foo :foo dir/path dir/path:fo... |
def authenticated_session(username, password): """ Given username and password, return an authenticated Yahoo `requests` session that can be used for further scraping requests. Throw an AuthencationError if authentication fails. """ session = requests.Session() session.headers.update(headers()) response = session.get(u... |
def post_data(page, username, password): """ Given username and password, return the post data necessary for login """ soup = BeautifulSoup(page) try: inputs = soup.find(id='hiddens').findAll('input') post_data = {input['name']: input['value'] for input in inputs} post_data['username'] = username post_data['passwd'] = ... |
def from_signed_raw(cls: Type[CertificationType], signed_raw: str) -> CertificationType: """ Return Certification instance from signed raw document :param signed_raw: Signed raw document :return: """ n = 0 lines = signed_raw.splitlines(True) version = int(Identity.parse_field("Version", lines[n])) n += 1 Certification.... |
def from_inline(cls: Type[CertificationType], version: int, currency: str, blockhash: Optional[str], inline: str) -> CertificationType: """ Return Certification instance from inline document Only self.pubkey_to is populated. You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods :p... |
def raw(self) -> str: """ Return a raw document of the certification """ if not isinstance(self.identity, Identity): raise MalformedDocumentError("Can not return full certification document created from inline") return """Version: {version} Type: Certification Currency: {currency} Issuer: {issuer} IdtyIssuer: {certifie... |
def inline(self) -> str: """ Return inline document string :return: """ return "{0}:{1}:{2}:{3}".format(self.pubkey_from, self.pubkey_to, self.timestamp.number, self.signatures[0]) |
def command(execute=None): # noqa: E501 """Execute a Command Execute a command # noqa: E501 :param execute: The data needed to execute this command :type execute: dict | bytes :rtype: Response """ if connexion.request.is_json: execute = Execute.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!... |
def endpoint_catalog(catalog=None): # noqa: E501 """Retrieve the endpoint catalog Retrieve the endpoint catalog # noqa: E501 :param catalog: The data needed to get a catalog :type catalog: dict | bytes :rtype: Response """ if connexion.request.is_json: catalog = UserAuth.from_dict(connexion.request.get_json()) # noqa: ... |
def frog_tip(self): """\ Return a single FROG tip. """ cache = self._cache client = self._client if self.should_refresh: tips = client.croak() for number, tip in tips.items(): cache[str(number)] = tip choice = random.choice(list(cache.keys())) # We'll get a bytes() object here during real usage # but a text-like object... |
def queryset_iterator(queryset, chunksize=1000): ''''' Iterate over a Django Queryset ordered by the primary key This method loads a maximum of chunksize (default: 1000) rows in it's memory at the same time while django normally would load all rows in it's memory. Using the iterator() method only causes it to not prelo... |
def remove_dir(self, destination_path): """ Remove folder. Based on https://gist.github.com/artlogic/2632647. """ wd = self.conn.pwd() try: names = self.conn.nlst(destination_path) except ftplib.all_errors as e: # some FTP servers complain when you try and list non-existent paths logger.debug('FtpRmTree: Could not remo... |
def cli(dirty, stash): """ This is a tool that handles all the tasks to build a Python application This tool is installed as a setuptools entry point, which means it should be accessible from your terminal once this application is installed in develop mode. """ _setup_logging() LOGGER.info('EPAB %s', __version__) LOGGE... |
def _handle_response(response, command, id_xpath='./id', **kwargs): """ Initialize the corect Response object from the response string based on the API command type. """ _response_switch = { 'insert': ModifyResponse, 'replace': ModifyResponse, 'partial-replace': ModifyResponse, 'update': ModifyResponse, 'delete': Modif... |
def _parse_for_errors(self): """ Look for an error tag and raise APIError for fatal errors or APIWarning for nonfatal ones. """ error = self._response.find('{www.clusterpoint.com}error') if error is not None: if error.find('level').text.lower() in ('rejected', 'failed', 'error', 'fatal'): raise APIError(error) else: wa... |
def get_content_string(self): """ Ge thet Clusterpoint response's content as a string. """ return ''.join([ET.tostring(element, encoding="utf-8", method="xml") for element in list(self._content)]) |
def get_content_field(self, name): """ Get the contents of a specific subtag from Clusterpoint Storage's response's content tag. Args: name -- A name string of the content's subtag to be returned. Returns: A dict representing the contents of the specified field or a list of dicts if there are multiple fields with that ... |
def get_documents(self, doc_format='dict'): """ Get the documents returned from Storege in this response. Keyword args: doc_format -- Specifies the doc_format for the returned documents. Can be 'dict', 'etree' or 'string'. Default is 'dict'. Returns: A dict where keys are document ids and values depending of the requir... |
doc_format == 'list-string': return list([(ET.tostring(document)) for document in self._get_doc_list()]) elif doc_format in ('', None, 'string'): return dict([(get_doc_id(document, self._id_xpath), ET.tostring(document)) for document in self._get_doc_list()]) else: raise ParameterError("doc_format=" + doc_format) |
def get_aggregate(self): """ Get aggregate data. Returns: A dict in with queries as keys and results as values. """ return dict([(aggregate.find('query').text, [(ET.tostring(data).lstrip('<data xmlns:cps="www.clusterpoint.com" xmlns:cpse="www.clusterpoint.com">').strip().rstrip("</data>")) for data in aggregate.findall... |
def get_words(self): """ Get words matching the request search terms. Returns: A dict in form: {<search term>: {<matching word>: <number of times this word is found in the Storage> } // Repeated for every matching word. } // Repeated for every search term. """ return dict([(word_list.attrib['to'], dict([(word.text, wor... |
def get_alternatives(self): """ Get the spelling alternatives for search terms. Returns: A dict in form: {<search term>: {'count': <number of times the searh term occurs in the Storage>, 'words': {<an alternative>: {'count': <number of times the alternative occurs in the Storage>, 'cr': <cr value of the alternative>, '... |
def get_facets(self): """ Get facets from the response. Returns: A dict where requested facet paths are keys and a list of coresponding terms are values. """ return dict([(facet.attrib['path'], [term.text for term in facet.findall('term')]) for facet in self._content.findall('facet')]) |
def _process_response(self): """Return a JSON result after an HTTP Request. Process the response of an HTTP Request and make it a JSON error if it failed. Otherwise return the response's content. """ response = self.conn.getresponse() if response.status == 200 or response.status == 201: data = response.read() else: dat... |
def post(self, url, data): """Send a HTTP POST request to a URL and return the result. """ headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/json" } self.conn.request("POST", url, data, headers) return self._process_response() |
def put(self, url, data=None): """Send a HTTP PUT request to a URL and return the result. """ self.conn.request("PUT", url, data) return self._process_response() |
def number_of_issues_by_year(self, issn, collection, years=0, type=None): """ type: ['regular', 'supplement', 'pressrelease', 'ahead', 'special'] """ body = { "query": { "bool": { "must": [ { "match": { "issn": issn } }, { "match": { "collection": collection } } ] } }, "aggs": { "issue": { "cardinality": { "field": "is... |
def _must_not_custom_query(issn): """ Este metodo constroi a lista de filtros por título de periódico que será aplicada na pesquisa boleana como restrição "must_not". A lista de filtros é coletada do template de pesquisa customizada do periódico, quanto este template existir. """ custom_queries = set([utils.cleanup_str... |
def _fuzzy_custom_query(issn, titles): """ Este metodo constroi a lista de filtros por título de periódico que será aplicada na pesquisa boleana como match por similaridade "should". A lista de filtros é coletada do template de pesquisa customizada do periódico, quanto este template existir. """ custom_queries = journa... |
def nginx_web_ssl_config(self): """ Nginx web ssl config """ dt = [self.nginx_web_dir, self.nginx_ssl_dir] return nginx_conf_string.simple_ssl_web_conf.format(dt=dt) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.