text
stringlengths
81
112k
Predicate for whether the open token is in an exception context :arg exceptions: list of strings or None :arg before_token: the text of the function up to the token delimiter :arg after_token: the text of the function after the token delimiter :arg token: the token (only if we're looking at a close del...
Collapses the text between two delimiters in a frame function value This collapses the text between two delimiters and either removes the text altogether or replaces it with a replacement string. There are certain contexts in which we might not want to collapse the text between two delimiters. These a...
Takes the function value from a frame and drops prefix and return type For example:: static void * Allocator<MozJemallocBase>::malloc(unsigned __int64) ^ ^^^^^^ return type prefix This gets changes to this:: Allocator<MozJemallocBase>::malloc(unsigned __int64) This ...
Wait for connections to be made and their handshakes to finish :param conns: a single or list of (host, port) tuples with the connections that must be finished before the method will return. defaults to all the peers the :class:`Hub` was instantiated with. :param tim...
Close all peer connections and stop listening for new ones def shutdown(self): 'Close all peer connections and stop listening for new ones' log.info("shutting down") for peer in self._dispatcher.peers.values(): peer.go_down(reconnect=False) if self._listener_coro: ...
Set a handler for incoming publish messages :param service: the incoming message must have this service :type service: anything hash-able :param mask: value to be bitwise-and'ed against the incoming id, the result of which must mask the 'value' param :type mask: ...
Remove a publish subscription :param service: the service of the subscription to remove :type service: anything hash-able :param mask: the mask of the subscription to remove :type mask: int :param value: the value in the subscription to remove :type value: int :...
Send a 1-way message :param service: the service name (the routing top level) :type service: anything hash-able :param int routing_id: the id used for routing within the registered handlers of the service :param string method: the method name to call :par...
Get the number of peers that would handle a particular publish :param service: the service name :type service: anything hash-able :param routing_id: the id used for limiting the service handlers :type routing_id: int def publish_receiver_count(self, service, routing_id): '''Get...
Set a handler for incoming RPCs :param service: the incoming RPC must have this service :type service: anything hash-able :param mask: value to be bitwise-and'ed against the incoming id, the result of which must mask the 'value' param :type mask: int :par...
Remove a rpc subscription :param service: the service of the subscription to remove :type service: anything hash-able :param mask: the mask of the subscription to remove :type mask: int :param value: the value in the subscription to remove :type value: int :param...
Send out an RPC request :param service: the service name (the routing top level) :type service: anything hash-able :param routing_id: The id used for routing within the registered handlers of the service. :type routing_id: int :param method: the method na...
Send an RPC request and return the corresponding response This will block waiting until the response has been received. :param service: the service name (the routing top level) :type service: anything hash-able :param routing_id: The id used for routing within the registere...
Get the number of peers that would handle a particular RPC :param service: the service name :type service: anything hash-able :param routing_id: the id used for narrowing within the service handlers :type routing_id: int :returns: the integer number of p...
Start up the hub's server, and have it start initiating connections def start(self): "Start up the hub's server, and have it start initiating connections" log.info("starting") self._listener_coro = backend.greenlet(self._listener) self._udp_listener_coro = backend.greenlet(self._udp_li...
Build a connection to the Hub at a given ``(host, port)`` address def add_peer(self, peer_addr): "Build a connection to the Hub at a given ``(host, port)`` address" peer = connection.Peer( self._ident, self._dispatcher, peer_addr, backend.Socket()) peer.start() self._sta...
list of the (host, port) pairs of all connected peer Hubs def peers(self): "list of the (host, port) pairs of all connected peer Hubs" return [addr for (addr, peer) in self._dispatcher.peers.items() if peer.up]
Takes crash data via args and generates a Socorro signature def main(argv=None): """Takes crash data via args and generates a Socorro signature """ parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG) parser.add_argument( '-v', '--verbose', help='increase output verbosity',...
Send result to the Skinken WS def send_result(self, return_code, output, service_description='', time_stamp=0, specific_servers=None): ''' Send result to the Skinken WS ''' if time_stamp == 0: time_stamp = int(time.time()) if specific_servers == None: sp...
Close cache of WS Shinken def close_cache(self): ''' Close cache of WS Shinken ''' # Close all WS_Shinken cache files for server in self.servers: if self.servers[server]['cache'] == True: self.servers[server]['file'].close()
Create apidoc dir, delete contents if delete is True. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param directory: the apidoc directory. you can use relative paths here :type directory: str :param delete: if True, deletes the contents of apidoc. This acts like an overr...
Join package and module with a dot. Package or Module can be empty. :param package: the package name :type package: :class:`str` :param module: the module name :type module: :class:`str` :returns: the joined name :rtype: :class:`str` :raises: :class:`AssertionError`, if both package an...
Write the output file for module/package <name>. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param name: the file name without file extension :type name: :class:`str` :param text: the content of the file :type text: :class:`str` :param dest: the output director...
Import the given name and return name, obj, parent, mod_name :param name: name to import :type name: str :returns: the imported object or None :rtype: object | None :raises: None def import_name(app, name): """Import the given name and return name, obj, parent, mod_name :param name: name ...
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'``, ``'data'``, ``'members'`` :type typ: str :param inclu...
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 package :rtype: list :raises: TypeEr...
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 packages :rtype: list :raises: Type...
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 :raises: TypeError def get_subpackages(app, m...
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 classes in module * :allclasses: public and private clas...
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` :param package: the package name :type package: :class:`str` :param module: the ...
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` :param root_package: the parent package :type root_package: :class:`str` :param ...
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` def shall_skip(app, module, private): """Check...
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 env: :class:`jinja2.Environment` :param src: the path to the python source files :type src: :cl...
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. Note: by having trailing slashes, we avoid common prefix issues, like e.g. an exlude "foo" also accidentally excluding "foobar". def is_excluded(root, excludes): """Check if the directory is in the exclude list. Note: by having trailing slashes, we...
Generage the rst files Raises an :class:`OSError` if the source path is not a directory. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param src: path to python source files :type src: :class:`str` :param dest: output directory :type dest: :class:`str` :para...
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 def main(app): """Parse the config of the app and initiate the generation process :param app: the sphinx app ...
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. Both Python standard data types and Numpy data types are supported. :param obj: Object :type obj: any :rtype: boolean def _isreal(obj): """ Determine if an object is a real number. Both Python standard data types and Numpy data types are support...
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) def _no_exp(number): r""" Convert a number to a string without using scientific no...
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 (*string*) and the second ...
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.html>`_. When possible it i...
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 value will be in the ran...
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 computed. If any of the numbers in...
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 >>> str(pmisc.pgcd(0.05, ...
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.channe...
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: {e...
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.subscr...
Run command `cmd`. It's like that, and that's the way it is. 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, ...
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: i...
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_...
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, ...
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__.g...
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[b...
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...
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( ...
Wraps text like HelpFormatter, but doesn't squash lines This makes it easier to do lists and paragraphs. 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.spl...
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") ...
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...
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: ...
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 configurati...
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()[...
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() ]...
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_serv...
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 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 ...
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. @return: remote driver def gen_remote_driver(execut...
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 def gen_local_driver(browser, capabilities): ''' Generate ...
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 v...
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. ''' n...
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_...
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. d...
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 the resource. @return: A L{StaticProducer}. Calling C{.star...
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. ...
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 ...
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(driv...
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(d...
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')) def DyStrData(cls, name, regx, index = 0): ''' set dynamic value from the string data of response @pa...
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={"a":1, "b":[1,2,3,4], ...
获取当前页面的url def VerifyURL(cls, url): """ 获取当前页面的url """ if Web.driver.current_url == url: return True else: print("VerifyURL: %s" % Web.driver.current_url) return False
通过索引,选择下拉框选项, @param index: 下拉框 索引 def SelectByIndex(cls, index): ''' 通过索引,选择下拉框选项, @param index: 下拉框 索引 ''' try: Select(cls._element()).select_by_index(int(index)) except: return False
通过索引,取消选择下拉框选项, @param index: 下拉框 索引 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....
右键点击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()
在指定输入框发送回回车键 @note: key event -> enter 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组合键事件 @note: key event -> control + key @param key: 如'X' def Ctrl(cls, key): """ 在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X' """ element = cls._element() element.send_keys(Keys.CONTROL, key)