code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def visualize_explanation(explanation, label=None): """ Given the output of the explain() endpoint, produces a terminal visual that plots response strength over a sequence """ if not sys.version_info[:2] >= (3, 5): raise IndicoError("Python >= 3.5+ is required for explanation visualization") ...
Given the output of the explain() endpoint, produces a terminal visual that plots response strength over a sequence
def _writetypesdoc(doc, thing, forceload=0): """Write HTML documentation to a file in the current directory. """ try: object, name = pydoc.resolve(thing, forceload) name = os.path.join(doc, name + '.html') except (ImportError, pydoc.ErrorDuringImport), value: log.debug(str(value)...
Write HTML documentation to a file in the current directory.
def PublishEvent(cls, event_name, msg, token=None): """Publish the message into all listeners of the event. We send the message to all event handlers which contain this string in their EVENT static member. This allows the event to be sent to multiple interested listeners. Args: event_name: A...
Publish the message into all listeners of the event. We send the message to all event handlers which contain this string in their EVENT static member. This allows the event to be sent to multiple interested listeners. Args: event_name: An event name. msg: The message to send to the event h...
def openflow_controller_controller_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") openflow_controller = ET.SubElement(config, "openflow-controller", xmlns="urn:brocade.com:mgmt:brocade-openflow") controller_name = ET.SubElement(openflow_controller,...
Auto Generated Code
def _set_default_vrf(self, v, load=False): """ Setter method for default_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf (container) If this variable is read-only (config: false) in the source YANG file, then _set_default_vrf is considered as a p...
Setter method for default_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf (container) If this variable is read-only (config: false) in the source YANG file, then _set_default_vrf is considered as a private method. Backends looking to populate this va...
def _empty_queue(self): """Dump all live point proposals currently on the queue.""" while True: try: # Remove unused points from the queue. self.queue.pop() self.unused += 1 # add to the total number of unused points self.nque...
Dump all live point proposals currently on the queue.
def _set_ocsp_callback(self, helper, data): """ This internal helper does the common work for ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is almost all of it. """ self._ocsp_helper = helper self._ocsp_callback = helper.callback if ...
This internal helper does the common work for ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is almost all of it.
def modified(self, base: pathlib.PurePath = pathlib.PurePath()) \ -> Iterator[str]: """ Find the paths of modified files. There is no option to include intermediate directories, as all files and directories exist in both the left and right trees. :param base: The bas...
Find the paths of modified files. There is no option to include intermediate directories, as all files and directories exist in both the left and right trees. :param base: The base directory to recursively append to the right entity. :return: An iterable of paths of...
def inverse(self): """Return the inverse operator. Examples -------- >>> r3 = odl.rn(3) >>> vec = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2.0) >>> inv = op.inverse >>> inv(op(vec)) == vec True >>> op(inv(vec)) == vec Tru...
Return the inverse operator. Examples -------- >>> r3 = odl.rn(3) >>> vec = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2.0) >>> inv = op.inverse >>> inv(op(vec)) == vec True >>> op(inv(vec)) == vec True
def as_tree(self, visitor=None, children=None): """ Recursively traverses each tree (starting from each root) in order to generate a dictionary-based tree structure of the entire forest. Each level of the forest/tree is a list of nodes, and each node consists of a dictionary ...
Recursively traverses each tree (starting from each root) in order to generate a dictionary-based tree structure of the entire forest. Each level of the forest/tree is a list of nodes, and each node consists of a dictionary representation, where the entry ``children`` (by...
def default(self, vid): """ Defaults the VLAN configuration .. code-block:: none default vlan <vlanid> Args: vid (str): The VLAN ID to default Returns: True if the operation was successful otherwise False """ command = 'default vlan...
Defaults the VLAN configuration .. code-block:: none default vlan <vlanid> Args: vid (str): The VLAN ID to default Returns: True if the operation was successful otherwise False
def put(self, transfer_id, amount, created_timestamp, receipt): """ :param transfer_id: int of the account_id to deposit the money to :param amount: float of the amount to transfer :param created_timestamp: str of the validated receipt that money has been received ...
:param transfer_id: int of the account_id to deposit the money to :param amount: float of the amount to transfer :param created_timestamp: str of the validated receipt that money has been received :param receipt: str of the receipt :return: ...
def _sort_results(self, results): """ Order the results. :param results: The disordened results. :type results: array.bs4.element.Tag :return: The ordened results. :rtype: array.bs4.element.Tag """ parents = [] groups = [] for result in r...
Order the results. :param results: The disordened results. :type results: array.bs4.element.Tag :return: The ordened results. :rtype: array.bs4.element.Tag
def attach_stream(self, stream): """Notify that we would like to attach a node input to this stream. The return value from this function is the DataStream that should be attached to since this function may internally allocate a new SGNode that copies the stream if there is no space in t...
Notify that we would like to attach a node input to this stream. The return value from this function is the DataStream that should be attached to since this function may internally allocate a new SGNode that copies the stream if there is no space in the output list to hold another input. ...
def wait_for_simulation_stop(self, timeout=None): """Block until the simulation is done or timeout seconds exceeded. If the simulation stops before timeout, siminfo is returned. """ start = datetime.now() while self.get_is_sim_running(): sleep(0.5) if tim...
Block until the simulation is done or timeout seconds exceeded. If the simulation stops before timeout, siminfo is returned.
def read_config_files(self, files): """Read a list of config files. :param iterable files: An iterable (e.g. list) of files to read. """ errors = {} for _file in files: config, valid = self.read_config_file(_file) self.update(config) if valid ...
Read a list of config files. :param iterable files: An iterable (e.g. list) of files to read.
def get_active_lines(lines, comment_char="#"): """ Returns lines, or parts of lines, from content that are not commented out or completely empty. The resulting lines are all individually stripped. This is useful for parsing many config files such as ifcfg. Parameters: lines (list): List o...
Returns lines, or parts of lines, from content that are not commented out or completely empty. The resulting lines are all individually stripped. This is useful for parsing many config files such as ifcfg. Parameters: lines (list): List of strings to parse. comment_char (str): String indi...
def _convert_coordinatelist(input_obj): """convert from 'list' or 'tuple' object to pgmagick.CoordinateList. :type input_obj: list or tuple """ cdl = pgmagick.CoordinateList() for obj in input_obj: cdl.append(pgmagick.Coordinate(obj[0], obj[1])) return cdl
convert from 'list' or 'tuple' object to pgmagick.CoordinateList. :type input_obj: list or tuple
def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ans...
Introspect Ansible module. :param module: :return:
def name2rgb(name): """Convert the name of a color into its RGB value""" try: import colour except ImportError: raise ImportError('You need colour to be installed: pip install colour') c = colour.Color(name) color = int(c.red * 255), int(c.green * 255), int(c.blue * 255) return ...
Convert the name of a color into its RGB value
def _mk_connectivity_flats(self, i12, j1, j2, mat_data, flats, elev, mag): """ Helper function for _mk_adjacency_matrix. This calcualtes the connectivity for flat regions. Every pixel in the flat will drain to a random pixel in the flat. This accumulates all the area in the flat ...
Helper function for _mk_adjacency_matrix. This calcualtes the connectivity for flat regions. Every pixel in the flat will drain to a random pixel in the flat. This accumulates all the area in the flat region to a single pixel. All that area is then drained from that pixel to the surround...
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works. ''' # if the username and password were already found don't fo though the # connection process again if 'username' in DETAILS and 'password' in DETAILS: return DETAILS['userna...
Cycle through all the possible credentials and return the first one that works.
def get_config_id(kwargs=None, call=None): ''' Returns a config_id for a given linode. .. versionadded:: 2015.8.0 name The name of the Linode for which to get the config_id. Can be used instead of ``linode_id``.h linode_id The ID of the Linode for which to get the config_i...
Returns a config_id for a given linode. .. versionadded:: 2015.8.0 name The name of the Linode for which to get the config_id. Can be used instead of ``linode_id``.h linode_id The ID of the Linode for which to get the config_id. Can be used instead of ``name``. CLI Ex...
def get_link(self, task_id): """Get a ``LinkOfTrust`` by task id. Args: task_id (str): the task id to find. Returns: LinkOfTrust: the link matching the task id. Raises: CoTError: if no ``LinkOfTrust`` matches. """ links = [x for x i...
Get a ``LinkOfTrust`` by task id. Args: task_id (str): the task id to find. Returns: LinkOfTrust: the link matching the task id. Raises: CoTError: if no ``LinkOfTrust`` matches.
def catch_config_error(method, app, *args, **kwargs): """Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook...
Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input.
def remove_all_observers(self): """ Removes all registered observers. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: self.remove_observer(observer)
Removes all registered observers.
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel subclass. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard orde...
Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel subclass. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compo...
def generate_nodeinfo2_document(**kwargs): """ Generate a NodeInfo2 document. Pass in a dictionary as per NodeInfo2 1.0 schema: https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json Minimum required schema: {server: baseUrl name software ...
Generate a NodeInfo2 document. Pass in a dictionary as per NodeInfo2 1.0 schema: https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json Minimum required schema: {server: baseUrl name software version } openRegistrations ...
def configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s'): """ Configure the default stream handler for logging messages to the console, remove other logging handlers, and enable capturing warnings. .. versionadded:: 1.3.0 :param str logger: The logger to add the stream handler ...
Configure the default stream handler for logging messages to the console, remove other logging handlers, and enable capturing warnings. .. versionadded:: 1.3.0 :param str logger: The logger to add the stream handler for. :param level: The level to set the logger to, will default to WARNING if no level is specifie...
def parse_request() -> Dict[str, str]: """ Parse the request of the git credential API from stdin. Returns: A dictionary with all key-value pairs of the request """ in_lines = sys.stdin.readlines() LOGGER.debug('Received request "%s"', in_lines) request = {} for line in in_line...
Parse the request of the git credential API from stdin. Returns: A dictionary with all key-value pairs of the request
def verify_leaf_inclusion(self, leaf: bytes, leaf_index: int, proof: List[bytes], sth: STH): """Verify a Merkle Audit Path. See section 2.1.1 of RFC6962 for the exact path description. Args: leaf: The leaf for which the proof was provided. ...
Verify a Merkle Audit Path. See section 2.1.1 of RFC6962 for the exact path description. Args: leaf: The leaf for which the proof was provided. leaf_index: Index of the leaf in the tree. proof: A list of SHA-256 hashes representing the Merkle audit path...
def dumps(self): """Return representation of the path command.""" ret_str = [] for item in self._arg_list: if isinstance(item, TikZUserPath): ret_str.append(item.dumps()) elif isinstance(item, TikZCoordinate): ret_str.append(item.dumps()) ...
Return representation of the path command.
def transformer_tall_finetune_uniencdec(): """Fine-tune CNN/DM with a unidirectional encoder and decoder.""" hparams = transformer_tall() hparams.max_input_seq_length = 750 hparams.max_target_seq_length = 100 hparams.optimizer = "true_adam" hparams.learning_rate_schedule = ("linear_warmup*constant*cosdecay"...
Fine-tune CNN/DM with a unidirectional encoder and decoder.
def has_sources(self, extension=None): """Return `True` if this target owns sources; optionally of the given `extension`. :API: public :param string extension: Optional suffix of filenames to test for. :return: `True` if the target contains sources that match the optional extension suffix. :rtype:...
Return `True` if this target owns sources; optionally of the given `extension`. :API: public :param string extension: Optional suffix of filenames to test for. :return: `True` if the target contains sources that match the optional extension suffix. :rtype: bool
def get_probmodel_data(model): """ Returns the model_data based on the given model. Parameters ---------- model: BayesianModel instance Model to write Return ------ model_data: dict dictionary containing model data of the given model. Examples -------- >>> ...
Returns the model_data based on the given model. Parameters ---------- model: BayesianModel instance Model to write Return ------ model_data: dict dictionary containing model data of the given model. Examples -------- >>> model_data = pgmpy.readwrite.get_model_data...
def _merge_tops_merge_all(self, tops): ''' Merge the top files into a single dictionary ''' def _read_tgt(tgt): match_type = None states = [] for item in tgt: if isinstance(item, dict): match_type = item ...
Merge the top files into a single dictionary
def auto_discover_board(self, verbose): """ This method will allow up to 30 seconds for discovery (communicating with) an Arduino board and then will determine a pin configuration table for the board. :return: True if board is successfully discovered or False upon timeout """ ...
This method will allow up to 30 seconds for discovery (communicating with) an Arduino board and then will determine a pin configuration table for the board. :return: True if board is successfully discovered or False upon timeout
def _cleanup_temp_dir(self, base_dir): """Delete given temporary directory and all its contents.""" if self._should_cleanup_temp_dir: logging.debug('Cleaning up temporary directory %s.', base_dir) if self._user is None: util.rmtree(base_dir, onerror=util.log_rmtre...
Delete given temporary directory and all its contents.
def available_phone_numbers(self): """ Access the available_phone_numbers :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList """ if se...
Access the available_phone_numbers :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList
def load_stock_quantity(self, symbol: str) -> Decimal(0): """ retrieves stock quantity """ book = self.get_gc_book() collection = SecuritiesAggregate(book) sec = collection.get_aggregate_for_symbol(symbol) quantity = sec.get_quantity() return quantity
retrieves stock quantity
def _update_alpha(self, event=None): """Update display after a change in the alpha spinbox.""" a = self.alpha.get() hexa = self.hexa.get() hexa = hexa[:7] + ("%2.2x" % a).upper() self.hexa.delete(0, 'end') self.hexa.insert(0, hexa) self.alphabar.set(a) sel...
Update display after a change in the alpha spinbox.
def _enable_read_access(self): """! @brief Ensure flash is accessible by initing the algo for verify. Not all flash memories are always accessible. For instance, external QSPI. Initing the flash algo for the VERIFY operation is the canonical way to ensure that the flash is memor...
! @brief Ensure flash is accessible by initing the algo for verify. Not all flash memories are always accessible. For instance, external QSPI. Initing the flash algo for the VERIFY operation is the canonical way to ensure that the flash is memory mapped and accessible.
async def process_check_ins(self): """ finalize the check in phase |methcoro| Warning: |unstable| Note: |from_api| This should be invoked after a tournament's check-in window closes before the tournament is started. 1. Marks participants who have no...
finalize the check in phase |methcoro| Warning: |unstable| Note: |from_api| This should be invoked after a tournament's check-in window closes before the tournament is started. 1. Marks participants who have not checked in as inactive. 2. Moves ...
def generate_row_keys(self): """ Method for generating key features at serving time or prediction time :param data: Pass in the data that is necessary for generating the keys Example : Feature : User warehouse searches and conversions Keys will be of the form 'us...
Method for generating key features at serving time or prediction time :param data: Pass in the data that is necessary for generating the keys Example : Feature : User warehouse searches and conversions Keys will be of the form 'user_id#warehouse_id#searches=23811676#3' ...
def launch_external_file(filename: str, raise_if_fails: bool = False) -> None: """ Launches a file using the operating system's standard launcher. Args: filename: file to launch raise_if_fails: raise any exceptions from ``subprocess.call(["xdg-open", filename])`` (Linux) ...
Launches a file using the operating system's standard launcher. Args: filename: file to launch raise_if_fails: raise any exceptions from ``subprocess.call(["xdg-open", filename])`` (Linux) or ``os.startfile(filename)`` (otherwise)? If not, exceptions are suppress...
def add_postprocessor(postproc): """ Define a postprocessor to run after the function is executed, when running in console script mode. :param postproc: The callable, which will be passed the Namespace object generated by argparse and the return result of the f...
Define a postprocessor to run after the function is executed, when running in console script mode. :param postproc: The callable, which will be passed the Namespace object generated by argparse and the return result of the function. The return result of the ...
def matchiter(r, s, flags=0): """ Yields contiguous MatchObjects of r in s. Raises ValueError if r eventually doesn't match contiguously. """ if isinstance(r, basestring): r = re.compile(r, flags) i = 0 while s: m = r.match(s) g = m and m.group(0) if not m or ...
Yields contiguous MatchObjects of r in s. Raises ValueError if r eventually doesn't match contiguously.
def _parse_connection_string(connstr): """ MSSQL style connection string parser Returns normalized dictionary of connection string parameters """ res = {} for item in connstr.split(';'): item = item.strip() if not item: continue key, value = item.split('=', 1...
MSSQL style connection string parser Returns normalized dictionary of connection string parameters
def _check_dhcp_server(self, vboxnet): """ Check if the DHCP server associated with a vboxnet is enabled. :param vboxnet: vboxnet name :returns: boolean """ properties = yield from self._execute("list", ["dhcpservers"]) flag_dhcp_server_found = False fo...
Check if the DHCP server associated with a vboxnet is enabled. :param vboxnet: vboxnet name :returns: boolean
def _posix_split_name(self, name): """Split a name longer than 100 chars into a prefix and a name part. """ prefix = name[:LENGTH_PREFIX + 1] while prefix and prefix[-1] != "/": prefix = prefix[:-1] name = name[len(prefix):] prefix = prefix[:-1] ...
Split a name longer than 100 chars into a prefix and a name part.
def _track_stack_pointers(self): """ For each instruction, track its stack pointer offset and stack base pointer offset. :return: None """ regs = {self.project.arch.sp_offset} if hasattr(self.project.arch, 'bp_offset') and self.project.arch.bp_offset is not None: ...
For each instruction, track its stack pointer offset and stack base pointer offset. :return: None
def results(self): """Return the value and optionally derivative and second order derivative""" if self.deriv == 0: return self.v, if self.deriv == 1: return self.v, self.d if self.deriv == 2: return self.v, self.d, self.dd
Return the value and optionally derivative and second order derivative
def _compile_pattern(pat, ignore_case=True): """Translate and compile a glob pattern to a regular expression matcher.""" if isinstance(pat, bytes): pat_str = pat.decode('ISO-8859-1') res_str = _translate_glob(pat_str) res = res_str.encode('ISO-8859-1') else: res = _translate_...
Translate and compile a glob pattern to a regular expression matcher.
def environ_setting(name, default=None, required=True): """ Fetch setting from the environment. The bahavior of the setting if it is not in environment is as follows: 1. If it is required and the default is None, raise Exception 2. If it is requried and a default exists, return default ...
Fetch setting from the environment. The bahavior of the setting if it is not in environment is as follows: 1. If it is required and the default is None, raise Exception 2. If it is requried and a default exists, return default 3. If it is not required and default is None, return None ...
def from_class(cls, target_class): """Create a FunctionDescriptor from a class. Args: cls: Current class which is required argument for classmethod. target_class: the python class used to create the function descriptor. Returns: The FunctionD...
Create a FunctionDescriptor from a class. Args: cls: Current class which is required argument for classmethod. target_class: the python class used to create the function descriptor. Returns: The FunctionDescriptor instance created according to the cl...
def get_edges_with_citations(self, citations: Iterable[Citation]) -> List[Edge]: """Get edges with one of the given citations.""" return self.session.query(Edge).join(Evidence).filter(Evidence.citation.in_(citations)).all()
Get edges with one of the given citations.
def Times(self, val): """ Returns a new point which is pointwise multiplied by val. """ return Point(self.x * val, self.y * val, self.z * val)
Returns a new point which is pointwise multiplied by val.
def stack_push(self, key, value): """Set a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeError: task._context_stack = context = {} if key not in context: context[key] = [...
Set a value in a task context stack
def wsgi(self, environ, start_response): """Implements the mapper's WSGI interface.""" request = Request(environ) ctx = Context(request) try: try: response = self(request, ctx) ctx._run_callbacks('finalize', (request, response)) ...
Implements the mapper's WSGI interface.
def contributors(self, sr, limit=None): """Login required. GETs list of contributors to subreddit ``sr``. Returns :class:`things.ListBlob` object. **NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit retu...
Login required. GETs list of contributors to subreddit ``sr``. Returns :class:`things.ListBlob` object. **NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each contributor, yo...
def STRH(self, params): """ STRH Ra, [Rb, Rc] STRH Ra, [Rb, #imm6_2] Store Ra into memory as a half word Ra, Rb, and Rc must be low registers """ Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) if self.is_immediate(Rc):...
STRH Ra, [Rb, Rc] STRH Ra, [Rb, #imm6_2] Store Ra into memory as a half word Ra, Rb, and Rc must be low registers
def set_values(self,x): """ Updates self.theta parameter. No returns values""" x = numpy.atleast_2d(x) x = x.real # ahem C_inv = self.__C_inv__ theta = numpy.dot( x, C_inv ) self.theta = theta return theta
Updates self.theta parameter. No returns values
def ADC(cpu, dest, src): """ Adds with carry. Adds the destination operand (first operand), the source operand (second operand), and the carry (CF) flag and stores the result in the destination operand. The state of the CF flag represents a carry from a previous addition. When a...
Adds with carry. Adds the destination operand (first operand), the source operand (second operand), and the carry (CF) flag and stores the result in the destination operand. The state of the CF flag represents a carry from a previous addition. When an immediate value is used as an opera...
def show(self): """ Print with a pretty display the MapList object """ bytecode._Print("MAP_LIST SIZE", self.size) for i in self.map_item: if i.item != self: # FIXME this does not work for CodeItems! # as we do not have the method analy...
Print with a pretty display the MapList object
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and plugin not disabled if not self.stats or self.is_disable(): return ret # Build the s...
Return the dict to display in the curse interface.
def set_current_operation_progress(self, percent): """Internal method, not to be called externally. in percent of type int """ if not isinstance(percent, baseinteger): raise TypeError("percent can only be an instance of type baseinteger") self._call("setCurrentOpera...
Internal method, not to be called externally. in percent of type int
def delete_connection(self, **kwargs): """Remove a single connection to a provider for the specified user.""" conn = self.find_connection(**kwargs) if not conn: return False self.delete(conn) return True
Remove a single connection to a provider for the specified user.
def p_genvarlist(self, p): 'genvarlist : genvarlist COMMA genvar' p[0] = p[1] + (p[3],) p.set_lineno(0, p.lineno(1))
genvarlist : genvarlist COMMA genvar
def _compute_total_chunks(self, chunk_size): # type: (Descriptor, int) -> int """Compute total number of chunks for entity :param Descriptor self: this :param int chunk_size: chunk size :rtype: int :return: num chunks """ try: return int(math.c...
Compute total number of chunks for entity :param Descriptor self: this :param int chunk_size: chunk size :rtype: int :return: num chunks
def call_moses_detokenizer(workspace_dir: str, input_fname: str, output_fname: str, lang_code: Optional[str] = None): """ Call Moses detokenizer. :param workspace_dir: Workspace third-party directory where Moses tokenizer is checked out. :param input_fname: Path of tokenized i...
Call Moses detokenizer. :param workspace_dir: Workspace third-party directory where Moses tokenizer is checked out. :param input_fname: Path of tokenized input file, plain text or gzipped. :param output_fname: Path of tokenized output file, plain text. :param lang_code: Langua...
def convert_relational(relational): """Convert all inequalities to >=0 form. """ rel = relational.rel_op if rel in ['==', '>=', '>']: return relational.lhs-relational.rhs elif rel in ['<=', '<']: return relational.rhs-relational.lhs else: raise Exception("The relational o...
Convert all inequalities to >=0 form.
def window_iterator(data, width): """ Instead of iterating element by element, get a number of elements at each iteration step. :param data: data to iterate on :param width: maximum number of elements to get in each iteration step :return: """ start = 0 while start < len(data): y...
Instead of iterating element by element, get a number of elements at each iteration step. :param data: data to iterate on :param width: maximum number of elements to get in each iteration step :return:
def _paged_api_call(self, func, kwargs, item_type='photo'): """ Takes a Flickr API function object and dict of keyword args and calls the API call repeatedly with an incrementing page value until all contents are exhausted. Flickr seems to limit to about 500 items. """ pa...
Takes a Flickr API function object and dict of keyword args and calls the API call repeatedly with an incrementing page value until all contents are exhausted. Flickr seems to limit to about 500 items.
def get_agile_board(self, board_id): """ Get agile board info by id :param board_id: :return: """ url = 'rest/agile/1.0/board/{}'.format(str(board_id)) return self.get(url)
Get agile board info by id :param board_id: :return:
def add_boundary_regions(regions=None, faces=['front', 'back', 'left', 'right', 'top', 'bottom']): r""" Given an image partitioned into regions, pads specified faces with new regions Parameters ---------- regions : ND-array An image of the p...
r""" Given an image partitioned into regions, pads specified faces with new regions Parameters ---------- regions : ND-array An image of the pore space partitioned into regions and labeled faces : list of strings The faces of ``regions`` which should have boundaries added. Opti...
def clone(self, instance): ''' Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass. ''' metaclass = get_metaclass(instance) metaclass = self.find_metaclass(metaclass.ki...
Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass.
def channels(self): """List[:class:`abc.GuildChannel`]: Returns the channels that are under this category. These are sorted by the official Discord UI, which places voice channels below the text channels. """ def comparator(channel): return (not isinstance(channel, TextChann...
List[:class:`abc.GuildChannel`]: Returns the channels that are under this category. These are sorted by the official Discord UI, which places voice channels below the text channels.
def parse_dossier_data(data, ep): """Parse data from parltarck dossier export (1 dossier) Update dossier if it existed before, this function goal is to import and update a dossier, not to import all parltrack data """ changed = False doc_changed = False ref = data['procedure']['reference'] ...
Parse data from parltarck dossier export (1 dossier) Update dossier if it existed before, this function goal is to import and update a dossier, not to import all parltrack data
def _compute_a22_factor(self, imt): """ Compute and return the a22 factor, equation 20, page 80. """ if imt.name == 'PGV': return 0.0 period = imt.period if period < 2.0: return 0.0 else: return 0.0625 * (period - 2.0)
Compute and return the a22 factor, equation 20, page 80.
def precompile_python_code(context: Context): """ Pre-compiles python modules """ from compileall import compile_dir kwargs = {} if context.verbosity < 2: kwargs['quiet'] = True compile_dir(context.app.django_app_name, **kwargs)
Pre-compiles python modules
def try_greyscale(pixels, alpha=False, dirty_alpha=True): """ Check if flatboxed RGB `pixels` could be converted to greyscale If could - return iterator with greyscale pixels, otherwise return `False` constant """ planes = 3 + bool(alpha) res = list() apix = list() for row in pixels...
Check if flatboxed RGB `pixels` could be converted to greyscale If could - return iterator with greyscale pixels, otherwise return `False` constant
def get_gan_loss(self, true_frames, gen_frames, name): """Get the discriminator + generator loss at every step. This performs an 1:1 update of the discriminator and generator at every step. Args: true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C) Assumed to be g...
Get the discriminator + generator loss at every step. This performs an 1:1 update of the discriminator and generator at every step. Args: true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C) Assumed to be ground truth. gen_frames: 5-D Tensor of shape (num_steps,...
def read_lock(self): """Context manager that grants a read lock. Will wait until no active or pending writers. Raises a ``RuntimeError`` if a pending writer tries to acquire a read lock. """ me = self._current_thread() if me in self._pending_writers: ...
Context manager that grants a read lock. Will wait until no active or pending writers. Raises a ``RuntimeError`` if a pending writer tries to acquire a read lock.
def locate_point(nodes, x_val, y_val): r"""Find the parameter corresponding to a point on a curve. .. note:: This assumes that the curve :math:`B(s, t)` defined by ``nodes`` lives in :math:`\mathbf{R}^2`. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. ...
r"""Find the parameter corresponding to a point on a curve. .. note:: This assumes that the curve :math:`B(s, t)` defined by ``nodes`` lives in :math:`\mathbf{R}^2`. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. x_val (float): The :math:`x`-coordinate ...
def _get_version_for_class_from_state(state, klass): """ retrieves the version of the current klass from the state mapping from old locations to new ones. """ # klass may have been renamed, so we have to look this up in the class rename registry. names = [_importable_name(klass)] # looku...
retrieves the version of the current klass from the state mapping from old locations to new ones.
def get_device_status(host, services=None, zconf=None): """ :param host: Hostname or ip to fetch status from :type host: str :return: The device status as a named tuple. :rtype: pychromecast.dial.DeviceStatus or None """ try: status = _get_status( host, services, zconf, ...
:param host: Hostname or ip to fetch status from :type host: str :return: The device status as a named tuple. :rtype: pychromecast.dial.DeviceStatus or None
def _create_app(self): """ Method for creating a new Application Template. USAGE: cloud-harness create <dir_name> [--destination=<path>] """ template_path = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), self.TEMPLATE_FOLDER, self.TEMPLATE_...
Method for creating a new Application Template. USAGE: cloud-harness create <dir_name> [--destination=<path>]
def getValue(self): ''' Returns str(option_string * DropDown Value) e.g. -vvvvv ''' dropdown_value = self.widget.GetValue() if not str(dropdown_value).isdigit(): return '' arg = str(self.option_string).replace('-', '') repeated_args = arg * int(dropdown_value) ret...
Returns str(option_string * DropDown Value) e.g. -vvvvv
def repr_imgs(imgs): """Printing of img or imgs""" if isinstance(imgs, string_types): return imgs if isinstance(imgs, collections.Iterable): return '[{}]'.format(', '.join(repr_imgs(img) for img in imgs)) # try get_filename try: filename = imgs.get_filename() if fil...
Printing of img or imgs
def _add_games_to_schedule(self, schedule): """ Add game information to list of games. Create a Game instance for the given game in the schedule and add it to the list of games the team has or will play during the season. Parameters ---------- schedule : PyQuery...
Add game information to list of games. Create a Game instance for the given game in the schedule and add it to the list of games the team has or will play during the season. Parameters ---------- schedule : PyQuery object A PyQuery object pertaining to a team's sche...
def main(): ''' Simple examples ''' args = parse_arguments() if args.askpass: password = getpass.getpass("Password: ") else: password = None if args.asksudopass: sudo = True sudo_pass = getpass.getpass("Sudo password[default ssh password]: ") if len(s...
Simple examples
def where(self, fieldname, value, negate=False): """ Returns a new DataTable with rows only where the value at `fieldname` == `value`. """ if negate: return self.mask([elem != value for elem in self[fieldname]]) else: ...
Returns a new DataTable with rows only where the value at `fieldname` == `value`.
def modify_replication_group(ReplicationGroupId=None, ReplicationGroupDescription=None, PrimaryClusterId=None, SnapshottingClusterId=None, AutomaticFailoverEnabled=None, CacheSecurityGroupNames=None, SecurityGroupIds=None, PreferredMaintenanceWindow=None, NotificationTopicArn=None, CacheParameterGroupName=None, Notific...
Modifies the settings for a replication group. See also: AWS API Documentation :example: response = client.modify_replication_group( ReplicationGroupId='string', ReplicationGroupDescription='string', PrimaryClusterId='string', SnapshottingClusterId='string', Aut...
def parse(self, gff_file, strict=False): """Parse the gff file into the following data structures: * lines(list of line_data(dict)) - line_index(int): the index in lines - line_raw(str) - line_type(str in ['feature', 'directive', 'comment', 'blank', 'unknown']) ...
Parse the gff file into the following data structures: * lines(list of line_data(dict)) - line_index(int): the index in lines - line_raw(str) - line_type(str in ['feature', 'directive', 'comment', 'blank', 'unknown']) - line_errors(list of str): a list of error m...
def _cleanup_and_die(data): """ cleanup func for step 1 """ tmpfiles = glob.glob(os.path.join(data.dirs.fastqs, "tmp_*_R*.fastq")) tmpfiles += glob.glob(os.path.join(data.dirs.fastqs, "tmp_*.p")) for tmpf in tmpfiles: os.remove(tmpf)
cleanup func for step 1
def delete(self, object_id): """ Delete an object by its id :param object_id: the objects id. :return: the deleted object :raises: :class: NoResultFound when the object could not be found """ obj = self.session.query(self.cls).filter_by(id=object_id).one() ...
Delete an object by its id :param object_id: the objects id. :return: the deleted object :raises: :class: NoResultFound when the object could not be found
def calculate_bins(array, _=None, *args, **kwargs) -> BinningBase: """Find optimal binning from arguments. Parameters ---------- array: arraylike Data from which the bins should be decided (sometimes used, sometimes not) _: int or str or Callable or arraylike or Iterable or BinningBase ...
Find optimal binning from arguments. Parameters ---------- array: arraylike Data from which the bins should be decided (sometimes used, sometimes not) _: int or str or Callable or arraylike or Iterable or BinningBase To-be-guessed parameter that specifies what kind of binning should be ...
def mav_to_gpx(infilename, outfilename): '''convert a mavlink log file to a GPX file''' mlog = mavutil.mavlink_connection(infilename) outf = open(outfilename, mode='w') def process_packet(timestamp, lat, lon, alt, hdg, v): t = time.localtime(timestamp) outf.write('''<trkpt lat="%s" lon...
convert a mavlink log file to a GPX file
def _run_config_cmds(self, commands, server): """Execute/sends a CAPI (Command API) command to EOS. In this method, list of commands is appended with prefix and postfix commands - to make is understandble by EOS. :param commands : List of command to be executed on EOS. :param s...
Execute/sends a CAPI (Command API) command to EOS. In this method, list of commands is appended with prefix and postfix commands - to make is understandble by EOS. :param commands : List of command to be executed on EOS. :param server: Server endpoint on the Arista switch to be configu...
def plugin(module, *args, **kwargs): """ Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): ...
Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): return {} return MyEx...