code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def set_meta_refresh_enabled(self, enabled): """ *Deprecated:* set :attr:`~.Cluster.schema_metadata_enabled` :attr:`~.Cluster.token_metadata_enabled` instead Sets a flag to enable (True) or disable (False) all metadata refresh queries. This applies to both schema and node topology. ...
*Deprecated:* set :attr:`~.Cluster.schema_metadata_enabled` :attr:`~.Cluster.token_metadata_enabled` instead Sets a flag to enable (True) or disable (False) all metadata refresh queries. This applies to both schema and node topology. Disabling this is useful to minimize refreshes during multip...
def pivot_wavelength_ee(bpass): """Compute pivot wavelength assuming equal-energy convention. `bpass` should have two properties, `resp` and `wlen`. The units of `wlen` can be anything, and `resp` need not be normalized in any particular way. """ from scipy.integrate import simps return np.sqr...
Compute pivot wavelength assuming equal-energy convention. `bpass` should have two properties, `resp` and `wlen`. The units of `wlen` can be anything, and `resp` need not be normalized in any particular way.
def subdivide(self): r"""Split the surface into four sub-surfaces. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four sub-triangles .. image:: ../../images/surface_subdivide1.png :align: center Then the surface is re-para...
r"""Split the surface into four sub-surfaces. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four sub-triangles .. image:: ../../images/surface_subdivide1.png :align: center Then the surface is re-parameterized via the map to / fr...
def uv_to_color(uv, image): """ Get the color in a texture image. Parameters ------------- uv : (n, 2) float UV coordinates on texture image image : PIL.Image Texture image Returns ---------- colors : (n, 4) float RGBA color at each of the UV coordinates """ ...
Get the color in a texture image. Parameters ------------- uv : (n, 2) float UV coordinates on texture image image : PIL.Image Texture image Returns ---------- colors : (n, 4) float RGBA color at each of the UV coordinates
def coords_to_vec(lon, lat): """ Converts longitute and latitude coordinates to a unit 3-vector return array(3,n) with v_x[i],v_y[i],v_z[i] = directional cosines """ phi = np.radians(lon) theta = (np.pi / 2) - np.radians(lat) sin_t = np.sin(theta) cos_t = np.cos(theta) xVals = sin_t * ...
Converts longitute and latitude coordinates to a unit 3-vector return array(3,n) with v_x[i],v_y[i],v_z[i] = directional cosines
def urls_old(self, protocol=Resource.Protocol.http): ''' Iterate through all resources registered with this router and create a list endpoint and a detail endpoint for each one. Uses the router name as prefix and endpoint name of the resource when registered, to assemble the url pattern....
Iterate through all resources registered with this router and create a list endpoint and a detail endpoint for each one. Uses the router name as prefix and endpoint name of the resource when registered, to assemble the url pattern. Uses the constructor-passed url method or class for generating u...
def write_to_buffer(self, buf): """Save the context to a buffer.""" doc = self.to_dict() if config.rxt_as_yaml: content = dump_yaml(doc) else: content = json.dumps(doc, indent=4, separators=(",", ": ")) buf.write(content)
Save the context to a buffer.
def filter_entities(self, model, context=None): """ Filter entities Runs filters on entity properties changing them in place. :param model: object or dict :param context: object, dict or None :return: None """ if model is None: return ...
Filter entities Runs filters on entity properties changing them in place. :param model: object or dict :param context: object, dict or None :return: None
def get_common_properties(root): """Read common properties from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with common properties """ properties = {} for elem in root.iterfind('co...
Read common properties from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with common properties
def model_fn(hparams, seed): """Create a Keras model with the given hyperparameters. Args: hparams: A dict mapping hyperparameters in `HPARAMS` to values. seed: A hashable object to be used as a random seed (e.g., to construct dropout layers in the model). Returns: A compiled Keras model. ""...
Create a Keras model with the given hyperparameters. Args: hparams: A dict mapping hyperparameters in `HPARAMS` to values. seed: A hashable object to be used as a random seed (e.g., to construct dropout layers in the model). Returns: A compiled Keras model.
def model_page(self, request, app_label, model_name, rest_of_url=None): """ Handles the model-specific functionality of the databrowse site, delegating<to the appropriate ModelDatabrowse class. """ try: model = get_model(app_label, model_name) except LookupErr...
Handles the model-specific functionality of the databrowse site, delegating<to the appropriate ModelDatabrowse class.
def OnChar(self, event): """ on Character event""" key = event.GetKeyCode() entry = wx.TextCtrl.GetValue(self).strip() pos = wx.TextCtrl.GetSelection(self) # really, the order here is important: # 1. return sends to ValidateEntry if key == wx.WXK_RETURN: ...
on Character event
def get_docargs(self, args=None, prt=None): """Pare down docopt. Return a minimal dictionary and a set containing runtime arg values.""" # docargs = self.objdoc.get_docargs(args, exp_letters=set(['o', 't', 'p', 'c'])) docargs = self.objdoc.get_docargs(args, prt) self._chk_docopts(docargs...
Pare down docopt. Return a minimal dictionary and a set containing runtime arg values.
def clean_virtualenv(self): """ Empty our virtualenv so that new (or older) dependencies may be installed """ self.user_run_script( script=scripts.get_script_path('clean_virtualenv.sh'), args=[], rw_venv=True, )
Empty our virtualenv so that new (or older) dependencies may be installed
def get_session(account_info): """Get a boto3 sesssion potentially cross account sts assumed assumed sessions are automatically refreshed. """ s = getattr(CONN_CACHE, '%s-session' % account_info['name'], None) if s is not None: return s if account_info.get('role'): s = assumed_s...
Get a boto3 sesssion potentially cross account sts assumed assumed sessions are automatically refreshed.
def fitSphere(coords): """ Fits a sphere to a set of points. Extra info is stored in ``actor.info['radius']``, ``actor.info['center']``, ``actor.info['residue']``. .. hint:: Example: |fitspheres1.py|_ |fitspheres2| |fitspheres2.py|_ """ coords = np.array(coords) n = len(coords) ...
Fits a sphere to a set of points. Extra info is stored in ``actor.info['radius']``, ``actor.info['center']``, ``actor.info['residue']``. .. hint:: Example: |fitspheres1.py|_ |fitspheres2| |fitspheres2.py|_
def setup(): """ Install handlers for Mitogen loggers to redirect them into the Ansible display framework. Ansible installs its own logging framework handlers when C.DEFAULT_LOG_PATH is set, therefore disable propagation for our handlers. """ l_mitogen = logging.getLogger('mitogen') l_mitoge...
Install handlers for Mitogen loggers to redirect them into the Ansible display framework. Ansible installs its own logging framework handlers when C.DEFAULT_LOG_PATH is set, therefore disable propagation for our handlers.
def export_saved_model(sess, export_dir, tag_set, signatures): """Convenience function to export a saved_model using provided arguments The caller specifies the saved_model signatures in a simplified python dictionary form, as follows:: signatures = { 'signature_def_key': { 'inputs': { 'input_te...
Convenience function to export a saved_model using provided arguments The caller specifies the saved_model signatures in a simplified python dictionary form, as follows:: signatures = { 'signature_def_key': { 'inputs': { 'input_tensor_alias': input_tensor_name }, 'outputs': { 'output_tenso...
def worker_wrapper(worker_instance, pid_path): """ A wrapper to start RQ worker as a new process. :param worker_instance: RQ's worker instance :param pid_path: A file to check if the worker is running or not """ def exit_handler(*args): """ Remove pid file on exit ...
A wrapper to start RQ worker as a new process. :param worker_instance: RQ's worker instance :param pid_path: A file to check if the worker is running or not
def require_instance(obj, types=None, name=None, type_name=None, truncate_at=80): """ Raise an exception if obj is not an instance of one of the specified types. Similarly to isinstance, 'types' may be either a single type or a tuple of types. If name or type_name is provided, it is used in the ex...
Raise an exception if obj is not an instance of one of the specified types. Similarly to isinstance, 'types' may be either a single type or a tuple of types. If name or type_name is provided, it is used in the exception message. The object's string representation is also included in the message, t...
def hsv_to_rgb(hsv): """Converts a tuple of hue, saturation, value to a tuple of red, green blue. Hue should be an angle from 0.0 to 359.0. Saturation and value should be a value from 0.0 to 1.0, where saturation controls the intensity of the hue and value controls the brightness. """ # Algorit...
Converts a tuple of hue, saturation, value to a tuple of red, green blue. Hue should be an angle from 0.0 to 359.0. Saturation and value should be a value from 0.0 to 1.0, where saturation controls the intensity of the hue and value controls the brightness.
def eigen(X, P, NSIG=None, method='music', threshold=None, NFFT=default_NFFT, criteria='aic', verbose=False): r"""Pseudo spectrum using eigenvector method (EV or Music) This function computes either the Music or EigenValue (EV) noise subspace frequency estimator. First, an autocorrelation ma...
r"""Pseudo spectrum using eigenvector method (EV or Music) This function computes either the Music or EigenValue (EV) noise subspace frequency estimator. First, an autocorrelation matrix of order `P` is computed from the data. Second, this matrix is separated into vector subspaces, one a signal su...
def needs_refresh(self, source): """Has the (persisted) source expired in the store Will return True if the source is not in the store at all, if it's TTL is set to None, or if more seconds have passed than the TTL. """ now = time.time() if source._tok in self: ...
Has the (persisted) source expired in the store Will return True if the source is not in the store at all, if it's TTL is set to None, or if more seconds have passed than the TTL.
def build(self, corpus, state_size): """ Build a Python representation of the Markov model. Returns a dict of dicts where the keys of the outer dict represent all possible states, and point to the inner dicts. The inner dicts represent all possibilities for the "next" item in the...
Build a Python representation of the Markov model. Returns a dict of dicts where the keys of the outer dict represent all possible states, and point to the inner dicts. The inner dicts represent all possibilities for the "next" item in the chain, along with the count of times it appears.
def identify_triggers( cfg, sources, sinks, lattice, nosec_lines ): """Identify sources, sinks and sanitisers in a CFG. Args: cfg(CFG): CFG to find sources, sinks and sanitisers in. sources(tuple): list of sources, a source is a (source, sanitiser) tuple. sinks(tuple...
Identify sources, sinks and sanitisers in a CFG. Args: cfg(CFG): CFG to find sources, sinks and sanitisers in. sources(tuple): list of sources, a source is a (source, sanitiser) tuple. sinks(tuple): list of sources, a sink is a (sink, sanitiser) tuple. nosec_lines(set): lines with #...
def est_propensity_s(self, lin_B=None, C_lin=1, C_qua=2.71): """ Estimates the propensity score with covariates selected using the algorithm suggested by [1]_. The propensity score is the conditional probability of receiving the treatment given the observed covariates. Estimation is done via a logistic r...
Estimates the propensity score with covariates selected using the algorithm suggested by [1]_. The propensity score is the conditional probability of receiving the treatment given the observed covariates. Estimation is done via a logistic regression. The covariate selection algorithm is based on a sequence ...
def combined_download(accounts, days=60): """Download OFX files and combine them into one It expects an 'accounts' list of ofxclient.Account objects as well as an optional 'days' specifier which defaults to 60 """ client = Client(institution=None) out_file = StringIO() out_file.write(clie...
Download OFX files and combine them into one It expects an 'accounts' list of ofxclient.Account objects as well as an optional 'days' specifier which defaults to 60
def set_ioloop(self, ioloop=None): """Set the tornado IOLoop to use. Sets the tornado.ioloop.IOLoop instance to use, defaulting to IOLoop.current(). If set_ioloop() is never called the IOLoop is started in a new thread, and will be stopped if self.stop() is called. Notes ...
Set the tornado IOLoop to use. Sets the tornado.ioloop.IOLoop instance to use, defaulting to IOLoop.current(). If set_ioloop() is never called the IOLoop is started in a new thread, and will be stopped if self.stop() is called. Notes ----- Must be called before start() ...
def add_samples(self, samples: Iterable[Sample]) -> None: """Add samples in an iterable to this :class:`SampleSheet`.""" for sample in samples: self.add_sample(sample)
Add samples in an iterable to this :class:`SampleSheet`.
def save_state(self): """Store the options into the user's stored session info.""" # Save boolean settings for key, check_box in list(self.boolean_settings.items()): self.save_boolean_setting(key, check_box) # Save text settings for key, line_edit in list(self.text_se...
Store the options into the user's stored session info.
def send_exception(self, code, exc_info=None, headers=None): "send an error response including a backtrace to the client" if headers is None: headers = {} if not exc_info: exc_info = sys.exc_info() self.send_error_msg(code, traceback....
send an error response including a backtrace to the client
def intersection(self,other): """ Return a new DiscreteSet with the intersection of the two sets, i.e. all elements that are in both self and other. :param DiscreteSet other: Set to intersect with :rtype: DiscreteSet """ if self.everything: if other.e...
Return a new DiscreteSet with the intersection of the two sets, i.e. all elements that are in both self and other. :param DiscreteSet other: Set to intersect with :rtype: DiscreteSet
def generate(self, dir_pattern, file_pattern, action_ch='g', recursively=False, force=False): """ Main method to generate (source code) files from templates. See documentation about the directory and file patterns and their possible combinations. Args: dir_pattern: ``glob``...
Main method to generate (source code) files from templates. See documentation about the directory and file patterns and their possible combinations. Args: dir_pattern: ``glob`` pattern taken from the root directory. **Only** used for directories. file_pattern: ``fnmatch`` patte...
def _parse_authors(html_chunk): """ Parse authors of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: list: List of :class:`structures.Author` objects. Blank if no author \ found. """ authors = html_chunk.match( ...
Parse authors of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: list: List of :class:`structures.Author` objects. Blank if no author \ found.
def build_from_queue(cls, input_queue, replay_size, batch_size): """Builds a `ReplayableQueue` that draws from a regular `input_queue`. Args: input_queue: The queue to draw from. replay_size: The size of the replay buffer. batch_size: The size of each batch. Returns: A ReplayableQu...
Builds a `ReplayableQueue` that draws from a regular `input_queue`. Args: input_queue: The queue to draw from. replay_size: The size of the replay buffer. batch_size: The size of each batch. Returns: A ReplayableQueue.
def search_index_advanced(self, index, query): ''' Advanced search query against an entire index > query = ElasticQuery().query_string(query='imchi') > search = ElasticSearch() ''' request = self.session url = 'http://%s:%s/%s/_search' % (self.host, self.port, in...
Advanced search query against an entire index > query = ElasticQuery().query_string(query='imchi') > search = ElasticSearch()
def readPopulations(inputFileName, requiredPopulation): """Reads a population file. :param inputFileName: the name of the population file. :param requiredPopulation: the required population. :type inputFileName: str :type requiredPopulation: list :returns: a :py:class:`dict` containing the po...
Reads a population file. :param inputFileName: the name of the population file. :param requiredPopulation: the required population. :type inputFileName: str :type requiredPopulation: list :returns: a :py:class:`dict` containing the population of each samples.
def reprcall(name, args=(), kwargs=(), keywords='', sep=', ', argfilter=repr): """Format a function call for display.""" if keywords: keywords = ((', ' if (args or kwargs) else '') + '**' + keywords) argfilter = argfilter or repr return "{name}({args}{sep}{kwargs}{key...
Format a function call for display.
def get_account_invitation(self, account_id, invitation_id, **kwargs): # noqa: E501 """Details of a user invitation. # noqa: E501 An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account. **Example usage:** `curl https://api.us-east-...
Details of a user invitation. # noqa: E501 An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{account-id}/user-invitations/{invitation-id} -H 'Authorization: Bea...
def _to_array(value): """As a convenience, turn Python lists and tuples into NumPy arrays.""" if isinstance(value, (tuple, list)): return array(value) elif isinstance(value, (float, int)): return np.float64(value) else: return value
As a convenience, turn Python lists and tuples into NumPy arrays.
def _set_igmp_snooping_state(self, v, load=False): """ Setter method for igmp_snooping_state, mapped from YANG variable /igmp_snooping_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_igmp_snooping_state is considered as a private method. Backends lo...
Setter method for igmp_snooping_state, mapped from YANG variable /igmp_snooping_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_igmp_snooping_state is considered as a private method. Backends looking to populate this variable should do so via calling th...
def kitchen_delete(backend, kitchen): """ Provide the name of the kitchen to delete """ click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki,...
Provide the name of the kitchen to delete
def ToPhotlam(self, wave, flux, **kwargs): """Convert to ``photlam``. Since there is no real conversion necessary, this returns a copy of input flux (if array) or just the input (if scalar). An input array is copied to avoid modifying the input in subsequent **pysynphot** proces...
Convert to ``photlam``. Since there is no real conversion necessary, this returns a copy of input flux (if array) or just the input (if scalar). An input array is copied to avoid modifying the input in subsequent **pysynphot** processing. Parameters ---------- w...
def from_rest(model, props): """ Map the REST data onto the model Additionally, perform the following tasks: * set all blank strings to None where needed * purge all fields not allowed as incoming data * purge all unknown fields from the incoming data * lowercase certain fields...
Map the REST data onto the model Additionally, perform the following tasks: * set all blank strings to None where needed * purge all fields not allowed as incoming data * purge all unknown fields from the incoming data * lowercase certain fields that need it * merge new dat...
def function(self, x, y, amp, alpha, beta, center_x, center_y): """ returns Moffat profile """ x_shift = x - center_x y_shift = y - center_y return amp * (1. + (x_shift**2+y_shift**2)/alpha**2)**(-beta)
returns Moffat profile
def add_input_stream(self, datastream, data_type, options, data): """ To add data stream to a Datastream :param datastream: string :param data_type: string :param options: dict :param data: Stream """ url = self.get_add_input_data_url(datastream, options)...
To add data stream to a Datastream :param datastream: string :param data_type: string :param options: dict :param data: Stream
def __check_mapping(self, landmarks): """ Checks whether the image, from which the supplied landmarks were extracted, can be transformed to the learned standard intensity space without loss of information. """ sc_udiff = numpy.asarray(self.__sc_umaxs)[1:] - numpy.asarray(...
Checks whether the image, from which the supplied landmarks were extracted, can be transformed to the learned standard intensity space without loss of information.
def libvlc_media_set_user_data(p_md, p_new_user_data): '''Sets media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a L{Media} pointer. @param p_md: media descriptor object. @param p_new_u...
Sets media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a L{Media} pointer. @param p_md: media descriptor object. @param p_new_user_data: pointer to user data.
def remove_dataset_from_collection(dataset_id, collection_id, **kwargs): """ Add a single dataset to a dataset collection. """ collection_i = _get_collection(collection_id) collection_item = _get_collection_item(collection_id, dataset_id) if collection_item is None: raise HydraError(...
Add a single dataset to a dataset collection.
def address(cls, address, bits = None): """ @type address: int @param address: Memory address. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @r...
@type address: int @param address: Memory address. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text output.
def open_readable(self, name): """Open cur_dir/name for reading. Note: we read everything into a buffer that supports .read(). Args: name (str): file name, located in self.curdir Returns: file-like (must support read() method) """ # pri...
Open cur_dir/name for reading. Note: we read everything into a buffer that supports .read(). Args: name (str): file name, located in self.curdir Returns: file-like (must support read() method)
def post_event_access_code(self, id, access_code_id, **data): """ POST /events/:id/access_codes/:access_code_id/ Updates an access code; returns the result as a :format:`access_code` as the key ``access_code``. """ return self.post("/events/{0}/access_codes/{0}/"...
POST /events/:id/access_codes/:access_code_id/ Updates an access code; returns the result as a :format:`access_code` as the key ``access_code``.
def _udf_cell(args, js): """Implements the bigquery_udf cell magic for ipython notebooks. The supported syntax is: %%bigquery udf --module <var> <js function> Args: args: the optional arguments following '%%bigquery udf'. js: the UDF declaration (inputs and outputs) and implementation in javascript....
Implements the bigquery_udf cell magic for ipython notebooks. The supported syntax is: %%bigquery udf --module <var> <js function> Args: args: the optional arguments following '%%bigquery udf'. js: the UDF declaration (inputs and outputs) and implementation in javascript. Returns: The results of...
def load_json_file(json_file): """ load json file and check file content format """ with io.open(json_file, encoding='utf-8') as data_file: try: json_content = json.load(data_file) except exceptions.JSONDecodeError: err_msg = u"JSONDecodeError: JSON file format error:...
load json file and check file content format
def select_all(self, table, limit=MAX_ROWS_PER_QUERY, execute=True): """Query all rows and columns from a table.""" # Determine if a row per query limit should be set num_rows = self.count_rows(table) if num_rows > limit: return self._select_batched(table, '*', num_rows, limi...
Query all rows and columns from a table.
def intervalSum(self, a, b): """ :param int a b: with 1 <= a <= b :returns: t[a] + ... + t[b] """ return self.prefixSum(b) - self.prefixSum(a-1)
:param int a b: with 1 <= a <= b :returns: t[a] + ... + t[b]
def _build(self, leaves): """Private helper function to create the next aggregation level and put all references in place. """ new, odd = [], None # check if even number of leaves, promote odd leaf to next level, if not if len(leaves) % 2 == 1: odd = leaves.pop(-1) ...
Private helper function to create the next aggregation level and put all references in place.
def pypackable(name, pytype, format): """ Create a "mix-in" class with a python type and a Packable with the given struct format """ size, items = _formatinfo(format) return type(Packable)(name, (pytype, Packable), { '_format_': format, '_size_': size, '_items_': items, ...
Create a "mix-in" class with a python type and a Packable with the given struct format
def get_python_json(scala_json): """Return a JSON dict from a org.json4s.JsonAST""" def convert_node(node): if node.__class__.__name__ in ('org.json4s.JsonAST$JValue', 'org.json4s.JsonAST$JObject'): # Make a dictionary and then convert each value ...
Return a JSON dict from a org.json4s.JsonAST
def acoustic_similarity_mapping(path_mapping, analysis_function, distance_function, stop_check=None, call_back=None, multiprocessing=True): """Takes in an explicit mapping of full paths to .wav files to have acoustic similarity computed. Parameters ---------- path_mapping : iterable of iterables ...
Takes in an explicit mapping of full paths to .wav files to have acoustic similarity computed. Parameters ---------- path_mapping : iterable of iterables Explicit mapping of full paths of .wav files, in the form of a list of tuples to be compared. Returns ------- dict ...
def export_table(datatable_code, **kwargs): """Downloads an entire table as a zip file. :param str datatable_code: The datatable code to download, such as MER/F1 :param str filename: The filename for the download. \ If not specified, will download to the current working directory :param str api_key:...
Downloads an entire table as a zip file. :param str datatable_code: The datatable code to download, such as MER/F1 :param str filename: The filename for the download. \ If not specified, will download to the current working directory :param str api_key: Most databases require api_key for bulk download
def data_to_df(self, sysbase=False): """ Return a pandas.DataFrame of device parameters. :param sysbase: save per unit values in system base """ p_dict_comp = self.data_to_dict(sysbase=sysbase) self._check_pd() self.param_df = pd.DataFrame(data=p_dict_comp).set_...
Return a pandas.DataFrame of device parameters. :param sysbase: save per unit values in system base
def to_char(token): """Transforms the ASCII control character symbols to their real char. Note: If the token is not an ASCII control character symbol, just return the token. Keyword arguments: token -- the token to transform """ if ord(token) in _range(9216, 9229 + 1): token = _un...
Transforms the ASCII control character symbols to their real char. Note: If the token is not an ASCII control character symbol, just return the token. Keyword arguments: token -- the token to transform
def p_throttling(p): """ throttling : THROTTLING COLON NONE | THROTTLING COLON TAIL_DROP OPEN_BRACKET NUMBER CLOSE_BRACKET """ throttling = NoThrottlingSettings() if len(p) == 7: throttling = TailDropSettings(int(p[5])) p[0] = {"throttling": throttling}
throttling : THROTTLING COLON NONE | THROTTLING COLON TAIL_DROP OPEN_BRACKET NUMBER CLOSE_BRACKET
async def _get_response(self, msg): """Perform the request, get the response.""" try: protocol = await self._get_protocol() pr = protocol.request(msg) r = await pr.response return pr, r except ConstructionRenderableError as e: raise Cli...
Perform the request, get the response.
def draw_step(self): """iterator that computes all vertices coordinates and edge routing after just one step (one layer after the other from top to bottom to top). Purely inefficient ! Use it only for "animation" or debugging purpose. """ ostep = self.ordering_step() ...
iterator that computes all vertices coordinates and edge routing after just one step (one layer after the other from top to bottom to top). Purely inefficient ! Use it only for "animation" or debugging purpose.
def json(self): """ Return a JSON-serializable representation of this result. The output of this function can be converted to a serialized string with :any:`json.dumps`. """ data = super(CalTRACKHourlyModel, self).json() data.update( { "occupa...
Return a JSON-serializable representation of this result. The output of this function can be converted to a serialized string with :any:`json.dumps`.
def p(self, path): """ provide absolute path within the container :param path: path with container :return: str """ if path.startswith("/"): path = path[1:] p = os.path.join(self.mount_point, path) logger.debug("path = %s", p) return p
provide absolute path within the container :param path: path with container :return: str
def set_pixel(self,x,y,state): """Set pixel at "x,y" to "state" where state can be one of "ON", "OFF" or "TOGGLE" """ self.send_cmd("P"+str(x+1)+","+str(y+1)+","+state)
Set pixel at "x,y" to "state" where state can be one of "ON", "OFF" or "TOGGLE"
def binary_size(self): '''Return the number of bytes needed to store this parameter.''' return ( 1 + # group_id 2 + # next offset marker 1 + len(self.name.encode('utf-8')) + # size of name and name bytes 1 + # data size 1 + len(self.dimensions)...
Return the number of bytes needed to store this parameter.
def acknowledged_by(self): """Username of the acknowledger.""" if (self.is_acknowledged and self._proto.acknowledgeInfo.HasField('acknowledgedBy')): return self._proto.acknowledgeInfo.acknowledgedBy return None
Username of the acknowledger.
def update_iteration(self): """Update the last experiment group's iteration with experiment performance.""" iteration_config = self.get_iteration_config() if not iteration_config: return experiments_metrics = self.experiment_group.get_experiments_metrics( experime...
Update the last experiment group's iteration with experiment performance.
def apply(self, dir_or_plan=None, input=False, skip_plan=False, no_color=IsFlagged, **kwargs): """ refer to https://terraform.io/docs/commands/apply.html no-color is flagged by default :param no_color: disable color of stdout :param input: disable prompt for a missi...
refer to https://terraform.io/docs/commands/apply.html no-color is flagged by default :param no_color: disable color of stdout :param input: disable prompt for a missing variable :param dir_or_plan: folder relative to working folder :param skip_plan: force apply without plan (def...
def calculate_output(self, variable_name, period): """ Calculate the value of a variable using the ``calculate_output`` attribute of the variable. """ variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True) if variable.calculate_output is None...
Calculate the value of a variable using the ``calculate_output`` attribute of the variable.
def get_event_q(self, event_name): """Obtain the queue storing events of the specified name. If no event of this name has been polled, wait for one to. Returns: A queue storing all the events of the specified name. None if timed out. Raises: queue.E...
Obtain the queue storing events of the specified name. If no event of this name has been polled, wait for one to. Returns: A queue storing all the events of the specified name. None if timed out. Raises: queue.Empty: Raised if the queue does not exist and t...
def build_columns(self, X, verbose=False): """construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse arr...
construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse array with n rows
def retcode_pillar(pillar_name): ''' Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com ...
Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -...
def send_media_file(self, filename): """ Function used to send media files from the media folder to the browser. """ cache_timeout = self.get_send_file_max_age(filename) return send_from_directory(self.config['MEDIA_FOLDER'], filename, cache_tim...
Function used to send media files from the media folder to the browser.
def accept(self, addr): """ Add an address to the set of addresses this proxy is permitted to introduce. :param addr: The address to add. """ # Add the address to the set ip_addr = _parse_ip(addr) if ip_addr is None: LOG.warn("Cannot add addr...
Add an address to the set of addresses this proxy is permitted to introduce. :param addr: The address to add.
def line_line(origins, directions, plane_normal=None): """ Find the intersection between two lines. Uses terminology from: http://geomalgorithms.com/a05-_intersect-1.html line 1: P(s) = p_0 + sU line 2: Q(t) = q_0 + tV Parameters --------- origins:...
Find the intersection between two lines. Uses terminology from: http://geomalgorithms.com/a05-_intersect-1.html line 1: P(s) = p_0 + sU line 2: Q(t) = q_0 + tV Parameters --------- origins: (2, d) float, points on lines (d in [2,3]) directions: (2, d) float, direction vect...
def removeCMSPadding(str, blocksize=AES_blocksize): '''CMS padding: Remove padding with bytes containing the number of padding bytes ''' try: pad_len = ord(str[-1]) # last byte contains number of padding bytes except TypeError: pad_len = str[-1] assert pad_len <= blocksize, 'padding error' assert pad...
CMS padding: Remove padding with bytes containing the number of padding bytes
def drawRect(self, x1, y1, x2, y2, angle=0): """ Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: The X of the top-left corner of the rectangle. :param y1: The Y of the top-lef...
Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: The X of the top-left corner of the rectangle. :param y1: The Y of the top-left corner of the rectangle. :param x2: The X of the ...
def drop_network_by_id(self, network_id: int) -> None: """Drop a network by its database identifier.""" network = self.session.query(Network).get(network_id) self.drop_network(network)
Drop a network by its database identifier.
def append_copy(self, elem): """Append a copy of the specified element as a child.""" return XMLElement(lib.lsl_append_copy(self.e, elem.e))
Append a copy of the specified element as a child.
def _put(self, item: SQLBaseObject): """Puts a item into the database. Updates lastUpdate column""" if item._dto_type in self._expirations and self._expirations[item._dto_type] == 0: # The expiration time has been set to 0 -> shoud not be cached return item.updated() ...
Puts a item into the database. Updates lastUpdate column
def save_to_file(self, filename, format=None, **kwargs): """ Save the object to file given by filename. """ if format is None: # try to derive protocol from file extension format = format_from_extension(filename) with file(filename, 'wb') as fp: self.s...
Save the object to file given by filename.
def incr(self, name, amount=1): """自增key的对应的值,当key不存在时则为默认值,否则在基础上自增整数amount :param name: key :param amount: 默认值 :return: 返回自增后的值 """ return self.client.incr(name, amount=amount)
自增key的对应的值,当key不存在时则为默认值,否则在基础上自增整数amount :param name: key :param amount: 默认值 :return: 返回自增后的值
def divide_prefixes(prefixes: List[str], seed:int=0) -> Tuple[List[str], List[str], List[str]]: """Divide data into training, validation and test subsets""" if len(prefixes) < 3: raise PersephoneException( "{} cannot be split into 3 groups as it only has {} items".format(pref...
Divide data into training, validation and test subsets
def show_vcs_output_vcs_nodes_vcs_node_info_node_switch_mac(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") config = show_vcs output = ET.SubElement(show_vcs, "output") vcs_nodes = ET.SubElement(output, "...
Auto Generated Code
def get_octets(self, octets=None, timeout=1.0): """Get NDEF message octets from a SNEP Server. .. versionadded:: 0.13 If the client has not yet a data link connection with a SNEP Server, it temporarily connects to the default SNEP Server, sends the message octets, disconnects a...
Get NDEF message octets from a SNEP Server. .. versionadded:: 0.13 If the client has not yet a data link connection with a SNEP Server, it temporarily connects to the default SNEP Server, sends the message octets, disconnects after the server response, and returns the received ...
def make_pdb(self, alt_states=False, inc_ligands=True): """Generates a PDB string for the `Polymer`. Parameters ---------- alt_states : bool, optional Include alternate conformations for `Monomers` in PDB. inc_ligands : bool, optional Includes `Ligands` i...
Generates a PDB string for the `Polymer`. Parameters ---------- alt_states : bool, optional Include alternate conformations for `Monomers` in PDB. inc_ligands : bool, optional Includes `Ligands` in PDB. Returns ------- pdb_str : str ...
def _convert_to_config(self): """self.parsed_data->self.config""" for k, v in vars(self.parsed_data).iteritems(): exec "self.config.%s = v"%k in locals(), globals()
self.parsed_data->self.config
def on_to_position(self, speed, position, brake=True, block=True): """ Rotate the motor at ``speed`` to ``position`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units. """ speed = self._speed_native_units(speed) ...
Rotate the motor at ``speed`` to ``position`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units.
def list_role_binding_for_all_namespaces(self, **kwargs): """ list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_role_binding_for_all_namespaces(...
list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_role_binding_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bo...
def clean_value(self): """ Populates json serialization ready data. This is the method used to serialize and store the object data in to DB Returns: List of dicts. """ result = [] for mdl in self: result.append(super(ListNode, mdl).clean_v...
Populates json serialization ready data. This is the method used to serialize and store the object data in to DB Returns: List of dicts.
def download_document(self, document: Document, overwrite=True, path=None): """ Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename. If overwrite is set the local version will be overwritten if the file was changed on...
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename. If overwrite is set the local version will be overwritten if the file was changed on studip since the last check
def before_export(self): """ Set the attributes nbytes """ # sanity check that eff_ruptures have been set, i.e. are not -1 try: csm_info = self.datastore['csm_info'] except KeyError: csm_info = self.datastore['csm_info'] = self.csm.info for...
Set the attributes nbytes
def compressBWTPoolProcess(tup): ''' During compression, each available process will calculate a subportion of the BWT independently using this function. This process takes the chunk and rewrites it into a given filename using the technique described in the compressBWT(...) function header ''' ...
During compression, each available process will calculate a subportion of the BWT independently using this function. This process takes the chunk and rewrites it into a given filename using the technique described in the compressBWT(...) function header
def get_foreign_key(self, name): """ Returns the foreign key constraint with the given name. :param name: The constraint name :type name: str :rtype: ForeignKeyConstraint """ name = self._normalize_identifier(name) if not self.has_foreign_key(name): ...
Returns the foreign key constraint with the given name. :param name: The constraint name :type name: str :rtype: ForeignKeyConstraint
def style_from_dict(style_dict, include_defaults=True): """ Create a ``Style`` instance from a dictionary or other mapping. The dictionary is equivalent to the ``Style.styles`` dictionary from pygments, with a few additions: it supports 'reverse' and 'blink'. Usage:: style_from_dict({ ...
Create a ``Style`` instance from a dictionary or other mapping. The dictionary is equivalent to the ``Style.styles`` dictionary from pygments, with a few additions: it supports 'reverse' and 'blink'. Usage:: style_from_dict({ Token: '#ff0000 bold underline', Token.Title: '...