code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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: raise IpRang...
def by_ip(self, ip)
Find the smallest range containing the given IP.
3.653873
3.427188
1.066143
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)
def _parse_bool(value)
Convert ``string`` or ``bool`` to ``bool``.
2.657021
2.574941
1.031876
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/.nojekyll" % output, capture=False)
def docs(output=DOC_OUTPUT, proj_settings=PROJ_SETTINGS, github=False)
Generate API documentation (using Sphinx). :param output: Output directory. :param proj_settings: Django project settings to use. :param github: Convert to GitHub-friendly format?
4.537397
4.670235
0.971557
local("export PYTHONPATH='' && " "export DJANGO_SETTINGS_MODULE='%s' && " "django-admin.py %s %s" % (proj_settings, target, extra), capture=False)
def _manage(target, extra='', proj_settings=PROJ_SETTINGS)
Generic wrapper for ``django-admin.py``.
4.184281
3.679644
1.137143
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 pass return response
def process_response(self, request, response)
Do nothing, if process_request never completed (redirect)
5.903991
5.696436
1.036436
def wrap(f): @functools.wraps(f) def typed_func(*pargs, **kwargs): # Analyze the incoming arguments so we know how to apply the # type-conversion functions in `typefuncs`. argspec = inspect.getargspec(f) # The `args` property contains the list of...
def types(**typefuncs)
Decorate a function that takes strings to one that takes typed values. The decorator's arguments are functions to perform type conversion. The positional and keyword arguments will be mapped to the positional and keyword arguments of the decoratored function. This allows web-based service functions, w...
3.675247
3.674305
1.000256
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 = rettype(result) ...
def return_type(rettype)
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...
4.073076
3.642138
1.11832
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("webroot")) result = None ...
def tangelo_import(*args, **kwargs)
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...
3.085639
3.021899
1.021092
if cls._excepts is None: cls._excepts = tuple(cls.translations.keys()) return cls._excepts
def excepts(cls)
Return tuple of underlying exception classes to trap and wrap. :rtype: ``tuple`` of ``type``
4.64701
5.746926
0.808608
# 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
def translate(self, exc)
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).
5.345827
4.93344
1.08359
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 ImportError("Unable to import module: ...
def settings_view_decorator(function)
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).
4.048841
3.29126
1.230179
full = None crumbs = [] for part in path_yield(path): full = path_join(full, part) if full else part crumbs.append((full, part)) return crumbs
def _breadcrumbs(path)
Return breadcrumb dict from path.
4.634587
4.290253
1.08026
from itertools import islice try: # pylint: disable=redefined-builtin from future_builtins import filter except ImportError: # pylint: disable=import-error from builtins import filter # Inputs. container_path, object_path = path_parts(path) incoming = requ...
def browser(request, path='', template="cloud_browser/browser.html")
View files in a file path. :param request: The request. :param path: Path to resource, including container as first part of path. :param template: Template to render.
3.933386
3.882372
1.01314
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: raise Http404("Access...
def document(_, path='')
View single document from path. :param path: Path to resource, including container as first part of path.
2.525575
2.58665
0.976388
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
def truncatechars(value, num, end_text="...")
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 ...
2.578942
3.982828
0.647515
bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument" % bits[0]) rel_path = bits[1] return MediaUrlNode(rel_path)
def cloud_browser_media_url(_, token)
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" %}" />
3.300327
4.319997
0.763965
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.static_media_url is not Non...
def render(self, context)
Render.
4.547297
4.361115
1.042691
self.lattice.reset() for atom in self.atoms.atoms: atom.reset()
def reset( self )
Reset all counters for this simulation. Args: None Returns: None
7.422263
8.53257
0.869874
self.number_of_atoms = n self.atoms = species.Species( self.lattice.populate_sites( self.number_of_atoms, selected_sites=selected_sites ) )
def set_number_of_atoms( self, n, selected_sites=None )
Set the number of atoms for the simulation, and populate the simulation lattice. Args: n (Int): Number of atoms for this simulation. selected_sites (:obj:(List|Set|String), optional): Selects a subset of site types to be populated with atoms. Defaults to None. Returns: ...
5.275517
4.033897
1.307797
self.lattice = init_lattice.lattice_from_sites_file( filename, cell_lengths = cell_lengths )
def define_lattice_from_file( self, filename, cell_lengths )
Set up the simulation lattice from a file containing site data. Uses `init_lattice.lattice_from_sites_file`, which defines the site file spec. Args: filename (Str): sites file filename. cell_lengths (List(x,y,z)): cell lengths for the simulation cell. Returns: ...
6.506006
2.637132
2.467076
if not self.lattice: raise AttributeError('Running a simulation needs the lattice to be initialised') if not self.atoms: raise AttributeError('Running a simulation needs the atoms to be initialised') if not self.number_of_jumps and not self.for_time: ...
def is_initialised( self )
Check whether the simulation has been initialised. Args: None Returns: None
4.181746
3.902854
1.071458
self.for_time = for_time try: self.is_initialised() except AttributeError: raise if self.number_of_equilibration_jumps > 0: for step in range( self.number_of_equilibration_jumps ): self.lattice.jump() self.reset() ...
def run( self, for_time=None )
Run the simulation. Args: for_time (:obj:Float, optional): If `for_time` is set, then run the simulation until a set amount of time has passed. Otherwise, run the simulation for a set number of jumps. Defaults to None. Returns: None
2.91178
2.677452
1.087519
if self.has_run: return self.atoms.sum_dr_squared() / float( self.number_of_jumps ) else: return None
def old_tracer_correlation( self )
Deprecated tracer correlation factor for this simulation. Args: None Returns: (Float): The tracer correlation factor, f. Notes: This function assumes that the jump distance between sites has been normalised to a=1. If the jump distance is...
9.727695
8.735021
1.113643
if self.has_run: return self.atoms.sum_dr_squared() / ( 6.0 * float( self.number_of_atoms ) * self.lattice.time ) else: return None
def tracer_diffusion_coefficient( self )
Tracer diffusion coefficient, D*. Args: None Returns: (Float): The tracer diffusion coefficient, D*.
8.358844
9.582433
0.872309
if self.has_run: return self.atoms.collective_dr_squared() / float( self.number_of_jumps ) else: return None
def old_collective_correlation( self )
Returns the collective correlation factor, f_I Args: None Returns: (Float): The collective correlation factor, f_I. Notes: This function assumes that the jump distance between sites has been normalised to a=1. If the jumps distance is not equal ...
10.026809
10.329449
0.970701
if self.has_run: return self.atoms.collective_dr_squared() / ( 6.0 * self.lattice.time ) else: return None
def collective_diffusion_coefficient( self )
Returns the collective or "jump" diffusion coefficient, D_J. Args: None Returns: (Float): The collective diffusion coefficient, D_J.
9.664395
12.083048
0.799831
expected_hamiltonian_values = [ 'nearest-neighbour', 'coordination_number' ] if hamiltonian not in expected_hamiltonian_values: raise ValueError self.lattice.jump_lookup_table = lookup_table.LookupTable( self.lattice, hamiltonian )
def setup_lookup_table( self, hamiltonian='nearest-neighbour' )
Create a jump-probability look-up table corresponding to the appropriate Hamiltonian. Args: hamiltonian (Str, optional): String specifying the simulation Hamiltonian. valid values are 'nearest-neighbour' (default) and 'coordination_number'. Returns: None
4.202985
3.653196
1.150495
for s in self.sites: for i in range(3): if s.r[i] < 0.0: s.r[i] += self.cell_lengths[i] if s.r[i] > self.cell_lengths[i]: s.r[i] -= self.cell_lengths[i]
def enforce_periodic_boundary_conditions( self )
Ensure that all lattice sites are within the central periodic image of the simulation cell. Sites that are outside the central simulation cell are mapped back into this cell. Args: None Returns: None
2.175477
1.987696
1.094472
self.site_lookup = {} for site in self.sites: self.site_lookup[ site.number ] = site
def initialise_site_lookup_table( self )
Create a lookup table allowing sites in this lattice to be queried using `self.site_lookup[n]` where `n` is the identifying site numbe. Args: None Returns: None
3.169121
3.015887
1.050809
jumps = [] if self.number_of_occupied_sites <= self.number_of_sites / 2: for occupied_site in self.occupied_sites(): unoccupied_neighbours = [ site for site in [ self.site_with_id( n ) for n in occupied_site.neighbours ] if not site.is_occupied ] for ...
def potential_jumps( self )
All nearest-neighbour jumps not blocked by volume exclusion (i.e. from occupied to neighbouring unoccupied sites). Args: None Returns: (List(Jump)): List of possible jumps.
2.220296
2.165494
1.025307
atom = jump.initial_site.atom dr = jump.dr( self.cell_lengths ) #print( "atom {} jumped from site {} to site {}".format( atom.number, jump.initial_site.number, jump.final_site.number ) ) jump.final_site.occupation = atom.number jump.final_site.atom = atom jump.fi...
def update( self, jump )
Update the lattice state by accepting a specific jump Args: jump (Jump): The jump that has been accepted. Returns: None.
4.402537
4.529422
0.971987
if number_of_atoms > self.number_of_sites: raise ValueError if selected_sites: atoms = [ atom.Atom( initial_site = site ) for site in random.sample( [ s for s in self.sites if s.label in selected_sites ], number_of_atoms ) ] else: atoms = [ atom.Atom(...
def populate_sites( self, number_of_atoms, selected_sites=None )
Populate the lattice sites with a specific number of atoms. Args: number_of_atoms (Int): The number of atoms to populate the lattice sites with. selected_sites (:obj:List, optional): List of site labels if only some sites are to be occupied. Defaults to None. Returns: ...
2.696212
2.637653
1.022201
potential_jumps = self.potential_jumps() if not potential_jumps: raise BlockedLatticeError('No moves are possible in this lattice') all_transitions = transitions.Transitions( self.potential_jumps() ) random_jump = all_transitions.random() delta_t = all_transi...
def jump( self )
Select a jump at random from all potential jumps, then update the lattice state. Args: None Returns: None
5.37376
4.701492
1.14299
if self.time == 0.0: return None occupation_stats = { label : 0.0 for label in self.site_labels } for site in self.sites: occupation_stats[ site.label ] += site.time_occupied for label in self.site_labels: occupation_stats[ label ] /= self.tim...
def site_occupation_statistics( self )
Average site occupation for each site type Args: None Returns: (Dict(Str:Float)): Dictionary of occupation statistics, e.g.:: { 'A' : 2.5, 'B' : 25.3 }
2.675851
2.810647
0.952041
self.site_energies = energies for site_label in energies: for site in self.sites: if site.label == site_label: site.energy = energies[ site_label ]
def set_site_energies( self, energies )
Set the energies for every site in the lattice according to the site labels. Args: energies (Dict(Str:Float): Dictionary of energies for each site label, e.g.:: { 'A' : 1.0, 'B', 0.0 } Returns: None
2.690569
2.661479
1.01093
for site in self.sites: site.set_cn_occupation_energies( cn_energies[ site.label ] ) self.cn_energies = cn_energies
def set_cn_energies( self, cn_energies )
Set the coordination number dependent energies for this lattice. Args: cn_energies (Dict(Str:Dict(Int:Float))): Dictionary of dictionaries specifying the coordination number dependent energies for each site type. e.g.:: { 'A' : { 0 : 0.0, 1 : 1.0, 2 : 2.0 }, 'B' : { 0 : 0.0, 1 : 2....
3.940279
4.70825
0.836888
coordination_numbers = {} for l in self.site_labels: coordination_numbers[ l ] = set( [ len( site.neighbours ) for site in self.sites if site.label is l ] ) return coordination_numbers
def site_coordination_numbers( self )
Returns a dictionary of the coordination numbers for each site label. e.g.:: { 'A' : { 4 }, 'B' : { 2, 4 } } Args: none Returns: coordination_numbers (Dict(Str:Set(Int))): dictionary of coordination nu...
3.932333
4.175172
0.941837
return { l : max( c ) for l, c in self.site_coordination_numbers().items() }
def max_site_coordination_numbers( self )
Returns a dictionary of the maximum coordination number for each site label. e.g.:: { 'A' : 4, 'B' : 4 } Args: none Returns: max_coordination_numbers (Dict(Str:Int)): dictionary of maxmimum coordination ...
5.331474
6.785209
0.785749
specific_coordination_numbers = {} for site in self.sites: specific_coordination_numbers[ site.label ] = site.site_specific_neighbours() return specific_coordination_numbers
def site_specific_coordination_numbers( self )
Returns a dictionary of coordination numbers for each site type. Args: None Returns: (Dict(Str:List(Int))) : Dictionary of coordination numbers for each site type, e.g.:: { 'A' : [ 2, 4 ], 'B' : [ 2 ] }
3.368695
3.564728
0.945008
site_connections = {} for initial_site in self.sites: if not initial_site.label in site_connections: site_connections[ initial_site.label ] = [] for final_site in initial_site.p_neighbours: if final_site.label not in site_connections[ init...
def connected_site_pairs( self )
Returns a dictionary of all connections between pair of sites (by site label). e.g. for a linear lattice A-B-C will return:: { 'A' : [ 'B' ], 'B' : [ 'A', 'C' ], 'C' : [ 'B' ] } Args: None Returns: site_connections (Dict{Str List[Str]}): A dictionar...
2.234812
2.227439
1.00331
selected_sites = self.select_sites( old_site_label ) for site in random.sample( selected_sites, n_sites_to_change ): site.label = new_site_label self.site_labels = set( [ site.label for site in self.sites ] )
def transmute_sites( self, old_site_label, new_site_label, n_sites_to_change )
Selects a random subset of sites with a specific label and gives them a different label. Args: old_site_label (String or List(String)): Site label(s) of the sites to be modified.. new_site_label (String): Site label to be applied to the modified sites. n_site...
2.606282
2.618536
0.99532
if site_labels: selected_sites = self.select_sites( site_labels ) else: selected_sites = self.sites initial_clusters = [ cluster.Cluster( [ site ] ) for site in selected_sites ] if site_labels: blocking_sites = self.site_labels - set( site_label...
def connected_sites( self, site_labels=None )
Searches the lattice to find sets of sites that are contiguously neighbouring. Mutually exclusive sets of contiguous sites are returned as Cluster objects. Args: site_labels (:obj:(List(Str)|Set(Str)|Str), optional): Labels for sites to be considered in the search. This can ...
2.925675
2.694747
1.085696
if type( site_labels ) in ( list, set ): selected_sites = [ s for s in self.sites if s.label in site_labels ] elif type( site_labels ) is str: selected_sites = [ s for s in self.sites if s.label is site_labels ] else: raise ValueError( str( site_label...
def select_sites( self, site_labels )
Selects sites in the lattice with specified labels. Args: site_labels (List(Str)|Set(Str)|Str): Labels of sites to select. This can be a List [ 'A', 'B' ], a Set ( 'A', 'B' ), or a String 'A'. Returns: (List(Site)): List of sites with labels given by `site_label...
2.164001
2.238042
0.966917
clusters = self.connected_sites( site_labels=site_labels ) island_clusters = [ c for c in clusters if not any( c.is_periodically_contiguous() ) ] return list( itertools.chain.from_iterable( ( c.sites for c in island_clusters ) ) )
def detached_sites( self, site_labels=None )
Returns all sites in the lattice (optionally from the set of sites with specific labels) that are not part of a percolating network. This is determined from clusters of connected sites that do not wrap round to themselves through a periodic boundary. Args: site_labels (Strin...
4.100444
4.184092
0.980008
new_cluster = Cluster( self.sites | other_cluster.sites ) new_cluster.neighbours = ( self.neighbours | other_cluster.neighbours ).difference( new_cluster.sites ) return new_cluster
def merge( self, other_cluster )
Combine two clusters into a single cluster. Args: other_cluster (Cluster): The second cluster to combine. Returns: (Cluster): The combination of both clusters.
3.466111
3.810292
0.909671
min_x = min( [ s.r[0] for s in self.sites ] ) max_x = max( [ s.r[0] for s in self.sites ] ) min_y = min( [ s.r[1] for s in self.sites ] ) max_y = max( [ s.r[1] for s in self.sites ] ) min_z = min( [ s.r[2] for s in self.sites ] ) max_z = max( [ s.r[2] for s in se...
def sites_at_edges( self )
Finds the six sites with the maximum and minimum coordinates along x, y, and z. Args: None Returns: (List(List)): In the order [ +x, -x, +y, -y, +z, -z ]
1.305077
1.272001
1.026003
edges = self.sites_at_edges() is_contiguous = [ False, False, False ] along_x = any( [ s2 in s1.p_neighbours for s1 in edges[0] for s2 in edges[1] ] ) along_y = any( [ s2 in s1.p_neighbours for s1 in edges[2] for s2 in edges[3] ] ) along_z = any( [ s2 in s1.p_neighbours ...
def is_periodically_contiguous( self )
logical check whether a cluster connects with itself across the simulation periodic boundary conditions. Args: none Returns ( Bool, Bool, Bool ): Contiguity along the x, y, and z coordinate axes
2.563625
2.416003
1.061102
if type( remove_labels ) is str: remove_labels = [ remove_labels ] self.neighbours = set( n for n in self.neighbours if n.label not in remove_labels )
def remove_sites_from_neighbours( self, remove_labels )
Removes sites from the set of neighbouring sites if these have labels in remove_labels. Args: Remove_labels (List) or (Str): List of Site labels to be removed from the cluster neighbour set. Returns: None
2.775078
2.949863
0.940748
partition_function = np.sum( self.p ) return np.cumsum( self.p ) / partition_function
def cumulative_probabilities( self )
Cumulative sum of the relative probabilities for all possible jumps. Args: None Returns: (np.array): Cumulative sum of relative jump probabilities.
6.019536
8.166388
0.737111
j = np.searchsorted( self.cumulative_probabilities(), random.random() ) return self.jumps[ j ]
def random( self )
Select a jump at random with appropriate relative probabilities. Args: None Returns: (Jump): The randomly selected Jump.
10.016768
7.844529
1.276911
k_tot = rate_prefactor * np.sum( self.p ) return -( 1.0 / k_tot ) * math.log( random.random() )
def time_to_jump( self )
The timestep until the next jump. Args: None Returns: (Float): The timestep until the next jump.
13.212533
15.791072
0.836709
stored_location = self._get_stored_location() if not stored_location: ip_range = self._get_ip_range() stored_location = self._get_corresponding_location(ip_range) return stored_location
def locate(self)
Find out what is user location (either from his IP or cookie). :return: :ref:`Custom location model <location_model>`
3.869107
4.11152
0.94104
try: # Trying to work with most common proxy headers real_ip = self.request.META['HTTP_X_FORWARDED_FOR'] return real_ip.split(',')[0] except KeyError: return self.request.META['REMOTE_ADDR'] except Exception: # Unknown IP ...
def _get_real_ip(self)
Get IP from request. :param request: A usual request object :type request: HttpRequest :return: ipv4 string or None
3.646059
3.799671
0.959572
ip = self._get_real_ip() try: geobase_entry = IpRange.objects.by_ip(ip) except IpRange.DoesNotExist: geobase_entry = None return geobase_entry
def _get_ip_range(self)
Fetches IpRange instance if request IP is found in database. :param request: A ususal request object :type request: HttpRequest :return: IpRange object or None
4.810729
4.608263
1.043935
location_storage = storage_class(request=self.request, response=None) return location_storage.get()
def _get_stored_location(self)
Get location from cookie. :param request: A ususal request object :type request: HttpRequest :return: Custom location model
11.121256
12.467119
0.892047
return { cloudfiles.errors.NoSuchContainer: errors.NoContainerException, cloudfiles.errors.NoSuchObject: errors.NoObjectException, }
def lazy_translations(cls)
Lazy translations.
8.58837
7.618381
1.127322
create_fn = cls.from_subdir if 'subdir' in info_obj \ else cls.from_file_info return create_fn(container, info_obj)
def from_info(cls, container, info_obj)
Create from subdirectory or file info object.
5.265296
3.353917
1.569895
return cls(container, info_obj['subdir'], obj_type=cls.type_cls.SUBDIR)
def from_subdir(cls, container, info_obj)
Create from subdirectory info object.
13.750715
9.284678
1.481012
return cls.type_cls.SUBDIR if content_type in cls.subdir_types \ else cls.type_cls.FILE
def choose_type(cls, content_type)
Choose object type from content type.
7.790079
6.547498
1.18978
# RFC 8601: 2010-04-15T01:52:13.919070 return cls(container, name=info_obj['name'], size=info_obj['bytes'], content_type=info_obj['content_type'], last_modified=dt_from_header(info_obj['last_modified']), ...
def from_file_info(cls, container, info_obj)
Create from regular info object.
3.870018
3.692003
1.048216
# RFC 1123: Thu, 07 Jun 2007 18:57:07 GMT return cls(container, name=file_obj.name, size=file_obj.size, content_type=file_obj.content_type, last_modified=dt_from_header(file_obj.last_modified), obj_ty...
def from_obj(cls, container, file_obj)
Create from regular info object.
3.586564
3.441574
1.042129
object_infos, full_query = self._get_object_infos(path, marker, limit) if full_query and len(object_infos) < limit: # The underlying query returned a full result set, but we # truncated it to under limit. Re-run at twice the limit and then # slice back. ...
def get_objects(self, path, marker=None, limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT)
Get objects. **Pseudo-directory Notes**: Rackspace has two approaches to pseudo- directories within the (really) flat storage object namespace: 1. Dummy directory storage objects. These are real storage objects of type "application/directory" and must be manually uploaded ...
4.273929
4.66426
0.916315
# Adjust limit to +1 to handle marker object as first result. # We can get in to this situation for a marker of "foo", that will # still return a 'subdir' object of "foo/" because of the extra # slash. orig_limit = limit limit += 1 # Enforce maximum obje...
def _get_object_infos(self, path, marker=None, limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT)
Get raw object infos (single-shot).
4.982708
5.000368
0.996468
obj = self.native_container.get_object(path) return self.obj_cls.from_obj(self, obj)
def get_object(self, path)
Get single object.
6.533926
5.839201
1.118976
kwargs = { 'username': self.account, 'api_key': self.secret_key, } # Only add kwarg for servicenet if True because user could set # environment variable 'RACKSPACE_SERVICENET' separately. if self.servicenet: kwargs['servicenet'] = Tru...
def _get_connection(self)
Return native connection object.
6.2845
5.936995
1.058532
infos = self.native_conn.list_containers_info() return [self.cont_cls(self, i['name'], i['count'], i['bytes']) for i in infos]
def _get_containers(self)
Return available containers.
8.005012
6.619428
1.209321
cont = self.native_conn.get_container(path) return self.cont_cls(self, cont.name, cont.object_count, cont.size_used)
def _get_container(self, path)
Return single container.
6.78818
5.824332
1.165487
site_delta_E = self.final_site.energy - self.initial_site.energy if self.nearest_neighbour_energy: site_delta_E += self.nearest_neighbour_delta_E() if self.coordination_number_energy: site_delta_E += self.coordination_number_delta_E() return site_delta_E
def delta_E( self )
The change in system energy if this jump were accepted. Args: None Returns: (Float): delta E
3.1976
3.286832
0.972852
delta_nn = self.final_site.nn_occupation() - self.initial_site.nn_occupation() - 1 # -1 because the hopping ion is not counted in the final site occupation number return ( delta_nn * self.nearest_neighbour_energy )
def nearest_neighbour_delta_E( self )
Nearest-neighbour interaction contribution to the change in system energy if this jump were accepted. Args: None Returns: (Float): delta E (nearest-neighbour)
9.394169
10.406946
0.902683
initial_site_neighbours = [ s for s in self.initial_site.p_neighbours if s.is_occupied ] # excludes final site, since this is always unoccupied final_site_neighbours = [ s for s in self.final_site.p_neighbours if s.is_occupied and s is not self.initial_site ] # excludes initial site ini...
def coordination_number_delta_E( self )
Coordination-number dependent energy conrtibution to the change in system energy if this jump were accepted. Args: None Returns: (Float): delta E (coordination-number)
2.136971
2.19786
0.972296
half_cell_lengths = cell_lengths / 2.0 this_dr = self.final_site.r - self.initial_site.r for i in range( 3 ): if this_dr[ i ] > half_cell_lengths[ i ]: this_dr[ i ] -= cell_lengths[ i ] if this_dr[ i ] < -half_cell_lengths[ i ]: th...
def dr( self, cell_lengths )
Particle displacement vector for this jump Args: cell_lengths (np.array(x,y,z)): Cell lengths for the orthogonal simulation cell. Returns (np.array(x,y,z)): dr
2.204559
2.381449
0.925722
l1 = self.initial_site.label l2 = self.final_site.label c1 = self.initial_site.nn_occupation() c2 = self.final_site.nn_occupation() return jump_lookup_table.jump_probability[ l1 ][ l2 ][ c1 ][ c2 ]
def relative_probability_from_lookup_table( self, jump_lookup_table )
Relative probability of accepting this jump from a lookup-table. Args: jump_lookup_table (LookupTable): the lookup table to be used for this jump. Returns: (Float): relative probability of accepting this jump.
3.790995
4.172384
0.908592
if getattr(cache, "config", False): config_file = module[:-2] + "yaml" if config_file not in cache.config_files and os.path.exists(config_file): try: config = yaml_safe_load(config_file, type=dict) except TypeError as e: tangelo.log_warnin...
def module_cache_get(cache, module)
Import a module with an optional yaml config file, but only if we haven't imported it already. :param cache: object which holds information on which modules and config files have been loaded and whether config files should be loaded. :param module: the path of the module...
3.498666
3.285927
1.064742
if within_block_offset < 0 or within_block_offset >= 65536: raise ValueError("Require 0 <= within_block_offset < 2**16, got %i" % within_block_offset) if block_start_offset < 0 or block_start_offset >= 281474976710656: raise ValueError("Require 0 <= block_start_offset < 2**48, got %i" % blo...
def make_virtual_offset(block_start_offset, within_block_offset)
Compute a BGZF virtual offset from block start and within block offsets. The BAM indexing scheme records read positions using a 64 bit 'virtual offset', comprising in C terms: block_start_offset << 16 | within_block_offset Here block_start_offset is the file offset of the BGZF block start (unsigned ...
1.871826
1.51477
1.235716
if self._buffer: self.flush() self._handle.write(_bgzf_eof) self._handle.flush() self._handle.close()
def close(self)
Flush data, write 28 bytes BGZF EOF marker, and close BGZF file. samtools will look for a magic EOF marker, just a 28 byte empty BGZF block, and if it is missing warns the BAM file may be truncated. In addition to samtools writing this block, so too does bgzip - so this implementation do...
6.626153
3.62253
1.829151
home_dir = os.environ['HOME'] file_name = home_dir + "/.ipcamweb" if os.path.exists(file_name): with open(file_name, "r") as s_file: secret = s_file.readline() else: secret = os.urandom(24) with open(file_name, "w") as s_file: secret = s_file.write(se...
def ensure_secret()
Check if secret key to encryot sessions exists, generate it otherwise.
2.551784
2.427697
1.051113
screenshoots_path = path + "/" + str(cam_id) if os.path.exists(screenshoots_path): days = [] for day_dir in os.listdir(screenshoots_path): date = datetime.datetime.strptime(day_dir, "%d%m%Y").strftime('%d/%m/%y') days.append((date, day_dir)) return days e...
def list_snapshots_days(path, cam_id)
Returns a list of (date, dir) in which snapshopts are present
2.619174
2.390469
1.095674
screenshoots_path = path+"/"+str(cam_id)+"/"+day if os.path.exists(screenshoots_path): hours = [] for hour_dir in sorted(os.listdir(screenshoots_path)): hrm = datetime.datetime.strptime(hour_dir, "%H%M").strftime('%H:%M') hours.append((hrm, hour_dir)) return ...
def list_snapshots_hours(path, cam_id, day)
Returns a list of hour/min in which snapshopts are present
2.838767
2.694036
1.053723
screenshoots_path = path+"/"+str(cam_id)+"/"+day+"/"+hourm if os.path.exists(screenshoots_path): screenshots = [scr for scr in sorted(os.listdir(screenshoots_path))] return screenshots else: return []
def list_snapshots_for_a_minute(path, cam_id, day, hourm)
Returns a list of screenshots
3.465392
3.140557
1.103432
return len(self.REF) == 1 and all(a.type == "SNV" for a in self.ALT)
def is_snv(self)
Return ``True`` if it is a SNV
6.37422
5.812773
1.096589
types = {alt.type for alt in self.ALT} # set! BAD_MIX = {INS, SV, BND, SYMBOLIC} # don't mix well with others if (BAD_MIX & types) and len(types) == 1 and list(types)[0] == INS: # Only insertions, return 0-based position right of first base return self.POS # r...
def affected_start(self)
Return affected start position in 0-based coordinates For SNVs, MNVs, and deletions, the behaviour is the start position. In the case of insertions, the position behind the insert position is returned, yielding a 0-length interval together with :py:meth:`~Record.affected_end`
10.33182
8.633942
1.196652
if label not in self.FILTER: if "PASS" in self.FILTER: self.FILTER = [f for f in self.FILTER if f != "PASS"] self.FILTER.append(label)
def add_filter(self, label)
Add label to FILTER if not set yet, removing ``PASS`` entry if present
3.537174
2.212087
1.599021
if key in self.FORMAT: return self.FORMAT.append(key) if value is not None: for call in self: call.data.setdefault(key, value)
def add_format(self, key, value=None)
Add an entry to format The record's calls ``data[key]`` will be set to ``value`` if not yet set and value is not ``None``. If key is already in FORMAT then nothing is done.
4.669372
3.518025
1.327271
result = [] for a in self.gt_alleles: if a is None: result.append(None) elif a == 0: result.append(self.site.REF) else: result.append(self.site.ALT[a - 1].value) return tuple(result)
def gt_bases(self)
Return the actual genotype bases, e.g. if VCF genotype is 0/1, could return ('A', 'T')
3.03241
2.694135
1.12556
if not self.called: return None # not called elif all(a == 0 for a in self.gt_alleles): return HOM_REF elif len(set(self.gt_alleles)) == 1: return HOM_ALT else: return HET
def gt_type(self)
The type of genotype, returns one of ``HOM_REF``, ``HOM_ALT``, and ``HET``.
4.086984
2.800728
1.459258
ignore = ignore or ["PASS"] if "FT" not in self.data or not self.data["FT"]: return False for ft in self.data["FT"]: if ft in ignore: continue # skip if not require: return True elif ft in require: ...
def is_filtered(self, require=None, ignore=None)
Return ``True`` for filtered calls :param iterable ignore: if set, the filters to ignore, make sure to include 'PASS', when setting, default is ``['PASS']`` :param iterable require: if set, the filters to require for returning ``True``
3.880482
4.896497
0.792502
if self.mate_chrom is None: remote_tag = "." else: if self.within_main_assembly: mate_chrom = self.mate_chrom else: mate_chrom = "<{}>".format(self.mate_chrom) tpl = {FORWARD: "[{}:{}[", REVERSE: "]{}:{}]"}[self.mat...
def serialize(self)
Return string representation for VCF
4.636992
4.247838
1.091612
'''Override Series.trend() to return a TimeSeries instance.''' coefficients = self.trend_coefficients(order) x = self.timestamps trend_y = LazyImport.numpy().polyval(coefficients, x) return TimeSeries(zip(x, trend_y))
def trend(self, order=LINEAR)
Override Series.trend() to return a TimeSeries instance.
8.808557
6.325459
1.392556
'''Calculate trend coefficients for the specified order.''' if not len(self.points): raise ArithmeticError('Cannot calculate the trend of an empty series') return LazyImport.numpy().polyfit(self.timestamps, self.values, order)
def trend_coefficients(self, order=LINEAR)
Calculate trend coefficients for the specified order.
7.823071
8.170097
0.957525
'''Calculate a moving average using the specified method and window''' if len(self.points) < window: raise ArithmeticError('Not enough points for moving average') numpy = LazyImport.numpy() if method == TimeSeries.SIMPLE: weights = numpy.ones(window) / float(windo...
def moving_average(self, window, method=SIMPLE)
Calculate a moving average using the specified method and window
4.813006
4.800705
1.002562
'''Forecast points beyond the time series range using the specified forecasting method. `horizon` is the number of points to forecast.''' if len(self.points) <= 1: raise ArithmeticError('Cannot run forecast when len(series) <= 1') R = LazyImport.rpy2() series = LazyIm...
def forecast(self, horizon, method=ARIMA, frequency=None)
Forecast points beyond the time series range using the specified forecasting method. `horizon` is the number of points to forecast.
4.641785
3.78203
1.227326
'''Use STL to decompose the time series into seasonal, trend, and residual components.''' R = LazyImport.rpy2() if periodic: window = 'periodic' elif window is None: window = frequency timestamps = self.timestamps series = LazyImport.numpy(...
def decompose(self, frequency, window=None, periodic=False)
Use STL to decompose the time series into seasonal, trend, and residual components.
4.09935
3.419975
1.198649
pylab.legend() pylab.show()
def plot(self, label=None, colour='g', style='-'): # pragma: no cover '''Plot the time series.''' pylab = LazyImport.pylab() pylab.plot(self.dates, self.values, '%s%s' % (colour, style), label=label) if label is not None
Plot the time series.
22.04171
5.372132
4.102973
'''Get a table representation of a dictionary.''' if type(data) == DictType: data = data.items() headings = [ item[0] for item in data ] rows = [ item[1] for item in data ] columns = zip(*rows) if len(columns): widths = [ max([ len(str(y)) for y in row ]) for row in rows ] el...
def table_output(data)
Get a table representation of a dictionary.
2.31299
2.263951
1.021661
'''Convert `time` to a datetime.''' if type(time) == IntType or type(time) == LongType: time = datetime.fromtimestamp(time // 1000) return time
def to_datetime(time)
Convert `time` to a datetime.
4.262259
4.623717
0.921825
''' Spell check words by using the praatio spellcheck function Incorrect items are noted in a new tier and optionally printed to the screen ''' def checkFunc(word): try: isleDict.lookup(word) except isletool.WordNotInISLE: returnVal = False ...
def spellCheckTextgrid(tg, targetTierName, newTierName, isleDict, printEntries=False)
Spell check words by using the praatio spellcheck function Incorrect items are noted in a new tier and optionally printed to the screen
8.118196
3.726015
2.178788
''' Performs naive alignment for words in a textgrid Naive alignment gives each segment equal duration. Phone duration is determined by the duration of the word and the number of phones. removeOverlappingSegments - remove any labeled words or phones that ...
def naivePhoneAlignment(tg, wordTierName, phoneTierName, isleDict, removeOverlappingSegments=False)
Performs naive alignment for words in a textgrid Naive alignment gives each segment equal duration. Phone duration is determined by the duration of the word and the number of phones. removeOverlappingSegments - remove any labeled words or phones that fall under ...
3.688913
2.76425
1.334508
parser = argparse.ArgumentParser(description="Parser benchmark") parser.add_argument("--debug", default=False, action="store_true", help="Enable debugging") parser.add_argument("--repetitions", type=int, default=10, help="Number of repetitions") parser.add_argument("--line-count", type=int, defaul...
def main(argv=None)
Main program entry point for parsing command line arguments
2.495311
2.449427
1.018733
# open VCF reader reader = vcf.Reader(filename=args.input_vcf) # optionally, open VCF writer writer = None # read through input VCF file, optionally also writing out start = time.clock() num = 0 for num, r in enumerate(reader): if num % 10000 == 0: print(num, ""....
def run_pyvcf(args)
Main program entry point after parsing arguments
3.100778
3.100382
1.000127
parser = argparse.ArgumentParser(description="Benchmark driver") parser.add_argument("--max-records", type=int, default=100 * 1000) parser.add_argument("--engine", type=str, choices=("vcfpy", "pyvcf"), default="vcfpy") parser.add_argument("--input-vcf", type=str, required=True, help="Path to VCF f...
def main(argv=None)
Main program entry point for parsing command line arguments
2.615188
2.579243
1.013936