code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def DataProcessorsPost(self, parameters):
if self.__SenseApiCall__('/dataprocessors.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Create a Data processor in CommonSense.
If DataProcessorsPost is successful, the data processor and sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictonary) - Dictionary containing the details... |
def DataProcessorsDelete(self, dataProcessorId):
if self.__SenseApiCall__('/dataprocessors/{id}.json'.format(id = dataProcessorId), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete a data processor in CommonSense.
@param dataProcessorId - The id of the data processor that will be deleted.
@return (bool) - Boolean indicating whether GroupsPost was successful. |
def deriv(self, mu):
from statsmodels.tools.numdiff import approx_fprime_cs, approx_fprime
# return approx_fprime_cs(mu, self) # TODO fix breaks in `fabs
# TODO: diag is workaround problem with numdiff for 1d
return np.diag(approx_fprime(mu, self)) | Derivative of the variance function v'(mu) |
def deriv(self, mu):
p = self._clean(mu)
return 1 + 2 * self.alpha * p | Derivative of the negative binomial variance function. |
def _compute_betas(y, x):
xT = x.T
xtx = spdot(xT, x)
xtx_inv = la.inv(xtx)
xtx_inv = sp.csr_matrix(xtx_inv)
xTy = spdot(xT, y, array_out=False)
betas = spdot(xtx_inv, xTy)
return betas | compute MLE coefficients using iwls routine
Methods: p189, Iteratively (Re)weighted Least Squares (IWLS),
Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).
Geographically weighted regression: the analysis of spatially varying relationships. |
def _compute_betas_gwr(y, x, wi):
xT = (x * wi).T
xtx = np.dot(xT, x)
xtx_inv_xt = linalg.solve(xtx, xT)
betas = np.dot(xtx_inv_xt, y)
return betas, xtx_inv_xt | compute MLE coefficients using iwls routine
Methods: p189, Iteratively (Re)weighted Least Squares (IWLS),
Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).
Geographically weighted regression: the analysis of spatially varying relationships. |
def _next_regular(target):
if target <= 6:
return target
# Quickly check if it's already a power of 2
if not (target & (target - 1)):
return target
match = float('inf') # Anything found will be smaller
p5 = 1
while p5 < target:
p35 = p5
while p35 < target:... | Find the next regular number greater than or equal to target.
Regular numbers are composites of the prime factors 2, 3, and 5.
Also known as 5-smooth numbers or Hamming numbers, these are the optimal
size for inputs to FFTPACK.
Target must be a positive integer. |
def quantile_1D(data, weights, quantile):
# Check the data
if not isinstance(data, np.matrix):
data = np.asarray(data)
if not isinstance(weights, np.matrix):
weights = np.asarray(weights)
nd = data.ndim
if nd != 1:
raise TypeError("data must be a one dimensional array")
... | Compute the weighted quantile of a 1D numpy array.
Parameters
----------
data : ndarray
Input array (one dimension).
weights : ndarray
Array with the weights of the same size of `data`.
quantile : float
Quantile to compute. It must have a value between 0 and 1.
Returns
... |
def quantile(data, weights, quantile):
# TODO: Allow to specify the axis
nd = data.ndim
if nd == 0:
TypeError("data must have at least one dimension")
elif nd == 1:
return quantile_1D(data, weights, quantile)
elif nd > 1:
n = data.shape
imr = data.reshape((np.pro... | Weighted quantile of an array with respect to the last axis.
Parameters
----------
data : ndarray
Input array.
weights : ndarray
Array with the weights. It must have the same size of the last
axis of `data`.
quantile : float
Quantile to compute. It must have a value... |
def __render_config_block(self, config_block):
config_block_str = ''
for line in config_block:
if isinstance(line, config.Option):
line_str = self.__render_option(line)
elif isinstance(line, config.Config):
line_str = self.__render_config(... | Summary
Args:
config_block [config.Item, ...]: config lines
Returns:
str: config block str |
def einfo(self, args=None):
if args is None:
args = {}
return self._query('/einfo.fcgi', args, skip_cache=True) | execute a NON-cached, throttled einfo query
einfo.fcgi?db=<database>
Input: Entrez database (&db) or None (returns info on all Entrez databases)
Output: XML containing database statistics
Example: Find database statistics for Entrez Protein.
QueryService.einfo({'db': 'pr... |
def native_obj(self):
if self.__native is None:
self.__native = self._get_object()
return self.__native | Native storage object. |
def smart_content_type(self):
content_type = self.content_type
if content_type in (None, '', 'application/octet-stream'):
content_type, _ = mimetypes.guess_type(self.name)
return content_type | Smart content type. |
def smart_content_encoding(self):
encoding = self.content_encoding
if not encoding:
base_list = self.basename.split('.')
while (not encoding) and len(base_list) > 1:
_, encoding = mimetypes.guess_type('.'.join(base_list))
base_list.pop()
... | Smart content encoding. |
def native_container(self):
if self.__native is None:
self.__native = self._get_container()
return self.__native | Native container object. |
def native_conn(self):
if self.__native is None:
self.__native = self._get_connection()
return self.__native | Native connection object. |
def get_containers(self):
permitted = lambda c: settings.container_permitted(c.name)
return [c for c in self._get_containers() if permitted(c)] | Return available containers. |
def get_container(self, path):
if not settings.container_permitted(path):
raise errors.NotPermittedException(
"Access to container \"%s\" is not permitted." % path)
return self._get_container(path) | Return single container. |
def is_key(cls, result):
from boto.s3.key import Key
return isinstance(result, Key) | Return ``True`` if result is a key object. |
def validate(self, name, value):
if self.valid_set and value not in self.valid_set:
raise ImproperlyConfigured(
"%s: \"%s\" is not a valid setting (choose between %s)." %
(name, value, ", ".join("\"%s\"" % x for x in self.valid_set)))
return value | Validate and return a value. |
def get(self, name, default=None):
default = default if default is not None else self.default
try:
value = getattr(_settings, name)
except AttributeError:
value = os.environ.get(name, default) if self.from_env else default
# Convert env variable.
... | Get value. |
def parse_bool(cls, value, default=None):
if value is None:
return default
elif isinstance(value, bool):
return value
elif isinstance(value, str):
if value == 'True':
return True
elif value == 'False':
ret... | Convert ``string`` or ``bool`` to ``bool``. |
def _container_whitelist(self):
if self.__container_whitelist is None:
self.__container_whitelist = \
set(self.CLOUD_BROWSER_CONTAINER_WHITELIST or [])
return self.__container_whitelist | Container whitelist. |
def _container_blacklist(self):
if self.__container_blacklist is None:
self.__container_blacklist = \
set(self.CLOUD_BROWSER_CONTAINER_BLACKLIST or [])
return self.__container_blacklist | Container blacklist. |
def container_permitted(self, name):
white = self._container_whitelist
black = self._container_blacklist
return name not in black and (not white or name in white) | Return whether or not a container is permitted.
:param name: Container name.
:return: ``True`` if container is permitted.
:rtype: ``bool`` |
def app_media_url(self):
url = None
media_dir = self.CLOUD_BROWSER_STATIC_MEDIA_DIR
if media_dir:
url = os.path.join(self.MEDIA_URL, media_dir).rstrip('/') + '/'
return url | Get application media root from real media root URL. |
def app_media_doc_root(self): # pylint: disable=R0201
app_dir = os.path.abspath(os.path.dirname(__file__))
media_root = os.path.join(app_dir, 'media')
return media_root | Get application media document (file) root. |
def module_getmtime(filename):
if os.path.splitext(filename)[1].lower() in (".pyc", ".pyo") and os.path.exists(filename[:-1]):
return os.path.getmtime(filename[:-1])
if os.path.exists(filename):
return os.path.getmtime(filename)
return None | Get the mtime associated with a module. If this is a .pyc or .pyo file and
a corresponding .py file exists, the time of the .py file is returned.
:param filename: filename of the module.
:returns: mtime or None if the file doesn"t exist. |
def module_reload_changed(key):
imp.acquire_lock()
try:
modkey = module_sys_modules_key(key)
if not modkey:
return False
found = None
if modkey:
for second in WatchList:
secmodkey = module_sys_modules_key(second)
if sec... | Reload a module if it has changed since we last imported it. This is
necessary if module a imports script b, script b is changed, and then
module c asks to import script b.
:param key: our key used in the WatchList.
:returns: True if reloaded. |
def module_sys_modules_key(key):
moduleparts = key.split(".")
for partnum, part in enumerate(moduleparts):
modkey = ".".join(moduleparts[partnum:])
if modkey in sys.modules:
return modkey
return None | Check if a module is in the sys.modules dictionary in some manner. If so,
return the key used in that dictionary.
:param key: our key to the module.
:returns: the key in sys.modules or None. |
def reload_including_local(module):
try:
reload(module)
except ImportError:
# This can happen if the module was loaded in the immediate script
# directory. Add the service path and try again.
if not hasattr(cherrypy.thread_data, "modulepath"):
raise
path... | Reload a module. If it isn"t found, try to include the local service
directory. This must be called from a thread that has acquired the import
lock.
:param module: the module to reload. |
def reload_recent_submodules(module, mtime=0, processed=[]):
if module.endswith(".py"):
module = module[:-3]
if module in processed:
return False
any_reloaded = False
for key in WatchList:
if WatchList[key]["parent"] == module:
reloaded = reload_recent_submodules... | Recursively reload submodules which are more recent than a specified
timestamp. To be called from a thread that has acquired the import lock to
be thread safe.
:param module: the module name. The WatchList is checked for modules that
list this as a parent.
:param mtime: the latest ... |
def watch_import(name, globals=None, *args, **kwargs):
# Don"t monitor builtin modules. types seem special, so don"t monitor it
# either.
monitor = not imp.is_builtin(name) and name not in ("types", )
# Don"t monitor modules if we don"t know where they came from
monitor = monitor and isinstanc... | When a module is asked to be imported, check if we have previously imported
it. If so, check if the time stamp of it, a companion yaml file, or any
modules it imports have changed. If so, reimport the module.
:params: see __builtin__.__import__ |
def get_int(value, default, test_fn=None):
try:
converted = int(value)
except ValueError:
return default
test_fn = test_fn if test_fn else lambda x: True
return converted if test_fn(converted) else default | Convert value to integer.
:param value: Integer value.
:param default: Default value on failed conversion.
:param test_fn: Constraint function. Use default if returns ``False``.
:return: Integer value.
:rtype: ``int`` |
def check_version(mod, required):
vers = tuple(int(v) for v in mod.__version__.split('.')[:3])
if vers < required:
req = '.'.join(str(v) for v in required)
raise ImproperlyConfigured(
"Module \"%s\" version (%s) must be >= %s." %
(mod.__name__, mod.__version__, req)) | Require minimum version of module using ``__version__`` member. |
def requires(module, name=""):
def wrapped(method):
"""Call and enforce method."""
if module is None:
raise ImproperlyConfigured("Module '%s' is not installed." % name)
return method
return wrapped | Enforces module presence.
The general use here is to allow conditional imports that may fail (e.g., a
required python package is not installed) but still allow the rest of the
python package to compile and run fine. If the wrapped method with this
decorated is invoked, then a runtime error is generated... |
def dt_from_rfc8601(date_str):
# Normalize string and adjust for milliseconds. Note that Python 2.6+ has
# ".%f" format, but we're going for Python 2.5, so truncate the portion.
date_str = date_str.rstrip('Z').split('.')[0]
# Format string. (2010-04-13T14:02:48.000Z)
fmt = "%Y-%m-%dT%H:%M:%S"
... | Convert 8601 (ISO) date string to datetime object.
Handles "Z" and milliseconds transparently.
:param date_str: Date string.
:type date_str: ``string``
:return: Date time.
:rtype: :class:`datetime.datetime` |
def dt_from_header(date_str):
convert_fns = (
dt_from_rfc8601,
dt_from_rfc1123,
)
for convert_fn in convert_fns:
try:
return convert_fn(date_str)
except ValueError:
pass
return None | Try various RFC conversions to ``datetime`` or return ``None``.
:param date_str: Date string.
:type date_str: ``string``
:return: Date time.
:rtype: :class:`datetime.datetime` or ``None`` |
def basename(path):
base_path = path.strip(SEP)
sep_ind = base_path.rfind(SEP)
if sep_ind < 0:
return path
return base_path[sep_ind + 1:] | Rightmost part of path after separator. |
def path_parts(path):
path = path if path is not None else ''
container_path = object_path = ''
parts = path_list(path)
if len(parts) >= 1:
container_path = parts[0]
if len(parts) > 1:
object_path = path_join(*parts[1:])
return container_path, object_path | Split path into container, object.
:param path: Path to resource (including container).
:type path: `string`
:return: Container, storage object tuple.
:rtype: `tuple` of `string`, `string` |
def path_yield(path):
for part in (x for x in path.strip(SEP).split(SEP) if x not in (None, '')):
yield part | Yield on all path parts. |
def path_join(*args):
return SEP.join((x for x in args if x not in (None, ''))).strip(SEP) | Join path parts to single path. |
def relpath(path, start):
path_items = path_list(path)
start_items = path_list(start)
# Find common parts of path.
common = []
for pth, stt in zip(path_items, start_items):
if pth != stt:
break
common.append(pth)
# Shared parts index in both lists.
common_i... | Get relative path to start.
Note: Modeled after python2.6 :meth:`os.path.relpath`. |
def collective_dr_squared( self ):
return sum( np.square( sum( [ atom.dr for atom in self.atoms ] ) ) ) | Squared sum of total displacements for these atoms.
Args:
None
Returns:
(Float): The square of the summed total displacements for these atoms. |
def occupations( self, site_label ):
return sum( atom.site.label == site_label for atom in self.atoms ) | Number of these atoms occupying a specific site type.
Args:
site_label (Str): Label for the site type being considered.
Returns:
(Int): Number of atoms occupying sites of type `site_label`. |
def get_class(class_string):
try:
mod_name, class_name = get_mod_func(class_string)
if class_name != '':
cls = getattr(__import__(mod_name, {}, {}, ['']), class_name)
return cls
except (ImportError, AttributeError):
pass
raise ImportError('Failed to impor... | Convert a string version of a function name to the callable object. |
def get_mod_func(class_string):
try:
dot = class_string.rindex('.')
except ValueError:
return class_string, ''
return class_string[:dot], class_string[dot + 1:] | Converts 'django.views.news.stories.story_detail' to
('django.views.news.stories', 'story_detail')
Taken from django.core.urlresolvers |
def _is_gs_folder(cls, result):
return (cls.is_key(result) and
result.size == 0 and
result.name.endswith(cls._gs_folder_suffix)) | Return ``True`` if GS standalone folder object.
GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a
pseudo-directory place holder if there are no files present. |
def is_key(cls, result):
from boto.gs.key import Key
return isinstance(result, Key) | Return ``True`` if result is a key object. |
def is_prefix(cls, result):
from boto.s3.prefix import Prefix
return isinstance(result, Prefix) or cls._is_gs_folder(result) | Return ``True`` if result is a prefix object.
.. note::
Boto uses the S3 Prefix object for GS prefixes. |
def from_prefix(cls, container, prefix):
if cls._is_gs_folder(prefix):
name, suffix, extra = prefix.name.partition(cls._gs_folder_suffix)
if (suffix, extra) == (cls._gs_folder_suffix, ''):
# Patch GS specific folder to remove suffix.
prefix.name =... | Create from prefix object. |
def get_objects(self, path, marker=None,
limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):
# Get basename of implied folder.
folder = path.split(SEP)[-1]
# Query extra objects, then strip 0-byte dummy object if present.
objs = super(GsContainer, self).get_ob... | Get objects.
Certain upload clients may add a 0-byte object (e.g., ``FOLDER`` object
for path ``path/to/FOLDER`` - ``path/to/FOLDER/FOLDER``). We add an
extra +1 limit query and ignore any such file objects. |
def translate(self, exc):
from boto.exception import StorageResponseError
if isinstance(exc, StorageResponseError):
if exc.status == 404:
return self.error_cls(str(exc))
return None | Return whether or not to do translation. |
def from_result(cls, container, result):
if result is None:
raise errors.NoObjectException
elif cls.is_prefix(result):
return cls.from_prefix(container, result)
elif cls.is_key(result):
return cls.from_key(container, result)
raise errors.Cl... | Create from ambiguous result. |
def from_prefix(cls, container, prefix):
if prefix is None:
raise errors.NoObjectException
return cls(container,
name=prefix.name,
obj_type=cls.type_cls.SUBDIR) | Create from prefix object. |
def from_key(cls, container, key):
if key is None:
raise errors.NoObjectException
# Get Key (1123): Tue, 13 Apr 2010 14:02:48 GMT
# List Keys (8601): 2010-04-13T14:02:48.000Z
return cls(container,
name=key.name,
size=key.size,... | Create from key object. |
def get_objects(self, path, marker=None,
limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):
from itertools import islice
path = path.rstrip(SEP) + SEP if path else path
result_set = self.native_container.list(path, SEP, marker)
# Get +1 results because marke... | Get objects. |
def get_object(self, path):
key = self.native_container.get_key(path)
return self.obj_cls.from_key(self, key) | Get single object. |
def from_bucket(cls, connection, bucket):
if bucket is None:
raise errors.NoContainerException
# It appears that Amazon does not have a single-shot REST query to
# determine the number of keys / overall byte size of a bucket.
return cls(connection, bucket.name) | Create from bucket object. |
def _get_containers(self):
buckets = self.native_conn.get_all_buckets()
return [self.cont_cls.from_bucket(self, b) for b in buckets] | Return available containers. |
def _get_container(self, path):
bucket = self.native_conn.get_bucket(path)
return self.cont_cls.from_bucket(self, bucket) | Return single container. |
def get_connection_cls(cls):
if cls.__connection_cls is None:
cls.__connection_cls, _ = cls.from_settings()
return cls.__connection_cls | Return connection class.
:rtype: :class:`type` |
def get_connection(cls):
if cls.__connection_obj is None:
if cls.__connection_fn is None:
_, cls.__connection_fn = cls.from_settings()
cls.__connection_obj = cls.__connection_fn()
return cls.__connection_obj | Return connection object.
:rtype: :class:`cloud_browser.cloud.base.CloudConnection` |
def base_path(self):
return os.path.join(self.container.base_path, self.name) | Base absolute path of container. |
def from_path(cls, container, path):
from datetime import datetime
path = path.strip(SEP)
full_path = os.path.join(container.base_path, path)
last_modified = datetime.fromtimestamp(os.path.getmtime(full_path))
obj_type = cls.type_cls.SUBDIR if is_dir(full_path)\
... | Create object from path. |
def get_objects(self, path, marker=None,
limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):
def _filter(name):
"""Filter."""
return (not_dot(name) and
(marker is None or
os.path.join(path, name).strip(SEP) > marker.stri... | Get objects. |
def base_path(self):
return os.path.join(self.conn.abs_root, self.name) | Base absolute path of container. |
def from_path(cls, conn, path):
path = path.strip(SEP)
full_path = os.path.join(conn.abs_root, path)
return cls(conn, path, 0, os.path.getsize(full_path)) | Create container from path. |
def _get_containers(self):
def full_fn(path):
return os.path.join(self.abs_root, path)
return [self.cont_cls.from_path(self, d)
for d in os.listdir(self.abs_root) if is_dir(full_fn(d))] | Return available containers. |
def _get_container(self, path):
path = path.strip(SEP)
if SEP in path:
raise errors.InvalidNameException(
"Path contains %s - %s" % (SEP, path))
return self.cont_cls.from_path(self, path) | Return single container. |
def cubic_lattice( a, b, c, spacing ):
grid = np.array( list( range( 1, a * b * c + 1 ) ) ).reshape( a, b, c, order='F' )
it = np.nditer( grid, flags=[ 'multi_index' ] )
sites = []
while not it.finished:
x, y, z = it.multi_index
r = np.array( [ x, y, z ] ) * spacing
neighbou... | Generate a cubic lattice.
Args:
a (Int): Number of lattice repeat units along x.
b (Int): Number of lattice repeat units along y.
c (Int): Number of lattice repeat units along z.
spacing (Float): Distance between lattice sites.
Returns:
(Lattice)... |
def set_location(request):
next = request.GET.get('next', None) or request.POST.get('next', None)
if not next:
next = request.META.get('HTTP_REFERER', None)
if not next:
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
location_id = requ... | Redirect to a given url while setting the chosen location in the
cookie. The url and the location_id need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
re... |
def site_specific_nn_occupation( self ):
to_return = { l : 0 for l in set( ( site.label for site in self.p_neighbours ) ) }
for site in self.p_neighbours:
if site.is_occupied:
to_return[ site.label ] += 1
return to_return | Returns the number of occupied nearest neighbour sites, classified by site type.
Args:
None
Returns:
(Dict(Str:Int)): Dictionary of nearest-neighbour occupied site numbers, classified by site label, e.g. { 'A' : 2, 'B' : 1 }. |
def cn_occupation_energy( self, delta_occupation=None ):
nn_occupations = self.site_specific_nn_occupation()
if delta_occupation:
for site in delta_occupation:
assert( site in nn_occupations )
nn_occupations[ site ] += delta_occupation[ site ]
... | The coordination-number dependent energy for this site.
Args:
delta_occupation (:obj:Dict(Str:Int), optional): A dictionary of a change in (site-type specific) coordination number, e.g. { 'A' : 1, 'B' : -1 }.
If this is not None, the coordination-number dependent energy is calculate... |
def clear_database(self):
self.logger.info('Removing obsolete geoip from database...')
IpRange.objects.all().delete()
City.objects.all().delete()
Region.objects.all().delete()
Country.objects.all().delete() | Removes all geodata stored in database.
Useful for development, never use on production. |
def _download_extract_archive(self, url):
self.logger.info('Downloading zipfile from ipgeobase.ru...')
temp_dir = tempfile.mkdtemp()
archive = zipfile.ZipFile(self._download_url_to_string(url))
self.logger.info('Extracting files...')
file_cities = archive.extract(setting... | Returns dict with 2 extracted filenames |
def _line_to_dict(self, file, field_names):
for line in file:
delimiter = settings.IPGEOBASE_FILE_FIELDS_DELIMITER
yield self._extract_data_from_line(line, field_names, delimiter) | Converts file line into dictonary |
def _process_cidr_file(self, file):
data = {'cidr': list(), 'countries': set(), 'city_country_mapping': dict()}
allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES
for cidr_info in self._line_to_dict(file, field_names=settings.IPGEOBASE_CIDR_FIELDS):
city_id = cidr_info... | Iterate over ip info and extract useful data |
def _process_cities_file(self, file, city_country_mapping):
data = {'all_regions': list(), 'regions': list(), 'cities': list(), 'city_region_mapping': dict()}
allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES
for geo_info in self._line_to_dict(file, field_names=settings.IPGEOBASE... | Iterate over cities info and extract useful data |
def _update_geography(self, countries, regions, cities, city_country_mapping):
existing = {
'cities': list(City.objects.values_list('id', flat=True)),
'regions': list(Region.objects.values('name', 'country__code')),
'countries': Country.objects.values_list('code', fl... | Update database with new countries, regions and cities |
def _update_cidr(self, cidr):
new_ip_ranges = []
is_bulk_create_supported = hasattr(IpRange.objects, 'bulk_create')
IpRange.objects.all().delete()
city_region_mapping = self._build_city_region_mapping()
if self.logger.getEffectiveLevel() in [logging.INFO, logging.DEBUG]... | Rebuild IPRegion table with fresh data (old ip ranges are removed for simplicity) |
def relative_probability( self, l1, l2, c1, c2 ):
if self.site_energies:
site_delta_E = self.site_energies[ l2 ] - self.site_energies[ l1 ]
else:
site_delta_E = 0.0
if self.nn_energy:
delta_nn = c2 - c1 - 1 # -1 because the hopping ion is not counted ... | The relative probability for a jump between two sites with specific site types and coordination numbers.
Args:
l1 (Str): Site label for the initial site.
l2 (Str): Site label for the final site.
c1 (Int): Coordination number for the initial site.
c2 (Int): Coordi... |
def generate_nearest_neighbour_lookup_table( self ):
self.jump_probability = {}
for site_label_1 in self.connected_site_pairs:
self.jump_probability[ site_label_1 ] = {}
for site_label_2 in self.connected_site_pairs[ site_label_1 ]:
self.jump_probability[... | Construct a look-up table of relative jump probabilities for a nearest-neighbour interaction Hamiltonian.
Args:
None.
Returns:
None. |
def reset( self ):
self.number_of_hops = 0
self.dr = np.array( [ 0.0, 0.0, 0.0 ] )
self.summed_dr2 = 0.0
self.sites_visited = [ self._site.number ] | Reinitialise the stored displacements, number of hops, and list of sites visited for this `Atom`.
Args:
None
Returns:
None |
def by_ip(self, ip):
try:
number = inet_aton(ip)
except Exception:
raise IpRange.DoesNotExist
try:
return self.filter(start_ip__lte=number, end_ip__gte=number)\
.order_by('end_ip', '-start_ip')[0]
except IndexError:
... | Find the smallest range containing the given IP. |
def _parse_bool(value):
if isinstance(value, bool):
return value
elif isinstance(value, str):
if value == 'True':
return True
elif value == 'False':
return False
raise Exception("Value %s is not boolean." % value) | Convert ``string`` or ``bool`` to ``bool``. |
def docs(output=DOC_OUTPUT, proj_settings=PROJ_SETTINGS, github=False):
local("export PYTHONPATH='' && "
"export DJANGO_SETTINGS_MODULE=%s && "
"sphinx-build -b html %s %s" % (proj_settings, DOC_INPUT, output),
capture=False)
if _parse_bool(github):
local("touch %s/.... | Generate API documentation (using Sphinx).
:param output: Output directory.
:param proj_settings: Django project settings to use.
:param github: Convert to GitHub-friendly format? |
def _manage(target, extra='', proj_settings=PROJ_SETTINGS):
local("export PYTHONPATH='' && "
"export DJANGO_SETTINGS_MODULE='%s' && "
"django-admin.py %s %s" %
(proj_settings, target, extra),
capture=False) | Generic wrapper for ``django-admin.py``. |
def process_response(self, request, response):
if not hasattr(request, 'location'):
return response
storage = storage_class(request=request, response=response)
try:
storage.set(location=request.location)
except ValueError:
# bad location_id
... | Do nothing, if process_request never completed (redirect) |
def return_type(rettype):
def wrap(f):
@functools.wraps(f)
def converter(*pargs, **kwargs):
# Run the function to capture the output.
result = f(*pargs, **kwargs)
# Convert the result using the return type function.
try:
result = ... | Decorate a function to automatically convert its return type to a string
using a custom function.
Web-based service functions must return text to the client. Tangelo
contains default logic to convert many kinds of values into string, but this
decorator allows the service writer to specify custom behav... |
def tangelo_import(*args, **kwargs):
try:
return builtin_import(*args, **kwargs)
except ImportError:
if not hasattr(cherrypy.thread_data, "modulepath"):
raise
path = os.path.abspath(cherrypy.thread_data.modulepath)
root = os.path.abspath(cherrypy.config.get("webr... | When we are asked to import a module, if we get an import error and the
calling script is one we are serving (not one in the python libraries), try
again in the same directory as the script that is calling import.
It seems like we should use sys.meta_path and combine our path with the
path sent to i... |
def excepts(cls):
if cls._excepts is None:
cls._excepts = tuple(cls.translations.keys())
return cls._excepts | Return tuple of underlying exception classes to trap and wrap.
:rtype: ``tuple`` of ``type`` |
def translate(self, exc):
# Find actual class.
for key in self.translations.keys():
if isinstance(exc, key):
# pylint: disable=unsubscriptable-object
return self.translations[key](str(exc))
return None | Return translation of exception to new class.
Calling code should only raise exception if exception class is passed
in, else ``None`` (which signifies no wrapping should be done). |
def settings_view_decorator(function):
dec = settings.CLOUD_BROWSER_VIEW_DECORATOR
# Trade-up string to real decorator.
if isinstance(dec, str):
# Split into module and decorator strings.
mod_str, _, dec_str = dec.rpartition('.')
if not (mod_str and dec_str):
raise... | Insert decorator from settings, if any.
.. note:: Decorator in ``CLOUD_BROWSER_VIEW_DECORATOR`` can be either a
callable or a fully-qualified string path (the latter, which we'll
lazy import). |
def _breadcrumbs(path):
full = None
crumbs = []
for part in path_yield(path):
full = path_join(full, part) if full else part
crumbs.append((full, part))
return crumbs | Return breadcrumb dict from path. |
def document(_, path=''):
container_path, object_path = path_parts(path)
conn = get_connection()
try:
container = conn.get_container(container_path)
except errors.NoContainerException:
raise Http404("No container at: %s" % container_path)
except errors.NotPermittedException:
... | View single document from path.
:param path: Path to resource, including container as first part of path. |
def truncatechars(value, num, end_text="..."):
length = None
try:
length = int(num)
except ValueError:
pass
if length is not None and len(value) > length:
return value[:length - len(end_text)] + end_text
return value | Truncate string on character boundary.
.. note::
Django ticket `5025 <http://code.djangoproject.com/ticket/5025>`_ has a
patch for a more extensible and robust truncate characters tag filter.
Example::
{{ my_variable|truncatechars:22 }}
:param value: Value to truncate.
:type ... |
def cloud_browser_media_url(_, token):
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument" % bits[0])
rel_path = bits[1]
return MediaUrlNode(rel_path) | Get base media URL for application static media.
Correctly handles whether or not the settings variable
``CLOUD_BROWSER_STATIC_MEDIA_DIR`` is set and served.
For example::
<link rel="stylesheet" type="text/css"
href="{% cloud_browser_media_url "css/cloud-browser.css" %}" /> |
def render(self, context):
try:
from django.core.urlresolvers import reverse
except ImportError:
# pylint: disable=no-name-in-module, import-error
from django.urls import reverse
# Check if we have real or Django static-served media
if self.... | Render. |
def reset( self ):
self.lattice.reset()
for atom in self.atoms.atoms:
atom.reset() | Reset all counters for this simulation.
Args:
None
Returns:
None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.