code stringlengths 1 18.2k |
|---|
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 ycycle = trunc(((2134 * aux1) + (2816 * aux2) + 2815) / 10285... |
1 year = ycycle + (2820 * cycle) + 474 if (year <= 0): year -= 1 yday = (jd - to_jd(year, 1, 1)) + 1 if yday <= 186: month = ceil(yday / 31) else: month = ceil((yday - 6) / 30) day = int(jd - to_jd(year, month, 1)) + 1 return (year, month, day) |
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: return orig_logger_class = logging.getLoggerClass()... |
'.exc') sys.excepthook = LoggingExceptionHook(exception_logger) logging.captureWarnings(True) rawinput = 'input' if PY3K else 'raw_input' builtins._original_raw_input = getattr(builtins, rawinput) setattr(builtins, rawinput, global_logging_raw_input) global_logging_started = True |
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.stdout is stdout_logger: sys.stdout =... |
= sys.exc_info() if exc_type is not None: sys.excepthook(exc_type, exc_value, exc_traceback) del exc_type del exc_value del exc_traceback if not PY3K: sys.exc_clear() del sys.excepthook logging.captureWarnings(False) rawinput = 'input' if PY3K else 'raw_input' if hasattr(builtins, '_original_raw_input'): setattr(builti... |
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 ``name`` is configurable and both a file output and a... |
format string, and add the handler to the ``name`` logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. :param name: Logger name :param format: handler format string :param datefmt: handler date/time format specifier :param stream: add a StreamHandler using ``stream`` ... |
(default=None) :param filemode: open ``filename`` with specified filemode ('w' or 'a') :param filelevel: logger level for file logger (default=``level``) :param propagate: propagate message to parent (default=True) :returns: logging.Logger object """ # Get a logger for the specified name logger = logging.getLogger(name... |
Add handlers. Add NullHandler if no file or stream output so that # modules don't emit a warning about no handler. if not (filename or stream): logger.addHandler(logging.NullHandler()) if filename: hdlr = logging.FileHandler(filename, filemode) if filelevel is None: filelevel = level hdlr.setLevel(filelevel) hdlr.setFo... |
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 in self.handlers[:]: if isinstance(handler, logging.Stream... |
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: return # For each line in the buffer ending with \n, output that... |
echo=True) finally: self.__thread_local_ctx.write_count -= 1 |
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. """ # Gleaned from code in the logging mo... |
of IronPython, currentframe() returns None if # IronPython isn't run with -X:Frames. if f is not None: f = f.f_back rv = "(unknown module)", "(unknown file)", 0, "(unknown function)" while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) mod = inspect.getmodule(f) if mod is None: modname ... |
of this module f = f.f_back continue rv = (modname, filename, f.f_lineno, co.co_name) break return rv |
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): columns[key].append(value) return columns |
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 login url content = yield from raw_res.text() soup = BeautifulSoup(content, 'html.parser') form_node = soup.... |
login_url |
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, timeout=self._timeout, allow_redirects=False) except OSError: raise PyHydroQuebecError("Can not submit login form")... |
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 not get profile page") # Parse html content = yield from raw_res.text() soup = BeautifulSoup(content, 'htm... |
for links for node in soup.find_all('a', {"class": "big iconLink"}): for contract in contracts: if contract in node.attrs.get('href'): contracts[contract] = node.attrs.get('href') # Looking for p_p_id p_p_id = None for node in soup.find_all('span'): node_id = node.attrs.get('id', "") if node_id.startswith("p_portraitCo... |
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 PyHydroQuebecError("Can not get main page") # Parse html content = yield from raw_res.text() soup = BeautifulSoup(co... |
is not None: contracts[research.group(1).replace(" ", "")] = None if contracts == {}: raise PyHydroQuebecError("Can not found contract") return contracts |
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 from self._session.get(MAIN_URL, timeout=self._timeout) except OSError: raise PyHydroQuebecEr... |
if solde_nodes == []: raise PyHydroQuebecError("Can not found balance") for solde_node in solde_nodes: try: balance = solde_node.find("p").text except AttributeError: raise PyHydroQuebecError("Can not found balance") balances.append(float(balance[:-2] .replace(",", ".") .replace("\xa0", ""))) return balances |
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 PyHydroQuebecError("Can not get profile page for a " "specific contract") |
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: raw_res = yield from self._session.get(PROFILE_URL, params=params, timeout=self._timeout) except OS... |
get annual data") if 'courant' not in json_output.get('results')[0]: raise PyHydroQuebecAnnualError("Could not get annual data") return json_output.get('results')[0]['courant'] |
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._session.get(PROFILE_URL, params=params, timeout=self._timeout) except OSError: raise PyHydroQuebecError("Can ... |
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", "p_p_cacheability": "cacheLevelPage", "p_p_col_id": "column-2", "p_p_col_count": 1, "date": day... |
json_output['results']['listeDonneesConsoPuissanceHoraire'] params = {"p_p_id": p_p_id, "p_p_lifecycle": 2, "p_p_state": "normal", "p_p_mode": "view", "p_p_resource_id": "resourceObtenirDonneesMeteoHoraires", "p_p_cacheability": "cacheLevelPage", "p_p_col_id": "column-2", "p_p_col_count": 1, "dateDebut": day_date, "dat... |
data from Hydro-Quebec (but don't crash the app for that) hourly_weather_data = [None]*24 else: hourly_weather_data = json_output['results'][0]['listeTemperaturesHeure'] # Add temp in data processed_hourly_data = [{'hour': data['heure'], 'lower': data['consoReg'], 'high': data['consoHaut'], 'total': data['consoTotal'],... |
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.datetime.now(HQ_TIMEZONE) # Get http session yi... |
we don't have any contrats that means we have only # onecontract. Let's get it if contracts == {}: contracts = yield from self._get_lonely_contract() # For all contracts for contract, contract_url in contracts.items(): if contract_url: yield from self._load_contract_page(contract_url) data = {} dates = [(start_date + d... |
= yield from self._get_hourly_data(day_date, p_p_id) data[day_date] = hourly_data['raw_hourly_data'] # Add contract self._data[contract] = data |
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_id and contracts p_p_id, contracts = yield from self._get_p_p_id_... |
= yield from self._get_lonely_contract() # Get balance balances = yield from self._get_balances() balances_len = len(balances) balance_id = 0 # For all contracts for contract, contract_url in contracts.items(): if contract_url: yield from self._load_contract_page(contract_url) # Get Hourly data try: yesterday = datetim... |
data for some reason hourly_data = {} # Get Annual data try: annual_data = yield from self._get_annual_data(p_p_id) except PyHydroQuebecAnnualError: # We don't have annual data, which is possible if your # contract is younger than 1 year annual_data = {} # Get Monthly data monthly_data = yield from self._get_monthly_da... |
= yield from self._get_daily_data(p_p_id, start_date, end_date) except Exception: # pylint: disable=W0703 daily_data = [] # We have to test daily_data because it's empty # At the end/starts of a period if daily_data: daily_data = daily_data[0]['courant'] # format data contract_data = {"balance": balances[balance_id]} f... |
daily_data because it's empty # At the end/starts of a period if daily_data: for key1, key2 in DAILY_MAP: contract_data[key1] = daily_data[key2] # Hourly if hourly_data: contract_data['yesterday_hourly_consumption'] = hourly_data # Add contract self._data[contract] = contract_data balance_count = balance_id + 1 if bala... |
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)) |
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.sendHeartbeat() self.scheduleNextHeartbeat(nextRun) |
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['serviceURL'] = self.cfg.getServiceURL() + API_PREFIX + '/devices/' + name targetURL = self.serverURL... |
+ targetURL + " with " + str(data.keys()) + ", response is " + str(resp.status_code)) else: logger.info("Pinged server at " + targetURL + " with " + str(data.items())) except: logger.exception("Unable to ping server") |
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.utcnow().timestamp(), 0) logging.getLogger('recorder').info("Scheduling next... |
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( "argument of %s can be a type or a matcher (got %r)" % ( self.__class__.__name__, type(arg)))... |
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, " "got %s" % len(args)) if kwargs: raise TypeError( "expected positional o... |
kwargs and 'values' in kwargs has_of = 'of' in kwargs if not (has_kv or has_of): raise TypeError("expected keys/values or items matchers, " "but got: %s" % list(kwargs.keys())) if has_kv and has_of: raise TypeError( "expected keys & values, or items matchers, not both") if has_kv: # got keys= and values= matchers self.... |
a tuple of matchers, # or a single matcher for dictionary items of = kwargs['of'] if isinstance(of, tuple): try: # got of= as tuple of matchers self.keys, self.values = \ map(self._validate_argument, of) except ValueError: raise TypeError( "of= tuple has to be a pair of matchers/types" % ( self.__class__.__name__,)) el... |
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 '', verbose='-v' if verbose else '')) if not sphinx_buil... |
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 PyPI!", version) # run the upload i... |
upload to PyPI [y/N]? ") yes = answer.strip().lower() == 'y' if not yes: logging.warning("Aborted -- not uploading to PyPI.") return -2 logging.debug("Uploading version %s to PyPI...", version) setup_py_upload = ctx.run('python setup.py sdist upload') if not setup_py_upload.ok: fatal("Failed to upload version %s to PyP... |
not git_tag.ok: fatal("Failed to add a Git tag for uploaded version %s", version, cause=git_tag) git_push = ctx.run('git push && git push --tags') if not git_push.ok: fatal("Failed to push the release upstream.", cause=git_push) |
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 operating system exitcode = None if 'exitcode... |
raise TypeError( "invalid cause of fatal error: expected %r, got %r" % ( Result, type(cause))) exitcode = exitcode or cause.return_code logging.error(*args, **kwargs) raise Exit(exitcode or -1) |
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, smoothdays=81) f107a = f107Ap['f107s'].item() f107 = f10... |
float)) assert isinstance(time, np.datetime64) or (time.size == 1 and isinstance( time[0], np.datetime64)), 'if you have multiple times, for loop over them' # don't check ap, too complicated assert isinstance(MASS, (float, int)) assert len(TSELECOPS) == 25 # %% gtd7.tselec(TSELECOPS) # like the msis_driver example iyd,... |
(float, int)): Ap = [Ap]*7 # even if SW(9) == 1 due to f2py needs for array dens = np.empty((altkm.size, len(species))) temp = np.empty((altkm.size, len(ttypes))) for i, a in enumerate(altkm): dens[i, :], temp[i, :] = gtd7.gtd7(iyd, utsec, a, glat, glon, stl, f107a, f107, Ap, MASS) dsf = {k: (('time', 'alt_km', 'lat', ... |
'alt_km', 'lat', 'lon'), temp[:, 1][None, :, None, None]), 'Texo': (('time', 'alt_km', 'lat', 'lon'), temp[:, 0][None, :, None, None])}) atmos = xarray.Dataset(dsf, coords={'time': time.astype(datetime), 'alt_km': altkm, 'lat': [glat], 'lon': [glon], }, attrs={'Ap': Ap, 'f107': f107, 'f107a': f107a, 'species': species}... |
def form_valid(self, form): """ Call `form.save()` and super itself. """ form.save() return super(SubscriptionView, self).form_valid(form) |
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 functions that this decor... |
entered and exited, or that they are passed into a function properly. This adds an session keyword argument to the method signature, and that session will be used as _session if it is not None.""" # The function the decorator returns async def decorated_func(*args, session=None, **kwargs): if session is not None: # The... |
The session argument wasn't passed, so we create our own async with aiohttp.ClientSession() as new_session: return await func(*args, _session=new_session, **kwargs) # We return the decorated func return decorated_func |
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_ratelimit=handle_ratelimit, max_tries=max... |
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 without a matching user, the for... |
self.default_platform try: blob_dict = await self._base_request(battletag, "stats", _session, platform=platform, handle_ratelimit=handle_ratelimit, max_tries=max_tries, request_timeout=request_timeout) except ProfileNotFoundError as e: # The battletag doesn't exist blob_dict = {} existing_regions = {key: val for key, v... |
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 the different optional arguments, and if the... |
= self.default_handle_ratelimit if max_tries is None: max_tries = self.default_max_tries if request_timeout is None: request_timeout = self.default_request_timeout # The battletag with #s removed san_battle_tag = self.sanitize_battletag(battle_tag) # The ratelimit logic for _ in range(max_tries): # We execute a request... |
searching on headers={"User-Agent": "overwatch_python_api"}, # According to https://github.com/SunDwarf/OWAPI/blob/master/owapi/v3/v3_util.py#L18 we have to customise our User-Agent, so we do _async_timeout_seconds=request_timeout ) if status == 429 and resp_json["msg"] == "you are being ratelimited": raise RatelimitEr... |
ratelimited, so we check if we handle ratelimiting logic # If so, we wait and then execute the next iteration of the loop if handle_ratelimit: # We wait to remedy ratelimiting, and we wait a bit more than the response says we should await asyncio.sleep(resp_json["retry"] + 1) continue else: raise else: # We didn't get ... |
was a successful request break else: # The loop didn't stop because it got breaked, which means that we got ratelimited until the maximum number of tries were finished raise RatelimitError("Got ratelimited for each requests until the maximum number of retries were reached.") # Validate the response if status != 200: if... |
HTTP 404, profile not found. This is caused by the given battletag not existing on the specified platform.") if status == 429 and resp_json["msg"] == "you are being ratelimited": raise RatelimitError( "Got HTTP 429, you are being ratelimited. This is caused by calls to the api too frequently.") raise ConnectionError("D... |
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 (default 5) seconds.""" # Taken almost directly from the... |
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 (inspect.ismethod, inspect.ismethodde... |
inspectable, # so if it's file.read() or file.write(), we can't tell it for sure. # Given how this check is being used, assuming the best is probably # all we can do here. return True else: if argnames and argnames[0] == 'self': argnames = argnames[1:] if min_arity is not None: actual_min_arity = len(argnames) - len(de... |
of %r found to be negative (got %s)!" % ( arg, actual_min_arity)) if int(min_arity) != actual_min_arity: return False if max_arity is not None: actual_max_arity = sys.maxsize if varargs or kwargs else len(argnames) if int(max_arity) != actual_max_arity: return False return True |
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) |
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) |
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 = np.atleast_2d(glat) glon = np.... |
1 and isinstance(time, (str, date, datetime, np.datetime64)): atmos = rungtd1d(time, altkm, glat.squeeze()[()], glon.squeeze()[()], f107a=f107a, f107=f107, Ap=Ap) # %% lat/lon grid at 1 altitude else: atmos = loopalt_gtd(time, glat, glon, altkm, f107a=f107a, f107=f107, Ap=Ap) return atmos |
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: datetime or numpy.datetime64 or list of datetime or np.ndarra... |
glat = np.atleast_2d(glat) glon = np.atleast_2d(glon) assert glat.ndim == glon.ndim == 2 times = np.atleast_1d(time) assert times.ndim == 1 atmos = xarray.Dataset() for k, t in enumerate(times): print('computing', t) for i in range(glat.shape[0]): for j in range(glat.shape[1]): # atmos = xarray.concat((atmos, rungtd1d(... |
atm.attrs return atmos |
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 parameters for date if f107a and f107a and Ap: pass else: f107Ap... |
= f107Ap['Ap'].item() # %% dimensions altkm = np.atleast_1d(altkm) assert altkm.ndim == 1 assert isinstance(glon, (int, float)) assert isinstance(glat, (int, float)) # %% iyd = time.strftime('%y%j') altkm = np.atleast_1d(altkm) # %% dens = np.empty((altkm.size, len(species))) temp = np.empty((altkm.size, len(ttypes))) ... |
dens[i, :] = np.genfromtxt(f, max_rows=1) temp[i, :] = np.genfromtxt(f, max_rows=1) dsf = {k: (('time', 'alt_km', 'lat', 'lon'), v[None, :, None, None]) for (k, v) in zip(species, dens.T)} dsf.update({'Tn': (('time', 'alt_km', 'lat', 'lon'), temp[:, 1][None, :, None, None]), 'Texo': (('time', 'alt_km', 'lat', 'lon'), t... |
f107a, 'species': species}) return atmos |
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),)) # Python 2 mandates __repr__ to be an ASCII string, # so if Unicode is passed (... |
desc = desc.encode('ascii', errors='strict') except UnicodeEncodeError: raise TypeError("predicate description must be " "an ASCII string in Python 2") return desc |
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 |
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_): return # ensure that no important magic m... |
name = name[2:-2] if not name: continue # unlikely case of a ``____`` function if name not in meta._list_magic_methods(BaseMatcher): continue if name in meta.USER_OVERRIDABLE_MAGIC_METHODS: continue # non-function attributes, like __slots__, are harmless if not inspect.isfunction(member): continue # classes in this ver... |
"matcher class %s cannot override the __%s__ method" % ( classname, name)) |
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 methods and all(m.__module__ == __name__ for m in methods) |
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.startswith('__') and name.endswith('__') and inspect.isfunction(... |
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 (!(this instanceof SemVer)) return new SemVer(version, loose); """ ret... |
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. """ # check that only symbols ... |
is not a part of the public API!" % name) # for classes exempt from automatic merging of class & __init__ docs, # pretend their __init__ methods have no docstring at all, # so that nothing will be appended to the class's docstring if what == 'class' and name in autoclass_content_exceptions: # amusingly, when autodoc re... |
class docstring, it will report ``what`` # as 'class' (again!); hence we must check what it actually read ctor_docstring_lines = prepare_docstring(obj.__init__.__doc__) if lines == ctor_docstring_lines: lines[:] = [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.