code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def used_states(self): 'a list of the used states in the order they appear' c = itertools.count() canonical_ids = collections.defaultdict(lambda: next(c)) for s in self.states_list: for state in s.stateseq: canonical_ids[state] return list(map(operator...
a list of the used states in the order they appear
def get_node(cls, info, id): """ Bear in mind that if you are overriding this method get_node(info, pk), you should always call maybe_optimize(info, qs, pk) and never directly call get_optimized_node(info, qs, pk) as it would result to the node being attempted to be optimized whe...
Bear in mind that if you are overriding this method get_node(info, pk), you should always call maybe_optimize(info, qs, pk) and never directly call get_optimized_node(info, qs, pk) as it would result to the node being attempted to be optimized when it is not supposed to actually get opti...
def removefromreadergroup(self, groupname): """Remove a reader from a reader group""" hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if 0 != hresult: raise EstablishContextException(hresult) try: hresult = SCardRemoveReaderFromGroup(hcontext, self.na...
Remove a reader from a reader group
def default_update_function(self, n: Tuple[str, dict]) -> List[float]: """ The default update function for a CAG node. n: A 2-tuple containing the node name and node data. Returns: A list of values corresponding to the distribution of the value of the real-valued var...
The default update function for a CAG node. n: A 2-tuple containing the node name and node data. Returns: A list of values corresponding to the distribution of the value of the real-valued variable representing the node.
def load(fp, **kwargs): ''' Deserialize `fp` (a `.read()`-supporting file-like object containing a JSON document with Python or JavaScript like comments) to a Python object. :param fp: a `.read()`-supporting file-like object containing a JSON document with or without comments. :param kwa...
Deserialize `fp` (a `.read()`-supporting file-like object containing a JSON document with Python or JavaScript like comments) to a Python object. :param fp: a `.read()`-supporting file-like object containing a JSON document with or without comments. :param kwargs: all the arguments that `jso...
def deregisterevent(self, event_name): """ Remove callback of registered event @param event_name: Event name in at-spi format. @type event_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer """ if event_name in self._pollE...
Remove callback of registered event @param event_name: Event name in at-spi format. @type event_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer
def get_account_entitlement(self): """GetAccountEntitlement. [Preview API] Gets the account entitlement of the current user it is mapped to _apis/licensing/entitlements/me so specifically is looking for the user of the request :rtype: :class:`<AccountEntitlement> <azure.devops.v5_0.licensing.mod...
GetAccountEntitlement. [Preview API] Gets the account entitlement of the current user it is mapped to _apis/licensing/entitlements/me so specifically is looking for the user of the request :rtype: :class:`<AccountEntitlement> <azure.devops.v5_0.licensing.models.AccountEntitlement>`
def install(self, io_handler, module_name): """ Installs the bundle with the given module name """ bundle = self._context.install_bundle(module_name) io_handler.write_line("Bundle ID: {0}", bundle.get_bundle_id()) return bundle.get_bundle_id()
Installs the bundle with the given module name
def get_fields(self): """Get all fields""" if not hasattr(self, '__fields'): self.__fields = [ self.parse_field(field, index) for index, field in enumerate(getattr(self, 'fields', [])) ] return self.__fields
Get all fields
def saml_provider_present(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' .. versionadded:: 2016.11.0 Ensure the SAML provider with the specified name is present. name (string) The name of the SAML provider. saml_metadata_document (string) The x...
.. versionadded:: 2016.11.0 Ensure the SAML provider with the specified name is present. name (string) The name of the SAML provider. saml_metadata_document (string) The xml document of the SAML provider. region (string) Region to connect to. key (string) Secret ...
def _from_dict(cls, _dict): """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" args = {} if 'results' in _dict: args['results'] = [ LogQueryResponseResultDocumentsResult._from_dict(x) for x in (_dict.get('results')) ...
Initialize a LogQueryResponseResultDocuments object from a json dictionary.
def bring_tab_to_the_top(self, tab_label): """Find tab with label tab_label in list of notebook's and set it to the current page. :param tab_label: String containing the label of the tab to be focused """ page = self.page_dict[tab_label] for notebook in self.notebook_names: ...
Find tab with label tab_label in list of notebook's and set it to the current page. :param tab_label: String containing the label of the tab to be focused
def clean(): '''Delete temporary files not under version control.''' basedir = dirname(__file__) print(cyan('delete temp files and dirs for packaging')) local(flo( 'rm -rf ' '{basedir}/.eggs/ ' '{basedir}/fabsetup.egg-info/ ' '{basedir}/dist ' '{basedir}/REA...
Delete temporary files not under version control.
def body(self): """return the raw version of the body""" body = None if self.body_input: body = self.body_input.read(int(self.get_header('content-length', -1))) return body
return the raw version of the body
def open(self): """Open or re-open file.""" if self._fh: return # file is open if isinstance(self._file, pathlib.Path): self._file = str(self._file) if isinstance(self._file, basestring): # file name self._file = os.path.realpath(self._fi...
Open or re-open file.
def delete(self, id): """ Deletes an "object" (line, triangle, image, etc) from the drawing. :param int id: The id of the object. """ if id in self._images.keys(): del self._images[id] self.tk.delete(id)
Deletes an "object" (line, triangle, image, etc) from the drawing. :param int id: The id of the object.
def info(self, i: int=None) -> str: """ Returns an info message """ head = "[" + colors.blue("info") + "]" if i is not None: head = str(i) + " " + head return head
Returns an info message
def get_membership(self, uuid=None): """Get membership data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: ...
Get membership data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: membership json
def get_next_asset(self): """Gets the next Asset in this list. return: (osid.repository.Asset) - the next Asset in this list. The has_next() method should be used to test that a next Asset is available before calling this method. raise: IllegalState - no more el...
Gets the next Asset in this list. return: (osid.repository.Asset) - the next Asset in this list. The has_next() method should be used to test that a next Asset is available before calling this method. raise: IllegalState - no more elements available in this list ...
def names(self): """The list of column names (List[str]).""" if not self._ex._cache.names_valid(): self._ex._cache.flush() self._frame(fill_cache=True) return list(self._ex._cache.names)
The list of column names (List[str]).
def quantstr(typestr, num, plural_suffix='s'): r""" Heuristically generates an english phrase relating to the quantity of something. This is useful for writing user messages. Args: typestr (str): singular form of the word num (int): quanity of the type plural_suffix (str): heur...
r""" Heuristically generates an english phrase relating to the quantity of something. This is useful for writing user messages. Args: typestr (str): singular form of the word num (int): quanity of the type plural_suffix (str): heurstic plural form (default = 's') Returns: ...
def get_nn(self, structure, n): """ Get near neighbors of site with index n in structure. Args: structure (Structure): input structure. n (integer): index of site in structure for which to determine neighbors. Returns: sites (list ...
Get near neighbors of site with index n in structure. Args: structure (Structure): input structure. n (integer): index of site in structure for which to determine neighbors. Returns: sites (list of Site objects): near neighbors.
def findpk2(self, r1, s1, r2, s2, flag1, flag2): """ find pubkey Y from 2 different signature on the same message sigs: (r1,s1) and (r2,s2) returns (R1*s1-R2*s2)/(r1-r2) """ R1 = self.ec.decompress(r1, flag1) R2 = self.ec.decompress(r2, flag2) rdiff = se...
find pubkey Y from 2 different signature on the same message sigs: (r1,s1) and (r2,s2) returns (R1*s1-R2*s2)/(r1-r2)
def Execute(self, http): """Execute all the requests as a single batched HTTP request. Args: http: A httplib2.Http object to be used with the request. Returns: None Raises: BatchError if the response is the wrong format. """ self._Execute...
Execute all the requests as a single batched HTTP request. Args: http: A httplib2.Http object to be used with the request. Returns: None Raises: BatchError if the response is the wrong format.
def _class_exists(self, classname, namespace): """ Test if class defined by classname parameter exists in repository defined by namespace parameter. Returns `True` if class exists and `False` if it does not exist. Exception if the namespace does not exist """ cl...
Test if class defined by classname parameter exists in repository defined by namespace parameter. Returns `True` if class exists and `False` if it does not exist. Exception if the namespace does not exist
def if_exists(self): """ Check the existence of an object before an update or delete. If the update or delete isn't applied, a LWTException is raised. """ if self.model._has_counter: raise IfExistsWithCounterColumn('if_exists cannot be used with tables containing cou...
Check the existence of an object before an update or delete. If the update or delete isn't applied, a LWTException is raised.
def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oa...
Depending on the state passed in, get self._oauth up and running
def likes(user, *models): """ Usage: {% likes user as var %} Or {% likes user [model1, model2] as var %} """ content_types = [] model_list = models or settings.PINAX_LIKES_LIKABLE_MODELS.keys() for model in model_list: if not _allowed(model): continue ...
Usage: {% likes user as var %} Or {% likes user [model1, model2] as var %}
def findfivo(ol,*args,**kwargs): ''' #findfivo f,i,v,o四元决定 fivo-4-tuple-engine #cond_func diff_func(index,value,*diff_args) ''' args = list(args) lngth = args.__len__() if(lngth==0): diff_funcs_arr = kwargs['cond_funcs'] diff_args_...
#findfivo f,i,v,o四元决定 fivo-4-tuple-engine #cond_func diff_func(index,value,*diff_args)
def not_query(expression): """Apply logical not operator to expression.""" compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = index.get_all_keys() returned_keys = e...
Apply logical not operator to expression.
def in_generator(self, generator): """Context manager: set the given generator as the current generator.""" previous_generator = self._current_generator try: self._current_generator = generator yield finally: self._current_generator = previous_generato...
Context manager: set the given generator as the current generator.
def sca_intensity(scatterer, h_pol=True): """Scattering intensity (phase function) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The differential scatter...
Scattering intensity (phase function) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The differential scattering cross section.
def add_file_handler(log_file_level, log_filename, str_format=None, date_format=None, formatter=None, log_filter=None): """ :param log_filename: :param log_file_level str of the log level to use on this file :param str_format: str of the logging format :param date_format:...
:param log_filename: :param log_file_level str of the log level to use on this file :param str_format: str of the logging format :param date_format: str of the date format :param log_restart: bool if True the log file will be deleted first :param log_history: bool if True will sav...
def print_matrix(matrix, msg=None): """ Convenience function: Displays the contents of a matrix of integers. :Parameters: matrix : list of lists Matrix to print msg : str Optional message to print before displaying the matrix """ import math if msg is n...
Convenience function: Displays the contents of a matrix of integers. :Parameters: matrix : list of lists Matrix to print msg : str Optional message to print before displaying the matrix
def save(self, commit=True): """ Saves the instance. """ if self.instance.pk: # First handle updates post = super().save(commit=False) post.updated_by = self.user post.updates_count = F('updates_count') + 1 else: post = Post( ...
Saves the instance.
def _walk_through_splits(self): """ Yields (parent_split, child_plit) tuples. """ def walk(split): for c in split: if isinstance(c, (HSplit, VSplit)): yield split, c for i in walk(c): yield i ...
Yields (parent_split, child_plit) tuples.
def search_dashboard_deleted_for_facets(self, **kwargs): # noqa: E501 """Lists the values of one or more facets over the customer's deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass...
Lists the values of one or more facets over the customer's deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_dashboard_deleted_for_facets(async...
def new_media_object(blog_id, username, password, media): """ metaWeblog.newMediaObject(blog_id, username, password, media) => media structure """ authenticate(username, password) path = default_storage.save(Entry().image_upload_to(media['name']), ContentFile(medi...
metaWeblog.newMediaObject(blog_id, username, password, media) => media structure
def voice_channels(self): """List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)] r.sort(key=lambda ...
List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom.
def send_sms(phone: str, message: str, sender: str='', **kw): """ Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access. :param phone: Phone number :param message: Message to be esnd :param sender: Sender (max 11 characters) :param kw: Variable key-value pairs to be sent to SMS ...
Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access. :param phone: Phone number :param message: Message to be esnd :param sender: Sender (max 11 characters) :param kw: Variable key-value pairs to be sent to SMS API :return: Response from requests.post
def decompose_space(H, A): """Simplifies OperatorTrace expressions over tensor-product spaces by turning it into iterated partial traces. Args: H (ProductSpace): The full space. A (Operator): Returns: Operator: Iterative partial trace expression """ return OperatorTrace...
Simplifies OperatorTrace expressions over tensor-product spaces by turning it into iterated partial traces. Args: H (ProductSpace): The full space. A (Operator): Returns: Operator: Iterative partial trace expression
def vote(self, direction=0): """Vote for the given item in the direction specified. Note: votes must be cast by humans. That is, API clients proxying a human's action one-for-one are OK, but bots deciding how to vote on content or amplifying a human's vote are not. See the reddit rules ...
Vote for the given item in the direction specified. Note: votes must be cast by humans. That is, API clients proxying a human's action one-for-one are OK, but bots deciding how to vote on content or amplifying a human's vote are not. See the reddit rules for more details on what constit...
def mom_recurse(self, idxi, idxj, idxk): """Backend mement main loop.""" rank_ = min( chaospy.bertran.rank(idxi, self.dim), chaospy.bertran.rank(idxj, self.dim), chaospy.bertran.rank(idxk, self.dim) ) par, axis0 = chaospy.bertran.parent(idxk, self.dim)...
Backend mement main loop.
def _B(self, R): """Return numpy array from B1 up to and including Bn. (eqn. 6)""" HNn_R = self._HNn / R return HNn_R / self._sin_alpha * (0.4 * HNn_R / self._sin_alpha + 1)
Return numpy array from B1 up to and including Bn. (eqn. 6)
def modifies_known_mutable(obj, attr): """This function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and with Python 2.6 onwards the abstract base classes `Mut...
This function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and with Python 2.6 onwards the abstract base classes `MutableSet`, `MutableMapping`, and `MutableSe...
def _to_message_element(self, element): """ Args: element the element to be checked and if necessary converted Returns: the correct element Raises: Errors are propagated """ if element is None: return None elif sel...
Args: element the element to be checked and if necessary converted Returns: the correct element Raises: Errors are propagated
def euler(self): """ Get the euler angles. The convention is Tait-Bryan (ZY'X'') :returns: array containing the euler angles [roll, pitch, yaw] """ if self._euler is None: if self._q is not None: # try to get euler angles from q via DCM ...
Get the euler angles. The convention is Tait-Bryan (ZY'X'') :returns: array containing the euler angles [roll, pitch, yaw]
def _preprocess_sqlite_view(asql_query, library, backend, connection): """ Finds view or materialized view in the asql query and converts it to create table/insert rows. Note: Assume virtual tables for all partitions already created. Args: asql_query (str): asql query library (ambr...
Finds view or materialized view in the asql query and converts it to create table/insert rows. Note: Assume virtual tables for all partitions already created. Args: asql_query (str): asql query library (ambry.Library): backend (SQLiteBackend): connection (apsw.Connectio...
def setup_fields(attrs): """ Collect all fields declared on the class and remove them from attrs """ fields = {} iterator = list(attrs.items()) for key, value in iterator: if not isinstance(value, Field): continue fields[key] = value del attrs[key] return ...
Collect all fields declared on the class and remove them from attrs
def _get_requested_filters(self, **kwargs): """ Convert 'filters' query params into a dict that can be passed to Q. Returns a dict with two fields, 'include' and 'exclude', which can be used like: result = self._get_requested_filters() q = Q(**result['include'] & ~Q(...
Convert 'filters' query params into a dict that can be passed to Q. Returns a dict with two fields, 'include' and 'exclude', which can be used like: result = self._get_requested_filters() q = Q(**result['include'] & ~Q(**result['exclude'])
def RRlist2bitmap(lst): """ Encode a list of integers representing Resource Records to a bitmap field used in the NSEC Resource Record. """ # RFC 4034, 4.1.2. The Type Bit Maps Field import math bitmap = b"" lst = list(set(lst)) lst.sort() #lst = filter(lambda x: x <= 655...
Encode a list of integers representing Resource Records to a bitmap field used in the NSEC Resource Record.
def get_mkt_val(self, pxs=None): """ return the market value series for the specified Series of pxs """ pxs = self._closing_pxs if pxs is None else pxs return pxs * self.multiplier
return the market value series for the specified Series of pxs
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be ...
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation ...
def offset(self, value): """ Allows for skipping a specified number of results in query. Useful for pagination. """ self._query = self._query.skip(value) return self
Allows for skipping a specified number of results in query. Useful for pagination.
def p_statement_return(p): '''statement : RETURN SEMI | RETURN expr SEMI''' if len(p) == 3: p[0] = ast.Return(None, lineno=p.lineno(1)) else: p[0] = ast.Return(p[2], lineno=p.lineno(1))
statement : RETURN SEMI | RETURN expr SEMI
def elemental_abund(self,cycle,zrange=[1,85],ylim=[0,0],title_items=None, ref=-1,ref_filename=None,z_pin=None,pin=None, pin_filename=None,zchi2=None,logeps=False,dilution=None,show_names=True,label='', colour='black',plotlines=':',plotlabels=True,m...
Plot the decayed elemental abundance distribution (PPN). Plot the elemental abundance distribution (nugridse). (FH, 06/2014; SJ 07/2014) Parameters ---------- cycle : string, integer or list The cycle of interest. If it is a list of cycles, this method w...
def wait_for_focus(self, title, timeOut=5): """ Wait for window with the given title to have focus Usage: C{window.wait_for_focus(title, timeOut=5)} If the window becomes active, returns True. Otherwise, returns False if the window has not become active by the t...
Wait for window with the given title to have focus Usage: C{window.wait_for_focus(title, timeOut=5)} If the window becomes active, returns True. Otherwise, returns False if the window has not become active by the time the timeout has elapsed. @param title: titl...
def _initialize(self): r"""Initialize the mean and covariance of the posterior. Given that :math:`\tilde{\mathrm T}` is a matrix of zeros right before the first EP iteration, we have .. math:: \boldsymbol\mu = \mathrm K^{-1} \mathbf m ~\text{ and }~ \Sigma = \m...
r"""Initialize the mean and covariance of the posterior. Given that :math:`\tilde{\mathrm T}` is a matrix of zeros right before the first EP iteration, we have .. math:: \boldsymbol\mu = \mathrm K^{-1} \mathbf m ~\text{ and }~ \Sigma = \mathrm K as the initial...
def _make_jwt(self): """Make a signed JWT. Returns: Tuple[bytes, datetime]: The encoded JWT and the expiration. """ now = _helpers.utcnow() lifetime = datetime.timedelta(seconds=self._token_lifetime) expiry = now + lifetime payload = { 'i...
Make a signed JWT. Returns: Tuple[bytes, datetime]: The encoded JWT and the expiration.
def vq_discrete_unbottleneck(x, hparams): """Simple undiscretization from vector quantized representation.""" x_shape = common_layers.shape_list(x) bottleneck_size = 2**hparams.bottleneck_bits means = hparams.means x_flat = tf.reshape(x, [-1, bottleneck_size]) result = tf.matmul(x_flat, means) result = tf...
Simple undiscretization from vector quantized representation.
def seek(self, n_bytes, from_what=os.SEEK_SET): """Seek to a new position in the memory region. Parameters ---------- n_bytes : int Number of bytes to seek. from_what : int As in the Python standard: `0` seeks from the start of the memory regi...
Seek to a new position in the memory region. Parameters ---------- n_bytes : int Number of bytes to seek. from_what : int As in the Python standard: `0` seeks from the start of the memory region, `1` seeks from the current position and `2` seeks from ...
def dump(stream=None): """ Dumps a string representation of `FILTERS` to a stream, normally an open file. If none is passed, `FILTERS` is dumped to a default location within the project. """ if stream: stream.write(dumps()) else: path = os.path.join(os.path.dirname(insights._...
Dumps a string representation of `FILTERS` to a stream, normally an open file. If none is passed, `FILTERS` is dumped to a default location within the project.
def _parse_list(features, new_names): """Helping function of `_parse_features` that parses a list.""" feature_collection = OrderedDict() for feature in features: if isinstance(feature, FeatureType): feature_collection[feature] = ... elif isinstance...
Helping function of `_parse_features` that parses a list.
def set_messenger_theme(self, theme="default", location="default", max_messages="default"): """ Sets a theme for posting messages. Themes: ["flat", "future", "block", "air", "ice"] Locations: ["top_left", "top_center", "top_right", "bot...
Sets a theme for posting messages. Themes: ["flat", "future", "block", "air", "ice"] Locations: ["top_left", "top_center", "top_right", "bottom_left", "bottom_center", "bottom_right"] max_messages is the limit of concurrent messages to display.
def read_config(config_path): """read config_path and return options as dictionary""" result = {} with open(config_path, 'r') as fd: for line in fd.readlines(): if '=' in line: key, value = line.split('=', 1) try: result[key] = json.loa...
read config_path and return options as dictionary
def update_expiry(self, commit=True): """Update token's expiration datetime on every auth action.""" self.expires = update_expiry(self.created) if commit: self.save()
Update token's expiration datetime on every auth action.
def setval(key, val, dict_=None, delim=defaults.DEFAULT_DELIM): ''' Set a value under the dictionary hierarchy identified under the key. The target 'foo/bar/baz' returns the dictionary hierarchy {'foo': {'bar': {'baz': {}}}}. .. note:: Currently this doesn't work with integers, i.e. ...
Set a value under the dictionary hierarchy identified under the key. The target 'foo/bar/baz' returns the dictionary hierarchy {'foo': {'bar': {'baz': {}}}}. .. note:: Currently this doesn't work with integers, i.e. cannot build lists dynamically. TODO
def _convert_external(bundle, name, external): """ Converts external documentation to resource dict ready to save to CKAN. """ # http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create ret = { 'package_id': bundle.dataset.vid.lower(), 'url': external.url, 'descri...
Converts external documentation to resource dict ready to save to CKAN.
def plot_origin(array, origin, units, kpc_per_arcsec, zoom_offset_arcsec): """Plot the (y,x) origin ofo the array's coordinates as a 'x'. Parameters ----------- array : data.array.scaled_array.ScaledArray The 2D array of data which is plotted. origin : (float, float). The origin...
Plot the (y,x) origin ofo the array's coordinates as a 'x'. Parameters ----------- array : data.array.scaled_array.ScaledArray The 2D array of data which is plotted. origin : (float, float). The origin of the coordinate system of the array, which is plotted as an 'x' on the image if...
def add_formatter(self, tag_name, render_func, **kwargs): """ Installs a render function for the specified tag name. The render function should have the following signature: def render(tag_name, value, options, parent, context) The arguments are as follows: tag...
Installs a render function for the specified tag name. The render function should have the following signature: def render(tag_name, value, options, parent, context) The arguments are as follows: tag_name The name of the tag being rendered. value ...
def remove_observations_below_value(x, y, z, val=0): r"""Remove all x, y, and z where z is less than val. Will not destroy original values. Parameters ---------- x: array_like x coordinate. y: array_like y coordinate. z: array_like Observation value. val: float ...
r"""Remove all x, y, and z where z is less than val. Will not destroy original values. Parameters ---------- x: array_like x coordinate. y: array_like y coordinate. z: array_like Observation value. val: float Value at which to threshold z. Returns -...
def restart_program(): """ Restarts the current program. Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function. """ logging.debug("Restarting program...") python = sys.executable os.execl(python, python, * sys.argv)
Restarts the current program. Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function.
def _call(self, x, out=None): """Take the power of ``x`` and write to ``out`` if given.""" if out is None: return x ** self.exponent elif self.__domain_is_field: raise ValueError('cannot use `out` with field') else: out.assign(x) out **= se...
Take the power of ``x`` and write to ``out`` if given.
def _link_policy(self, role): """If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the appropriate managed policy to this Role. :param model.iam.IAMROle role: the execution role generated for the function """ policy_arn = self.get_polic...
If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the appropriate managed policy to this Role. :param model.iam.IAMROle role: the execution role generated for the function
def _get_string_and_set_width(self, combination, mode): """ Construct the string to be displayed and record the max width. """ show = "{}".format(self._separator(mode)).join(combination) show = show.rstrip("{}".format(self._separator(mode))) self.max_width = max([self.max...
Construct the string to be displayed and record the max width.
def _initSymbols(ptc): """ Helper function to initialize the single character constants and other symbols needed. """ ptc.timeSep = [ u':' ] ptc.dateSep = [ u'/' ] ptc.meridian = [ u'AM', u'PM' ] ptc.usesMeridian = True ptc.uses24 = False if pyicu and ptc.usePyICU: ...
Helper function to initialize the single character constants and other symbols needed.
def signature(f, s=None, block_size=RS_DEFAULT_BLOCK_LEN): """ Generate a signature for the file `f`. The signature will be written to `s`. If `s` is omitted, a temporary file will be used. This function returns the signature file `s`. You can specify the size of the blocks using the optional `block...
Generate a signature for the file `f`. The signature will be written to `s`. If `s` is omitted, a temporary file will be used. This function returns the signature file `s`. You can specify the size of the blocks using the optional `block_size` parameter.
def bibString(self, maxLength = 1000, WOSMode = False, restrictedOutput = False, niceID = True): """Makes a string giving the Record as a bibTex entry. If the Record is of a journal article (`PT J`) the bibtext type is set to `'article'`, otherwise it is set to `'misc'`. The ID of the entry is the WOS number an...
Makes a string giving the Record as a bibTex entry. If the Record is of a journal article (`PT J`) the bibtext type is set to `'article'`, otherwise it is set to `'misc'`. The ID of the entry is the WOS number and all the Record's fields are given as entries with their long names. **Note** This is not meant to...
def split_all_edges_between_two_vertices(self, vertex1, vertex2, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True): """ Splits all edges between two supplied vertices in current :class:`BreakpointGraph` instance with respect to t...
Splits all edges between two supplied vertices in current :class:`BreakpointGraph` instance with respect to the provided guidance. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__split_all_edges_between_two_vertices` method. :param vertex1: a first out of two vertices edges between which ar...
def get_xyz(self, xyz_axis=0): """Return a vector array of the x, y, and z coordinates. Parameters ---------- xyz_axis : int, optional The axis in the final array along which the x, y, z components should be stored (default: 0). Returns ------- ...
Return a vector array of the x, y, and z coordinates. Parameters ---------- xyz_axis : int, optional The axis in the final array along which the x, y, z components should be stored (default: 0). Returns ------- xs : `~astropy.units.Quantity` ...
def convert_pkt_to_json(pkg): """ convert_pkt_to_json Inspired by: https://gist.githubusercontent.com/cr0hn/1b0c2e672cd0721d3a07/raw/9144676ceb12dbd545e6dce366822bbedde8de2c/pkg_to_json.py This function convert a Scapy packet to JSON :param pkg: A kamene package :type pkg: objects :return:...
convert_pkt_to_json Inspired by: https://gist.githubusercontent.com/cr0hn/1b0c2e672cd0721d3a07/raw/9144676ceb12dbd545e6dce366822bbedde8de2c/pkg_to_json.py This function convert a Scapy packet to JSON :param pkg: A kamene package :type pkg: objects :return: A JSON data :rtype: dict()
def n_queens(queen_count): """N-Queens solver. Args: queen_count: the number of queens to solve for. This is also the board size. Yields: Solutions to the problem. Each yielded value is looks like (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the ...
N-Queens solver. Args: queen_count: the number of queens to solve for. This is also the board size. Yields: Solutions to the problem. Each yielded value is looks like (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the queen, and the index into ...
def issues_closed_since(period=timedelta(days=365), project="arokem/python-matlab-bridge", pulls=False): """Get all issues closed since a particular point in time. period can either be a datetime object, or a timedelta object. In the latter case, it is used as a time before the present. """ which =...
Get all issues closed since a particular point in time. period can either be a datetime object, or a timedelta object. In the latter case, it is used as a time before the present.
def get_field_mappings(self, field): """Converts ES field mappings to .kibana field mappings""" retdict = {} retdict['indexed'] = False retdict['analyzed'] = False for (key, val) in iteritems(field): if key in self.mappings: if (key == 'type' and ...
Converts ES field mappings to .kibana field mappings
def _on_click(self, *args): """ Function bound to double click on Listbox that calls the callback if a valid callback object is passed :param args: Tkinter event """ if callable(self._callback): self._callback(self.selection)
Function bound to double click on Listbox that calls the callback if a valid callback object is passed :param args: Tkinter event
def update(dest, variation, path=None): """ Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values from variation :param dest: :param variation: :param path: :return: """ if dest is None: r...
Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values from variation :param dest: :param variation: :param path: :return:
def get_within_delta(key, app=None): """Get a timedelta object from the application configuration following the internal convention of:: <Amount of Units> <Type of Units> Examples of valid config values:: 5 days 10 minutes :param key: The config value key without the 'SECURIT...
Get a timedelta object from the application configuration following the internal convention of:: <Amount of Units> <Type of Units> Examples of valid config values:: 5 days 10 minutes :param key: The config value key without the 'SECURITY_' prefix :param app: Optional applicat...
def handle_effect_results(permutation_result): """Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFr...
Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFrame formatted output suitable to save
def find_by_token(self, token, salt=None, max_age=None): """Loads a user instance identified by the token generated using generate_user_token() """ model = current_app.features.models[self.options["model"]] try: id = self.token_serializer.loads(token, salt=salt, max_age=max_a...
Loads a user instance identified by the token generated using generate_user_token()
def _get_oxm_field_int(self): """Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and ...
Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and the enum has no such valu...
def _map_unity_proxy_to_object(value): """ Map returning value, if it is unity SFrame, SArray, map it """ vtype = type(value) if vtype in _proxy_map: return _proxy_map[vtype](value) elif vtype == list: return [_map_unity_proxy_to_object(v) for v in value] elif vtype == dict: ...
Map returning value, if it is unity SFrame, SArray, map it
def split_subquery(sql): """Split on subqueries and replace them by '&'.""" sql, params = mark_quoted_strings(sql) sql = simplify_expression(sql) _ = params # NOQA start = 0 out = [] subqueries = [] pattern = re.compile(r'\(SELECT\b', re.I) match = pattern.search(sql, start) whi...
Split on subqueries and replace them by '&'.
def stop(dev=None): ''' Stop a bcache device If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped. .. warning:: 'Stop' on an individual backing device means hard-stop; no attempt at flushing will be done and the bcache device wil...
Stop a bcache device If no device is given, all backing devices will be detached from the cache, which will subsequently be stopped. .. warning:: 'Stop' on an individual backing device means hard-stop; no attempt at flushing will be done and the bcache device will seemingly 'disappear' from the...
def repr2_json(obj_, **kwargs): """ hack for json reprs """ import utool as ut kwargs['trailing_sep'] = False json_str = ut.repr2(obj_, **kwargs) json_str = str(json_str.replace('\'', '"')) json_str = json_str.replace('(', '[') json_str = json_str.replace(')', ']') json_str = json_str.re...
hack for json reprs
def type_inherits_of_type(inheriting_type, base_type): """Checks whether inheriting_type inherits from base_type :param str inheriting_type: :param str base_type: :return: True is base_type is base of inheriting_type """ assert isinstance(inheriting_type, type) or isclass(inheriting_type) a...
Checks whether inheriting_type inherits from base_type :param str inheriting_type: :param str base_type: :return: True is base_type is base of inheriting_type
def configure_extensions(app): """Configure Flask extensions.""" extensions.toolbar.init_app(app) extensions.bootstrap.init_app(app) extensions.mongo.init_app(app) extensions.store.init_app(app) extensions.login_manager.init_app(app) extensions.oauth.init_app(app) extensions.mail.init_ap...
Configure Flask extensions.
def getCompoundIdForFeatureId(self, featureId): """ Returns server-style compound ID for an internal featureId. :param long featureId: id of feature in database :return: string representing ID for the specified GA4GH protocol Feature object in this FeatureSet. """ ...
Returns server-style compound ID for an internal featureId. :param long featureId: id of feature in database :return: string representing ID for the specified GA4GH protocol Feature object in this FeatureSet.
def load(self, patterns, dirs, ignore=None, **kwargs): """Load objects from the filesystem into the ``paths`` dictionary. If the setting ``autoapi_patterns`` was not specified, look for a ``docfx.json`` file by default. A ``docfx.json`` should be treated as the canonical source before ...
Load objects from the filesystem into the ``paths`` dictionary. If the setting ``autoapi_patterns`` was not specified, look for a ``docfx.json`` file by default. A ``docfx.json`` should be treated as the canonical source before the default patterns. Fallback to default pattern matches...
def rdf_graph_from_yaml(yaml_root): """Convert the YAML object into an RDF Graph object.""" G = Graph() for top_entry in yaml_root: assert len(top_entry) == 1 node = list(top_entry.keys())[0] build_relations(G, node, top_entry[node], None) return G
Convert the YAML object into an RDF Graph object.
def parse_event_files_spec(logdir): """Parses `logdir` into a map from paths to run group names. The events files flag format is a comma-separated list of path specifications. A path specification either looks like 'group_name:/path/to/directory' or '/path/to/directory'; in the latter case, the group is unname...
Parses `logdir` into a map from paths to run group names. The events files flag format is a comma-separated list of path specifications. A path specification either looks like 'group_name:/path/to/directory' or '/path/to/directory'; in the latter case, the group is unnamed. Group names cannot start with a forw...