code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def set_xtick_labels(self, row, column, labels): """Manually specify the x-axis tick labels. :param row,column: specify the subplot. :param labels: list of tick labels. """ subplot = self.get_subplot_at(row, column) subplot.set_xtick_labels(labels)
Manually specify the x-axis tick labels. :param row,column: specify the subplot. :param labels: list of tick labels.
def branch_rate(self, filename=None): """ Return the global branch rate of the coverage report. If the `filename` file is given, return the branch rate of the file. """ if filename is None: el = self.xml else: el = self._get_class_element_by_filena...
Return the global branch rate of the coverage report. If the `filename` file is given, return the branch rate of the file.
def socket_handler(name, logname, host, port): """ A Bark logging handler logging output to a stream (TCP) socket. The server listening at the given 'host' and 'port' will be sent a pickled dictionary. Similar to logging.handlers.SocketHandler. """ return wrap_log_handler(logging.handlers....
A Bark logging handler logging output to a stream (TCP) socket. The server listening at the given 'host' and 'port' will be sent a pickled dictionary. Similar to logging.handlers.SocketHandler.
def pl_resolution(KB, alpha): "Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]" clauses = KB.clauses + conjuncts(to_cnf(~alpha)) new = set() while True: n = len(clauses) pairs = [(clauses[i], clauses[j]) for i in range(n) for j in range(i+1, n)]...
Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]
def batch( baba, ipyclient=None, ): """ distributes jobs to the parallel client """ ## parse args handle = baba.data taxdicts = baba.tests mindicts = baba.params.mincov nboots = baba.params.nboots ## if ms generator make into reusable list sims = 0 if isinstance...
distributes jobs to the parallel client
def getsourcefile(object): """Return the Python source file an object was defined in, if it exists.""" filename = getfile(object) if string.lower(filename[-4:]) in ['.pyc', '.pyo']: filename = filename[:-4] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.l...
Return the Python source file an object was defined in, if it exists.
def start(self): """ start the channel listener and start consuming messages """ self.connections(True) binding_keys = sys.argv[1:] if not binding_keys: print(sys.stderr, 'Usage: {0!s} [binding_key]...'.format(sys.argv[0])) sys.exit(0) ...
start the channel listener and start consuming messages
def check_order(self, order): """ order must be a subset of self.order """ own_order = self.order for item in order: if item not in own_order: raise ValueError(f'Order item {item} not found.') return order
order must be a subset of self.order
def rawsql(query, ec=None): """ ec could be engine name or engine instance """ if isinstance(query, Result): query = query.get_query() ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): engine = engine_manager[ec] dialect = engine.engine.dialect else: ...
ec could be engine name or engine instance
def update_indel(self, nucmer_snp): '''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False''' new_v...
Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False
def doFind(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params): """This function will perform the command -find.""" self._preFind(WHAT, SORT, SKIP, MAX, LOP) for key in params: self._addDBParam(key, params[key]) try: return self._doAction('-find') except FMServerError as e: if e.args...
This function will perform the command -find.
def set_name(self, name): """Set the name of the item. :Parameters: - `name`: the new name or `None`. :Types: - `name`: `unicode` """ if name is None: if self.xmlnode.hasProp("name"): self.xmlnode.unsetProp("name") return ...
Set the name of the item. :Parameters: - `name`: the new name or `None`. :Types: - `name`: `unicode`
def load_extra(cls, filename): """Loads extra JSON configuration parameters from a file on the filesystem. Args: filename: str, the filename to open. Returns: bool: True if the extra configuration parameters were read. """ try: with open(filename, 'rb') as configuration_file: ...
Loads extra JSON configuration parameters from a file on the filesystem. Args: filename: str, the filename to open. Returns: bool: True if the extra configuration parameters were read.
def default(self, obj): """ Convert an object to a form ready to dump to json. :param obj: Object being serialized. The type of this object must be one of the following: None; a single object derived from the Pio class; or a list of objects, each derived from the Pio class. :return: Lis...
Convert an object to a form ready to dump to json. :param obj: Object being serialized. The type of this object must be one of the following: None; a single object derived from the Pio class; or a list of objects, each derived from the Pio class. :return: List of dictionaries, each representing a physi...
def get_unique_name(self, name): """ returns an available unique name Parameters ---------- name : str name to be made unique Returns ------- unique_name : str new unique name """ if name not in self._db: sel...
returns an available unique name Parameters ---------- name : str name to be made unique Returns ------- unique_name : str new unique name
async def unban(self, user, *, reason=None): """|coro| Unbans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.S...
|coro| Unbans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to unban. reason:...
def packed_checksum(self, data): """Given the data of the entire packet return the checksum bytes""" self.field.setval(self.algo(data[self.start:self.end])) sio = BytesIO() self.field.pack(sio) return sio.getvalue()
Given the data of the entire packet return the checksum bytes
def humanize_seconds(total_seconds, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}', negative_frmt=None): """Given time in int(seconds), return a string representing the time. If negative_frmt is not given, a negative sign is prepended to frmt and the result is wrap...
Given time in int(seconds), return a string representing the time. If negative_frmt is not given, a negative sign is prepended to frmt and the result is wrapped in a <span> with the "negative-time" class.
def depth_july_average_ground_temperature(self, value=None): """Corresponds to IDD Field `depth_july_average_ground_temperature` Args: value (float): value for IDD Field `depth_july_average_ground_temperature` Unit: C if `value` is None it will not be checked...
Corresponds to IDD Field `depth_july_average_ground_temperature` Args: value (float): value for IDD Field `depth_july_average_ground_temperature` Unit: C if `value` is None it will not be checked against the specification and is assumed to be a missin...
def _format_text(self, title, text, color, ellide=False): """ Create HTML template for calltips and tooltips. This will display title and text as separate sections and add `...` if `ellide` is True and the text is too long. """ template = ''' <div sty...
Create HTML template for calltips and tooltips. This will display title and text as separate sections and add `...` if `ellide` is True and the text is too long.
def sample(self, bqm, **kwargs): """Sample from the problem provided by bqm and truncate output. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **kwargs: Parameters for the sampling method, specified by ...
Sample from the problem provided by bqm and truncate output. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **kwargs: Parameters for the sampling method, specified by the child sampler. ...
def getscale(self): """Obtain the scale values along a dimension. Args:: no argument Returns:: list with the scale values; the list length is equal to the dimension length; the element type is equal to the dimension data type, as set when the 'setdimsc...
Obtain the scale values along a dimension. Args:: no argument Returns:: list with the scale values; the list length is equal to the dimension length; the element type is equal to the dimension data type, as set when the 'setdimscale()' method was called. ...
def get_all_parsers(self, strict_type_matching: bool = False) -> List[Parser]: """ Returns the list of all parsers in order of relevance. :return: """ matching = self.find_all_matching_parsers(strict=strict_type_matching)[0] # matching[1] (approx match) is supposed to be...
Returns the list of all parsers in order of relevance. :return:
def read(self, pk=None, fail_on_no_results=False, fail_on_multiple_results=False, **kwargs): """ =====API DOCS===== Retrieve and return objects from the Ansible Tower API. :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read that object ...
=====API DOCS===== Retrieve and return objects from the Ansible Tower API. :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read that object if ``pk`` is provided (not ``None``). :type pk: int :param fail_on_no_results: Flag that if se...
def _SR(cpu, insn_id, dest, op, *rest): """ Notes on Capstone behavior: - In ARM mode, _SR reg has `rest`, but _SR imm does not, its baked into `op`. - In ARM mode, `lsr r1, r2` will have a `rest[0]` - In Thumb mode, `lsr r1, r2` will have an empty `rest` - In ARM mode, s...
Notes on Capstone behavior: - In ARM mode, _SR reg has `rest`, but _SR imm does not, its baked into `op`. - In ARM mode, `lsr r1, r2` will have a `rest[0]` - In Thumb mode, `lsr r1, r2` will have an empty `rest` - In ARM mode, something like `lsr r1, 3` will not have `rest` and op will b...
def rel_url_to_id(url): """Converts a relative URL to a unique ID. Here, 'ID' refers generally to the unique ID for a given 'type' that a given datum has. For example, 'BradTo00' is Tom Brady's player ID - this corresponds to his relative URL, '/players/B/BradTo00.htm'. Similarly, '201409070dal' re...
Converts a relative URL to a unique ID. Here, 'ID' refers generally to the unique ID for a given 'type' that a given datum has. For example, 'BradTo00' is Tom Brady's player ID - this corresponds to his relative URL, '/players/B/BradTo00.htm'. Similarly, '201409070dal' refers to the boxscore of the SF ...
def nl_send_simple(sk, type_, flags, buf=None, size=0): """Construct and transmit a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L549 Allocates a new Netlink message based on `type_` and `flags`. If `buf` points to payload of length `size` that payload will be appended t...
Construct and transmit a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L549 Allocates a new Netlink message based on `type_` and `flags`. If `buf` points to payload of length `size` that payload will be appended to the message. Sends out the message using `nl_send_auto()...
def config(self): """ Allows changing the config on the fly """ # TODO more efficient to read once and put watch on the file config = {} if self.config_file.exists(): with open(self.config_file.as_posix(), 'rt') as f: # 3.5/pypy3 can't open Path directly conf...
Allows changing the config on the fly
def precision(classifier, testset): """ Runs the classifier for each example in `testset` and verifies that the classification is correct using the `target`. Returns a number between 0.0 and 1.0 with the precision of classification for this test set. """ hit = 0 total = 0 for e...
Runs the classifier for each example in `testset` and verifies that the classification is correct using the `target`. Returns a number between 0.0 and 1.0 with the precision of classification for this test set.
def ekgc(selidx, row, element, lenout=_default_len_out): """ Return an element of an entry in a column of character type in a specified row. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgc_c.html :param selidx: Index of parent column in SELECT clause. :type selidx: int :param ...
Return an element of an entry in a column of character type in a specified row. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgc_c.html :param selidx: Index of parent column in SELECT clause. :type selidx: int :param row: Row to fetch from. :type row: int :param element: Index ...
def autodiscover(path=None, plugin_prefix='intake_'): """Scan for Intake plugin packages and return a dict of plugins. This function searches path (or sys.path) for packages with names that start with plugin_prefix. Those modules will be imported and scanned for subclasses of intake.source.base.Plugin...
Scan for Intake plugin packages and return a dict of plugins. This function searches path (or sys.path) for packages with names that start with plugin_prefix. Those modules will be imported and scanned for subclasses of intake.source.base.Plugin. Any subclasses found will be instantiated and returned...
def splitFile(inputFileName, linePerFile, outPrefix): """Split a file. :param inputFileName: the name of the input file. :param linePerFile: the number of line per file (after splitting). :param outPrefix: the prefix of the output files. :type inputFileName: str :type linePerFile: int :typ...
Split a file. :param inputFileName: the name of the input file. :param linePerFile: the number of line per file (after splitting). :param outPrefix: the prefix of the output files. :type inputFileName: str :type linePerFile: int :type outPrefix: str :returns: the number of created tempora...
def read_csv(path, fieldnames=None, sniff=True, encoding='utf-8', *args, **kwargs): ''' Read CSV rows as table from a file. By default, csv.reader() will be used any output will be a list of lists. If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead. CSV sni...
Read CSV rows as table from a file. By default, csv.reader() will be used any output will be a list of lists. If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead. CSV sniffing (dialect detection) is enabled by default, set sniff=False to switch it off.
def path_to_str(path): """ Convert pathlib.Path objects to str; return other objects as-is. """ try: from pathlib import Path as _Path except ImportError: # Python < 3.4 class _Path: pass if isinstance(path, _Path): return str(path) return path
Convert pathlib.Path objects to str; return other objects as-is.
def _start_of_week(self): """ Reset the date to the first day of the week and the time to 00:00:00. :rtype: DateTime """ dt = self if self.day_of_week != pendulum._WEEK_STARTS_AT: dt = self.previous(pendulum._WEEK_STARTS_AT) return dt.start_...
Reset the date to the first day of the week and the time to 00:00:00. :rtype: DateTime
def shap_values(self, X, **kwargs): """ Estimate the SHAP values for a set of samples. Parameters ---------- X : numpy.array or pandas.DataFrame A matrix of samples (# samples x # features) on which to explain the model's output. Returns ------- For ...
Estimate the SHAP values for a set of samples. Parameters ---------- X : numpy.array or pandas.DataFrame A matrix of samples (# samples x # features) on which to explain the model's output. Returns ------- For a models with a single output this returns a mat...
def get_fast_scanner(self): """ Return :class:`.FastScanner` for association scan. Returns ------- fast-scanner : :class:`.FastScanner` Instance of a class designed to perform very fast association scan. """ v0 = self.v0 v1 = self.v1 Q...
Return :class:`.FastScanner` for association scan. Returns ------- fast-scanner : :class:`.FastScanner` Instance of a class designed to perform very fast association scan.
def p_casecontent_statement(self, p): 'casecontent_statement : casecontent_condition COLON basic_statement' p[0] = Case(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
casecontent_statement : casecontent_condition COLON basic_statement
def gt(self, key, value, includeMissing=False): '''Return entries where the key's value is greater (>). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]},...
Return entries where the key's value is greater (>). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 1500...
def describe_connection(self): """Return string representation of the device, including the connection state""" if self.device==None: return "%s [disconnected]" % (self.name) else: return "%s connected to %s %s version: %s [serial: %s]" % (self.name, ...
Return string representation of the device, including the connection state
def post(request): """Sets a key to a value on the currently logged in users preferences :param key: Key to set :type key: str :param val: Value to set :type val: primitive :returns: json """ data = request.POST or json.loads(request.body)['body'] key = data.get('key', None) val...
Sets a key to a value on the currently logged in users preferences :param key: Key to set :type key: str :param val: Value to set :type val: primitive :returns: json
def dfs_absent(path): ''' Check if a file or directory is absent on the distributed FS. CLI Example: .. code-block:: bash salt '*' hadoop.dfs_absent /some_random_file Returns True if the file is absent ''' cmd_return = _hadoop_cmd('dfs', 'stat', path) match = 'No such file or...
Check if a file or directory is absent on the distributed FS. CLI Example: .. code-block:: bash salt '*' hadoop.dfs_absent /some_random_file Returns True if the file is absent
def handle_update_search_space(self, data): """change json format to ConfigSpace format dict<dict> -> configspace Parameters ---------- data: JSON object search space of this experiment """ search_space = data cs = CS.ConfigurationSpace() for ...
change json format to ConfigSpace format dict<dict> -> configspace Parameters ---------- data: JSON object search space of this experiment
def to_curve25519_private_key(self): """ Converts a :class:`~nacl.signing.SigningKey` to a :class:`~nacl.public.PrivateKey` :rtype: :class:`~nacl.public.PrivateKey` """ sk = self._signing_key raw_private = nacl.bindings.crypto_sign_ed25519_sk_to_curve25519(sk) ...
Converts a :class:`~nacl.signing.SigningKey` to a :class:`~nacl.public.PrivateKey` :rtype: :class:`~nacl.public.PrivateKey`
def on_block_received(self, block_id): """This is exposed for unit tests, and should not be called directly. """ _libexec('chain_controller_on_block_received', self.pointer, ctypes.c_char_p(block_id.encode('utf-8')))
This is exposed for unit tests, and should not be called directly.
def logSE(x1, x2=-1): """ 10 * log10(e**2) This function accepts two series of data or directly one series with error. **Args:** * `x1` - first data series or error (1d array) **Kwargs:** * `x2` - second series (1d array) if first series was not error directly,\\ then thi...
10 * log10(e**2) This function accepts two series of data or directly one series with error. **Args:** * `x1` - first data series or error (1d array) **Kwargs:** * `x2` - second series (1d array) if first series was not error directly,\\ then this should be the second series ...
def votes(self, req) -> int: """ Get the number of propagates for a given reqId and identifier. """ try: votes = len(self[req.key].propagates) except KeyError: votes = 0 return votes
Get the number of propagates for a given reqId and identifier.
def _Assign(self, t): """ Expression Assignment such as "a = 1". This only handles assignment in expressions. Keyword assignment is handled separately. """ self._fill() for target in t.nodes: self._dispatch(target) self._write(" = ") ...
Expression Assignment such as "a = 1". This only handles assignment in expressions. Keyword assignment is handled separately.
def check_s3_url(self, s3url): """ Check if an S3 URL exists :param s3url: S3 url :type s3url: str :rtype: bool """ bucket, key = S3Hook.parse_s3_url(s3url) if not self.s3_hook.check_for_bucket(bucket_name=bucket): raise AirflowException( ...
Check if an S3 URL exists :param s3url: S3 url :type s3url: str :rtype: bool
def add_contig_to_header_cl(ref_file, out_file): """Add update ##contig lines to VCF header, required for bcftools/GATK compatibility. """ header_file = "%s-contig_header.txt" % utils.splitext_plus(out_file)[0] with open(header_file, "w") as out_handle: for region in ref.file_contigs(ref_file, {...
Add update ##contig lines to VCF header, required for bcftools/GATK compatibility.
def know(self, what, confidence): """Know something with the given confidence, and return self for chaining. If confidence is higher than that of what we already know, replace what we already know with what you're telling us. """ if confidence > self.confidence: sel...
Know something with the given confidence, and return self for chaining. If confidence is higher than that of what we already know, replace what we already know with what you're telling us.
def output_barplot(df, figformat, path, title=None, palette=None): """Create barplots based on number of reads and total sum of nucleotides sequenced.""" logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.") read_count = Plot(path=path + "NanoComp_number_of_reads." + figfo...
Create barplots based on number of reads and total sum of nucleotides sequenced.
def create_was_invalidated_by_relation(self, activity_id, entity_kind, entity_id): """ Create a was invalidated by relationship between an activity and a entity(file). :param activity_id: str: uuid of the activity :param entity_kind: str: kind of entity('dds-file') :param entity_...
Create a was invalidated by relationship between an activity and a entity(file). :param activity_id: str: uuid of the activity :param entity_kind: str: kind of entity('dds-file') :param entity_id: str: uuid of the entity :return: requests.Response containing the successful result
def regex_in(pl,regex): ''' regex = re.compile("^[a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) regex = re.compile("^[0-9a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) ''' def cond_func(ele,regex): m...
regex = re.compile("^[a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) regex = re.compile("^[0-9a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex)
def histogram(self, column='r', filename=None, log10=False, **kwargs): """Plot a histogram of one data column""" return_dict = HS.plot_histograms(self.data, column) if filename is not None: return_dict['all'].savefig(filename, dpi=300) return return_dict
Plot a histogram of one data column
def draw(self): """ Draw the figure using the renderer """ if __debug__: verbose.report('FigureCanvasAgg.draw', 'debug-annoying') self.renderer = self.get_renderer(cleared=True) # acquire a lock on the shared font cache RendererAgg.lock.acquire() try: ...
Draw the figure using the renderer
def _generate_examples(self, file_id, extracted_dirs): """Yields examples.""" filedir = os.path.join(extracted_dirs["img_align_celeba"], "img_align_celeba") img_list_path = extracted_dirs["list_eval_partition"] landmarks_path = extracted_dirs["landmarks_celeba"] attr_path ...
Yields examples.
def wrapped_setups(self): """Create tokens for Described.setup = noy_wrap_setup(Described, Described.setup) for setup/teardown""" lst = [] for group in self.all_groups: if not group.root: if group.has_after_each: lst.extend(self.tokens.wrap_after_e...
Create tokens for Described.setup = noy_wrap_setup(Described, Described.setup) for setup/teardown
def get_dir(path, dest, saltenv='base'): ''' Transfer a directory down ''' src = __context__['fileclient'].cache_dir( path, saltenv, cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_'])) src = ' '.join(src) single = salt.client.ssh.Single( __opts__, ...
Transfer a directory down
def rn_theory(af, b): """ R(n) ratio expected from theory for given noise type alpha = b + 2 """ # From IEEE1139-2008 # alpha beta ADEV_mu MDEV_mu Rn_mu # -2 -4 1 1 0 Random Walk FM # -1 -3 0 0 0 Flicker FM # ...
R(n) ratio expected from theory for given noise type alpha = b + 2
def set_scale(self, scale): """ Set the device scale register. Device must be in standby before calling this function @param scale: scale factor @return: No return value """ register = self.MMA8452Q_Register['XYZ_DATA_CFG'] self.board.i2c_read_request(self...
Set the device scale register. Device must be in standby before calling this function @param scale: scale factor @return: No return value
def update_rel_to(self, klass): """ If we have a string for a model, see if we know about it yet, if so use it directly otherwise take the lazy approach. This check is needed because this is called before the main M2M field contribute to class is called. """ if i...
If we have a string for a model, see if we know about it yet, if so use it directly otherwise take the lazy approach. This check is needed because this is called before the main M2M field contribute to class is called.
def _set_date_tuple(self, mediafile, year, month=None, day=None): """Set the value of the field given a year, month, and day number. Each number can be an integer or None to indicate an unset component. """ if year is None: self.__delete__(mediafile) retur...
Set the value of the field given a year, month, and day number. Each number can be an integer or None to indicate an unset component.
def messageReceived(self, message): """ Overridden from :class:`ZmqConnection` to process and unframe incoming messages. All parsed messages are passed to :meth:`gotMessage`. :param message: message data """ if len(message) == 2: # compatibility rece...
Overridden from :class:`ZmqConnection` to process and unframe incoming messages. All parsed messages are passed to :meth:`gotMessage`. :param message: message data
def dict_strip(d): """Strips whitespace from the string values of the given dictionary (recursively). Args: d: A dictionary object. Returns: A new dictionary object, whose string values' whitespace has been stripped out. """ _d = deepcopy(d) for k, v in iteritems(d): if...
Strips whitespace from the string values of the given dictionary (recursively). Args: d: A dictionary object. Returns: A new dictionary object, whose string values' whitespace has been stripped out.
def overview(): """ Function to create an overview of the services. Will print a list of ports found an the number of times the port was seen. """ search = Service.search() search = search.filter("term", state='open') search.aggs.bucket('port_count', 'terms', field='port', order={'_c...
Function to create an overview of the services. Will print a list of ports found an the number of times the port was seen.
def prettify(string): """ replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis πŸ“– β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ0% ``` """ ...
replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis πŸ“– β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ0% ```
def cmd(send, msg, args): """Check the git revison. Syntax: {command} [check|master] """ parser = arguments.ArgParser(args['config']) parser.add_argument('action', choices=['check', 'master', 'commit'], nargs='?') try: cmdargs = parser.parse_args(msg) except arguments.ArgumentExce...
Check the git revison. Syntax: {command} [check|master]
def cmd(send, *_): """Causes the bot to generate some jargon. Syntax: {command} """ words = [[verb, noun, abbrev, noun, adj, abbrev, noun], [verb, adj, abbrev, noun], [verb, abbrev, noun, verb, adj, noun], [verb, noun, ingverb, adj, abbrev, noun], [adj, abbrev, noun, verb, adj, noun], [ab...
Causes the bot to generate some jargon. Syntax: {command}
def formatSubclassOf(fmt, cls, ontology, visited): # type: (Text, Text, Optional[Graph], Set[Text]) -> bool """Determine if `fmt` is a subclass of `cls`.""" if URIRef(fmt) == URIRef(cls): return True if ontology is None: return False if fmt in visited: return False vi...
Determine if `fmt` is a subclass of `cls`.
def get_document( self, collection_id, ref=None, mimetype="application/tei+xml, application/xml"): """ Make a navigation request on the DTS API :param collection_id: Id of the collection :param ref: If ref is a tuple, it is treated as a range. String or int are treated a...
Make a navigation request on the DTS API :param collection_id: Id of the collection :param ref: If ref is a tuple, it is treated as a range. String or int are treated as single ref :param mimetype: Media type to request :return: Response :rtype: requests.Response
def createissue(accountable, options): """ Create new issue. """ issue = accountable.issue_create(options) headers = sorted(['id', 'key', 'self']) rows = [headers, [itemgetter(header)(issue) for header in headers]] print_table(SingleTable(rows))
Create new issue.
def get_tags_of_letter_per_page(self, letter_id, per_page=1000, page=1): """ Get tags of letter per page :param letter_id: the letter id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list """ return...
Get tags of letter per page :param letter_id: the letter id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
def rgb2hex(rgb, force_long=False): """Transform RGB tuple to hex RGB representation :param rgb: RGB 3-uple of float between 0 and 1 :rtype: 3 hex char or 6 hex char string representation Usage ----- >>> from colour import rgb2hex >>> rgb2hex((0.0,1.0,0.0)) '#0f0' Rounding try t...
Transform RGB tuple to hex RGB representation :param rgb: RGB 3-uple of float between 0 and 1 :rtype: 3 hex char or 6 hex char string representation Usage ----- >>> from colour import rgb2hex >>> rgb2hex((0.0,1.0,0.0)) '#0f0' Rounding try to be as natural as possible: >>> rgb2h...
def get_projects(): """ Returns a dict of projects present in the database. :return: dict -> {<int_keys>: <project_name>} """ conn, c = open_data_base_connection() try: c.execute("""SELECT project_name FROM main_table""") project_names = np.array(c.fetchall()).squeeze(axis=1) ...
Returns a dict of projects present in the database. :return: dict -> {<int_keys>: <project_name>}
def say(self, txt, lang=None): ''' Says the text. if ``lang`` is ``None``, then uses ``classify()`` to detect language. ''' lang = lang or self.classify(txt) self.get_engine_for_lang(lang).say(txt, language=lang)
Says the text. if ``lang`` is ``None``, then uses ``classify()`` to detect language.
def adapt(obj, to_cls): """ Will adapt `obj` to an instance of `to_cls`. First sees if `obj` has an `__adapt__` method and uses it to adapt. If that fails it checks if `to_cls` has an `__adapt__` classmethod and uses it to adapt. IF that fails, MRO is used. If that fails, a `TypeError` is raise...
Will adapt `obj` to an instance of `to_cls`. First sees if `obj` has an `__adapt__` method and uses it to adapt. If that fails it checks if `to_cls` has an `__adapt__` classmethod and uses it to adapt. IF that fails, MRO is used. If that fails, a `TypeError` is raised.
def get(self, list_id=None, email_address=None, include_tracking_preference=False): """Gets a subscriber by list ID and email address.""" params = { "email": email_address or self.email_address, "includetrackingpreference": include_tracking_preference, } response ...
Gets a subscriber by list ID and email address.
def post_chat_message(self, merchant_id, channel_id, message): """post a chat message Arguments: channel_id: Scan token """ return self.do_req('POST', self.base_url + '/chat/v1/merchant/%s/channel/%s/message/' % (merchant_id, chann...
post a chat message Arguments: channel_id: Scan token
def get_books_containing_page(cursor, uuid, version, context_uuid=None, context_version=None): """Return a list of book names and UUIDs that contain a given module UUID.""" with db_connect() as db_connection: # Uses a RealDictCursor instead of the regular cursor ...
Return a list of book names and UUIDs that contain a given module UUID.
def assign_from_ast(node, expr): """ Creates code to assign name (or tuple of names) node from expr This is useful for recreating destructuring assignment behavior, like a, *b = [1,2,3]. """ if isinstance(expr, str): expr = ast.Name(id=expr, ctx=ast.Load()) mod = ast.Module([ast.Ass...
Creates code to assign name (or tuple of names) node from expr This is useful for recreating destructuring assignment behavior, like a, *b = [1,2,3].
def enumerate_imports(tokens): """ Iterates over *tokens* and returns a list of all imported modules. .. note:: This ignores imports using the 'as' and 'from' keywords. """ imported_modules = [] import_line = False from_import = False for index, tok in enumerate(tokens): token_t...
Iterates over *tokens* and returns a list of all imported modules. .. note:: This ignores imports using the 'as' and 'from' keywords.
def __pred_for_np2d(self, mat, num_iteration, predict_type): """Predict for a 2-D numpy matrix.""" if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray or list must be 2 dimensional') def inner_predict(mat, num_iteration, predict_type, preds=None): if mat.dtype ...
Predict for a 2-D numpy matrix.
def locate_range(self, key, start=None, stop=None): """Locate slice of index containing all entries within the range `key`:`start`-`stop` **inclusive**. Parameters ---------- key : object Level 1 key value. start : object, optional Level 2 start v...
Locate slice of index containing all entries within the range `key`:`start`-`stop` **inclusive**. Parameters ---------- key : object Level 1 key value. start : object, optional Level 2 start value. stop : object, optional Level 2 stop ...
def makebunches_alter(data, commdct, theidf): """make bunches with data""" bunchdt = {} dt, dtls = data.dt, data.dtls for obj_i, key in enumerate(dtls): key = key.upper() objs = dt[key] list1 = [] for obj in objs: bobj = makeabunch(commdct, obj, obj_i) ...
make bunches with data
def copy( self ): """ Make a copy of this :class:`ParserElement`. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) ...
Make a copy of this :class:`ParserElement`. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) integerK = integer.copy().addParse...
def tsne(self, data_view_id): """ Get the t-SNE projection, including responses and tags. :param data_view_id: The ID of the data view to retrieve TSNE from :type data_view_id: int :return: The TSNE analysis :rtype: :class:`Tsne` """ analysis = self._data...
Get the t-SNE projection, including responses and tags. :param data_view_id: The ID of the data view to retrieve TSNE from :type data_view_id: int :return: The TSNE analysis :rtype: :class:`Tsne`
def column_list(string): """Validate and convert comma-separated list of column numbers.""" try: columns = list(map(int, string.split(','))) except ValueError as e: raise argparse.ArgumentTypeError(*e.args) for column in columns: if column < 1: raise argparse.Argument...
Validate and convert comma-separated list of column numbers.
def Fierz_to_JMS_chrom(C, qq): """From chromomagnetic Fierz to JMS basis for Class V. qq should be of the form 'sb', 'ds' etc.""" if qq[0] in dflav: s = dflav[qq[0]] + 1 b = dflav[qq[1]] + 1 return {'dgamma_{}{}'.format(s, b): C['F7gamma' + qq], 'dG_{}{}'.format(s, b)...
From chromomagnetic Fierz to JMS basis for Class V. qq should be of the form 'sb', 'ds' etc.
def pip_installer_url(version=None): """Get argument to give to ``pip`` to install HPCBench. """ version = version or hpcbench.__version__ version = str(version) if '.dev' in version: git_rev = 'master' if 'TRAVIS_BRANCH' in os.environ: git_rev = version.split('+', 1)[-1]...
Get argument to give to ``pip`` to install HPCBench.
def load_mnist_data(args): ''' Load MNIST dataset ''' (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = (np.expand_dims(x_train, -1).astype(np.float) / 255.)[:args.num_train] x_test = (np.expand_dims(x_test, -1).astype(np.float) / 255.)[:args.num_test] y_train = keras.utils...
Load MNIST dataset
def _default_conflict_solver(match, conflicting_match): """ Default conflict solver for matches, shorter matches if they conflicts with longer ones :param conflicting_match: :type conflicting_match: :param match: :type match: :return: :rtype: """ if len(conflicting_match.initiat...
Default conflict solver for matches, shorter matches if they conflicts with longer ones :param conflicting_match: :type conflicting_match: :param match: :type match: :return: :rtype:
def set_focus(self, pos): "Set the focus in the underlying body widget." logging.debug('setting focus to %s ', pos) self.body.set_focus(pos)
Set the focus in the underlying body widget.
def convert(isbn, code='978'): """Convert ISBNs between ISBN-10 and ISBN-13. Note: No attempt to hyphenate converted ISBNs is made, because the specification requires that *any* hyphenation must be correct but allows ISBNs without hyphenation. Args: isbn (str): SBN, ISBN-10...
Convert ISBNs between ISBN-10 and ISBN-13. Note: No attempt to hyphenate converted ISBNs is made, because the specification requires that *any* hyphenation must be correct but allows ISBNs without hyphenation. Args: isbn (str): SBN, ISBN-10 or ISBN-13 code (str): EAN Bo...
def dump_yaml(data, clean_up=False, long_form=False): """ Output some YAML """ return yaml.dump( data, Dumper=get_dumper(clean_up, long_form), default_flow_style=False, allow_unicode=True )
Output some YAML
def add_single(self, address, rank=1, nodeid=1, ospf_area=None, **kwargs): """ Add a single loopback interface to this engine. This is used for single or virtual FW engines. :param str address: ip address for loopback :param int nodeid: nodeid to apply. Default to 1 for ...
Add a single loopback interface to this engine. This is used for single or virtual FW engines. :param str address: ip address for loopback :param int nodeid: nodeid to apply. Default to 1 for single FW :param str, Element ospf_area: ospf area href or element :raises Upda...
def rotate(file_name, rotation, suffix='rotated', tempdir=None, method='pypdf3'): """Rotate PDF by increments of 90 degrees.""" return str(Rotate(file_name, rotation, suffix, tempdir, method))
Rotate PDF by increments of 90 degrees.
def CorrectWrongEmails(self, askInput=True): '''Corrects Emails in wrong_emails''' for email in self.wrong_emails: corrected_email = self.CorrectEmail(email) self.emails[self.emails.index(email)] = corrected_email self.wrong_emails = []
Corrects Emails in wrong_emails
def get_EOL(file): """ find EOL of input file (whether mac,PC or unix format) """ f = open(file, 'r') firstline = f.read(350) EOL = "" for k in range(350): if firstline[k:k + 2] == "\r\n": print(file, ' appears to be a dos file') EOL = '\r\n' brea...
find EOL of input file (whether mac,PC or unix format)
def _updateMetadata(self, variantFile): """ Updates the metadata for his variant set based on the specified variant file """ metadata = self._getMetadataFromVcf(variantFile) if self._metadata is None: self._metadata = metadata
Updates the metadata for his variant set based on the specified variant file