code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
resource_list = self.traffic_incident() road_closed = namedtuple('road_closed', 'road_closed') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [road_closed(resource['roadClosed']) ...
def road_closed(self)
Retrieves the road closed information for the incident/incidents from the output response Returns: road_closed(namedtuple): List of named tuples of road closed information for the incident/incidents
3.610081
3.068885
1.17635
resource_list = self.traffic_incident() severity = namedtuple('severity', 'severity') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [severity(resource['severity']) for resour...
def severity(self)
Retrieves the severity for the incident/incidents from the output response Returns: severity(namedtuple): List of named tuples of severity for the incident/incidents
3.845313
3.638865
1.056734
resource_list = self.traffic_incident() type = namedtuple('type', 'type') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [type(resource['type']) for resource in resource_list]...
def type(self)
Retrieves the type of the incident/incidents from the output response Returns: type(namedtuple): List of named tuples of type of the incident/incidents
4.190108
3.916823
1.069772
resource_list = self.traffic_incident() verified = namedtuple('verified', 'verified') if len(resource_list) == 1 and resource_list[0] is None: return None else: try: return [verified(resource['verified']) for resour...
def is_verified(self)
Retrieves the verification status of the incident/incidents from the output response Returns: verified(namedtuple): List of named tuples of verification status of the incident/incidents
4.311716
3.800701
1.134453
query = [] keys_to_be_removed = [] for key, value in data.items(): if key not in ['version', 'restApi', 'resourcePath']: if not key == 'method': if key == 'points': value = ','.join(str(val) for val in value) ...
def build_query_string(self, data)
This method occurs after dumping the data into the class. Args: data (dict): dictionary of all the query values Returns: data (dict): ordered dict of all the values
2.793449
2.950455
0.946786
resource_list = self.get_resource() coordinates = namedtuple('coordinates', ['latitude', 'longitude']) try: return [coordinates(*resource['point']['coordinates']) for resource in resource_list] except (KeyError, TypeError): try: ...
def get_coordinates(self)
Retrieves coordinates (latitudes/longitudes) from the output JSON/XML response Returns: coordinates (namedtuple): List of named tuples of coordinates (latitudes and longitudes)
3.10146
3.031591
1.023047
resource_list = self.get_resource() try: return [resource['address'] for resource in resource_list] except (KeyError, TypeError): try: if isinstance(resource_list, dict): resource_list = [resource_list] return [...
def get_address(self)
Retrieves addresses from the output JSON/XML response Returns: address (namedtuple): List of named tuples of addresses
2.940367
3.140883
0.936159
resource_list = self.get_resource() bounding_box = namedtuple('boundingbox', ['southlatitude', 'westlongitude', 'northlatitude', 'eastlongitude']...
def get_bbox(self)
Retrieves the bounding box coordinates from the output JSON/XML response Returns: boundingbox (namedtuple): List of named tuples of bounding box coordinates
2.721628
2.585108
1.05281
url = self.build_url() self.locationApiData = requests.get(url) if not self.locationApiData.status_code == 200: raise self.locationApiData.raise_for_status()
def get_data(self)
Gets data from the built url
3.946814
3.099457
1.273389
cluster = get_cluster() if name not in cluster.metadata.keyspaces: #try the 1.2 method replication_map = { 'class': strategy_class, 'replication_factor':replication_factor } replication_map.update(replication_values) if strategy_class.lower()...
def create_keyspace(name, strategy_class, replication_factor, durable_writes=True, **replication_values)
creates a keyspace :param name: name of keyspace to create :param strategy_class: keyspace replication strategy class :param replication_factor: keyspace replication factor :param durable_writes: 1.2 only, write log is bypassed if set to False :param **replication_values: 1.2 only, additional value...
4.779141
4.863326
0.98269
if not issubclass(model, Model): raise CQLEngineException("Models must be derived from base Model.") if model.__abstract__: raise CQLEngineException("cannot create table from abstract model") #construct query string cf_name = model.column_family_name() raw_cf_name = model.co...
def sync_table(model)
Inspects the model and creates / updates the corresponding table and columns. Note that the attributes removed from the model are not deleted on the database. They become effectively ignored by (will not show up on) the model.
3.679466
3.735618
0.984968
if not model.__compaction__: return {} result = {'class':model.__compaction__} def setter(key, limited_to_strategy = None): mkey = "__compaction_{}__".format(key) tmp = getattr(model, mkey) if tmp and limited_to_strategy and limited_to_strategy != model.__comp...
def get_compaction_options(model)
Generates dictionary (later converted to a string) for creating and altering tables with compaction strategy :param model: :return:
3.885152
4.019799
0.966504
logger.debug("Checking %s for compaction differences", model) table = get_table_settings(model) existing_options = table.options.copy() existing_compaction_strategy = existing_options['compaction_strategy_class'] existing_options = json.loads(existing_options['compaction_strategy_options']) ...
def update_compaction(model)
Updates the compaction options for the given model if necessary. :param model: The model to update. :return: `True`, if the compaction options were modified in Cassandra, `False` otherwise. :rtype: bool
3.285897
3.108319
1.05713
if not isinstance(clause, WhereClause): raise StatementException("only instances of WhereClause can be added to statements") clause.set_context_id(self.context_counter) self.context_counter += clause.get_context_size() self.where_clauses.append(clause)
def add_where_clause(self, clause)
adds a where clause to this statement :param clause: the clause to add :type clause: WhereClause
3.938621
3.770447
1.044603
if not isinstance(clause, AssignmentClause): raise StatementException("only instances of AssignmentClause can be added to statements") clause.set_context_id(self.context_counter) self.context_counter += clause.get_context_size() self.assignments.append(clause)
def add_assignment_clause(self, clause)
adds an assignment clause to this statement :param clause: the clause to add :type clause: AssignmentClause
4.05587
4.098787
0.989529
if not isinstance(clause, TransactionClause): raise StatementException('only instances of AssignmentClause can be added to statements') clause.set_context_id(self.context_counter) self.context_counter += clause.get_context_size() self.transactions.append(clause)
def add_transaction_clause(self, clause)
Adds a iff clause to this statement :param clause: The clause that will be added to the iff statement :type clause: TransactionClause
5.096263
5.32483
0.957075
global cluster, session, default_consistency_level, lazy_connect_args if 'username' in kwargs or 'password' in kwargs: raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider") if not default_keyspace: raise UndefinedKeyspaceException()...
def setup( hosts, default_keyspace, consistency=ConsistencyLevel.ONE, lazy_connect=False, retry_connect=False, **kwargs)
Records the hosts and connects to one of them :param hosts: list of hosts, see http://datastax.github.io/python-driver/api/cassandra/cluster.html :type hosts: list :param default_keyspace: The default keyspace to use :type default_keyspace: str :param consistency: The global consistency level :...
2.700458
3.052203
0.884757
if value is None: if self.required: raise ValidationError('{} - None values are not allowed'.format(self.column_name or self.db_field)) return value
def validate(self, value)
Returns a cleaned and validated value. Raises a ValidationError if there's a problem
6.289902
6.354792
0.989789
global _last_timestamp epoch = datetime(1970, 1, 1, tzinfo=dt.tzinfo) offset = epoch.tzinfo.utcoffset(epoch).total_seconds() if epoch.tzinfo else 0 timestamp = (dt - epoch).total_seconds() - offset node = None clock_seq = None nanoseconds = int(timest...
def from_datetime(self, dt)
generates a UUID for a given datetime :param dt: datetime :type dt: datetime :return:
2.880296
2.877956
1.000813
static = "static" if self.static else "" db_type = self.db_type.format(self.value_type.db_type) return '{} {} {}'.format(self.cql, db_type, static)
def get_column_def(self)
Returns a column definition for CQL table definition
6.275275
5.053505
1.241767
# we're going to take the values, which is from the DB as a dict # and translate that into our local fields # the db_map is a db_field -> model field map items = values.items() field_dict = dict([(cls._db_map.get(k, k),v) for k,v in items]) if cls._is_polymorphi...
def _construct_instance(cls, values)
method used to construct instances from query results this is where polymorphic deserialization occurs
3.235897
3.167869
1.021474
if not self._is_persisted: return False pks = self._primary_keys.keys() return all([not self._values[k].changed for k in self._primary_keys])
def _can_update(self)
Called by the save function to check if this should be persisted with update or insert :return:
7.858625
7.292156
1.077682
cf_name = '' if cls.__table_name__: cf_name = cls.__table_name__.lower() else: # get polymorphic base table names if model is polymorphic if cls._is_polymorphic and not cls._is_polymorphic_base: return cls._polymorphic_base.column_fami...
def column_family_name(cls, include_keyspace=True)
Returns the column family name if it's been defined otherwise, it creates it from the module and class name
3.038436
3.015332
1.007662
self.__dmlquery__(self.__class__, self, batch=self._batch, timestamp=self._timestamp, consistency=self.__consistency__, timeout=self._timeout).delete()
def delete(self)
Deletes this instance
11.777637
11.414823
1.031785
if self._where: self._validate_select_where() return SelectStatement( self.column_family_name, fields=self._select_fields(), where=self._where, order_by=self._order, limit=self._limit, allow_filtering=self._allo...
def _select_query(self)
Returns a select clause based on the given filter args
4.24003
3.92944
1.079042
statement = arg.rsplit('__', 1) if len(statement) == 1: return arg, None elif len(statement) == 2: return statement[0], statement[1] else: raise QueryException("Can't parse '{}'".format(arg))
def _parse_filter_arg(self, arg)
Parses a filter arg in the format: <colname>__<op> :returns: colname, op tuple
3.264609
3.132581
1.042147
if len([x for x in kwargs.values() if x is None]): raise CQLEngineException("None values on iff are not allowed") clone = copy.deepcopy(self) for operator in args: if not isinstance(operator, TransactionClause): raise QueryException('{} is not a ...
def iff(self, *args, **kwargs)
Adds IF statements to queryset
4.266349
4.216916
1.011722
#add arguments to the where clause filters if len([x for x in kwargs.values() if x is None]): raise CQLEngineException("None values on filter are not allowed") clone = copy.deepcopy(self) for operator in args: if not isinstance(operator, WhereClause): ...
def filter(self, *args, **kwargs)
Adds WHERE arguments to the queryset, returning a new queryset #TODO: show examples :rtype: AbstractQuerySet
3.878106
3.799497
1.020689
if args or kwargs: return self.filter(*args, **kwargs).get() self._execute_query() if len(self._result_cache) == 0: raise self.model.DoesNotExist elif len(self._result_cache) > 1: raise self.model.MultipleObjectsReturned( ...
def get(self, *args, **kwargs)
Returns a single instance matching this query, optionally with additional filter kwargs. A DoesNotExistError will be raised if there are no rows matching the query A MultipleObjectsFoundError will be raised if there is more than one row matching the queyr
2.849469
2.594016
1.098478
if len(colnames) == 0: clone = copy.deepcopy(self) clone._order = [] return clone conditions = [] for colname in colnames: conditions.append('"{}" {}'.format(*self._get_ordering_condition(colname))) clone = copy.deepcopy(self) ...
def order_by(self, *colnames)
orders the result set. ordering can only use clustering columns. Default order is ascending, prepend a '-' to the column name for descending
2.903976
3.292878
0.881896
if self._batch: raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode") if self._result_cache is None: query = self._select_query() query.count = True result = self._execute(query) return result[0]['...
def count(self)
Returns the number of rows matched by this query
5.231064
4.699142
1.113196
if not (v is None or isinstance(v, six.integer_types)): raise TypeError if v == self._limit: return self if v < 0: raise QueryException("Negative limit is not allowed") clone = copy.deepcopy(self) clone._limit = v return clon...
def limit(self, v)
Sets the limit on the number of results returned CQL has a default limit of 10,000
3.523831
3.504186
1.005606
#validate where clause partition_key = [x for x in self.model._primary_keys.values()][0] if not any([c.field == partition_key.column_name for c in self._where]): raise QueryException("The partition key must be defined on delete queries") dq = DeleteStatement( ...
def delete(self)
Deletes the contents of a query
6.891899
6.750987
1.020873
#check that there's either a = or IN relationship with a primary key or indexed field equal_ops = [self.model._columns.get(w.field) for w in self._where if isinstance(w.operator, EqualsOperator)] token_comparison = any([w for w in self._where if isinstance(w.value, Token)]) if n...
def _validate_select_where(self)
Checks that a filterset will not create invalid select statement
5.599938
5.434115
1.030515
if not self._values_list: # we want models return lambda rows: self.model._construct_instance(rows) elif self._flat_values_list: # the user has requested flattened list (1 value per row) return lambda row: row.popitem()[1] else: return lambda row: sel...
def _get_result_constructor(self)
Returns a function that will be used to instantiate query results
8.110733
7.320111
1.108007
if not values: return nulled_columns = set() us = UpdateStatement(self.column_family_name, where=self._where, ttl=self._ttl, timestamp=self._timestamp, transactions=self._transaction) for name, val in values.items(): col_name...
def update(self, **values)
Updates the rows in this queryset
3.4031
3.39428
1.002599
ds = DeleteStatement(self.column_family_name) deleted_fields = False for _, v in self.instance._values.items(): col = v.column if v.deleted: ds.add_field(col.db_field_name) deleted_fields = True elif isinstance(col, Map...
def _delete_null_columns(self)
executes a delete query to remove columns that have changed to null
4.696887
4.299263
1.092487
if self.instance is None: raise CQLEngineException("DML Query intance attribute is None") assert type(self.instance) == self.model null_clustering_key = False if len(self.instance._clustering_keys) == 0 else True static_changed_only = True statement = UpdateS...
def update(self)
updates a row. This is a blind update call. All validation and cleaning needs to happen prior to calling this.
4.0596
3.973398
1.021695
if self.instance is None: raise CQLEngineException("DML Query instance attribute is None") ds = DeleteStatement(self.column_family_name, timestamp=self._timestamp) for name, col in self.model._primary_keys.items(): if (not col.partition_key) and (getattr(self.in...
def delete(self)
Deletes one instance
5.777863
5.617214
1.028599
formaters = request.get('formaters', None) if not formaters: formaters = [{'name': 'autopep8'}] logging.debug('formaters: ' + json.dumps(formaters, indent=4)) data = request.get('data', None) if not isinstance(data, str): return send(client, 'invalid data', None) max_line_l...
def handle(client, request)
Handle format request request struct: { 'data': 'data_need_format', 'formaters': [ { 'name': 'formater_name', 'config': {} # None or dict }, ... # formaters ] } if no f...
2.485235
2.046446
1.214415
if include_keyspace: return '{}.{}'.format(self.keyspace, self.name) else: return self.name
def column_family_name(self, include_keyspace=True)
Returns the column family name if it's been defined otherwise, it creates it from the module and class name
2.424606
2.284403
1.061374
_checkRange(n) if n < 0.5: return 2 * n**2 else: n = n * 2 - 1 return -0.5 * (n*(n-2) - 1)
def easeInOutQuad(n)
A quadratic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
3.81439
5.132972
0.743115
_checkRange(n) n = 2 * n if n < 1: return 0.5 * n**3 else: n = n - 2 return 0.5 * (n**3 + 2)
def easeInOutCubic(n)
A cubic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
3.066849
4.809514
0.637663
_checkRange(n) n = 2 * n if n < 1: return 0.5 * n**4 else: n = n - 2 return -0.5 * (n**4 - 2)
def easeInOutQuart(n)
A quartic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
3.412229
5.463165
0.624588
_checkRange(n) n = 2 * n if n < 1: return 0.5 * n**5 else: n = n - 2 return 0.5 * (n**5 + 2)
def easeInOutQuint(n)
A quintic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
2.992119
4.827
0.619871
_checkRange(n) if n == 0: return 0 elif n == 1: return 1 else: n = n * 2 if n < 1: return 0.5 * 2**(10 * (n - 1)) else: n -= 1 # 0.5 * (-() + 2) return 0.5 * (-1 * (2 ** (-10 * n)) + 2)
def easeInOutExpo(n)
An exponential tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
2.656146
3.361231
0.79023
_checkRange(n) n = n * 2 if n < 1: return -0.5 * (math.sqrt(1 - n**2) - 1) else: n = n - 2 return 0.5 * (math.sqrt(1 - n**2) + 1)
def easeInOutCirc(n)
A circular tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
2.160133
3.138793
0.688205
_checkRange(n) return 1 - easeOutElastic(1-n, amplitude=amplitude, period=period)
def easeInElastic(n, amplitude=1, period=0.3)
An elastic tween function that begins with an increasing wobble and then snaps into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
5.715546
9.171687
0.623173
_checkRange(n) if amplitude < 1: amplitude = 1 s = period / 4 else: s = period / (2 * math.pi) * math.asin(1 / amplitude) return amplitude * 2**(-10*n) * math.sin((n-s)*(2*math.pi / period)) + 1
def easeOutElastic(n, amplitude=1, period=0.3)
An elastic tween function that overshoots the destination and then "rubber bands" into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
3.172365
4.407121
0.719827
_checkRange(n) n *= 2 if n < 1: return easeInElastic(n, amplitude=amplitude, period=period) / 2 else: return easeOutElastic(n-1, amplitude=amplitude, period=period) / 2 + 0.5
def easeInOutElastic(n, amplitude=1, period=0.5)
An elastic tween function wobbles towards the midpoint. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
2.684357
3.414873
0.786078
_checkRange(n) return n * n * ((s + 1) * n - s)
def easeInBack(n, s=1.70158)
A tween function that backs up first at the start and then goes to the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
5.299856
8.539732
0.620612
_checkRange(n) n = n - 1 return n * n * ((s + 1) * n + s) + 1
def easeOutBack(n, s=1.70158)
A tween function that overshoots the destination a little and then backs into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
3.989796
6.391308
0.624253
_checkRange(n) n = n * 2 if n < 1: s *= 1.525 return 0.5 * (n * n * ((s + 1) * n - s)) else: n -= 2 s *= 1.525 return 0.5 * (n * n * ((s + 1) * n + s) + 2)
def easeInOutBack(n, s=1.70158)
A "back-in" tween function that overshoots both the start and destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
2.023891
2.730769
0.741143
_checkRange(n) if n < (1/2.75): return 7.5625 * n * n elif n < (2/2.75): n -= (1.5/2.75) return 7.5625 * n * n + 0.75 elif n < (2.5/2.75): n -= (2.25/2.75) return 7.5625 * n * n + 0.9375 else: n -= (2.65/2.75) return 7.5625 * n * n + 0.984...
def easeOutBounce(n)
A bouncing tween function that hits the destination and then bounces to rest. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
1.448257
1.624458
0.891532
''' Not all Admin subclasses use get_field_queryset here, so we will use it explicitly ''' db = kwargs.get('using') kwargs['queryset'] = kwargs.get('queryset', self.get_field_queryset(db, db_field, request)) return super(AccessControlMixin, self).formfield_for_manytomany(...
def formfield_for_manytomany(self, db_field, request, **kwargs)
Not all Admin subclasses use get_field_queryset here, so we will use it explicitly
4.915665
2.367328
2.076462
"The 'delete' admin view for this model." queryset = self.model._default_manager.filter(pk=object_id) response = self.delete_selected(request, queryset) if response: return response url = reverse('admin:%s_%s_changelist' % (self.model._meta.app_label, self.model._meta...
def delete_view(self, request, object_id, extra_context=None)
The 'delete' admin view for this model.
2.241408
2.173059
1.031453
''' The real delete function always evaluated either from the action, or from the instance delete link ''' opts = self.model._meta app_label = opts.app_label # Populate deletable_objects, a data structure of all related objects that # will also be deleted. ...
def delete_selected(self, request, queryset)
The real delete function always evaluated either from the action, or from the instance delete link
1.842418
1.657841
1.111336
collector = NestedObjects(using=queryset.db) collector.collect(queryset) model_perms_needed = set() object_perms_needed = set() STRONG_DELETION_CONTROL = getattr(settings, 'ACCESS_STRONG_DELETION_CONTROL', False) def format_callback(obj): has_admin ...
def get_deleted_objects(self, request, queryset)
Find all objects related to instances of ``queryset`` that should also be deleted. Returns - to_delete - a nested list of strings suitable for display in the template with the ``unordered_list`` filter. - model_count - statistics for models of all deleted instances - perms_n...
3.937204
3.780754
1.041381
''' Reguster plugins. The plugins parameter should be dict mapping model to plugin. Just calls a register_plugin for every such a pair. ''' for model in plugins: cls.register_plugin(model, plugins[model])
def register_plugins(cls, plugins)
Reguster plugins. The plugins parameter should be dict mapping model to plugin. Just calls a register_plugin for every such a pair.
17.220598
2.681113
6.42293
''' Reguster a plugin for the model. The only one plugin can be registered. If you want to combine plugins, use CompoundPlugin. ''' logger.info("Plugin registered for %s: %s", model, plugin) cls.plugins[model] = plugin
def register_plugin(cls, model, plugin)
Reguster a plugin for the model. The only one plugin can be registered. If you want to combine plugins, use CompoundPlugin.
9.804666
3.2504
3.016449
''' Return a default plugin. ''' from importlib import import_module from django.conf import settings default_plugin = getattr(settings, 'ACCESS_DEFAULT_PLUGIN', "access.plugins.DjangoAccessPlugin") if default_plugin not in cls.default_plugins: logger....
def get_default_plugin(cls)
Return a default plugin.
2.676432
2.475272
1.081268
''' Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered. ''' logger.debug("Getting a plugin for: %s", model) if not issubclass(model, Model): return if model in cls.plugins: return cls.plugins[mo...
def plugin_for(cls, model)
Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered.
4.758142
2.786011
1.707869
''' The apply_able(ability, queryset, request) applies the ability to the instance set determined by the queryset for the user requesting the request. This call is passed to the resolved or default plugin if the plugin is found and the method named apply_<ability> is found in th...
def apply_able(self, ability, queryset, request)
The apply_able(ability, queryset, request) applies the ability to the instance set determined by the queryset for the user requesting the request. This call is passed to the resolved or default plugin if the plugin is found and the method named apply_<ability> is found in the plugin, and return...
6.46692
1.820129
3.553
''' Checks the both, check_visible and apply_visible, against the owned model and it's instance set ''' return self.apply_visible(self.get_queryset(), request) if self.check_visible(self.model, request) is not False else self.get_queryset().none()
def visible(self, request)
Checks the both, check_visible and apply_visible, against the owned model and it's instance set
12.615542
3.026759
4.168004
''' Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set ''' return self.apply_changeable(self.get_queryset(), request) if self.check_changeable(self.model, request) is not False else self.get_queryset().none()
def changeable(self, request)
Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set
10.948023
2.997998
3.651778
''' Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set ''' return self.apply_deleteable(self.get_queryset(), request) if self.check_deleteable(self.model, request) is not False else self.get_queryset().none()
def deleteable(self, request)
Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set
10.961607
2.968739
3.692345
modulename, classname = plugin_name.rsplit('.', 1) module = import_module(modulename) return getattr(module, classname)
def get_plugin_from_string(plugin_name)
Returns plugin or plugin point class from given ``plugin_name`` string. Example of ``plugin_name``:: 'my_app.MyPlugin'
2.535134
3.021827
0.838941
if value is None: return default try: return int(value) except ValueError: print "Couldn't cast value to `int`." return default
def _parse_int(value, default=None)
Attempt to cast *value* into an integer, returning *default* if it fails.
4.081908
3.494008
1.16826
if value is None: return default try: return float(value) except ValueError: print "Couldn't cast value to `float`." return default
def _parse_float(value, default=None)
Attempt to cast *value* into a float, returning *default* if it fails.
4.137051
3.520606
1.175096
default = type_func(0) if value is None: return default try: return type_func(value) except ValueError: return default
def _parse_type(value, type_func)
Attempt to cast *value* into *type_func*, returning *default* if it fails.
3.149286
2.492192
1.263661
# Get histogram of original data y, x = np.histogram(data, bins=bins, normed=True) x = (x + np.roll(x, -1))[:-1] / 2.0 # Distributions to check DISTRIBUTIONS = [ st.alpha,st.anglit,st.arcsine,st.beta,st.betaprime,st.bradford,st.burr,st.cauchy,st.chi,st.chi2,st.cosine, s...
def best_fit_distribution(data, bins=200, ax=None)
Model data by finding best fit distribution to data
1.355458
1.346977
1.006296
# Separate parts of parameters arg = params[:-2] loc = params[-2] scale = params[-1] # Get sane start and end points of distribution start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale) end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if ...
def make_pdf(dist, params, size=10000)
Generate distributions's Propbability Distribution Function
2.035293
1.997777
1.018779
with open('raw.json') as input: data = json.load(input) ''' print("Loading index") md = readmetadata() for record in data: id = record['metadata']['id'] metadata = md[id] pprint(metadata) sys.exit(0) title = record['book']['title'] isbn = isbnl...
def download_isbn()
print("Loading index") md = readmetadata() for record in data: id = record['metadata']['id'] metadata = md[id] pprint(metadata) sys.exit(0) title = record['book']['title'] isbn = isbnlib.isbn_from_words(title) metadata = isbnlib.meta(isbn) pprint(m...
4.819635
2.380555
2.024585
return query + '?' + "&".join(key+'='+quote_plus(str(value)) for key, value in params)
def urlencode(query, params)
Correctly convert the given query and parameters into a full query+query string, ensuring the order of the params.
5.508845
5.976608
0.921734
if value is None: return default try: return bool(value) except ValueError: return default
def _parse_boolean(value, default=False)
Attempt to cast *value* into a bool, returning *default* if it fails.
3.153574
2.495797
1.263554
if PYTHON_3: req = request.Request(url, headers=HEADER) response = request.urlopen(req) return response.read().decode('utf-8') else: req = urllib2.Request(url, headers=HEADER) response = urllib2.urlopen(req) return response.read()
def _get(url)
Convert a URL into it's response (a *str*).
2.038549
2.0029
1.017799
if isinstance(input, dict): return {_recursively_convert_unicode_to_str(key): _recursively_convert_unicode_to_str(value) for key, value in input.items()} elif isinstance(input, list): return [_recursively_convert_unicode_to_str(element) for element in input] elif not PYTHON_3 and isinst...
def _recursively_convert_unicode_to_str(input)
Force the given input to only use `str` instead of `bytes` or `unicode`. This works even if the input is a dict, list,
1.575077
1.66564
0.945628
'''Loads the cache from the string''' global _CACHE if PYTHON_3: data = json.loads(data.decode("utf-8")) else: data = json.loads(data) _CACHE = _recursively_convert_unicode_to_str(data)['data']
def _load_from_string(data)
Loads the cache from the string
5.28124
5.062703
1.043166
global _CONNECTED if filename is not None: try: with open(filename, 'r') as f: _load_from_string(f.read()) except FileNotFoundError: raise USGSException(.format(filename)) for key in _CACHE.keys(): _CACHE_COUNTER[key] = 0 _CONNECTED = ...
def disconnect(filename=None)
Connect to the local cache, so no internet connection is required. :returns: void
5.051528
4.97527
1.015327
if key not in _CACHE: return None if _CACHE_COUNTER[key] >= len(_CACHE[key][1:]): if _CACHE[key][0] == "empty": return "" elif _CACHE[key][0] == "repeat" and _CACHE[key][1:]: return _CACHE[key][-1] elif _CACHE[key][0] == "repeat": return "...
def _lookup(key)
Internal method that looks up a key in the local cache. :param key: Get the value based on the key from the cache. :type key: string :returns: void
2.551043
2.597022
0.982296
if key in _CACHE: _CACHE[key].append(value) else: _CACHE[key] = [_PATTERN, value] _CACHE_COUNTER[key] = 0
def _add_to_cache(key, value)
Internal method to add a new key-value to the local cache. :param str key: The new url to add to the cache :param str value: The HTTP response for this key. :returns: void
4.311478
4.891403
0.88144
key = _get_report_request(time, threshold) result = _get(key) if _CONNECTED else _lookup(key) if (_CONNECTED or online) and _EDITABLE: _add_to_cache(key, result) return result
def _get_report_string(time='hour', threshold='significant', online=False)
Like :func:`get_report` except returns the raw data instead. :param str time: A string indicating the time range of earthquakes to report. Must be either "hour" (only earthquakes in the past hour), "day" (only earthquakes that happened today), "week" (only earthquakes that happened in the past 7 days), or "mon...
7.938841
9.462934
0.838941
if threshold not in THRESHOLDS: raise USGSException('Unknown threshold: "{}" (must be either "significant", "all", "4.5", "2.5", or "1.0")'.format(threshold)) if time not in TIMES: raise USGSException('Unknown time: "{}" (must be either "hour", "day", "week", "month")'.format(time)) try...
def get_report(time='hour', threshold='significant', online=False)
Retrieves a new Report about recent earthquakes. :param str time: A string indicating the time range of earthquakes to report. Must be either "hour" (only earthquakes in the past hour), "day" (only earthquakes that happened today), "week" (only earthquakes that happened in the past 7 days), or "month" (only ea...
3.499188
3.220152
1.086653
''' Returns a dictionary representation of this object ''' return dict(latitude=self.latitude, longitude=self.longitude, depth=self.depth)
def _to_dict(self)
Returns a dictionary representation of this object
5.422328
4.890665
1.10871
if len(json_data) >= 3: return Coordinate(_parse_float(json_data[0]), _parse_float(json_data[1]), _parse_float(json_data[2])) else: raise USGSException("The given coordinate information was incomplete.")
def _from_json(json_data)
Creates a Coordinate from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: Coordinate
4.307091
4.052209
1.062899
''' Returns a dictionary representation of this object ''' return dict(minimum=self.minimum._to_dict(), maximum=self.maximum._to_dict())
def _to_dict(self)
Returns a dictionary representation of this object
5.976367
5.229564
1.142804
if len(json_data) >= 6: return BoundingBox( Coordinate(_parse_float(json_data[0]), _parse_float(json_data[1]), _parse_float(json_data[2])), Coordinate(_parse_float(json_data...
def _from_json(json_data)
Creates a BoundingBox from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: BoundingBox
2.724051
2.57659
1.057231
try: coordinates = json_data['geometry']['coordinates'] except KeyError: raise USGSException("The geometry information was not returned from the USGS website.") try: properties = json_data['properties'] except KeyError: raise USGSE...
def _from_json(json_data)
Creates a Earthquake from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: Earthquake
2.246871
2.190216
1.025867
''' Returns a dictionary representation of this object ''' return dict(area= self.area._to_dict(), earthquakes = [q._to_dict() for q in self.earthquakes], title = self.title)
def _to_dict(self)
Returns a dictionary representation of this object
6.088658
5.533817
1.100264
if 'bbox' in json_data: box = BoundingBox._from_json(json_data['bbox']) else: box = BoundingBox(Coordinate(0.,0.,0.), Coordinate(0.,0.,0.)) if 'features' in json_data and json_data['features']: quakes = list(map(Earthquake._from_json, json_data['featu...
def _from_json(json_data)
Creates a Report from json data. :param json_data: The raw json data to parse :type json_data: dict :returns: Report
3.285559
3.237885
1.014724
if isinstance(input, dict): return {_byteify(key): _byteify(value) for key, value in input.items()} elif isinstance(input, list): return [_byteify(element) for element in input] elif _PYTHON_3 and isinstance(input, str): return str(input.encode('ascii', 'replace').decode('ascii'...
def _byteify(input)
Force the given input to only use `str` instead of `bytes` or `unicode`. This works even if the input is a dict, list,
1.873975
1.860801
1.00708
soup = BeautifulSoup(html,'lxml') table = soup.find("table", attrs={"class":"basic_table"}) if table is None: return table return table '''# The first tr contains the field names. datasets = [] for row in table.find_all("tr"): dataset = list((td.get_text().strip(), ...
def extract_table(html)
# The first tr contains the field names. datasets = [] for row in table.find_all("tr"): dataset = list((td.get_text().strip(), td.attrs.get('colspan', 1), td.attrs.get('rowspan', 1)) for td in row.find_all("td")) datasets.a...
4.613174
2.197065
2.099698
bad_indexes = set() bad_keys = set() DEVIATIONS = 4 MAX_LENGTH = 10000 for data in lodol: #print(data['name']) #print([e for e in data['data'] if isinstance(e, (str, unicode))]) if isinstance(data['data'][0], (int, float)): mean = statistics.mean(data['data']...
def remove_outliers(lodol, actually_keep=True)
I have a list of numbers Z from 0 to N I have a list of J numbers (where J < N) randomly distributed throughout Z I wish to remove K numbers from Z, without drawing from any number in J
3.435984
2.7751
1.238148
bad_indexes = set() bad_keys = set() DEVIATIONS = 3 MAX_LENGTH = 10000 for data in lodol: #print(data['name']) #print([e for e in data['data'] if isinstance(e, (str, unicode))]) if isinstance(data['data'][0], (int, float)): print(data['name']) mea...
def remove_outliers(lodol, actually_keep=True)
I have a list of numbers Z from 0 to N I have a list of J numbers (where J < N) randomly distributed throughout Z I wish to remove K numbers from Z, without drawing from any number in J
3.407276
2.840625
1.199481
ppath = cls.get_pythonpath() if is_plugin_point(cls): if name is not None: kwargs = {} if status is not None: kwargs['status'] = status return Plugin.objects.get(point__pythonpath=ppath, ...
def get_model(cls, name=None, status=ENABLED)
Returns model instance of plugin point or plugin, depending from which class this methos is called. Example:: plugin_model_instance = MyPlugin.get_model() plugin_model_instance = MyPluginPoint.get_model('plugin-name') plugin_point_model_instance = MyPluginPoint.get_...
3.806041
3.71638
1.024126
if is_plugin_point(cls): raise Exception(_('This method is only available to plugin ' 'classes.')) else: return PluginPointModel.objects.\ get(plugin__pythonpath=cls.get_pythonpath())
def get_point_model(cls)
Returns plugin point model instance. Only used from plugin classes.
9.09224
6.032055
1.50732
# Django >= 1.9 changed something with the migration logic causing # plugins to be executed before the corresponding database tables # exist. This method will only return something if the database # tables have already been created. # XXX: I don't fully understand the is...
def get_plugins(cls)
Returns all plugin instances of plugin point, passing all args and kwargs to plugin constructor.
8.007493
7.264863
1.102222
if is_plugin_point(cls): point_pythonpath = cls.get_pythonpath() return Plugin.objects.filter(point__pythonpath=point_pythonpath, status=ENABLED).\ order_by('index') else: raise Exception(_('This method...
def get_plugins_qs(cls)
Returns query set of all plugins belonging to plugin point. Example:: for plugin_instance in MyPluginPoint.get_plugins_qs(): print(plugin_instance.get_plugin().name)
7.006909
6.783118
1.032992
if os.path.exists(PICKLEFILE): metadata = pickle.load(gzip.open(PICKLEFILE, 'rb')) else: metadata = {} for xml in tqdm(getrdfdata()): ebook = xml.find(r'{%(pg)s}ebook' % NS) if ebook is None: continue result = parsemetadata(ebook) if result is not None: metadata[result['id']] = result pi...
def readmetadata()
Read/create cached metadata dump of Gutenberg catalog. Returns: A dictionary with the following fields: id (int): Gutenberg identifier of text author (str): Last name, First name title (str): title of work subjects (list of str): list of descriptive subjects; a subject may be hierarchical, e.g: 'Englan...
3.026994
3.082936
0.981854
if not os.path.exists(RDFFILES): _, _ = urllib.urlretrieve(RDFURL, RDFFILES) with tarfile.open(RDFFILES) as archive: for tarinfo in archive: yield ElementTree.parse(archive.extractfile(tarinfo))
def getrdfdata()
Downloads Project Gutenberg RDF catalog. Yields: xml.etree.ElementTree.Element: An etext meta-data definition.
3.518454
3.051447
1.153044