text stringlengths 81 112k |
|---|
Helper to decode a request field into unicode based on charsets encoding.
Args:
request: the HttpRequest object.
field_name: the field expected in the request.POST
Kwargs:
default: if passed in then field is optional and default is used if not
found; if None, then assume fi... |
Takes RFC-compliant email addresses in both terse (email only)
and verbose (name + email) forms and returns a list of
email address strings
(TODO: breaking change that returns a tuple of (name, email) per string)
def _get_addresses(self, address_data, retain_name=False):
"""
Ta... |
Parse incoming request and return an email instance.
Args:
request: an HttpRequest object, containing the forwarded email, as
per the SendGrid specification for inbound emails.
Returns:
an EmailMultiAlternatives instance, containing the parsed contents
... |
Parse incoming request and return an email instance.
Mailgun does a lot of the heavy lifting at their end - requests
come in from them UTF-8 encoded, and with the message reply and
signature stripped out for you.
Args:
request: an HttpRequest object, containing the forwarde... |
Returns an iterator of objects
in the form ["Name <address@example.com", ...]
from the array [["address@example.com", "Name"]]
def _get_recipients(self, array):
"""Returns an iterator of objects
in the form ["Name <address@example.com", ...]
from the array [["address... |
Parse incoming request and return an email instance.
Args:
request: an HttpRequest object, containing a list of forwarded emails, as
per Mandrill specification for inbound emails.
Returns:
a list of EmailMultiAlternatives instances
def parse(self, request):
... |
Helper function to dump out debug info.
def _log_request(request):
"""Helper function to dump out debug info."""
logger.debug("Inbound email received")
for k, v in list(request.POST.items()):
logger.debug("- POST['%s']='%s'" % (k, v))
for n, f in list(request.FILES.items()):
logger.de... |
Receives inbound email from SendGrid.
This view receives the email from SendGrid, parses the contents, logs
the message and the fires the inbound_email signal.
def receive_inbound_email(request):
"""Receives inbound email from SendGrid.
This view receives the email from SendGrid, parses the contents,... |
Return reference to the configured backed class.
def get_backend_class():
"""Return reference to the configured backed class."""
# this will (intentionally) blow up if the setting does not exist
assert hasattr(settings, 'INBOUND_EMAIL_PARSER')
assert getattr(settings, 'INBOUND_EMAIL_PARSER') is not Non... |
For list, values, returns the insert position for item x and whether the item already exists in the list. This
allows one function call to return either the index to overwrite an existing value in the list, or the index to
insert a new item in the list and keep the list in sorted order.
:param values: list... |
For list, values, returns the index location of element x. If x does not exist will raise an error.
:param values: list
:param x: item
:return: integer index
def sorted_index(values, x):
"""
For list, values, returns the index location of element x. If x does not exist will raise an error.
:p... |
Sorts a list but returns the order of the index values of the list for the sort and not the values themselves.
For example is the list provided is ['b', 'a', 'c'] then the result will be [2, 1, 3]
:param list_to_sort: list to sort
:param key: if not None then a function of one argument that is used to extr... |
Generate the diagrams using Dia.
def runDia(diagram):
"""Generate the diagrams using Dia."""
ifname = '{}.dia'.format(diagram)
ofname = '{}.png'.format(diagram)
cmd = 'dia -t png-libart -e {} {}'.format(ofname, ifname)
print(' {}'.format(cmd))
subprocess.call(cmd, shell=True)
return True |
Create *num_workers* worker objects with *input_tube* and
an iterable of *output_tubes*. The worker reads a task from *input_tube*
and writes the result to *output_tubes*.
def init2(
self,
input_tube, # Read task from the input tube.
output_tubes, # Send result on all... |
Create, assemble and start workers.
Workers are created of class *cls*, initialized with *args*, and given
task/result communication channels *input_tube* and *output_tubes*.
The number of workers created is according to *size* parameter.
*do_stop_task* indicates whether doTask() will be... |
Link the worker to the given next worker object,
connecting the two workers with communication tubes.
def _link(self, next_worker, next_is_first=False):
"""Link the worker to the given next worker object,
connecting the two workers with communication tubes."""
lock = multiprocessing.... |
Register the *result* by putting it on all the output tubes.
def putResult(self, result):
"""Register the *result* by putting it on all the output tubes."""
self._lock_prev_output.acquire()
for tube in self._tubes_result_output:
tube.put((result, 0))
self._lock_next_output.r... |
Create *num_workers* worker objects with *input_tube* and
an iterable of *output_tubes*. The worker reads a task from *input_tube*
and writes the result to *output_tubes*.
def init2(
self,
input_tube, # Read task from the input tube.
output_tubes, # Send result on all... |
Create, assemble and start workers.
Workers are created of class *cls*, initialized with *args*, and given
task/result communication channels *input_tube* and *output_tubes*.
The number of workers created is according to *size* parameter.
*do_stop_task* indicates whether doTask() will be... |
Print the contents of the Series. This method uses the tabulate function from the tabulate package. Use the
kwargs to pass along any arguments to the tabulate function.
:param index: If True then include the indexes as a column in the output, if False ignore the index
:param kwargs: Parameters ... |
Given indexes will return a sub-set of the Series. This method will direct to the specific methods
based on what types are passed in for the indexes. The type of the return is determined by the
types of the parameters.
:param indexes: index value, list of index values, or a list of booleans.
... |
For a single index and return the value
:param index: index value
:return: value
def get_cell(self, index):
"""
For a single index and return the value
:param index: index value
:return: value
"""
i = sorted_index(self._index, index) if self._sort else ... |
For a list of indexes return the values of the indexes in that column.
:param indexes: either a list of index values or a list of booleans with same length as all indexes
:param as_list: if True return a list, if False return Series
:return: Series if as_list if False, a list if as_list is True... |
For an index location return a dict of the index and value. This is optimized for speed because
it does not need to lookup the index location with a search. Also can accept relative indexing from the end of
the SEries in standard python notation [-3, -2, -1]
:param location: index location in s... |
For list of locations return a Series or list of the values.
:param locations: list of index locations
:param as_list: True to return a list of values
:return: Series or list
def get_locations(self, locations, as_list=False):
"""
For list of locations return a Series or list of... |
For sorted Series will return either a Series or list of all of the rows where the index is greater than
or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the
start or stop index is None then will include from the first or last element, similar to st... |
Returns a dict where the keys are the data and index names and the values are list of the data and index.
:param index: If True then include the index in the dict with the index_name as the key
:param ordered: If True then return an OrderedDict() to preserve the order of the columns in the Series
... |
Return a Series of the first N rows
:param rows: number of rows
:return: Series
def head(self, rows):
"""
Return a Series of the first N rows
:param rows: number of rows
:return: Series
"""
rows_bool = [True] * min(rows, len(self._index))
rows_b... |
Finds the elements in the index that match the compare parameter and returns either a list of the values that
match, of a boolean list the length of the index with True to each index that matches. If the indexes are
tuples then the compare is a tuple where None in any field of the tuple will be treated ... |
Math helper method. Given a column and optional indexes will return a list of booleans on the equality of the
value for that index in the DataFrame to the value parameter.
:param indexes: list of index values or list of booleans. If a list of booleans then the list must be the same\
length as t... |
Pad the data in Series with [None] to ensure that data is the same length as index
:param index_len: length of index to extend data to
:return: nothing
def _pad_data(self, index_len):
"""
Pad the data in Series with [None] to ensure that data is the same length as index
:param... |
Sort the Series by the index. The sort modifies the Series inplace
:return: nothing
def sort_index(self):
"""
Sort the Series by the index. The sort modifies the Series inplace
:return: nothing
"""
sort = sorted_list_indexes(self._index)
# sort index
se... |
Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below
methods based on what types are passed in for the indexes. If the indexes contains values not in the Series
then new rows or columns will be added.
:param indexes: indexes value, list o... |
Add a new row to the Series
:param index: index of the new row
:return: nothing
def _add_row(self, index):
"""
Add a new row to the Series
:param index: index of the new row
:return: nothing
"""
self._index.append(index)
self._data.append(None) |
Insert a new row in the Series.
:param i: index location to insert
:param index: index value to insert into the index list
:return: nothing
def _insert_row(self, i, index):
"""
Insert a new row in the Series.
:param i: index location to insert
:param index: ind... |
Given a list of indexes, find all the indexes that are not currently in the Series and make a new row for
that index by appending to the Series. This does not maintain sorted order for the index.
:param indexes: list of indexes
:return: nothing
def _add_missing_rows(self, indexes):
"""... |
Given a list of indexes, find all the indexes that are not currently in the Series and make a new row for
that index, inserting into the index. This requires the Series to be sorted=True
:param indexes: list of indexes
:return: nothing
def _insert_missing_rows(self, indexes):
"""
... |
Sets the value of a single cell. If the index is not in the current index then a new index will be created.
:param index: index value
:param value: value to set
:return: nothing
def set_cell(self, index, value):
"""
Sets the value of a single cell. If the index is not in the cu... |
Set rows to a single value or list of values. If any of the index values are not in the current indexes
then a new row will be created.
:param index: list of index values or list of booleans. If a list of booleans then the list must be the same\
length as the Series
:param values: eithe... |
For a list of locations set the values.
:param locations: list of index locations
:param values: list of values or a single value
:return: nothing
def set_locations(self, locations, values):
"""
For a list of locations set the values.
:param locations: list of index lo... |
Appends a row of value to the end of the data. Be very careful with this function as for sorted Series it will
not enforce sort order. Use this only for speed when needed, be careful.
:param index: index
:param value: value
:return: nothing
def append_row(self, index, value):
... |
Appends values to the end of the data. Be very careful with this function as for sort DataFrames it will not
enforce sort order. Use this only for speed when needed, be careful.
:param indexes: list of indexes to append
:param values: list of values to append
:return: nothing
def appe... |
Delete rows from the DataFrame
:param indexes: either a list of values or list of booleans for the rows to delete
:return: nothing
def delete(self, indexes):
"""
Delete rows from the DataFrame
:param indexes: either a list of values or list of booleans for the rows to delete
... |
Resets the index of the Series to simple integer list and the index name to 'index'.
:return: nothing
def reset_index(self):
"""
Resets the index of the Series to simple integer list and the index name to 'index'.
:return: nothing
"""
self.index = list(range(self.__len... |
Wrapper function for get. It will return a list, no index. If the indexes are integers it will be assumed
that they are locations unless int_as_index = True. If the indexes are locations then they will be rotated to
the left by offset number of locations.
:param indexes: integer location, sing... |
Creates and return a Series from a DataFrame and specific column
:param dataframe: raccoon DataFrame
:param column: column name
:param offset: offset value must be provided as there is no equivalent for a DataFrame
:return: Series
def from_dataframe(cls, dataframe, column, offset=0):
... |
Creates and return a Series from a Series
:param series: raccoon Series
:param offset: offset value must be provided as there is no equivalent for a DataFrame
:return: Series
def from_series(cls, series, offset=0):
"""
Creates and return a Series from a Series
:param s... |
Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it.
def get(self, timeout=None):
"""Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it."""
if timeo... |
Retrieve results from all the output tubes.
def get(self, timeout=None):
"""Retrieve results from all the output tubes."""
valid = False
result = None
for tube in self._output_tubes:
if timeout:
valid, result = tube.get(timeout)
if valid:
... |
Link to the given downstream stage *next_stage*
by adding its input tube to the list of this stage's output tubes.
Return this stage.
def link(self, next_stage):
"""Link to the given downstream stage *next_stage*
by adding its input tube to the list of this stage's output tubes.
... |
Return the downstream leaf stages of this stage.
def getLeaves(self):
"""Return the downstream leaf stages of this stage."""
result = list()
if not self._next_stages:
result.append(self)
else:
for stage in self._next_stages:
leaves = stage.getLeav... |
Create and start up the internal workers.
def build(self):
"""Create and start up the internal workers."""
# If there's no output tube, it means that this stage
# is at the end of a fork (hasn't been linked to any stage downstream).
# Therefore, create one output tube.
if not s... |
Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it.
def get(self, timeout=None):
"""Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it."""
if timeo... |
Given a list of column names will sort the DataFrame columns to match the given order
:param columns_list: list of column names. Must include all column names
:return: nothing
def _sort_columns(self, columns_list):
"""
Given a list of column names will sort the DataFrame columns to mat... |
Pad the data in DataFrame with [None} to ensure that all columns have the same length.
:param max_len: If provided will extend all columns to this length, if not then will use the longest column
:return: nothing
def _pad_data(self, max_len=None):
"""
Pad the data in DataFrame with [Non... |
Given indexes and columns will return a sub-set of the DataFrame. This method will direct to the below methods
based on what types are passed in for the indexes and columns. The type of the return is determined by the
types of the parameters.
:param indexes: index value, list of index values, o... |
For a single index and column value return the value of the cell
:param index: index value
:param column: column name
:return: value
def get_cell(self, index, column):
"""
For a single index and column value return the value of the cell
:param index: index value
... |
For a list of indexes and a single column name return the values of the indexes in that column.
:param indexes: either a list of index values or a list of booleans with same length as all indexes
:param column: single column name
:param as_list: if True return a list, if False return DataFrame
... |
For a single index and list of column names return a DataFrame of the values in that index as either a dict
or a DataFrame
:param index: single index value
:param columns: list of column names
:param as_dict: if True then return the result as a dictionary
:return: DataFrame or d... |
Shortcut method to retrieve a single column all rows. Since this is a common use case this method will be
faster than the more general method.
:param column: single column name
:param as_list: if True return a list, if False return DataFrame
:return: DataFrame is as_list if False, a lis... |
For a list of indexes and list of columns return a DataFrame of the values.
:param indexes: either a list of index values or a list of booleans with same length as all indexes
:param columns: list of column names
:return: DataFrame
def get_matrix(self, indexes, columns):
"""
Fo... |
For an index location and either (1) list of columns return a DataFrame or dictionary of the values or
(2) single column name and return the value of that cell. This is optimized for speed because it does not need
to lookup the index location with a search. Also can accept relative indexing from the end... |
For list of locations and list of columns return a DataFrame of the values.
:param locations: list of index locations
:param columns: list of column names
:param kwargs: will pass along these parameters to the get() method
:return: DataFrame
def get_locations(self, locations, columns=N... |
For sorted DataFrames will return either a DataFrame or dict of all of the rows where the index is greater than
or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the
start or stop index is None then will include from the first or last element, simila... |
Insert a new row in the DataFrame.
:param i: index location to insert
:param index: index value to insert into the index list
:return: nothing
def _insert_row(self, i, index):
"""
Insert a new row in the DataFrame.
:param i: index location to insert
:param inde... |
Add a new row to the DataFrame
:param index: index of the new row
:return: nothing
def _add_row(self, index):
"""
Add a new row to the DataFrame
:param index: index of the new row
:return: nothing
"""
self._index.append(index)
for c, _ in enumer... |
Add a new column to the DataFrame
:param column: column name
:return: nothing
def _add_column(self, column):
"""
Add a new column to the DataFrame
:param column: column name
:return: nothing
"""
self._columns.append(column)
if self._blist:
... |
Given indexes and columns will set a sub-set of the DataFrame to the values provided. This method will direct
to the below methods based on what types are passed in for the indexes and columns. If the indexes or columns
contains values not in the DataFrame then new rows or columns will be added.
... |
Sets the value of a single cell. If the index and/or column is not in the current index/columns then a new
index and/or column will be created.
:param index: index value
:param column: column name
:param value: value to set
:return: nothing
def set_cell(self, index, column, val... |
Sets the values of the columns in a single row.
:param index: index value
:param values: dict with the keys as the column names and the values what to set that column to
:return: nothing
def set_row(self, index, values):
"""
Sets the values of the columns in a single row.
... |
Set a column to a single value or list of values. If any of the index values are not in the current indexes
then a new row will be created.
:param index: list of index values or list of booleans. If a list of booleans then the list must be the same\
length as the DataFrame
:param column... |
Sets the column values, as given by the keys of the values dict, for the row at location to the values of the
values dict. If missing_to_none is False then columns not in the values dict will be left unchanged, if it is
True then they are set to None. This method does not add new columns and raises an e... |
Appends a row of values to the end of the data. If there are new columns in the values and new_cols is True
they will be added. Be very careful with this function as for sort DataFrames it will not enforce sort order.
Use this only for speed when needed, be careful.
:param index: value of the ... |
Appends rows of values to the end of the data. If there are new columns in the values and new_cols is True
they will be added. Be very careful with this function as for sort DataFrames it will not enforce sort order.
Use this only for speed when needed, be careful.
:param indexes: list of inde... |
Returns a dict where the keys are the column names and the values are lists of the values for that column.
:param index: If True then include the index in the dict with the index_name as the key
:param ordered: If True then return an OrderedDict() to preserve the order of the columns in the DataFrame
... |
Returns a JSON of the entire DataFrame that can be reconstructed back with raccoon.from_json(input). Any object
that cannot be serialized will be replaced with the representation of the object using repr(). In that instance
the DataFrame will have a string representation in place of the object and will ... |
Renames the columns
:param rename_dict: dict where the keys are the current column names and the values are the new names
:return: nothing
def rename_columns(self, rename_dict):
"""
Renames the columns
:param rename_dict: dict where the keys are the current column names and th... |
Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all
information, and at the same time it keeps the container lists for the columns and index so if there is another
object that references this DataFrame, like a ViewSeries, the reference remains in t... |
Delete columns from the DataFrame
:param columns: list of columns to delete
:return: nothing
def delete_columns(self, columns):
"""
Delete columns from the DataFrame
:param columns: list of columns to delete
:return: nothing
"""
columns = [columns] if n... |
Sort the DataFrame by the index. The sort modifies the DataFrame inplace
:return: nothing
def sort_index(self):
"""
Sort the DataFrame by the index. The sort modifies the DataFrame inplace
:return: nothing
"""
sort = sorted_list_indexes(self._index)
# sort inde... |
Sort the DataFrame by one of the columns. The sort modifies the DataFrame inplace. The key and reverse
parameters have the same meaning as for the built-in sort() function.
:param column: column name to use for the sort
:param key: if not None then a function of one argument that is used to ext... |
Validate the integrity of the DataFrame. This checks that the indexes, column names and internal data are not
corrupted. Will raise an error if there is a problem.
:return: nothing
def validate_integrity(self):
"""
Validate the integrity of the DataFrame. This checks that the indexes, ... |
Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current
DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the
current indexes or will raise an error.
:param data_frame: DataFrame to append
... |
Math helper method that adds element-wise two columns. If indexes are not None then will only perform the math
on that sub-set of the columns.
:param left_column: first column name
:param right_column: second column name
:param indexes: list of index values or list of booleans. If a lis... |
Returns a boolean list where each elements is whether that element in the column is in the compare_list.
:param column: single column name, does not work for multiple columns
:param compare_list: list of items to compare to
:return: list of booleans
def isin(self, column, compare_list):
... |
Iterates over DataFrame rows as dictionary of the values. The index will be included.
:param index: if True include the index in the results
:return: dictionary
def iterrows(self, index=True):
"""
Iterates over DataFrame rows as dictionary of the values. The index will be included.
... |
Iterates over DataFrame rows as tuple of the values.
:param index: if True then include the index
:param name: name of the namedtuple
:return: namedtuple
def itertuples(self, index=True, name='Raccoon'):
"""
Iterates over DataFrame rows as tuple of the values.
:param i... |
Resets the index of the DataFrame to simple integer list and the index name to 'index'. If drop is True then
the existing index is dropped, if drop is False then the current index is made a column in the DataFrame with
the index name the name of the column. If the index is a tuple multi-index then each ... |
Creates and return a DataFrame from a JSON of the type created by to_json
:param json_string: JSON
:return: DataFrame
def from_json(cls, json_string):
"""
Creates and return a DataFrame from a JSON of the type created by to_json
:param json_string: JSON
:return: DataFr... |
Filter input *task* to pipelines -- make sure each one has no more
than *max_tasks* tasks in it. Return a tuple
(*task*, *results*)
where *task* is the given task, and *results* is
a list of latest retrieved results from pipelines.
def doTask(self, task):
"""Filter input *tas... |
For unit testing equality of two DataFrames.
:param left: first DataFrame
:param right: second DataFrame
:param data_function: if provided will use this function to assert compare the df.data
:param data_args: arguments to pass to the data_function
:return: nothing
def assert_frame_equal(left, rig... |
For unit testing equality of two Series.
:param left: first Series
:param right: second Series
:param data_function: if provided will use this function to assert compare the df.data
:param data_args: arguments to pass to the data_function
:return: nothing
def assert_series_equal(left, right, data_... |
Return result from the pipeline.
def get(self, timeout=None):
"""Return result from the pipeline."""
result = None
for stage in self._output_stages:
result = stage.get(timeout)
return result |
Run the CLI.
def main():
"""
Run the CLI.
"""
parser = argparse.ArgumentParser(
description='Search artists, lyrics, and songs!'
)
parser.add_argument(
'artist',
help='Specify an artist name (Default: Taylor Swift)',
default='Taylor Swift',
nargs='?',
... |
Load the lyrics from MetroLyrics.
def load(self):
"""Load the lyrics from MetroLyrics."""
page = requests.get(self._url)
# Forces utf-8 to prevent character mangling
page.encoding = 'utf-8'
tree = html.fromstring(page.text)
lyric_div = tree.get_element_by_id('lyrics-bod... |
Load the list of songs.
Note that this only loads a list of songs that this artist was the main
artist of. If they were only featured in the song, that song won't be
listed here. There is a list on the artist page for that, I just
haven't added any parsing code for that, since I don't... |
Return the distance between two points on the surface of the Earth.
Parameters
----------
p0 : point-like (or array of point-like) [longitude, latitude] objects
p1 : point-like (or array of point-like) [longitude, latitude] objects
deg : bool, optional (default True)
indicates if p0 and p1 ... |
Compute the initial bearing along the great circle from p0 to p1
NB: The angle returned by course() is not the traditional definition of
bearing. It is definted such that 0 degrees to due East increasing
counter-clockwise such that 90 degrees is due North. To obtain the bearing
(0 degrees is due North ... |
Given an initial point and angle, move distance d along the surface
Parameters
----------
p0 : point-like (or array of point-like) [lon, lat] objects
angle : float (or array of float)
bearing. Note that by default, 0 degrees is due East increasing
clockwise so that 90 degrees is due No... |
Validate request signature.
:param signature: A string signature parameter sent by weixin.
:param timestamp: A int timestamp parameter sent by weixin.
:param nonce: A int nonce parameter sent by weixin.
def validate(self, signature, timestamp, nonce):
"""Validate request signature.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.