INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Performs batch reply on target accounts. Looks up the recent messages of the target user applies the callback and replies with what the callback generates.
def perform_batch_reply( self, *, callback: Callable[..., str]=None, target_handles: Dict[str, str]=None, lookback_limit: int=20, per_service_lookback_limit: Dict[str, int]=None, ) -> IterationRecord: """ Performs batch reply on...
Go to sleep for the duration of self. delay.
def nap(self) -> None: """ Go to sleep for the duration of self.delay. :returns: None """ self.log.info(f"Sleeping for {self.delay} seconds.") for _ in progress.bar(range(self.delay)): time.sleep(1)
Store some extra value in the messaging storage.
def store_extra_info(self, key: str, value: Any) -> None: """ Store some extra value in the messaging storage. :param key: key of dictionary entry to add. :param value: value of dictionary entry to add. :returns: None """ self.extra_keys[key] = value
Store several extra values in the messaging storage.
def store_extra_keys(self, d: Dict[str, Any]) -> None: """ Store several extra values in the messaging storage. :param d: dictionary entry to merge with current self.extra_keys. :returns: None """ new_dict = dict(self.extra_keys, **d) self.extra_keys = new_dict.c...
Update messaging history on disk.
def update_history(self) -> None: """ Update messaging history on disk. :returns: None """ self.log.debug(f"Saving history. History is: \n{self.history}") jsons = [] for item in self.history: json_item = item.__dict__ # Convert sub-entri...
Load messaging history from disk to self.
def load_history(self) -> List["IterationRecord"]: """ Load messaging history from disk to self. :returns: List of iteration records comprising history. """ if path.isfile(self.history_filename): with open(self.history_filename, "r") as f: try: ...
Set up all output methods. Provide them credentials and anything else they need.
def _setup_all_outputs(self) -> None: """Set up all output methods. Provide them credentials and anything else they need.""" # The way this is gonna work is that we assume an output should be set up iff it has a # credentials_ directory under our secrets dir. for key in self.outputs.key...
Parse output records into dicts ready for JSON.
def _parse_output_records(self, item: IterationRecord) -> Dict[str, Any]: """Parse output records into dicts ready for JSON.""" output_records = {} for key, sub_item in item.output_records.items(): if isinstance(sub_item, dict) or isinstance(sub_item, list): output_re...
Create the directory of a fully qualified file name if it does not exist.
def make_dir(fname): """ Create the directory of a fully qualified file name if it does not exist. :param fname: File name :type fname: string Equivalent to these Bash shell commands: .. code-block:: bash $ fname="${HOME}/mydir/myfile.txt" $ dir=$(dirname "${fname}") ...
r Fix potential problems with a Microsoft Windows file name.
def normalize_windows_fname(fname, _force=False): r""" Fix potential problems with a Microsoft Windows file name. Superfluous backslashes are removed and unintended escape sequences are converted to their equivalent (presumably correct and intended) representation, for example :code:`r'\\\\x07pps'`...
Enforce line separators to be the right one depending on platform.
def _homogenize_linesep(line): """Enforce line separators to be the right one depending on platform.""" token = str(uuid.uuid4()) line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "") return line.replace(token, os.linesep)
Process line range tokens.
def _proc_token(spec, mlines): """Process line range tokens.""" spec = spec.strip().replace(" ", "") regexp = re.compile(r".*[^0123456789\-,]+.*") tokens = spec.split(",") cond = any([not item for item in tokens]) if ("--" in spec) or ("-," in spec) or (",-" in spec) or cond or regexp.match(spec...
r Return a Python source file formatted in reStructuredText.
def incfile(fname, fpointer, lrange=None, sdir=None): r""" Return a Python source file formatted in reStructuredText. .. role:: bash(code) :language: bash :param fname: File name, relative to environment variable :bash:`PKG_DOC_DIR` :type fname: string :param fpoint...
Print STDOUT of a shell command formatted in reStructuredText.
def ste(command, nindent, mdir, fpointer, env=None): """ Print STDOUT of a shell command formatted in reStructuredText. This is a simplified version of :py:func:`pmisc.term_echo`. :param command: Shell command (relative to **mdir** if **env** is not given) :type command: string :param ninden...
Print STDOUT of a shell command formatted in reStructuredText.
def term_echo(command, nindent=0, env=None, fpointer=None, cols=60): """ Print STDOUT of a shell command formatted in reStructuredText. .. role:: bash(code) :language: bash :param command: Shell command :type command: string :param nindent: Indentation level :type nindent: integ...
Return the string given by param formatted with the callers locals.
def flo(string): '''Return the string given by param formatted with the callers locals.''' callers_locals = {} frame = inspect.currentframe() try: outerframe = frame.f_back callers_locals = outerframe.f_locals finally: del frame return string.format(**callers_locals)
Color wrapper.
def _wrap_with(color_code): '''Color wrapper. Example: >>> blue = _wrap_with('34') >>> print(blue('text')) \033[34mtext\033[0m ''' def inner(text, bold=False): '''Inner color function.''' code = color_code if bold: code = flo("1;{code}") ...
Delete temporary files not under version control.
def clean(deltox=False): '''Delete temporary files not under version control. Args: deltox: If True, delete virtual environments used by tox ''' basedir = dirname(__file__) print(cyan('delete temp files and dirs for packaging')) local(flo( 'rm -rf ' '{basedir}/.eggs/ ...
Install latest pythons with pyenv.
def pythons(): '''Install latest pythons with pyenv. The python version will be activated in the projects base dir. Will skip already installed latest python versions. ''' if not _pyenv_exists(): print('\npyenv is not installed. You can install it with fabsetup ' '(https://gi...
Run tox.
def tox(args=''): '''Run tox. Build package and run unit tests against several pythons. Args: args: Optional arguments passed to tox. Example: fab tox:'-e py36 -r' ''' basedir = dirname(__file__) latest_pythons = _determine_latest_pythons() # e.g. highest_mino...
Build package and upload to pypi.
def pypi(): '''Build package and upload to pypi.''' if query_yes_no('version updated in setup.py?'): print(cyan('\n## clean-up\n')) execute(clean) basedir = dirname(__file__) latest_pythons = _determine_latest_pythons() # e.g. highest_minor: '3.6' highest_minor...
Check that none of the input column numbers is out of range. ( Instead of defining this function we could depend on Python s built - in IndexError exception for this issue but the IndexError exception wouldn t include line number information which is helpful for users to find exactly which line is the culprit. )
def chk_col_numbers(line_num, num_cols, tax_id_col, id_col, symbol_col): """ Check that none of the input column numbers is out of range. (Instead of defining this function, we could depend on Python's built-in IndexError exception for this issue, but the IndexError exception wouldn't include line n...
Read input gene history file into the database. Note that the arguments tax_id_col id_col and symbol_col have been converted into 0 - based column indexes.
def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col): """ Read input gene history file into the database. Note that the arguments tax_id_col, id_col and symbol_col have been converted into 0-based column indexes. """ # Make sure that tax_id is not "" or " " if not t...
Initialize what requires credentials/ secret files.
def cred_init( self, *, secrets_dir: str, log: Logger, bot_name: str="", ) -> None: """Initialize what requires credentials/secret files.""" super().__init__(secrets_dir=secrets_dir, log=log, bot_name=bot_name) self.ldebug("Retriev...
Send mastodon message.
def send( self, *, text: str, ) -> List[OutputRecord]: """ Send mastodon message. :param text: text to send in post. :returns: list of output records, each corresponding to either a single post, or an error. """ ...
Upload media to mastodon and send status and media and captions if present.
def send_with_media( self, *, text: str, files: List[str], captions: List[str]=[], ) -> List[OutputRecord]: """ Upload media to mastodon, and send status and media, and captions if present. :param text: post text. ...
Performs batch reply on target account. Looks up the recent messages of the target user applies the callback and replies with what the callback generates.
def perform_batch_reply( self, *, callback: Callable[..., str], lookback_limit: int, target_handle: str, ) -> List[OutputRecord]: """ Performs batch reply on target account. Looks up the recent messages of the target user, a...
Handle error while trying to do something.
def handle_error(self, message: str, e: mastodon.MastodonError) -> OutputRecord: """Handle error while trying to do something.""" self.lerror(f"Got an error! {e}") # Handle errors if we know how. try: code = e[0]["code"] if code in self.handled_errors: ...
Little - endian |... 4 bytes unsigned int... |... 4 bytes unsigned int... | | frames count | dimensions count |
def _read_header(self): ''' Little-endian |... 4 bytes unsigned int ...|... 4 bytes unsigned int ...| | frames count | dimensions count | ''' self._fh.seek(0) buf = self._fh.read(4*2) fc, dc = struct.unpack("<II", buf) retur...
Request a callback for value modification.
def listen(self, you): """ Request a callback for value modification. Parameters ---------- you : object An instance having ``__call__`` attribute. """ self._listeners.append(you) self.raw.talk_to(you)
Simple utility function to load a term.
def _get_term_by_id(self, id): '''Simple utility function to load a term. ''' url = (self.url + '/%s.json') % id r = self.session.get(url) return r.json()
Returns all concepts or collections that form the top - level of a display hierarchy.
def get_top_display(self, **kwargs): ''' Returns all concepts or collections that form the top-level of a display hierarchy. As opposed to the :meth:`get_top_concepts`, this method can possibly return both concepts and collections. :rtype: Returns a list of concepts and...
Return a list of concepts or collections that should be displayed under this concept or collection.
def get_children_display(self, id, **kwargs): ''' Return a list of concepts or collections that should be displayed under this concept or collection. :param id: A concept or collection id. :rtype: A list of concepts and collections. For each an id is present and a la...
Pass a list of identifiers ( id_list ) the name of the database ( Entrez Symbol Standard name Systematic name or a loaded crossreference database ) that you wish to translate from and the name of the database that you wish to translate to.
def translate_genes(id_list=None, from_id=None, to_id=None, organism=None): """ Pass a list of identifiers (id_list), the name of the database ('Entrez', 'Symbol', 'Standard name', 'Systematic name' or a loaded crossreference database) that you wish to translate from, and the name of the database th...
must be applied to all inner functions that return contexts. Wraps all instances of pygame. Surface in the input in Surface
def _inner_func_anot(func): """must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface""" @wraps(func) def new_func(*args): return func(*_lmap(_wrap_surface, args)) return new_func
Draws a cross centered in the target area
def Cross(width=3, color=0): """Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color """ return Overlay(Line("h", width, color), Line("v", width, color))
Top level function to create a surface.: param target: the pygame. Surface to blit on. Or a ( width height ) tuple in which case a new surface will be created
def compose(target, root=None): """Top level function to create a surface. :param target: the pygame.Surface to blit on. Or a (width, height) tuple in which case a new surface will be created :type target: - """ if type(root) == Surface: raise ValueError("A Surface may not be u...
Unifies loading of fonts.
def Font(name=None, source="sys", italic=False, bold=False, size=20): """Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: ...
Renders a text. Supports multiline text the background will be transparent.: param align: text - alignment must be center left or righ: type align: str: return: the input text: rtype: pygame. Surface
def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"): """Renders a text. Supports multiline text, the background will be transparent. :param align: text-alignment must be "center", "left", or "righ" :type align: str :return: the input text :rtype: pygame.Surface ...
Creates a padding by the remaining space after scaling the content.
def from_scale(scale_w, scale_h=None): """Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not b...
: param levels string: An optional argument of declaring a single or comma - delimited list of levels is available as seen in the example as 1. An example of a comma - delimited list of levels is 1 2 5 9.
def radicals(self, levels=None): """ :param levels string: An optional argument of declaring a single or comma-delimited list of levels is available, as seen in the example as 1. An example of a comma-delimited list of levels is 1,2,5,9. http://www.wanikani.com/api/v1.2#...
: param levels: An optional argument of declaring a single or comma - delimited list of levels is available as seen in the example as 1. An example of a comma - delimited list of levels is 1 2 5 9.: type levels: str or None
def kanji(self, levels=None): """ :param levels: An optional argument of declaring a single or comma-delimited list of levels is available, as seen in the example as 1. An example of a comma-delimited list of levels is 1,2,5,9. :type levels: str or None http://ww...
: param levels: An optional argument of declaring a single or comma - delimited list of levels is available as seen in the example as 1. An example of a comma - delimited list of levels is 1 2 5 9.: type levels: str or None
def vocabulary(self, levels=None): """ :param levels: An optional argument of declaring a single or comma-delimited list of levels is available, as seen in the example as 1. An example of a comma-delimited list of levels is 1,2,5,9. :type levels: str or None http...
Test if the argument is a string representing a valid hexadecimal digit.
def ishex(obj): """ Test if the argument is a string representing a valid hexadecimal digit. :param obj: Object :type obj: any :rtype: boolean """ return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits)
Test if the argument is a number ( complex float or integer ).
def isnumber(obj): """ Test if the argument is a number (complex, float or integer). :param obj: Object :type obj: any :rtype: boolean """ return ( (obj is not None) and (not isinstance(obj, bool)) and isinstance(obj, (int, float, complex)) )
Test if the argument is a real number ( float or integer ).
def isreal(obj): """ Test if the argument is a real number (float or integer). :param obj: Object :type obj: any :rtype: boolean """ return ( (obj is not None) and (not isinstance(obj, bool)) and isinstance(obj, (int, float)) )
Create and return an API context
def create_api_context(self, cls): """Create and return an API context""" return self.api_context_schema().load({ "name": cls.name, "cls": cls, "inst": [], "conf": self.conf.get_api_service(cls.name), "calls": self.conf.get_api_calls(), ...
Pass an API result down the pipeline
def receive(self, data, api_context): """Pass an API result down the pipeline""" self.log.debug(f"Putting data on the pipeline: {data}") result = { "api_contexts": self.api_contexts, "api_context": api_context, "strategy": dict(), # Shared strategy data ...
Shut it down
def shutdown(self, signum, frame): # pylint: disable=unused-argument """Shut it down""" if not self.exit: self.exit = True self.log.debug(f"SIGTRAP!{signum};{frame}") self.api.shutdown() self.strat.shutdown()
Course this node belongs to
def course(self): """ Course this node belongs to """ course = self.parent while course.parent: course = course.parent return course
Path of this node on Studip. Looks like Coures/ folder/ folder/ document. Respects the renaming policies defined in the namemap
def path(self): """ Path of this node on Studip. Looks like Coures/folder/folder/document. Respects the renaming policies defined in the namemap """ if self.parent is None: return self.title return join(self.parent.path, self.title)
get title of this node. If an entry for this course is found in the configuration namemap it is used otherwise the default value from stud. ip is used.
def title(self): """ get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default value from stud.ip is used. """ tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title retur...
list of all documents find in subtrees of this node
def deep_documents(self): """ list of all documents find in subtrees of this node """ tree = [] for entry in self.contents: if isinstance(entry, Document): tree.append(entry) else: tree += entry.deep_documents return...
The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name = $STUD. IP_NAME + $SEMESTER_NAME
def title(self): """ The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME """ name = c.namemap_lookup(self.id) if name is None: name = self._title + " " + client.get_semester_...
run a get request against an url. Returns the response which can optionally be streamed
def _get(self, route, stream=False): """ run a get request against an url. Returns the response which can optionally be streamed """ log.debug("Running GET request against %s" % route) return r.get(self._url(route), auth=c.auth, stream=stream)
List all contents of a folder. Returns a list of all Documents and Folders ( in this order ) in the folder.
def get_contents(self, folder: Folder): """ List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder. """ log.debug("Listing Contents of %s/%s" % (folder.course.id, folder.id)) if isinstance(folder, Course): response = j...
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud. ip path + filename. If overwrite is set the local version will be overwritten if the file was changed on studip since the last check
def download_document(self, document: Document, overwrite=True, path=None): """ Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename. If overwrite is set the local version will be overwritten if the file was changed on...
get the semester of a node
def get_semester_title(self, node: BaseNode): """ get the semester of a node """ log.debug("Getting Semester Title for %s" % node.course.id) return self._get_semester_from_id(node.course.semester)
use the base_url and auth data from the configuration to list all courses the user is subscribed to
def get_courses(self): """ use the base_url and auth data from the configuration to list all courses the user is subscribed to """ log.info("Listing Courses...") courses = json.loads(self._get('/api/courses').text)["courses"] courses = [Course.from_response(course) for co...
Minimize a scalar function using Brent s method.
def _minimize_scalar( self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True ): """ Minimize a scalar function using Brent's method. Parameters ---------- verbose : bool ``True`` for verbose output; ``False`` otherwise. """ ...
return a url - safe hash of the string optionally ( and by default ) base64 - encoded alg = sha256 = the hash algorithm must be in hashlib b64 = True = whether to base64 - encode the output strip = True = whether to strip trailing = from the base64 output Using the default arguments returns a url - safe base64 - encode...
def digest(self, alg='sha256', b64=True, strip=True): """return a url-safe hash of the string, optionally (and by default) base64-encoded alg='sha256' = the hash algorithm, must be in hashlib b64=True = whether to base64-encode the output strip=True = wheth...
turn a string to CamelCase omitting non - word characters
def camelify(self): """turn a string to CamelCase, omitting non-word characters""" outstring = self.titleify(allwords=True) outstring = re.sub(r"&[^;]+;", " ", outstring) outstring = re.sub(r"\W+", "", outstring) return String(outstring)
takes a string and makes a title from it
def titleify(self, lang='en', allwords=False, lastword=True): """takes a string and makes a title from it""" if lang in LOWERCASE_WORDS: lc_words = LOWERCASE_WORDS[lang] else: lc_words = [] s = str(self).strip() l = re.split(r"([_\W]+)", s) ...
return a python identifier from the string ( underscore separators )
def identifier(self, camelsplit=False, ascii=True): """return a python identifier from the string (underscore separators)""" return self.nameify(camelsplit=camelsplit, ascii=ascii, sep='_')
return an XML name ( hyphen - separated by default initial underscore if non - letter )
def nameify(self, camelsplit=False, ascii=True, sep='-'): """return an XML name (hyphen-separated by default, initial underscore if non-letter)""" s = String(str(self)) # immutable if camelsplit == True: s = s.camelsplit() s = s.hyphenify(ascii=ascii).replace('-', sep) ...
Turn non - word characters ( incl. underscore ) into single hyphens. If ascii = True return ASCII - only. If also lossless = True use the UTF - 8 codes for the non - ASCII characters.
def hyphenify(self, ascii=False): """Turn non-word characters (incl. underscore) into single hyphens. If ascii=True, return ASCII-only. If also lossless=True, use the UTF-8 codes for the non-ASCII characters. """ s = str(self) s = re.sub("""['"\u2018\u2019\u201c\u20...
Turn a CamelCase string into a string with spaces
def camelsplit(self): """Turn a CamelCase string into a string with spaces""" s = str(self) for i in range(len(s) - 1, -1, -1): if i != 0 and ( (s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper()) or (s[i].isnumeric() and s[i - 1].i...
Pyramid pluggable and discoverable function.
def includeme(config): """Pyramid pluggable and discoverable function.""" global_settings = config.registry.settings settings = local_settings(global_settings, PREFIX) try: file = settings['file'] except KeyError: raise KeyError("Must supply '{}.file' configuration value " ...
Executed on startup of application
def run(self): """Executed on startup of application""" self.api = self.context.get("cls")(self.context) self.context["inst"].append(self) # Adapters used by strategies for call, calldata in self.context.get("calls", {}).items(): def loop(): """Loop on event...
Executed on each scheduled iteration
def call(self, callname, arguments=None): """Executed on each scheduled iteration""" # See if a method override exists action = getattr(self.api, callname, None) if action is None: try: action = self.api.ENDPOINT_OVERRIDES.get(callname, None) excep...
Generate a request object for delivery to the API
def _generate_request(self, callname, request): """Generate a request object for delivery to the API""" # Retrieve path from API class schema = self.api.request_schema() schema.context['callname'] = callname return schema.dump(request).data.get("payload")
Generate a results object for delivery to the context object
def _generate_result(self, callname, result): """Generate a results object for delivery to the context object""" # Retrieve path from API class schema = self.api.result_schema() schema.context['callname'] = callname self.callback(schema.load(result), self.context)
create a key for index by converting index into a base - 26 number using A - Z as the characters.
def excel_key(index): """create a key for index by converting index into a base-26 number, using A-Z as the characters.""" X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or '' return X(int(index))
Takes a raw crash and a processed crash ( these are Socorro - centric data structures ) and converts them to a crash data structure used by signature generation.
def convert_to_crash_data(raw_crash, processed_crash): """ Takes a raw crash and a processed crash (these are Socorro-centric data structures) and converts them to a crash data structure used by signature generation. :arg raw_crash: raw crash data from Socorro :arg processed_crash: processed cr...
Takes a text and drops all non - printable and non - ascii characters and also any whitespace characters that aren t space.
def drop_bad_characters(text): """Takes a text and drops all non-printable and non-ascii characters and also any whitespace characters that aren't space. :arg str text: the text to fix :returns: text with all bad characters dropped """ # Strip all non-ascii and non-printable characters te...
Parses a source file thing and returns the file name
def parse_source_file(source_file): """Parses a source file thing and returns the file name Example: >>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06') 'js/src/jit/MIR.h' :arg str source_file: the source file ("file") from a stack frame :returns: the fil...
Predicate for whether the open token is in an exception context
def _is_exception(exceptions, before_token, after_token, token): """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 d...
Collapses the text between two delimiters in a frame function value
def collapse( function, open_string, close_string, replacement='', exceptions=None, ): """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. ...
Takes the function value from a frame and drops prefix and return type
def drop_prefix_and_return_type(function): """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<Moz...
Wait for connections to be made and their handshakes to finish
def wait_connected(self, conns=None, timeout=None): '''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 p...
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: backend.schedule_exception( errors._...
Set a handler for incoming publish messages
def accept_publish( self, service, mask, value, method, handler=None, schedule=False): '''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-an...
Remove a publish subscription
def unsubscribe_publish(self, service, mask, value): '''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 i...
Send a 1 - way message
def publish(self, service, routing_id, method, args=None, kwargs=None, broadcast=False, udp=False): '''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 w...
Get the number of peers that would handle a particular publish
def publish_receiver_count(self, service, routing_id): '''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 ...
Set a handler for incoming RPCs
def accept_rpc(self, service, mask, value, method, handler=None, schedule=True): '''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 incom...
Remove a rpc subscription
def unsubscribe_rpc(self, service, mask, value): '''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 su...
Send out an RPC request
def send_rpc(self, service, routing_id, method, args=None, kwargs=None, broadcast=False): '''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 r...
Send an RPC request and return the corresponding response
def rpc(self, service, routing_id, method, args=None, kwargs=None, timeout=None, broadcast=False): '''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) ...
Get the number of peers that would handle a particular RPC
def rpc_receiver_count(self, service, routing_id): '''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_...
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_listener) backend.schedule(self._listener_coro) backend...
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._started_peers[peer_addr] = peer
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', action='store_true' ) parser.add_argument( '...
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: specific_servers = self.servers ...
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.
def prepare_dir(app, directory, delete=False): """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, d...
Join package and module with a dot.
def makename(package, module): """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: :clas...
Write the output file for module/ package <name >.
def write_file(app, name, text, dest, suffix, dryrun, force): """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 f...
Import the given name and return name obj parent mod_name
def import_name(app, name): """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 """ try: logger.debug('Importing %r', name) name, obj = autos...