INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
create data - only container if it doesn t already exist. | 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 make
it difficult, see issue #5
"""
info = inspect_container(name)
if info:
return
c = _get_docker().create_container(
... |
The main entry point for datacats cli tool | def main():
"""
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
"""
# pylint: disable=bare-except
try:
command_fn, opts = _parse_arguments(sys.argv[1:])
... |
Return ( subcommand ( possibly adjusted ) arguments for that subcommand ) | def _subcommand_arguments(args):
"""
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
opt... |
Create containers and start serving environment | def start(environment, opts):
"""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... |
Reload environment source and configuration | def reload_(environment, opts):
"""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... |
Display information about environment and running containers | def info(environment, opts):
"""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: '.'
"""
... |
Display or follow container logs | def logs(environment, opts):
"""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 inst... |
Open web browser window to this environment | def open_(environment, opts):
# pylint: disable=unused-argument
"""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 director... |
Commands operating on environment data | def tweak(environment, opts):
"""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 re... |
A wrapper around the normal split function that ignores any trailing/. | def _split_path(path):
"""
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.
"""
# Get around a quirk in path_split where a / at the end will make the
# dirname (split[0])... |
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. | def _one_to_two(datadir):
"""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 "prima... |
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 ba... | def _two_to_one(datadir):
"""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 maintai... |
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 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.
"""
# Si... |
Fetch the history of a flight by its number. | def get_history_by_flight_number(self, flight_number, page=1, limit=100):
"""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:
fl... |
Fetch the history of a particular aircraft by its tail number. | def get_history_by_tail_number(self, tail_number, page=1, limit=100):
"""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.
... |
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 | def get_airports(self, country):
"""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
Exam... |
Fetch the details of a particular aircraft by its tail number. | def get_info_by_tail_number(self, tail_number, page=1, limit=100):
"""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 ... |
Get the fleet for a particular airline. | def get_fleet(self, airline_key):
"""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... |
Get the flights for a particular airline. | def get_flights(self, search_key):
"""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 r... |
Get the flights for a particular origin and destination. | def get_flights_from_to(self, origin, destination):
"""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... |
Retrieve the weather at an airport | def get_airport_weather(self, iata, page=1, limit=100):
"""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 u... |
Retrieve the metar data at the current time | def get_airport_metars(self, iata, page=1, limit=100):
"""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;... |
Retrieve the metar data for past 72 hours. The data will not be parsed to readable format. | def get_airport_metars_hist(self, iata):
"""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... |
Retrieve the performance statistics at an airport | def get_airport_stats(self, iata, page=1, limit=100):
"""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 (i... |
Retrieve the details of an airport | def get_airport_details(self, iata, page=1, limit=100):
"""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
... |
Fetch the images of a particular aircraft by its tail number. | def get_images_by_tail_number(self, tail_number, page=1, limit=100):
"""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): ... |
Login to the flightradar24 session | def login(self, email, password):
"""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... |
Simple method that decodes a given metar string. | def decode_metar(self, metar):
"""
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()
... |
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.CreateAuthPacket(code=AccessRequest,
User_Name=username)
pkt["User-... |
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>).
"""
return Client(
server=server[0],
authport=server[1],
secret=server[2],
dict=sel... |
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 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.
"""
try:
... |
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(server)
packet = self._get_auth_packet(username, password, client)
return self._perform_... |
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 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).
"""
try:
... |
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):
username = username.encode('utf-8')
if isinstance(password, basestring):
... |
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):
"""
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... |
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. | def sigma_clipping(date, mag, err, threshold=3, iteration=1):
"""
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.
t... |
Return a schema object from a spec. | 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 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}.
"""
if spec == '':
return any_schema
if framework.is_str(spec):
# Scalar type
if spec not... |
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 returned object according to its own schema
if hasattr(obj, 'tuple_schema'):
... |
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 tuples and attach the schema in
# there.
... |
Return a list of entire features. | def get_feature_set_all():
"""
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.
"""
features = get_feature_set()
features.append('cu... |
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)
return parameters |
Used to set all of the model s parameters to new values. | def parameters(self, value):
""" 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``.
"""
if len(value) != self.n_parameters:
... |
Returns an MD5 digest of the model. | def checksum(self):
""" Returns an MD5 digest of the model.
This can be used to easily identify whether two models have the
same architecture.
"""
m = md5()
for hl in self.hidden_layers:
m.update(str(hl.architecture))
m.update(str(self.top_la... |
Evaluate the loss function without computing gradients. | def evaluate(self, input_data, targets,
return_cache=False, prediction=True):
""" Evaluate the loss function without computing gradients.
**Parameters:**
input_data : GPUArray
Data to evaluate
targets: GPUArray
Targets
return_cache : b... |
Perform a full forward and backward pass through the model. | def training_pass(self, input_data, targets):
""" 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
... |
Run data forward through the model. | def feed_forward(self, input_data, return_cache=False, prediction=True):
""" 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.
... |
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(self.mag)
# Some zero valu... |
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.
# Should be called after t... |
Period finding using the Lomb - Scargle algorithm. | def get_period_LS(self, date, mag, n_threads, min_period):
"""
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.
Parame... |
Get uncertainty of a period. | def get_period_uncertainty(self, fx, fy, jmax, fx_width=100):
"""
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 h... |
Residual of Fourier Series. | def residuals(self, pars, x, y, order):
"""
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.
... |
Function to fit Fourier Series. | def fourier_series(self, pars, x, order):
"""
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
... |
Return Stetson K feature. | def get_stetson_k(self, mag, avg, err):
"""
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.
... |
Return ratio of amplitude of higher and lower magnitudes. | def half_mag_amplitude_ratio(self, mag, avg, weight):
"""
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.
... |
Return ratio of amplitude of higher and lower magnitudes. | def half_mag_amplitude_ratio2(self, mag, avg):
"""
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.
Param... |
Return Eta feature. | def get_eta(self, mag, std):
"""
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 ... |
Return 10% and 90% percentile of slope. | def slope_percentile(self, date, mag):
"""
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.
Return... |
Return max - min of cumulative sum. | def get_cusum(self, mag):
"""
Return max - min of cumulative sum.
Parameters
----------
mag : array_like
An array of magnitudes.
Returns
-------
mm_cusum : float
Max - min of cumulative sum.
"""
c = np.cumsum(mag ... |
Return all features with its names. | def get_features2(self):
"""
Return all features with its names.
Returns
-------
names : list
Feature names.
values : list
Feature values
"""
feature_names = []
feature_values = []
# Get all the names of features.... |
Return all features with its names. | def get_features_all(self):
"""
Return all features with its names.
Regardless of being used for train and prediction. Sorted by the names.
Returns
-------
all_features : OrderedDict
Features dictionary.
"""
features = {}
# Get all ... |
Initialize Hebel. | def init(device_id=None, random_seed=None):
"""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... |
Instantiate a Tuple from a TupleNode. | 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'):
# We only need to look at tuple members going down.
inflated = ast_rootpath[0].eval(root_env)
... |
Return a dict of { name = > Completions } for the given tuple node. | def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False):
"""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.
"""
with util.LogTime('enu... |
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)
if not path:
return {}
deref = pa... |
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 len(rootpath) >= 1 and is_tuple_node(rootpath[-1]):
# No deeper node than tu... |
Find completions at the cursor. | 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)
rootpath = ast_tree.find_tokens(q)
if is_identifier_position(rootpath):
return f... |
Return completion keys from INHERITED tuples. | def find_inherited_key_completions(rootpath, root_env):
"""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.
"""
tup = inflate_context_tuple(rootpath, root_env)
if is... |
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(rootpath) <= 1:
# Just the file tuple itself... |
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] == mat.shape[1]:
... |
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
vector_normalize_kernel.prepared_call(
(m, 1, 1), (32, 1, 1),
mat.gpudata,
np.f... |
Preprocesses a string by replacing $ { VARNAME } with os. environ [ VARNAME ] | def preprocess(string):
"""
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string
"""
split = string.split('${')
rval = [split[0]]
for candidate... |
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 [ s ]
else:
tokens = []
if r[0] > 0:
tokens.append(s[0:r[0]])
tokens.app... |
cmp function for sorting a list of strings by alphabetical order but with numbers sorted numerically. | def number_aware_alphabetical_cmp(str1, str2):
""" 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 flatten_tokens(tokens):
l = []
for token in tokens... |
wrong: a mispelling candidates: a set of correct words | def match(wrong, candidates):
"""
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 filen... |
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 ''.join([censor(ch) for ch in s]) |
Check if a given period is possibly an alias. | def is_period_alias(period):
"""
Check if a given period is possibly an alias.
Parameters
----------
period : float
A period to test if it is a possible alias or not.
Returns
-------
is_alias : boolean
True if the given period is in a range of period alias.
"""
... |
Serialize object to a file denoted by filepath. | def save(filepath, obj, on_overwrite = 'ignore'):
"""
Serialize `object` to a file denoted by `filepath`.
Parameters
----------
filepath : str
A filename. If the suffix is `.joblib` and joblib can be
imported, `joblib.dump` is used in place of the regular
pickling mechanisms... |
Allow configuration of the pickle protocol on a per - machine basis. This way if you use multiple platforms with different versions of pickle you can configure each of them to use the highest protocol supported by all of the machines that you want to be able to communicate. | def get_pickle_protocol():
"""
Allow configuration of the pickle protocol on a per-machine basis.
This way, if you use multiple platforms with different versions of
pickle, you can configure each of them to use the highest protocol
supported by all of the machines that you want to be able to
com... |
Loads and parses a yaml file for a Train object. Publishes the relevant training environment variables | def load_train_file(config_file_path):
"""Loads and parses a yaml file for a Train object.
Publishes the relevant training environment variables"""
from pylearn2.config import yaml_parse
suffix_to_strip = '.yaml'
# publish environment variables related to file name
if config_file_path.endswith... |
Propagate forward through the layer | def feed_forward(self, input_data, prediction=False):
"""Propagate forward through the layer
**Parameters:**
input_data : ``GPUArray``
Inpute data to perform dropout on.
prediction : bool, optional
Whether to use prediction model. If true, then the data is
... |
Backpropagate through the hidden layer | def backprop(self, input_data, df_output, cache=None):
""" Backpropagate through the hidden layer
**Parameters:**
input_data : ``GPUArray``
Inpute data to perform dropout on.
df_output : ``GPUArray``
Gradients with respect to the output of this layer
... |
Create ctypes pointer to object. | def POINTER(obj):
"""
Create ctypes pointer to object.
Notes
-----
This function converts None to a real NULL pointer because of bug
in how ctypes handles None on 64-bit platforms.
"""
p = ctypes.POINTER(obj)
if not isinstance(p.from_param, classmethod):
def from_param(cls... |
Return ctypes pointer to data in GPUAarray object. | def gpuarray_ptr(g):
"""
Return ctypes pointer to data in GPUAarray object.
"""
addr = int(g.gpudata)
if g.dtype == np.int8:
return ctypes.cast(addr, POINTER(ctypes.c_byte))
if g.dtype == np.uint8:
return ctypes.cast(addr, POINTER(ctypes.c_ubyte))
if g.dtype == np.int16:
... |
Allocate device memory. | def cudaMalloc(count, ctype=None):
"""
Allocate device memory.
Allocate memory on the device associated with the current active
context.
Parameters
----------
count : int
Number of bytes of memory to allocate
ctype : _ctypes.SimpleType, optional
ctypes type to cast retu... |
Allocate pitched device memory. | def cudaMallocPitch(pitch, rows, cols, elesize):
"""
Allocate pitched device memory.
Allocate pitched memory on the device associated with the current active
context.
Parameters
----------
pitch : int
Pitch for allocation.
rows : int
Requested pitched allocation height.... |
Copy memory from host to device. | def cudaMemcpy_htod(dst, src, count):
"""
Copy memory from host to device.
Copy data from host memory to device memory.
Parameters
----------
dst : ctypes pointer
Device memory pointer.
src : ctypes pointer
Host memory pointer.
count : int
Number of bytes to cop... |
Copy memory from device to host. | def cudaMemcpy_dtoh(dst, src, count):
"""
Copy memory from device to host.
Copy data from device memory to host memory.
Parameters
----------
dst : ctypes pointer
Host memory pointer.
src : ctypes pointer
Device memory pointer.
count : int
Number of bytes to cop... |
Return the amount of free and total device memory. | def cudaMemGetInfo():
"""
Return the amount of free and total device memory.
Returns
-------
free : long
Free memory in bytes.
total : long
Total memory in bytes.
"""
free = ctypes.c_size_t()
total = ctypes.c_size_t()
status = _libcudart.cudaMemGetInfo(ctypes.b... |
Get current CUDA device. | def cudaGetDevice():
"""
Get current CUDA device.
Return the identifying number of the device currently used to
process CUDA operations.
Returns
-------
dev : int
Device number.
"""
dev = ctypes.c_int()
status = _libcudart.cudaGetDevice(ctypes.byref(dev))
cudaChec... |
Get installed CUDA driver version. | def cudaDriverGetVersion():
"""
Get installed CUDA driver version.
Return the version of the installed CUDA driver as an integer. If
no driver is detected, 0 is returned.
Returns
-------
version : int
Driver version.
"""
version = ctypes.c_int()
status = _libcudart.cu... |
Get memory pointer attributes. | def cudaPointerGetAttributes(ptr):
"""
Get memory pointer attributes.
Returns attributes of the specified pointer.
Parameters
----------
ptr : ctypes pointer
Memory pointer to examine.
Returns
-------
memory_type : int
Memory type; 1 indicates host memory, 2 indica... |
Evaluate a thunk in an environment. | def eval(thunk, env):
"""Evaluate a thunk in an environment.
Will defer the actual evaluation to the thunk itself, but adds two things:
caching and recursion detection.
Since we have to use a global evaluation stack (because there is a variety of functions that may
be invoked, not just eval() but also __get... |
Delegate to our current value provider for the node belonging to this key. | def get_node(self, key):
"""Delegate to our current "value provider" for the node belonging to this key."""
if key in self.names:
return self.values.get_member_node(key) if hasattr(self.values, 'get_member_node') else None
return self.parent.get_node(key) |
create_table | def create_table(cls):
"""
create_table
Manually create a temporary table for model in test data base.
:return:
"""
schema_editor = getattr(connection, 'schema_editor', None)
if schema_editor:
with schema_editor() as schema_editor:
sch... |
delete_table | def delete_table(cls):
"""
delete_table
Manually delete a temporary table for model in test data base.
:return:
"""
schema_editor = getattr(connection, 'schema_editor', None)
if schema_editor:
with connection.schema_editor() as schema_editor:
... |
fake_me | def fake_me(cls, source):
"""
fake_me
Class or method decorator
Class decorator: create temporary table for all tests in SimpleTestCase.
Method decorator: create temporary model only for given test method.
:param source: SimpleTestCase or test function
:return:
... |
Decorator for capturing and simulating network communication | def vcr(decorated_func=None, debug=False, overwrite=False, disabled=False,
playback_only=False, tape_name=None):
"""
Decorator for capturing and simulating network communication
``debug`` : bool, optional
Enables debug mode.
``overwrite`` : bool, optional
Will run vcr in recordi... |
Reset to default settings | def reset(cls):
"""
Reset to default settings
"""
cls.debug = False
cls.disabled = False
cls.overwrite = False
cls.playback_only = False
cls.recv_timeout = 5
cls.recv_endmarkers = []
cls.recv_size = None |
Reify values to their Python equivalents. | def to_python(value, seen=None):
"""Reify values to their Python equivalents.
Does recursion detection, failing when that happens.
"""
seen = seen or set()
if isinstance(value, framework.TupleLike):
if value.ident in seen:
raise RecursionException('to_python: infinite recursion while evaluating %r'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.