text stringlengths 81 112k |
|---|
Calculates the expected lifecycle position the subscription in
subscription_ids, and creates a BehindSubscription entry for them.
Args:
subscription_id (str): ID of subscription to calculate lifecycle for
def calculate_subscription_lifecycle(subscription_id):
"""
Calculates the expected lifecy... |
Finds any subscriptions that are behind according to where they should be,
and creates a BehindSubscription entry for them.
def find_behind_subscriptions():
"""
Finds any subscriptions that are behind according to where they should be,
and creates a BehindSubscription entry for them.
"""
subscr... |
Sends all the subscriptions for the specified schedule
def send(self, request, pk=None):
"""
Sends all the subscriptions for the specified schedule
"""
schedule = self.get_object()
queue_subscription_send.delay(str(schedule.id))
return Response({}, status=status.HTTP_20... |
Return the configured value for the given key name, or `default` if
no value is available or key is invalid.
def get(self, key: Any, default: Any=None) -> Any:
'''Return the configured value for the given key name, or `default` if
no value is available or key is invalid.'''
return self... |
Return the task-specific configuration.
def task_config(self, task: Task) -> Any:
'''Return the task-specific configuration.'''
return self.get(task.__class__.__name__) |
Load configuration in JSON format from either a file or
a raw data string.
async def init(self) -> None:
'''Load configuration in JSON format from either a file or
a raw data string.'''
if self.data:
return
if self.json_data:
try:
self.d... |
Execute the task inside the asyncio event loop after `DELAY`
seconds. Track the time it takes to run, and log when it starts/stops.
If/when `reset()` is called, reset the wait time to `DELAY` seconds.
async def run_task(self) -> None:
'''Execute the task inside the asyncio event loop after `DE... |
Reset task execution to `DELAY` seconds from now.
def reset(self) -> None:
'''Reset task execution to `DELAY` seconds from now.'''
Log.debug('resetting timer task %s')
self.target = self.time() + self.DELAY |
A view decorator which blocks access for requests coming through the load balancer.
def internal_only(view_func):
"""
A view decorator which blocks access for requests coming through the load balancer.
"""
@functools.wraps(view_func)
def wrapper(request, *args, **kwargs):
forwards = reques... |
Validates subscription data before creating Outbound message
def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Outbound message
"""
schedule_disable.delay(kwargs["subscription_id"])
return Response({"accepted": True}, status=201) |
Validates subscription data before creating Outbound message
def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Outbound message
"""
# Look up subscriber
subscription_id = kwargs["subscription_id"]
if Subscription.objects.filter(id=subscrip... |
Validates subscription data before creating Subscription message
def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Subscription message
"""
# Ensure that we check for the 'data' key in the request object before
# attempting to reference it
... |
Starts a celery task that looks through active subscriptions to find
and subscriptions that are behind where they should be, and adds a
BehindSubscription for them.
def find_behind_subscriptions(self, request):
"""
Starts a celery task that looks through active subscriptions to find
... |
Read-Eval-Print-Loop for reading the query, printing it and its parse tree.
Exit the loop either with an interrupt or "quit".
def repl():
"""Read-Eval-Print-Loop for reading the query, printing it and its parse tree.
Exit the loop either with an interrupt or "quit".
"""
while True:
try:
... |
Initialize the queue and spawn extra worker tasks if this if the
first task. Then wait for work items to enter the task queue, and
execute the `run()` method with the current work item.
async def run_task(self) -> None:
'''Initialize the queue and spawn extra worker tasks if this if the
... |
Fires off the celery task to ensure that this schedule is in the scheduler
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the Schedule that we want to sync
def schedule_saved(sender, instance, **kwargs):
"""
Fires off the ce... |
Fires off the celery task to ensure that this schedule is deactivated
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the schedule that we want to deactivate
def schedule_deleted(sender, instance, **kwargs):
"""
Fires off the... |
Execute the task inside the asyncio event loop. Track the time it
takes to run, and log when it starts/stops. After `INTERVAL` seconds,
if/once the task has finished running, run it again until `stop()`
is called.
async def run_task(self) -> None:
'''Execute the task inside the asynci... |
construct a grouping object on the given keys, optionally performing the given reduction on the given values
Parameters
----------
keys : indexable object
keys to group by
values : array_like, optional
sequence of values, of the same length as keys
if a reduction function is pro... |
Group iterable into iterables, in the order of the keys
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
Memory consumption depends... |
Group iterable into iterables, without regard for the ordering of self.index.unique
key-group tuples are yielded as soon as they are complete
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
... |
Group sequence into iterables
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
This is the preferred method if values has random ac... |
Group ndarray into ndarray by means of reshaping
Parameters
----------
values : ndarray_like, [index.size, ...]
Returns
-------
ndarray, [groups, group_size, ...]
values grouped by key
Raises
------
AssertionError
This op... |
Group values as a list of arrays, or a jagged-array
Parameters
----------
values : ndarray, [keys, ...]
Returns
-------
list of length self.groups of ndarray, [key_count, ...]
def split_array_as_list(self, values):
"""Group values as a list of arrays, or a jagg... |
Reduce the values over identical key groups, using the given ufunc
reduction is over the first axis, which should have elements corresponding to the keys
all other axes are treated indepenently for the sake of this reduction
Parameters
----------
values : ndarray, [keys, ...]
... |
compute the sum over each group
Parameters
----------
values : array_like, [keys, ...]
values to sum per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarray, [group... |
compute the product over each group
Parameters
----------
values : array_like, [keys, ...]
values to multiply per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarra... |
compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
weights : ndarray, [keys, ...], optional
weight to use for e... |
compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
... |
standard deviation over each group
Parameters
----------
values : array_like, [keys, ...]
values to take standard deviation of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
... |
compute the median value over each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the median of per group
axis : int, optional
alternative reduction axis for values
average : bool, optional
when average is true... |
compute the mode within each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the mode of per group
weights : array_like, [keys], float, optional
optional weight associated with each entry in values
Returns
-------
... |
return the minimum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take minimum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
... |
return the maximum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take maximum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
... |
return values at first occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the first value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: n... |
return values at last occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the last value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: nda... |
compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ... |
compute if all items evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique:... |
return the index into values corresponding to the minimum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmin of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmin : ndarray, ... |
return the index into values corresponding to the maximum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmax of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmax : ndarray, ... |
casting rules for a keys object to an index object
the preferred semantics is that keys is a sequence of key objects,
except when keys is an instance of tuple,
in which case the zipped elements of the tuple are the key objects
the axis keyword specifies the axis which enumerates the keys
if axis i... |
return index array that maps unique values back to original space. unique[inverse]==keys
def inverse(self):
"""return index array that maps unique values back to original space. unique[inverse]==keys"""
inv = np.empty(self.size, np.int)
inv[self.sorter] = self.sorted_group_rank_per_key
... |
how high in sorted list each key is. inverse permutation of sorter, such that sorted[rank]==keys
def rank(self):
"""how high in sorted list each key is. inverse permutation of sorter, such that sorted[rank]==keys"""
r = np.empty(self.size, np.int)
r[self.sorter] = np.arange(self.size)
r... |
returns a tuple of unique key columns
def unique(self):
"""returns a tuple of unique key columns"""
return tuple(
(array_as_typed(s, k.dtype, k.shape) if k.ndim>1 else s)[self.start]
for s, k in zip(self.sorted, self._keys)) |
pack a sequence of columns into a recarray
Parameters
----------
columns : sequence of key objects
Returns
-------
data : recarray
recarray containing the input columns as struct fields
def as_struct_array(*columns):
"""pack a sequence of columns into a recarray
Parameters
... |
cast the given axis of an array to a void object
if the axis to be cast is contiguous, a view is returned, otherwise a copy is made
this is useful for efficiently sorting by the content of an axis, for instance
Parameters
----------
arr : ndarray
array to view as void object type
axis :... |
cast an array of void objects to a typed axis
Parameters
----------
arr : ndarray, [ndim], void
array of type np.void
dtype : numpy dtype object
the output dtype to cast the input array to
axis : int
position to insert the newly formed axis into
Returns
-------
... |
count the number of times each key occurs in the input set
Arguments
---------
keys : indexable object
Returns
-------
unique : ndarray, [groups, ...]
unique keys
count : ndarray, [groups], int
the number of times each key occurs in the input set
Notes
-----
Ca... |
count the number of times each key occurs in the input set
Arguments
---------
keys : tuple of indexable objects, each having the same number of items
Returns
-------
unique : tuple of ndarray, [groups, ...]
unique keys for each input item
they form the axes labels of the table... |
Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10)
def binning(keys, start, end, count, axes=None):
"""Perform binning over the given axes of the keys
Parameters
---... |
return the multiplicity of each key, or how often it occurs in the set
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
the number of times each input item occurs in the set
def multiplicity(keys, axis=semantics.axis_default):
"""return the m... |
where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[index.rank] == keys
def rank(keys, axis=semantics.axis_... |
compute the mode, or most frequent occuring key in a set
Parameters
----------
keys : ndarray, [n_keys, ...]
input array. elements of 'keys' can have arbitrary shape or dtype
weights : ndarray, [n_keys], optional
if given, the contribution of each key to the mode is weighted by the give... |
given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib
def incidence(boundary):
"""
given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; shoul... |
Returns true if all keys are unique
def all_unique(keys, axis=semantics.axis_default):
"""Returns true if all keys are unique"""
index = as_index(keys, axis)
return index.groups == index.size |
returns true if any of the keys is unique
def any_unique(keys, axis=semantics.axis_default):
"""returns true if any of the keys is unique"""
index = as_index(keys, axis)
return np.any(index.count == 1) |
returns true of all keys are equal
def all_equal(keys, axis=semantics.axis_default):
"""returns true of all keys are equal"""
index = as_index(keys, axis)
return index.groups == 1 |
returns true if all keys have equal multiplicity
def is_uniform(keys, axis=semantics.axis_default):
"""returns true if all keys have equal multiplicity"""
index = as_index(keys, axis)
return index.uniform |
Returns
-------
Tuple of inverse indices
def get_inverses(self, keys):
"""
Returns
-------
Tuple of inverse indices
"""
return tuple([as_index(k, axis=0).inverse for k in keys]) |
Place each entry in a table, while asserting that each entry occurs once
def unique(self, values):
"""Place each entry in a table, while asserting that each entry occurs once"""
_, count = self.count()
if not np.array_equiv(count, 1):
raise ValueError("Not every entry in the table i... |
compute the set of unique keys
Parameters
----------
keys : indexable key object
keys object to find unique keys within
axis : int
if keys is a multi-dimensional array, the axis to regard as the sequence of key objects
return_index : bool
if True, return indexes such that ke... |
Returns bool for each element of `that`, indicating if it is contained in `this`
Parameters
----------
this : indexable key sequence
sequence of items to test against
that : indexable key sequence
sequence of items to test for
Returns
-------
ndarray, [that.size], bool
... |
Returns bool for each element of `this`, indicating if it is present in `that`
Parameters
----------
this : indexable key sequence
sequence of items to test for
that : indexable key sequence
sequence of items to test against
Returns
-------
ndarray, [that.size], bool
... |
Find indices such that this[indices] == that
If multiple indices satisfy this condition, the first index found is returned
Parameters
----------
this : indexable object
items to search in
that : indexable object
items to search for
axis : int, optional
axis to operate on... |
Given an input array, remap its entries corresponding to 'keys' to 'values'
equivalent of output = [map.get(i, default=i) for i in input],
if map were a dictionary of corresponding keys and values
Parameters
----------
input : ndarray, [...]
values to perform replacements in
keys : ndar... |
upcasts a sequence of indexable objects to Index objets according to the given kwargs
Parameters
----------
sets : iterable of indexable objects
axis : int, optional
axis to view as item sequence
assume_unique : bool, optional
if we should assume the items sequence does not contain ... |
concatenate indexable objects.
Parameters
----------
sets : iterable of indexable objects
Returns
-------
indexable object
handles both arrays and tuples of arrays
def _set_concatenate(sets):
"""concatenate indexable objects.
Parameters
----------
sets : iterable of inde... |
return the elements which occur n times over the sequence of sets
Parameters
----------
sets : iterable of indexable objects
n : int
number of sets the element should occur in
Returns
-------
indexable
indexable with all elements that occured in n of the sets
Notes
... |
all unique items which occur in any one of the sets
Parameters
----------
sets : tuple of indexable objects
Returns
-------
union of all items in all sets
def union(*sets, **kwargs):
"""all unique items which occur in any one of the sets
Parameters
----------
sets : tuple of ... |
subtracts all tail sets from the head set
Parameters
----------
sets : tuple of indexable objects
first set is the head, from which we subtract
other items form the tail, which are subtracted from head
Returns
-------
items which are in the head but not in any of the tail sets
... |
Generate a random id for div chart.
def _generate_div_id_chart(prefix="chart_id", digits=8):
"""Generate a random id for div chart.
"""
choices = (random.randrange(0, 52) for _ in range(digits))
return prefix + "".join((string.ascii_letters[x] for x in choices)) |
Display you DataFrame with Highcharts.
df: DataFrame
chart_type: str
'default' or 'stock'
render_to: str
div id for plotting your data
def display_charts(df, chart_type="default", render_to=None, **kwargs):
"""Display you DataFrame with Highcharts.
df: DataFrame
chart_type: st... |
Replace each 'data' key in the list stored under 'series' by "[...]".
Use to not store and display the series data when you just want display and
modify the Highcharts parameters.
data: dict
Serialized DataFrame in a dict for Highcharts
Returns: a dict with filtered values
See also `core... |
Pretty print your Highcharts params (into a JSON).
data: dict
Serialized DataFrame in a dict for Highcharts
def pretty_params(data, indent=2):
"""Pretty print your Highcharts params (into a JSON).
data: dict
Serialized DataFrame in a dict for Highcharts
"""
data_to_print = _series... |
Filter to get the additional params needed for polling
def get_additional_params(self, **params):
"""
Filter to get the additional params needed for polling
"""
# TODO: Move these params to their own vertical if needed.
polling_params = [
'locationschema',
... |
Get all results, no filtering, etc. by creating and polling the
session.
def get_result(self, errors=GRACEFUL, **params):
"""
Get all results, no filtering, etc. by creating and polling the
session.
"""
additional_params = self.get_additional_params(**params)
ret... |
Reusable method for performing requests.
:param service_url - URL to request
:param method - request method, default is 'get'
:param headers - request headers
:param data - post data
:param callback - callback to be applied to response,
default callback... |
Get the list of markets
http://business.skyscanner.net/portal/en-GB/Documentation/Markets
def get_markets(self, market):
"""
Get the list of markets
http://business.skyscanner.net/portal/en-GB/Documentation/Markets
"""
url = "{url}/{market}".format(url=self.MARKET_SERVIC... |
Location Autosuggest Services
Doc URLs:
http://business.skyscanner.net/portal/en-GB/
Documentation/Autosuggest
http://business.skyscanner.net/portal/en-GB/
Documentation/CarHireAutoSuggest
http://business.skyscanner.net/portal/en-GB/
Doc... |
Poll the URL
:param poll_url - URL to poll,
should be returned by 'create_session' call
:param initial_delay - specifies how many seconds to wait before
the first poll
:param delay - specifies how many seconds to wait between the polls
... |
Construct params list in order of given keys.
def _construct_params(params, required_keys, opt_keys=None):
"""
Construct params list in order of given keys.
"""
try:
params_list = [params.pop(key) for key in required_keys]
except KeyError as e:
raise Miss... |
Create the session
date format: YYYY-mm-dd
location: ISO code
def create_session(self, **params):
"""
Create the session
date format: YYYY-mm-dd
location: ISO code
"""
return self.make_request(self.PRICING_SESSION_URL,
met... |
Request for booking details
URL Format:
{API_HOST}/apiservices/pricing/v1.0/{session key}/booking
?apiKey={apiKey}
def request_booking_details(self, poll_url, **params):
"""
Request for booking details
URL Format:
{API_HOST}/apiservices/pricing/v1.0/{... |
{API_HOST}/apiservices/browsedates/v1.0/{market}/{currency}/{locale}/
{originPlace}/{destinationPlace}/
{outboundPartialDate}/{inboundPartialDate}
?apiKey={apiKey}
def get_cheapest_price_by_date(self, **params):
"""
{API_HOST}/apiservices/browsedates/v1.0/{market}/{currency}/{lo... |
{API_HOST}/apiservices/browseroutes/v1.0/{market}/{currency}/{locale}/
{originPlace}/{destinationPlace}/
{outboundPartialDate}/{inboundPartialDate}
?apiKey={apiKey}
def get_cheapest_price_by_route(self, **params):
"""
{API_HOST}/apiservices/browseroutes/v1.0/{market}/{currency}/... |
{API_HOST}/apiservices/browsequotes/v1.0/{market}/{currency}/{locale}/
{originPlace}/{destinationPlace}/
{outboundPartialDate}/{inboundPartialDate}
?apiKey={apiKey}
def get_cheapest_quotes(self, **params):
"""
{API_HOST}/apiservices/browsequotes/v1.0/{market}/{currency}/{locale}... |
{API_HOST}/apiservices/browsegrid/v1.0/{market}/{currency}/{locale}/
{originPlace}/{destinationPlace}/
{outboundPartialDate}/{inboundPartialDate}
?apiKey={apiKey}
def get_grid_prices_by_date(self, **params):
"""
{API_HOST}/apiservices/browsegrid/v1.0/{market}/{currency}/{locale}... |
Create the session
date format: YYYY-MM-DDThh:mm
location: ISO code
def create_session(self, **params):
"""
Create the session
date format: YYYY-MM-DDThh:mm
location: ISO code
"""
required_keys = ('market', 'currency', 'locale', 'pickupplace',
... |
Format keyboard /command field.
def keyboard_field(value, args=None):
"""
Format keyboard /command field.
"""
qs = QueryDict(args)
per_line = qs.get('per_line', 1)
field = qs.get("field", "slug")
command = qs.get("command")
convert = lambda element: "/" + command + " " + str(getattr(el... |
Return the `QuerySet` that will be used to look up the object.
Note that this method is called by the default implementation of
`get_object` and may not be called if `get_object` is overridden.
def get_queryset(self):
"""
Return the `QuerySet` that will be used to look up the object.
... |
Decorator for command views that checks that the chat is authenticated,
sends message with link for authenticated if necessary.
def login_required(view_func):
"""
Decorator for command views that checks that the chat is authenticated,
sends message with link for authenticated if necessary.
"""
... |
Decorator that handles X objects and partial application for pipe-utils.
def pipe_util(func):
"""
Decorator that handles X objects and partial application for pipe-utils.
"""
@wraps(func)
def pipe_util_wrapper(function, *args, **kwargs):
if isinstance(function, XObject):
functio... |
Decorator that handles automatic string formatting.
By converting a string argument to a function that does formatting on said
string.
def auto_string_formatter(func):
"""
Decorator that handles automatic string formatting.
By converting a string argument to a function that does formatting on sai... |
Decorator to handle automatic data structure creation for pipe-utils.
def data_structure_builder(func):
"""
Decorator to handle automatic data structure creation for pipe-utils.
"""
@wraps(func)
def ds_builder_wrapper(function, *args, **kwargs):
try:
function = DSBuilder(functio... |
If a condition is given as string instead of a function, it is turned
into a regex-matching function.
def regex_condition(func):
"""
If a condition is given as string instead of a function, it is turned
into a regex-matching function.
"""
@wraps(func)
def regex_condition_wrapper(condition, ... |
Sorts an incoming sequence by using the given `function` as key.
>>> range(10) > sort_by(-X)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Supports automatic data-structure creation::
users > sort_by([X.last_name, X.first_name])
There is also a shortcut for ``sort_by(X)`` called ``sort``:
>>> [4, 5, 8... |
Assumes an iterable on the input, returns an iterable with first `count`
items from the input (or possibly less, if there isn't that many).
>>> range(9000) > where(X % 100 == 0) | take_first(5) | tuple
(0, 100, 200, 300, 400)
def take_first(count):
"""
Assumes an iterable on the input, returns an ... |
Assumes an iterable on the input, returns an iterable with identical items
except for the first `count`.
>>> range(10) > drop_first(5) | tuple
(5, 6, 7, 8, 9)
def drop_first(count):
"""
Assumes an iterable on the input, returns an iterable with identical items
except for the first `count`.
... |
When `exception_class_or_tuple` occurs while executing `func`, it will
be caught and ``None`` will be returned.
>>> f = where(X > 10) | list | unless(IndexError, X[0])
>>> f([5, 8, 12, 4])
12
>>> f([1, 2, 3])
None
def unless(exception_class_or_tuple, func, *args, **kwargs):
"""
When `e... |
Groups input sequence by `function`.
Returns an iterator over a sequence of tuples where the first item is a
result of `function` and the second one a list of items matching this
result.
Ordering of the resulting iterator is undefined, but ordering of the items
in the groups is preserved.
>>>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.