code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def count(self):
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)
r... | Returns the number of rows matched by this query |
def limit(self, v):
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... | Sets the limit on the number of results returned
CQL has a default limit of 10,000 |
def delete(self):
#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 = Delet... | Deletes the contents of a query |
def _validate_select_where(self):
#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 isinsta... | Checks that a filterset will not create invalid select statement |
def _get_result_constructor(self):
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:... | Returns a function that will be used to instantiate query results |
def update(self, **values):
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.i... | Updates the rows in this queryset |
def _delete_null_columns(self):
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
... | executes a delete query to remove columns that have changed to null |
def delete(self):
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) an... | Deletes one instance |
def handle(client, request):
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... | Handle format request
request struct:
{
'data': 'data_need_format',
'formaters': [
{
'name': 'formater_name',
'config': {} # None or dict
},
... # formaters
]
}
if no f... |
def column_family_name(self, include_keyspace=True):
if include_keyspace:
return '{}.{}'.format(self.keyspace, self.name)
else:
return self.name | Returns the column family name if it's been defined
otherwise, it creates it from the module and class name |
def easeInOutQuad(n):
_checkRange(n)
if n < 0.5:
return 2 * n**2
else:
n = n * 2 - 1
return -0.5 * (n*(n-2) - 1) | 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(). |
def easeInOutCubic(n):
_checkRange(n)
n = 2 * n
if n < 1:
return 0.5 * n**3
else:
n = n - 2
return 0.5 * (n**3 + 2) | 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(). |
def easeInOutQuart(n):
_checkRange(n)
n = 2 * n
if n < 1:
return 0.5 * n**4
else:
n = n - 2
return -0.5 * (n**4 - 2) | 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(). |
def easeInOutQuint(n):
_checkRange(n)
n = 2 * n
if n < 1:
return 0.5 * n**5
else:
n = n - 2
return 0.5 * (n**5 + 2) | 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(). |
def easeInOutExpo(n):
_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) | 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(). |
def easeInOutCirc(n):
_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) | 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(). |
def easeInElastic(n, amplitude=1, period=0.3):
_checkRange(n)
return 1 - easeOutElastic(1-n, amplitude=amplitude, period=period) | 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(). |
def easeOutElastic(n, amplitude=1, period=0.3):
_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 | 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(). |
def easeInOutElastic(n, amplitude=1, period=0.5):
_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 | 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(). |
def easeInBack(n, s=1.70158):
_checkRange(n)
return n * n * ((s + 1) * n - s) | 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(). |
def easeOutBack(n, s=1.70158):
_checkRange(n)
n = n - 1
return n * n * ((s + 1) * n + s) + 1 | 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(). |
def easeInOutBack(n, s=1.70158):
_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) | 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(). |
def easeOutBounce(n):
_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 ... | 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(). |
def formfield_for_manytomany(self, db_field, request, **kwargs):
'''
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))
... | Not all Admin subclasses use get_field_queryset here, so we will use it explicitly |
def delete_view(self, request, object_id, extra_context=None):
"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... | The 'delete' admin view for this 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.
'''
for model in plugins:
cls.register_plugin(model, plugins[model]f register_plugins(cls, plug... | Reguster plugins. The plugins parameter should be dict mapping model to plugin.
Just calls a register_plugin for every such a pair. |
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.
'''
logger.info("Plugin registered for %s: %s", model, plugin)
cls.plugins[model] = plugif register_pl... | Reguster a plugin for the model.
The only one plugin can be registered. If you want to combine plugins, use CompoundPlugin. |
def get_default_plugin(cls):
'''
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... | Return a default plugin. |
def plugin_for(cls, model):
'''
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:
... | Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered. |
def visible(self, request):
'''
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(f visible(self... | Checks the both, check_visible and apply_visible, against the owned model and it's instance set |
def changeable(self, request):
'''
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... | Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set |
def deleteable(self, request):
'''
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... | Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set |
def get_plugin_from_string(plugin_name):
modulename, classname = plugin_name.rsplit('.', 1)
module = import_module(modulename)
return getattr(module, classname) | Returns plugin or plugin point class from given ``plugin_name`` string.
Example of ``plugin_name``::
'my_app.MyPlugin' |
def _parse_int(value, default=None):
if value is None:
return default
try:
return int(value)
except ValueError:
print "Couldn't cast value to `int`."
return default | Attempt to cast *value* into an integer, returning *default* if it fails. |
def _parse_float(value, default=None):
if value is None:
return default
try:
return float(value)
except ValueError:
print "Couldn't cast value to `float`."
return default | Attempt to cast *value* into a float, returning *default* if it fails. |
def _parse_type(value, type_func):
default = type_func(0)
if value is None:
return default
try:
return type_func(value)
except ValueError:
return default | Attempt to cast *value* into *type_func*, returning *default* if it fails. |
def make_pdf(dist, params, size=10000):
# 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.p... | Generate distributions's Propbability Distribution Function |
def urlencode(query, params):
return query + '?' + "&".join(key+'='+quote_plus(str(value))
for key, value in params) | Correctly convert the given query and parameters into a full query+query
string, ensuring the order of the params. |
def _parse_boolean(value, default=False):
if value is None:
return default
try:
return bool(value)
except ValueError:
return default | Attempt to cast *value* into a bool, returning *default* if it fails. |
def _get(url):
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() | Convert a URL into it's response (a *str*). |
def _recursively_convert_unicode_to_str(input):
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 el... | Force the given input to only use `str` instead of `bytes` or `unicode`.
This works even if the input is a dict, list, |
def _load_from_string(data):
'''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'f _load_from_string(data):
'''Loads the cache from the stri... | Loads the cache from the string |
def disconnect(filename=None):
global _CONNECTED
if filename is not None:
try:
with open(filename, 'r') as f:
_load_from_string(f.read())
except FileNotFoundError:
raise USGSException("""The cache file '{0}' was not found, and I cannot disconnect with... | Connect to the local cache, so no internet connection is required.
:returns: void |
def _lookup(key):
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":
... | 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 |
def _add_to_cache(key, value):
if key in _CACHE:
_CACHE[key].append(value)
else:
_CACHE[key] = [_PATTERN, value]
_CACHE_COUNTER[key] = 0 | 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 |
def _get_report_string(time='hour', threshold='significant', online=False):
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 | 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... |
def _to_dict(self):
''' Returns a dictionary representation of this object '''
return dict(latitude=self.latitude,
longitude=self.longitude,
depth=self.depthf _to_dict(self):
''' Returns a dictionary representation of this object '''
return dict(la... | Returns a dictionary representation of this object |
def _from_json(json_data):
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 incomp... | Creates a Coordinate from json data.
:param json_data: The raw json data to parse
:type json_data: dict
:returns: Coordinate |
def _to_dict(self):
''' Returns a dictionary representation of this object '''
return dict(minimum=self.minimum._to_dict(),
maximum=self.maximum._to_dict()f _to_dict(self):
''' Returns a dictionary representation of this object '''
return dict(minimum=self.minimum._to... | Returns a dictionary representation of this object |
def _from_json(json_data):
if len(json_data) >= 6:
return BoundingBox(
Coordinate(_parse_float(json_data[0]),
_parse_float(json_data[1]),
_parse_float(json_data[2])),
Coordi... | Creates a BoundingBox from json data.
:param json_data: The raw json data to parse
:type json_data: dict
:returns: BoundingBox |
def _from_json(json_data):
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 KeyErr... | Creates a Earthquake from json data.
:param json_data: The raw json data to parse
:type json_data: dict
:returns: Earthquake |
def _to_dict(self):
''' 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.titlef _to_dict(self):
''' Returns a dictionary representation of th... | Returns a dictionary representation of this object |
def _from_json(json_data):
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._... | Creates a Report from json data.
:param json_data: The raw json data to parse
:type json_data: dict
:returns: Report |
def _byteify(input):
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', 'rep... | Force the given input to only use `str` instead of `bytes` or `unicode`.
This works even if the input is a dict, list, |
def extract_table(html):
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... | # 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... |
def get_model(cls, name=None, status=ENABLED):
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_... | 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_... |
def get_point_model(cls):
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()) | Returns plugin point model instance. Only used from plugin classes. |
def get_plugins(cls):
# 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 f... | Returns all plugin instances of plugin point, passing all args and
kwargs to plugin constructor. |
def get_plugins_qs(cls):
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... | 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) |
def readmetadata():
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[... | 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... |
def getrdfdata():
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)) | Downloads Project Gutenberg RDF catalog.
Yields:
xml.etree.ElementTree.Element: An etext meta-data definition. |
def etextno(lines):
for line in lines:
match = ETEXTRE.search(line)
if match is not None:
front_match = match.group('etextid_front')
back_match = match.group('etextid_back')
if front_match is not None:
return int(front_match)
elif back_match is not None:
return int(back_match)
else:
ra... | Retrieves the id for an etext.
Args:
lines (iter): The lines of the etext to search.
Returns:
int: The id of the etext.
Raises:
ValueError: If no etext id was found.
Examples:
>>> etextno(['Release Date: March 17, 2004 [EBook #11609]'])
11609
>>> etextno(['Release Date: July, 2003 [Etext# 4263]'])
426... |
def safeunicode(arg, *args, **kwargs):
return arg if isinstance(arg, unicode) else unicode(arg, *args, **kwargs) | Coerce argument to unicode, if it's not already. |
def get_reports():
if False:
# If there was a Test version of this method, it would go here. But alas.
pass
else:
rows = _Constants._DATABASE.execute("SELECT data FROM energy".format(
hardware=_Constants._HARDWARE))
data = [r[0] for r in rows]
data = [_Au... | Returns energy data from 1960 to 2014 across various factors. |
def available(self, src, dst, model):
for name, point in six.iteritems(src):
inst = dst.pop(name, None)
if inst is None:
self.print_(1, "Registering %s for %s" % (model.__name__,
name))
ins... | Iterate over all registered plugins or plugin points and prepare to add
them to database. |
def missing(self, dst):
for inst in six.itervalues(dst):
if inst.status != REMOVED:
inst.status = REMOVED
inst.save() | Mark all missing plugins, that exists in database, but are not
registered. |
def all(self):
# 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 un... | Synchronize all registered plugins and plugin points to database. |
def get_weather(test=False):
if _Constants._TEST or test:
rows = _Constants._DATABASE.execute("SELECT data FROM weather LIMIT {hardware}".format(
hardware=_Constants._HARDWARE))
data = [r[0] for r in rows]
data = [_Auxiliary._byteify(_json.loads(r)) for r in data]
... | Returns weather reports from the dataset. |
def _get(self, url, **kw):
'''
Makes a GET request, setting Authorization
header by default
'''
headers = kw.pop('headers', {})
headers.setdefault('Content-Type', 'application/json')
headers.setdefault('Accept', 'application/json')
headers.setdefault('Auth... | Makes a GET request, setting Authorization
header by default |
def _post(self, url, **kw):
'''
Makes a POST request, setting Authorization
header by default
'''
headers = kw.pop('headers', {})
headers.setdefault('Authorization', self.AUTHORIZATION_HEADER)
kw['headers'] = headers
resp = self.session.post(url, **kw)
... | Makes a POST request, setting Authorization
header by default |
def _post_json(self, url, data, **kw):
'''
Makes a POST request, setting Authorization
and Content-Type headers by default
'''
data = json.dumps(data)
headers = kw.pop('headers', {})
headers.setdefault('Content-Type', 'application/json')
headers.setdefault... | Makes a POST request, setting Authorization
and Content-Type headers by default |
def from_xuid(cls, xuid):
'''
Instantiates an instance of ``GamerProfile`` from
an xuid
:param xuid: Xuid to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance
'''
url = 'https://profile.xboxlive.... | Instantiates an instance of ``GamerProfile`` from
an xuid
:param xuid: Xuid to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance |
def from_gamertag(cls, gamertag):
'''
Instantiates an instance of ``GamerProfile`` from
a gamertag
:param gamertag: Gamertag to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance
'''
url = 'https:/... | Instantiates an instance of ``GamerProfile`` from
a gamertag
:param gamertag: Gamertag to look up
:raises: :class:`~xbox.exceptions.GamertagNotFound`
:returns: :class:`~xbox.GamerProfile` instance |
def saved_from_user(cls, user, include_pending=False):
'''
Gets all clips 'saved' by a user.
:param user: :class:`~xbox.GamerProfile` instance
:param bool include_pending: whether to ignore clips that are not
yet uploaded. These clips will have thumbnails and media_url
... | Gets all clips 'saved' by a user.
:param user: :class:`~xbox.GamerProfile` instance
:param bool include_pending: whether to ignore clips that are not
yet uploaded. These clips will have thumbnails and media_url
set to ``None``
:returns: Iterator of :class:`~xbox.Clip` in... |
def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None):
if self.total is False and error:
# Disabled, indicate to re-raise the error.
raise six.reraise(type(error), error, _stacktrace)
total = self.total
if total is n... | Return a new Retry object with incremented retry counters.
:param response: A response object, or None, if the server did not
return a response.
:type response: :class:`~urllib3.response.HTTPResponse`
:param Exception error: An error encountered during the request, or
No... |
def from_httplib(ResponseCls, r, **response_kw):
headers = HTTPHeaderDict()
for k, v in r.getheaders():
headers.add(k, v)
# HTTPResponse objects in Python 3 don't have a .strict attribute
strict = getattr(r, 'strict', 0)
return ResponseCls(body=r,
... | Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``. |
def add(self, key, value):
self._data.setdefault(key.lower(), []).append((key, value)) | Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz' |
def handle_401(self, r, **kwargs):
if self.pos is not None:
# Rewind the file position indicator of the body to where
# it was to resend the request.
r.request.body.seek(self.pos)
num_401_calls = getattr(self, 'num_401_calls', 1)
s_auth = r.headers.g... | Takes the given response and tries digest-auth, if needed. |
def prepare(self):
p = PreparedRequest()
p.prepare(
method=self.method,
url=self.url,
headers=self.headers,
files=self.files,
data=self.data,
params=self.params,
auth=self.auth,
cookies=self.cookies,... | Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. |
def prepare_url(self, url, params):
url = to_native_string(url)
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'... | Prepares the given HTTP URL. |
def prepare_body(self, data, files):
# Check if file, fo, generator, iterator.
# If not, run through normal process.
# Nottin' on you.
body = None
content_type = None
length = None
is_stream = all([
hasattr(data, '__iter__'),
no... | Prepares the given HTTP body data. |
def request_url(self, request, proxies):
proxies = proxies or {}
scheme = urlparse(request.url).scheme
proxy = proxies.get(scheme)
if proxy and scheme != 'https':
url, _ = urldefrag(request.url)
else:
url = request.path_url
return url | Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
... |
def get_encodings_from_content(content):
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
return (charset_re.findall(content) +
... | Returns encodings from given content string.
:param content: bytestring to extract encodings from. |
def _prepare_conn(self, conn):
if isinstance(conn, VerifiedHTTPSConnection):
conn.set_cert(key_file=self.key_file,
cert_file=self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs,
... | Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
and establish the tunnel if proxy is used. |
def description_of(file, name='stdin'):
u = UniversalDetector()
for line in file:
u.feed(line)
u.close()
result = u.result
if result['encoding']:
return '%s: %s with confidence %s' % (name,
result['encoding'],
... | Return a string describing the probable encoding of a file. |
def dumps(obj, **kwargs):
''' Serialize `obj` to a JSON formatted `str`. Accepts the same arguments
as `json` module in stdlib.
:param obj: a JSON serializable Python object.
:param kwargs: all the arguments that `json.dumps <http://docs.python.org/
2/library/json.html#json.dumps>`_ ... | Serialize `obj` to a JSON formatted `str`. Accepts the same arguments
as `json` module in stdlib.
:param obj: a JSON serializable Python object.
:param kwargs: all the arguments that `json.dumps <http://docs.python.org/
2/library/json.html#json.dumps>`_ accepts.
:raises: commentjson.... |
def load(fp, **kwargs):
''' Deserialize `fp` (a `.read()`-supporting file-like object containing a
JSON document with Python or JavaScript like comments) to a Python object.
:param fp: a `.read()`-supporting file-like object containing a JSON
document with or without comments.
:param kwa... | Deserialize `fp` (a `.read()`-supporting file-like object containing a
JSON document with Python or JavaScript like comments) to a Python object.
:param fp: a `.read()`-supporting file-like object containing a JSON
document with or without comments.
:param kwargs: all the arguments that `jso... |
def dump(obj, fp, **kwargs):
''' Serialize `obj` as a JSON formatted stream to `fp` (a
`.write()`-supporting file-like object). Accepts the same arguments as
`json` module in stdlib.
:param obj: a JSON serializable Python object.
:param fp: a `.read()`-supporting file-like object containing a JSON
... | Serialize `obj` as a JSON formatted stream to `fp` (a
`.write()`-supporting file-like object). Accepts the same arguments as
`json` module in stdlib.
:param obj: a JSON serializable Python object.
:param fp: a `.read()`-supporting file-like object containing a JSON
document with or witho... |
def prepend_name_prefix(func):
@wraps(func)
def prepend_prefix(self, name, *args, **kwargs):
name = self.name_prefix + name
return func(self, name, *args, **kwargs)
return prepend_prefix | Decorator that wraps instance methods to prepend the instance's filename
prefix to the beginning of the referenced filename. Must only be used on
instance methods where the first parameter after `self` is `name` or a
comparable parameter of a different name. |
def get_chalk(level):
if level >= logging.ERROR:
_chalk = chalk.red
elif level >= logging.WARNING:
_chalk = chalk.yellow
elif level >= logging.INFO:
_chalk = chalk.blue
elif level >= logging.DEBUG:
_chalk = chalk.green
else:
_chalk = chalk.white
retur... | Gets the appropriate piece of chalk for the logging level |
def to_str(obj):
if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):
obj = obj.decode('utf-8')
return obj if isinstance(obj, string_types) else str(obj) | Attempts to convert given object to a string object |
def get_color(self, value):
if value in COLOR_SET:
value = COLOR_MAP[value]
else:
try:
value = int(value)
if value >= 8:
raise ValueError()
except ValueError as exc:
raise ValueError(
... | Helper method to validate and map values used in the instantiation of
of the Color object to the correct unicode value. |
def ctr_counter(nonce, f, start = 0):
for n in range(start, 2**64):
yield f(nonce, n)
while True:
for n in range(0, 2**64):
yield f(nonce, n) | Return an infinite iterator that starts at `start` and iterates by 1 over
integers between 0 and 2^64 - 1 cyclically, returning on each iteration the
result of combining each number with `nonce` using function `f`.
`nonce` should be an random 64-bit integer that is used to make the counter
unique.
`f` s... |
def encrypt_block(self, block):
S0, S1, S2, S3 = self.S
P = self.P
u4_1_pack = self._u4_1_pack
u1_4_unpack = self._u1_4_unpack
try:
L, R = self._u4_2_unpack(block)
except struct_error:
raise ValueError("block is not 8 bytes in length")
for p1, p2 in P[:-1]:
... | Return a :obj:`bytes` object containing the encrypted bytes of a `block`.
`block` should be a :obj:`bytes`-like object with exactly 8 bytes.
If it is not, a :exc:`ValueError` exception is raised. |
def encrypt_ecb(self, data):
S1, S2, S3, S4 = self.S
P = self.P
u4_1_pack = self._u4_1_pack
u1_4_unpack = self._u1_4_unpack
encrypt = self._encrypt
u4_2_pack = self._u4_2_pack
try:
LR_iter = self._u4_2_iter_unpack(data)
except struct_error:
raise ValueErro... | Return an iterator that encrypts `data` using the Electronic Codebook (ECB)
mode of operation.
ECB mode can only operate on `data` that is a multiple of the block-size
in length.
Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes)
containing the encrypted bytes of the c... |
def decrypt_ecb(self, data):
S1, S2, S3, S4 = self.S
P = self.P
u4_1_pack = self._u4_1_pack
u1_4_unpack = self._u1_4_unpack
decrypt = self._decrypt
u4_2_pack = self._u4_2_pack
try:
LR_iter = self._u4_2_iter_unpack(data)
except struct_error:
raise ValueErro... | Return an iterator that decrypts `data` using the Electronic Codebook (ECB)
mode of operation.
ECB mode can only operate on `data` that is a multiple of the block-size
in length.
Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes)
containing the decrypted bytes of the c... |
def encrypt_cbc(self, data, init_vector):
S1, S2, S3, S4 = self.S
P = self.P
u4_1_pack = self._u4_1_pack
u1_4_unpack = self._u1_4_unpack
encrypt = self._encrypt
u4_2_pack = self._u4_2_pack
try:
prev_cipher_L, prev_cipher_R = self._u4_2_unpack(init_vector)
except... | Return an iterator that encrypts `data` using the Cipher-Block Chaining
(CBC) mode of operation.
CBC mode can only operate on `data` that is a multiple of the block-size
in length.
Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes)
containing the encrypted bytes of the... |
def decrypt_cbc(self, data, init_vector):
S1, S2, S3, S4 = self.S
P = self.P
u4_1_pack = self._u4_1_pack
u1_4_unpack = self._u1_4_unpack
decrypt = self._decrypt
u4_2_pack = self._u4_2_pack
try:
prev_cipher_L, prev_cipher_R = self._u4_2_unpack(init_vector)
except... | Return an iterator that decrypts `data` using the Cipher-Block Chaining
(CBC) mode of operation.
CBC mode can only operate on `data` that is a multiple of the block-size
in length.
Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes)
containing the decrypted bytes of the... |
def encrypt_pcbc(self, data, init_vector):
S1, S2, S3, S4 = self.S
P = self.P
u4_1_pack = self._u4_1_pack
u1_4_unpack = self._u1_4_unpack
encrypt = self._encrypt
u4_2_pack = self._u4_2_pack
try:
init_L, init_R = self._u4_2_unpack(init_vector)
except struct_error... | Return an iterator that encrypts `data` using the Propagating Cipher-Block
Chaining (PCBC) mode of operation.
PCBC mode can only operate on `data` that is a multiple of the block-size
in length.
Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes)
containing the encrypte... |
def convert(self, im):
_im = im
if self.image_property:
_im = self.image_property.convert(im)
return _im | Please override this method if you want to resize/grascale the image. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.