text stringlengths 81 112k |
|---|
Temporarily change or set the environment variable during the execution of a function.
Args:
name: The name of the environment variable
value: A value to set for the environment variable
Returns:
The function return value.
def write(name, value):
"""Temporarily change or set the e... |
Only execute the function if the variable is set.
Args:
name: The name of the environment variable
Returns:
The function return value or `None` if the function was skipped.
def isset(name):
"""Only execute the function if the variable is set.
Args:
name: The name of the envir... |
Only execute the function if the boolean variable is set.
Args:
name: The name of the environment variable
execute_bool: The boolean value to execute the function on
default: The default value if the environment variable is not set (respects `execute_bool`)
Returns:
The functio... |
Reads the cell at position x+1 and y+1; return value
:param x: line index
:param y: coll index
:return: {header: value}
def read_cell(self, x, y):
"""
Reads the cell at position x+1 and y+1; return value
:param x: line index
:param y: coll index
:return: ... |
Writing value in the cell of x+1 and y+1 position
:param x: line index
:param y: coll index
:param value: value to be written
:return:
def write_cell(self, x, y, value):
"""
Writing value in the cell of x+1 and y+1 position
:param x: line index
:param y: ... |
Open the file; get sheets
:return:
def _open(self):
"""
Open the file; get sheets
:return:
"""
if not hasattr(self, '_file'):
self._file = self.gc.open(self.name)
self.sheet_names = self._file.worksheets() |
Read the sheet, get value the header, get number columns and rows
:return:
def _open_sheet(self):
"""
Read the sheet, get value the header, get number columns and rows
:return:
"""
if self.sheet_name and not self.header:
self._sheet = self._file.worksheet(sel... |
Makes imports
:return:
def _import(self):
"""
Makes imports
:return:
"""
import os.path
import gspread
self.path = os.path
self.gspread = gspread
self._login() |
Login with your Google account
:return:
def _login(self):
"""
Login with your Google account
:return:
"""
# TODO(dmvieira) login changed to oauth2
self.gc = self.gspread.login(self.email, self.password) |
All fields are selectable
def flags(self, index: QModelIndex):
"""All fields are selectable"""
if self.IS_EDITABLE and self.header[index.column()] in self.EDITABLE_FIELDS:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
else:
return super().flags(index)... |
Order is defined by the current state of sorting
def sort(self, section: int, order=None):
"""Order is defined by the current state of sorting"""
attr = self.header[section]
old_i, old_sort = self.sort_state
self.beginResetModel()
if section == old_i:
self.collection... |
Base implementation just pops the item from collection.
Re-implements to add global behaviour
def remove_line(self, section):
"""Base implementation just pops the item from collection.
Re-implements to add global behaviour
"""
self.beginResetModel()
self.collection.pop(s... |
Emit dataChanged signal on all cells
def _update(self):
"""Emit dataChanged signal on all cells"""
self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(
len(self.collection), len(self.header))) |
Acces shortcut
:param index: Number of row or index of cell
:return: Dict-like item
def get_item(self, index):
""" Acces shortcut
:param index: Number of row or index of cell
:return: Dict-like item
"""
row = index.row() if hasattr(index, "row") else index
... |
Reset sort state, set collection and emit resetModel signal
def set_collection(self, collection):
"""Reset sort state, set collection and emit resetModel signal"""
self.beginResetModel()
self.collection = collection
self.sort_state = (-1, False)
self.endResetModel() |
Changes item at index in collection. Emit dataChanged signal.
:param index: Number of row or index of cell
:param new_item: Dict-like object
def set_item(self, index, new_item):
""" Changes item at index in collection. Emit dataChanged signal.
:param index: Number of row or index of c... |
Uses given data setter, and emit modelReset signal
def set_data(self, index, value):
"""Uses given data setter, and emit modelReset signal"""
acces, field = self.get_item(index), self.header[index.column()]
self.beginResetModel()
self.set_data_hook(acces, field, value)
self.endR... |
Update selected_ids and emit dataChanged
def _set_id(self, Id, is_added, index):
"""Update selected_ids and emit dataChanged"""
if is_added:
self.selected_ids.add(Id)
else:
self.selected_ids.remove(Id)
self.dataChanged.emit(index, index) |
Update selected_ids on click on index cell.
def setData(self, index: QModelIndex, value, role=None):
"""Update selected_ids on click on index cell."""
if not (index.isValid() and role == Qt.CheckStateRole):
return False
c_id = self.get_item(index).Id
self._set_id(c_id, value... |
Update selected_ids with given Id
def set_by_Id(self, Id, is_added):
"""Update selected_ids with given Id"""
row = self.collection.index_from_id(Id)
if row is None:
return
self._set_id(Id, is_added, self.index(row, 0)) |
Add resize behavior on edit
def _setup_delegate(self):
"""Add resize behavior on edit"""
delegate = self.DELEGATE_CLASS(self)
self.setItemDelegate(delegate)
delegate.sizeHintChanged.connect(
lambda index: self.resizeRowToContents(index.row()))
if self.RESIZE_COLUMN:
... |
To be used in QTreeView
def _draw_placeholder(self):
"""To be used in QTreeView"""
if self.model().rowCount() == 0:
painter = QPainter(self.viewport())
painter.setFont(_custom_font(is_italic=True))
painter.drawText(self.rect().adjusted(0, 0, -5, -5), Qt.AlignCenter |... |
Returns (first) selected item or None
def get_current_item(self):
"""Returns (first) selected item or None"""
l = self.selectedIndexes()
if len(l) > 0:
return self.model().get_item(l[0]) |
Return a model with a collection from a list of entry
def model_from_list(l, header):
"""Return a model with a collection from a list of entry"""
col = groups.sortableListe(PseudoAccesCategorie(n) for n in l)
return MultiSelectModel(col, header) |
Return error string code if the response is an error, otherwise ``"OK"``
def _parse_status_code(response):
"""
Return error string code if the response is an error, otherwise ``"OK"``
"""
# This happens when a status response is expected
if isinstance(response, string_types):
return respon... |
Remove the zone record with the given ID that belongs to the given
domain and sub domain. If no sub domain is given the wildcard sub-domain
is assumed.
def remove_zone_record(self, id, domain, subdomain=None):
"""
Remove the zone record with the given ID that belongs to the given
... |
Parse the module and class name part of the fully qualifed class name.
def parse_module_class(self):
"""Parse the module and class name part of the fully qualifed class name.
"""
cname = self.class_name
match = re.match(self.CLASS_REGEX, cname)
if not match:
raise V... |
Return the module and class as a tuple of the given class in the
initializer.
:param reload: if ``True`` then reload the module before returning the
class
def get_module_class(self):
"""Return the module and class as a tuple of the given class in the
initializer.
:para... |
Create an instance of the specified class in the initializer.
:param args: the arguments given to the initializer of the new class
:param kwargs: the keyword arguments given to the initializer of the
new class
def instance(self, *args, **kwargs):
"""Create an instance of t... |
Convenciene method to set the log level of the module given in the
initializer of this class.
:param level: and instance of ``logging.<level>``
def set_log_level(self, level=logging.INFO):
"""Convenciene method to set the log level of the module given in the
initializer of this class.
... |
Register a class with the factory.
:param instance_class: the class to register with the factory (not a
string)
:param name: the name to use as the key for instance class lookups;
defaults to the name of the class
def register(cls, instance_class, name=None):
"""Registe... |
Resolve the class from the name.
def _find_class(self, class_name):
"Resolve the class from the name."
classes = {}
classes.update(globals())
classes.update(self.INSTANCE_CLASSES)
logger.debug(f'looking up class: {class_name}')
cls = classes[class_name]
logger.de... |
Get the class name and parameters to use for ``__init__``.
def _class_name_params(self, name):
"Get the class name and parameters to use for ``__init__``."
sec = self.pattern.format(**{'name': name})
logger.debug(f'section: {sec}')
params = {}
params.update(self.config.populate(... |
Return whether the class has a ``config`` parameter in the ``__init__``
method.
def _has_init_config(self, cls):
"""Return whether the class has a ``config`` parameter in the ``__init__``
method.
"""
args = inspect.signature(cls.__init__)
return self.config_param_name i... |
Return whether the class has a ``name`` parameter in the ``__init__``
method.
def _has_init_name(self, cls):
"""Return whether the class has a ``name`` parameter in the ``__init__``
method.
"""
args = inspect.signature(cls.__init__)
return self.name_param_name in args.p... |
Return the instance.
:param cls: the class to create the instance from
:param args: given to the ``__init__`` method
:param kwargs: given to the ``__init__`` method
def _instance(self, cls, *args, **kwargs):
"""Return the instance.
:param cls: the class to create the instance ... |
Create a new instance using key ``name``.
:param name: the name of the class (by default) or the key name of the
class used to find the class
:param args: given to the ``__init__`` method
:param kwargs: given to the ``__init__`` method
def instance(self, name=None, *args, **kwargs)... |
Load the instance of the object from the stash.
def load(self, name=None, *args, **kwargs):
"Load the instance of the object from the stash."
inst = self.stash.load(name)
if inst is None:
inst = self.instance(name, *args, **kwargs)
logger.debug(f'loaded (conf mng) instance: ... |
Save the object instance to the stash.
def dump(self, name: str, inst):
"Save the object instance to the stash."
self.stash.dump(name, inst) |
Return a client configured from environment variables.
Essentially copying this:
https://github.com/docker/docker-py/blob/master/docker/client.py#L43.
The environment variables looked for are the following:
.. envvar:: SALTANT_API_URL
The URL of the saltant API. For examp... |
Clear only any cached global data.
def clear_global(self):
"""Clear only any cached global data.
"""
vname = self.varname
logger.debug(f'global clearning {vname}')
if vname in globals():
logger.debug('removing global instance var: {}'.format(vname))
del ... |
Clear the data, and thus, force it to be created on the next fetch. This is
done by removing the attribute from ``owner``, deleting it from globals
and removing the file from the disk.
def clear(self):
"""Clear the data, and thus, force it to be created on the next fetch. This is
done... |
Invoke the file system operations to get the data, or create work.
If the file does not exist, calling ``__do_work__`` and save it.
def _load_or_create(self, *argv, **kwargs):
"""Invoke the file system operations to get the data, or create work.
If the file does not exist, calling ``__do_work... |
Return whether or not the stash has any data available or not.
def has_data(self):
"""Return whether or not the stash has any data available or not."""
if not hasattr(self, '_has_data'):
try:
next(iter(self.delegate.keys()))
self._has_data = True
... |
Return a path to the pickled data with key ``name``.
def _get_instance_path(self, name):
"Return a path to the pickled data with key ``name``."
fname = self.pattern.format(**{'name': name})
logger.debug(f'path {self.create_path}: {self.create_path.exists()}')
self._create_path_dir()
... |
Return an opened shelve object.
def shelve(self):
"""Return an opened shelve object.
"""
logger.info('creating shelve data')
fname = str(self.create_path.absolute())
inst = sh.open(fname, writeback=self.writeback)
self.is_open = True
return inst |
Delete the shelve data file.
def delete(self, name=None):
"Delete the shelve data file."
logger.info('clearing shelve data')
self.close()
for path in Path(self.create_path.parent, self.create_path.name), \
Path(self.create_path.parent, self.create_path.name + '.db'):
... |
Close the shelve object, which is needed for data consistency.
def close(self):
"Close the shelve object, which is needed for data consistency."
if self.is_open:
logger.info('closing shelve data')
try:
self.shelve.close()
self._shelve.clear()
... |
Map ``data_item`` separately in each thread.
def _map(self, data_item):
"Map ``data_item`` separately in each thread."
delegate = self.delegate
logger.debug(f'mapping: {data_item}')
if self.clobber or not self.exists(data_item.id):
logger.debug(f'exist: {data_item.id}: {self... |
Load all instances witih multiple threads.
:param workers: number of workers to use to load instances, which
defaults to what was given in the class initializer
:param limit: return a maximum, which defaults to no limit
:param n_expected: rerun the iteration on the data... |
Monkey-patch object persistence (ex: to/from database) into a
bravado-core model class
def _make_persistent(self, model_name, pkg_name):
"""Monkey-patch object persistence (ex: to/from database) into a
bravado-core model class"""
#
# WARNING: ugly piece of monkey-patching below... |
Auto-generate server endpoints implementing the API into this Flask app
def spawn_api(self, app, decorator=None):
"""Auto-generate server endpoints implementing the API into this Flask app"""
if decorator:
assert type(decorator).__name__ == 'function'
self.is_server = True
s... |
Take a json strust and a model name, and return a model instance
def json_to_model(self, model_name, j, validate=False):
"""Take a json strust and a model name, and return a model instance"""
if validate:
self.api_spec.validate(model_name, j)
return self.api_spec.json_to_model(model... |
Assemble items in *iterable* into discreet collections.
*patterns* may be specified as a list of regular expressions to limit
the returned collection possibilities. Use this when interested in
collections that only match specific patterns. Each pattern must contain
the expression from :py:data:`DIGITS_... |
Parse *value* into a :py:class:`~clique.collection.Collection`.
Use *pattern* to extract information from *value*. It may make use of the
following keys:
* *head* - Common leading part of the collection.
* *tail* - Common trailing part of the collection.
* *padding* - Padding value in ... |
Add *item*.
def add(self, item):
'''Add *item*.'''
if not item in self:
index = bisect.bisect_right(self._members, item)
self._members.insert(index, item) |
Remove *item*.
def discard(self, item):
'''Remove *item*.'''
index = self._index(item)
if index >= 0:
del self._members[index] |
Return index of *item* in member list or -1 if not present.
def _index(self, item):
'''Return index of *item* in member list or -1 if not present.'''
index = bisect.bisect_left(self._members, item)
if index != len(self) and self._members[index] == item:
return index
return ... |
Update internal expression.
def _update_expression(self):
'''Update internal expression.'''
self._expression = re.compile(
'^{0}(?P<index>(?P<padding>0*)\d+?){1}$'
.format(re.escape(self.head), re.escape(self.tail))
) |
Return whether *item* matches this collection expression.
If a match is successful return data about the match otherwise return
None.
def match(self, item):
'''Return whether *item* matches this collection expression.
If a match is successful return data about the match otherwise retu... |
Add *item* to collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
added to the collection.
def add(self, item):
'''Add *item* to collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
added to the collection.
'''
... |
Remove *item* from collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
removed from the collection.
def remove(self, item):
'''Remove *item* from collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
removed from the collec... |
Return string representation as specified by *pattern*.
Pattern can be any format accepted by Python's standard format function
and will receive the following keyword arguments as context:
* *head* - Common leading part of the collection.
* *tail* - Common trailing part of the ... |
Return whether entire collection is contiguous.
def is_contiguous(self):
'''Return whether entire collection is contiguous.'''
previous = None
for index in self.indexes:
if previous is None:
previous = index
continue
if index != (previous... |
Return holes in collection.
Return :py:class:`~clique.collection.Collection` of missing indexes.
def holes(self):
'''Return holes in collection.
Return :py:class:`~clique.collection.Collection` of missing indexes.
'''
missing = set([])
previous = None
for inde... |
Return whether *collection* is compatible with this collection.
To be compatible *collection* must have the same head, tail and padding
properties as this collection.
def is_compatible(self, collection):
'''Return whether *collection* is compatible with this collection.
To be compatib... |
Merge *collection* into this collection.
If the *collection* is compatible with this collection then update
indexes with all indexes in *collection*.
raise :py:class:`~clique.error.CollectionError` if *collection* is not
compatible with this collection.
def merge(self, collection):
... |
Return contiguous parts of collection as separate collections.
Return as list of :py:class:`~clique.collection.Collection` instances.
def separate(self):
'''Return contiguous parts of collection as separate collections.
Return as list of :py:class:`~clique.collection.Collection` instances.
... |
Check the format of a osmnet_config object.
Parameters
----------
settings : dict
osmnet_config as a dictionary
Returns
-------
Nothing
def format_check(settings):
"""
Check the format of a osmnet_config object.
Parameters
----------
settings : dict
osmnet_... |
Return a dict representation of an osmnet osmnet_config instance.
def to_dict(self):
"""
Return a dict representation of an osmnet osmnet_config instance.
"""
return {'logs_folder': self.logs_folder,
'log_file': self.log_file,
'log_console': self.log_cons... |
Get the distance (in meters) between two lat/lon points
via the Haversine formula.
Parameters
----------
lat1, lon1, lat2, lon2 : float
Latitude and longitude in degrees.
Returns
-------
dist : float
Distance in meters.
def great_circle_dist(lat1, lon1, lat2, lon2):
""... |
Create a filter to query Overpass API for the specified OSM network type.
Parameters
----------
network_type : string, {'walk', 'drive'} denoting the type of street
network to extract
Returns
-------
osm_filter : string
def osm_filter(network_type):
"""
Create a filter to query Ov... |
Download OSM ways and nodes within a bounding box from the Overpass API.
Parameters
----------
lat_min : float
southern latitude of bounding box
lng_min : float
eastern longitude of bounding box
lat_max : float
northern latitude of bounding box
lng_max : float
we... |
Send a request to the Overpass API via HTTP POST and return the
JSON response
Parameters
----------
data : dict or OrderedDict
key-value pairs of parameters to post to Overpass API
pause_duration : int
how long to pause in seconds before requests, if None, will query
Overpas... |
Check the Overpass API status endpoint to determine how long to wait until
next slot is available.
Parameters
----------
recursive_delay : int
how long to wait between recursive calls if server is currently
running a query
default_duration : int
if fatal error, function fall... |
Consolidate a geometry into a convex hull, then subdivide it into
smaller sub-polygons if its area exceeds max size (in geometry's units).
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to consolidate and subdivide
max_query_area_size : float
max area ... |
Split a Polygon or MultiPolygon up into sub-polygons of a specified size,
using quadrats.
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to split up into smaller sub-polygons
quadrat_width : float
the linear width of the quadrats with which to cut up t... |
Project a shapely Polygon or MultiPolygon from WGS84 to UTM, or vice-versa
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to project
crs : int
the starting coordinate reference system of the passed-in geometry
to_latlong : bool
if True, project... |
Process a node element entry into a dict suitable for going into a
Pandas DataFrame.
Parameters
----------
e : dict
individual node element in downloaded OSM json
Returns
-------
node : dict
def process_node(e):
"""
Process a node element entry into a dict suitable for goi... |
Process a way element entry into a list of dicts suitable for going into
a Pandas DataFrame.
Parameters
----------
e : dict
individual way element in downloaded OSM json
Returns
-------
way : dict
waynodes : list of dict
def process_way(e):
"""
Process a way element en... |
Convert OSM query data to DataFrames of ways and way-nodes.
Parameters
----------
data : dict
Result of an OSM query.
Returns
-------
nodes, ways, waynodes : pandas.DataFrame
def parse_network_osm_query(data):
"""
Convert OSM query data to DataFrames of ways and way-nodes.
... |
Get DataFrames of OSM data in a bounding box.
Parameters
----------
lat_min : float
southern latitude of bounding box
lng_min : float
eastern longitude of bounding box
lat_max : float
northern latitude of bounding box
lng_max : float
western longitude of bounding... |
Returns a set of all the nodes that appear in 2 or more ways.
Parameters
----------
waynodes : pandas.DataFrame
Mapping of way IDs to node IDs as returned by `ways_in_bbox`.
Returns
-------
intersections : set
Node IDs that appear in 2 or more ways.
def intersection_nodes(wayn... |
Create a table of node pairs with the distances between them.
Parameters
----------
nodes : pandas.DataFrame
Must have 'lat' and 'lon' columns.
ways : pandas.DataFrame
Table of way metadata.
waynodes : pandas.DataFrame
Table linking way IDs to node IDs. Way IDs should be in ... |
Make a graph network from a bounding lat/lon box composed of nodes and
edges for use in Pandana street network accessibility calculations.
You may either enter a lat/long box via the four lat_min,
lng_min, lat_max, lng_max parameters or the bbox parameter as a tuple.
Parameters
----------
lat_m... |
Returns a list of lines from a input markdown file.
def read_lines(in_file):
"""Returns a list of lines from a input markdown file."""
with open(in_file, 'r') as inf:
in_contents = inf.read().split('\n')
return in_contents |
Removes existing [back to top] links and <a id> tags.
def remove_lines(lines, remove=('[[back to top]', '<a class="mk-toclify"')):
"""Removes existing [back to top] links and <a id> tags."""
if not remove:
return lines[:]
out = []
for l in lines:
if l.startswith(remove):
c... |
Takes a header line from a Markdown document and
returns a tuple of the
'#'-stripped version of the head line,
a string version for <a id=''></a> anchor tags,
and the level of the headline as integer.
E.g.,
>>> dashify_headline('### some header lvl3')
('Some header lvl3', 'some-h... |
Gets headlines from the markdown document and creates anchor tags.
Keyword arguments:
lines: a list of sublists where every sublist
represents a line from a Markdown document.
id_tag: if true, creates inserts a the <a id> tags (not req. by GitHub)
back_links: if true, adds "back... |
Strips unnecessary whitespaces/tabs if first header is not left-aligned
def positioning_headlines(headlines):
"""
Strips unnecessary whitespaces/tabs if first header is not left-aligned
"""
left_just = False
for row in headlines:
if row[-1] == 1:
left_just = True
bre... |
Creates the table of contents from the headline list
that was returned by the tag_and_collect function.
Keyword Arguments:
headlines: list of lists
e.g., ['Some header lvl3', 'some-header-lvl3', 3]
hyperlink: Creates hyperlinks in Markdown format if True,
e.g., '- [Some ... |
Returns a string with the Markdown output contents incl.
the table of contents.
Keyword arguments:
toc_headlines: lines for the table of contents
as created by the create_toc function.
body: contents of the Markdown file including
ID-anchor tags as returned by the
... |
Writes to an output file if `outfile` is a valid path.
def output_markdown(markdown_cont, output_file):
"""
Writes to an output file if `outfile` is a valid path.
"""
if output_file:
with open(output_file, 'w') as out:
out.write(markdown_cont) |
Function to add table of contents to markdown files.
Parameters
-----------
input_file: str
Path to the markdown input file.
output_file: str (defaul: None)
Path to the markdown output file.
github: bool (default: False)
Uses GitHub TOC syntax if True.
back_to... |
parse urls with different prefixes
def url_parse(name):
"""parse urls with different prefixes"""
position = name.find("github.com")
if position >= 0:
if position != 0:
position_1 = name.find("www.github.com")
position_2 = name.find("http://github.com")
position_3... |
simple get request
def get_req(url):
"""simple get request"""
request = urllib.request.Request(url)
request.add_header('Authorization', 'token %s' % API_TOKEN)
try:
response = urllib.request.urlopen(request).read().decode('utf-8')
return response
except urllib.error.HTTPError:
... |
get request that returns 302
def geturl_req(url):
"""get request that returns 302"""
request = urllib.request.Request(url)
request.add_header('Authorization', 'token %s' % API_TOKEN)
try:
response_url = urllib.request.urlopen(request).geturl()
return response_url
except urllib.error... |
main function
def main():
"""main function"""
parser = argparse.ArgumentParser(
description='Github within the Command Line')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', '--url', type=str,
help="Get repos from the user profile's URL")
group.... |
Capture the contents of a tag output.
Usage:
.. code-block:: html+django
{% capture %}..{% endcapture %} # output in {{ capture }}
{% capture silent %}..{% endcapture %} # output in {{ capture }} only
{% capture as varname %}..{% endcapture %} # o... |
Helper method that parses special fields to Python objects
:param data: response from Monzo API request
:type data: dict
def _parse_special_fields(self, data):
"""
Helper method that parses special fields to Python objects
:param data: response from Monzo API request
:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.