code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def train_model_from_file(parameter_filename: str,
serialization_dir: str,
overrides: str = "",
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
... | A wrapper around :func:`train_model` which loads the params from a file.
Parameters
----------
parameter_filename : ``str``
A json parameter file specifying an AllenNLP experiment.
serialization_dir : ``str``
The directory in which to save results and logs. We just pass this along to
... |
def statement(self):
"""
statement : assign_statement
| expression
| control
| empty
Feature For Loop adds:
| loop
Feature Func adds:
| func
| return statement
... | statement : assign_statement
| expression
| control
| empty
Feature For Loop adds:
| loop
Feature Func adds:
| func
| return statement |
def try_write(wd_item, record_id, record_prop, login, edit_summary='', write=True):
"""
Write a PBB_core item. Log if item was created, updated, or skipped.
Catch and log all errors.
:param wd_item: A wikidata item that will be written
:type wd_item: PBB_Core.WDItemEngine
:param record_id: An e... | Write a PBB_core item. Log if item was created, updated, or skipped.
Catch and log all errors.
:param wd_item: A wikidata item that will be written
:type wd_item: PBB_Core.WDItemEngine
:param record_id: An external identifier, to be used for logging
:type record_id: str
:param record_prop: Prop... |
def force_delete(self):
"""
Force a hard delete on a soft deleted model.
"""
self._force_deleting = True
self.delete()
self._force_deleting = False | Force a hard delete on a soft deleted model. |
def rfft2d_freqs(h, w):
"""Computes 2D spectrum frequencies."""
fy = np.fft.fftfreq(h)[:, None]
# when we have an odd input dimension we need to keep one additional
# frequency and later cut off 1 pixel
if w % 2 == 1:
fx = np.fft.fftfreq(w)[: w // 2 + 2]
else:
fx = np.fft.fftfre... | Computes 2D spectrum frequencies. |
def patch_context(self, context):
"""
Patches the context to add utility functions
Sets up the base_url, and the get_url() utility function.
"""
context.__class__ = PatchedContext
# Simply setting __class__ directly doesn't work
# because behave.runner.Context.__... | Patches the context to add utility functions
Sets up the base_url, and the get_url() utility function. |
def get_colours(color_group, color_name, reverse=False):
color_group = color_group.lower()
cmap = get_map(color_group, color_name, reverse=reverse)
return cmap.hex_colors
"""
if not reverse:
return cmap.hex_colors
else:
return cmap.hex_colors[::-1]
""" | if not reverse:
return cmap.hex_colors
else:
return cmap.hex_colors[::-1] |
def _parse_args(cls):
"""
Method to parse command line arguments
"""
cls.parser = argparse.ArgumentParser()
cls.parser.add_argument(
"symbol", help="Symbol for horizontal line", nargs="*")
cls.parser.add_argument(
"--color", "-c", help="Color of th... | Method to parse command line arguments |
def get_as_map(self, key):
"""
Converts map element into an AnyValueMap or returns empty AnyValueMap if conversion is not possible.
:param key: a key of element to get.
:return: AnyValueMap value of the element or empty AnyValueMap if conversion is not supported.
"""
va... | Converts map element into an AnyValueMap or returns empty AnyValueMap if conversion is not possible.
:param key: a key of element to get.
:return: AnyValueMap value of the element or empty AnyValueMap if conversion is not supported. |
def register_cli_argument(self, scope, dest, argtype, **kwargs):
""" Add an argument to the argument registry
:param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand')
:type scope: str
:param dest: The parameter/destination that this argument is for
... | Add an argument to the argument registry
:param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand')
:type scope: str
:param dest: The parameter/destination that this argument is for
:type dest: str
:param argtype: The argument type for this com... |
def asbool(value):
"""Function used to convert certain string values into an appropriated
boolean value.If value is not a string the built-in python
bool function will be used to convert the passed parameter
:param value: an object to be converted to a boolean value
:returns: A boolean value... | Function used to convert certain string values into an appropriated
boolean value.If value is not a string the built-in python
bool function will be used to convert the passed parameter
:param value: an object to be converted to a boolean value
:returns: A boolean value |
def get_amplification_factors(self, imt, sctx, rctx, dists, stddev_types):
"""
Returns the amplification factors for the given rupture and site
conditions.
:param imt:
Intensity measure type as an instance of the :class:
`openquake.hazardlib.imt`
:param s... | Returns the amplification factors for the given rupture and site
conditions.
:param imt:
Intensity measure type as an instance of the :class:
`openquake.hazardlib.imt`
:param sctx:
SiteCollection instance
:param rctx:
Rupture instance
... |
def label(self, input_grid):
"""
Labels input grid using enhanced watershed algorithm.
Args:
input_grid (numpy.ndarray): Grid to be labeled.
Returns:
Array of labeled pixels
"""
marked = self.find_local_maxima(input_grid)
marked = np.wher... | Labels input grid using enhanced watershed algorithm.
Args:
input_grid (numpy.ndarray): Grid to be labeled.
Returns:
Array of labeled pixels |
def url_equal(first, second, ignore_scheme=False, ignore_netloc=False, ignore_path=False, ignore_params=False,
ignore_query=False, ignore_fragment=False):
"""
Compare two URLs and return True if they are equal, some parts of the URLs can be ignored
:param first: URL
:param second: URL
... | Compare two URLs and return True if they are equal, some parts of the URLs can be ignored
:param first: URL
:param second: URL
:param ignore_scheme: ignore the scheme
:param ignore_netloc: ignore the netloc
:param ignore_path: ignore the path
:param ignore_params: ignore the params
:param ig... |
def append(self, other):
"""Appends stars from another StarPopulations, in place.
:param other:
Another :class:`StarPopulation`; must have same columns as ``self``.
"""
if not isinstance(other,StarPopulation):
raise TypeError('Only StarPopulation objects can be ... | Appends stars from another StarPopulations, in place.
:param other:
Another :class:`StarPopulation`; must have same columns as ``self``. |
def persist(name, value, config=None):
'''
Assign and persist a simple sysctl parameter for this minion. If ``config``
is not specified, a sensible default will be chosen using
:mod:`sysctl.default_config <salt.modules.linux_sysctl.default_config>`.
CLI Example:
.. code-block:: bash
s... | Assign and persist a simple sysctl parameter for this minion. If ``config``
is not specified, a sensible default will be chosen using
:mod:`sysctl.default_config <salt.modules.linux_sysctl.default_config>`.
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.ipv4.ip_forward 1 |
def verify_psd_options(opt, parser):
"""Parses the CLI options and verifies that they are consistent and
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimat... | Parses the CLI options and verifies that they are consistent and
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimation,
psd_segment_length, psd_segment... |
def send_screen_to_connection(self, screen):
"""
Actually used for Curses
:param screen:
:return:void
"""
display_who_run_core = self.get_connection_who_have_to_run_core()
if not display_who_run_core:
raise Exception('Need Terminal object to do that')
... | Actually used for Curses
:param screen:
:return:void |
def build_acl(self, tenant_name, rule):
"""Build the ACL. """
# TODO(padkrish) actions that is not deny or allow, throw error
if rule['action'] == 'allow':
action = 'permit'
else:
action = 'deny'
acl_str = "access-list %(tenant)s extended %(action)s %(prot... | Build the ACL. |
def fullscreen(self):
''' Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!')
'''
stream = self._stream
stream.write(self.alt_screen_enable)
... | Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!') |
def pair(args):
"""
%prog pair samfile
Parses the sam file and retrieve in pairs format,
query:pos ref:pos
"""
p = OptionParser(pair.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
def callback(s):
print(s.pairline)
Sam(args... | %prog pair samfile
Parses the sam file and retrieve in pairs format,
query:pos ref:pos |
def _apply_local_transforms(p, ts):
"""
Given a 2d array of single shot results (outer axis iterates over shots, inner axis over bits)
and a list of assignment probability matrices (one for each bit in the readout, ordered like
the inner axis of results) apply local 2x2 matrices to each bit index.
... | Given a 2d array of single shot results (outer axis iterates over shots, inner axis over bits)
and a list of assignment probability matrices (one for each bit in the readout, ordered like
the inner axis of results) apply local 2x2 matrices to each bit index.
:param np.array p: An array that enumerates a fu... |
def generateImplicitParameters(obj):
"""
Generate a UID if one does not exist.
This is just a dummy implementation, for now.
"""
if not hasattr(obj, 'uid'):
rand = int(random.random() * 100000)
now = datetime.datetime.now(utc)
now = dateTimeTo... | Generate a UID if one does not exist.
This is just a dummy implementation, for now. |
def find_xref(self, parser):
"""Internal function used to locate the first XRef."""
# search the last xref table by scanning the file backwards.
prev = None
for line in parser.revreadlines():
line = line.strip()
if self.debug:
logging.debug('find_x... | Internal function used to locate the first XRef. |
def getch():
"""
get character. waiting for key
"""
try:
termios.tcsetattr(_fd, termios.TCSANOW, _new_settings)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(_fd, termios.TCSADRAIN, _old_settings)
return ch | get character. waiting for key |
def RunValidation(feed, options, problems):
"""Validate feed, returning the loaded Schedule and exit code.
Args:
feed: GTFS file, either path of the file as a string or a file object
options: options object returned by optparse
problems: transitfeed.ProblemReporter instance
Returns:
a transitfee... | Validate feed, returning the loaded Schedule and exit code.
Args:
feed: GTFS file, either path of the file as a string or a file object
options: options object returned by optparse
problems: transitfeed.ProblemReporter instance
Returns:
a transitfeed.Schedule object, exit code and plain text strin... |
def lineincustcols (inlist,colsizes):
"""
Returns a string composed of elements in inlist, with each element
right-aligned in a column of width specified by a sequence colsizes. The
length of colsizes must be greater than or equal to the number of columns
in inlist.
Usage: lineincustcols (inlist,colsizes)
Retur... | Returns a string composed of elements in inlist, with each element
right-aligned in a column of width specified by a sequence colsizes. The
length of colsizes must be greater than or equal to the number of columns
in inlist.
Usage: lineincustcols (inlist,colsizes)
Returns: formatted string created from inlist |
def parse_args(self, args=None, values=None):
"""
parse_args(args : [string] = sys.argv[1:],
values : Values = None)
-> (values : Values, args : [string])
Parse the command-line options found in 'args' (default:
sys.argv[1:]). Any errors result in a call to '... | parse_args(args : [string] = sys.argv[1:],
values : Values = None)
-> (values : Values, args : [string])
Parse the command-line options found in 'args' (default:
sys.argv[1:]). Any errors result in a call to 'error()', which
by default prints the usage message to std... |
def plot_covariance(self, corr=False, param_slice=None, tick_labels=None, tick_params=None):
"""
Plots the covariance matrix of the posterior as a Hinton diagram.
.. note::
This function requires that mpltools is installed.
:param bool corr: If `True`, the covariance matri... | Plots the covariance matrix of the posterior as a Hinton diagram.
.. note::
This function requires that mpltools is installed.
:param bool corr: If `True`, the covariance matrix is first normalized
by the outer product of the square root diagonal of the covariance matrix
... |
def maskname(mask):
"""
Returns the event name associated to mask. IN_ISDIR is appended to
the result when appropriate. Note: only one event is returned, because
only one event can be raised at a given time.
@param mask: mask.
@type mask: int
@return: event name.... | Returns the event name associated to mask. IN_ISDIR is appended to
the result when appropriate. Note: only one event is returned, because
only one event can be raised at a given time.
@param mask: mask.
@type mask: int
@return: event name.
@rtype: str |
async def on_raw_privmsg(self, message):
""" Modify PRIVMSG to redirect CTCP messages. """
nick, metadata = self._parse_user(message.source)
target, msg = message.params
if is_ctcp(msg):
self._sync_user(nick, metadata)
type, contents = parse_ctcp(msg)
... | Modify PRIVMSG to redirect CTCP messages. |
def cancel_reason(self, cancel_reason):
"""
Sets the cancel_reason of this OrderFulfillmentPickupDetails.
A description of why the pickup was canceled. Max length is 100 characters.
:param cancel_reason: The cancel_reason of this OrderFulfillmentPickupDetails.
:type: str
... | Sets the cancel_reason of this OrderFulfillmentPickupDetails.
A description of why the pickup was canceled. Max length is 100 characters.
:param cancel_reason: The cancel_reason of this OrderFulfillmentPickupDetails.
:type: str |
def add_task(self, subject, status, **attrs):
"""
Add a :class:`Task` to the current :class:`UserStory` and return it.
:param subject: subject of the :class:`Task`
:param status: status of the :class:`Task`
:param attrs: optional attributes for :class:`Task`
"""
... | Add a :class:`Task` to the current :class:`UserStory` and return it.
:param subject: subject of the :class:`Task`
:param status: status of the :class:`Task`
:param attrs: optional attributes for :class:`Task` |
def get_class_by_id(self, ac_id: int) -> AssetClass:
""" Finds the asset class by id """
assert isinstance(ac_id, int)
# iterate recursively
for ac in self.asset_classes:
if ac.id == ac_id:
return ac
# if nothing returned so far.
return None | Finds the asset class by id |
def notes(self, item_type, item_id):
"""Get the notes from pagination"""
payload = {
'order_by': 'updated_at',
'sort': 'asc',
'per_page': PER_PAGE
}
path = urijoin(item_type, str(item_id), GitLabClient.NOTES)
return self.fetch_items(path, pa... | Get the notes from pagination |
def SeqN(n, *inner_rules, **kwargs):
"""
A rule that accepts a sequence of tokens satisfying ``rules`` and returns
the value returned by rule number ``n``, or None if the first rule was not satisfied.
"""
@action(Seq(*inner_rules), loc=kwargs.get("loc", None))
def rule(parser, *values):
... | A rule that accepts a sequence of tokens satisfying ``rules`` and returns
the value returned by rule number ``n``, or None if the first rule was not satisfied. |
def defaults(cls, *options, **kwargs):
"""Set default options for a session.
Set default options for a session. whether in a Python script or
a Jupyter notebook.
Args:
*options: Option objects used to specify the defaults.
backend: The plotting extension the opti... | Set default options for a session.
Set default options for a session. whether in a Python script or
a Jupyter notebook.
Args:
*options: Option objects used to specify the defaults.
backend: The plotting extension the options apply to |
def reverse_media_url(target_type, url_string, *args, **kwargs):
'''
Given a target type and an resource URL, generates a valid URL to this via
'''
args_str = '<%s>' % '><'.join(args)
kwargs_str = '<%s>' % '><'.join('%s:%s' % pair for pair in kwargs.items())
url_str = ''.join([url_string, args_s... | Given a target type and an resource URL, generates a valid URL to this via |
def _slice_mostly_sorted(array, keep, rest, ind=None):
"""Slice dask array `array` that is almost entirely sorted already.
We perform approximately `2 * len(keep)` slices on `array`.
This is OK, since `keep` is small. Individually, each of these slices
is entirely sorted.
Parameters
----------... | Slice dask array `array` that is almost entirely sorted already.
We perform approximately `2 * len(keep)` slices on `array`.
This is OK, since `keep` is small. Individually, each of these slices
is entirely sorted.
Parameters
----------
array : dask.array.Array
keep : ndarray[Int]
... |
def setdict(self, D=None):
"""Set dictionary array."""
if D is not None:
self.D = np.asarray(D, dtype=self.dtype)
self.Df = sl.rfftn(self.D, self.cri.Nv, self.cri.axisN)
if self.opt['HighMemSolve'] and self.cri.Cd == 1:
self.c = sl.solvedbd_sm_c(
... | Set dictionary array. |
async def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
"""
Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an extern... | Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning ... |
def getJobStore(cls, locator):
"""
Create an instance of the concrete job store implementation that matches the given locator.
:param str locator: The location of the job store to be represent by the instance
:return: an instance of a concrete subclass of AbstractJobStore
:rtyp... | Create an instance of the concrete job store implementation that matches the given locator.
:param str locator: The location of the job store to be represent by the instance
:return: an instance of a concrete subclass of AbstractJobStore
:rtype: toil.jobStores.abstractJobStore.AbstractJobStore |
def delete_hc(kwargs=None, call=None):
'''
Permanently delete a health check.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_hc gce name=hc
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_hc function must be called with -f or --function.'
... | Permanently delete a health check.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_hc gce name=hc |
def getComponentState(self, pchRenderModelName, pchComponentName):
"""This version of GetComponentState takes a controller state block instead of an action origin. This function is deprecated. You should use the new input system and GetComponentStateForDevicePath instead."""
fn = self.function_table.ge... | This version of GetComponentState takes a controller state block instead of an action origin. This function is deprecated. You should use the new input system and GetComponentStateForDevicePath instead. |
def deflections_from_grid(self, grid):
"""
Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
"""
... | Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on. |
def create_shot(self, ):
"""Create a shot and store it in the self.shot
:returns: None
:rtype: None
:raises: None
"""
name = self.name_le.text()
if not name:
self.name_le.setPlaceholderText("Please enter a name!")
return
desc = sel... | Create a shot and store it in the self.shot
:returns: None
:rtype: None
:raises: None |
def rebin_image(bin_size, image, wht_map, sigma_bkg, ra_coords, dec_coords, idex_mask):
"""
rebins pixels, updates cutout image, wht_map, sigma_bkg, coordinates, PSF
:param bin_size: number of pixels (per axis) to merge
:return:
"""
numPix = int(len(image)/bin_size)
numPix_precut = numPix * ... | rebins pixels, updates cutout image, wht_map, sigma_bkg, coordinates, PSF
:param bin_size: number of pixels (per axis) to merge
:return: |
def log_with_color(level):
""" log with color by different level
"""
def wrapper(text):
color = log_colors_config[level.upper()]
getattr(logger, level.lower())(coloring(text, color))
return wrapper | log with color by different level |
def mv(i):
"""
Input: {
(repo_uoa) - repo UOA
module_uoa - module UOA
data_uoa - data UOA
xcids[0] - {'repo_uoa', 'module_uoa', 'data_uoa'} - new CID
or
(new_repo_uoa) - new repo UOA
(new_... | Input: {
(repo_uoa) - repo UOA
module_uoa - module UOA
data_uoa - data UOA
xcids[0] - {'repo_uoa', 'module_uoa', 'data_uoa'} - new CID
or
(new_repo_uoa) - new repo UOA
(new_module_uoa) - new modul... |
def interpolate(text, global_dict=None, local_dict=None):
'''Evaluate expressions in `text` '''
# step 1, make it a f-string (add quotation marks and f
# step 2, evaluate as a string
try:
return eval(as_fstring(text), global_dict, local_dict)
except Exception as e:
raise ValueError(f... | Evaluate expressions in `text` |
def infix_handle(tokens):
"""Process infix calls."""
func, args = get_infix_items(tokens, callback=infix_handle)
return "(" + func + ")(" + ", ".join(args) + ")" | Process infix calls. |
def get_tag(self, tag):
"""
::
GET /:login/machines/:id/tags/:tag
:Returns: the value for a single tag
:rtype: :py:class:`basestring`
"""
headers = {'Accept': 'text/plain'}
j, _ = self.datacenter.request('GET', self.path + '/tags/' + ... | ::
GET /:login/machines/:id/tags/:tag
:Returns: the value for a single tag
:rtype: :py:class:`basestring` |
def ports(self):
'''The list of ports involved in this connection.
The result is a list of tuples, (port name, port object). Each port
name is a full path to the port (e.g. /localhost/Comp0.rtc:in) if
this Connection object is owned by a Port, which is in turn owned by
a Compone... | The list of ports involved in this connection.
The result is a list of tuples, (port name, port object). Each port
name is a full path to the port (e.g. /localhost/Comp0.rtc:in) if
this Connection object is owned by a Port, which is in turn owned by
a Component in the tree. Otherwise, o... |
def lose():
"""Enables access to websites that are defined as 'distractors'"""
changed = False
with open(settings.HOSTS_FILE, "r") as hosts_file:
new_file = []
in_block = False
for line in hosts_file:
if in_block:
if line.strip() == settings.END_TOKEN:
... | Enables access to websites that are defined as 'distractors |
def register_pubkey(self):
"""
XXX Support compressed point format.
XXX Check that the pubkey received is on the curve.
"""
# point_format = 0
# if self.point[0] in [b'\x02', b'\x03']:
# point_format = 1
curve_name = _tls_named_curves[self.named_curve]... | XXX Support compressed point format.
XXX Check that the pubkey received is on the curve. |
def update_checkplotdict_nbrlcs(
checkplotdict,
timecol, magcol, errcol,
lcformat='hat-sql',
lcformatdir=None,
verbose=True,
):
'''For all neighbors in a checkplotdict, make LCs and phased LCs.
Parameters
----------
checkplotdict : dict
This is the chec... | For all neighbors in a checkplotdict, make LCs and phased LCs.
Parameters
----------
checkplotdict : dict
This is the checkplot to process. The light curves for the neighbors to
the object here will be extracted from the stored file paths, and this
function will make plots of these... |
def remove_plugin(self, name, force=False):
"""
Remove an installed plugin.
Args:
name (string): Name of the plugin to remove. The ``:latest``
tag is optional, and is the default if omitted.
force (bool): Disable the plugin before remo... | Remove an installed plugin.
Args:
name (string): Name of the plugin to remove. The ``:latest``
tag is optional, and is the default if omitted.
force (bool): Disable the plugin before removing. This may
result in issues if the plugin is... |
def DeregisterHelper(cls, analyzer_helper):
"""Deregisters a format analyzer helper.
Args:
analyzer_helper (AnalyzerHelper): analyzer helper.
Raises:
KeyError: if analyzer helper object is not set for the corresponding
type indicator.
"""
if analyzer_helper.type_indicator not... | Deregisters a format analyzer helper.
Args:
analyzer_helper (AnalyzerHelper): analyzer helper.
Raises:
KeyError: if analyzer helper object is not set for the corresponding
type indicator. |
def has_reset(self):
"""Checks the grizzly to see if it reset itself because of
voltage sag or other reasons. Useful to reinitialize acceleration or
current limiting."""
currentTime = self._read_as_int(Addr.Uptime, 4)
if currentTime <= self._ticks:
self._ticks = curre... | Checks the grizzly to see if it reset itself because of
voltage sag or other reasons. Useful to reinitialize acceleration or
current limiting. |
def create_datacenter(self, datacenter):
"""
Creates a data center -- both simple and complex are supported.
"""
server_items = []
volume_items = []
lan_items = []
loadbalancer_items = []
entities = dict()
properties = {
"name": data... | Creates a data center -- both simple and complex are supported. |
def replace_label(self, oldLabel, newLabel):
""" Replaces old label with a new one
"""
if oldLabel == newLabel:
return
tmp = re.compile(r'\b' + oldLabel + r'\b')
last = 0
l = len(newLabel)
while True:
match = tmp.search(self.asm[last:])
... | Replaces old label with a new one |
def format_stats(self, stats:TensorOrNumList)->None:
"Format stats before printing."
str_stats = []
for name,stat in zip(self.names,stats):
str_stats.append('#na#' if stat is None else str(stat) if isinstance(stat, int) else f'{stat:.6f}')
if self.add_time: str_stats.append(f... | Format stats before printing. |
def check_object_permissions(self, request, obj):
"""
Check if the request should be permitted for a given object.
Raises an appropriate exception if the request is not permitted.
:param request: Pyramid Request object.
:param obj: The SQLAlchemy model instance that permissions ... | Check if the request should be permitted for a given object.
Raises an appropriate exception if the request is not permitted.
:param request: Pyramid Request object.
:param obj: The SQLAlchemy model instance that permissions will be evaluated against. |
def binaryorbit(orbit, comp1, comp2, envelope=None):
"""
Build the string representation of a hierarchy containing a binary
orbit with 2 components.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.set_hierarchy`
:parameter comp1: an existin... | Build the string representation of a hierarchy containing a binary
orbit with 2 components.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.set_hierarchy`
:parameter comp1: an existing hierarchy string, Parameter, or ParameterSet
:parameter com... |
def need_summary(self, now, max_updates, max_age):
"""
Helper method to determine if a "summarize" record should be
added.
:param now: The current time.
:param max_updates: Maximum number of updates before a
summarize is required.
:param max_a... | Helper method to determine if a "summarize" record should be
added.
:param now: The current time.
:param max_updates: Maximum number of updates before a
summarize is required.
:param max_age: Maximum age of the last summarize record.
T... |
def record_modify_subfield(rec, tag, subfield_code, value, subfield_position,
field_position_global=None,
field_position_local=None):
"""Modify subfield at specified position.
Specify the subfield by tag, field number and subfield position.
"""
subf... | Modify subfield at specified position.
Specify the subfield by tag, field number and subfield position. |
def replace_widgets(self, widgets, team_context, dashboard_id, eTag=None):
"""ReplaceWidgets.
[Preview API] Replace the widgets on specified dashboard with the supplied widgets.
:param [Widget] widgets: Revised state of widgets to store for the dashboard.
:param :class:`<TeamContext> <az... | ReplaceWidgets.
[Preview API] Replace the widgets on specified dashboard with the supplied widgets.
:param [Widget] widgets: Revised state of widgets to store for the dashboard.
:param :class:`<TeamContext> <azure.devops.v5_0.dashboard.models.TeamContext>` team_context: The team context for the ... |
def save_json(obj, filename, **kwargs):
"""
Save an object as a JSON file.
Args:
obj: The object to save. Must be JSON-serializable.
filename: Path to the output file.
**kwargs: Additional arguments to `json.dump`.
"""
with open(filename, 'w', encoding='utf-8') as f:
... | Save an object as a JSON file.
Args:
obj: The object to save. Must be JSON-serializable.
filename: Path to the output file.
**kwargs: Additional arguments to `json.dump`. |
def render_layout(layout_name, content, **context):
"""Uses a jinja template to wrap the content inside a layout.
Wraps the content inside a block and adds the extend statement before rendering it
with jinja. The block name can be specified in the layout_name after the filename separated
by a colon. The... | Uses a jinja template to wrap the content inside a layout.
Wraps the content inside a block and adds the extend statement before rendering it
with jinja. The block name can be specified in the layout_name after the filename separated
by a colon. The default block name is "content". |
def update_notify_on_sample_invalidation(portal):
"""The name of the Setup field was NotifyOnARRetract, so it was
confusing. There was also two fields "NotifyOnRejection"
"""
setup = api.get_setup()
# NotifyOnARRetract --> NotifyOnSampleInvalidation
old_value = setup.__dict__.get("NotifyOnARRet... | The name of the Setup field was NotifyOnARRetract, so it was
confusing. There was also two fields "NotifyOnRejection" |
def make_iaf_stack(total_event_size,
num_hidden_layers=2,
seed=None,
dtype=tf.float32):
"""Creates an stacked IAF bijector.
This bijector operates on vector-valued events.
Args:
total_event_size: Number of dimensions to operate over.
num_hidden_la... | Creates an stacked IAF bijector.
This bijector operates on vector-valued events.
Args:
total_event_size: Number of dimensions to operate over.
num_hidden_layers: How many hidden layers to use in each IAF.
seed: Random seed for the initializers.
dtype: DType for the variables.
Returns:
bijec... |
def last_position(self):
"""
Returns the last position of this Sprite as a tuple
(x, y, width, height).
"""
return self._old_x, self._old_y, self._old_width, self._old_height | Returns the last position of this Sprite as a tuple
(x, y, width, height). |
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var... | .. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:... |
def rehook_symbol(self, new_address, symbol_name):
"""
Move the hook for a symbol to a specific address
:param new_address: the new address that will trigger the SimProc execution
:param symbol_name: the name of the symbol (f.i. strcmp )
:return: None
"""
new_sim_... | Move the hook for a symbol to a specific address
:param new_address: the new address that will trigger the SimProc execution
:param symbol_name: the name of the symbol (f.i. strcmp )
:return: None |
def write8(self, value, char_mode=False):
"""Write 8-bit value in character or data mode. Value should be an int
value from 0-255, and char_mode is True if character data or False if
non-character data (default).
"""
# One millisecond delay to prevent writing too quickly.
... | Write 8-bit value in character or data mode. Value should be an int
value from 0-255, and char_mode is True if character data or False if
non-character data (default). |
def show_progress(self):
"""If we are in a progress scope, and no log messages have been
shown, write out another '.'"""
if self.in_progress_hanging:
sys.stdout.write('.')
sys.stdout.flush() | If we are in a progress scope, and no log messages have been
shown, write out another '. |
def show_warnings(self):
"""Return detailed information about warnings as a
sequence of tuples of (Level, Code, Message). This
is only supported in MySQL-4.1 and up. If your server
is an earlier version, an empty sequence is returned."""
if self._server_version < (4,1): return ()... | Return detailed information about warnings as a
sequence of tuples of (Level, Code, Message). This
is only supported in MySQL-4.1 and up. If your server
is an earlier version, an empty sequence is returned. |
def from_pcount(nevents):
"""We assume a Poisson process. nevents is the number of events in
some interval. The distribution of values is the distribution of the
Poisson rate parameter given this observed number of events, where the
"rate" is in units of events per interval of the same d... | We assume a Poisson process. nevents is the number of events in
some interval. The distribution of values is the distribution of the
Poisson rate parameter given this observed number of events, where the
"rate" is in units of events per interval of the same duration. The
max-likelihood v... |
def calc_qdb_v1(self):
"""Calculate direct runoff released from the soil.
Required control parameters:
|NHRU|
|Lnk|
|NFk|
|BSf|
Required state sequence:
|BoWa|
Required flux sequence:
|WaDa|
Calculated flux sequence:
|QDB|
Basic equations:
:ma... | Calculate direct runoff released from the soil.
Required control parameters:
|NHRU|
|Lnk|
|NFk|
|BSf|
Required state sequence:
|BoWa|
Required flux sequence:
|WaDa|
Calculated flux sequence:
|QDB|
Basic equations:
:math:`QDB = \\Bigl \\lbrace
... |
def register(lifter, arch_name):
"""
Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifte... | Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocess... |
def _clean_accents(self, text):
"""Remove most accent marks.
Note that the circumflexes over alphas and iotas in the text since
they determine vocalic quantity.
:param text: raw text
:return: clean text with minimum accent marks
:rtype : string
"""
accent... | Remove most accent marks.
Note that the circumflexes over alphas and iotas in the text since
they determine vocalic quantity.
:param text: raw text
:return: clean text with minimum accent marks
:rtype : string |
def runfile(filename, args=None, wdir=None, namespace=None, post_mortem=False):
"""
Run filename
args: command line arguments (string)
wdir: working directory
post_mortem: boolean, whether to enter post-mortem mode on error
"""
try:
filename = filename.decode('utf-8')
except (Uni... | Run filename
args: command line arguments (string)
wdir: working directory
post_mortem: boolean, whether to enter post-mortem mode on error |
def check_stripe_api_host(app_configs=None, **kwargs):
"""
Check that STRIPE_API_HOST is not being used in production.
"""
from django.conf import settings
messages = []
if not settings.DEBUG and hasattr(settings, "STRIPE_API_HOST"):
messages.append(
checks.Warning(
"STRIPE_API_HOST should not be set i... | Check that STRIPE_API_HOST is not being used in production. |
def _class_type(klass, ancestors=None):
"""return a ClassDef node type to differ metaclass and exception
from 'regular' classes
"""
# XXX we have to store ancestors in case we have an ancestor loop
if klass._type is not None:
return klass._type
if _is_metaclass(klass):
klass._typ... | return a ClassDef node type to differ metaclass and exception
from 'regular' classes |
def _is_redundant(self, matrix, cutoff=None):
"""Identify rdeundant rows in a matrix that can be removed."""
cutoff = 1.0 - self.feasibility_tol
# Avoid zero variances
extra_col = matrix[:, 0] + 1
# Avoid zero rows being correlated with constant rows
extra_col[matrix.s... | Identify rdeundant rows in a matrix that can be removed. |
def authenticate(self, req, resp, resource):
"""
Extract basic auth token from request `authorization` header, deocode the
token, verifies the username/password and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception`
"""
usernam... | Extract basic auth token from request `authorization` header, deocode the
token, verifies the username/password and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception` |
def region(self, start=0, end=None):
'''
Returns a region of ``Sequence.sequence``, in FASTA format.
If called without kwargs, the entire sequence will be returned.
Args:
start (int): Start position of the region to be returned. Default
is 0.
e... | Returns a region of ``Sequence.sequence``, in FASTA format.
If called without kwargs, the entire sequence will be returned.
Args:
start (int): Start position of the region to be returned. Default
is 0.
end (int): End position of the region to be returned. Nega... |
def expire_file(filepath):
""" Expire a record for a missing file """
load_message.cache_clear()
orm.delete(pa for pa in model.PathAlias if pa.entry.file_path == filepath)
orm.delete(item for item in model.Entry if item.file_path == filepath)
orm.commit() | Expire a record for a missing file |
def add_events(self, names, send_event=True, event_factory=None):
"""
Add event by name.
This is called for you as needed if you allow auto creation of events (see __init__).
Upon an event being added, all handlers are searched for if they have this event,
and if they do, they ... | Add event by name.
This is called for you as needed if you allow auto creation of events (see __init__).
Upon an event being added, all handlers are searched for if they have this event,
and if they do, they are added to the Event's list of callables.
:param tuple names: Names |
def __execute_str(self, instr):
"""Execute STR instruction.
"""
op0_val = self.read_operand(instr.operands[0])
self.write_operand(instr.operands[2], op0_val)
return None | Execute STR instruction. |
def to_quaternion(roll = 0.0, pitch = 0.0, yaw = 0.0):
"""
Convert degrees to quaternions
"""
t0 = math.cos(math.radians(yaw * 0.5))
t1 = math.sin(math.radians(yaw * 0.5))
t2 = math.cos(math.radians(roll * 0.5))
t3 = math.sin(math.radians(roll * 0.5))
t4 = math.cos(math.radians(pitch * 0... | Convert degrees to quaternions |
def hexblock_dword(cls, data, address = None,
bits = None,
separator = ' ',
width = 4):
... | Dump a block of hexadecimal DWORDs from binary data.
@type data: str
@param data: Binary data.
@type address: str
@param address: Memory address where the data was read from.
@type bits: int
@param bits:
(Optional) Number of bits of the target architectu... |
def add_action_view(self, name, url, actions, **kwargs):
"""Creates an ActionsView instance and registers it.
"""
view = ActionsView(name, url=url, self_var=self, **kwargs)
if isinstance(actions, dict):
for group, actions in actions.iteritems():
view.actions.e... | Creates an ActionsView instance and registers it. |
def register_standard (id, source_types, target_types, requirements = []):
""" Creates new instance of the 'generator' class and registers it.
Returns the creates instance.
Rationale: the instance is returned so that it's possible to first register
a generator and then call 'run' method on t... | Creates new instance of the 'generator' class and registers it.
Returns the creates instance.
Rationale: the instance is returned so that it's possible to first register
a generator and then call 'run' method on that generator, bypassing all
generator selection. |
def _GetAPFSVolumeIdentifiers(self, scan_node):
"""Determines the APFS volume identifiers.
Args:
scan_node (dfvfs.SourceScanNode): scan node.
Returns:
list[str]: APFS volume identifiers.
Raises:
SourceScannerError: if the format of or within the source is not
supported or ... | Determines the APFS volume identifiers.
Args:
scan_node (dfvfs.SourceScanNode): scan node.
Returns:
list[str]: APFS volume identifiers.
Raises:
SourceScannerError: if the format of or within the source is not
supported or the the scan node is invalid.
UserAbort: if the u... |
def calc_mass_2(mh,cm,nm,teff,logg):
""" Table A2 in Martig 2016 """
CplusN = calc_sum(mh,cm,nm)
t = teff/4000.
return (95.8689 - 10.4042*mh - 0.7266*mh**2
+ 41.3642*cm - 5.3242*cm*mh - 46.7792*cm**2
+ 15.0508*nm - 0.9342*nm*mh - 30.5159*nm*cm - 1.6083*nm**2
- 67.6093... | Table A2 in Martig 2016 |
def mach2cas(Mach, H):
"""Mach number to Calibrated Airspeed"""
Vtas = mach2tas(Mach, H)
Vcas = tas2cas(Vtas, H)
return Vcas | Mach number to Calibrated Airspeed |
def compute_composite_distance(distance, x, y):
"""
Compute the value of a composite distance function on two dictionaries,
typically SFrame rows.
Parameters
----------
distance : list[list]
A composite distance function. Composite distance functions are a
weighted sum of standa... | Compute the value of a composite distance function on two dictionaries,
typically SFrame rows.
Parameters
----------
distance : list[list]
A composite distance function. Composite distance functions are a
weighted sum of standard distance functions, each of which applies to
its ... |
def hellinger(Ks, dim, required, clamp=True, to_self=False):
r'''
Estimate the Hellinger distance between distributions, based on kNN
distances: \sqrt{1 - \int \sqrt{p q}}
Always enforces 0 <= H, to be able to sqrt; if clamp, also enforces
H <= 1.
Returns a vector: one element for each K.
... | r'''
Estimate the Hellinger distance between distributions, based on kNN
distances: \sqrt{1 - \int \sqrt{p q}}
Always enforces 0 <= H, to be able to sqrt; if clamp, also enforces
H <= 1.
Returns a vector: one element for each K. |
def configure(self, ext):
"""Configures the given Extension object using this build configuration."""
ext.include_dirs += self.include_dirs
ext.library_dirs += self.library_dirs
ext.libraries += self.libraries
ext.extra_compile_args += self.extra_compile_args
ext.extra_li... | Configures the given Extension object using this build configuration. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.