text stringlengths 81 112k |
|---|
Gather a batch of samples by indices, applying the mapping
described by the (optional) `indices` array passed to the
constructor.
Parameters
----------
indices: 1D-array of ints or slice
The samples to retrieve
Returns
-------
list of arrays
... |
Create an iterator that generates mini-batch sample indices.
The batches will have `batch_size` elements, with the exception
of the final batch which will have less if there are insufficient
elements left to make a complete batch.
If `shuffle` is `None` or `False` elements will be extra... |
Create an iterator that generates mini-batches extracted from
this data source. The batches will have `batch_size` elements, with
the exception of the final batch which will have less if there are
insufficient elements left to make a complete batch.
If `shuffle` is `None` or `False` el... |
Gather a batch of samples by indices *without* applying any index
mapping resulting from the (optional) use of the `indices` array
passed to the constructor.
Parameters
----------
indices: 1D-array of ints or slice
The samples to retrieve
Returns
---... |
Get the number of samples in this data source.
Returns
-------
int, `np.inf` or `None`.
An int if the number of samples is known, `np.inf` if it is
infinite or `None` if the number of samples is unknown.
def num_samples(self, **kwargs):
"""
Get the numbe... |
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: list of either 1D-array of ints or slice
A list of index arrays or slices; one for each data source
that identify the samples to access
Returns
... |
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Pa... |
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: a tuple of the form `(dataset_index, sample_indices)`
The `dataset_index` identifies the dataset from which to draw
samples while `sample_indices` identifies... |
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Pa... |
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested list of arrays
A min... |
Gather a batch of samples by indices, applying any index
mapping defined by the underlying data sources.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested li... |
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Pa... |
Purge environment database and uploaded files
Usage:
datacats purge [-s NAME | --delete-environment] [-y] [ENVIRONMENT]
Options:
--delete-environment Delete environment directory as well as its data, as
well as the data for **all** sites.
-s --site=NAME Specify a site to be pu... |
Print the error message to stdout with colors and borders
def pretty_print(self):
"""
Print the error message to stdout with colors and borders
"""
print colored.blue("-" * 40)
print colored.red("datacats: problem was encountered:")
print self.message
print color... |
Return a 16-character alphanumeric random string generated by the
operating system's secure pseudo random number generator
def generate_password():
"""
Return a 16-character alphanumeric random string generated by the
operating system's secure pseudo random number generator
"""
chars = uppercas... |
This method calls to docker-machine on the command line and
makes sure that it is up and ready.
Potential improvements to be made:
- Support multiple machine names (run a `docker-machine ls` and then
see which machines are active. Use a priority list)
def _machine_check_connectivity():
"""... |
ro and rw {localdir: binddir} dicts to docker-py's
{localdir: {'bind': binddir, 'ro': T/F}} binds dicts
def ro_rw_to_binds(ro, rw):
"""
ro and rw {localdir: binddir} dicts to docker-py's
{localdir: {'bind': binddir, 'ro': T/F}} binds dicts
"""
out = {}
if ro:
for localdir, binddir i... |
Run a single command in a web image optionally preloaded with the ckan
source and virtual envrionment.
:param command: command to execute
:param ro: {localdir: binddir} dict for read-only volumes
:param rw: {localdir: binddir} dict for read-write volumes
:param links: links passed to start
:par... |
Wraps web_command function with docker bindings needed to connect to
a remote server (such as datacats.com) and run commands there
(for example, when you want to copy your catalog to that server).
The files binded to the docker image include the user's ssh credentials:
ssh_config file,
... |
Wrapper for docker create_container, start calls
:param log_syslog: bool flag to redirect container's logs to host's syslog
:returns: container info dict or None if container couldn't be created
Raises PortAllocatedError if container couldn't start on the
requested port.
def run_container(name, imag... |
Wrapper for docker remove_container
:returns: True if container was found and removed
def remove_container(name, force=False):
"""
Wrapper for docker remove_container
:returns: True if container was found and removed
"""
try:
if not force:
_get_docker().stop(name)
exc... |
Wrapper for docker logs, attach commands.
def container_logs(name, tail, follow, timestamps):
"""
Wrapper for docker logs, attach commands.
"""
if follow:
return _get_docker().attach(
name,
stdout=True,
stderr=True,
stream=True
)
... |
Returns a string representation of the logs from a container.
This is similar to container_logs but uses the `follow` option
and flattens the logs into a string instead of a generator.
:param name: The container name to grab logs for
:return: A string representation of the logs
def collect_logs(name):... |
Return generator of pull status objects
def pull_stream(image):
"""
Return generator of pull status objects
"""
return (json.loads(s) for s in _get_docker().pull(image, stream=True)) |
create "data-only container" if it doesn't already exist.
We'd like to avoid these, but postgres + boot2docker make
it difficult, see issue #5
def data_only_container(name, volumes):
"""
create "data-only container" if it doesn't already exist.
We'd like to avoid these, but postgres + boot2docker... |
The main entry point for datacats cli tool
(as defined in setup.py's entry_points)
It parses the cli arguments for corresponding options
and runs the corresponding command
def main():
"""
The main entry point for datacats cli tool
(as defined in setup.py's entry_points)
It parses the cli ... |
Return (subcommand, (possibly adjusted) arguments for that subcommand)
Returns (None, args) when no subcommand is found
Parsing our arguments is hard. Each subcommand has its own docopt
validation, and some subcommands (paster and shell) have positional
options (some options passed to datacats and oth... |
Create containers and start serving environment
Usage:
datacats start [-b] [--site-url SITE_URL] [-p|--no-watch] [-s NAME]
[-i] [--syslog] [--address=IP] [ENVIRONMENT [PORT]]
datacats start -r [-b] [--site-url SITE_URL] [-s NAME] [--syslog]
[-i] [--address=IP] [ENVIRONMENT]
Optio... |
Reload environment source and configuration
Usage:
datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL]
[-i] [--address=IP] [ENVIRONMENT [PORT]]
datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE_URL]
[-i] ... |
Display information about environment and running containers
Usage:
datacats info [-qr] [ENVIRONMENT]
Options:
-q --quiet Echo only the web URL or nothing if not running
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
def info(environment, opts):
"""Display... |
Display or follow container logs
Usage:
datacats logs [--postgres | --solr | --datapusher] [-s NAME] [-tr] [--tail=LINES] [ENVIRONMENT]
datacats logs -f [--postgres | --solr | --datapusher] [-s NAME] [-r] [ENVIRONMENT]
Options:
--datapusher Show logs for datapusher instead of web logs
--postgres ... |
Open web browser window to this environment
Usage:
datacats open [-r] [-s NAME] [ENVIRONMENT]
Options:
-s --site=NAME Choose a site to open [default: primary]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
def open_(environment, opts):
# pylint: disable=unused... |
Commands operating on environment data
Usage:
datacats tweak --install-postgis [ENVIRONMENT]
datacats tweak --add-redis [ENVIRONMENT]
datacats tweak --admin-password [ENVIRONMENT]
Options:
--install-postgis Install postgis in ckan database
--add-redis Adds redis next time this environment reload... |
A wrapper around the normal split function that ignores any trailing /.
:return: A tuple of the form (dirname, last) where last is the last element
in the path.
def _split_path(path):
"""
A wrapper around the normal split function that ignores any trailing /.
:return: A tuple of the form... |
After this command, your environment will be converted to format version {}.
and will only work with datacats version exceeding and including 1.0.0.
This migration is necessary to support multiple sites within the same environment.
Your current site will be kept and will be named "primary".
Would you like to continue ... |
After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintained if you
wish to do a migration... |
Converts an environment TO the version specified by `version`.
:param datadir: The datadir to convert.
:param version: The version to convert TO.
:param always_yes: True if the user shouldn't be prompted about the migration.
def convert_environment(datadir, version, always_yes):
"""
Converts an env... |
Fetch the history of a flight by its number.
This method can be used to get the history of a flight route by the number.
It checks the user authentication and returns the data accordingly.
Args:
flight_number (str): The flight number, e.g. AI101
page (int): Optional pag... |
Fetch the history of a particular aircraft by its tail number.
This method can be used to get the history of a particular aircraft by its tail number.
It checks the user authentication and returns the data accordingly.
Args:
tail_number (str): The tail number, e.g. VT-ANL
... |
Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Example::
from pyflightdata import ... |
Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the aircraft.
It checks the user authentication and returns the dat... |
Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
Returns:
A list of dicts, one for each aircraft in the ... |
Get the flights for a particular airline.
Given a full or partial flight number string, this method returns the first 100 flights matching that string.
Please note this method was different in earlier versions. The older versions took an airline code and returned all scheduled flights for that airline... |
Get the flights for a particular origin and destination.
Given an origin and destination this method returns the upcoming scheduled flights between these two points.
The data returned has the airline, airport and schedule information - this is subject to change in future.
Args:
ori... |
Retrieve the weather at an airport
Given the IATA code of an airport, this method returns the weather information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher p... |
Retrieve the metar data at the current time
Given the IATA code of an airport, this method returns the metar information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in h... |
Retrieve the metar data for past 72 hours. The data will not be parsed to readable format.
Given the IATA code of an airport, this method returns the metar information for last 72 hours.
Args:
iata (str): The IATA code for an airport, e.g. HYD
Returns:
The metar data f... |
Retrieve the performance statistics at an airport
Given the IATA code of an airport, this method returns the performance statistics for the airport.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with fligh... |
Retrieve the details of an airport
Given the IATA code of an airport, this method returns the detailed information like lat lon, full name, URL, codes etc.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan wit... |
Fetch the images of a particular aircraft by its tail number.
This method can be used to get the images of the aircraft. The images are in 3 sizes and you can use what suits your need.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for u... |
Login to the flightradar24 session
The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans.
For users who have signed up for a plan, this method allows to login with the credentials from flightradar24. The API obtains
a tok... |
Simple method that decodes a given metar string.
Args:
metar (str): The metar data
Returns:
The metar data in readable format
Example::
from pyflightdata import FlightData
f=FlightData()
f.decode_metar('WSSS 181030Z 04009KT 010V080 ... |
Get the pyrad authentication packet for the username/password and the
given pyrad client.
def _get_auth_packet(self, username, password, client):
"""
Get the pyrad authentication packet for the username/password and the
given pyrad client.
"""
pkt = client.CreateAuthPack... |
Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>).
def _get_client(self, server):
"""
Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>).
"""
retu... |
Perform the actual radius authentication by passing the given packet
to the server which `client` is bound to.
Returns True or False depending on whether the user is authenticated
successfully.
def _perform_radius_auth(self, client, packet):
"""
Perform the actual radius authent... |
Authenticate the given username/password against the RADIUS server
described by `server`.
def _radius_auth(self, server, username, password):
"""
Authenticate the given username/password against the RADIUS server
described by `server`.
"""
client = self._get_client(serve... |
Get the Django user with the given username, or create one if it
doesn't already exist. If `password` is given, then set the user's
password to that (regardless of whether the user was created or not).
def get_django_user(self, username, password=None):
"""
Get the Django user with the ... |
Check credentials against RADIUS server and return a User object or
None.
def authenticate(self, request, username=None, password=None):
"""
Check credentials against RADIUS server and return a User object or
None.
"""
if isinstance(username, basestring):
use... |
Check credentials against the RADIUS server identified by `realm` and
return a User object or None. If no argument is supplied, Django will
skip this backend and try the next one (as a TypeError will be raised
and caught).
def authenticate(self, request, username=None, password=None, realm=None... |
Closes then moves the file to dst.
def move(self, dst):
"Closes then moves the file to dst."
self.close()
shutil.move(self.path, dst) |
Remove any fluctuated data points by magnitudes.
Parameters
----------
date : array_like
An array of dates.
mag : array_like
An array of magnitudes.
err : array_like
An array of magnitude errors.
threshold : float, optional
Threshold for sigma-clipping.
itera... |
Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}.
def from_spec(spec):
"""Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 spe... |
Validate an object according to its own AND an externally imposed schema.
def validate(obj, schema):
"""Validate an object according to its own AND an externally imposed schema."""
if not framework.EvaluationContext.current().validate:
# Short circuit evaluation when disabled
return obj
# Validate retur... |
Attach the given schema to the given object.
def attach(obj, schema):
"""Attach the given schema to the given object."""
# We have a silly exception for lists, since they have no 'attach_schema'
# method, and I don't feel like making a subclass for List just to add it.
# So, we recursively search the list for... |
Return a list of entire features.
A set of entire features regardless of being used to train a model or
predict a class.
Returns
-------
feature_names : list
A list of features' names.
def get_feature_set_all():
"""
Return a list of entire features.
A set of entire features r... |
A property that returns all of the model's parameters.
def parameters(self):
""" A property that returns all of the model's parameters. """
parameters = []
for hl in self.hidden_layers:
parameters.extend(hl.parameters)
parameters.extend(self.top_layer.parameters)
ret... |
Used to set all of the model's parameters to new values.
**Parameters:**
value : array_like
New values for the model parameters. Must be of length
``self.n_parameters``.
def parameters(self, value):
""" Used to set all of the model's parameters to new values.
... |
Returns an MD5 digest of the model.
This can be used to easily identify whether two models have the
same architecture.
def checksum(self):
""" Returns an MD5 digest of the model.
This can be used to easily identify whether two models have the
same architecture.
"""
... |
Evaluate the loss function without computing gradients.
**Parameters:**
input_data : GPUArray
Data to evaluate
targets: GPUArray
Targets
return_cache : bool, optional
Whether to return intermediary variables from the
computation and the... |
Perform a full forward and backward pass through the model.
**Parameters:**
input_data : GPUArray
Data to train the model with.
targets : GPUArray
Training targets.
**Returns:**
loss : float
Value of loss function as evaluated on the data ... |
Run data forward through the model.
**Parameters:**
input_data : GPUArray
Data to run through the model.
return_cache : bool, optional
Whether to return the intermediary results.
prediction : bool, optional
Whether to run in prediction mode. Only r... |
Derive not-period-based features.
def shallow_run(self):
"""Derive not-period-based features."""
# Number of data points
self.n_points = len(self.date)
# Weight calculation.
# All zero values.
if not self.err.any():
self.err = np.ones(len(self.mag)) * np.std... |
Derive period-based features.
def deep_run(self):
"""Derive period-based features."""
# Lomb-Scargle period finding.
self.get_period_LS(self.date, self.mag, self.n_threads, self.min_period)
# Features based on a phase-folded light curve
# such as Eta, slope-percentile, etc.
... |
Period finding using the Lomb-Scargle algorithm.
Finding two periods. The second period is estimated after whitening
the first period. Calculating various other features as well
using derived periods.
Parameters
----------
date : array_like
An array of obser... |
Get uncertainty of a period.
The uncertainty is defined as the half width of the frequencies
around the peak, that becomes lower than average + standard deviation
of the power spectrum.
Since we may not have fine resolution around the peak,
we do not assume it is gaussian. So, ... |
Residual of Fourier Series.
Parameters
----------
pars : array_like
Fourier series parameters.
x : array_like
An array of date.
y : array_like
An array of true values to fit.
order : int
An order of Fourier Series.
def res... |
Function to fit Fourier Series.
Parameters
----------
x : array_like
An array of date divided by period. It doesn't need to be sorted.
pars : array_like
Fourier series parameters.
order : int
An order of Fourier series.
def fourier_series(se... |
Return Stetson K feature.
Parameters
----------
mag : array_like
An array of magnitude.
avg : float
An average value of magnitudes.
err : array_like
An array of magnitude errors.
Returns
-------
stetson_k : float
... |
Return ratio of amplitude of higher and lower magnitudes.
A ratio of amplitude of higher and lower magnitudes than average,
considering weights. This ratio, by definition, should be higher
for EB than for others.
Parameters
----------
mag : array_like
An ar... |
Return ratio of amplitude of higher and lower magnitudes.
A ratio of amplitude of higher and lower magnitudes than average,
considering weights. This ratio, by definition, should be higher
for EB than for others.
Parameters
----------
mag : array_like
An ar... |
Return Eta feature.
Parameters
----------
mag : array_like
An array of magnitudes.
std : array_like
A standard deviation of magnitudes.
Returns
-------
eta : float
The value of Eta index.
def get_eta(self, mag, std):
... |
Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Returns
-------
per_10 : float
10% pe... |
Return max - min of cumulative sum.
Parameters
----------
mag : array_like
An array of magnitudes.
Returns
-------
mm_cusum : float
Max - min of cumulative sum.
def get_cusum(self, mag):
"""
Return max - min of cumulative sum.
... |
Return all features with its names.
Returns
-------
names : list
Feature names.
values : list
Feature values
def get_features2(self):
"""
Return all features with its names.
Returns
-------
names : list
Featur... |
Return all features with its names.
Regardless of being used for train and prediction. Sorted by the names.
Returns
-------
all_features : OrderedDict
Features dictionary.
def get_features_all(self):
"""
Return all features with its names.
Regardle... |
Initialize Hebel.
This function creates a CUDA context, CUBLAS context and
initializes and seeds the pseudo-random number generator.
**Parameters:**
device_id : integer, optional
The ID of the GPU device to use. If this is omitted, PyCUDA's
default context is used, which by defaul... |
Instantiate a Tuple from a TupleNode.
Walking the AST tree upwards, evaluate from the root down again.
def inflate_context_tuple(ast_rootpath, root_env):
"""Instantiate a Tuple from a TupleNode.
Walking the AST tree upwards, evaluate from the root down again.
"""
with util.LogTime('inflate_context_tuple'):... |
Return a dict of { name => Completions } for the given tuple node.
Enumerates all keys that are in scope in a given tuple. The node
part of the tuple may be None, in case the binding is a built-in.
def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False):
"""Return a dict of { name => Co... |
Returns a dict of { name => Completions }.
def find_deref_completions(ast_rootpath, root_env=gcl.default_env):
"""Returns a dict of { name => Completions }."""
with util.LogTime('find_deref_completions'):
tup = inflate_context_tuple(ast_rootpath, root_env)
path = path_until(ast_rootpath, is_deref_node)
... |
Return whether the cursor is in identifier-position in a member declaration.
def is_identifier_position(rootpath):
"""Return whether the cursor is in identifier-position in a member declaration."""
if len(rootpath) >= 2 and is_tuple_member_node(rootpath[-2]) and is_identifier(rootpath[-1]):
return True
if le... |
Find completions at the cursor.
Return a dict of { name => Completion } objects.
def find_completions_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find completions at the cursor.
Return a dict of { name => Completion } objects.
"""
q = gcl.SourceQuery(filename, line, col - 1)
ro... |
Return completion keys from INHERITED tuples.
Easiest way to get those is to evaluate the tuple, check if it is a CompositeTuple,
then enumerate the keys that are NOT in the rightmost tuple.
def find_inherited_key_completions(rootpath, root_env):
"""Return completion keys from INHERITED tuples.
Easiest way t... |
Find the value of the object under the cursor.
def find_value_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find the value of the object under the cursor."""
q = gcl.SourceQuery(filename, line, col)
rootpath = ast_tree.find_tokens(q)
rootpath = path_until(rootpath, is_thunk)
if len(... |
Add a vector to a matrix
def add_vec_to_mat(mat, vec, axis=None, inplace=False,
target=None, substract=False):
""" Add a vector to a matrix
"""
assert mat.flags.c_contiguous
if axis is None:
if vec.shape[0] == mat.shape[0]:
axis = 0
elif vec.shape[0] == ... |
Normalize each column vector in mat to length
max_vec_norm if it is longer than max_vec_norm
def vector_normalize(mat, max_vec_norm=1.):
""" Normalize each column vector in mat to length
max_vec_norm if it is longer than max_vec_norm
"""
assert mat.flags.c_contiguous
n, m = mat.shape
vecto... |
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string
def preprocess(string):
"""
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
... |
splits a string into a list of tokens
each is either a string containing no numbers
or a float
def tokenize_by_number(s):
""" splits a string into a list of tokens
each is either a string containing no numbers
or a float """
r = find_number(s)
if r == None:
return ... |
cmp function for sorting a list of strings by alphabetical order, but with
numbers sorted numerically.
i.e., foo1, foo2, foo10, foo11
instead of foo1, foo10
def number_aware_alphabetical_cmp(str1, str2):
""" cmp function for sorting a list of strings by alphabetical order, but with
... |
wrong: a mispelling
candidates: a set of correct words
returns a guess of which candidate is the right one
This should be used with a small number of candidates and a high potential
edit distance.
ie, use it to correct a wrong filename in a directory, wrong class name
i... |
Returns s with all non-alphanumeric characters replaced with *
def censor_non_alphanum(s):
"""
Returns s with all non-alphanumeric characters replaced with *
"""
def censor(ch):
if (ch >= 'A' and ch <= 'z') or (ch >= '0' and ch <= '9'):
return ch
return '*'
return ''.j... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.