code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def format_exp_floats(decimals): """ sometimes the exp. column can be too large """ threshold = 10 ** 5 return ( lambda n: "{:.{prec}e}".format(n, prec=decimals) if n > threshold else "{:4.{prec}f}".format(n, prec=decimals) )
sometimes the exp. column can be too large
async def execute(self, coro, name, user, info=None): ''' Create a synapse task from the given coroutine. ''' task = self.schedCoro(coro) return await s_task.Task.anit(self, task, name, user, info=info)
Create a synapse task from the given coroutine.
def pinch(self, direction='in', percent=0.6, duration=2.0, dead_zone=0.1): """ Squeezing or expanding 2 fingers on this UI with given motion range and duration. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding ...
Squeezing or expanding 2 fingers on this UI with given motion range and duration. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding percent (:py:obj:`float`): squeezing range from or expanding range to of the bounds of the U...
def on_log(self): # type: () -> Callable """Decorate a callback function to handle MQTT logging. **Example Usage:** :: @mqtt.on_log() def handle_logging(client, userdata, level, buf): print(client, userdata, level, buf) """ def d...
Decorate a callback function to handle MQTT logging. **Example Usage:** :: @mqtt.on_log() def handle_logging(client, userdata, level, buf): print(client, userdata, level, buf)
def fixminimized(self, alphabet): """ After pyfst minimization, all unused arcs are removed, and all sink states are removed. However this may break compatibility. Args: alphabet (list): The input alphabet Returns: None """ ...
After pyfst minimization, all unused arcs are removed, and all sink states are removed. However this may break compatibility. Args: alphabet (list): The input alphabet Returns: None
def predict_proba(self, time): """Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, s...
Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, shape = (n_samples,) Probabilit...
def classify(self, token_type, value, lineno, column, line): """Find the label for a token.""" if token_type == self.grammar.KEYWORD_TOKEN: label_index = self.grammar.keyword_ids.get(value, -1) if label_index != -1: return label_index label_index = self.gr...
Find the label for a token.
def phi_vector(self): """property decorated method to get a vector of L2 norm (phi) for the realizations. The ObservationEnsemble.pst.weights can be updated prior to calling this method to evaluate new weighting strategies Return ------ pandas.DataFrame : pandas.DataFra...
property decorated method to get a vector of L2 norm (phi) for the realizations. The ObservationEnsemble.pst.weights can be updated prior to calling this method to evaluate new weighting strategies Return ------ pandas.DataFrame : pandas.DataFrame
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the IQR normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_IQR.png **Range:** 0 ≤ NRMSE < inf. **Notes:*...
Compute the IQR normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_IQR.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the interquartile range of the observed time series (x). Normalizing allows comparison between dat...
def _updatePoolingState(self, activeColWithPredictedInput, fractionUnpredicted): """ This function updates the pooling state of TP cells. A cell will stop pooling if: (1) It hasn't received any predicted input in the last self._poolingLife steps or (2) the overall fraction of unpredicted inp...
This function updates the pooling state of TP cells. A cell will stop pooling if: (1) It hasn't received any predicted input in the last self._poolingLife steps or (2) the overall fraction of unpredicted input to the TP is above _poolingThreshUnpredicted
def _init_vocab(self, token_generator, add_reserved_tokens=True): """Initialize vocabulary with tokens from token_generator.""" self._id_to_token = {} non_reserved_start_index = 0 if add_reserved_tokens: self._id_to_token.update(enumerate(RESERVED_TOKENS)) non_reserved_start_index = len(RE...
Initialize vocabulary with tokens from token_generator.
def startTicker(self, reqId, contract, tickType): """ Start a tick request that has the reqId associated with the contract. Return the ticker. """ ticker = self.tickers.get(id(contract)) if not ticker: ticker = Ticker( contract=contract, ticks=...
Start a tick request that has the reqId associated with the contract. Return the ticker.
def MakePmfFromList(t, name=''): """Makes a PMF from an unsorted sequence of values. Args: t: sequence of numbers name: string name for this PMF Returns: Pmf object """ hist = MakeHistFromList(t) d = hist.GetDict() pmf = Pmf(d, name) pmf.Normalize() return p...
Makes a PMF from an unsorted sequence of values. Args: t: sequence of numbers name: string name for this PMF Returns: Pmf object
def to_geopandas(raster, **kwargs): """ Convert GeoRaster to GeoPandas DataFrame, which can be easily exported to other types of files and used to do other types of operations. The DataFrame has the geometry (Polygon), row, col, value, x, and y values for each cell Usage: df = gr.to_geopanda...
Convert GeoRaster to GeoPandas DataFrame, which can be easily exported to other types of files and used to do other types of operations. The DataFrame has the geometry (Polygon), row, col, value, x, and y values for each cell Usage: df = gr.to_geopandas(raster)
async def ensure_closed(self): """Send quit command and then close socket connection""" if self._writer is None: # connection has been closed return send_data = struct.pack('<i', 1) + int2byte(COMMAND.COM_QUIT) self._writer.write(send_data) await self._wri...
Send quit command and then close socket connection
def add_missing_components(network): # Munich """Add missing transformer at Heizkraftwerk Nord in Munich and missing transformer in Stuttgart Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network...
Add missing transformer at Heizkraftwerk Nord in Munich and missing transformer in Stuttgart Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
def get_attr_text(self): """Get html attr text to render in template""" return ' '.join([ '{}="{}"'.format(key, value) for key, value in self.attr.items() ])
Get html attr text to render in template
def get_lldp_neighbor_detail_output_has_more(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubElement(get_lldp_neighbor_detail, "out...
Auto Generated Code
def _get_directory_stash(self, path): """Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir.""" try: save_dir = AdjacentTempDirectory(path) save_dir.create() except ...
Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir.
def get_dict_for_class(self, class_name, state=None, base_name='View'): """The style dict for a given class and state. This collects the style attributes from parent classes and the class of the given object and gives precedence to values thereof to the children. The state attr...
The style dict for a given class and state. This collects the style attributes from parent classes and the class of the given object and gives precedence to values thereof to the children. The state attribute of the view instance is taken as the current state if state is None. ...
def hashes(self): """Return set of hashes uses in this resource_list.""" hashes = set() if (self.resources is not None): for resource in self: if (resource.md5 is not None): hashes.add('md5') if (resource.sha1 is not None): ...
Return set of hashes uses in this resource_list.
def _get_local_ip(self): """Try to determine the local IP address of the machine.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Use Google Public DNS server to determine own IP sock.connect(('8.8.8.8', 80)) return sock.getsockname()[0...
Try to determine the local IP address of the machine.
def ss(inlist): """ Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist) """ ss = 0 for item in inlist: ss = ss + item * item return ss
Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist)
def voronoi(script, region_num=10, overlap=False): """Voronoi Atlas parameterization """ filter_xml = ''.join([ ' <filter name="Parametrization: Voronoi Atlas">\n', ' <Param name="regionNum"', 'value="%d"' % region_num, 'description="Approx. Region Num"', 'type="...
Voronoi Atlas parameterization
def write_member(self, data): """Writes the given data as one gzip member. The data can be a string, an iterator that gives strings or a file-like object. """ if isinstance(data, basestring): self.write(data) else: for text in data: ...
Writes the given data as one gzip member. The data can be a string, an iterator that gives strings or a file-like object.
def make_gp_funs(cov_func, num_cov_params): """Functions that perform Gaussian process regression. cov_func has signature (cov_params, x, x')""" def unpack_kernel_params(params): mean = params[0] cov_params = params[2:] noise_scale = np.exp(params[1]) + 0.0001 ret...
Functions that perform Gaussian process regression. cov_func has signature (cov_params, x, x')
async def fetch_neighbourhood(lat: float, long: float) -> Optional[dict]: """ Gets the neighbourhood from the fetch that is associated with the given postcode. :return: A neighbourhood object parsed from the fetch. :raise ApiError: When there was an error connecting to the API. """ lookup_url =...
Gets the neighbourhood from the fetch that is associated with the given postcode. :return: A neighbourhood object parsed from the fetch. :raise ApiError: When there was an error connecting to the API.
def newDocNodeEatName(self, ns, name, content): """Creation of a new node element within a document. @ns and @content are optional (None). NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities references, but XML special chars need to be escaped first by using...
Creation of a new node element within a document. @ns and @content are optional (None). NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities references, but XML special chars need to be escaped first by using xmlEncodeEntitiesReentrant(). Use xmlNewDocRawNo...
def position(self, chromosome, position, exact=False): """ Shortcut to do a single position filter on genomic datasets. """ return self._clone( filters=[GenomicFilter(chromosome, position, exact=exact)])
Shortcut to do a single position filter on genomic datasets.
def oftype(self, typ): '''Return a generator of formatters codes of type typ''' for key, val in self.items(): if val.type == typ: yield key
Return a generator of formatters codes of type typ
def url_join(url, path): """ url version of os.path.join """ p = six.moves.urllib.parse.urlparse(url) t = None if p.path and p.path[-1] == '/': if path and path[0] == '/': path = path[1:] t = ''.join([p.path, path]) else: t = ('' if path and path[0] == '/' el...
url version of os.path.join
def add_arguments(self, parser): """Adds the unlock command arguments to the parser. Args: self (UnlockCommand): the ``UnlockCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None`` """ parser.add_ar...
Adds the unlock command arguments to the parser. Args: self (UnlockCommand): the ``UnlockCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None``
def plan_to_assignment(plan): """Convert the plan to the format used by cluster-topology.""" assignment = {} for elem in plan['partitions']: assignment[ (elem['topic'], elem['partition']) ] = elem['replicas'] return assignment
Convert the plan to the format used by cluster-topology.
def get_imagery(cls, lat, lon, date=None, dim=None, cloud_score=False): """ Returns satellite image Args: lat: latitude float lon: longitude float date: date instance of available date from `get_assets` dim: width and height of image in degrees as...
Returns satellite image Args: lat: latitude float lon: longitude float date: date instance of available date from `get_assets` dim: width and height of image in degrees as float cloud_score: boolean to calculate the percentage of the image covered by ...
def write_artifacts_metadata(self): """Write out a JSON file with all built targets artifact metadata, if such output file is specified.""" if self.conf.artifacts_metadata_file: logger.info('Writing artifacts metadata to file "%s"', self.conf.artifacts_meta...
Write out a JSON file with all built targets artifact metadata, if such output file is specified.
def get_rva_from_offset(self, offset): """Get the RVA corresponding to this file offset. """ s = self.get_section_by_offset(offset) if not s: if self.sections: lowest_rva = min( [ adjust_SectionAlignment( s.VirtualAddress, self.OPTIONAL_H...
Get the RVA corresponding to this file offset.
def mixin_class(target, cls): """Mix cls content in target.""" for name, field in getmembers(cls): Mixin.mixin(target, field, name)
Mix cls content in target.
def to_json_data(self): """ Returns ------- A dictionary of serialized data. """ # create data d = collections.OrderedDict((t.get_ref(), t.to_json_data()) for t in self._tables.values()) d["_comment"] = self._comment d.move_to_end("_comment", last=...
Returns ------- A dictionary of serialized data.
def images_create(self, filename): """Create and image file or image group object from the given file. The type of the created database object is determined by the suffix of the given file. An ValueError exception is thrown if the file has an unknown suffix. Raises ValueError if...
Create and image file or image group object from the given file. The type of the created database object is determined by the suffix of the given file. An ValueError exception is thrown if the file has an unknown suffix. Raises ValueError if invalid file is given. Parameters ...
def default(restart_cb=None, restart_func=None, close_fds=True): '''Sets up lazarus in default mode. See the :py:func:`custom` function for a more powerful mode of use. The default mode of lazarus is to watch all modules rooted at ``PYTHONPATH`` for changes and restart when they take place. Keywo...
Sets up lazarus in default mode. See the :py:func:`custom` function for a more powerful mode of use. The default mode of lazarus is to watch all modules rooted at ``PYTHONPATH`` for changes and restart when they take place. Keyword arguments: restart_cb -- Callback invoked prior to restartin...
def next_id(self): """Next available positive integer id value in this story XML document. The value is determined by incrementing the maximum existing id value. Gaps in the existing id sequence are not filled. The id attribute value is unique in the document, without regard to the elem...
Next available positive integer id value in this story XML document. The value is determined by incrementing the maximum existing id value. Gaps in the existing id sequence are not filled. The id attribute value is unique in the document, without regard to the element type it appears on.
def register_arrays(self, arrays): """ Register arrays using a list of dictionaries defining the arrays. The list should itself contain dictionaries. i.e. .. code-block:: python D = [{ 'name':'uvw', 'shape':(3,'ntime','nbl'),'dtype':np.float32 }, { 'name':'...
Register arrays using a list of dictionaries defining the arrays. The list should itself contain dictionaries. i.e. .. code-block:: python D = [{ 'name':'uvw', 'shape':(3,'ntime','nbl'),'dtype':np.float32 }, { 'name':'lm', 'shape':(2,'nsrc'),'dtype':np.float32 }] ...
def indirect_font(font, fonts, text): """ Check input font for indirect modes. :param font: input font :type font : str :param fonts: fonts list :type fonts : list :param text: input text :type text:str :return: font as str """ if font == "rnd-small" or font == "random-small...
Check input font for indirect modes. :param font: input font :type font : str :param fonts: fonts list :type fonts : list :param text: input text :type text:str :return: font as str
def _init_metadata(self): """stub""" self._choice_ids_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'choice_ids'), 'element_label': 'response set', 'ins...
stub
def get_covariance(datargs, outargs, vargs, datvar, outvar): """ Get covariance matrix. :param datargs: data arguments :param outargs: output arguments :param vargs: variable arguments :param datvar: variance of data arguments :param outvar: variance of output ar...
Get covariance matrix. :param datargs: data arguments :param outargs: output arguments :param vargs: variable arguments :param datvar: variance of data arguments :param outvar: variance of output arguments :return: covariance
def _has_not_qual(ntd): """Return True if the qualifiers contain a 'NOT'""" for qual in ntd.Qualifier: if 'not' in qual: return True if 'NOT' in qual: return True return False
Return True if the qualifiers contain a 'NOT
def vertical_horizontal_filter(data, period): """ Vertical Horizontal Filter. Formula: ABS(pHIGH - pLOW) / SUM(ABS(Pi - Pi-1)) """ catch_errors.check_for_period_error(data, period) vhf = [abs(np.max(data[idx+1-period:idx+1]) - np.min(data[idx+1-period:idx+1])) / sum([ab...
Vertical Horizontal Filter. Formula: ABS(pHIGH - pLOW) / SUM(ABS(Pi - Pi-1))
def query(self, where="1=1", out_fields="*", timeFilter=None, geometryFilter=None, returnGeometry=True, returnIDsOnly=False, returnCountOnly=False, returnFeatureClass=False, returnDistinctValues...
queries a feature service based on a sql statement Inputs: where - the selection sql statement out_fields - the attribute fields to return timeFilter - a TimeFilter object where either the start time or start and end time are defined t...
def pic_inflow_v2(self): """Update the inlet link sequences. Required inlet sequences: |dam_inlets.Q| |dam_inlets.S| |dam_inlets.R| Calculated flux sequence: |Inflow| Basic equation: :math:`Inflow = Q + S + R` """ flu = self.sequences.fluxes.fastaccess inl = ...
Update the inlet link sequences. Required inlet sequences: |dam_inlets.Q| |dam_inlets.S| |dam_inlets.R| Calculated flux sequence: |Inflow| Basic equation: :math:`Inflow = Q + S + R`
def __import_vars(self, env_file): """Actual importing function.""" with open(env_file, "r") as f: # pylint: disable=invalid-name for line in f: try: line = line.lstrip() if line.startswith('export'): line = lin...
Actual importing function.
def attributive(adjective, gender=MALE, role=SUBJECT, article=None): """ For a predicative adjective, returns the attributive form (lowercase). In German, the attributive is formed with -e, -em, -en, -er or -es, depending on gender (masculine, feminine, neuter or plural) and role (nominative...
For a predicative adjective, returns the attributive form (lowercase). In German, the attributive is formed with -e, -em, -en, -er or -es, depending on gender (masculine, feminine, neuter or plural) and role (nominative, accusative, dative, genitive).
def append_summary_to_module_docstring(module): """ Change the ``module.__doc__`` docstring to include a summary table based on its contents as declared on ``module.__all__``. """ pairs = [(name, getattr(module, name)) for name in module.__all__] kws = dict(key_header="Name", summary_type="module contents")...
Change the ``module.__doc__`` docstring to include a summary table based on its contents as declared on ``module.__all__``.
def filter_parts(self, predicate='', exclude=True): """ Filter the data by partition string. A partition string looks like `pt1=1,pt2=2/pt1=2,pt2=1`, where comma (,) denotes 'and', while (/) denotes 'or'. :param str|Partition predicate: predicate string of partition filter :para...
Filter the data by partition string. A partition string looks like `pt1=1,pt2=2/pt1=2,pt2=1`, where comma (,) denotes 'and', while (/) denotes 'or'. :param str|Partition predicate: predicate string of partition filter :param bool exclude: True if you want to exclude partition fields, otherwise ...
def transform(self, y): """ Transform features per specified math function. :param y: :return: """ if self.transform_type == 'log': return np.log(y) elif self.transform_type == 'exp': return np.exp(y) elif self.transform_type == 'sq...
Transform features per specified math function. :param y: :return:
def long_fname_format(fmt_str, fmt_dict, hashable_keys=[], max_len=64, hashlen=16, ABS_MAX_LEN=255, hack27=False): r""" DEPRICATE Formats a string and hashes certain parts if the resulting string becomes too long. Used for making filenames fit onto disk. Args: fmt_str...
r""" DEPRICATE Formats a string and hashes certain parts if the resulting string becomes too long. Used for making filenames fit onto disk. Args: fmt_str (str): format of fname fmt_dict (str): dict to format fname with hashable_keys (list): list of dict keys you are willing to ...
def commercial_domains(): # type: () -> set """ Return list of commercial email domains, which means: - domain is not public - domain is not university - it is not personal (more than 1 person using this domain) >>> "google.com" in commercial_domains() True >>> "microsoft.com" in commerc...
Return list of commercial email domains, which means: - domain is not public - domain is not university - it is not personal (more than 1 person using this domain) >>> "google.com" in commercial_domains() True >>> "microsoft.com" in commercial_domains() True >>> "isri.cs.cmu.edu" in comm...
def _get_function_wrapper( self, func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]] ) -> typing.Callable[..., typing.Any]: """Here should be constructed and returned real decorator. :param func: Wrapped function :type func: typing.Callable[..., typi...
Here should be constructed and returned real decorator. :param func: Wrapped function :type func: typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]] :rtype: typing.Callable
def render_item(self, all_posts): """ Renders the Post as HTML using the template specified in :attr:`html_template_path`. :param all_posts: An optional :class:`PostCollection` containing all of the posts in the site. :return: The rendered HTML as a string. """ index = a...
Renders the Post as HTML using the template specified in :attr:`html_template_path`. :param all_posts: An optional :class:`PostCollection` containing all of the posts in the site. :return: The rendered HTML as a string.
def removeTab(self, index): """ Removes tab at index ``index``. This method will emits tab_closed for the removed tab. :param index: index of the tab to remove. """ widget = self.widget(index) try: self._widgets.remove(widget) except ValueErr...
Removes tab at index ``index``. This method will emits tab_closed for the removed tab. :param index: index of the tab to remove.
def on_exception(wait_gen, exception, max_tries=None, max_time=None, jitter=full_jitter, giveup=lambda e: False, on_success=None, on_backoff=None, on_giveup=None, logg...
Returns decorator for backoff and retry triggered by exception. Args: wait_gen: A generator yielding successive wait times in seconds. exception: An exception type (or tuple of types) which triggers backoff. max_tries: The maximum number of attempts to make before gi...
def GetParserFromFilename(self, path): """Returns the appropriate parser class from the filename.""" # Find the configuration parser. handler_name = path.split("://")[0] for parser_cls in itervalues(GRRConfigParser.classes): if parser_cls.name == handler_name: return parser_cls # Hand...
Returns the appropriate parser class from the filename.
def iat(x, maxlag=None): """Calculate the integrated autocorrelation time (IAT), given the trace from a Stochastic.""" if not maxlag: # Calculate maximum lag to which autocorrelation is calculated maxlag = _find_max_lag(x) acr = [autocorr(x, lag) for lag in range(1, maxlag + 1)] # Cal...
Calculate the integrated autocorrelation time (IAT), given the trace from a Stochastic.
def put(self, destination): """ Copy the referenced directory to this path Note: This ignores anything not in the desired directory, given by ``self.dirname``. Args: destination (str): path to put this directory (which must NOT already exist) References: ...
Copy the referenced directory to this path Note: This ignores anything not in the desired directory, given by ``self.dirname``. Args: destination (str): path to put this directory (which must NOT already exist) References: https://stackoverflow.com/a/826108...
def read(self, stream): """Reads the topology from a stream or file.""" def read_it(stream): bytes = stream.read() transportIn = TMemoryBuffer(bytes) protocolIn = TBinaryProtocol.TBinaryProtocol(transportIn) topology = StormTopology() topology....
Reads the topology from a stream or file.
def get_version(self, diff_to_increase_ratio): """Gets version :param diff_to_increase_ratio: Ratio to convert number of changes into :return: Version of this code, based on commits diffs """ diffs = self.get_diff_amounts() version = Version() for diff in diffs:...
Gets version :param diff_to_increase_ratio: Ratio to convert number of changes into :return: Version of this code, based on commits diffs
def reparentUnions(self): ''' Helper method for :func:`~exhale.graph.ExhaleRoot.reparentAll`. Namespaces and classes should have the unions defined in them to be in the child list of itself rather than floating around. Union nodes that are reparented (e.g. a union defined in a ...
Helper method for :func:`~exhale.graph.ExhaleRoot.reparentAll`. Namespaces and classes should have the unions defined in them to be in the child list of itself rather than floating around. Union nodes that are reparented (e.g. a union defined in a class) will be removed from the list ``self.un...
def get(self, address): """ Get a loopback address by it's address. Find all loopback addresses by iterating at either the node level or the engine:: loopback = engine.loopback_interface.get('127.0.0.10') :param str address: ip address of loopback :r...
Get a loopback address by it's address. Find all loopback addresses by iterating at either the node level or the engine:: loopback = engine.loopback_interface.get('127.0.0.10') :param str address: ip address of loopback :raises InterfaceNotFound: invalid interface s...
def _ImportHookBySuffix( name, globals=None, locals=None, fromlist=None, level=None): """Callback when an import statement is executed by the Python interpreter. Argument names have to exactly match those of __import__. Otherwise calls to __import__ that use keyword syntax will fail: __import('a', fromlist=[...
Callback when an import statement is executed by the Python interpreter. Argument names have to exactly match those of __import__. Otherwise calls to __import__ that use keyword syntax will fail: __import('a', fromlist=[]).
def modify_column_if_table_exists(self, tablename: str, fieldname: str, newdef: str) -> Optional[int]: """Alters a column's definition without renaming it.""" if not self.table_exists(tablen...
Alters a column's definition without renaming it.
def center(self): """The cartesian center of the Compound based on its Particles. Returns ------- np.ndarray, shape=(3,), dtype=float The cartesian center of the Compound based on its Particles """ if np.all(np.isfinite(self.xyz)): return np.mea...
The cartesian center of the Compound based on its Particles. Returns ------- np.ndarray, shape=(3,), dtype=float The cartesian center of the Compound based on its Particles
def setup_config(self, cfg=None): ''' Open suitable config file. :return: ''' _opts, _args = optparse.OptionParser.parse_args(self) configs = self.find_existing_configs(_opts.support_unit) if configs and cfg not in configs: cfg = configs[0] re...
Open suitable config file. :return:
def find_sanitiser_nodes( sanitiser, sanitisers_in_file ): """Find nodes containing a particular sanitiser. Args: sanitiser(string): sanitiser to look for. sanitisers_in_file(list[Node]): list of CFG nodes with the sanitiser. Returns: Iterable of sanitiser nodes. """ ...
Find nodes containing a particular sanitiser. Args: sanitiser(string): sanitiser to look for. sanitisers_in_file(list[Node]): list of CFG nodes with the sanitiser. Returns: Iterable of sanitiser nodes.
def hypercube_edges(dims, use_map=False): '''Create edge lists for an arbitrary hypercube. TODO: this is probably not the fastest way.''' edges = [] nodes = np.arange(np.product(dims)).reshape(dims) for i,d in enumerate(dims): for j in range(d-1): for n1, n2 in zip(np.take(nodes, [j]...
Create edge lists for an arbitrary hypercube. TODO: this is probably not the fastest way.
def get_context_data(self, **kwargs): """ Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. """ context ...
Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization.
async def volume(self, ctx, volume: int): """Changes the player's volume""" if ctx.voice_client is None: return await ctx.send("Not connected to a voice channel.") ctx.voice_client.source.volume = volume / 100 await ctx.send("Changed volume to {}%".format(volume))
Changes the player's volume
def process_doc(text): """ The :ref: role is supported by Sphinx but not by plain docutils """ # remove :ref: directives document = docutils.core.publish_doctree(text) # http://epydoc.sourceforge.net/docutils/private/docutils.nodes.document-class.html visitor = RefVisitor(document) document....
The :ref: role is supported by Sphinx but not by plain docutils
def discharge(self): """Discharge of the element in each layer """ rv = np.zeros(self.aq[0].naq) Qls = self.parameters[:, 0] * self.dischargeinf() Qls.shape = (self.nls, self.nlayers, self.order + 1) Qls = np.sum(Qls, 2) for i, q in enumerate(Qls): ...
Discharge of the element in each layer
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_...
Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled:
def generate_private_investment(asset_manager_id=None, asset_id=None, client_id=None): attributes = generate_common(asset_manager_id=asset_manager_id, asset_id=asset_id) """currency, display_name""" private_investment = PrivateInvestment(client_id=client_id or random_string(5), ...
currency, display_name
def append(self, parent, content): """ Select an appender and append the content to parent. @param parent: A parent node. @type parent: L{Element} @param content: The content to append. @type content: L{Content} """ appender = self.default for matc...
Select an appender and append the content to parent. @param parent: A parent node. @type parent: L{Element} @param content: The content to append. @type content: L{Content}
def in_simo_and_inner(self): """ Test if a node is simo: single input and multiple output """ return len(self.successor) > 1 and self.successor[0] is not None and not self.successor[0].in_or_out and \ len(self.precedence) == 1 and self.precedence[0] is not None and not sel...
Test if a node is simo: single input and multiple output
def _stream_blob(self, key, fileobj, progress_callback): """Streams contents of given key to given fileobj. Data is read sequentially in chunks without any seeks. This requires duplicating some functionality of the Azure SDK, which only allows reading entire blob into memory at once or returning...
Streams contents of given key to given fileobj. Data is read sequentially in chunks without any seeks. This requires duplicating some functionality of the Azure SDK, which only allows reading entire blob into memory at once or returning data from random offsets
def dump_pk(obj, abspath, pk_protocol=pk_protocol, replace=False, compress=False, enable_verbose=True): """Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file exten...
Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file extension has to be ``.pickle`` or ``.gz`` (for compressed Pickle). :type abspath: string :param pk_protocol: (default your...
def publish_predictions_to_core(self): """publish_predictions_to_core""" status = FAILED msg = "not started" try: msg = "generating request" log.info(msg) # noqa https://stackoverflow.com/questions/29815129/pandas-dataframe-to-list-of-dictionaries ...
publish_predictions_to_core
def get_organizations(self, page=None): """Get organizations""" opts = {} if page: opts['page'] = page return self.api_call(ENDPOINTS['organizations']['list'], **opts)
Get organizations
def create_salt(length: int=128) -> bytes: """ Create a new salt :param int length: How many bytes should the salt be long? :return: The salt :rtype: bytes """ return b''.join(bytes([SystemRandom().randint(0, 255)]) for _ in range(length))
Create a new salt :param int length: How many bytes should the salt be long? :return: The salt :rtype: bytes
def delete_biggest(self): """ Delete all the biggest duplicates. Keeps all mail of the duplicate set but those sharing the biggest size. """ logger.info( "Deleting all mails sharing the biggest size of {} bytes..." "".format(self.biggest_size)) # ...
Delete all the biggest duplicates. Keeps all mail of the duplicate set but those sharing the biggest size.
def check_async(paths, options, rootdir=None): """Check given paths asynchronously. :return list: list of errors """ LOGGER.info('Async code checking is enabled.') path_queue = Queue.Queue() result_queue = Queue.Queue() for num in range(CPU_COUNT): worker = Worker(path_queue, resu...
Check given paths asynchronously. :return list: list of errors
def begin_batch(self): ''' Starts the batch operation. Intializes the batch variables is_batch: batch operation flag. batch_table: the table name of the batch operation batch_partition_key: the PartitionKey of the batch requests. batch...
Starts the batch operation. Intializes the batch variables is_batch: batch operation flag. batch_table: the table name of the batch operation batch_partition_key: the PartitionKey of the batch requests. batch_row_keys: the RowKey list of a...
def subdivide_to_size(vertices, faces, max_edge, max_iter=10): """ Subdivide a mesh until every edge is shorter than a specified length. Will return a triangle soup, not a nicely structured mesh. Parameters ------------ vert...
Subdivide a mesh until every edge is shorter than a specified length. Will return a triangle soup, not a nicely structured mesh. Parameters ------------ vertices : (n, 3) float Vertices in space faces : (m, 3) int Indices of vertices which make up triangles max_edge : float ...
def get_context_arguments(self): """Return a dictionary containing the current context arguments.""" cargs = {} for context in self.__context_stack: cargs.update(context.context_arguments) return cargs
Return a dictionary containing the current context arguments.
def system(cmd, data=None): ''' pipes the output of a program ''' import subprocess s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) out, err = s.communicate(data) return out.decode('utf8')
pipes the output of a program
def Write2000256List(self, arr): """ Write an array of 64 byte items to the stream. Args: arr (list): a list of 2000 items of 64 bytes in size. """ for item in arr: ba = bytearray(binascii.unhexlify(item)) ba.reverse() self.WriteBy...
Write an array of 64 byte items to the stream. Args: arr (list): a list of 2000 items of 64 bytes in size.
def midi2f(params, midi=69): ''' Convert a midi value to a frequency. Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to one semitone :param params: buffer parameters, controls length of signal created :param midi: midi value :return: array of resulting freq...
Convert a midi value to a frequency. Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to one semitone :param params: buffer parameters, controls length of signal created :param midi: midi value :return: array of resulting frequency
def _env_runner(base_env, extra_batch_callback, policies, policy_mapping_fn, unroll_length, horizon, preprocessors, obs_filters, clip_rewards, clip_actions, pack, callbacks, tf_sess, perf_stats, soft_horizon): """This implements the common experience collection logic....
This implements the common experience collection logic. Args: base_env (BaseEnv): env implementing BaseEnv. extra_batch_callback (fn): function to send extra batch data to. policies (dict): Map of policy ids to PolicyGraph instances. policy_mapping_fn (func): Function that maps agen...
def _fetch(self, url, params): """Fetch a resource. Method to fetch and to iterate over the contents of a type of resource. The method returns a generator of pages for that resource and parameters. :param url: the endpoint of the API :param params: parameters to filter ...
Fetch a resource. Method to fetch and to iterate over the contents of a type of resource. The method returns a generator of pages for that resource and parameters. :param url: the endpoint of the API :param params: parameters to filter :returns: the text of the respons...
def run_flow(flow, storage, flags=None, http=None): """Core code for a command-line application. The ``run()`` function is called from your application and runs through all the steps to obtain credentials. It takes a ``Flow`` argument and attempts to open an authorization server page in the user's ...
Core code for a command-line application. The ``run()`` function is called from your application and runs through all the steps to obtain credentials. It takes a ``Flow`` argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your...
def upload_and_confirm(self, incoming, **kwargs): """Upload the file to okcupid and confirm, among other things, its thumbnail position. :param incoming: A filepath string, :class:`.Info` object or a file like object to upload to okcupid.com. If...
Upload the file to okcupid and confirm, among other things, its thumbnail position. :param incoming: A filepath string, :class:`.Info` object or a file like object to upload to okcupid.com. If an info object is provided, its thumbnail ...
def get_dyndns_records(login, password): """Gets the set of dynamic DNS records associated with this account""" params = dict(action='getdyndns', sha=get_auth_key(login, password)) response = requests.get('http://freedns.afraid.org/api/', params=params, timeout=timeout) raw_records = (line.split('|') fo...
Gets the set of dynamic DNS records associated with this account
def _repr_html_(self): """Give a nice representation of columns in notebooks.""" out="<table class='taqltable'>\n" # Print column name (not if it is auto-generated) if not(self.name()[:4]=="Col_"): out+="<tr>" out+="<th><b>"+self.name()+"</b></th>" ou...
Give a nice representation of columns in notebooks.