INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Parameters ---------- y: 1D numpy array The data to be fitted x: 1D numpy array The x values of the y array. x and y must have the same shape. weights: 1D numpy array must have the same shape as x and y weight values | def linefit(x, y, weights=None):
"""
Parameters
----------
y: 1D numpy array
The data to be fitted
x: 1D numpy array
The x values of the y array. x and y must
have the same shape.
weights: 1D numpy array, must have the same shape as x and y
weight values
E... |
Analyses the measurement with the given parameters: param measurementId:: return: | def get(self, measurementId):
"""
Analyses the measurement with the given parameters
:param measurementId:
:return:
"""
logger.info('Analysing ' + measurementId)
measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE)
... |
compares the current device state against the targetStateProvider and issues updates as necessary to ensure the device is at that state.: param md:: param targetState: the target state.: param httpclient: the http client: return: | def _applyTargetState(targetState, md, httpclient):
"""
compares the current device state against the targetStateProvider and issues updates as necessary to ensure the
device is
at that state.
:param md:
:param targetState: the target state.
:param httpclient: the http client
:return:
... |
Updates the target state on the specified device.: param targetState: the target state to reach.: param device: the device to update.: return: | def updateDeviceState(self, device):
"""
Updates the target state on the specified device.
:param targetState: the target state to reach.
:param device: the device to update.
:return:
"""
# this is only threadsafe because the targetstate is effectively immutable, ... |
Updates the system target state and propagates that to all devices.: param newState:: return: | def updateTargetState(self, newState):
"""
Updates the system target state and propagates that to all devices.
:param newState:
:return:
"""
self._targetStateProvider.state = loadTargetState(newState, self._targetStateProvider.state)
for device in self.deviceContr... |
Input ASCII trailer file input will be read. | def convert(input, width=132, output=None, keep=False):
"""Input ASCII trailer file "input" will be read.
The contents will then be written out to a FITS file in the same format
as used by 'stwfits' from IRAF.
Parameters
===========
input : str
Filename of input ASCII trailer file
... |
An example function that will turn a nested dictionary of results ( as returned by ConfigObj. validate ) into a flat list. | def flatten_errors(cfg, res, levels=None, results=None):
"""
An example function that will turn a nested dictionary of results
(as returned by ``ConfigObj.validate``) into a flat list.
``cfg`` is the ConfigObj instance being checked, ``res`` is the results
dictionary returned by ``validate``.
... |
Find all the values and sections not in the configspec from a validated ConfigObj. | def get_extra_values(conf, _prepend=()):
"""
Find all the values and sections not in the configspec from a validated
ConfigObj.
``get_extra_values`` returns a list of tuples where each tuple represents
either an extra section, or an extra value.
The tuples contain two values, a tuple represent... |
Helper function to fetch values from owning section. | def _fetch(self, key):
"""Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found.
"""
# switch off interpolation before we try and fetch anything !
save_interp = self.section.main.interpolation
self.section.m... |
D. pop ( k [ d ] ) - > v remove specified key and return the corresponding value. If key is not found d is returned if given otherwise KeyError is raised | def pop(self, key, default=MISSING):
"""
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised'
"""
try:
val = self[key]
except KeyError:
if default is... |
Pops the first ( key val ) | def popitem(self):
"""Pops the first (key,val)"""
sequence = (self.scalars + self.sections)
if not sequence:
raise KeyError(": 'popitem(): dictionary is empty'")
key = sequence[0]
val = self[key]
del self[key]
return key, val |
A version of clear that also affects scalars/ sections Also clears comments and configspec. | def clear(self):
"""
A version of clear that also affects scalars/sections
Also clears comments and configspec.
Leaves other attributes alone :
depth/main/parent are not affected
"""
dict.clear(self)
self.scalars = []
self.sections = []
... |
D. items () - > list of D s ( key value ) pairs as 2 - tuples | def items(self):
"""D.items() -> list of D's (key, value) pairs, as 2-tuples"""
return list(zip((self.scalars + self.sections), list(self.values()))) |
Return a deepcopy of self as a dictionary. | def dict(self):
"""
Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict() # doctest: +SKIP
>>> n == a # doctest: +SKIP
1
... |
A recursive update - useful for merging config files. | def merge(self, indict):
"""
A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... |
Change a keyname to another without changing position in sequence. | def rename(self, oldkey, newkey):
"""
Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments.
"""
if oldkey in self.scal... |
Walk every member and call a function on the keyword and value. | def walk(self, function, raise_errors=True,
call_on_sections=False, **keywargs):
"""
Walk every member and call a function on the keyword and value.
Return a dictionary of the return values
If the function raises an exception, raise the errror
unless ``raise_errors=... |
Accepts a key as input. The corresponding value must be a string or the objects ( True or 1 ) or ( False or 0 ). We allow 0 and 1 to retain compatibility with Python 2. 2. | def as_bool(self, key):
"""
Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
... |
A convenience method which fetches the specified value guaranteeing that it is a list. | def as_list(self, key):
"""
A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]... |
Restore ( and return ) default value for the specified key. | def restore_default(self, key):
"""
Restore (and return) default value for the specified key.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
If there is no default value for this key, ``KeyError`` is raised.
"""
... |
Recursively restore default values to all members that have them. | def restore_defaults(self):
"""
Recursively restore default values to all members
that have them.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
It doesn't delete or modify entries without default values.
""... |
Handle any BOM and decode if necessary. | def _handle_bom(self, infile):
"""
Handle any BOM, and decode if necessary.
If an encoding is specified, that *must* be used - but the BOM should
still be removed (and the BOM attribute set).
(If the encoding is wrongly specified, then a BOM for an alternative
encoding ... |
Decode infile to unicode. Using the specified encoding. | def _decode(self, infile, encoding):
"""
Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list.
"""
if isinstance(infile, string_types):
# can't be unicode
# NOTE: Could raise a ``UnicodeDecodeError``
... |
Decode element to unicode if necessary. | def _decode_element(self, line):
"""Decode element to unicode if necessary."""
if not self.encoding:
return line
if isinstance(line, str) and self.default_encoding:
return line.decode(self.default_encoding)
return line |
Actually parse the config file. | def _parse(self, infile):
"""Actually parse the config file."""
temp_list_values = self.list_values
if self.unrepr:
self.list_values = False
comment_list = []
done_start = False
this_section = self
maxline = len(infile) - 1
cur_index = -1
... |
Given a section and a depth level walk back through the sections parents to see if the depth level matches a previous section. | def _match_depth(self, sect, depth):
"""
Given a section and a depth level, walk back through the sections
parents to see if the depth level matches a previous section.
Return a reference to the right section,
or raise a SyntaxError.
"""
while depth < sect.depth:... |
Handle an error according to the error settings. | def _handle_error(self, text, ErrorClass, infile, cur_index):
"""
Handle an error according to the error settings.
Either raise the error or store it.
The error will have occured at ``cur_index``
"""
line = infile[cur_index]
cur_index += 1
message = text ... |
Return an unquoted version of a value | def _unquote(self, value):
"""Return an unquoted version of a value"""
if not value:
# should only happen during parsing of lists
raise SyntaxError
if (value[0] == value[-1]) and (value[0] in ('"', "'")):
value = value[1:-1]
return value |
Return a safely quoted version of a value. | def _quote(self, value, multiline=True):
"""
Return a safely quoted version of a value.
Raise a ConfigObjError if the value cannot be safely quoted.
If multiline is ``True`` (default) then use triple quotes
if necessary.
* Don't quote values that don't need it.
... |
Given a value string unquote remove comment handle lists. ( including empty and single member lists ) | def _handle_value(self, value):
"""
Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists)
"""
if self._inspec:
# Parsing a configspec so don't handle comments
return (value, '')
# do we look for list... |
Extract the value where we are in a multiline situation. | def _multiline(self, value, infile, cur_index, maxline):
"""Extract the value, where we are in a multiline situation."""
quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)... |
Parse the configspec. | def _handle_configspec(self, configspec):
"""Parse the configspec."""
# FIXME: Should we check that the configspec was created with the
# correct settings ? (i.e. ``list_values=False``)
if not isinstance(configspec, ConfigObj):
try:
configspec = ConfigO... |
Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__ | def _set_configspec(self, section, copy):
"""
Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__
"""
configspec = section.configspec
many = configspec.get('__many__')
if isinstance(many, dict):
... |
Write an individual line for the write method | def _write_line(self, indent_string, entry, this_entry, comment):
"""Write an individual line, for the write method"""
# NOTE: the calls to self._quote here handles non-StringType values.
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
... |
Write a section marker line | def _write_marker(self, indent_string, depth, entry, comment):
"""Write a section marker line"""
return '%s%s%s%s%s' % (indent_string,
self._a_to_u('[' * depth),
self._quote(self._decode_element(entry), multiline=False),
... |
Deal with a comment. | def _handle_comment(self, comment):
"""Deal with a comment."""
if not comment:
return ''
start = self.indent_type
if not comment.startswith('#'):
start += self._a_to_u(' # ')
return (start + comment) |
Write the current ConfigObj as a file | def write(self, outfile=None, section=None):
"""
Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename # doctest: +SKIP
>>> a.filename = 'test.ini' # doctest: +SKIP
>>> a.write() # doctest: +SKIP
... |
Test the ConfigObj against a configspec. | def validate(self, validator, preserve_errors=False, copy=False,
section=None):
"""
Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
test = config.validate(... |
Clear ConfigObj instance and restore to freshly created state. | def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state."""
self.clear()
self._initialise()
# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
# requires an empty dictionary
self.configspec = None
# ... |
Reload a ConfigObj from file. | def reload(self):
"""
Reload a ConfigObj from file.
This method raises a ``ReloadError`` if the ConfigObj doesn't have
a filename attribute pointing to a file.
"""
if not isinstance(self.filename, string_types):
raise ReloadError()
filename = self.fi... |
A dummy check method always returns the value unchanged. | def check(self, check, member, missing=False):
"""A dummy check method, always returns the value unchanged."""
if missing:
raise self.baseErrorClass()
return member |
Get the command line arguments | def _processCommandLineArgs():
"""
Get the command line arguments
Parameters: NONE
Returns:
files list of file specifications to be converted
outputFileNames list of output file specifications
(one per input file)
... |
Verify that the input HDUList is for a waivered FITS file. | def _verify(waiveredHdul):
"""
Verify that the input HDUList is for a waivered FITS file.
Parameters:
waiveredHdul HDUList object to be verified
Returns: None
Exceptions:
ValueError Input HDUList is not for a waivered FITS file
"""
if len... |
Convert the input waivered FITS object to a multi - extension FITS HDUList object. Generate an output multi - extension FITS file if requested. | def toMultiExtensionFits(waiveredObject,
multiExtensionFileName=None,
forceFileOutput=False,
verbose=False):
"""
Convert the input waivered FITS object to a multi-extension FITS
HDUList object. Generate an output multi-exten... |
Convert the input waivered FITS object to various formats. The default conversion format is multi - extension FITS. Generate an output file in the desired format if requested. | def convertwaiveredfits(waiveredObject,
outputFileName=None,
forceFileOutput=False,
convertTo='multiExtension',
verbose=False):
"""
Convert the input waivered FITS object to various formats. The
default ... |
Determine Julian day from Persian date | def to_jd(year, month, day):
'''Determine Julian day from Persian date'''
if year >= 0:
y = 474
else:
y = 473
epbase = year - y
epyear = 474 + (epbase % 2820)
if month <= 7:
m = (month - 1) * 31
else:
m = (month - 1) * 30 + 6
return day + m + trunc(((ep... |
Calculate Persian date from Julian day | def from_jd(jd):
'''Calculate Persian date from Julian day'''
jd = trunc(jd) + 0.5
depoch = jd - to_jd(475, 1, 1)
cycle = trunc(depoch / 1029983)
cyear = (depoch % 1029983)
if cyear == 1029982:
ycycle = 2820
else:
aux1 = trunc(cyear / 366)
aux2 = cyear % 366
... |
Initializes capture of stdout/ stderr Python warnings and exceptions ; redirecting them to the loggers for the modules from which they originated. | def setup_global_logging():
"""
Initializes capture of stdout/stderr, Python warnings, and exceptions;
redirecting them to the loggers for the modules from which they originated.
"""
global global_logging_started
if not PY3K:
sys.exc_clear()
if global_logging_started:
retu... |
Disable global logging of stdio warnings and exceptions. | def teardown_global_logging():
"""Disable global logging of stdio, warnings, and exceptions."""
global global_logging_started
if not global_logging_started:
return
stdout_logger = logging.getLogger(__name__ + '.stdout')
stderr_logger = logging.getLogger(__name__ + '.stderr')
if sys.std... |
Do basic configuration for the logging system. Similar to logging. basicConfig but the logger name is configurable and both a file output and a stream output can be created. Returns a logger object. | def create_logger(name, format='%(levelname)s: %(message)s', datefmt=None,
stream=None, level=logging.INFO, filename=None, filemode='w',
filelevel=None, propagate=True):
"""
Do basic configuration for the logging system. Similar to
logging.basicConfig but the logger ``nam... |
Set the stream that this logger is meant to replace. Usually this will be either sys. stdout or sys. stderr but can be any object with write () and flush () methods as supported by logging. StreamHandler. | def set_stream(self, stream):
"""
Set the stream that this logger is meant to replace. Usually this will
be either `sys.stdout` or `sys.stderr`, but can be any object with
`write()` and `flush()` methods, as supported by
`logging.StreamHandler`.
"""
for handler ... |
Buffers each message until a newline is reached. Each complete line is then published to the logging system through self. log (). | def write(self, message):
"""
Buffers each message until a newline is reached. Each complete line is
then published to the logging system through ``self.log()``.
"""
self.__thread_local_ctx.write_count += 1
try:
if self.__thread_local_ctx.write_count > 1:
... |
Returns the full - qualified module name full pathname line number and function in which StreamTeeLogger. write () was called. For example if this instance is used to replace sys. stdout this will return the location of any print statement. | def find_actual_caller(self):
"""
Returns the full-qualified module name, full pathname, line number, and
function in which `StreamTeeLogger.write()` was called. For example,
if this instance is used to replace `sys.stdout`, this will return the
location of any print statement.
... |
Deserialize fp ( a. read () - supporting file - like object containing a XPORT document ) to a Python object. | def load(fp):
'''
Deserialize ``fp`` (a ``.read()``-supporting file-like object
containing a XPORT document) to a Python object.
'''
reader = reading.Reader(fp)
keys = reader.fields
columns = {k: [] for k in keys}
for row in reader:
for key, value in zip(keys, row):
c... |
Go to the login page. | def _get_login_page(self):
"""Go to the login page."""
try:
raw_res = yield from self._session.get(HOME_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can not connect to login page")
# Get l... |
Login to HydroQuebec website. | def _post_login_page(self, login_url):
"""Login to HydroQuebec website."""
data = {"login": self.username,
"_58_password": self.password}
try:
raw_res = yield from self._session.post(login_url,
data=data,
... |
Get id of consumption profile. | def _get_p_p_id_and_contract(self):
"""Get id of consumption profile."""
contracts = {}
try:
raw_res = yield from self._session.get(PROFILE_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can... |
Get contract number when we have only one contract. | def _get_lonely_contract(self):
"""Get contract number when we have only one contract."""
contracts = {}
try:
raw_res = yield from self._session.get(MAIN_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQu... |
Get all balances. | def _get_balances(self):
"""Get all balances.
.. todo::
IT SEEMS balances are shown (MAIN_URL) in the same order
that contracts in profile page (PROFILE_URL).
Maybe we should ensure that.
"""
balances = []
try:
raw_res = yield fro... |
Load the profile page of a specific contract when we have multiple contracts. | def _load_contract_page(self, contract_url):
"""Load the profile page of a specific contract when we have multiple contracts."""
try:
yield from self._session.get(contract_url,
timeout=self._timeout)
except OSError:
raise PyHydroQu... |
Get annual data. | def _get_annual_data(self, p_p_id):
"""Get annual data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationAnnuelles"}
try:
... |
Get monthly data. | def _get_monthly_data(self, p_p_id):
"""Get monthly data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_resource_id": ("resourceObtenirDonnees"
"PeriodesConsommation")}
try:
raw_res = yield from self.... |
Get Hourly Data. | def _get_hourly_data(self, day_date, p_p_id):
"""Get Hourly Data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationHoraires",
... |
Get detailled energy use from a specific contract. | def fetch_data_detailled_energy_use(self, start_date=None, end_date=None):
"""Get detailled energy use from a specific contract."""
if start_date is None:
start_date = datetime.datetime.now(HQ_TIMEZONE) - datetime.timedelta(days=1)
if end_date is None:
end_date = datetime... |
Get the latest data from HydroQuebec. | def fetch_data(self):
"""Get the latest data from HydroQuebec."""
# Get http session
yield from self._get_httpsession()
# Get login page
login_url = yield from self._get_login_page()
# Post login page
yield from self._post_login_page(login_url)
# Get p_p_i... |
Return collected data. | def get_data(self, contract=None):
"""Return collected data."""
if contract is None:
return self._data
if contract in self._data.keys():
return {contract: self._data[contract]}
raise PyHydroQuebecError("Contract {} not found".format(contract)) |
Posts the current state of each device to the server and schedules the next call in n seconds.: param serverURL:: return: | def ping(self):
"""
Posts the current state of each device to the server and schedules the next call in n seconds.
:param serverURL:
:return:
"""
from datetime import datetime
nextRun = datetime.utcnow().timestamp() + self.cfg.getPingInterval()
self.sendHe... |
Posts the current state to the server.: param serverURL: the URL to ping.: return: | def sendHeartbeat(self):
"""
Posts the current state to the server.
:param serverURL: the URL to ping.
:return:
"""
for name, md in self.cfg.recordingDevices.items():
try:
data = marshal(md, recordingDeviceFields)
data['serviceU... |
Schedules the next ping.: param nextRun: when we should run next.: param serverURL: the URL to ping.: return: | def scheduleNextHeartbeat(self, nextRun):
"""
Schedules the next ping.
:param nextRun: when we should run next.
:param serverURL: the URL to ping.
:return:
"""
import threading
from datetime import datetime
tilNextTime = max(nextRun - datetime.utcn... |
Validate a type or matcher argument to the constructor. | def _validate_argument(self, arg):
"""Validate a type or matcher argument to the constructor."""
if arg is None:
return arg
if isinstance(arg, type):
return InstanceOf(arg)
if not isinstance(arg, BaseMatcher):
raise TypeError(
"argumen... |
Initiaize the mapping matcher with constructor arguments. | def _initialize(self, *args, **kwargs):
"""Initiaize the mapping matcher with constructor arguments."""
self.items = None
self.keys = None
self.values = None
if args:
if len(args) != 2:
raise TypeError("expected exactly two positional arguments, "
... |
Build the docs and show them in default web browser. | def docs(ctx, output='html', rebuild=False, show=True, verbose=True):
"""Build the docs and show them in default web browser."""
sphinx_build = ctx.run(
'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format(
output=output,
all='-a -E' if rebuild else '',
... |
Upload the package to PyPI. | def upload(ctx, yes=False):
"""Upload the package to PyPI."""
import callee
version = callee.__version__
# check the packages version
# TODO: add a 'release' to automatically bless a version as release one
if version.endswith('-dev'):
fatal("Can't upload a development version (%s) to Py... |
Log an error message and exit. | def fatal(*args, **kwargs):
"""Log an error message and exit.
Following arguments are keyword-only.
:param exitcode: Optional exit code to use
:param cause: Optional Invoke's Result object, i.e.
result of a subprocess invocation
"""
# determine the exitcode to return to the o... |
This is the atomic function looped by other functions | def rungtd1d(time: Union[datetime, str, np.ndarray],
altkm: np.ndarray,
glat: float, glon: float) -> xarray.Dataset:
"""
This is the "atomic" function looped by other functions
"""
time = todt64(time)
# %% get solar parameters for date
f107Ap = gi.getApF107(time, smooth... |
Call form. save () and super itself. | def form_valid(self, form):
""" Call `form.save()` and super itself. """
form.save()
return super(SubscriptionView, self).form_valid(form) |
This is a decorator that creates an async with statement around a function and makes sure that a _session argument is always passed. Only usable on async functions of course. The _session argument is ( supposed to be ) an aiohttp. ClientSession instance in all functions that this decorator has been used on. This is use... | def _uses_aiohttp_session(func):
"""This is a decorator that creates an async with statement around a function, and makes sure that a _session argument is always passed.
Only usable on async functions of course.
The _session argument is (supposed to be) an aiohttp.ClientSession instance in all f... |
Adds the ratelimit and request timeout parameters to a function. | def _add_request_parameters(func):
"""Adds the ratelimit and request timeout parameters to a function."""
# The function the decorator returns
async def decorated_func(*args, handle_ratelimit=None, max_tries=None, request_timeout=None, **kwargs):
return await func(*args, handle_rate... |
Returns the stats for the profiles on the specified regions and platform. The format for regions without a matching user the format is the same as get_profile. The stats are returned in a dictionary with a similar format to what https:// github. com/ SunDwarf/ OWAPI/ blob/ master/ api. md#get - apiv3ubattletagstats spe... | async def get_stats(self, battletag: str, regions=(EUROPE, KOREA, AMERICAS, CHINA, JAPAN, ANY),
platform=None, _session=None, handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Returns the stats for the profiles on the specified regions and platform. The format for regions ... |
Does a request to some endpoint. This is also where ratelimit logic is handled. | async def _base_request(self, battle_tag: str, endpoint_name: str, session: aiohttp.ClientSession, *, platform=None,
handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Does a request to some endpoint. This is also where ratelimit logic is handled."""
# We check ... |
Uses aiohttp to make a get request asynchronously. Will raise asyncio. TimeoutError if the request could not be completed within _async_timeout_seconds ( default 5 ) seconds. | async def _async_get(self, session: aiohttp.ClientSession, *args, _async_timeout_seconds: int = 5,
**kwargs):
"""Uses aiohttp to make a get request asynchronously.
Will raise asyncio.TimeoutError if the request could not be completed
within _async_timeout_seconds (defa... |
Check if argument is a method. | def is_method(arg, min_arity=None, max_arity=None):
"""Check if argument is a method.
Optionally, we can also check if minimum or maximum arities
(number of accepted arguments) match given minimum and/or maximum.
"""
if not callable(arg):
return False
if not any(is_(arg) for is_ in (in... |
Check if the argument is a readable file - like object. | def _is_readable(self, obj):
"""Check if the argument is a readable file-like object."""
try:
read = getattr(obj, 'read')
except AttributeError:
return False
else:
return is_method(read, max_arity=1) |
Check if the argument is a writable file - like object. | def _is_writable(self, obj):
"""Check if the argument is a writable file-like object."""
try:
write = getattr(obj, 'write')
except AttributeError:
return False
else:
return is_method(write, min_arity=1, max_arity=1) |
loops the rungtd1d function below. Figure it s easier to troubleshoot in Python than Fortran. | def run(time: datetime, altkm: float,
glat: Union[float, np.ndarray], glon: Union[float, np.ndarray], *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
loops the rungtd1d function below. Figure it's easier to troubleshoot in Python than Fortran.
"""
glat ... |
loop over location and time | def loopalt_gtd(time: datetime,
glat: Union[float, np.ndarray], glon: Union[float, np.ndarray],
altkm: Union[float, List[float], np.ndarray], *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
loop over location and time
time: ... |
This is the atomic function looped by other functions | def rungtd1d(time: datetime,
altkm: np.ndarray,
glat: float, glon: float, *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
This is the "atomic" function looped by other functions
"""
time = todatetime(time)
# %% get solar param... |
Validate the predicate description. | def _validate_desc(self, desc):
"""Validate the predicate description."""
if desc is None:
return desc
if not isinstance(desc, STRING_TYPES):
raise TypeError(
"predicate description for Matching must be a string, "
"got %r" % (type(desc),)... |
Return the placeholder part of matcher s __repr__. | def _get_placeholder_repr(self):
"""Return the placeholder part of matcher's ``__repr__``."""
placeholder = '...'
if self.TRANSFORM is not None:
placeholder = '%s(%s)' % (self.TRANSFORM.__name__, placeholder)
return placeholder |
Ensure the matcher class definition is acceptable.: raise RuntimeError: If there is a problem | def _validate_class_definition(meta, classname, bases, dict_):
"""Ensure the matcher class definition is acceptable.
:raise RuntimeError: If there is a problem
"""
# let the BaseMatcher class be created without hassle
if meta._is_base_matcher_class_definition(classname, dict_):
... |
Checks whether given class name and dictionary define the: class: BaseMatcher. | def _is_base_matcher_class_definition(meta, classname, dict_):
"""Checks whether given class name and dictionary
define the :class:`BaseMatcher`.
"""
if classname != 'BaseMatcher':
return False
methods = list(filter(inspect.isfunction, dict_.values()))
return ... |
Return names of magic methods defined by a class.: return: Iterable of magic methods each w/ o the __ prefix/ suffix | def _list_magic_methods(meta, class_):
"""Return names of magic methods defined by a class.
:return: Iterable of magic methods, each w/o the ``__`` prefix/suffix
"""
return [
name[2:-2] for name, member in class_.__dict__.items()
if len(name) > 4 and name.startswi... |
if ( ! ( this instanceof SemVer )) return new SemVer ( version loose ) ; | def semver(version, loose):
if isinstance(version, SemVer):
if version.loose == loose:
return version
else:
version = version.version
elif not isinstance(version, str): # xxx:
raise InvalidTypeIncluded("must be str, but {!r}".format(version))
"""
if (!(t... |
Handler for the event emitted when autodoc processes a docstring. See http:// sphinx - doc. org/ ext/ autodoc. html#event - autodoc - process - docstring. | def autodoc_process_docstring(app, what, name, obj, options, lines):
"""Handler for the event emitted when autodoc processes a docstring.
See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring.
The TL;DR is that we can modify ``lines`` in-place to influence the output.
"""
# che... |
Raise ValidationError if the contact exists. | def clean_email(self):
""" Raise ValidationError if the contact exists. """
contacts = self.api.lists.contacts(id=self.list_id)['result']
for contact in contacts:
if contact['email'] == self.cleaned_data['email']:
raise forms.ValidationError(
_(u'... |
Create a contact with using the email on the list. | def add_contact(self):
""" Create a contact with using the email on the list. """
self.api.lists.addcontact(
contact=self.cleaned_data['email'], id=self.list_id, method='POST') |
Get or create an Api () instance using django settings. | def api(self):
""" Get or create an Api() instance using django settings. """
api = getattr(self, '_api', None)
if api is None:
self._api = mailjet.Api()
return self._api |
Get or create the list id. | def list_id(self):
""" Get or create the list id. """
list_id = getattr(self, '_list_id', None)
if list_id is None:
for l in self.api.lists.all()['lists']:
if l['name'] == self.list_name:
self._list_id = l['id']
if not getattr(self, '... |
Portable version of inspect. getargspec (). | def getargspec(obj):
"""Portable version of inspect.getargspec().
Necessary because the original is no longer available
starting from Python 3.6.
:return: 4-tuple of (argnames, varargname, kwargname, defaults)
Note that distinction between positional-or-keyword and keyword-only
parameters wil... |
Reads values of magic tags defined in the given Python file. | def read_tags(filename):
"""Reads values of "magic tags" defined in the given Python file.
:param filename: Python filename to read the tags from
:return: Dictionary of tags
"""
with open(filename) as f:
ast_tree = ast.parse(f.read(), filename)
res = {}
for node in ast.walk(ast_tre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.