INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return the members of mod of the given type
def get_members(app, mod, typ, include_public=None): """Return the members of mod of the given type :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param mod: the module with members :type mod: module :param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, `...
Get all submodules for the given module/ package
def _get_submodules(app, module): """Get all submodules for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of module names and boolean whether its a pac...
Get all submodules without packages for the given module/ package
def get_submodules(app, module): """Get all submodules without packages for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of module names excluding pac...
Get all subpackages for the given module/ package
def get_subpackages(app, module): """Get all subpackages for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of packages names :rtype: list :rais...
Return a dict for template rendering
def get_context(app, package, module, fullname): """Return a dict for template rendering Variables: * :package: The top package * :module: the module * :fullname: package.module * :subpkgs: packages beneath module * :submods: modules beneath module * :classes: public classe...
Build the text of the file and write the file.
def create_module_file(app, env, package, module, dest, suffix, dryrun, force): """Build the text of the file and write the file. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param env: the jinja environment for the templates :type env: :class:`jinja2.Environment` :...
Build the text of the file and write the file.
def create_package_file(app, env, root_package, sub_package, private, dest, suffix, dryrun, force): """Build the text of the file and write the file. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param env: the jinja environment for the templates ...
Check if we want to skip this module.
def shall_skip(app, module, private): """Check if we want to skip this module. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module name :type module: :class:`str` :param private: True, if privates are allowed :type private: :class:`bool` ""...
Look for every file in the directory tree and create the corresponding ReST files.
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix): """Look for every file in the directory tree and create the corresponding ReST files. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param env: the jinja environment :type en...
Normalize the excluded directory list.
def normalize_excludes(excludes): """Normalize the excluded directory list.""" return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
Check if the directory is in the exclude list.
def is_excluded(root, excludes): """Check if the directory is in the exclude list. Note: by having trailing slashes, we avoid common prefix issues, like e.g. an exlude "foo" also accidentally excluding "foobar". """ root = os.path.normpath(root) for exclude in excludes: if root ==...
Generage the rst files
def generate(app, src, dest, exclude=[], followlinks=False, force=False, dryrun=False, private=False, suffix='rst', template_dirs=None): """Generage the rst files Raises an :class:`OSError` if the source path is not a directory. :param app: the sphinx app :type app: :class:`s...
Parse the config of the app and initiate the generation process
def main(app): """Parse the config of the app and initiate the generation process :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :returns: None :rtype: None :raises: None """ c = app.config src = c.jinjaapi_srcdir if not src: return suffix...
Return floating point equality.
def _isclose(obja, objb, rtol=1e-05, atol=1e-08): """Return floating point equality.""" return abs(obja - objb) <= (atol + rtol * abs(objb))
Determine if an object is a real number.
def _isreal(obj): """ Determine if an object is a real number. Both Python standard data types and Numpy data types are supported. :param obj: Object :type obj: any :rtype: boolean """ # pylint: disable=W0702 if (obj is None) or isinstance(obj, bool): return False try...
r Convert a number to a string without using scientific notation.
def _no_exp(number): r""" Convert a number to a string without using scientific notation. :param number: Number to convert :type number: integer or float :rtype: string :raises: RuntimeError (Argument \`number\` is not valid) """ if isinstance(number, bool) or (not isinstance(number,...
r Return mantissa and exponent of a number expressed in scientific notation.
def _to_scientific_tuple(number): r""" Return mantissa and exponent of a number expressed in scientific notation. Full precision is maintained if the number is represented as a string. :param number: Number :type number: integer, float or string :rtype: Tuple whose first item is the mantissa...
Calculate the greatest common divisor ( GCD ) of a sequence of numbers.
def gcd(vector): """ Calculate the greatest common divisor (GCD) of a sequence of numbers. The sequence can be a list of numbers or a Numpy vector of numbers. The computations are carried out with a precision of 1E-12 if the objects are not `fractions <https://docs.python.org/3/library/fractions.ht...
r Scale a value to the range defined by a series.
def normalize(value, series, offset=0): r""" Scale a value to the range defined by a series. :param value: Value to normalize :type value: number :param series: List of numbers that defines the normalization range :type series: list :param offset: Normalization offset, i.e. the returned...
r Calculate percentage difference between numbers.
def per(arga, argb, prec=10): r""" Calculate percentage difference between numbers. If only two numbers are given, the percentage difference between them is computed. If two sequences of numbers are given (either two lists of numbers or Numpy vectors), the element-wise percentage difference is ...
Calculate the greatest common divisor ( GCD ) of two numbers.
def pgcd(numa, numb): """ Calculate the greatest common divisor (GCD) of two numbers. :param numa: First number :type numa: number :param numb: Second number :type numb: number :rtype: number For example: >>> import pmisc, fractions >>> pmisc.pgcd(10, 15) 5...
Connect to a websocket: channels: List of SockChannel instances
def connect_ws(self, post_connect_callback, channels, reconnect=False): """ Connect to a websocket :channels: List of SockChannel instances """ self.post_conn_cb = post_connect_callback self.channels = channels self.wsendpoint = self.context["conf"]["endpoints"]....
Submit a request on the websocket
def wscall(self, method, query=None, callback=None): """Submit a request on the websocket""" if callback is None: self.sock.emit(method, query) else: self.sock.emitack(method, query, callback)
Connect the provided channels
def connect_channels(self, channels): """Connect the provided channels""" self.log.info(f"Connecting to channels...") for chan in channels: chan.connect(self.sock) self.log.info(f"\t{chan.channel}")
Set Auth request received from websocket
def _on_set_auth(self, sock, token): """Set Auth request received from websocket""" self.log.info(f"Token received: {token}") sock.setAuthtoken(token)
Message received from websocket
def _on_auth(self, sock, authenticated): # pylint: disable=unused-argument """Message received from websocket""" def ack(eventname, error, data): # pylint: disable=unused-argument """Ack""" if error: self.log.error(f"""OnAuth: {error}""") else: ...
Error received from websocket
def _on_connect_error(self, sock, err): # pylint: disable=unused-argument """Error received from websocket""" if isinstance(err, SystemExit): self.log.error(f"Shutting down websocket connection") else: self.log.error(f"Websocket error: {err}")
Attach a given socket to a channel
def connect(self, sock): """Attach a given socket to a channel""" def cbwrap(*args, **kwargs): """Callback wrapper; passes in response_type""" self.callback(self.response_type, *args, **kwargs) self.sock = sock self.sock.subscribe(self.channel) self.sock....
Run command cmd.
def run_cmd(cmd, input=None, timeout=30, max_try=3, num_try=1): '''Run command `cmd`. It's like that, and that's the way it is. ''' if type(cmd) == str: cmd = cmd.split() process = subprocess.Popen(cmd, stdin=open('/dev/null', 'r'), ...
find first positional arg ( does not start with - ) take it out of array and return it separately returns ( arg array )
def pop_first_arg(argv): """ find first positional arg (does not start with -), take it out of array and return it separately returns (arg, array) """ for arg in argv: if not arg.startswith('-'): argv.remove(arg) return (arg, argv) return (None, argv)
check options requirements print and return exit value
def check_options(options, parser): """ check options requirements, print and return exit value """ if not options.get('release_environment', None): print("release environment is required") parser.print_help() return os.EX_USAGE return 0
write all needed state info to filesystem
def write(self): """ write all needed state info to filesystem """ dumped = self._fax.codec.dump(self.__state, open(self.state_file, 'w'))
configure the module at the given path with a config template and file. path = the filesystem path to the given module template = the config template filename within that path config_name = the config filename within that path params = a dict containing config params which are found in the template using % ( key ) s.
def package_config(path, template='__config__.ini.TEMPLATE', config_name='__config__.ini', **params): """configure the module at the given path with a config template and file. path = the filesystem path to the given module template = the config template filename within that path ...
write the contents of this config to fn or its __filename__.
def write(self, fn=None, sorted=False, wait=0): """write the contents of this config to fn or its __filename__. """ config = ConfigParser(interpolation=None) if sorted==True: keys.sort() for key in self.__dict__.get('ordered_keys') or self.keys(): config[key] = ...
returns a list of params that this ConfigTemplate expects to receive
def expected_param_keys(self): """returns a list of params that this ConfigTemplate expects to receive""" expected_keys = [] r = re.compile('%\(([^\)]+)\)s') for block in self.keys(): for key in self[block].keys(): s = self[block][key] i...
return a Config with the given params formatted via str. format ( ** params ). fn = None: If given will assign this filename to the rendered Config. prompt = False: If True will prompt for any param that is None.
def render(self, fn=None, prompt=False, **params): """return a Config with the given params formatted via ``str.format(**params)``. fn=None : If given, will assign this filename to the rendered Config. prompt=False : If True, will prompt for any param that is None. """ ...
Takes a crash id pulls down data from Socorro generates signature data
def main(): """Takes a crash id, pulls down data from Socorro, generates signature data""" parser = argparse.ArgumentParser( formatter_class=WrappedTextHelpFormatter, description=DESCRIPTION ) parser.add_argument( '-v', '--verbose', help='increase output verbosity', action='store...
Wraps text like HelpFormatter but doesn t squash lines
def _fill_text(self, text, width, indent): """Wraps text like HelpFormatter, but doesn't squash lines This makes it easier to do lists and paragraphs. """ parts = text.split('\n\n') for i, part in enumerate(parts): # Check to see if it's a bulleted list--if so, then...
Return a dict of services by name
def get_api_services_by_name(self): """Return a dict of services by name""" if not self.services_by_name: self.services_by_name = dict({s.get('name'): s for s in self.conf .get("api") .get("services")}) ...
Returns the API endpoints
def get_api_endpoints(self, apiname): """Returns the API endpoints""" try: return self.services_by_name\ .get(apiname)\ .get("endpoints")\ .copy() except AttributeError: raise Exception(f"Couldn't find the API en...
Returns the websocket subscriptions
def get_ws_subscriptions(self, apiname): """Returns the websocket subscriptions""" try: return self.services_by_name\ .get(apiname)\ .get("subscriptions")\ .copy() except AttributeError: raise Exception(f"Couldn'...
Returns the API configuration
def get_api(self, name=None): """Returns the API configuration""" if name is None: try: return self.conf.get("api").copy() except: # NOQA raise Exception(f"Couldn't find the API configuration")
Returns the specific service config definition
def get_api_service(self, name=None): """Returns the specific service config definition""" try: svc = self.services_by_name.get(name, None) if svc is None: raise ValueError(f"Couldn't find the API service configuration") return svc except: # N...
Return a string corresponding to the exception type.
def _ex_type_str(exobj): """Return a string corresponding to the exception type.""" regexp = re.compile(r"<(?:\bclass\b|\btype\b)\s+'?([\w|\.]+)'?>") exc_type = str(exobj) if regexp.match(exc_type): exc_type = regexp.match(exc_type).groups()[0] exc_type = exc_type[11:] if exc_type.starts...
Convert to ASCII.
def _unicode_to_ascii(obj): # pragma: no cover """Convert to ASCII.""" # pylint: disable=E0602,R1717 if isinstance(obj, dict): return dict( [ (_unicode_to_ascii(key), _unicode_to_ascii(value)) for key, value in obj.items() ] ) if i...
Send results
def send_result(self, return_code, output, service_description='', specific_servers=None): ''' Send results ''' if specific_servers == None: specific_servers = self.servers else: specific_servers = set(self.servers).intersection(specific_servers) ...
Get remote hosts from Selenium Grid Hub Console
def get_remote_executors(hub_ip, port = 4444): ''' Get remote hosts from Selenium Grid Hub Console @param hub_ip: hub ip of selenium grid hub @param port: hub port of selenium grid hub ''' resp = requests.get("http://%s:%s/grid/console" %(hub_ip, port)) re...
Generate remote drivers with desired capabilities ( self. __caps ) and command_executor
def gen_remote_driver(executor, capabilities): ''' Generate remote drivers with desired capabilities(self.__caps) and command_executor @param executor: command executor for selenium remote driver @param capabilities: A dictionary of capabilities to request when starting the browser session. ...
Generate localhost drivers with desired capabilities ( self. __caps )
def gen_local_driver(browser, capabilities): ''' Generate localhost drivers with desired capabilities(self.__caps) @param browser: firefox or chrome @param capabilities: A dictionary of capabilities to request when starting the browser session. @return: localhost driver '...
Calculate total energy production. Not rounded
def _production(self): """Calculate total energy production. Not rounded""" return self._nuclear + self._diesel + self._gas + self._wind + self._combined + self._vapor + self._solar + self._hydraulic + self._carbon + self._waste + self._other
Calculate total energy production. Not Rounded
def _links(self): """Calculate total energy production. Not Rounded""" total = 0.0 for value in self.link.values(): total += value return total
Ask a yes/ no question via raw_input () and return their answer. question is a string that is presented to the user. default is the presumed answer if the user just hits <Enter >. It must be yes ( the default ) no or None ( meaning an answer is required of the user ). The answer return value is True for yes or False fo...
def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer i...
Appends identifiers for the different databases ( such as Entrez id s ) and returns them. Uses the CrossRef class below.
def wall_of_name(self): ''' Appends identifiers for the different databases (such as Entrez id's) and returns them. Uses the CrossRef class below. ''' names = [] if self.standard_name: names.append(self.standard_name) if self.systematic_name: ...
Override save () method to make sure that standard_name and systematic_name won t be null or empty or consist of only space characters ( such as space tab new line etc ).
def save(self, *args, **kwargs): """ Override save() method to make sure that standard_name and systematic_name won't be null or empty, or consist of only space characters (such as space, tab, new line, etc). """ empty_std_name = False if not self.standard_name or...
Extends save () method of Django models to check that the database name is not left blank. Note: blank = False is only checked at a form - validation - stage. A test using Fixtureless that tries to randomly create a CrossRefDB with an empty string name would unintentionally break the test.
def save(self, *args, **kwargs): """ Extends save() method of Django models to check that the database name is not left blank. Note: 'blank=False' is only checked at a form-validation-stage. A test using Fixtureless that tries to randomly create a CrossRefDB with an empty...
Make a L { StaticProducer } that will produce the body of this response.
def makeProducer(self, request, fileForReading): """ Make a L{StaticProducer} that will produce the body of this response. This method will also set the response code and Content-* headers. @param request: The L{Request} object. @param fileForReading: The file object containing...
Begin sending the contents of this L { File } ( or a subset of the contents based on the range header ) to the given request.
def render_GET(self, request): """ Begin sending the contents of this L{File} (or a subset of the contents, based on the 'range' header) to the given request. """ request.setHeader(b'accept-ranges', b'bytes') producer = self.makeProducer(request, self.fileObject) ...
Implement the interface for the adapter object
def interface(self, context): """Implement the interface for the adapter object""" self.context = context self.callback = self.context.get("callback")
Executed on shutdown of application
def shutdown(self): """Executed on shutdown of application""" self.stopped.set() if hasattr(self.api, "shutdown"): self.api.shutdown() for thread in self.thread.values(): thread.join()
<input value = Test type = button onClick = alert ( OK ) >
def SwitchToAlert(): ''' <input value="Test" type="button" onClick="alert('OK')" > ''' try: alert = WebDriverWait(Web.driver, 10).until(lambda driver: driver.switch_to_alert()) return alert except: print("Waring: Time...
find the element with controls
def _element(cls): ''' find the element with controls ''' if not cls.__is_selector(): raise Exception("Invalid selector[%s]." %cls.__control["by"]) driver = Web.driver try: elements = WebDriverWait(driver, cls.__control["timeout"]).un...
find the elements with controls
def _elements(cls): ''' find the elements with controls ''' if not cls.__is_selector(): raise Exception("Invalid selector[%s]." %cls.__control["by"]) driver = Web.driver try: elements = WebDriverWait(driver, cls.__control["timeout"])....
set dynamic value from the string data of response
def DyStrData(cls, name, regx, index = 0): ''' set dynamic value from the string data of response @param name: glob parameter name @param regx: re._pattern_type e.g. DyStrData("a",re.compile('123')) ''' text = Web.PageSource() if not text...
set dynamic value from the json data of response
def DyJsonData(cls,name, sequence): ''' set dynamic value from the json data of response @note: 获取innerHTML json的数据 如, <html><body>{ "code": 1,"desc": "成功"}</body></html> @param name: glob parameter name @param sequence: sequence for the json e.g. result=...
获取当前页面的url
def VerifyURL(cls, url): """ 获取当前页面的url """ if Web.driver.current_url == url: return True else: print("VerifyURL: %s" % Web.driver.current_url) return False
通过索引,选择下拉框选项,
def SelectByIndex(cls, index): ''' 通过索引,选择下拉框选项, @param index: 下拉框 索引 ''' try: Select(cls._element()).select_by_index(int(index)) except: return False
通过索引,取消选择下拉框选项,
def DeSelectByIndex(cls, index): ''' 通过索引,取消选择下拉框选项, @param index: 下拉框 索引 ''' try: Select(cls._element()).deselect_by_index(int(index)) except: return False
鼠标悬浮
def MouseOver(cls): ''' 鼠标悬浮 ''' element = cls._element() action = ActionChains(Web.driver) action.move_to_element(element) action.perform() time.sleep(1)
左键 点击 1次
def Click(cls): ''' 左键 点击 1次 ''' element= cls._element() action = ActionChains(Web.driver) action.click(element) action.perform()
左键点击2次
def DoubleClick(cls): ''' 左键点击2次 ''' element = cls._element() action = ActionChains(Web.driver) action.double_click(element) action.perform()
Description: Sometimes one click on the element doesn t work. So wait more time then click again and again. Risk: It may operate more than one click operations.
def EnhancedClick(cls): ''' Description: Sometimes, one click on the element doesn't work. So wait more time, then click again and again. Risk: It may operate more than one click operations. ''' element = cls._element() for _ in r...
右键点击1次
def RightClick(cls): ''' 右键点击1次 ''' element = cls._element() action = ActionChains(Web.driver) action.context_click(element) action.perform()
相当于 按压,press
def ClickAndHold(cls): ''' 相当于 按压,press ''' element = cls._element() action = ActionChains(Web.driver) action.click_and_hold(element) action.perform()
释放按压操作
def ReleaseClick(cls): ''' 释放按压操作 ''' element = cls._element() action = ActionChains(Web.driver) action.release(element) action.perform()
在指定输入框发送回回车键
def Enter(cls): ''' 在指定输入框发送回回车键 @note: key event -> enter ''' element = cls._element() action = ActionChains(Web.driver) action.send_keys_to_element(element, Keys.ENTER) action.perform()
在指定元素上执行ctrl组合键事件
def Ctrl(cls, key): """ 在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X' """ element = cls._element() element.send_keys(Keys.CONTROL, key)
在指定元素上执行alt组合事件
def Alt(cls, key): """ 在指定元素上执行alt组合事件 @note: key event -> alt + key @param key: 如'X' """ element = cls._element() element.send_keys(Keys.ALT, key)
在指定输入框发送 Null, 用于设置焦点
def Focus(cls): """ 在指定输入框发送 Null, 用于设置焦点 @note: key event -> NULL """ element = cls._element() # element.send_keys(Keys.NULL) action = ActionChains(Web.driver) action.send_keys_to_element(element, Keys.NULL) actio...
文件上传, 非原生input
def Upload(cls, filename): """ 文件上传, 非原生input @todo: some upload.exe not prepared @param file: 文件名(文件必须存在在工程resource目录下), upload.exe工具放在工程tools目录下 """ raise Exception("to do") TOOLS_PATH = "" RESOURCE_PATH = "" tool_4path = os.path....
上传, 一般,上传页面如果是input 原生file文件框 如: <input type = file id = test - image - file name = test accept = image/ gif > ,像这样的,定位到该元素,然后使用 send_keys 上传的文件的绝对路径
def UploadType(cls, file_path): """ 上传, 一般,上传页面如果是input,原生file文件框, 如: <input type="file" id="test-image-file" name="test" accept="image/gif">,像这样的,定位到该元素,然后使用 send_keys 上传的文件的绝对路径 @param file_name: 文件名(文件必须存在在工程resource目录下) """ if not os.path.isabs(file_path): ...
Updates the Dict with the given values. Turns internal dicts into Dicts.
def update(xCqNck7t, **kwargs): """Updates the Dict with the given values. Turns internal dicts into Dicts.""" def dict_list_val(inlist): l = [] for i in inlist: if type(i)==dict: l.append(Dict(**i)) elif type(i)==list: ...
sort the keys before returning them
def keys(self, key=None, reverse=False): """sort the keys before returning them""" ks = sorted(list(dict.keys(self)), key=key, reverse=reverse) return ks
java - jar selenium - server. jar - role hub - port 4444
def hub(self, port): ''' java -jar selenium-server.jar -role hub -port 4444 @param port: listen port of selenium hub ''' self._ip = "localhost" self._port = port self.command = [self._conf["java_path"], "-jar", self._conf["jar_path"], "-port", str(port), "-role",...
java - jar selenium - server. jar - role node - port 5555 - hub http:// 127. 0. 0. 1: 4444/ grid/ register/
def node(self,port, hub_address=("localhost", 4444)): ''' java -jar selenium-server.jar -role node -port 5555 -hub http://127.0.0.1:4444/grid/register/ @param port: listen port of selenium node @param hub_address: hub address which node will connect to ''' self._ip, self._...
start the selenium Remote Server.
def start_server(self): """start the selenium Remote Server.""" self.__subp = subprocess.Popen(self.command) #print("\tselenium jar pid[%s] is running." %self.__subp.pid) time.sleep(2)
Determine whether hub server is running: return: True or False
def is_runnnig(self): """Determine whether hub server is running :return:True or False """ resp = None try: resp = requests.get("http://%s:%s" %(self._ip, self._port)) if resp.status_code == 200: return True else: ...
Implements two s complement negation.
def negate_gate(wordlen, input='x', output='~x'): """Implements two's complement negation.""" neg = bitwise_negate(wordlen, input, "tmp") inc = inc_gate(wordlen, "tmp", output) return neg >> inc
Return a circuit taking a wordlen bitvector where only k valuations return True. Uses encoding from [ 1 ].
def kmodels(wordlen: int, k: int, input=None, output=None): """Return a circuit taking a wordlen bitvector where only k valuations return True. Uses encoding from [1]. Note that this is equivalent to (~x < k). - TODO: Add automated simplification so that the circuits are equiv. [1]: Ch...
Recursively flattens a list.
def flatten_list(lobj): """ Recursively flattens a list. :param lobj: List to flatten :type lobj: list :rtype: list For example: >>> import pmisc >>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7]) [1, 2, 3, 4, 5, 6, 7] """ ret = [] for item in lobj: ...
tuple of ( username password ). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the configuration file.
def auth(self): """ tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the configuration file. """ username = self._settings["username"] if not username: raise ValueError("Use...
load a configuration file. loads default config if file is not found
def load(self, file=CONFIG_FILE): """ load a configuration file. loads default config if file is not found """ if not os.path.exists(file): print("Config file was not found under %s. Default file has been created" % CONFIG_FILE) self._settings = yaml.load(DEFAULT_...
Save configuration to provided path as a yaml file
def save(self, file=CONFIG_FILE): """ Save configuration to provided path as a yaml file """ os.makedirs(os.path.dirname(file), exist_ok=True) with open(file, "w") as f: yaml.dump(self._settings, f, Dumper=yaml.RoundTripDumper, width=float("inf"))
opens a curses/ picker based interface to select courses that should be downloaded.
def selection_dialog(self, courses): """ opens a curses/picker based interface to select courses that should be downloaded. """ selected = list(filter(lambda x: x.course.id in self._settings["selected_courses"], courses)) selection = Picker( title="Select courses to d...
Create the corresponding index. Will overwrite existing indexes of the same name.
def create(self): """Create the corresponding index. Will overwrite existing indexes of the same name.""" body = dict() if self.mapping is not None: body['mappings'] = self.mapping if self.settings is not None: body['settings'] = self.settings else: ...
Search the index with a query.
def search(self, query=None, size=100, unpack=True): """Search the index with a query. Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned. The default number of hits returned is 100. """ logging.in...
Scan the index with the query.
def scan_index(self, query: Union[Dict[str, str], None] = None) -> List[Dict[str, str]]: """Scan the index with the query. Will return any number of results above 10'000. Important to note is, that all the data is loaded into memory at once and returned. This works only with small data ...
Scroll an index with the specified search query.
def scroll(self, query=None, scroll='5m', size=100, unpack=True): """Scroll an index with the specified search query. Works as a generator. Will yield `size` results per iteration until all hits are returned. """ query = self.match_all if query is None else query response = self...
Fetch document by _id.
def get(self, identifier): """Fetch document by _id. Returns None if it is not found. (Will log a warning if not found as well. Should not be used to search an id.)""" logging.info('Download document with id ' + str(identifier) + '.') try: record = self.instance.get(...
Index a single document into the index.
def index_into(self, document, id) -> bool: """Index a single document into the index.""" try: self.instance.index(index=self.index, doc_type=self.doc_type, body=json.dumps(document, ensure_ascii=False), id=id) except RequestError as ex: logging.error(ex) retu...
Delete a document with id.
def delete(self, doc_id: str) -> bool: """Delete a document with id.""" try: self.instance.delete(self.index, self.doc_type, doc_id) except RequestError as ex: logging.error(ex) return False else: return True