code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def on_button_release(self, event):
"""Write back changes
If one or more items have been moved, the new position are stored in the corresponding meta data and a signal
notifying the change is emitted.
:param event: The button event
"""
affected_models = {}
for ... | Write back changes
If one or more items have been moved, the new position are stored in the corresponding meta data and a signal
notifying the change is emitted.
:param event: The button event |
def attribute_exists(self, attribute, section):
"""
Checks if given attribute exists.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = Sect... | Checks if given attribute exists.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = cont... |
def preShear(self, h, v):
"""Calculate pre shearing and replace current matrix."""
a, b = self.a, self.b
self.a += v * self.c
self.b += v * self.d
self.c += h * a
self.d += h * b
return self | Calculate pre shearing and replace current matrix. |
def add_target(self, name=None):
"""
Add an SCons target to this nest.
The function decorated will be immediately called with each of the
output directories and current control dictionaries. Each result will
be added to the respective control dictionary for later nests to
... | Add an SCons target to this nest.
The function decorated will be immediately called with each of the
output directories and current control dictionaries. Each result will
be added to the respective control dictionary for later nests to
access.
:param name: Name for the target i... |
def logstop(self):
"""Fully stop logging and close log file.
In order to start logging again, a new logstart() call needs to be
made, possibly (though not necessarily) with a new filename, mode and
other options."""
if self.logfile is not None:
self.logfile.close()
... | Fully stop logging and close log file.
In order to start logging again, a new logstart() call needs to be
made, possibly (though not necessarily) with a new filename, mode and
other options. |
def update_ip(self, ip, record_type='A', domains=None, subdomains=None):
"""Update the IP address in all records, specified by type, to the value of ip. Returns True if no
exceptions occurred during the update. If no domains are provided, all domains returned from
self.get_domains() will be up... | Update the IP address in all records, specified by type, to the value of ip. Returns True if no
exceptions occurred during the update. If no domains are provided, all domains returned from
self.get_domains() will be updated. By default, only A records are updated.
:param record_type: The typ... |
def initialize(self, runtime=None):
"""Initializes this manager.
A manager is initialized once at the time of creation.
arg: runtime (osid.OsidRuntimeManager): the runtime
environment
raise: CONFIGURATION_ERROR - an error with implementation
configurat... | Initializes this manager.
A manager is initialized once at the time of creation.
arg: runtime (osid.OsidRuntimeManager): the runtime
environment
raise: CONFIGURATION_ERROR - an error with implementation
configuration
raise: ILLEGAL_STATE - this manage... |
def _encrypt(self, archive):
"""Encrypts the compressed archive using GPG.
If encryption fails for any reason, it should be logged by sos but not
cause execution to stop. The assumption is that the unencrypted archive
would still be of use to the user, and/or that the end user has anoth... | Encrypts the compressed archive using GPG.
If encryption fails for any reason, it should be logged by sos but not
cause execution to stop. The assumption is that the unencrypted archive
would still be of use to the user, and/or that the end user has another
means of securing the archive... |
def request(
self,
url: str,
method: str,
raise_for_status: bool = True,
path_to_errors: tuple = None,
*args,
**kwargs
) -> tuple:
"""
A wrapper method for :meth:`~requests.Session.request``, which adds some defaults and logging
:param... | A wrapper method for :meth:`~requests.Session.request``, which adds some defaults and logging
:param url: The URL to send the reply to
:param method: The method to use
:param raise_for_status: Should an exception be raised for a failed response. Default is **True**
:param args: Addition... |
def p_bound_terminal(self, p):
"""bound_terminal : unbound_terminal"""
if p[1][0].literal in ['*', '**']:
p[0] = [_Segment(_BINDING, '$%d' % self.binding_var_count),
p[1][0],
_Segment(_END_BINDING, '')]
self.binding_var_count += 1
e... | bound_terminal : unbound_terminal |
def prepare_video_params(self, title=None, tags='Others', description='',
copyright_type='original', public_type='all',
category=None, watch_password=None,
latitude=None, longitude=None, shoot_time=None
)... | util method for create video params to upload.
Only need to provide a minimum of two essential parameters:
title and tags, other video params are optional. All params spec
see: http://cloud.youku.com/docs?id=110#create .
Args:
title: string, 2-50 characters.
tag... |
def detect_fts(conn, table):
"Detect if table has a corresponding FTS virtual table and return it"
rows = conn.execute(detect_fts_sql(table)).fetchall()
if len(rows) == 0:
return None
else:
return rows[0][0] | Detect if table has a corresponding FTS virtual table and return it |
def generate(self):
'''
Generate noise samples.
Returns:
`np.ndarray` of samples.
'''
sampled_arr = np.zeros((self.__batch_size, self.__channel, self.__seq_len, self.__dim))
for batch in range(self.__batch_size):
for i in range(... | Generate noise samples.
Returns:
`np.ndarray` of samples. |
def fields(cls):
"""
Return the tuple of ``attrs`` attributes for a class.
The tuple also allows accessing the fields by their names (see below for
examples).
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *... | Return the tuple of ``attrs`` attributes for a class.
The tuple also allows accessing the fields by their names (see below for
examples).
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
... |
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
... | Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not. |
def wait_until_finished(
self, refresh_period=DEFAULT_TASK_INSTANCE_WAIT_REFRESH_PERIOD
):
"""Wait until a task instance with the given UUID is finished.
Args:
refresh_period (int, optional): How many seconds to wait
before checking the task's status. Defaults to... | Wait until a task instance with the given UUID is finished.
Args:
refresh_period (int, optional): How many seconds to wait
before checking the task's status. Defaults to 5
seconds.
Returns:
:class:`saltant.models.base_task_instance.BaseTaskInstan... |
def refresh(self):
"""
explicitely refresh user interface; useful when changing widgets dynamically
"""
logger.debug("refresh user interface")
try:
with self.refresh_lock:
self.draw_screen()
except AssertionError:
logger.warning("ap... | explicitely refresh user interface; useful when changing widgets dynamically |
def from_path(cls, path, suffix=''):
"""
Convenience method to run critic2 analysis on a folder containing
typical VASP output files.
This method will:
1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped
counterparts.
2. If AECCAR* files are present,... | Convenience method to run critic2 analysis on a folder containing
typical VASP output files.
This method will:
1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped
counterparts.
2. If AECCAR* files are present, constructs a temporary reference
file as AECCAR0... |
def close_event(self, id, **kwargs): # noqa: E501
"""Close a specific event # 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.close_event(id, async_req=True)
... | Close a specific event # 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.close_event(id, async_req=True)
>>> result = thread.get()
:param async_req bool... |
def get_binary_property(value, is_bytes=False):
"""Get `BINARY` property."""
obj = unidata.ascii_binary if is_bytes else unidata.unicode_binary
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['binary'].get(negated, negated)
else:
value = unidat... | Get `BINARY` property. |
def outgoing_args(self, nodeid):
"""
Return the arguments going from *nodeid* to other predications.
Valid arguments include regular variable arguments and scopal
(label-selecting or HCONS) arguments. MOD/EQ
links, intrinsic arguments, and constant arguments are not
incl... | Return the arguments going from *nodeid* to other predications.
Valid arguments include regular variable arguments and scopal
(label-selecting or HCONS) arguments. MOD/EQ
links, intrinsic arguments, and constant arguments are not
included.
Args:
nodeid: the nodeid o... |
def console_get_char(con: tcod.console.Console, x: int, y: int) -> int:
"""Return the character at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.ch`.
"""
return lib.TCOD_console_get_char(_console(con),... | Return the character at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.ch`. |
def gtd7(Input, flags, output):
'''The standard model subroutine (GTD7) always computes the
‘‘thermospheric’’ mass density by explicitly summing the masses of
the species in equilibrium at the thermospheric temperature T(z).
'''
mn3 = 5
zn3 = [32.5,20.0,15.0,10.0,0.0]
mn2 = 4
zn2 = [72.... | The standard model subroutine (GTD7) always computes the
‘‘thermospheric’’ mass density by explicitly summing the masses of
the species in equilibrium at the thermospheric temperature T(z). |
def calculate_sunrise_sunset(self, month, day, depression=0.833,
is_solar_time=False):
"""Calculate sunrise, noon and sunset.
Return:
A dictionary. Keys are ("sunrise", "noon", "sunset")
"""
datetime = DateTime(month, day, hour=12, leap_year=... | Calculate sunrise, noon and sunset.
Return:
A dictionary. Keys are ("sunrise", "noon", "sunset") |
def parse_pattern(pattern):
"""Parse number format patterns"""
if isinstance(pattern, NumberPattern):
return pattern
def _match_number(pattern):
rv = number_re.search(pattern)
if rv is None:
raise ValueError('Invalid number pattern %r' % pattern)
return rv.groups... | Parse number format patterns |
def enviar_dados_venda(self, dados_venda):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.enviar_dados_venda`.
:return: Uma resposta SAT especializada em ``EnviarDadosVenda``.
:rtype: satcfe.resposta.enviardadosvenda.RespostaEnviarDadosVenda
"""
resp = self._http_post('enviardadosve... | Sobrepõe :meth:`~satcfe.base.FuncoesSAT.enviar_dados_venda`.
:return: Uma resposta SAT especializada em ``EnviarDadosVenda``.
:rtype: satcfe.resposta.enviardadosvenda.RespostaEnviarDadosVenda |
def customCompute(self, recordNum, patternNZ, classification):
"""
Just return the inference value from one input sample. The actual
learning happens in compute() -- if, and only if learning is enabled --
which is called when you run the network.
.. warning:: This method is deprecated and exists on... | Just return the inference value from one input sample. The actual
learning happens in compute() -- if, and only if learning is enabled --
which is called when you run the network.
.. warning:: This method is deprecated and exists only to maintain backward
compatibility. This method is deprecated, a... |
def clear(self):
'''
Reset the current HyperLogLog to empty.
'''
self.reg = np.zeros((self.m,), dtype=np.int8) | Reset the current HyperLogLog to empty. |
def enable_cloud_integration(self, id, **kwargs): # noqa: E501
"""Enable a specific cloud integration # 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.enable_c... | Enable a specific cloud integration # 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.enable_cloud_integration(id, async_req=True)
>>> result = thread.get()
... |
def get_paths(folder):
'''Return *_phase.txt files in `folder`'''
folder = pathlib.Path(folder).resolve()
files = folder.rglob("*_phase.txt")
return sorted(files) | Return *_phase.txt files in `folder` |
def get_cube(self, name):
""" Given a cube name, construct that cube and return it. Do not
overwrite this method unless you need to. """
return Cube(self.get_engine(), name, self.get_cube_model(name)) | Given a cube name, construct that cube and return it. Do not
overwrite this method unless you need to. |
def load_if(s):
"""Load either a filename, or a string representation of yml/json."""
is_data_file = s.endswith('.json') or s.endswith('.yml')
return load(s) if is_data_file else loads(s) | Load either a filename, or a string representation of yml/json. |
def __download_from_s3(self, key, dest_dir):
"""Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the spec... | Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:param key: (str) S3... |
def plot_projected_dos(self, pdos_indices=None, legend=None):
"""Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
... | Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
pdos_indices=[[0, 1], [2, 3, 4, 5]]
Default is No... |
def delete_terms_indexes(es, index_name: str = "terms_*"):
"""Delete all terms indexes"""
try:
es.indices.delete(index=index_name)
except Exception as e:
log.error(f"Could not delete all terms indices: {e}") | Delete all terms indexes |
def header_little_endian(self):
"""Return the header_little_endian attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.HEADER_LITTLE_EN... | Return the header_little_endian attribute of the BFD file being
processed. |
def drop(self):
"""
Remove this node from the taxonomy, maintaining child subtrees by
adding them to the node's parent, and moving sequences at this node
to the parent.
Not valid for root node.
"""
if self.is_root:
raise ValueError("Cannot drop root n... | Remove this node from the taxonomy, maintaining child subtrees by
adding them to the node's parent, and moving sequences at this node
to the parent.
Not valid for root node. |
def returner(load):
'''
Return data to the local job cache
'''
serial = salt.payload.Serial(__opts__)
# if a minion is returning a standalone job, get a jobid
if load['jid'] == 'req':
load['jid'] = prep_jid(nocache=load.get('nocache', False))
jid_dir = salt.utils.jid.jid_dir(load['... | Return data to the local job cache |
def merge_dicts(dict_a, dict_b):
"""Deep merge of two dicts"""
obj = {}
for key, value in iteritems(dict_a):
if key in dict_b:
if isinstance(dict_b[key], dict):
obj[key] = merge_dicts(value, dict_b.pop(key))
else:
obj[key] = value
for key, value i... | Deep merge of two dicts |
def calcSMAfromT(self, epsilon=0.7):
""" Calculates the semi-major axis based on planet temperature
"""
return eq.MeanPlanetTemp(self.albedo(), self.star.T, self.star.R, epsilon, self.T).a | Calculates the semi-major axis based on planet temperature |
def click_text(self, text, exact_match=False):
"""Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`` and you ... | Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`` and you do not want first one,
use `locator` with `Get Web... |
def xor_key(first, second, trafaret):
"""
xor_key - takes `first` and `second` key names and `trafaret`.
Checks if we have only `first` or only `second` in data, not both,
and at least one.
Then checks key value against trafaret.
"""
trafaret = t.Trafaret._trafaret(trafaret)
def check... | xor_key - takes `first` and `second` key names and `trafaret`.
Checks if we have only `first` or only `second` in data, not both,
and at least one.
Then checks key value against trafaret. |
def create_inputs(inspecs):
"""Create input :obj:`nnabla.Variable` from :obj:`Inspec`.
Args:
inspecs (:obj:`list` of :obj:`Inspec`): A list of ``Inspec``.
Returns:
:obj:`list` of :obj:`nnabla.Variable`: Input variables.
"""
ret = []
for i in inspecs:
v = nn.Variable(i.... | Create input :obj:`nnabla.Variable` from :obj:`Inspec`.
Args:
inspecs (:obj:`list` of :obj:`Inspec`): A list of ``Inspec``.
Returns:
:obj:`list` of :obj:`nnabla.Variable`: Input variables. |
def and_join(strings):
"""Join the given ``strings`` by commas with last `' and '` conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
:param strings: a list of words to join
:type string: :class:`collections.abc.Sequence`
:returns: a joined string... | Join the given ``strings`` by commas with last `' and '` conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
:param strings: a list of words to join
:type string: :class:`collections.abc.Sequence`
:returns: a joined string
:rtype: :class:`str`, :cl... |
def add_missing_price_information_message(request, item):
"""
Add a message to the Django messages store indicating that we failed to retrieve price information about an item.
:param request: The current request.
:param item: The item for which price information is missing. Example: a program title, or... | Add a message to the Django messages store indicating that we failed to retrieve price information about an item.
:param request: The current request.
:param item: The item for which price information is missing. Example: a program title, or a course. |
def new_address(self, sender=None, nonce=None):
"""Create a fresh 160bit address"""
if sender is not None and nonce is None:
nonce = self.get_nonce(sender)
new_address = self.calculate_new_address(sender, nonce)
if sender is None and new_address in self:
return s... | Create a fresh 160bit address |
def animate_correlation_matrix(sync_output_dynamic, animation_velocity = 75, colormap = 'cool', save_movie = None):
"""!
@brief Shows animation of correlation matrix between oscillators during simulation.
@param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync netw... | !
@brief Shows animation of correlation matrix between oscillators during simulation.
@param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network.
@param[in] animation_velocity (uint): Interval between frames in milliseconds.
@param[in] colormap (strin... |
async def wasSet(self, node, oldv):
'''
Fire the onset() handlers for this property.
Args:
node (synapse.lib.node.Node): The node whose property was set.
oldv (obj): The previous value of the property.
'''
for func in self.onsets:
try:
... | Fire the onset() handlers for this property.
Args:
node (synapse.lib.node.Node): The node whose property was set.
oldv (obj): The previous value of the property. |
def _make_cache_key(key_prefix):
"""Make cache key from prefix
Borrowed from Flask-Cache extension
"""
if callable(key_prefix):
cache_key = key_prefix()
elif '%s' in key_prefix:
cache_key = key_prefix % request.path
else:
cache_key = key_prefix
cache_key = cache_key.... | Make cache key from prefix
Borrowed from Flask-Cache extension |
def fig_kernel_lfp_EITN_II(savefolders, params, transient=200, T=[800., 1000.], X='L5E',
lags=[20, 20], channels=[0,3,7,11,13]):
'''
This function calculates the STA of LFP, extracts kernels and recontructs the LFP from kernels.
Arguments
::
transient : the time in millis... | This function calculates the STA of LFP, extracts kernels and recontructs the LFP from kernels.
Arguments
::
transient : the time in milliseconds, after which the analysis should begin
so as to avoid any starting transients
X : id of presynaptic trigger population |
def log_to_ganttplot(execution_history_items):
"""
Example how to use the DataFrame representation
"""
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np
d = log_to_DataFrame(execution_history_items)
# de-duplicate states and make mapping from state to ... | Example how to use the DataFrame representation |
def AddArg(self, arg):
"""Adds a new arg to this expression.
Args:
arg: The argument to add (string).
Returns:
True if this arg is the last arg, False otherwise.
Raises:
ParseError: If there are too many args.
"""
self.args.append(arg)
if len(self.args) > self.number_of... | Adds a new arg to this expression.
Args:
arg: The argument to add (string).
Returns:
True if this arg is the last arg, False otherwise.
Raises:
ParseError: If there are too many args. |
def get_area(self):
"""
Compute area as the sum of the mesh cells area values.
"""
mesh = self.mesh
_, _, _, area = mesh.get_cell_dimensions()
return numpy.sum(area) | Compute area as the sum of the mesh cells area values. |
def find_prefix(self, iri: Union[URIRef, Literal, str]) -> Union[None, str]:
""" Finds if uri is in common_namespaces
Auto adds prefix if incoming iri has a uri in common_namespaces. If its not in the local
library, then it will just be spit out as the iri and not saved/condensed into qualified... | Finds if uri is in common_namespaces
Auto adds prefix if incoming iri has a uri in common_namespaces. If its not in the local
library, then it will just be spit out as the iri and not saved/condensed into qualified
names.
The reason for the maxes is find the longest string match. This ... |
def replace(self, name, newname):
"""
Replace all occurrences of name with newname
"""
if not re.match("[a-zA-Z]\w*", name):
return None
if not re.match("[a-zA-Z]\w*", newname):
return None
def _replace(match):
return match.group(0).re... | Replace all occurrences of name with newname |
def columns_used(self):
"""
Returns all the columns used in this model for filtering
and in the model expression.
"""
return list(tz.unique(tz.concatv(
util.columns_in_filters(self.fit_filters),
util.columns_in_filters(self.predict_filters),
u... | Returns all the columns used in this model for filtering
and in the model expression. |
def register_on_serial_port_changed(self, callback):
"""Set the callback function to consume on serial port changed events.
Callback receives a ISerialPortChangedEvent object.
Returns the callback_id
"""
event_type = library.VBoxEventType.on_serial_port_changed
return s... | Set the callback function to consume on serial port changed events.
Callback receives a ISerialPortChangedEvent object.
Returns the callback_id |
def decode(s, cls=PENMANCodec, **kwargs):
"""
Deserialize PENMAN-serialized *s* into its Graph object
Args:
s: a string containing a single PENMAN-serialized graph
cls: serialization codec class
kwargs: keyword arguments passed to the constructor of *cls*
Returns:
the Gr... | Deserialize PENMAN-serialized *s* into its Graph object
Args:
s: a string containing a single PENMAN-serialized graph
cls: serialization codec class
kwargs: keyword arguments passed to the constructor of *cls*
Returns:
the Graph object described by *s*
Example:
>>> ... |
def all(
self,
count=500,
offset=0,
type=None,
inactive=None,
emailFilter=None,
tag=None,
messageID=None,
fromdate=None,
todate=None,
):
"""
Returns many bounces.
:param int count: Number of bounces to return pe... | Returns many bounces.
:param int count: Number of bounces to return per request.
:param int offset: Number of bounces to skip.
:param str type: Filter by type of bounce.
:param bool inactive: Filter by emails that were deactivated by Postmark due to the bounce.
:param str emailF... |
def _get_menu_width(self, max_width, complete_state):
"""
Return the width of the main column.
"""
return min(max_width, max(self.MIN_WIDTH, max(get_cwidth(c.display)
for c in complete_state.current_completions) + 2)) | Return the width of the main column. |
def info_factory(name, libnames, headers, frameworks=None,
section=None, classname=None):
"""Create a system_info class.
Parameters
----------
name : str
name of the library
libnames : seq
list of libraries to look for
headers : seq
... | Create a system_info class.
Parameters
----------
name : str
name of the library
libnames : seq
list of libraries to look for
headers : seq
list of headers to look for
classname : str
name of the returned class
section : st... |
def add_hookcall_monitoring(self, before, after):
""" add before/after tracing functions for all hooks
and return an undo function which, when called,
will remove the added tracers.
``before(hook_name, hook_impls, kwargs)`` will be called ahead
of all hook calls and receive a ho... | add before/after tracing functions for all hooks
and return an undo function which, when called,
will remove the added tracers.
``before(hook_name, hook_impls, kwargs)`` will be called ahead
of all hook calls and receive a hookcaller instance, a list
of HookImpl instances and th... |
def create_geoms(self, gdefs, plot):
"""
Add geoms to the guide definitions
"""
new_gdefs = []
for gdef in gdefs:
gdef = gdef.create_geoms(plot)
if gdef:
new_gdefs.append(gdef)
return new_gdefs | Add geoms to the guide definitions |
def unmarshal(self, values, bind_client=None):
"""
Cast the list.
"""
if values is not None:
return [super(EntityCollection, self).unmarshal(v, bind_client=bind_client) for v in values] | Cast the list. |
def openidf(fname, idd=None, epw=None):
"""automatically set idd and open idf file. Uses version from idf to set correct idd
It will work under the following circumstances:
- the IDF file should have the VERSION object.
- Needs the version of EnergyPlus installed that matches the IDF version.
... | automatically set idd and open idf file. Uses version from idf to set correct idd
It will work under the following circumstances:
- the IDF file should have the VERSION object.
- Needs the version of EnergyPlus installed that matches the IDF version.
- Energyplus should be installed in the default... |
def get_subparser(self, name):
"""
Convenience method to get a certain subparser
Parameters
----------
name: str
The name of the subparser
Returns
-------
FuncArgParser
The subparsers corresponding to `name`
"""
if... | Convenience method to get a certain subparser
Parameters
----------
name: str
The name of the subparser
Returns
-------
FuncArgParser
The subparsers corresponding to `name` |
def map_value(self, value, gid):
"""
Return the value for a group id, applying requested mapping.
Map only groups related to a filter, ie when the basename of
the group is identical to the name of a filter.
"""
base_gid = self.base_gid_pattern.search(gid).group(1)
... | Return the value for a group id, applying requested mapping.
Map only groups related to a filter, ie when the basename of
the group is identical to the name of a filter. |
def request(self, hash_, quickkey, doc_type, page=None,
output=None, size_id=None, metadata=None,
request_conversion_only=None):
"""Query conversion server
hash_: 4 characters of file hash
quickkey: File quickkey
doc_type: "i" for image, "d" for documents... | Query conversion server
hash_: 4 characters of file hash
quickkey: File quickkey
doc_type: "i" for image, "d" for documents
page: The page to convert. If page is set to 'initial', the first
10 pages of the document will be provided. (document)
output: "pdf", "img",... |
def queryset(self, request, queryset):
"""
Return the filtered queryset based on the value provided in the query string.
source: https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
"""
if self.value() is None:
return queryset.all()
else:
return querys... | Return the filtered queryset based on the value provided in the query string.
source: https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter |
def _map_update(
self,
prior_mean,
prior_cov,
global_cov_scaled,
new_observation):
"""Maximum A Posterior (MAP) update of a parameter
Parameters
----------
prior_mean : float or 1D array
Prior mean of parameters.
... | Maximum A Posterior (MAP) update of a parameter
Parameters
----------
prior_mean : float or 1D array
Prior mean of parameters.
prior_cov : float or 1D array
Prior variance of scalar parameter, or
prior covariance of multivariate parameter
g... |
def coord2healpix(coords, frame, nside, nest=True):
"""
Calculate HEALPix indices from an astropy SkyCoord. Assume the HEALPix
system is defined on the coordinate frame ``frame``.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The input coordinates.
frame (:obj:`str`): The frame in... | Calculate HEALPix indices from an astropy SkyCoord. Assume the HEALPix
system is defined on the coordinate frame ``frame``.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The input coordinates.
frame (:obj:`str`): The frame in which the HEALPix system is defined.
nside (:obj:`int`)... |
def lookup(self, host_value):
"""Get a host value matching the given value.
:param host_value: a value of the host of a type that can be
listed by the service
:returns: an instance of AddressListItem representing
a matched value
:raises InvalidHostError: if the argument ... | Get a host value matching the given value.
:param host_value: a value of the host of a type that can be
listed by the service
:returns: an instance of AddressListItem representing
a matched value
:raises InvalidHostError: if the argument is not a valid
host string |
def _hide_column(self, column):
'''Hides a column by prefixing the name with \'__\''''
column = _ensure_string_from_expression(column)
new_name = self._find_valid_name('__' + column)
self._rename(column, new_name) | Hides a column by prefixing the name with \'__\ |
def create_question_dialog(self, text, second_text):
"""
Function creates a question dialog with title text
and second_text
"""
dialog = self.create_message_dialog(
text, buttons=Gtk.ButtonsType.YES_NO, icon=Gtk.MessageType.QUESTION
)
dialog.format_sec... | Function creates a question dialog with title text
and second_text |
def recv_sub(self, id_, name, params):
"""DDP sub handler."""
self.api.sub(id_, name, *params) | DDP sub handler. |
def vpc_peering_connection_present(name, requester_vpc_id=None, requester_vpc_name=None,
peer_vpc_id=None, peer_vpc_name=None, conn_name=None,
peer_owner_id=None, peer_region=None, region=None,
key=None, keyid=None,... | name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id.
peer_vpc_id
ID of the VPC tp crete VPC peering connection with. This can be a VPC in
... |
def list_required(self, type=None, service=None): # pylint: disable=redefined-builtin
"""
Displays all packages required by the current role
based on the documented services provided.
"""
from burlap.common import (
required_system_packages,
required_pytho... | Displays all packages required by the current role
based on the documented services provided. |
async def on_raw_kick(self, message):
""" KICK command. """
kicker, kickermeta = self._parse_user(message.source)
self._sync_user(kicker, kickermeta)
if len(message.params) > 2:
channels, targets, reason = message.params
else:
channels, targets = message.... | KICK command. |
def _derive_temporalnetwork(self, f, i, tag, params, confounds_exist, confound_files):
"""
Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing.
"""
data = load_tabular_file(f, index_col=True, header=True)
fs, _ = drop_bids_suffix(f)
save_name, ... | Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing. |
def from_settings(cls, settings):
"""Read Mongodb Source configuration from the provided settings"""
if not 'mongodb' in settings or not 'collection' in settings or \
settings['mongodb'] == '' or settings['collection'] == '':
raise Exception(
"Erroneous mongod... | Read Mongodb Source configuration from the provided settings |
def assign(var, new_val, assign_fn=assign_slice):
"""Assign a new value to a variable.
Args:
var: either a Variable operation or its output Tensor.
new_val: a Tensor
assign_fn: a function from
(mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation
Returns:
an Operation
Raises:
Value... | Assign a new value to a variable.
Args:
var: either a Variable operation or its output Tensor.
new_val: a Tensor
assign_fn: a function from
(mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation
Returns:
an Operation
Raises:
ValueError: if var is not a Variable and var.operation is no... |
def date_between(self, start_date='-30y', end_date='today'):
"""
Get a Date object based on a random date between two given dates.
Accepts date strings that can be recognized by strtotime().
:param start_date Defaults to 30 years ago
:param end_date Defaults to "today"
:... | Get a Date object based on a random date between two given dates.
Accepts date strings that can be recognized by strtotime().
:param start_date Defaults to 30 years ago
:param end_date Defaults to "today"
:example Date('1999-02-02')
:return Date |
def heating_degree_days(T, T_base=F2K(65), truncate=True):
r'''Calculates the heating degree days for a period of time.
.. math::
\text{heating degree days} = max(T - T_{base}, 0)
Parameters
----------
T : float
Measured temperature; sometimes an average over a length of time is us... | r'''Calculates the heating degree days for a period of time.
.. math::
\text{heating degree days} = max(T - T_{base}, 0)
Parameters
----------
T : float
Measured temperature; sometimes an average over a length of time is used,
other times the average of the lowest and highest t... |
def setHeight(self, vehID, height):
"""setHeight(string, double) -> None
Sets the height in m for this vehicle.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_HEIGHT, vehID, height) | setHeight(string, double) -> None
Sets the height in m for this vehicle. |
def get_apex(self, lat, height=None):
""" Calculate apex height
Parameters
-----------
lat : (float)
Latitude in degrees
height : (float or NoneType)
Height above the surface of the earth in km or NoneType to use
reference height (default=None... | Calculate apex height
Parameters
-----------
lat : (float)
Latitude in degrees
height : (float or NoneType)
Height above the surface of the earth in km or NoneType to use
reference height (default=None)
Returns
----------
apex... |
def navigate(self):
"""Return the longitudes and latitudes of the scene.
"""
tic = datetime.now()
lons40km = self._data["pos"][:, :, 1] * 1e-4
lats40km = self._data["pos"][:, :, 0] * 1e-4
try:
from geotiepoints import SatelliteInterpolator
except Impo... | Return the longitudes and latitudes of the scene. |
def app_token(vault_client, app_id, user_id):
"""Returns a vault token based on the app and user id."""
resp = vault_client.auth_app_id(app_id, user_id)
if 'auth' in resp and 'client_token' in resp['auth']:
return resp['auth']['client_token']
else:
raise aomi.exceptions.AomiCredentials('... | Returns a vault token based on the app and user id. |
def delete(self, hdfs_path, recursive=False):
"""Delete a file located at `hdfs_path`."""
return self.client.delete(hdfs_path, recursive=recursive) | Delete a file located at `hdfs_path`. |
def linearBlend(img1, img2, overlap, backgroundColor=None):
'''
Stitch 2 images vertically together.
Smooth the overlap area of both images with a linear fade from img1 to img2
@param img1: numpy.2dArray
@param img2: numpy.2dArray of the same shape[1,2] as img1
@param overlap: number of ... | Stitch 2 images vertically together.
Smooth the overlap area of both images with a linear fade from img1 to img2
@param img1: numpy.2dArray
@param img2: numpy.2dArray of the same shape[1,2] as img1
@param overlap: number of pixels both images overlap
@returns: stitched-image |
def set_level(logger=None, log_level=None):
'''Set logging levels using logger names.
:param logger: Name of the logger
:type logger: String
:param log_level: A string or integer corresponding to a Python logging level
:type log_level: String
:rtype: None
'''
log_level = logging.getL... | Set logging levels using logger names.
:param logger: Name of the logger
:type logger: String
:param log_level: A string or integer corresponding to a Python logging level
:type log_level: String
:rtype: None |
def get_dated_items(self):
"""
Override get_dated_items to add a useful 'week_end_day'
variable in the extra context of the view.
"""
self.date_list, self.object_list, extra_context = super(
EntryWeek, self).get_dated_items()
self.date_list = self.get_date_lis... | Override get_dated_items to add a useful 'week_end_day'
variable in the extra context of the view. |
def check_text(self, text):
"""Disable empty layout name possibility"""
if to_text_string(text) == u'':
self.button_ok.setEnabled(False)
else:
self.button_ok.setEnabled(True) | Disable empty layout name possibility |
def find_fields(self, classname=".*", fieldname=".*", fieldtype=".*", accessflags=".*"):
"""
find fields by regex
:param classname: regular expression of the classname
:param fieldname: regular expression of the fieldname
:param fieldtype: regular expression of the fieldtype
... | find fields by regex
:param classname: regular expression of the classname
:param fieldname: regular expression of the fieldname
:param fieldtype: regular expression of the fieldtype
:param accessflags: regular expression of the access flags
:rtype: generator of `FieldClassAnaly... |
def distribution_to_markdown(distribution):
"""Genera texto en markdown a partir de los metadatos de una
`distribution`.
Args:
distribution (dict): Diccionario con metadatos de una
`distribution`.
Returns:
str: Texto que describe una `distribution`.
"""
text_template = ... | Genera texto en markdown a partir de los metadatos de una
`distribution`.
Args:
distribution (dict): Diccionario con metadatos de una
`distribution`.
Returns:
str: Texto que describe una `distribution`. |
def from_rational(
cls,
value,
to_base,
precision=None,
method=RoundingMethods.ROUND_DOWN
):
"""
Convert rational value to a base.
:param Rational value: the value to convert
:param int to_base: base of result, must be at least 2
:param pre... | Convert rational value to a base.
:param Rational value: the value to convert
:param int to_base: base of result, must be at least 2
:param precision: number of digits in total or None
:type precision: int or NoneType
:param method: rounding method
:type method: element ... |
def url(**attributes):
"""Parses an URL and validates its attributes."""
def check_url(value):
validate(text, value)
parsed = urlparse(value)
if not parsed.netloc:
raise ValueError("'{0}' is not a valid URL".format(value))
for name, schema in attributes.items():
... | Parses an URL and validates its attributes. |
def deleteQueue(destinationRoot, queueArk, debug=False):
"""
Delete an entry from the queue
"""
url = urlparse.urljoin(destinationRoot, "APP/queue/" + queueArk + "/")
response, content = doWaitWebRequest(url, "DELETE")
if response.getcode() != 200:
raise Exception(
"Error up... | Delete an entry from the queue |
def get_variants(self, arch=None, types=None, recursive=False):
"""
Return all variants of given arch and types.
Supported variant types:
self - include the top-level ("self") variant as well
addon
variant
optional
"""
types = ... | Return all variants of given arch and types.
Supported variant types:
self - include the top-level ("self") variant as well
addon
variant
optional |
def times_update(self, factor):
"""Update each this multiset by multiplying each element's multiplicity with the given scalar factor.
>>> ms = Multiset('aab')
>>> ms.times_update(2)
>>> sorted(ms)
['a', 'a', 'a', 'a', 'b', 'b']
You can also use the ``*=`` operator for t... | Update each this multiset by multiplying each element's multiplicity with the given scalar factor.
>>> ms = Multiset('aab')
>>> ms.times_update(2)
>>> sorted(ms)
['a', 'a', 'a', 'a', 'b', 'b']
You can also use the ``*=`` operator for the same effect:
>>> ms = Multiset(... |
def get_session_id(self):
"""
get a unique id (shortish string) to allow simple aggregation
of log records from multiple sources. This id is used for the
life of the running program to allow extraction from all logs.
WARING - this can give duplicate sessions when 2 apps hit it
... | get a unique id (shortish string) to allow simple aggregation
of log records from multiple sources. This id is used for the
life of the running program to allow extraction from all logs.
WARING - this can give duplicate sessions when 2 apps hit it
at the same time. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.