repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
planetlabs/es_fluent | es_fluent/builder.py | QueryBuilder.sort | python | def sort(self, field, direction="asc"):
if not isinstance(field, basestring):
raise ValueError("Field should be a string")
if direction not in ["asc", "desc"]:
raise ValueError("Sort direction should be `asc` or `desc`")
self.sorts.append({field: direction}) | Adds sort criteria. | train | https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/builder.py#L144-L153 | null | class QueryBuilder(object):
def __init__(self):
self.root_filter = Dict()
self.script_fields = ScriptFields()
self.fields = Fields()
self.sorts = []
self.source = True
self._size = None
@property
def size(self):
"""
Sets current size limit of... |
planetlabs/es_fluent | es_fluent/builder.py | QueryBuilder.remove_sort | python | def remove_sort(self, field_name):
self.sorts = [dict(field=value) for field, value in self.sorts if field
is not field_name] | Clears sorting criteria affecting ``field_name``. | train | https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/builder.py#L155-L160 | null | class QueryBuilder(object):
def __init__(self):
self.root_filter = Dict()
self.script_fields = ScriptFields()
self.fields = Fields()
self.sorts = []
self.source = True
self._size = None
@property
def size(self):
"""
Sets current size limit of... |
planetlabs/es_fluent | es_fluent/fields/__init__.py | Fields.add_field | python | def add_field(self, field_instance_or_string):
if isinstance(field_instance_or_string, basestring):
field_instance = Field(field_instance_or_string)
elif isinstance(field_instance_or_string, Field):
field_instance_or_string = field_instance
else:
raise ValueEr... | Appends a field, can be a :class:`~es_fluent.fields.Field` or string. | train | https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/fields/__init__.py#L14-L27 | null | class Fields(object):
"""
Represents a collection of fields to be requested at query time.
"""
def __init__(self):
self.fields = []
def to_query(self):
"""
Serializes this into a json-serializable dictionary suitable for use
with the elasticsearch api.
"""
... |
planetlabs/es_fluent | es_fluent/script_fields/__init__.py | ScriptFields.add_field | python | def add_field(self, field_instance):
if isinstance(field_instance, BaseScriptField):
field_instance = field_instance
else:
raise ValueError('Expected a basetring or Field instance')
self.fields.append(field_instance)
return self | Appends a field. | train | https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/script_fields/__init__.py#L8-L19 | null | class ScriptFields(object):
"""
Represents a collection of requested script fields.
"""
def __init__(self):
self.fields = []
def is_empty(self):
"""
Returns True if there are no script fields, False otherwise.
"""
return len(self.fields) == 0
def to_que... |
planetlabs/es_fluent | es_fluent/script_fields/__init__.py | ScriptFields.to_query | python | def to_query(self):
query = {}
for field_instance in self.fields:
query.update(field_instance.to_query())
return query | Returns a json-serializable representation. | train | https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/script_fields/__init__.py#L27-L36 | null | class ScriptFields(object):
"""
Represents a collection of requested script fields.
"""
def __init__(self):
self.fields = []
def add_field(self, field_instance):
"""
Appends a field.
"""
if isinstance(field_instance, BaseScriptField):
field_instan... |
planetlabs/es_fluent | es_fluent/script_fields/__init__.py | ScriptField.to_query | python | def to_query(self):
return {
self.name: {
'lang': self.lang,
'script': self.script,
'params': self.script_params
}
} | Returns a json-serializable representation. | train | https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/script_fields/__init__.py#L63-L73 | null | class ScriptField(BaseScriptField):
"""
Represents a script field.
"""
def __init__(self, name, script, lang='groovy', **kwargs):
"""
:param string name: The resulting name of the field.
:param dict script: The script for the script field.
:param string lang: The language... |
planetlabs/es_fluent | es_fluent/filters/__init__.py | register_filter | python | def register_filter(filter_cls):
if filter_cls.name is None:
return
elif filter_cls.name in FILTER_REGISTRY:
raise RuntimeError(
"Filter class already registered: {}".format(filter_cls.name))
else:
FILTER_REGISTRY[filter_cls.name] = filter_cls | Adds the ``filter_cls`` to our registry. | train | https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/__init__.py#L22-L32 | null | # A dictionary of filter classes, keyed by their name attributes.
FILTER_REGISTRY = {}
class FilterRegistry(type):
"""
Metaclass used to automatically register new filter classes in our filter
registry. Enables shorthand filter notation.
>>> from es_fluent.builder import QueryBuilder
>>> ... |
planetlabs/es_fluent | es_fluent/filters/__init__.py | build_filter | python | def build_filter(filter_or_string, *args, **kwargs):
if isinstance(filter_or_string, basestring):
# Names that start with `~` indicate a negated filter.
if filter_or_string.startswith('~'):
filter_name = filter_or_string[1:]
return ~FILTER_REGISTRY[filter_name](*args, **kwarg... | Overloaded filter construction. If ``filter_or_string`` is a string
we look up it's corresponding class in the filter registry and return it.
Otherwise, assume ``filter_or_string`` is an instance of a filter.
:return: :class:`~es_fluent.filters.Filter` | train | https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/__init__.py#L35-L52 | null | # A dictionary of filter classes, keyed by their name attributes.
FILTER_REGISTRY = {}
class FilterRegistry(type):
"""
Metaclass used to automatically register new filter classes in our filter
registry. Enables shorthand filter notation.
>>> from es_fluent.builder import QueryBuilder
>>> ... |
eyeseast/python-tablefu | table_fu/__init__.py | TableFu.sort | python | def sort(self, column_name=None, reverse=False):
if not column_name and self.options.has_key('sorted_by'):
column_name = self.options['sorted_by'].keys()[0]
if column_name not in self.default_columns:
raise ValueError("%s isn't a column in this table" % column_name)
index... | Sort rows in this table, preserving a record of how that
sorting is done in TableFu.options['sorted_by'] | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L135-L146 | null | class TableFu(object):
"""
A table, to be manipulated like a spreadsheet.
TableFu reads in an open CSV file, parsing it
into a table property, Row and Datum objects.
Usage:
# test.csv
Author,Best Book,Number of Pages,Style
Samuel Beckett,Malone Muert,120,Modernism
James Joyce,Ul... |
eyeseast/python-tablefu | table_fu/__init__.py | TableFu.filter | python | def filter(self, func=None, **query):
if callable(func):
result = filter(func, self)
result.insert(0, self.default_columns)
return TableFu(result, **self.options)
else:
result = self
for column, value in query.items():
result = ... | Tables can be filtered in one of two ways:
- Simple keyword arguments return rows where values match *exactly*
- Pass in a function and return rows where that function evaluates to True
In either case, a new TableFu instance is returned | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L181-L197 | [
"def filter(self, func=None, **query):\n \"\"\"\n Tables can be filtered in one of two ways:\n - Simple keyword arguments return rows where values match *exactly*\n - Pass in a function and return rows where that function evaluates to True\n\n In either case, a new TableFu instance is returned\n ... | class TableFu(object):
"""
A table, to be manipulated like a spreadsheet.
TableFu reads in an open CSV file, parsing it
into a table property, Row and Datum objects.
Usage:
# test.csv
Author,Best Book,Number of Pages,Style
Samuel Beckett,Malone Muert,120,Modernism
James Joyce,Ul... |
eyeseast/python-tablefu | table_fu/__init__.py | TableFu.facet_by | python | def facet_by(self, column):
faceted_spreadsheets = {}
for row in self.rows:
if row[column]:
col = row[column].value
if faceted_spreadsheets.has_key(col):
faceted_spreadsheets[col].append(row.cells)
else:
... | Faceting creates new TableFu instances with rows matching
each possible value. | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L199-L225 | null | class TableFu(object):
"""
A table, to be manipulated like a spreadsheet.
TableFu reads in an open CSV file, parsing it
into a table property, Row and Datum objects.
Usage:
# test.csv
Author,Best Book,Number of Pages,Style
Samuel Beckett,Malone Muert,120,Modernism
James Joyce,Ul... |
eyeseast/python-tablefu | table_fu/__init__.py | TableFu.map | python | def map(self, func, *columns):
if not columns:
return map(func, self.rows)
else:
values = (self.values(column) for column in columns)
result = [map(func, v) for v in values]
if len(columns) == 1:
return result[0]
else:
... | Map a function to rows, or to given columns | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L239-L251 | null | class TableFu(object):
"""
A table, to be manipulated like a spreadsheet.
TableFu reads in an open CSV file, parsing it
into a table property, Row and Datum objects.
Usage:
# test.csv
Author,Best Book,Number of Pages,Style
Samuel Beckett,Malone Muert,120,Modernism
James Joyce,Ul... |
eyeseast/python-tablefu | table_fu/__init__.py | TableFu.csv | python | def csv(self, **kwargs):
out = StringIO()
writer = csv.DictWriter(out, self.columns, **kwargs)
writer.writerow(dict(zip(self.columns, self.columns)))
writer.writerows(dict(row.items()) for row in self.rows)
return out | Export this table as a CSV | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L260-L269 | null | class TableFu(object):
"""
A table, to be manipulated like a spreadsheet.
TableFu reads in an open CSV file, parsing it
into a table property, Row and Datum objects.
Usage:
# test.csv
Author,Best Book,Number of Pages,Style
Samuel Beckett,Malone Muert,120,Modernism
James Joyce,Ul... |
eyeseast/python-tablefu | table_fu/__init__.py | TableFu.from_file | python | def from_file(fn, **options):
if hasattr(fn, 'read'):
return TableFu(fn, **options)
with open(fn) as f:
return TableFu(f, **options) | Creates a new TableFu instance from a file or path | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L281-L288 | null | class TableFu(object):
"""
A table, to be manipulated like a spreadsheet.
TableFu reads in an open CSV file, parsing it
into a table property, Row and Datum objects.
Usage:
# test.csv
Author,Best Book,Number of Pages,Style
Samuel Beckett,Malone Muert,120,Modernism
James Joyce,Ul... |
eyeseast/python-tablefu | table_fu/__init__.py | TableFu.from_url | python | def from_url(url, **options):
resp = urllib2.urlopen(url)
return TableFu(resp, **options) | Downloads the contents of a given URL and loads it
into a new TableFu instance | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L291-L297 | null | class TableFu(object):
"""
A table, to be manipulated like a spreadsheet.
TableFu reads in an open CSV file, parsing it
into a table property, Row and Datum objects.
Usage:
# test.csv
Author,Best Book,Number of Pages,Style
Samuel Beckett,Malone Muert,120,Modernism
James Joyce,Ul... |
eyeseast/python-tablefu | table_fu/__init__.py | Row.get | python | def get(self, column_name, default=None):
if column_name in self.table.default_columns:
index = self.table.default_columns.index(column_name)
return Datum(self.cells[index], self.row_num, column_name, self.table)
return default | Return the Datum for column_name, or default. | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/__init__.py#L326-L333 | null | class Row(object):
"""
A row in a table
Rows act like dictionaries, but look more like lists.
Calling row['column'] returns a column lookup based on
the default set of columns.
"""
def __init__(self, cells, row_num, table):
self.table = table
self.row_num = row_num
s... |
eyeseast/python-tablefu | table_fu/formatting.py | _saferound | python | def _saferound(value, decimal_places):
try:
f = float(value)
except ValueError:
return ''
format = '%%.%df' % decimal_places
return format % f | Rounds a float value off to the desired precision | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L10-L19 | null | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def ap_state(value, failure_string=None):
"""
Converts a state's name, postal abbreviation or FIPS to A.P. style.
Example usage:
... |
eyeseast/python-tablefu | table_fu/formatting.py | ap_state | python | def ap_state(value, failure_string=None):
try:
return statestyle.get(value).ap
except:
if failure_string:
return failure_string
else:
return value | Converts a state's name, postal abbreviation or FIPS to A.P. style.
Example usage:
>> ap_state("California")
'Calif.' | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L22-L38 | null | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
eyeseast/python-tablefu | table_fu/formatting.py | capfirst | python | def capfirst(value, failure_string='N/A'):
try:
value = value.lower()
return value[0].upper() + value[1:]
except:
return failure_string | Capitalizes the first character of the value.
If the submitted value isn't a string, returns the `failure_string` keyword
argument.
Cribbs from django's default filter set | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L41-L54 | null | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
eyeseast/python-tablefu | table_fu/formatting.py | dollar_signs | python | def dollar_signs(value, failure_string='N/A'):
try:
count = int(value)
except ValueError:
return failure_string
string = ''
for i in range(0, count):
string += '$'
return string | Converts an integer into the corresponding number of dollar sign symbols.
If the submitted value isn't a string, returns the `failure_string` keyword
argument.
Meant to emulate the illustration of price range on Yelp. | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L61-L77 | null | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
eyeseast/python-tablefu | table_fu/formatting.py | image | python | def image(value, width='', height=''):
style = ""
if width:
style += "width:%s" % width
if height:
style += "height:%s" % height
data_dict = dict(src=value, style=style)
return '<img src="%(src)s" style="%(style)s">' % data_dict | Accepts a URL and returns an HTML image tag ready to be displayed.
Optionally, you can set the height and width with keyword arguments. | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L80-L92 | null | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
eyeseast/python-tablefu | table_fu/formatting.py | intcomma | python | def intcomma(value):
orig = str(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig)
if orig == new:
return new
else:
return intcomma(new) | Borrowed from django.contrib.humanize
Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'. | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L102-L114 | [
"def intcomma(value):\n \"\"\"\n Borrowed from django.contrib.humanize\n\n Converts an integer to a string containing commas every three digits.\n For example, 3000 becomes '3,000' and 45000 becomes '45,000'.\n \"\"\"\n orig = str(value)\n new = re.sub(\"^(-?\\d+)(\\d{3})\", '\\g<1>,\\g<2>', or... | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
eyeseast/python-tablefu | table_fu/formatting.py | percentage | python | def percentage(value, decimal_places=1, multiply=True, failure_string='N/A'):
try:
value = float(value)
except ValueError:
return failure_string
if multiply:
value = value * 100
return _saferound(value, decimal_places) + '%' | Converts a floating point value into a percentage value.
Number of decimal places set by the `decimal_places` kwarg. Default is one.
By default the number is multiplied by 100. You can prevent it from doing
that by setting the `multiply` keyword argument to False.
If the submitted value i... | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L117-L135 | [
"def _saferound(value, decimal_places):\n \"\"\"\n Rounds a float value off to the desired precision\n \"\"\"\n try:\n f = float(value)\n except ValueError:\n return ''\n format = '%%.%df' % decimal_places\n return format % f\n"
] | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
eyeseast/python-tablefu | table_fu/formatting.py | percent_change | python | def percent_change(value, decimal_places=1, multiply=True, failure_string='N/A'):
try:
f = float(value)
if multiply:
f = f * 100
except ValueError:
return failure_string
s = _saferound(f, decimal_places)
if f > 0:
return '+' + s + '%'
else:
return ... | Converts a floating point value into a percentage change value.
Number of decimal places set by the `precision` kwarg. Default is one.
Non-floats are assumed to be zero division errors and are presented as
'N/A' in the output.
By default the number is multiplied by 100. You can prevent it... | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L138-L160 | [
"def _saferound(value, decimal_places):\n \"\"\"\n Rounds a float value off to the desired precision\n \"\"\"\n try:\n f = float(value)\n except ValueError:\n return ''\n format = '%%.%df' % decimal_places\n return format % f\n"
] | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
eyeseast/python-tablefu | table_fu/formatting.py | ratio | python | def ratio(value, decimal_places=0, failure_string='N/A'):
try:
f = float(value)
except ValueError:
return failure_string
return _saferound(f, decimal_places) + ':1' | Converts a floating point value a X:1 ratio.
Number of decimal places set by the `precision` kwarg. Default is one. | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L163-L173 | [
"def _saferound(value, decimal_places):\n \"\"\"\n Rounds a float value off to the desired precision\n \"\"\"\n try:\n f = float(value)\n except ValueError:\n return ''\n format = '%%.%df' % decimal_places\n return format % f\n"
] | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
eyeseast/python-tablefu | table_fu/formatting.py | title | python | def title(value, failure_string='N/A'):
try:
value = value.lower()
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
result = re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)
if not result:
return failure_string
return result
excep... | Converts a string into titlecase.
Lifted from Django. | train | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L210-L224 | null | """
Utilities to format values into more meaningful strings.
Inspired by James Bennett's template_utils and Django's
template filters.
"""
import re
import statestyle
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
exce... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | read | python | def read(mfile, sfile):
assert os.path.isfile(mfile), "%s multiplicon file does not exist"
assert os.path.isfile(sfile), "%s segments file does not exist"
return IadhoreData(mfile, sfile) | Returns an IadhoreData object, constructed from the passed
i-ADHoRe multiplicon and segments output.
- mfile (str), location of multiplicons.txt
- sfile (str), location of segments.txt | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L366-L375 | null | #!/usr/bin/env python
""" Provides a data structure for handling i-ADHoRe output data, based on
a tree structure for identifying interesting multiplicons, and an SQLite
backend for holding the multiplicon data.
(c) The James Hutton Institute 2013
Author: Leighton Pritchard
Contact:
leighton.pritchard@hutton.ac.uk
Le... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData._dbsetup | python | def _dbsetup(self):
self._dbconn = sqlite3.connect(self._db_file)
# Create table for multiplicons
sql = '''CREATE TABLE multiplicons
(id, genome_x, list_x, parent, genome_y, list_y, level,
number_of_anchorpoints, profile_length, begin_x, end_x,
... | Create/open local SQLite database | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L82-L96 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData._parse_multiplicons | python | def _parse_multiplicons(self):
# Parse data with csv reader
reader = csv.reader(open(self._multiplicon_file, 'rU'),
delimiter='\t')
for row in reader:
if reader.line_num == 1: # skip header
continue
# Add data to SQLite db
... | Read the multiplicon output file, and parse into a (i) tree using
NetworkX, and (ii) an SQLite database. | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L98-L120 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData._parse_segments | python | def _parse_segments(self):
reader = csv.reader(open(self._segment_file, 'rU'),
delimiter='\t')
for row in reader:
if reader.line_num == 1: # skip header
continue
sql = '''INSERT INTO segments
(id, multiplicon, geno... | Read the segment output file and parse into an SQLite database. | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L122-L134 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.get_multiplicon_leaves | python | def get_multiplicon_leaves(self, redundant=False):
for node in self._multiplicon_graph.nodes():
if not len(self._multiplicon_graph.out_edges(node)):
if not self.is_redundant_multiplicon(node):
yield node
elif redundant:
yield no... | Return a generator of the IDs of multiplicons found at leaves
of the tree (i.e. from which no further multiplicons were derived).
Arguments:
o redundant - if true, report redundant multiplicons | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L136-L153 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.get_multiplicon_seeds | python | def get_multiplicon_seeds(self, redundant=False):
for node in self._multiplicon_graph.nodes():
if not len(self._multiplicon_graph.in_edges(node)):
if not self.is_redundant_multiplicon(node):
yield node
elif redundant:
yield node... | Return a generator of the IDs of multiplicons that are initial
seeding 'pairs' in level 2 multiplicons.
Arguments:
o redundant - if true, report redundant multiplicons | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L155-L172 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.get_multiplicon_intermediates | python | def get_multiplicon_intermediates(self, redundant=False):
for node in self._multiplicon_graph.nodes():
if len(self._multiplicon_graph.in_edges(node)) and \
len(self._multiplicon_graph.out_edges(node)):
if not self.is_redundant_multiplicon(node):
yie... | Return a generator of the IDs of multiplicons that are neither
seeding 'pairs' in level 2 multiplicons, nor leaves.
Arguments:
o redundant - if true, report redundant multiplicons | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L174-L192 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.get_multiplicon_properties | python | def get_multiplicon_properties(self, value):
sql = '''SELECT id, parent, level, number_of_anchorpoints,
profile_length, is_redundant
FROM multiplicons WHERE id=:id'''
cur = self._dbconn.cursor()
cur.execute(sql, {'id': str(value)})
result = cur... | Return a dictionary describing multiplicon data:
id, parent, level, number_of_anchorpoints, profile_length,
is_redundant and the contributing genome segments | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L194-L212 | [
"def get_multiplicon_segments(self, value):\n \"\"\" Return a dictionary describing the genome segments that\n contribute to the named multiplicon, keyed by genome, with\n (start feature, end feature) tuples.\n \"\"\"\n sql = '''SELECT genome, first, last FROM segments\n WHERE m... | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.get_multiplicon_segments | python | def get_multiplicon_segments(self, value):
sql = '''SELECT genome, first, last FROM segments
WHERE multiplicon=:mp'''
cur = self._dbconn.cursor()
cur.execute(sql, {'mp': str(value)})
result = cur.fetchall()
cur.close()
segdict = collections.defaultdict(... | Return a dictionary describing the genome segments that
contribute to the named multiplicon, keyed by genome, with
(start feature, end feature) tuples. | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L214-L228 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.get_multiplicons_at_level | python | def get_multiplicons_at_level(self, level, redundant=False):
sql = '''SELECT id FROM multiplicons
WHERE level=:level'''
cur = self._dbconn.cursor()
cur.execute(sql, {'level': str(level)})
result = [int(r[0]) for r in cur.fetchall()]
cur.close()
if redun... | Return a list of IDs of multiplicons at the requested level | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L230-L242 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.is_redundant_multiplicon | python | def is_redundant_multiplicon(self, value):
if not hasattr(self, '_redundant_multiplicon_cache'):
sql = '''SELECT id FROM multiplicons WHERE is_redundant="-1"'''
cur = self._dbconn.cursor()
cur.execute(sql, {'id': str(value)})
result = [int(r[0]) for r in cur.fetch... | Returns True if the passed multiplicon ID is redundant, False
otherwise.
- value, (int) multiplicon ID | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L244-L259 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.write | python | def write(self, mfile="multiplicons.txt", sfile="segments.txt",
clobber=False):
if not clobber:
if os.path.isfile(mfile):
raise IOError("Multiplicon file %s already exists." % mfile)
if os.path.isfile(sfile):
raise IOError("Segments file %s a... | Writes multiplicon and segment files to the named locations.
- mfile, (str) location for multiplicons file
- sfile, (str) location for segments file
- clobber, (Boolean) True if we overwrite target files | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L261-L275 | [
"def _write_multiplicons(self, filename):\n \"\"\" Write multiplicons to file.\n\n - filename, (str) location of output file\n \"\"\"\n # Column headers\n mhead = '\\t'.join(['id', 'genome_x', 'list_x', 'parent', 'genome_y',\n 'list_y', 'level', 'number_of_anchorpoints',\n ... | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData._write_multiplicons | python | def _write_multiplicons(self, filename):
# Column headers
mhead = '\t'.join(['id', 'genome_x', 'list_x', 'parent', 'genome_y',
'list_y', 'level', 'number_of_anchorpoints',
'profile_length', 'begin_x', 'end_x', 'begin_y',
'e... | Write multiplicons to file.
- filename, (str) location of output file | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L277-L290 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData._write_segments | python | def _write_segments(self, filename):
# Column headers
shead = '\t'.join(['id', 'multiplicon', 'genome', 'list', 'first',
'last', 'order'])
with open(filename, 'w') as fhandle:
fhandle.write(shead + '\n')
for mrow in self.segments:
... | Write segments to file.
- filename, (str) location of output file | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L292-L303 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.multiplicon_file | python | def multiplicon_file(self, value):
assert os.path.isfile(value), "%s is not a valid file" % value
self._multiplicon_file = value | Setter for _multiplicon_file attribute | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L311-L314 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.segment_file | python | def segment_file(self, value):
assert os.path.isfile(value), "%s is not a valid file" % value
self._segment_file = value | Setter for _segment_file attribute | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L322-L325 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.db_file | python | def db_file(self, value):
assert not os.path.isfile(value), "%s already exists" % value
self._db_file = value | Setter for _db_file attribute | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L333-L336 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | IadhoreData.multiplicons | python | def multiplicons(self):
sql = '''SELECT * FROM multiplicons'''
cur = self._dbconn.cursor()
cur.execute(sql)
data = [r for r in cur.fetchall()]
cur.close()
return data | Multiplicon table from SQLite database. | train | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L344-L351 | null | class IadhoreData(object):
""" Implements an interface to i-ADHoRe output data, using NetworkX to
hold a tree representation of multiplicon relationships, and SQLite3
to hold the output data tables
"""
def __init__(self, multiplicon_file=None, segment_file=None,
db_filename=... |
mozilla-b2g/fxos-certsuite | mcts/securitysuite/ssl.py | nssversion.to_ints | python | def to_ints(version):
# Example strings: "NSS_3_7_9_RTM", "NSS_3_6_BRANCH_20021026", "NSS_3_6_BETA2",
# "3.18 Basic ECC Beta", "3.16.5 Basic ECC"
# normalize version strings
norm_version = version.replace('NSS_', '').replace('.', '_').replace(' ', '_').upper().split('_... | Turn version string into a numeric representation for easy comparison.
Undeclared point versions are assumed to be 0.
:param version: a NSS version string
:return: array of [major, minor, point, pointpoint, tag value] | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/securitysuite/ssl.py#L203-L265 | null | class nssversion(ExtraTest):
"""
Test that logs nss component versions from device.
"""
group = "ssl"
module = sys.modules[__name__]
# TODO: This list's tail must be maintained regularly.
b2g_version_to_hginfo = {
'1.2': {
'hgtag': 'mozilla-b2g26_v1_2',
'rel... |
mozilla-b2g/fxos-certsuite | mcts/securitysuite/ssl.py | nssversion.first_older_than_second | python | def first_older_than_second(version_a, version_b):
a = nssversion.to_ints(version_a)
b = nssversion.to_ints(version_b)
# must be of equal length
assert len(a) == len(b)
# Compare each version component, bail out on difference
for i in xrange(len(a)):
if b[i... | Tests for the NSS version string in the first parameter being less
recent than the second (a < b). Tag order is RTM > RC > BETA > *.
Works with hg tags like "NSS_3_7_9_RTM" and version strings reported by
nsINSSVersion, like "3.18 Basic ECC Beta" (mixed, too).
:param version_a: a NSS ver... | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/securitysuite/ssl.py#L268-L291 | null | class nssversion(ExtraTest):
"""
Test that logs nss component versions from device.
"""
group = "ssl"
module = sys.modules[__name__]
# TODO: This list's tail must be maintained regularly.
b2g_version_to_hginfo = {
'1.2': {
'hgtag': 'mozilla-b2g26_v1_2',
'rel... |
mozilla-b2g/fxos-certsuite | mcts/securitysuite/ssl.py | nssversion.most_recent_among | python | def most_recent_among(versions):
latest = versions[0]
for v in versions[1:]:
if nssversion.first_older_than_second(latest, v):
latest = v
return latest | Compare a list of NSS versions and return the latest one.
Uses first_older_than_second() for comparison.
:param versions: an array of NSS version strings
:return: verbatim copy of the most recent version string | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/securitysuite/ssl.py#L294-L305 | null | class nssversion(ExtraTest):
"""
Test that logs nss component versions from device.
"""
group = "ssl"
module = sys.modules[__name__]
# TODO: This list's tail must be maintained regularly.
b2g_version_to_hginfo = {
'1.2': {
'hgtag': 'mozilla-b2g26_v1_2',
'rel... |
mozilla-b2g/fxos-certsuite | mcts/securitysuite/ssl.py | nssversion.run | python | def run(cls, version=None):
try:
dumper = certdump()
versions = dumper.nssversion_via_marionette()
except Exception as e: # TODO: too broad exception
cls.log_status('FAIL', 'Failed to gather information from the device via Marionette: %s' % e)
return Fal... | Test runner method; is called by parent class defined in suite.py.
:param version: B2G version string to test against
:return: bool PASS/FAIL status | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/securitysuite/ssl.py#L308-L353 | [
"def nssversion_via_marionette(self):\n return run_marionette_script(certdump.js_nssversions(),\n chrome=True)\n"
] | class nssversion(ExtraTest):
"""
Test that logs nss component versions from device.
"""
group = "ssl"
module = sys.modules[__name__]
# TODO: This list's tail must be maintained regularly.
b2g_version_to_hginfo = {
'1.2': {
'hgtag': 'mozilla-b2g26_v1_2',
'rel... |
mozilla-b2g/fxos-certsuite | mcts/securitysuite/filesystem.py | parse_ls | python | def parse_ls(out):
# assumed ls -lR line format:
# -rw-r--r-- root shell 0 2013-07-05 02:26 tasks
# drwxr-xr-x root root 2013-07-05 02:26 log
# brw------- root root 179, 0 2013-07-05 02:26 mmcblk0
# lrwxrwxrwx root root 2013-07-05 02:34 subs... | Parser for Android's ls -lR output.
Takes a string, returns parsed structure. | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/securitysuite/filesystem.py#L23-L119 | null | # -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import re
import os
import sys
import subprocess
import mozdevice
# getter for shared logger... |
mozilla-b2g/fxos-certsuite | mcts/securitysuite/suite.py | securitycli | python | def securitycli():
parser = argparse.ArgumentParser(description="Runner for security test suite")
parser.add_argument("-l", "--list-test-groups", action="store_true",
help="List all logical test groups")
parser.add_argument("-a", "--list-all-tests", action="store_true",
... | Entry point for the runner defined in setup.py. | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/securitysuite/suite.py#L140-L202 | [
"def wait_for_adb_device():\n try:\n device = DeviceHelper.getDevice()\n except ADBError:\n device = None\n print \"Waiting for adb connection...\"\n while device is None:\n try:\n device = DeviceHelper.getDevice()\n except ADBError:\n sleep(0.2)\n ... | # -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import sys
import logging
import argparse
import traceback
from mozdevice import DeviceManage... |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | ADBB2G.wait_for_device_ready | python | def wait_for_device_ready(self, timeout=None, wait_polling_interval=None, after_first=None):
if timeout is None:
timeout = self._timeout
if wait_polling_interval is None:
wait_polling_interval = self._wait_polling_interval
self._logger.info("Waiting for device to become... | Wait for the device to become ready for reliable interaction via adb.
NOTE: if the device is *already* ready this method will timeout.
:param timeout: Maximum time to wait for the device to become ready
:param wait_polling_interval: Interval at which to poll for device readiness.
:param... | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L131-L189 | [
"def poll_wait(func, polling_interval=1.0, timeout=30, after_first=None):\n start_time = time.time()\n ran_first = False\n\n current_time = time.time()\n while current_time - start_time < timeout:\n value = func()\n if value:\n return value\n\n if not ran_first and after_... | class ADBB2G(adb.ADBDevice):
def __init__(self, *args, **kwargs):
if "wait_polling_interval" in kwargs:
self._wait_polling_interval = kwargs.pop("wait_polling_interval")
else:
self._wait_polling_interval = 1.0
adb.ADBDevice.__init__(self, *args, **kwargs)
def ... |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | ADBB2G.wait_for_net | python | def wait_for_net(self, timeout=None, wait_polling_interval=None):
if timeout is None:
timeout = self._timeout
if wait_polling_interval is None:
wait_polling_interval = self._wait_polling_interval
self._logger.info("Waiting for network connection")
poll_wait(self.... | Wait for the device to be assigned an IP address.
:param timeout: Maximum time to wait for an IP address to be defined
:param wait_polling_interval: Interval at which to poll for ip address. | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L191-L203 | [
"def poll_wait(func, polling_interval=1.0, timeout=30, after_first=None):\n start_time = time.time()\n ran_first = False\n\n current_time = time.time()\n while current_time - start_time < timeout:\n value = func()\n if value:\n return value\n\n if not ran_first and after_... | class ADBB2G(adb.ADBDevice):
def __init__(self, *args, **kwargs):
if "wait_polling_interval" in kwargs:
self._wait_polling_interval = kwargs.pop("wait_polling_interval")
else:
self._wait_polling_interval = 1.0
adb.ADBDevice.__init__(self, *args, **kwargs)
def w... |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | ADBB2G.start | python | def start(self, wait=True, timeout=None, wait_polling_interval=None):
self._logger.info("Starting b2g process")
if timeout is None:
timeout = self._timeout
if wait_polling_interval is None:
wait_polling_interval = self._wait_polling_interval
if wait:
... | Start b2g, waiting for the adb connection to become stable.
:param wait:
:param timeout: Maximum time to wait for restart.
:param wait_polling_interval: Interval at which to poll for device readiness. | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L215-L235 | [
"def wait_for_device_ready(self, timeout=None, wait_polling_interval=None, after_first=None):\n \"\"\"Wait for the device to become ready for reliable interaction via adb.\n NOTE: if the device is *already* ready this method will timeout.\n\n :param timeout: Maximum time to wait for the device to become re... | class ADBB2G(adb.ADBDevice):
def __init__(self, *args, **kwargs):
if "wait_polling_interval" in kwargs:
self._wait_polling_interval = kwargs.pop("wait_polling_interval")
else:
self._wait_polling_interval = 1.0
adb.ADBDevice.__init__(self, *args, **kwargs)
def w... |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | ADBB2G.restart | python | def restart(self, wait=True, timeout=None, wait_polling_interval=None):
self.stop(timeout=timeout)
self.start(wait, timeout=timeout, wait_polling_interval=wait_polling_interval) | Restart b2g, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for restart.
:param wait_polling_interval: Interval at which to poll for device readiness. | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L237-L244 | [
"def stop(self, timeout=None):\n self._logger.info(\"Stopping b2g process\")\n if timeout is None:\n timeout = self._timeout\n self.shell_bool(\"stop b2g\")\n def b2g_stopped():\n processes = set(item[1].split(\"/\")[-1] for item in self.get_process_list())\n return \"b2g\" not in p... | class ADBB2G(adb.ADBDevice):
def __init__(self, *args, **kwargs):
if "wait_polling_interval" in kwargs:
self._wait_polling_interval = kwargs.pop("wait_polling_interval")
else:
self._wait_polling_interval = 1.0
adb.ADBDevice.__init__(self, *args, **kwargs)
def w... |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | ADBB2G.reboot | python | def reboot(self, timeout=None, wait_polling_interval=None):
if timeout is None:
timeout = self._timeout
if wait_polling_interval is None:
wait_polling_interval = self._wait_polling_interval
self._logger.info("Rebooting device")
self.wait_for_device_ready(timeout,... | Reboot the device, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for reboot.
:param wait_polling_interval: Interval at which to poll for device readiness. | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L246-L259 | [
"def wait_for_device_ready(self, timeout=None, wait_polling_interval=None, after_first=None):\n \"\"\"Wait for the device to become ready for reliable interaction via adb.\n NOTE: if the device is *already* ready this method will timeout.\n\n :param timeout: Maximum time to wait for the device to become re... | class ADBB2G(adb.ADBDevice):
def __init__(self, *args, **kwargs):
if "wait_polling_interval" in kwargs:
self._wait_polling_interval = kwargs.pop("wait_polling_interval")
else:
self._wait_polling_interval = 1.0
adb.ADBDevice.__init__(self, *args, **kwargs)
def w... |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | ADBB2G.get_profiles | python | def get_profiles(self, profile_base="/data/b2g/mozilla", timeout=None):
rv = {}
if timeout is None:
timeout = self._timeout
profile_path = posixpath.join(profile_base, "profiles.ini")
try:
proc = self.shell("cat %s" % profile_path, timeout=timeout)
... | Return a list of paths to gecko profiles on the device,
:param timeout: Timeout of each adb command run
:param profile_base: Base directory containing the profiles.ini file | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L266-L294 | null | class ADBB2G(adb.ADBDevice):
def __init__(self, *args, **kwargs):
if "wait_polling_interval" in kwargs:
self._wait_polling_interval = kwargs.pop("wait_polling_interval")
else:
self._wait_polling_interval = 1.0
adb.ADBDevice.__init__(self, *args, **kwargs)
def w... |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | ADBB2G.devices | python | def devices(self, timeout=None):
# b313b945 device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw
# from Android system/core/adb/transport.c statename()
re_device_info = re.compile(r'([^\s]+)\s+(offline|bootloader|device|host|recovery|sideload|no permissions|unauthorized|unknown... | Executes adb devices -l and returns a list of objects describing attached devices.
:param timeout: optional integer specifying the maximum time in
seconds for any spawned adb process to complete before
throwing an ADBTimeoutError. This timeout is per adb call. The
total tim... | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L296-L343 | null | class ADBB2G(adb.ADBDevice):
def __init__(self, *args, **kwargs):
if "wait_polling_interval" in kwargs:
self._wait_polling_interval = kwargs.pop("wait_polling_interval")
else:
self._wait_polling_interval = 1.0
adb.ADBDevice.__init__(self, *args, **kwargs)
def w... |
mozilla-b2g/fxos-certsuite | mcts/certsuite/wait.py | Wait.until | python | def until(self, condition, is_true=None, message=""):
rv = None
last_exc = None
until = is_true or until_pred
start = self.clock.now
while not until(self.clock, self.end):
try:
rv = condition()
except (KeyboardInterrupt, SystemExit) as e:... | Repeatedly runs condition until its return value evalutes to true,
or its timeout expires or the predicate evaluates to true.
This will poll at the given interval until the given timeout
is reached, or the predicate or conditions returns true. A
condition that returns null or does not ... | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/certsuite/wait.py#L78-L140 | null | class Wait(object):
"""An explicit conditional utility class for waiting until a condition
evalutes to true or not null.
This will repeatedly evaluate a condition in anticipation for a
truthy return value, or its timeout to expire, or its waiting
predicate to become true.
A ``Wait`` instance d... |
mozilla-b2g/fxos-certsuite | mcts/tools/webidl/process_idl.py | main | python | def main(argv):
argparser = argparse.ArgumentParser()
argparser.add_argument("manifest", help="Manifest file for the idl")
argparser.add_argument("b2g", help="Path to b2g directory (e.g. ~/B2G")
args = argparser.parse_args(argv[1:])
with open(args.manifest, 'r') as f:
manifest = json.loads... | This parses a json manifest file containing list of webidl files and
generates a file containing javascript arrays of json objects for
each webidl file.
usage: process_idl.py manifest.json ~/B2G
The generated js file can then be included with the test app. | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/tools/webidl/process_idl.py#L97-L158 | null | #!/usr/bin/python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import argparse
import json
import os
import re
import sys
# Map to types recognized by the idlharne... |
mozilla-b2g/fxos-certsuite | mcts/tools/webidl/manifest_parser.py | main | python | def main(argv):
argparser = argparse.ArgumentParser()
argparser.add_argument("gecko", help="/B2G/gecko/dom/webidl")
args = argparser.parse_args(argv[1:])
files = [ "gecko/dom/webidl/" + f for f in listdir(args.gecko) if isfile(join(args.gecko,f)) and f.endswith("webidl") ]
files.sort()
with o... | This will generate you a manifest file, and you need to modify it!
There are three category: files, untested, skipped.
You can reference current manifest.json.
usage: manifest_parser.py (GECKO LOCATION: /B2G/gecko/dom/webidl)
The generated file can then be used with process_idl.py | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/tools/webidl/manifest_parser.py#L15-L36 | null | #!/usr/bin/python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import argparse
import json
import re
import sys
from os import listdir
from os.path import isfile, ... |
mozilla-b2g/fxos-certsuite | mcts/certsuite/cert.py | run_marionette_script | python | def run_marionette_script(script, chrome=False, async=False, host='localhost', port=2828):
m = DeviceHelper.getMarionette(host, port)
m.start_session()
if chrome:
m.set_context(marionette.Marionette.CONTEXT_CHROME)
if not async:
result = m.execute_script(script)
else:
result ... | Create a Marionette instance and run the provided script | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/certsuite/cert.py#L520-L531 | [
"def getMarionette(host='localhost', port=2828):\n if not DeviceHelper.marionette:\n DeviceHelper.marionette = Marionette(host, port)\n\n return DeviceHelper.marionette\n"
] | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import argparse
import ConfigParser
import json
import logging
import os
import sys
import pkg_re... |
mozilla-b2g/fxos-certsuite | mcts/certsuite/cert.py | set_permission | python | def set_permission(permission, value, app):
# The object created to wrap PermissionSettingsModule is to work around
# an intermittent bug where it will sometimes be undefined.
script = """
const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
var a = {b: Cu.import("resource:/... | Set a permission for the specified app
Value should be 'deny' or 'allow' | train | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/certsuite/cert.py#L572-L590 | [
"def run_marionette_script(script, chrome=False, async=False, host='localhost', port=2828):\n \"\"\"Create a Marionette instance and run the provided script\"\"\"\n m = DeviceHelper.getMarionette(host, port)\n m.start_session()\n if chrome:\n m.set_context(marionette.Marionette.CONTEXT_CHROME)\n ... | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import argparse
import ConfigParser
import json
import logging
import os
import sys
import pkg_re... |
sixty-north/added-value | source/added_value/repr_role.py | make_repr_node | python | def make_repr_node(rawtext, app, prefixed_name, obj, parent, modname, options):
text = repr(obj)
node = nodes.Text(text, rawsource=rawtext)
return node | Render a Python object to text using the repr() function.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param prefixed_name: The dotted Python name for obj.
:param obj: The Python object to be rendered to text.
:param parent: The parent Python object of... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/repr_role.py#L6-L19 | null | from docutils import nodes
from added_value.pyobj_role import make_pyobj_role
repr_role = make_pyobj_role(make_repr_node)
|
sixty-north/added-value | docs/code/steel.py | Table.cells | python | def cells(self):
return {row_key: {column_key:cell for column_key, cell in zip(self._column_keys, cells)}
for row_key, cells in self._rows_mapping.items()} | A dictionary of dictionaries containing all cells. | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/docs/code/steel.py#L53-L57 | null | class Table:
def __init__(self, column_keys, rows_mapping):
self._column_keys = list(column_keys)
self._column_indexes = {key:index for index, key in enumerate(self._column_keys)}
num_columns = len(column_keys)
self._row_keys = list(rows_mapping.keys())
if not all(len(row)==... |
sixty-north/added-value | source/added_value/tabulator.py | tabulate_body | python | def tabulate_body(
obj,
level_keys,
v_level_indexes,
h_level_indexes,
v_level_sort_keys=None,
h_level_sort_keys=None,
):
v_key_sorted = make_sorter(v_level_sort_keys, v_level_indexes)
h_key_sorted = make_sorter(h_level_sort_keys, h_level_indexes)
h_level_keys = [level_keys[level] fo... | Args:
v_level_indexes: A sequence of level indexes.
h_level_indexes: A sequence of level indexes. | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/tabulator.py#L61-L105 | [
"def make_sorter(level_sort_keys, level_indexes):\n if level_sort_keys is not None:\n if len(level_sort_keys) != len(level_indexes):\n raise ValueError(\n \"level_sort_keys with length {} does not correspond to level_indexes with length {}\".format(\n len(level... | from collections import Mapping, deque
from itertools import product, chain, repeat
from added_value.items_table_directive import NonStringIterable
from added_value.multisort import tuplesorted
from added_value.sorted_frozen_set import SortedFrozenSet
from added_value.toposet import TopoSet
from added_value.util impor... |
sixty-north/added-value | source/added_value/tabulator.py | tabulate | python | def tabulate(
obj,
v_level_indexes=None,
h_level_indexes=None,
v_level_visibility=None,
h_level_visibility=None,
v_level_sort_keys=None,
h_level_sort_keys=None,
v_level_titles=None,
h_level_titles=None,
empty="",
):
level_keys = breadth_first(obj)
v_level_indexes, h_leve... | Render a nested data structure into a two-dimensional table.
Args:
obj: The indexable data structure to be rendered, which can
either be a non-string sequence or a mapping containing other
sequences and mappings nested to arbitrarily many levels,
with all the leaf items ... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/tabulator.py#L225-L335 | [
"def breadth_first(obj, leaves=False):\n queue = deque()\n queue.append(obj)\n queue.append(None)\n level_keys = []\n current_level_keys = TopoSet()\n while len(queue) > 0:\n node = queue.popleft()\n if node is None:\n level_keys.append(current_level_keys)\n cur... | from collections import Mapping, deque
from itertools import product, chain, repeat
from added_value.items_table_directive import NonStringIterable
from added_value.multisort import tuplesorted
from added_value.sorted_frozen_set import SortedFrozenSet
from added_value.toposet import TopoSet
from added_value.util impor... |
sixty-north/added-value | source/added_value/tabulator.py | validate_level_indexes | python | def validate_level_indexes(num_levels, v_level_indexes, h_level_indexes):
if num_levels < 1:
raise ValueError("num_levels {} is less than one".format(num_levels))
all_levels = SortedFrozenSet(range(num_levels))
if (h_level_indexes is None) and (v_level_indexes is None):
v_level_indexes = r... | Ensure that v_level_indexes and h_level_indexes are consistent.
Args:
num_levels: The number of levels of keys in the data structure being tabulated.
v_level_indexes: A sequence of level indexes between zero and num_levels for
the vertical axis, or None.
h_level_indexes: A seque... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/tabulator.py#L338-L399 | null | from collections import Mapping, deque
from itertools import product, chain, repeat
from added_value.items_table_directive import NonStringIterable
from added_value.multisort import tuplesorted
from added_value.sorted_frozen_set import SortedFrozenSet
from added_value.toposet import TopoSet
from added_value.util impor... |
sixty-north/added-value | source/added_value/tabulator.py | strip_hidden | python | def strip_hidden(key_tuples, visibilities):
result = []
for key_tuple in key_tuples:
if len(key_tuple) != len(visibilities):
raise ValueError(
"length of key tuple {} is not equal to length of visibilities {}".format(
key_tuple, visibilities
... | Filter each tuple according to visibility.
Args:
key_tuples: A sequence of tuples of equal length (i.e. rectangular)
visibilities: A sequence of booleans equal in length to the tuples contained in key_tuples.
Returns:
A sequence equal in length to key_tuples where the items are tuples ... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/tabulator.py#L402-L423 | null | from collections import Mapping, deque
from itertools import product, chain, repeat
from added_value.items_table_directive import NonStringIterable
from added_value.multisort import tuplesorted
from added_value.sorted_frozen_set import SortedFrozenSet
from added_value.toposet import TopoSet
from added_value.util impor... |
sixty-north/added-value | source/added_value/util.py | pairwise_longest | python | def pairwise_longest(iterable, fillvalue=None):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip_longest(a, b, fillvalue=fillvalue) | s -> (s0,s1), (s1,s2), (s2, s3), ... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/util.py#L19-L23 | null | from itertools import chain, repeat, islice, zip_longest, tee, groupby
def pad_infinite(iterable, padding=None):
return chain(iterable, repeat(padding))
def pad(iterable, size, padding=None):
return islice(pad_infinite(iterable, padding), size)
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3),... |
sixty-north/added-value | setup.py | read_version | python | def read_version():
"Read the `(version-string, version-info)` from `added_value/version.py`."
version_file = local_file('source', 'added_value', 'version.py')
local_vars = {}
with open(version_file) as handle:
exec(handle.read(), {}, local_vars) # pylint: disable=exec-used
return local_var... | Read the `(version-string, version-info)` from `added_value/version.py`. | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/setup.py#L25-L31 | [
"def local_file(*name):\n return os.path.join(\n os.path.dirname(__file__),\n *name)\n"
] | # -*- coding: utf-8 -*-
import os
import io
from setuptools import setup, find_packages
with open('README.rst', 'r') as readme:
long_description = readme.read()
def local_file(*name):
return os.path.join(
os.path.dirname(__file__),
*name)
def read(name, **kwargs):
with io.open(
... |
sixty-north/added-value | source/added_value/toposet.py | TopoSet.update | python | def update(self, iterable):
for pair in pairwise_longest(iterable, fillvalue=_FILL):
self._edges.append(pair)
self._results = None | Update with an ordered iterable of items.
Args:
iterable: An ordered iterable of items. The relative
order of the items in this iterable will be respected
in the TopoSet (in the absence of cycles). | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/toposet.py#L42-L52 | [
"def pairwise_longest(iterable, fillvalue=None):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return zip_longest(a, b, fillvalue=fillvalue)\n"
] | class TopoSet(MutableSet):
"""A topologically sorted set."""
def __init__(self, iterable=None):
self._results = None
self._edges = []
self._discarded = set()
if iterable is not None:
self.update(iterable)
def __len__(self):
return len(self._topo_sorted.s... |
sixty-north/added-value | source/added_value/pyobj_role.py | pyobj_role | python | def pyobj_role(make_node, name, rawtext, text, lineno, inliner, options=None, content=None):
if options is None:
options = {}
if content is None:
content = []
try:
prefixed_name, obj, parent, modname = import_by_name(text)
except ImportError:
msg = inliner.reporter.erro... | Include Python object value, rendering it to text using str.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param make_node: A callable which accepts (rawtext, app, prefixed_name, obj, parent, modname, options) a... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/pyobj_role.py#L10-L40 | null | from functools import partial
from sphinx.ext.autosummary import import_by_name
def make_pyobj_role(make_node):
return partial(pyobj_role, make_node)
|
sixty-north/added-value | source/added_value/toposort.py | topological_sort | python | def topological_sort(dependency_pairs):
"Sort values subject to dependency constraints"
num_heads = defaultdict(int) # num arrows pointing in
tails = defaultdict(list) # list of arrows going out
heads = [] # unique list of heads in order first seen
for h, t in dependency_pairs:
num_heads[... | Sort values subject to dependency constraints | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/toposort.py#L6-L26 | null | from collections import defaultdict, namedtuple
Results = namedtuple("Results", ["sorted", "cyclic"])
|
sixty-north/added-value | source/added_value/items_table_directive.py | ItemsTableDirective.interpret_obj | python | def interpret_obj(
self,
obj,
v_level_indexes,
h_level_indexes,
v_level_visibility,
h_level_visibility,
v_level_sort_keys,
h_level_sort_keys,
v_level_titles,
h_level_titles,
):
if not isinstance(obj, NonStringIterable):
... | Interpret the given Python object as a table.
Args:
obj: A sequence (later a mapping, too)
Returns:
A list of lists represents rows of cells.
Raises:
TypeError: If the type couldn't be interpreted as a table. | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/items_table_directive.py#L243-L282 | [
"def size(rows_of_columns):\n return size_v(rows_of_columns), size_h(rows_of_columns)\n",
"def tabulate(\n obj,\n v_level_indexes=None,\n h_level_indexes=None,\n v_level_visibility=None,\n h_level_visibility=None,\n v_level_sort_keys=None,\n h_level_sort_keys=None,\n v_level_titles=None... | class ItemsTableDirective(Directive):
"""Format a data structure as a table.
If the items of the sequence are themselves sequences, they will formatted as rows.
"""
required_arguments = 1
has_content = False
option_spec = {
TITLE_OPTION: unchanged_required,
HEADER_ROWS_OPTION: ... |
sixty-north/added-value | source/added_value/items_table_directive.py | ItemsTableDirective.augment_cells_no_span | python | def augment_cells_no_span(self, rows, source):
# TODO: Hardwired str transform.
# 4-tuple: morerows, morecols, offset, cellblock
# - morerows: The number of additional rows this cells spans
# - morecols: The number of additional columns this cell spans
# - offset: Offset from the... | Convert each cell into a tuple suitable for consumption by build_table. | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/items_table_directive.py#L300-L312 | null | class ItemsTableDirective(Directive):
"""Format a data structure as a table.
If the items of the sequence are themselves sequences, they will formatted as rows.
"""
required_arguments = 1
has_content = False
option_spec = {
TITLE_OPTION: unchanged_required,
HEADER_ROWS_OPTION: ... |
sixty-north/added-value | source/added_value/str_role.py | make_str_node | python | def make_str_node(rawtext, app, prefixed_name, obj, parent, modname, options):
text = str(obj)
node = nodes.Text(text, rawsource=rawtext)
return node | Render a Python object to text using the repr() function.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param prefixed_name: The dotted Python name for obj.
:param obj: The Python object to be rendered to text.
:param parent: The parent Python object of... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/str_role.py#L6-L19 | null | from docutils import nodes
from added_value.pyobj_role import make_pyobj_role
str_role = make_pyobj_role(make_str_node)
|
sixty-north/added-value | source/added_value/multisort.py | multisorted | python | def multisorted(items, *keys):
if len(keys) == 0:
keys = [asc()]
for key in reversed(keys):
items = sorted(items, key=key.func, reverse=key.reverse)
return items | Sort by multiple attributes.
Args:
items: An iterable series to be sorted.
*keys: Key objects which extract key values from the items.
The first key will be the most significant, and the
last key the least significant. If no key functions
are provided, the items ... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/multisort.py#L42-L59 | [
"def asc(func=identity):\n \"\"\"Obtain a key for ascending sort.\"\"\"\n return Key(func, reverse=False)\n"
] | from natsort import natsort_keygen
class Key(object):
def __init__(self, func, reverse=False):
self._func = func
self._reverse = reverse
@property
def func(self):
return self._func
@property
def reverse(self):
return self._reverse
def identity(x):
return x
... |
sixty-north/added-value | source/added_value/multisort.py | tuplesorted | python | def tuplesorted(items, *keys):
# Transform the keys so each works on one item of the tuple
tuple_keys = [
Key(func=lambda t, i=index, k=key: k.func(t[i]), reverse=key.reverse)
for index, key in enumerate(keys)
]
return multisorted(items, *tuple_keys) | Sort by tuples with a different key for each item.
Args:
items: An iterable series of sequences (typically tuples)
*keys: Key objects which transform individual elements of
each tuple into sort keys. The zeroth object
transforms the zeroth element of each tuple, the first
... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/multisort.py#L62-L81 | [
"def multisorted(items, *keys):\n \"\"\"Sort by multiple attributes.\n\n Args:\n items: An iterable series to be sorted.\n *keys: Key objects which extract key values from the items.\n The first key will be the most significant, and the\n last key the least significant. If ... | from natsort import natsort_keygen
class Key(object):
def __init__(self, func, reverse=False):
self._func = func
self._reverse = reverse
@property
def func(self):
return self._func
@property
def reverse(self):
return self._reverse
def identity(x):
return x
... |
sixty-north/added-value | source/added_value/format_role.py | format_role | python | def format_role(name, rawtext, text, lineno, inliner, options=None, content=None):
if options is None:
options = {}
if content is None:
content = []
name, _, format_spec = tuple(field.strip() for field in text.partition(","))
try:
prefixed_name, obj, parent, modname = import_b... | Include Python object value, rendering it to text using str.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param make_node: A callable which accepts (rawtext, app, prefixed_name, obj, parent, modname, options) a... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/format_role.py#L5-L47 | null | from docutils import nodes
from sphinx.ext.autosummary import import_by_name
|
sixty-north/added-value | source/added_value/any_items_role.py | make_any_items_node | python | def make_any_items_node(rawtext, app, prefixed_name, obj, parent, modname, options):
text = list_conjunction(obj, "or")
node = nodes.Text(text, rawsource=rawtext)
return node | Render a Python sequence as a comma-separated list, with an "or" for the final item.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param prefixed_name: The dotted Python name for obj.
:param obj: The Python object to be rendered to text.
:param parent: ... | train | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/any_items_role.py#L7-L20 | [
"def list_conjunction(sequence, word):\n if len(sequence) == 0:\n text = \"\"\n elif len(sequence) == 1:\n text = str(sequence)\n elif len(sequence) == 2:\n text = \"{!s} {} {!s}\".format(sequence[0], word, sequence[1])\n else:\n all_but_last = \", \".join(map(str, sequence[:... | from docutils import nodes
from added_value.grammatical_conjunctions import list_conjunction
from added_value.pyobj_role import make_pyobj_role
any_items_role = make_pyobj_role(make_any_items_node)
|
msiedlarek/wiring | wiring/interface.py | get_implemented_interfaces | python | def get_implemented_interfaces(cls):
if hasattr(cls, '__interfaces__'):
return cls.__interfaces__
return six.moves.reduce(
lambda x, y: x.union(y),
map(
get_implemented_interfaces,
inspect.getmro(cls)[1:]
),
set()
) | Returns a set of :term:`interfaces <interface>` declared as implemented by
class `cls`. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/interface.py#L287-L301 | null | import collections
import inspect
import operator
import six
__all__ = (
'InterfaceComplianceError',
'MissingAttributeError',
'MethodValidationError',
'Attribute',
'Method',
'Interface',
'get_implemented_interfaces',
'set_implemented_interfaces',
'add_implemented_interfaces',
... |
msiedlarek/wiring | wiring/interface.py | set_implemented_interfaces | python | def set_implemented_interfaces(cls, interfaces):
setattr(
cls,
'__interfaces__',
frozenset(
six.moves.reduce(
lambda x, y: x.union(y),
map(operator.attrgetter('implied'), interfaces),
set()
)
)
) | Declares :term:`interfaces <interface>` as implemented by class `cls`.
Those already declared are overriden. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/interface.py#L304-L319 | null | import collections
import inspect
import operator
import six
__all__ = (
'InterfaceComplianceError',
'MissingAttributeError',
'MethodValidationError',
'Attribute',
'Method',
'Interface',
'get_implemented_interfaces',
'set_implemented_interfaces',
'add_implemented_interfaces',
... |
msiedlarek/wiring | wiring/interface.py | add_implemented_interfaces | python | def add_implemented_interfaces(cls, interfaces):
implemented = set(
six.moves.reduce(
lambda x, y: x.union(y),
map(operator.attrgetter('implied'), interfaces),
set()
)
)
implemented.update(*map(
get_implemented_interfaces,
inspect.getmro(cl... | Adds :term:`interfaces <interface>` to those already declared as
implemented by class `cls`. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/interface.py#L322-L338 | null | import collections
import inspect
import operator
import six
__all__ = (
'InterfaceComplianceError',
'MissingAttributeError',
'MethodValidationError',
'Attribute',
'Method',
'Interface',
'get_implemented_interfaces',
'set_implemented_interfaces',
'add_implemented_interfaces',
... |
msiedlarek/wiring | wiring/interface.py | isimplementation | python | def isimplementation(obj, interfaces):
if not inspect.isclass(obj):
isimplementation(obj.__class__, interfaces)
if not isinstance(interfaces, collections.Iterable):
interfaces = [interfaces]
return frozenset(interfaces).issubset(
get_implemented_interfaces(obj)
) | Returns `True` if `obj` is a class implementing all of `interfaces` or an
instance of such class.
`interfaces` can be a single :term:`interface` class or an iterable of
interface classes. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/interface.py#L364-L378 | [
"def get_implemented_interfaces(cls):\n \"\"\"\n Returns a set of :term:`interfaces <interface>` declared as implemented by\n class `cls`.\n \"\"\"\n if hasattr(cls, '__interfaces__'):\n return cls.__interfaces__\n return six.moves.reduce(\n lambda x, y: x.union(y),\n map(\n ... | import collections
import inspect
import operator
import six
__all__ = (
'InterfaceComplianceError',
'MissingAttributeError',
'MethodValidationError',
'Attribute',
'Method',
'Interface',
'get_implemented_interfaces',
'set_implemented_interfaces',
'add_implemented_interfaces',
... |
msiedlarek/wiring | wiring/interface.py | Method.check_compliance | python | def check_compliance(self, function):
argument_specification = _get_argument_specification(function)
if inspect.ismethod(function):
# Remove implied `self` argument from specification if function is
# a method.
argument_specification = argument_specification._replace(... | Checks if a given `function` complies with this specification. If an
inconsistency is detected a :py:exc:`MethodValidationError` exception
is raised.
.. note::
This method will not work as expected when `function` is an unbound
method (``SomeClass.some_method``), as in P... | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/interface.py#L124-L151 | null | class Method(Attribute):
"""
This class stores a specification of a method, describing its arguments and
holding its docstring. It is used by :py:class:`InterfaceMetaclass` to
store information about required methods of an :term:`interface`.
"""
def __init__(self, argument_specification, docstr... |
msiedlarek/wiring | wiring/graph.py | Graph.acquire | python | def acquire(self, specification, arguments=None):
if arguments is None:
realized_dependencies = {}
else:
realized_dependencies = copy.copy(arguments)
provider = self.providers[specification]
scope = None
if provider.scope is not None:
try:
... | Returns an object for `specification` injecting its provider
with a mix of its :term:`dependencies <dependency>` and given
`arguments`. If there is a conflict between the injectable
dependencies and `arguments`, the value from `arguments` is
used.
When one of `arguments` keys is... | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/graph.py#L150-L222 | [
"def acquire(self, specification, arguments=None):\n \"\"\"\n Returns an object for `specification` injecting its provider\n with a mix of its :term:`dependencies <dependency>` and given\n `arguments`. If there is a conflict between the injectable\n dependencies and `arguments`, the value from `argum... | class Graph(object):
"""
Respresents an :term:`object graph`. Contains registered scopes and
providers, and can be used to validate and resolve provider dependencies
and creating provided objects.
"""
class FactoryProxy(object):
"""
A proxy object injected when `Factory(<specifi... |
msiedlarek/wiring | wiring/graph.py | Graph.get | python | def get(self, specification, *args, **kwargs):
arguments = dict(enumerate(args))
arguments.update(kwargs)
return self.acquire(specification, arguments=arguments) | A more convenient version of :py:meth:`acquire()` for when you can
provide positional arguments in a right order. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/graph.py#L224-L231 | [
"def acquire(self, specification, arguments=None):\n \"\"\"\n Returns an object for `specification` injecting its provider\n with a mix of its :term:`dependencies <dependency>` and given\n `arguments`. If there is a conflict between the injectable\n dependencies and `arguments`, the value from `argum... | class Graph(object):
"""
Respresents an :term:`object graph`. Contains registered scopes and
providers, and can be used to validate and resolve provider dependencies
and creating provided objects.
"""
class FactoryProxy(object):
"""
A proxy object injected when `Factory(<specifi... |
msiedlarek/wiring | wiring/graph.py | Graph.register_provider | python | def register_provider(self, specification, provider):
if provider.scope is not None and provider.scope not in self.scopes:
raise UnknownScopeError(provider.scope)
self.providers[specification] = provider | Registers a :term:`provider` (a :py:class:`wiring.providers.Provider`
instance) to be called when an object specified by
:term:`specification` is needed. If there was already a provider for
this specification it is overriden. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/graph.py#L233-L242 | null | class Graph(object):
"""
Respresents an :term:`object graph`. Contains registered scopes and
providers, and can be used to validate and resolve provider dependencies
and creating provided objects.
"""
class FactoryProxy(object):
"""
A proxy object injected when `Factory(<specifi... |
msiedlarek/wiring | wiring/graph.py | Graph.register_factory | python | def register_factory(self, specification, factory, scope=None):
self.register_provider(
specification,
FactoryProvider(factory, scope=scope)
) | Shortcut for creating and registering
a :py:class:`wiring.providers.FactoryProvider`. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/graph.py#L250-L258 | [
"def register_provider(self, specification, provider):\n \"\"\"\n Registers a :term:`provider` (a :py:class:`wiring.providers.Provider`\n instance) to be called when an object specified by\n :term:`specification` is needed. If there was already a provider for\n this specification it is overriden.\n ... | class Graph(object):
"""
Respresents an :term:`object graph`. Contains registered scopes and
providers, and can be used to validate and resolve provider dependencies
and creating provided objects.
"""
class FactoryProxy(object):
"""
A proxy object injected when `Factory(<specifi... |
msiedlarek/wiring | wiring/graph.py | Graph.register_function | python | def register_function(self, specification, function, scope=None):
self.register_provider(
specification,
FunctionProvider(function, scope=scope)
) | Shortcut for creating and registering
a :py:class:`wiring.providers.FunctionProvider`. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/graph.py#L260-L268 | [
"def register_provider(self, specification, provider):\n \"\"\"\n Registers a :term:`provider` (a :py:class:`wiring.providers.Provider`\n instance) to be called when an object specified by\n :term:`specification` is needed. If there was already a provider for\n this specification it is overriden.\n ... | class Graph(object):
"""
Respresents an :term:`object graph`. Contains registered scopes and
providers, and can be used to validate and resolve provider dependencies
and creating provided objects.
"""
class FactoryProxy(object):
"""
A proxy object injected when `Factory(<specifi... |
msiedlarek/wiring | wiring/graph.py | Graph.validate | python | def validate(self):
# This method uses Tarjan's strongly connected components algorithm
# with added self-dependency check to find dependency cyclces.
# Index is just an integer, it's wrapped in a list as a workaround for
# Python 2's lack of `nonlocal` keyword, so the nested
# ... | Asserts that every declared :term:`specification` can actually be
realized, meaning that all of its :term:`dependencies <dependency>` are
present and there are no self-dependencies or :term:`dependency cycles
<dependency cycle>`. If such a problem is found, a proper exception
(deriving f... | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/graph.py#L291-L356 | [
"def strongconnect(specification):\n # Set the depth index for the node to the smallest unused index.\n indices[specification] = index[0]\n lowlinks[specification] = index[0]\n index[0] += 1\n stack.append(specification)\n provider = self.providers[specification]\n dependencies = six.itervalues... | class Graph(object):
"""
Respresents an :term:`object graph`. Contains registered scopes and
providers, and can be used to validate and resolve provider dependencies
and creating provided objects.
"""
class FactoryProxy(object):
"""
A proxy object injected when `Factory(<specifi... |
msiedlarek/wiring | wiring/scanning/register.py | register | python | def register(provider_factory, *args, **kwargs):
def decorator(target):
def callback(scanner, name, target):
if not args:
specification = target
elif len(args) == 1:
specification = args[0]
else:
specification = tuple(args)
... | Returns a decorator that registers its arguments for scanning, so it can be
picked up by :py:func:`wiring.scanning.scan.scan`.
First argument - `provider_factory` - is a callable that is invoked during
scanning with decorated argument and `kwargs` as arguments, and it should
return a :term:`provider` t... | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/scanning/register.py#L14-L63 | null | import venusian
from wiring import FactoryProvider, FunctionProvider, InstanceProvider
WIRING_VENUSIAN_CATEGORY = 'wiring'
"""
A `Venusian`_ category under which all Wiring callbacks are registered.
.. _Venusian: https://pypi.python.org/pypi/venusian
"""
def factory(*args, **kwargs):
"""
A shortcut for u... |
msiedlarek/wiring | wiring/dependency.py | get_dependencies | python | def get_dependencies(factory):
if inspect.isclass(factory):
# If factory is a class we want to check constructor depdendencies.
if six.PY3:
init_check = inspect.isfunction
else:
init_check = inspect.ismethod
dependencies = {}
if hasattr(factory, '__ini... | This function inspects a function to find its arguments marked for
injection, either with :py:func:`inject()` decorator,
:py:class:`UnrealizedInjection` class of through Python 3 function
annotations. If `factory` is a class, then its constructor is inspected.
Returned dictionary is a mapping of::
... | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/dependency.py#L177-L249 | null | import inspect
import six
__all__ = (
'Factory',
'UnrealizedInjection',
'get_dependencies',
'inject',
'injected',
)
class Factory(tuple):
"""
This class is a wrapper for a specification, declaring that instead of
a created object for the specification, a callable returning the objec... |
msiedlarek/wiring | wiring/dependency.py | inject | python | def inject(*positional_dependencies, **keyword_dependencies):
def decorator(function):
dependencies = get_dependencies(function)
def process_dependency_tuples(tuples):
for key, dependency_description in tuples:
if dependency_description is None:
speci... | This decorator can be used to specify injection rules for decorated
function arguments. Each argument to this decorator should be
a :term:`specification` for injecting into related argument of decorated
function. `None` can be given instead of a specification to prevent
argument from being injected. Th... | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/dependency.py#L252-L299 | null | import inspect
import six
__all__ = (
'Factory',
'UnrealizedInjection',
'get_dependencies',
'inject',
'injected',
)
class Factory(tuple):
"""
This class is a wrapper for a specification, declaring that instead of
a created object for the specification, a callable returning the objec... |
msiedlarek/wiring | wiring/configuration.py | provides | python | def provides(*specification):
if len(specification) == 1:
specification = specification[0]
else:
specification = tuple(specification)
def decorator(function):
function.__provides__ = specification
return function
return decorator | Decorator marking wrapped :py:class:`Module` method as :term:`provider` for
given :term:`specification`.
For example::
class ApplicationModule(Module):
@provides('db_connection')
def provide_db_connection(self):
return DBConnection(host='localhost') | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/configuration.py#L249-L271 | null | import collections
import inspect
import six
from wiring.providers import (
FactoryProvider,
FunctionProvider,
InstanceProvider
)
__all__ = (
'InvalidConfigurationError',
'Module',
'provides',
'scope',
)
class InvalidConfigurationError(Exception):
"""
Raised when there is some ... |
msiedlarek/wiring | wiring/scanning/scan.py | scan_to_module | python | def scan_to_module(python_modules, module, ignore=tuple()):
def callback(specification, provider):
module.providers[specification] = provider
scan(python_modules, callback, ignore=ignore) | Scans `python_modules` with :py:func:`scan` and adds found providers
to `module`'s :py:attr:`wiring.configuration.Module.providers`.
`ignore` argument is passed through to :py:func:`scan`. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/scanning/scan.py#L16-L25 | [
"def scan(python_modules, callback, ignore=tuple()):\n \"\"\"\n Recursively scans `python_modules` for providers registered with\n :py:mod:`wiring.scanning.register` module and for each one calls `callback`\n with :term:`specification` as the first argument, and the provider object\n as the second.\n... | import importlib
import six
import venusian
from wiring.scanning.register import WIRING_VENUSIAN_CATEGORY
__all__ = (
'scan_to_module',
'scan_to_graph',
'scan',
)
def scan_to_graph(python_modules, graph, ignore=tuple()):
"""
Scans `python_modules` with :py:func:`scan` and registers found prov... |
msiedlarek/wiring | wiring/scanning/scan.py | scan_to_graph | python | def scan_to_graph(python_modules, graph, ignore=tuple()):
def callback(specification, provider):
graph.register_provider(specification, provider)
scan(python_modules, callback, ignore=ignore) | Scans `python_modules` with :py:func:`scan` and registers found providers
in `graph`.
`ignore` argument is passed through to :py:func:`scan`. | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/scanning/scan.py#L28-L37 | [
"def scan(python_modules, callback, ignore=tuple()):\n \"\"\"\n Recursively scans `python_modules` for providers registered with\n :py:mod:`wiring.scanning.register` module and for each one calls `callback`\n with :term:`specification` as the first argument, and the provider object\n as the second.\n... | import importlib
import six
import venusian
from wiring.scanning.register import WIRING_VENUSIAN_CATEGORY
__all__ = (
'scan_to_module',
'scan_to_graph',
'scan',
)
def scan_to_module(python_modules, module, ignore=tuple()):
"""
Scans `python_modules` with :py:func:`scan` and adds found provider... |
msiedlarek/wiring | wiring/scanning/scan.py | scan | python | def scan(python_modules, callback, ignore=tuple()):
scanner = venusian.Scanner(callback=callback)
for python_module in python_modules:
if isinstance(python_module, six.string_types):
python_module = importlib.import_module(python_module)
scanner.scan(
python_module,
... | Recursively scans `python_modules` for providers registered with
:py:mod:`wiring.scanning.register` module and for each one calls `callback`
with :term:`specification` as the first argument, and the provider object
as the second.
Each element in `python_modules` may be a module reference or a string
... | train | https://github.com/msiedlarek/wiring/blob/c32165b680356fe9f1e422a1d11127f867065f94/wiring/scanning/scan.py#L40-L60 | null | import importlib
import six
import venusian
from wiring.scanning.register import WIRING_VENUSIAN_CATEGORY
__all__ = (
'scan_to_module',
'scan_to_graph',
'scan',
)
def scan_to_module(python_modules, module, ignore=tuple()):
"""
Scans `python_modules` with :py:func:`scan` and adds found provider... |
invoice-x/invoice2data | src/invoice2data/input/tesseract4.py | to_text | python | def to_text(path, language='fra'):
import subprocess
from distutils import spawn
import tempfile
import time
# Check for dependencies. Needs Tesseract and Imagemagick installed.
if not spawn.find_executable('tesseract'):
raise EnvironmentError('tesseract not installed.')
if not spaw... | Wraps Tesseract 4 OCR with custom language model.
Parameters
----------
path : str
path of electronic invoice in JPG or PNG format
Returns
-------
extracted_str : str
returns extracted text from image in JPG or PNG format | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/tesseract4.py#L2-L69 | null | # -*- coding: utf-8 -*-
|
invoice-x/invoice2data | src/invoice2data/input/gvision.py | to_text | python | def to_text(path, bucket_name='cloud-vision-84893', language='fr'):
"""OCR with PDF/TIFF as source files on GCS"""
import os
from google.cloud import vision
from google.cloud import storage
from google.protobuf import json_format
# Supported mime_types are: 'application/pdf' and 'image/tiff'
... | Sends PDF files to Google Cloud Vision for OCR.
Before using invoice2data, make sure you have the auth json path set as
env var GOOGLE_APPLICATION_CREDENTIALS
Parameters
----------
path : str
path of electronic invoice in JPG or PNG format
bucket_name : str
name of bucket to us... | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/gvision.py#L2-L83 | null | # -*- coding: utf-8 -*-
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.