repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
misakar/mana
mana/mana.py
admin
def admin(module): """add sql modules into admin site""" # add module into admin site app = os.getcwd().split('/')[-1] if app != 'app': logger.warning('''\033[31m{Warning}\033[0m ==> your current path is \033[32m%s\033[0m\n ==> please add your sql module under app folder!''' % os.getcwd()) ...
python
def admin(module): """add sql modules into admin site""" # add module into admin site app = os.getcwd().split('/')[-1] if app != 'app': logger.warning('''\033[31m{Warning}\033[0m ==> your current path is \033[32m%s\033[0m\n ==> please add your sql module under app folder!''' % os.getcwd()) ...
[ "def", "admin", "(", "module", ")", ":", "# add module into admin site", "app", "=", "os", ".", "getcwd", "(", ")", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "app", "!=", "'app'", ":", "logger", ".", "warning", "(", "'''\\033[31m{Warning...
add sql modules into admin site
[ "add", "sql", "modules", "into", "admin", "site" ]
train
https://github.com/misakar/mana/blob/95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69/mana/mana.py#L332-L354
misakar/mana
mana/operators/_mkdir_p.py
_mkdir_p
def _mkdir_p(abspath): """ Usage: create the abspath except the abspath exist Param: abspath: the absolutly path you want to be created """ try: os.makedirs(abspath) except OSError as e: if (e.errno == errno.EEXIST) and (os.path.isdir(abspath)): ...
python
def _mkdir_p(abspath): """ Usage: create the abspath except the abspath exist Param: abspath: the absolutly path you want to be created """ try: os.makedirs(abspath) except OSError as e: if (e.errno == errno.EEXIST) and (os.path.isdir(abspath)): ...
[ "def", "_mkdir_p", "(", "abspath", ")", ":", "try", ":", "os", ".", "makedirs", "(", "abspath", ")", "except", "OSError", "as", "e", ":", "if", "(", "e", ".", "errno", "==", "errno", ".", "EEXIST", ")", "and", "(", "os", ".", "path", ".", "isdir"...
Usage: create the abspath except the abspath exist Param: abspath: the absolutly path you want to be created
[ "Usage", ":", "create", "the", "abspath", "except", "the", "abspath", "exist" ]
train
https://github.com/misakar/mana/blob/95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69/mana/operators/_mkdir_p.py#L22-L36
bachya/pyairvisual
pyairvisual/errors.py
raise_error
def raise_error(error_type: str) -> None: """Raise the appropriate error based on error message.""" try: error = next((v for k, v in ERROR_CODES.items() if k in error_type)) except StopIteration: error = AirVisualError raise error(error_type)
python
def raise_error(error_type: str) -> None: """Raise the appropriate error based on error message.""" try: error = next((v for k, v in ERROR_CODES.items() if k in error_type)) except StopIteration: error = AirVisualError raise error(error_type)
[ "def", "raise_error", "(", "error_type", ":", "str", ")", "->", "None", ":", "try", ":", "error", "=", "next", "(", "(", "v", "for", "k", ",", "v", "in", "ERROR_CODES", ".", "items", "(", ")", "if", "k", "in", "error_type", ")", ")", "except", "S...
Raise the appropriate error based on error message.
[ "Raise", "the", "appropriate", "error", "based", "on", "error", "message", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/errors.py#L63-L69
bachya/pyairvisual
pyairvisual/client.py
_raise_on_error
def _raise_on_error(data: Union[str, dict]) -> None: """Raise the appropriate exception on error.""" if isinstance(data, str): raise_error(data) elif 'status' in data and data['status'] != 'success': raise_error(data['data']['message'])
python
def _raise_on_error(data: Union[str, dict]) -> None: """Raise the appropriate exception on error.""" if isinstance(data, str): raise_error(data) elif 'status' in data and data['status'] != 'success': raise_error(data['data']['message'])
[ "def", "_raise_on_error", "(", "data", ":", "Union", "[", "str", ",", "dict", "]", ")", "->", "None", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "raise_error", "(", "data", ")", "elif", "'status'", "in", "data", "and", "data", "[", ...
Raise the appropriate exception on error.
[ "Raise", "the", "appropriate", "exception", "on", "error", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/client.py#L53-L58
bachya/pyairvisual
pyairvisual/client.py
Client.request
async def request( self, method: str, endpoint: str, *, base_url: str = API_URL_SCAFFOLD, headers: dict = None, params: dict = None, json: dict = None) -> dict: """Make a request against AirVisual.""" if not ...
python
async def request( self, method: str, endpoint: str, *, base_url: str = API_URL_SCAFFOLD, headers: dict = None, params: dict = None, json: dict = None) -> dict: """Make a request against AirVisual.""" if not ...
[ "async", "def", "request", "(", "self", ",", "method", ":", "str", ",", "endpoint", ":", "str", ",", "*", ",", "base_url", ":", "str", "=", "API_URL_SCAFFOLD", ",", "headers", ":", "dict", "=", "None", ",", "params", ":", "dict", "=", "None", ",", ...
Make a request against AirVisual.
[ "Make", "a", "request", "against", "AirVisual", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/client.py#L25-L50
bachya/pyairvisual
example.py
main
async def main() -> None: # pylint: disable=too-many-statements """Create the aiohttp session and run the example.""" logging.basicConfig(level=logging.INFO) async with ClientSession() as websession: client = Client(websession, api_key='<API KEY>') # Get supported locations (by location): ...
python
async def main() -> None: # pylint: disable=too-many-statements """Create the aiohttp session and run the example.""" logging.basicConfig(level=logging.INFO) async with ClientSession() as websession: client = Client(websession, api_key='<API KEY>') # Get supported locations (by location): ...
[ "async", "def", "main", "(", ")", "->", "None", ":", "# pylint: disable=too-many-statements", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ")", "async", "with", "ClientSession", "(", ")", "as", "websession", ":", "client", "=", "...
Create the aiohttp session and run the example.
[ "Create", "the", "aiohttp", "session", "and", "run", "the", "example", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/example.py#L13-L87
bachya/pyairvisual
pyairvisual/api.py
API._nearest
async def _nearest( self, kind: str, latitude: Union[float, str] = None, longitude: Union[float, str] = None) -> dict: """Return data from nearest city/station (IP or coordinates).""" params = {} if latitude and longitude: params.update...
python
async def _nearest( self, kind: str, latitude: Union[float, str] = None, longitude: Union[float, str] = None) -> dict: """Return data from nearest city/station (IP or coordinates).""" params = {} if latitude and longitude: params.update...
[ "async", "def", "_nearest", "(", "self", ",", "kind", ":", "str", ",", "latitude", ":", "Union", "[", "float", ",", "str", "]", "=", "None", ",", "longitude", ":", "Union", "[", "float", ",", "str", "]", "=", "None", ")", "->", "dict", ":", "para...
Return data from nearest city/station (IP or coordinates).
[ "Return", "data", "from", "nearest", "city", "/", "station", "(", "IP", "or", "coordinates", ")", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/api.py#L14-L26
bachya/pyairvisual
pyairvisual/api.py
API.city
async def city(self, city: str, state: str, country: str) -> dict: """Return data for the specified city.""" data = await self._request( 'get', 'city', params={ 'city': city, 'state': state, 'country': country ...
python
async def city(self, city: str, state: str, country: str) -> dict: """Return data for the specified city.""" data = await self._request( 'get', 'city', params={ 'city': city, 'state': state, 'country': country ...
[ "async", "def", "city", "(", "self", ",", "city", ":", "str", ",", "state", ":", "str", ",", "country", ":", "str", ")", "->", "dict", ":", "data", "=", "await", "self", ".", "_request", "(", "'get'", ",", "'city'", ",", "params", "=", "{", "'cit...
Return data for the specified city.
[ "Return", "data", "for", "the", "specified", "city", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/api.py#L28-L38
bachya/pyairvisual
pyairvisual/api.py
API.nearest_city
async def nearest_city( self, latitude: Union[float, str] = None, longitude: Union[float, str] = None) -> dict: """Return data from nearest city (IP or coordinates).""" return await self._nearest('city', latitude, longitude)
python
async def nearest_city( self, latitude: Union[float, str] = None, longitude: Union[float, str] = None) -> dict: """Return data from nearest city (IP or coordinates).""" return await self._nearest('city', latitude, longitude)
[ "async", "def", "nearest_city", "(", "self", ",", "latitude", ":", "Union", "[", "float", ",", "str", "]", "=", "None", ",", "longitude", ":", "Union", "[", "float", ",", "str", "]", "=", "None", ")", "->", "dict", ":", "return", "await", "self", "...
Return data from nearest city (IP or coordinates).
[ "Return", "data", "from", "nearest", "city", "(", "IP", "or", "coordinates", ")", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/api.py#L40-L45
bachya/pyairvisual
pyairvisual/api.py
API.node
async def node(self, node_id: str) -> dict: """Return data from a node by its ID.""" return await self._request('get', node_id, base_url=NODE_URL_SCAFFOLD)
python
async def node(self, node_id: str) -> dict: """Return data from a node by its ID.""" return await self._request('get', node_id, base_url=NODE_URL_SCAFFOLD)
[ "async", "def", "node", "(", "self", ",", "node_id", ":", "str", ")", "->", "dict", ":", "return", "await", "self", ".", "_request", "(", "'get'", ",", "node_id", ",", "base_url", "=", "NODE_URL_SCAFFOLD", ")" ]
Return data from a node by its ID.
[ "Return", "data", "from", "a", "node", "by", "its", "ID", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/api.py#L54-L56
bachya/pyairvisual
pyairvisual/supported.py
Supported.cities
async def cities(self, country: str, state: str) -> list: """Return a list of supported cities in a country/state.""" data = await self._request( 'get', 'cities', params={ 'state': state, 'country': country }) return [d['city'] for d in dat...
python
async def cities(self, country: str, state: str) -> list: """Return a list of supported cities in a country/state.""" data = await self._request( 'get', 'cities', params={ 'state': state, 'country': country }) return [d['city'] for d in dat...
[ "async", "def", "cities", "(", "self", ",", "country", ":", "str", ",", "state", ":", "str", ")", "->", "list", ":", "data", "=", "await", "self", ".", "_request", "(", "'get'", ",", "'cities'", ",", "params", "=", "{", "'state'", ":", "state", ","...
Return a list of supported cities in a country/state.
[ "Return", "a", "list", "of", "supported", "cities", "in", "a", "country", "/", "state", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/supported.py#L12-L19
bachya/pyairvisual
pyairvisual/supported.py
Supported.states
async def states(self, country: str) -> list: """Return a list of supported states in a country.""" data = await self._request( 'get', 'states', params={'country': country}) return [d['state'] for d in data['data']]
python
async def states(self, country: str) -> list: """Return a list of supported states in a country.""" data = await self._request( 'get', 'states', params={'country': country}) return [d['state'] for d in data['data']]
[ "async", "def", "states", "(", "self", ",", "country", ":", "str", ")", "->", "list", ":", "data", "=", "await", "self", ".", "_request", "(", "'get'", ",", "'states'", ",", "params", "=", "{", "'country'", ":", "country", "}", ")", "return", "[", ...
Return a list of supported states in a country.
[ "Return", "a", "list", "of", "supported", "states", "in", "a", "country", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/supported.py#L26-L30
bachya/pyairvisual
pyairvisual/supported.py
Supported.stations
async def stations(self, city: str, state: str, country: str) -> list: """Return a list of supported stations in a city.""" data = await self._request( 'get', 'stations', params={ 'city': city, 'state': state, 'country':...
python
async def stations(self, city: str, state: str, country: str) -> list: """Return a list of supported stations in a city.""" data = await self._request( 'get', 'stations', params={ 'city': city, 'state': state, 'country':...
[ "async", "def", "stations", "(", "self", ",", "city", ":", "str", ",", "state", ":", "str", ",", "country", ":", "str", ")", "->", "list", ":", "data", "=", "await", "self", ".", "_request", "(", "'get'", ",", "'stations'", ",", "params", "=", "{",...
Return a list of supported stations in a city.
[ "Return", "a", "list", "of", "supported", "stations", "in", "a", "city", "." ]
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/supported.py#L32-L42
ljcooke/see
see/output.py
column_width
def column_width(tokens): """ Return a suitable column width to display one or more strings. """ get_len = tools.display_len if PY3 else len lens = sorted(map(get_len, tokens or [])) or [0] width = lens[-1] # adjust for disproportionately long strings if width >= 18: most = lens...
python
def column_width(tokens): """ Return a suitable column width to display one or more strings. """ get_len = tools.display_len if PY3 else len lens = sorted(map(get_len, tokens or [])) or [0] width = lens[-1] # adjust for disproportionately long strings if width >= 18: most = lens...
[ "def", "column_width", "(", "tokens", ")", ":", "get_len", "=", "tools", ".", "display_len", "if", "PY3", "else", "len", "lens", "=", "sorted", "(", "map", "(", "get_len", ",", "tokens", "or", "[", "]", ")", ")", "or", "[", "0", "]", "width", "=", ...
Return a suitable column width to display one or more strings.
[ "Return", "a", "suitable", "column", "width", "to", "display", "one", "or", "more", "strings", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L117-L131
ljcooke/see
see/output.py
justify_token
def justify_token(tok, col_width): """ Justify a string to fill one or more columns. """ get_len = tools.display_len if PY3 else len tok_len = get_len(tok) diff_len = tok_len - len(tok) if PY3 else 0 cols = (int(math.ceil(float(tok_len) / col_width)) if col_width < tok_len + 4 e...
python
def justify_token(tok, col_width): """ Justify a string to fill one or more columns. """ get_len = tools.display_len if PY3 else len tok_len = get_len(tok) diff_len = tok_len - len(tok) if PY3 else 0 cols = (int(math.ceil(float(tok_len) / col_width)) if col_width < tok_len + 4 e...
[ "def", "justify_token", "(", "tok", ",", "col_width", ")", ":", "get_len", "=", "tools", ".", "display_len", "if", "PY3", "else", "len", "tok_len", "=", "get_len", "(", "tok", ")", "diff_len", "=", "tok_len", "-", "len", "(", "tok", ")", "if", "PY3", ...
Justify a string to fill one or more columns.
[ "Justify", "a", "string", "to", "fill", "one", "or", "more", "columns", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L134-L148
ljcooke/see
see/output.py
display_name
def display_name(name, obj, local): """ Get the display name of an object. Keyword arguments (all required): * ``name`` -- the name of the object as a string. * ``obj`` -- the object itself. * ``local`` -- a boolean value indicating whether the object is in local scope or owned by an obj...
python
def display_name(name, obj, local): """ Get the display name of an object. Keyword arguments (all required): * ``name`` -- the name of the object as a string. * ``obj`` -- the object itself. * ``local`` -- a boolean value indicating whether the object is in local scope or owned by an obj...
[ "def", "display_name", "(", "name", ",", "obj", ",", "local", ")", ":", "prefix", "=", "''", "if", "local", "else", "'.'", "if", "isinstance", "(", "obj", ",", "SeeError", ")", ":", "suffix", "=", "'?'", "elif", "hasattr", "(", "obj", ",", "'__call__...
Get the display name of an object. Keyword arguments (all required): * ``name`` -- the name of the object as a string. * ``obj`` -- the object itself. * ``local`` -- a boolean value indicating whether the object is in local scope or owned by an object.
[ "Get", "the", "display", "name", "of", "an", "object", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L151-L172
ljcooke/see
see/output.py
SeeResult.filter
def filter(self, pattern): """ Filter the results using a pattern. This accepts a shell-style wildcard pattern (as used by the fnmatch_ module):: >>> see([]).filter('*op*') .copy() .pop() It also accepts a regular expression. This may be a compil...
python
def filter(self, pattern): """ Filter the results using a pattern. This accepts a shell-style wildcard pattern (as used by the fnmatch_ module):: >>> see([]).filter('*op*') .copy() .pop() It also accepts a regular expression. This may be a compil...
[ "def", "filter", "(", "self", ",", "pattern", ")", ":", "if", "isinstance", "(", "pattern", ",", "REGEX_TYPE", ")", ":", "func", "=", "tools", ".", "filter_regex", "elif", "pattern", ".", "startswith", "(", "'/'", ")", ":", "pattern", "=", "re", ".", ...
Filter the results using a pattern. This accepts a shell-style wildcard pattern (as used by the fnmatch_ module):: >>> see([]).filter('*op*') .copy() .pop() It also accepts a regular expression. This may be a compiled regular expression (from the re_ mod...
[ "Filter", "the", "results", "using", "a", "pattern", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L62-L90
ljcooke/see
see/output.py
SeeResult.filter_ignoring_case
def filter_ignoring_case(self, pattern): """ Like ``filter`` but case-insensitive. Expects a regular expression string without the surrounding ``/`` characters. >>> see().filter('^my', ignore_case=True) MyClass() """ return self.filter(re.co...
python
def filter_ignoring_case(self, pattern): """ Like ``filter`` but case-insensitive. Expects a regular expression string without the surrounding ``/`` characters. >>> see().filter('^my', ignore_case=True) MyClass() """ return self.filter(re.co...
[ "def", "filter_ignoring_case", "(", "self", ",", "pattern", ")", ":", "return", "self", ".", "filter", "(", "re", ".", "compile", "(", "pattern", ",", "re", ".", "I", ")", ")" ]
Like ``filter`` but case-insensitive. Expects a regular expression string without the surrounding ``/`` characters. >>> see().filter('^my', ignore_case=True) MyClass()
[ "Like", "filter", "but", "case", "-", "insensitive", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L92-L103
ljcooke/see
see/term.py
term_width
def term_width(): """ Return the column width of the terminal, or ``None`` if it can't be determined. """ if fcntl and termios: try: winsize = fcntl.ioctl(0, termios.TIOCGWINSZ, ' ') _, width = struct.unpack('hh', winsize) return width except IO...
python
def term_width(): """ Return the column width of the terminal, or ``None`` if it can't be determined. """ if fcntl and termios: try: winsize = fcntl.ioctl(0, termios.TIOCGWINSZ, ' ') _, width = struct.unpack('hh', winsize) return width except IO...
[ "def", "term_width", "(", ")", ":", "if", "fcntl", "and", "termios", ":", "try", ":", "winsize", "=", "fcntl", ".", "ioctl", "(", "0", ",", "termios", ".", "TIOCGWINSZ", ",", "' '", ")", "_", ",", "width", "=", "struct", ".", "unpack", "(", "'hh...
Return the column width of the terminal, or ``None`` if it can't be determined.
[ "Return", "the", "column", "width", "of", "the", "terminal", "or", "None", "if", "it", "can", "t", "be", "determined", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/term.py#L27-L49
ljcooke/see
see/term.py
line_width
def line_width(default_width=DEFAULT_LINE_WIDTH, max_width=MAX_LINE_WIDTH): """ Return the ideal column width for the output from :func:`see.see`, taking the terminal width into account to avoid wrapping. """ width = term_width() if width: # pragma: no cover (no terminal info in Travis CI) ...
python
def line_width(default_width=DEFAULT_LINE_WIDTH, max_width=MAX_LINE_WIDTH): """ Return the ideal column width for the output from :func:`see.see`, taking the terminal width into account to avoid wrapping. """ width = term_width() if width: # pragma: no cover (no terminal info in Travis CI) ...
[ "def", "line_width", "(", "default_width", "=", "DEFAULT_LINE_WIDTH", ",", "max_width", "=", "MAX_LINE_WIDTH", ")", ":", "width", "=", "term_width", "(", ")", "if", "width", ":", "# pragma: no cover (no terminal info in Travis CI)", "return", "min", "(", "width", ",...
Return the ideal column width for the output from :func:`see.see`, taking the terminal width into account to avoid wrapping.
[ "Return", "the", "ideal", "column", "width", "for", "the", "output", "from", ":", "func", ":", "see", ".", "see", "taking", "the", "terminal", "width", "into", "account", "to", "avoid", "wrapping", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/term.py#L52-L61
Autodesk/pyccc
pyccc/picklers.py
DepartingPickler.persistent_id
def persistent_id(self, obj): """ Tags objects with a persistent ID, but do NOT emit it """ if getattr(obj, '_PERSIST_REFERENCES', None): objid = id(obj) obj._persistent_ref = objid _weakmemos[objid] = obj return None
python
def persistent_id(self, obj): """ Tags objects with a persistent ID, but do NOT emit it """ if getattr(obj, '_PERSIST_REFERENCES', None): objid = id(obj) obj._persistent_ref = objid _weakmemos[objid] = obj return None
[ "def", "persistent_id", "(", "self", ",", "obj", ")", ":", "if", "getattr", "(", "obj", ",", "'_PERSIST_REFERENCES'", ",", "None", ")", ":", "objid", "=", "id", "(", "obj", ")", "obj", ".", "_persistent_ref", "=", "objid", "_weakmemos", "[", "objid", "...
Tags objects with a persistent ID, but do NOT emit it
[ "Tags", "objects", "with", "a", "persistent", "ID", "but", "do", "NOT", "emit", "it" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/picklers.py#L35-L42
ljcooke/see
see/inspector.py
handle_deprecated_args
def handle_deprecated_args(tokens, args, kwargs): """ Backwards compatibility with deprecated arguments ``pattern`` and ``r``. """ num_args = len(args) pattern = args[0] if num_args else kwargs.get('pattern', None) regex = args[1] if num_args > 1 else kwargs.get('r', None) if pattern is not...
python
def handle_deprecated_args(tokens, args, kwargs): """ Backwards compatibility with deprecated arguments ``pattern`` and ``r``. """ num_args = len(args) pattern = args[0] if num_args else kwargs.get('pattern', None) regex = args[1] if num_args > 1 else kwargs.get('r', None) if pattern is not...
[ "def", "handle_deprecated_args", "(", "tokens", ",", "args", ",", "kwargs", ")", ":", "num_args", "=", "len", "(", "args", ")", "pattern", "=", "args", "[", "0", "]", "if", "num_args", "else", "kwargs", ".", "get", "(", "'pattern'", ",", "None", ")", ...
Backwards compatibility with deprecated arguments ``pattern`` and ``r``.
[ "Backwards", "compatibility", "with", "deprecated", "arguments", "pattern", "and", "r", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/inspector.py#L44-L64
ljcooke/see
see/inspector.py
see
def see(obj=DEFAULT_ARG, *args, **kwargs): """ see(obj=anything) Show the features and attributes of an object. This function takes a single argument, ``obj``, which can be of any type. A summary of the object is printed immediately in the Python interpreter. For example:: >>> see([])...
python
def see(obj=DEFAULT_ARG, *args, **kwargs): """ see(obj=anything) Show the features and attributes of an object. This function takes a single argument, ``obj``, which can be of any type. A summary of the object is printed immediately in the Python interpreter. For example:: >>> see([])...
[ "def", "see", "(", "obj", "=", "DEFAULT_ARG", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "use_locals", "=", "obj", "is", "DEFAULT_ARG", "if", "use_locals", ":", "# Get the local scope from the caller's stack frame.", "# Typically this is the scope of an inte...
see(obj=anything) Show the features and attributes of an object. This function takes a single argument, ``obj``, which can be of any type. A summary of the object is printed immediately in the Python interpreter. For example:: >>> see([]) [] in + ...
[ "see", "(", "obj", "=", "anything", ")" ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/inspector.py#L67-L126
Autodesk/pyccc
pyccc/files/localfiles.py
LocalFile.open
def open(self, mode='r', encoding=None): """Return file-like object (actually opens the file for this class)""" access_type = self._get_access_type(mode) return open(self.localpath, 'r'+access_type, encoding=encoding)
python
def open(self, mode='r', encoding=None): """Return file-like object (actually opens the file for this class)""" access_type = self._get_access_type(mode) return open(self.localpath, 'r'+access_type, encoding=encoding)
[ "def", "open", "(", "self", ",", "mode", "=", "'r'", ",", "encoding", "=", "None", ")", ":", "access_type", "=", "self", ".", "_get_access_type", "(", "mode", ")", "return", "open", "(", "self", ".", "localpath", ",", "'r'", "+", "access_type", ",", ...
Return file-like object (actually opens the file for this class)
[ "Return", "file", "-", "like", "object", "(", "actually", "opens", "the", "file", "for", "this", "class", ")" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/localfiles.py#L84-L87
Autodesk/pyccc
pyccc/files/localfiles.py
CachedFile._open_tmpfile
def _open_tmpfile(self, **kwargs): """ Open a temporary, unique file in CACHEDIR (/tmp/cyborgcache) by default. Leave it open, assign file handle to self.tmpfile **kwargs are passed to tempfile.NamedTemporaryFile """ self.tmpfile = get_tempfile(**kwargs) path = s...
python
def _open_tmpfile(self, **kwargs): """ Open a temporary, unique file in CACHEDIR (/tmp/cyborgcache) by default. Leave it open, assign file handle to self.tmpfile **kwargs are passed to tempfile.NamedTemporaryFile """ self.tmpfile = get_tempfile(**kwargs) path = s...
[ "def", "_open_tmpfile", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "tmpfile", "=", "get_tempfile", "(", "*", "*", "kwargs", ")", "path", "=", "self", ".", "tmpfile", ".", "name", "return", "path" ]
Open a temporary, unique file in CACHEDIR (/tmp/cyborgcache) by default. Leave it open, assign file handle to self.tmpfile **kwargs are passed to tempfile.NamedTemporaryFile
[ "Open", "a", "temporary", "unique", "file", "in", "CACHEDIR", "(", "/", "tmp", "/", "cyborgcache", ")", "by", "default", ".", "Leave", "it", "open", "assign", "file", "handle", "to", "self", ".", "tmpfile" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/localfiles.py#L113-L122
Autodesk/pyccc
pyccc/files/stringcontainer.py
StringContainer.open
def open(self, mode='r', encoding=None): """Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): encoding type (only for binary access) Returns: io.BytesIO OR io.TextIOWrapper: buffer accessing the file as ...
python
def open(self, mode='r', encoding=None): """Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): encoding type (only for binary access) Returns: io.BytesIO OR io.TextIOWrapper: buffer accessing the file as ...
[ "def", "open", "(", "self", ",", "mode", "=", "'r'", ",", "encoding", "=", "None", ")", ":", "access_type", "=", "self", ".", "_get_access_type", "(", "mode", ")", "if", "encoding", "is", "None", ":", "encoding", "=", "self", ".", "encoding", "# here, ...
Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): encoding type (only for binary access) Returns: io.BytesIO OR io.TextIOWrapper: buffer accessing the file as bytes or characters
[ "Return", "file", "-", "like", "object" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/stringcontainer.py#L48-L78
Autodesk/pyccc
pyccc/files/stringcontainer.py
StringContainer.put
def put(self, filename, encoding=None): """Write the file to the given path Args: filename (str): path to write this file to encoding (str): file encoding (default: system default) Returns: LocalFile: reference to the copy of the file stored at ``filename`` ...
python
def put(self, filename, encoding=None): """Write the file to the given path Args: filename (str): path to write this file to encoding (str): file encoding (default: system default) Returns: LocalFile: reference to the copy of the file stored at ``filename`` ...
[ "def", "put", "(", "self", ",", "filename", ",", "encoding", "=", "None", ")", ":", "from", ".", "import", "LocalFile", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", "and", "self", ".", "source", "is", "None", ":", "raise", "ValueError...
Write the file to the given path Args: filename (str): path to write this file to encoding (str): file encoding (default: system default) Returns: LocalFile: reference to the copy of the file stored at ``filename``
[ "Write", "the", "file", "to", "the", "given", "path" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/stringcontainer.py#L94-L123
Autodesk/pyccc
pyccc/source_inspections.py
get_global_vars
def get_global_vars(func): """ Store any methods or variables bound from the function's closure Args: func (function): function to inspect Returns: dict: mapping of variable names to globally bound VARIABLES """ closure = getclosurevars(func) if closure['nonlocal']: rai...
python
def get_global_vars(func): """ Store any methods or variables bound from the function's closure Args: func (function): function to inspect Returns: dict: mapping of variable names to globally bound VARIABLES """ closure = getclosurevars(func) if closure['nonlocal']: rai...
[ "def", "get_global_vars", "(", "func", ")", ":", "closure", "=", "getclosurevars", "(", "func", ")", "if", "closure", "[", "'nonlocal'", "]", ":", "raise", "TypeError", "(", "\"Can't launch a job with closure variables: %s\"", "%", "closure", "[", "'nonlocals'", "...
Store any methods or variables bound from the function's closure Args: func (function): function to inspect Returns: dict: mapping of variable names to globally bound VARIABLES
[ "Store", "any", "methods", "or", "variables", "bound", "from", "the", "function", "s", "closure" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/source_inspections.py#L34-L58
Autodesk/pyccc
pyccc/source_inspections.py
getsource
def getsource(classorfunc): """ Return the source code for a class or function. Notes: Returned source will not include any decorators for the object. This will only return the explicit declaration of the object, not any dependencies Args: classorfunc (type or function): the object...
python
def getsource(classorfunc): """ Return the source code for a class or function. Notes: Returned source will not include any decorators for the object. This will only return the explicit declaration of the object, not any dependencies Args: classorfunc (type or function): the object...
[ "def", "getsource", "(", "classorfunc", ")", ":", "if", "_isbuiltin", "(", "classorfunc", ")", ":", "return", "''", "try", ":", "source", "=", "inspect", ".", "getsource", "(", "classorfunc", ")", "except", "TypeError", ":", "# raised if defined in __main__ - us...
Return the source code for a class or function. Notes: Returned source will not include any decorators for the object. This will only return the explicit declaration of the object, not any dependencies Args: classorfunc (type or function): the object to get the source code for Ret...
[ "Return", "the", "source", "code", "for", "a", "class", "or", "function", "." ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/source_inspections.py#L61-L138
Autodesk/pyccc
pyccc/source_inspections.py
getsourcefallback
def getsourcefallback(cls): """ Fallback for getting the source of interactively defined classes (typically in ipython) This is basically just a patched version of the inspect module, in which we get the code by calling inspect.findsource on an *instancemethod* of a class for which inspect.findsource f...
python
def getsourcefallback(cls): """ Fallback for getting the source of interactively defined classes (typically in ipython) This is basically just a patched version of the inspect module, in which we get the code by calling inspect.findsource on an *instancemethod* of a class for which inspect.findsource f...
[ "def", "getsourcefallback", "(", "cls", ")", ":", "for", "attr", "in", "cls", ".", "__dict__", ":", "if", "inspect", ".", "ismethod", "(", "getattr", "(", "cls", ",", "attr", ")", ")", ":", "imethod", "=", "getattr", "(", "cls", ",", "attr", ")", "...
Fallback for getting the source of interactively defined classes (typically in ipython) This is basically just a patched version of the inspect module, in which we get the code by calling inspect.findsource on an *instancemethod* of a class for which inspect.findsource fails.
[ "Fallback", "for", "getting", "the", "source", "of", "interactively", "defined", "classes", "(", "typically", "in", "ipython", ")" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/source_inspections.py#L141-L199
Autodesk/pyccc
pyccc/engines/dockerengine.py
Docker.get_job
def get_job(self, jobid): """ Return a Job object for the requested job id. The returned object will be suitable for retrieving output, but depending on the engine, may not populate all fields used at launch time (such as `job.inputs`, `job.commands`, etc.) Args: jobid (str...
python
def get_job(self, jobid): """ Return a Job object for the requested job id. The returned object will be suitable for retrieving output, but depending on the engine, may not populate all fields used at launch time (such as `job.inputs`, `job.commands`, etc.) Args: jobid (str...
[ "def", "get_job", "(", "self", ",", "jobid", ")", ":", "import", "shlex", "from", "pyccc", ".", "job", "import", "Job", "job", "=", "Job", "(", "engine", "=", "self", ")", "job", ".", "jobid", "=", "job", ".", "rundata", ".", "containerid", "=", "j...
Return a Job object for the requested job id. The returned object will be suitable for retrieving output, but depending on the engine, may not populate all fields used at launch time (such as `job.inputs`, `job.commands`, etc.) Args: jobid (str): container id Returns: ...
[ "Return", "a", "Job", "object", "for", "the", "requested", "job", "id", "." ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/dockerengine.py#L81-L123
Autodesk/pyccc
pyccc/engines/dockerengine.py
Docker.submit
def submit(self, job): """ Submit job to the engine Args: job (pyccc.job.Job): Job to submit """ self._check_job(job) if job.workingdir is None: job.workingdir = self.default_wdir job.imageid = du.create_provisioned_image(self.client, job.image, ...
python
def submit(self, job): """ Submit job to the engine Args: job (pyccc.job.Job): Job to submit """ self._check_job(job) if job.workingdir is None: job.workingdir = self.default_wdir job.imageid = du.create_provisioned_image(self.client, job.image, ...
[ "def", "submit", "(", "self", ",", "job", ")", ":", "self", ".", "_check_job", "(", "job", ")", "if", "job", ".", "workingdir", "is", "None", ":", "job", ".", "workingdir", "=", "self", ".", "default_wdir", "job", ".", "imageid", "=", "du", ".", "c...
Submit job to the engine Args: job (pyccc.job.Job): Job to submit
[ "Submit", "job", "to", "the", "engine" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/dockerengine.py#L125-L143
Autodesk/pyccc
pyccc/engines/dockerengine.py
Docker.dump_all_outputs
def dump_all_outputs(self, job, target, abspaths=None): """ Specialized dumping strategy - copy the entire working directory, then discard the input files that came along for the ride. Not used if there are absolute paths This is slow and wasteful if there are big input files "...
python
def dump_all_outputs(self, job, target, abspaths=None): """ Specialized dumping strategy - copy the entire working directory, then discard the input files that came along for the ride. Not used if there are absolute paths This is slow and wasteful if there are big input files "...
[ "def", "dump_all_outputs", "(", "self", ",", "job", ",", "target", ",", "abspaths", "=", "None", ")", ":", "import", "os", "import", "shutil", "from", "pathlib", "import", "Path", "root", "=", "Path", "(", "native_str", "(", "target", ")", ")", "true_out...
Specialized dumping strategy - copy the entire working directory, then discard the input files that came along for the ride. Not used if there are absolute paths This is slow and wasteful if there are big input files
[ "Specialized", "dumping", "strategy", "-", "copy", "the", "entire", "working", "directory", "then", "discard", "the", "input", "files", "that", "came", "along", "for", "the", "ride", "." ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/dockerengine.py#L201-L241
Autodesk/pyccc
pyccc/ui.py
FileView.handle_download_click
def handle_download_click(self, *args): """ Callback for download button. Downloads the file and replaces the button with a view of the file. :param args: :return: """ self.download_button.on_click(self.handle_download_click,remove=True) self.download_butt...
python
def handle_download_click(self, *args): """ Callback for download button. Downloads the file and replaces the button with a view of the file. :param args: :return: """ self.download_button.on_click(self.handle_download_click,remove=True) self.download_butt...
[ "def", "handle_download_click", "(", "self", ",", "*", "args", ")", ":", "self", ".", "download_button", ".", "on_click", "(", "self", ".", "handle_download_click", ",", "remove", "=", "True", ")", "self", ".", "download_button", ".", "description", "=", "'D...
Callback for download button. Downloads the file and replaces the button with a view of the file. :param args: :return:
[ "Callback", "for", "download", "button", ".", "Downloads", "the", "file", "and", "replaces", "the", "button", "with", "a", "view", "of", "the", "file", ".", ":", "param", "args", ":", ":", "return", ":" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/ui.py#L157-L167
Autodesk/pyccc
pyccc/docker_utils.py
create_build_context
def create_build_context(image, inputs, wdir): """ Creates a tar archive with a dockerfile and a directory called "inputs" The Dockerfile will copy the "inputs" directory to the chosen working directory """ assert os.path.isabs(wdir) dockerlines = ["FROM %s" % image, "RUN mk...
python
def create_build_context(image, inputs, wdir): """ Creates a tar archive with a dockerfile and a directory called "inputs" The Dockerfile will copy the "inputs" directory to the chosen working directory """ assert os.path.isabs(wdir) dockerlines = ["FROM %s" % image, "RUN mk...
[ "def", "create_build_context", "(", "image", ",", "inputs", ",", "wdir", ")", ":", "assert", "os", ".", "path", ".", "isabs", "(", "wdir", ")", "dockerlines", "=", "[", "\"FROM %s\"", "%", "image", ",", "\"RUN mkdir -p %s\"", "%", "wdir", "]", "build_conte...
Creates a tar archive with a dockerfile and a directory called "inputs" The Dockerfile will copy the "inputs" directory to the chosen working directory
[ "Creates", "a", "tar", "archive", "with", "a", "dockerfile", "and", "a", "directory", "called", "inputs", "The", "Dockerfile", "will", "copy", "the", "inputs", "directory", "to", "the", "chosen", "working", "directory" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/docker_utils.py#L45-L68
Autodesk/pyccc
pyccc/docker_utils.py
make_tar_stream
def make_tar_stream(build_context, buffer): """ Write a tar stream of the build context to the provided buffer Args: build_context (Mapping[str, pyccc.FileReferenceBase]): dict mapping filenames to file references buffer (io.BytesIO): writable binary mode buffer """ tf = tarfile.TarFile...
python
def make_tar_stream(build_context, buffer): """ Write a tar stream of the build context to the provided buffer Args: build_context (Mapping[str, pyccc.FileReferenceBase]): dict mapping filenames to file references buffer (io.BytesIO): writable binary mode buffer """ tf = tarfile.TarFile...
[ "def", "make_tar_stream", "(", "build_context", ",", "buffer", ")", ":", "tf", "=", "tarfile", ".", "TarFile", "(", "fileobj", "=", "buffer", ",", "mode", "=", "'w'", ")", "for", "context_path", ",", "fileobj", "in", "build_context", ".", "items", "(", "...
Write a tar stream of the build context to the provided buffer Args: build_context (Mapping[str, pyccc.FileReferenceBase]): dict mapping filenames to file references buffer (io.BytesIO): writable binary mode buffer
[ "Write", "a", "tar", "stream", "of", "the", "build", "context", "to", "the", "provided", "buffer" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/docker_utils.py#L124-L137
Autodesk/pyccc
pyccc/docker_utils.py
tar_add_bytes
def tar_add_bytes(tf, filename, bytestring): """ Add a file to a tar archive Args: tf (tarfile.TarFile): tarfile to add the file to filename (str): path within the tar file bytestring (bytes or str): file contents. Must be :class:`bytes` or ascii-encodable :class:`str` "...
python
def tar_add_bytes(tf, filename, bytestring): """ Add a file to a tar archive Args: tf (tarfile.TarFile): tarfile to add the file to filename (str): path within the tar file bytestring (bytes or str): file contents. Must be :class:`bytes` or ascii-encodable :class:`str` "...
[ "def", "tar_add_bytes", "(", "tf", ",", "filename", ",", "bytestring", ")", ":", "if", "not", "isinstance", "(", "bytestring", ",", "bytes", ")", ":", "# it hasn't been encoded yet", "bytestring", "=", "bytestring", ".", "encode", "(", "'ascii'", ")", "buff", ...
Add a file to a tar archive Args: tf (tarfile.TarFile): tarfile to add the file to filename (str): path within the tar file bytestring (bytes or str): file contents. Must be :class:`bytes` or ascii-encodable :class:`str`
[ "Add", "a", "file", "to", "a", "tar", "archive" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/docker_utils.py#L140-L154
Autodesk/pyccc
pyccc/docker_utils.py
kwargs_from_client
def kwargs_from_client(client, assert_hostname=False): """ More or less stolen from docker-py's kwargs_from_env https://github.com/docker/docker-py/blob/c0ec5512ae7ab90f7fac690064e37181186b1928/docker/utils/utils.py :type client : docker.Client """ from docker import tls if client.base_url i...
python
def kwargs_from_client(client, assert_hostname=False): """ More or less stolen from docker-py's kwargs_from_env https://github.com/docker/docker-py/blob/c0ec5512ae7ab90f7fac690064e37181186b1928/docker/utils/utils.py :type client : docker.Client """ from docker import tls if client.base_url i...
[ "def", "kwargs_from_client", "(", "client", ",", "assert_hostname", "=", "False", ")", ":", "from", "docker", "import", "tls", "if", "client", ".", "base_url", "in", "(", "'http+docker://localunixsocket'", ",", "'http+docker://localhost'", ")", ":", "return", "{",...
More or less stolen from docker-py's kwargs_from_env https://github.com/docker/docker-py/blob/c0ec5512ae7ab90f7fac690064e37181186b1928/docker/utils/utils.py :type client : docker.Client
[ "More", "or", "less", "stolen", "from", "docker", "-", "py", "s", "kwargs_from_env", "https", ":", "//", "github", ".", "com", "/", "docker", "/", "docker", "-", "py", "/", "blob", "/", "c0ec5512ae7ab90f7fac690064e37181186b1928", "/", "docker", "/", "utils",...
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/docker_utils.py#L194-L213
Autodesk/pyccc
pyccc/static/run_job.py
MappedUnpickler.find_class
def find_class(self, module, name): """ This override is here to help pickle find the modules that classes are defined in. It does three things: 1) remaps the "PackagedFunction" class from pyccc to the `source.py` module. 2) Remaps any classes created in the client's '__main__' to the...
python
def find_class(self, module, name): """ This override is here to help pickle find the modules that classes are defined in. It does three things: 1) remaps the "PackagedFunction" class from pyccc to the `source.py` module. 2) Remaps any classes created in the client's '__main__' to the...
[ "def", "find_class", "(", "self", ",", "module", ",", "name", ")", ":", "import", "pickle", "modname", "=", "self", ".", "RENAMETABLE", ".", "get", "(", "module", ",", "module", ")", "try", ":", "# can't use ``super`` here (not 2/3 compatible)", "klass", "=", ...
This override is here to help pickle find the modules that classes are defined in. It does three things: 1) remaps the "PackagedFunction" class from pyccc to the `source.py` module. 2) Remaps any classes created in the client's '__main__' to the `source.py` module 3) Creates on-the-f...
[ "This", "override", "is", "here", "to", "help", "pickle", "find", "the", "modules", "that", "classes", "are", "defined", "in", "." ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/static/run_job.py#L97-L124
Autodesk/pyccc
pyccc/utils.py
gist_diff
def gist_diff(): """Diff this file with the gist on github""" remote_file = wget(RAW_GIST) proc = subprocess.Popen(('diff - %s'%MY_PATH).split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = proc.communicate(remote_file) retu...
python
def gist_diff(): """Diff this file with the gist on github""" remote_file = wget(RAW_GIST) proc = subprocess.Popen(('diff - %s'%MY_PATH).split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = proc.communicate(remote_file) retu...
[ "def", "gist_diff", "(", ")", ":", "remote_file", "=", "wget", "(", "RAW_GIST", ")", "proc", "=", "subprocess", ".", "Popen", "(", "(", "'diff - %s'", "%", "MY_PATH", ")", ".", "split", "(", ")", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "st...
Diff this file with the gist on github
[ "Diff", "this", "file", "with", "the", "gist", "on", "github" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/utils.py#L34-L41
Autodesk/pyccc
pyccc/utils.py
wget
def wget(url): """ Download the page into a string """ import urllib.parse request = urllib.request.urlopen(url) filestring = request.read() return filestring
python
def wget(url): """ Download the page into a string """ import urllib.parse request = urllib.request.urlopen(url) filestring = request.read() return filestring
[ "def", "wget", "(", "url", ")", ":", "import", "urllib", ".", "parse", "request", "=", "urllib", ".", "request", ".", "urlopen", "(", "url", ")", "filestring", "=", "request", ".", "read", "(", ")", "return", "filestring" ]
Download the page into a string
[ "Download", "the", "page", "into", "a", "string" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/utils.py#L44-L51
Autodesk/pyccc
pyccc/utils.py
autodecode
def autodecode(b): """ Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect Args: b (bytes): byte string Returns: str: decoded text string """ import warnings import chardet try: return b.decode() except UnicodeError: ...
python
def autodecode(b): """ Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect Args: b (bytes): byte string Returns: str: decoded text string """ import warnings import chardet try: return b.decode() except UnicodeError: ...
[ "def", "autodecode", "(", "b", ")", ":", "import", "warnings", "import", "chardet", "try", ":", "return", "b", ".", "decode", "(", ")", "except", "UnicodeError", ":", "result", "=", "chardet", ".", "detect", "(", "b", ")", "if", "result", "[", "'confid...
Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect Args: b (bytes): byte string Returns: str: decoded text string
[ "Try", "to", "decode", "bytes", "to", "text", "-", "try", "default", "encoding", "first", "otherwise", "try", "to", "autodetect" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/utils.py#L61-L79
Autodesk/pyccc
pyccc/utils.py
can_use_widgets
def can_use_widgets(): """ Expanded from from http://stackoverflow.com/a/34092072/1958900 """ if 'IPython' not in sys.modules: # IPython hasn't been imported, definitely not return False from IPython import get_ipython # check for `kernel` attribute on the IPython instance if ge...
python
def can_use_widgets(): """ Expanded from from http://stackoverflow.com/a/34092072/1958900 """ if 'IPython' not in sys.modules: # IPython hasn't been imported, definitely not return False from IPython import get_ipython # check for `kernel` attribute on the IPython instance if ge...
[ "def", "can_use_widgets", "(", ")", ":", "if", "'IPython'", "not", "in", "sys", ".", "modules", ":", "# IPython hasn't been imported, definitely not", "return", "False", "from", "IPython", "import", "get_ipython", "# check for `kernel` attribute on the IPython instance", "i...
Expanded from from http://stackoverflow.com/a/34092072/1958900
[ "Expanded", "from", "from", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "34092072", "/", "1958900" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/utils.py#L82-L100
Autodesk/pyccc
pyccc/utils.py
remove_directories
def remove_directories(list_of_paths): """ Removes non-leafs from a list of directory paths """ found_dirs = set('/') for path in list_of_paths: dirs = path.strip().split('/') for i in range(2,len(dirs)): found_dirs.add( '/'.join(dirs[:i]) ) paths = [ path for path i...
python
def remove_directories(list_of_paths): """ Removes non-leafs from a list of directory paths """ found_dirs = set('/') for path in list_of_paths: dirs = path.strip().split('/') for i in range(2,len(dirs)): found_dirs.add( '/'.join(dirs[:i]) ) paths = [ path for path i...
[ "def", "remove_directories", "(", "list_of_paths", ")", ":", "found_dirs", "=", "set", "(", "'/'", ")", "for", "path", "in", "list_of_paths", ":", "dirs", "=", "path", ".", "strip", "(", ")", ".", "split", "(", "'/'", ")", "for", "i", "in", "range", ...
Removes non-leafs from a list of directory paths
[ "Removes", "non", "-", "leafs", "from", "a", "list", "of", "directory", "paths" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/utils.py#L137-L149
Autodesk/pyccc
pyccc/engines/subproc.py
Subprocess._check_file_is_under_workingdir
def _check_file_is_under_workingdir(filename, wdir): """ Raise error if input is being staged to a location not underneath the working dir """ p = filename if not os.path.isabs(p): p = os.path.join(wdir, p) targetpath = os.path.realpath(p) wdir = os.path.realp...
python
def _check_file_is_under_workingdir(filename, wdir): """ Raise error if input is being staged to a location not underneath the working dir """ p = filename if not os.path.isabs(p): p = os.path.join(wdir, p) targetpath = os.path.realpath(p) wdir = os.path.realp...
[ "def", "_check_file_is_under_workingdir", "(", "filename", ",", "wdir", ")", ":", "p", "=", "filename", "if", "not", "os", ".", "path", ".", "isabs", "(", "p", ")", ":", "p", "=", "os", ".", "path", ".", "join", "(", "wdir", ",", "p", ")", "targetp...
Raise error if input is being staged to a location not underneath the working dir
[ "Raise", "error", "if", "input", "is", "being", "staged", "to", "a", "location", "not", "underneath", "the", "working", "dir" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/subproc.py#L89-L101
Autodesk/pyccc
pyccc/files/bytecontainer.py
BytesContainer.put
def put(self, filename, encoding=None): """Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename`` """ from . import LocalFile if os.path.isdir...
python
def put(self, filename, encoding=None): """Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename`` """ from . import LocalFile if os.path.isdir...
[ "def", "put", "(", "self", ",", "filename", ",", "encoding", "=", "None", ")", ":", "from", ".", "import", "LocalFile", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", "and", "self", ".", "source", "is", "None", ":", "raise", "ValueError...
Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename``
[ "Write", "the", "file", "to", "the", "given", "path" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/bytecontainer.py#L49-L72
Autodesk/pyccc
pyccc/files/bytecontainer.py
BytesContainer.open
def open(self, mode='r', encoding=None): """Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): text decoding method for text access (default: system default) Returns: io.BytesIO OR io.TextIOWrapper: buffe...
python
def open(self, mode='r', encoding=None): """Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): text decoding method for text access (default: system default) Returns: io.BytesIO OR io.TextIOWrapper: buffe...
[ "def", "open", "(", "self", ",", "mode", "=", "'r'", ",", "encoding", "=", "None", ")", ":", "access_type", "=", "self", ".", "_get_access_type", "(", "mode", ")", "if", "access_type", "==", "'t'", "and", "encoding", "is", "not", "None", "and", "encodi...
Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): text decoding method for text access (default: system default) Returns: io.BytesIO OR io.TextIOWrapper: buffer accessing the file as bytes or characters
[ "Return", "file", "-", "like", "object" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/bytecontainer.py#L74-L97
Autodesk/pyccc
pyccc/files/base.py
get_target_path
def get_target_path(destination, origname): """ Implements the directory/path semantics of linux mv/cp etc. Examples: >>> import os >>> os.makedirs('./a') >>> get_target_path('./a', '/tmp/myfile') './myfile' >>> get_target_path('./a/b', '/tmp/myfile') './a/b' ...
python
def get_target_path(destination, origname): """ Implements the directory/path semantics of linux mv/cp etc. Examples: >>> import os >>> os.makedirs('./a') >>> get_target_path('./a', '/tmp/myfile') './myfile' >>> get_target_path('./a/b', '/tmp/myfile') './a/b' ...
[ "def", "get_target_path", "(", "destination", ",", "origname", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "destination", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "destination", ")", ":", "raise", "OSError", "(", "'Cannot...
Implements the directory/path semantics of linux mv/cp etc. Examples: >>> import os >>> os.makedirs('./a') >>> get_target_path('./a', '/tmp/myfile') './myfile' >>> get_target_path('./a/b', '/tmp/myfile') './a/b' Raises: OSError: if neither destination NO...
[ "Implements", "the", "directory", "/", "path", "semantics", "of", "linux", "mv", "/", "cp", "etc", "." ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/base.py#L48-L72
Autodesk/pyccc
pyccc/files/base.py
FileReferenceBase.put
def put(self, filename): """Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename`` """ from . import LocalFile target = get_target_path(filenam...
python
def put(self, filename): """Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename`` """ from . import LocalFile target = get_target_path(filenam...
[ "def", "put", "(", "self", ",", "filename", ")", ":", "from", ".", "import", "LocalFile", "target", "=", "get_target_path", "(", "filename", ",", "self", ".", "source", ")", "with", "self", ".", "open", "(", "'rb'", ")", "as", "infile", ",", "open", ...
Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename``
[ "Write", "the", "file", "to", "the", "given", "path" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/base.py#L104-L117
Autodesk/pyccc
pyccc/files/base.py
FileReferenceBase._get_access_type
def _get_access_type(self, mode): """ Make sure mode is appropriate; return 'b' for binary access and 't' for text """ access_type = None for char in mode: # figure out whether it's binary or text access if char in 'bt': if access_type is not None: ...
python
def _get_access_type(self, mode): """ Make sure mode is appropriate; return 'b' for binary access and 't' for text """ access_type = None for char in mode: # figure out whether it's binary or text access if char in 'bt': if access_type is not None: ...
[ "def", "_get_access_type", "(", "self", ",", "mode", ")", ":", "access_type", "=", "None", "for", "char", "in", "mode", ":", "# figure out whether it's binary or text access", "if", "char", "in", "'bt'", ":", "if", "access_type", "is", "not", "None", ":", "rai...
Make sure mode is appropriate; return 'b' for binary access and 't' for text
[ "Make", "sure", "mode", "is", "appropriate", ";", "return", "b", "for", "binary", "access", "and", "t", "for", "text" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/base.py#L151-L166
Autodesk/pyccc
pyccc/backports.py
getclosurevars
def getclosurevars(func): """ Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. Not...
python
def getclosurevars(func): """ Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. Not...
[ "def", "getclosurevars", "(", "func", ")", ":", "if", "inspect", ".", "ismethod", "(", "func", ")", ":", "func", "=", "func", ".", "__func__", "elif", "not", "inspect", ".", "isroutine", "(", "func", ")", ":", "raise", "TypeError", "(", "\"'{!r}' is not ...
Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. Note: Modified function from the ...
[ "Get", "the", "mapping", "of", "free", "variables", "to", "their", "current", "values", "." ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/backports.py#L154-L216
Autodesk/pyccc
pyccc/files/directory.py
LocalDirectoryReference.put
def put(self, destination): """ Copy the referenced directory to this path The semantics of this command are similar to unix ``cp``: if ``destination`` already exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If it does not already exist, the dire...
python
def put(self, destination): """ Copy the referenced directory to this path The semantics of this command are similar to unix ``cp``: if ``destination`` already exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If it does not already exist, the dire...
[ "def", "put", "(", "self", ",", "destination", ")", ":", "target", "=", "get_target_path", "(", "destination", ",", "self", ".", "localpath", ")", "shutil", ".", "copytree", "(", "self", ".", "localpath", ",", "target", ")" ]
Copy the referenced directory to this path The semantics of this command are similar to unix ``cp``: if ``destination`` already exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If it does not already exist, the directory will be renamed to this path (the ...
[ "Copy", "the", "referenced", "directory", "to", "this", "path" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/directory.py#L34-L46
Autodesk/pyccc
pyccc/files/directory.py
DirectoryArchive.put
def put(self, destination): """ Copy the referenced directory to this path Note: This ignores anything not in the desired directory, given by ``self.dirname``. Args: destination (str): path to put this directory (which must NOT already exist) References: ...
python
def put(self, destination): """ Copy the referenced directory to this path Note: This ignores anything not in the desired directory, given by ``self.dirname``. Args: destination (str): path to put this directory (which must NOT already exist) References: ...
[ "def", "put", "(", "self", ",", "destination", ")", ":", "target", "=", "get_target_path", "(", "destination", ",", "self", ".", "dirname", ")", "valid_paths", "=", "(", "self", ".", "dirname", ",", "'./%s'", "%", "self", ".", "dirname", ")", "with", "...
Copy the referenced directory to this path Note: This ignores anything not in the desired directory, given by ``self.dirname``. Args: destination (str): path to put this directory (which must NOT already exist) References: https://stackoverflow.com/a/826108...
[ "Copy", "the", "referenced", "directory", "to", "this", "path" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/directory.py#L63-L95
Autodesk/pyccc
pyccc/files/directory.py
DockerArchive.put
def put(self, destination): """ Copy the referenced directory to this path Args: destination (str): path to put this directory (which must NOT already exist) """ if not self._fetched: self._fetch() DirectoryArchive.put(self, destination)
python
def put(self, destination): """ Copy the referenced directory to this path Args: destination (str): path to put this directory (which must NOT already exist) """ if not self._fetched: self._fetch() DirectoryArchive.put(self, destination)
[ "def", "put", "(", "self", ",", "destination", ")", ":", "if", "not", "self", ".", "_fetched", ":", "self", ".", "_fetch", "(", ")", "DirectoryArchive", ".", "put", "(", "self", ",", "destination", ")" ]
Copy the referenced directory to this path Args: destination (str): path to put this directory (which must NOT already exist)
[ "Copy", "the", "referenced", "directory", "to", "this", "path" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/files/directory.py#L111-L119
Autodesk/pyccc
pyccc/engines/base.py
EngineBase.dump_all_outputs
def dump_all_outputs(self, job, target, abspaths=None): """ Default dumping strategy - potentially slow for large numbers of files Subclasses should offer faster implementations, if available """ from pathlib import Path root = Path(native_str(target)) for outputpath, o...
python
def dump_all_outputs(self, job, target, abspaths=None): """ Default dumping strategy - potentially slow for large numbers of files Subclasses should offer faster implementations, if available """ from pathlib import Path root = Path(native_str(target)) for outputpath, o...
[ "def", "dump_all_outputs", "(", "self", ",", "job", ",", "target", ",", "abspaths", "=", "None", ")", ":", "from", "pathlib", "import", "Path", "root", "=", "Path", "(", "native_str", "(", "target", ")", ")", "for", "outputpath", ",", "outputfile", "in",...
Default dumping strategy - potentially slow for large numbers of files Subclasses should offer faster implementations, if available
[ "Default", "dumping", "strategy", "-", "potentially", "slow", "for", "large", "numbers", "of", "files" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/base.py#L63-L90
Autodesk/pyccc
pyccc/engines/base.py
EngineBase.launch
def launch(self, image, command, **kwargs): """ Create a job on this engine Args: image (str): name of the docker image to launch command (str): shell command to run """ if isinstance(command, PythonCall): return PythonJob(self, image, command...
python
def launch(self, image, command, **kwargs): """ Create a job on this engine Args: image (str): name of the docker image to launch command (str): shell command to run """ if isinstance(command, PythonCall): return PythonJob(self, image, command...
[ "def", "launch", "(", "self", ",", "image", ",", "command", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "command", ",", "PythonCall", ")", ":", "return", "PythonJob", "(", "self", ",", "image", ",", "command", ",", "*", "*", "kwargs",...
Create a job on this engine Args: image (str): name of the docker image to launch command (str): shell command to run
[ "Create", "a", "job", "on", "this", "engine" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/engines/base.py#L92-L103
ljcooke/see
see/tools.py
char_width
def char_width(char): """ Get the display length of a unicode character. """ if ord(char) < 128: return 1 elif unicodedata.east_asian_width(char) in ('F', 'W'): return 2 elif unicodedata.category(char) in ('Mn',): return 0 else: return 1
python
def char_width(char): """ Get the display length of a unicode character. """ if ord(char) < 128: return 1 elif unicodedata.east_asian_width(char) in ('F', 'W'): return 2 elif unicodedata.category(char) in ('Mn',): return 0 else: return 1
[ "def", "char_width", "(", "char", ")", ":", "if", "ord", "(", "char", ")", "<", "128", ":", "return", "1", "elif", "unicodedata", ".", "east_asian_width", "(", "char", ")", "in", "(", "'F'", ",", "'W'", ")", ":", "return", "2", "elif", "unicodedata",...
Get the display length of a unicode character.
[ "Get", "the", "display", "length", "of", "a", "unicode", "character", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/tools.py#L16-L27
ljcooke/see
see/tools.py
display_len
def display_len(text): """ Get the display length of a string. This can differ from the character length if the string contains wide characters. """ text = unicodedata.normalize('NFD', text) return sum(char_width(char) for char in text)
python
def display_len(text): """ Get the display length of a string. This can differ from the character length if the string contains wide characters. """ text = unicodedata.normalize('NFD', text) return sum(char_width(char) for char in text)
[ "def", "display_len", "(", "text", ")", ":", "text", "=", "unicodedata", ".", "normalize", "(", "'NFD'", ",", "text", ")", "return", "sum", "(", "char_width", "(", "char", ")", "for", "char", "in", "text", ")" ]
Get the display length of a string. This can differ from the character length if the string contains wide characters.
[ "Get", "the", "display", "length", "of", "a", "string", ".", "This", "can", "differ", "from", "the", "character", "length", "if", "the", "string", "contains", "wide", "characters", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/tools.py#L30-L36
ljcooke/see
see/tools.py
filter_regex
def filter_regex(names, regex): """ Return a tuple of strings that match the regular expression pattern. """ return tuple(name for name in names if regex.search(name) is not None)
python
def filter_regex(names, regex): """ Return a tuple of strings that match the regular expression pattern. """ return tuple(name for name in names if regex.search(name) is not None)
[ "def", "filter_regex", "(", "names", ",", "regex", ")", ":", "return", "tuple", "(", "name", "for", "name", "in", "names", "if", "regex", ".", "search", "(", "name", ")", "is", "not", "None", ")" ]
Return a tuple of strings that match the regular expression pattern.
[ "Return", "a", "tuple", "of", "strings", "that", "match", "the", "regular", "expression", "pattern", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/tools.py#L39-L44
ljcooke/see
see/tools.py
filter_wildcard
def filter_wildcard(names, pattern): """ Return a tuple of strings that match a shell-style wildcard pattern. """ return tuple(name for name in names if fnmatch.fnmatch(name, pattern))
python
def filter_wildcard(names, pattern): """ Return a tuple of strings that match a shell-style wildcard pattern. """ return tuple(name for name in names if fnmatch.fnmatch(name, pattern))
[ "def", "filter_wildcard", "(", "names", ",", "pattern", ")", ":", "return", "tuple", "(", "name", "for", "name", "in", "names", "if", "fnmatch", ".", "fnmatch", "(", "name", ",", "pattern", ")", ")" ]
Return a tuple of strings that match a shell-style wildcard pattern.
[ "Return", "a", "tuple", "of", "strings", "that", "match", "a", "shell", "-", "style", "wildcard", "pattern", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/tools.py#L47-L52
ljcooke/see
see/features.py
HelpFeature.match
def match(self, obj, attrs): """ Only match if the object contains a non-empty docstring. """ if '__doc__' in attrs: lstrip = getattr(obj.__doc__, 'lstrip', False) return lstrip and any(lstrip())
python
def match(self, obj, attrs): """ Only match if the object contains a non-empty docstring. """ if '__doc__' in attrs: lstrip = getattr(obj.__doc__, 'lstrip', False) return lstrip and any(lstrip())
[ "def", "match", "(", "self", ",", "obj", ",", "attrs", ")", ":", "if", "'__doc__'", "in", "attrs", ":", "lstrip", "=", "getattr", "(", "obj", ".", "__doc__", ",", "'lstrip'", ",", "False", ")", "return", "lstrip", "and", "any", "(", "lstrip", "(", ...
Only match if the object contains a non-empty docstring.
[ "Only", "match", "if", "the", "object", "contains", "a", "non", "-", "empty", "docstring", "." ]
train
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/features.py#L78-L84
Autodesk/pyccc
pyccc/python.py
PackagedFunction.run
def run(self, func=None): """ Evaluates the packaged function as func(*self.args,**self.kwargs) If func is a method of an object, it's accessed as getattr(self.obj,__name__). If it's a user-defined function, it needs to be passed in here because it can't be serialized. R...
python
def run(self, func=None): """ Evaluates the packaged function as func(*self.args,**self.kwargs) If func is a method of an object, it's accessed as getattr(self.obj,__name__). If it's a user-defined function, it needs to be passed in here because it can't be serialized. R...
[ "def", "run", "(", "self", ",", "func", "=", "None", ")", ":", "to_run", "=", "self", ".", "prepare_namespace", "(", "func", ")", "result", "=", "to_run", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "return", "result" ...
Evaluates the packaged function as func(*self.args,**self.kwargs) If func is a method of an object, it's accessed as getattr(self.obj,__name__). If it's a user-defined function, it needs to be passed in here because it can't be serialized. Returns: object: function's return ...
[ "Evaluates", "the", "packaged", "function", "as", "func", "(", "*", "self", ".", "args", "**", "self", ".", "kwargs", ")", "If", "func", "is", "a", "method", "of", "an", "object", "it", "s", "accessed", "as", "getattr", "(", "self", ".", "obj", "__na...
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/python.py#L278-L290
Autodesk/pyccc
pyccc/python.py
PackagedFunction.prepare_namespace
def prepare_namespace(self, func): """ Prepares the function to be run after deserializing it. Re-associates any previously bound variables and modules from the closure Returns: callable: ready-to-call function """ if self.is_imethod: to_run = get...
python
def prepare_namespace(self, func): """ Prepares the function to be run after deserializing it. Re-associates any previously bound variables and modules from the closure Returns: callable: ready-to-call function """ if self.is_imethod: to_run = get...
[ "def", "prepare_namespace", "(", "self", ",", "func", ")", ":", "if", "self", ".", "is_imethod", ":", "to_run", "=", "getattr", "(", "self", ".", "obj", ",", "self", ".", "imethod_name", ")", "else", ":", "to_run", "=", "func", "for", "varname", ",", ...
Prepares the function to be run after deserializing it. Re-associates any previously bound variables and modules from the closure Returns: callable: ready-to-call function
[ "Prepares", "the", "function", "to", "be", "run", "after", "deserializing", "it", ".", "Re", "-", "associates", "any", "previously", "bound", "variables", "and", "modules", "from", "the", "closure" ]
train
https://github.com/Autodesk/pyccc/blob/011698e78d49a83ac332e0578a4a2a865b75ef8d/pyccc/python.py#L292-L311
sphinx-contrib/datatemplates
sphinxcontrib/datatemplates/helpers.py
make_list_table
def make_list_table(headers, data, title='', columns=None): """Build a list-table directive. :param headers: List of header values. :param data: Iterable of row data, yielding lists or tuples with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the ...
python
def make_list_table(headers, data, title='', columns=None): """Build a list-table directive. :param headers: List of header values. :param data: Iterable of row data, yielding lists or tuples with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the ...
[ "def", "make_list_table", "(", "headers", ",", "data", ",", "title", "=", "''", ",", "columns", "=", "None", ")", ":", "results", "=", "[", "]", "add", "=", "results", ".", "append", "add", "(", "'.. list-table:: %s'", "%", "title", ")", "add", "(", ...
Build a list-table directive. :param headers: List of header values. :param data: Iterable of row data, yielding lists or tuples with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the columns.
[ "Build", "a", "list", "-", "table", "directive", "." ]
train
https://github.com/sphinx-contrib/datatemplates/blob/d1f961e3f3353a1f62b7b0bddab371e5d9804ff3/sphinxcontrib/datatemplates/helpers.py#L1-L24
sphinx-contrib/datatemplates
sphinxcontrib/datatemplates/helpers.py
make_list_table_from_mappings
def make_list_table_from_mappings(headers, data, title, columns=None): """Build a list-table directive. :param headers: List of tuples containing header title and key value. :param data: Iterable of row data, yielding mappings with rows. :param title: Optional text to show as the table title. :para...
python
def make_list_table_from_mappings(headers, data, title, columns=None): """Build a list-table directive. :param headers: List of tuples containing header title and key value. :param data: Iterable of row data, yielding mappings with rows. :param title: Optional text to show as the table title. :para...
[ "def", "make_list_table_from_mappings", "(", "headers", ",", "data", ",", "title", ",", "columns", "=", "None", ")", ":", "header_names", "=", "[", "h", "[", "0", "]", "for", "h", "in", "headers", "]", "header_keys", "=", "[", "h", "[", "1", "]", "fo...
Build a list-table directive. :param headers: List of tuples containing header title and key value. :param data: Iterable of row data, yielding mappings with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the columns.
[ "Build", "a", "list", "-", "table", "directive", "." ]
train
https://github.com/sphinx-contrib/datatemplates/blob/d1f961e3f3353a1f62b7b0bddab371e5d9804ff3/sphinxcontrib/datatemplates/helpers.py#L27-L41
openstates/billy
billy/web/public/templatetags/customtags.py
decimal_format
def decimal_format(value, TWOPLACES=Decimal(100) ** -2): 'Format a decimal.Decimal like to 2 decimal places.' if not isinstance(value, Decimal): value = Decimal(str(value)) return value.quantize(TWOPLACES)
python
def decimal_format(value, TWOPLACES=Decimal(100) ** -2): 'Format a decimal.Decimal like to 2 decimal places.' if not isinstance(value, Decimal): value = Decimal(str(value)) return value.quantize(TWOPLACES)
[ "def", "decimal_format", "(", "value", ",", "TWOPLACES", "=", "Decimal", "(", "100", ")", "**", "-", "2", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Decimal", ")", ":", "value", "=", "Decimal", "(", "str", "(", "value", ")", ")", "ret...
Format a decimal.Decimal like to 2 decimal places.
[ "Format", "a", "decimal", ".", "Decimal", "like", "to", "2", "decimal", "places", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/templatetags/customtags.py#L77-L81
openstates/billy
billy/web/public/templatetags/customtags.py
notification_preference
def notification_preference(obj_type, profile): '''Display two radio buttons for turning notifications on or off. The default value is is have alerts_on = True. ''' default_alert_value = True if not profile: alerts_on = True else: notifications = profile.get('notifications', {}) ...
python
def notification_preference(obj_type, profile): '''Display two radio buttons for turning notifications on or off. The default value is is have alerts_on = True. ''' default_alert_value = True if not profile: alerts_on = True else: notifications = profile.get('notifications', {}) ...
[ "def", "notification_preference", "(", "obj_type", ",", "profile", ")", ":", "default_alert_value", "=", "True", "if", "not", "profile", ":", "alerts_on", "=", "True", "else", ":", "notifications", "=", "profile", ".", "get", "(", "'notifications'", ",", "{", ...
Display two radio buttons for turning notifications on or off. The default value is is have alerts_on = True.
[ "Display", "two", "radio", "buttons", "for", "turning", "notifications", "on", "or", "off", ".", "The", "default", "value", "is", "is", "have", "alerts_on", "=", "True", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/templatetags/customtags.py#L120-L130
openstates/billy
billy/models/legislators.py
OldRole.committee_object
def committee_object(self): '''If the committee id no longer exists in mongo for some reason, this function returns None. ''' if 'committee_id' in self: _id = self['committee_id'] return self.document._old_roles_committees.get(_id) else: return...
python
def committee_object(self): '''If the committee id no longer exists in mongo for some reason, this function returns None. ''' if 'committee_id' in self: _id = self['committee_id'] return self.document._old_roles_committees.get(_id) else: return...
[ "def", "committee_object", "(", "self", ")", ":", "if", "'committee_id'", "in", "self", ":", "_id", "=", "self", "[", "'committee_id'", "]", "return", "self", ".", "document", ".", "_old_roles_committees", ".", "get", "(", "_id", ")", "else", ":", "return"...
If the committee id no longer exists in mongo for some reason, this function returns None.
[ "If", "the", "committee", "id", "no", "longer", "exists", "in", "mongo", "for", "some", "reason", "this", "function", "returns", "None", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/legislators.py#L72-L80
openstates/billy
billy/models/legislators.py
Legislator.context_role
def context_role(self, bill=None, vote=None, session=None, term=None): '''Tell this legislator object which session to use when calculating the legisator's context_role for a given bill or vote. ''' # If no hints were given about the context, look for a related bill, # then for a...
python
def context_role(self, bill=None, vote=None, session=None, term=None): '''Tell this legislator object which session to use when calculating the legisator's context_role for a given bill or vote. ''' # If no hints were given about the context, look for a related bill, # then for a...
[ "def", "context_role", "(", "self", ",", "bill", "=", "None", ",", "vote", "=", "None", ",", "session", "=", "None", ",", "term", "=", "None", ")", ":", "# If no hints were given about the context, look for a related bill,", "# then for a related vote.", "if", "not"...
Tell this legislator object which session to use when calculating the legisator's context_role for a given bill or vote.
[ "Tell", "this", "legislator", "object", "which", "session", "to", "use", "when", "calculating", "the", "legisator", "s", "context_role", "for", "a", "given", "bill", "or", "vote", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/legislators.py#L161-L287
openstates/billy
billy/models/legislators.py
Legislator.old_roles_manager
def old_roles_manager(self): '''Return old roles, grouped first by term, then by chamber, then by type.''' wrapper = self._old_role_wrapper chamber_getter = operator.methodcaller('get', 'chamber') for term, roles in self.get('old_roles', {}).items(): chamber_roles = d...
python
def old_roles_manager(self): '''Return old roles, grouped first by term, then by chamber, then by type.''' wrapper = self._old_role_wrapper chamber_getter = operator.methodcaller('get', 'chamber') for term, roles in self.get('old_roles', {}).items(): chamber_roles = d...
[ "def", "old_roles_manager", "(", "self", ")", ":", "wrapper", "=", "self", ".", "_old_role_wrapper", "chamber_getter", "=", "operator", ".", "methodcaller", "(", "'get'", ",", "'chamber'", ")", "for", "term", ",", "roles", "in", "self", ".", "get", "(", "'...
Return old roles, grouped first by term, then by chamber, then by type.
[ "Return", "old", "roles", "grouped", "first", "by", "term", "then", "by", "chamber", "then", "by", "type", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/legislators.py#L315-L327
openstates/billy
billy/importers/names.py
NameMatcher._normalize
def _normalize(self, name): """ Normalizes a legislator name by stripping titles from the front, converting to lowercase and removing punctuation. """ name = re.sub( r'^(Senator|Representative|Sen\.?|Rep\.?|' 'Hon\.?|Right Hon\.?|Mr\.?|Mrs\.?|Ms\.?|L\'hon\...
python
def _normalize(self, name): """ Normalizes a legislator name by stripping titles from the front, converting to lowercase and removing punctuation. """ name = re.sub( r'^(Senator|Representative|Sen\.?|Rep\.?|' 'Hon\.?|Right Hon\.?|Mr\.?|Mrs\.?|Ms\.?|L\'hon\...
[ "def", "_normalize", "(", "self", ",", "name", ")", ":", "name", "=", "re", ".", "sub", "(", "r'^(Senator|Representative|Sen\\.?|Rep\\.?|'", "'Hon\\.?|Right Hon\\.?|Mr\\.?|Mrs\\.?|Ms\\.?|L\\'hon\\.?|'", "'Assembly(member|man|woman)) '", ",", "''", ",", "name", ")", "retur...
Normalizes a legislator name by stripping titles from the front, converting to lowercase and removing punctuation.
[ "Normalizes", "a", "legislator", "name", "by", "stripping", "titles", "from", "the", "front", "converting", "to", "lowercase", "and", "removing", "punctuation", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/names.py#L120-L131
openstates/billy
billy/importers/names.py
NameMatcher._learn
def _learn(self, legislator): """ Expects a dictionary with full_name, first_name, last_name and middle_name elements as key. While this can grow quickly, we should never be dealing with more than a few hundred legislators at a time so don't worry about it. """ ...
python
def _learn(self, legislator): """ Expects a dictionary with full_name, first_name, last_name and middle_name elements as key. While this can grow quickly, we should never be dealing with more than a few hundred legislators at a time so don't worry about it. """ ...
[ "def", "_learn", "(", "self", ",", "legislator", ")", ":", "name", ",", "obj", "=", "legislator", ",", "legislator", "[", "'_id'", "]", "if", "(", "legislator", "[", "'roles'", "]", "and", "legislator", "[", "'roles'", "]", "[", "0", "]", "[", "'term...
Expects a dictionary with full_name, first_name, last_name and middle_name elements as key. While this can grow quickly, we should never be dealing with more than a few hundred legislators at a time so don't worry about it.
[ "Expects", "a", "dictionary", "with", "full_name", "first_name", "last_name", "and", "middle_name", "elements", "as", "key", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/names.py#L133-L215
openstates/billy
billy/importers/names.py
NameMatcher.match
def match(self, name, chamber=None): """ If this matcher has uniquely seen a matching name, return its value. Otherwise, return None. If chamber is set then the search will be limited to legislators with matching chamber. If chamber is None then the search will be cross-...
python
def match(self, name, chamber=None): """ If this matcher has uniquely seen a matching name, return its value. Otherwise, return None. If chamber is set then the search will be limited to legislators with matching chamber. If chamber is None then the search will be cross-...
[ "def", "match", "(", "self", ",", "name", ",", "chamber", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_manual", "[", "chamber", "]", "[", "name", "]", "except", "KeyError", ":", "pass", "if", "chamber", "==", "'joint'", ":", "chamber",...
If this matcher has uniquely seen a matching name, return its value. Otherwise, return None. If chamber is set then the search will be limited to legislators with matching chamber. If chamber is None then the search will be cross-chamber.
[ "If", "this", "matcher", "has", "uniquely", "seen", "a", "matching", "name", "return", "its", "value", ".", "Otherwise", "return", "None", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/names.py#L217-L246
openstates/billy
billy/scrape/__init__.py
get_scraper
def get_scraper(mod_path, scraper_type): """ import a scraper from the scraper registry """ # act of importing puts it into the registry try: module = importlib.import_module(mod_path) except ImportError as e: raise ScrapeError("could not import %s" % mod_path, e) # now find the cl...
python
def get_scraper(mod_path, scraper_type): """ import a scraper from the scraper registry """ # act of importing puts it into the registry try: module = importlib.import_module(mod_path) except ImportError as e: raise ScrapeError("could not import %s" % mod_path, e) # now find the cl...
[ "def", "get_scraper", "(", "mod_path", ",", "scraper_type", ")", ":", "# act of importing puts it into the registry", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "mod_path", ")", "except", "ImportError", "as", "e", ":", "raise", "ScrapeError",...
import a scraper from the scraper registry
[ "import", "a", "scraper", "from", "the", "scraper", "registry" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/__init__.py#L230-L255
openstates/billy
billy/scrape/__init__.py
Scraper._load_schemas
def _load_schemas(self): """ load all schemas into schema dict """ types = ('bill', 'committee', 'person', 'vote', 'event') for type in types: schema_path = os.path.join(os.path.split(__file__)[0], '../schemas/%s.json' % type) self...
python
def _load_schemas(self): """ load all schemas into schema dict """ types = ('bill', 'committee', 'person', 'vote', 'event') for type in types: schema_path = os.path.join(os.path.split(__file__)[0], '../schemas/%s.json' % type) self...
[ "def", "_load_schemas", "(", "self", ")", ":", "types", "=", "(", "'bill'", ",", "'committee'", ",", "'person'", ",", "'vote'", ",", "'event'", ")", "for", "type", "in", "types", ":", "schema_path", "=", "os", ".", "path", ".", "join", "(", "os", "."...
load all schemas into schema dict
[ "load", "all", "schemas", "into", "schema", "dict" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/__init__.py#L95-L117
openstates/billy
billy/scrape/__init__.py
Scraper.validate_session
def validate_session(self, session, latest_only=False): """ Check that a session is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if session is invalid :param session: string representing session to check """ if latest_only: if ses...
python
def validate_session(self, session, latest_only=False): """ Check that a session is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if session is invalid :param session: string representing session to check """ if latest_only: if ses...
[ "def", "validate_session", "(", "self", ",", "session", ",", "latest_only", "=", "False", ")", ":", "if", "latest_only", ":", "if", "session", "!=", "self", ".", "metadata", "[", "'terms'", "]", "[", "-", "1", "]", "[", "'sessions'", "]", "[", "-", "...
Check that a session is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if session is invalid :param session: string representing session to check
[ "Check", "that", "a", "session", "is", "present", "in", "the", "metadata", "dictionary", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/__init__.py#L138-L152
openstates/billy
billy/scrape/__init__.py
Scraper.validate_term
def validate_term(self, term, latest_only=False): """ Check that a term is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if term is invalid :param term: string representing term to check :param latest_only: if True, will raise exception if term ...
python
def validate_term(self, term, latest_only=False): """ Check that a term is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if term is invalid :param term: string representing term to check :param latest_only: if True, will raise exception if term ...
[ "def", "validate_term", "(", "self", ",", "term", ",", "latest_only", "=", "False", ")", ":", "if", "latest_only", ":", "if", "term", "==", "self", ".", "metadata", "[", "'terms'", "]", "[", "-", "1", "]", "[", "'name'", "]", ":", "return", "True", ...
Check that a term is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if term is invalid :param term: string representing term to check :param latest_only: if True, will raise exception if term is not the current term (default: ...
[ "Check", "that", "a", "term", "is", "present", "in", "the", "metadata", "dictionary", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/__init__.py#L154-L173
openstates/billy
billy/scrape/__init__.py
SourcedObject.add_source
def add_source(self, url, **kwargs): """ Add a source URL from which data related to this object was scraped. :param url: the location of the source """ self['sources'].append(dict(url=url, **kwargs))
python
def add_source(self, url, **kwargs): """ Add a source URL from which data related to this object was scraped. :param url: the location of the source """ self['sources'].append(dict(url=url, **kwargs))
[ "def", "add_source", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "self", "[", "'sources'", "]", ".", "append", "(", "dict", "(", "url", "=", "url", ",", "*", "*", "kwargs", ")", ")" ]
Add a source URL from which data related to this object was scraped. :param url: the location of the source
[ "Add", "a", "source", "URL", "from", "which", "data", "related", "to", "this", "object", "was", "scraped", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/__init__.py#L221-L227
openstates/billy
billy/scrape/utils.py
PlaintextColumns._get_column_ends
def _get_column_ends(self): '''Guess where the ends of the columns lie. ''' ends = collections.Counter() for line in self.text.splitlines(): for matchobj in re.finditer('\s{2,}', line.lstrip()): ends[matchobj.end()] += 1 return ends
python
def _get_column_ends(self): '''Guess where the ends of the columns lie. ''' ends = collections.Counter() for line in self.text.splitlines(): for matchobj in re.finditer('\s{2,}', line.lstrip()): ends[matchobj.end()] += 1 return ends
[ "def", "_get_column_ends", "(", "self", ")", ":", "ends", "=", "collections", ".", "Counter", "(", ")", "for", "line", "in", "self", ".", "text", ".", "splitlines", "(", ")", ":", "for", "matchobj", "in", "re", ".", "finditer", "(", "'\\s{2,}'", ",", ...
Guess where the ends of the columns lie.
[ "Guess", "where", "the", "ends", "of", "the", "columns", "lie", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/utils.py#L71-L78
openstates/billy
billy/scrape/utils.py
PlaintextColumns._get_column_boundaries
def _get_column_boundaries(self): '''Use the guessed ends to guess the boundaries of the plain text columns. ''' # Try to figure out the most common column boundaries. ends = self._get_column_ends() if not ends: # If there aren't even any nontrivial sequences ...
python
def _get_column_boundaries(self): '''Use the guessed ends to guess the boundaries of the plain text columns. ''' # Try to figure out the most common column boundaries. ends = self._get_column_ends() if not ends: # If there aren't even any nontrivial sequences ...
[ "def", "_get_column_boundaries", "(", "self", ")", ":", "# Try to figure out the most common column boundaries.", "ends", "=", "self", ".", "_get_column_ends", "(", ")", "if", "not", "ends", ":", "# If there aren't even any nontrivial sequences of whitespace", "# dividing text,...
Use the guessed ends to guess the boundaries of the plain text columns.
[ "Use", "the", "guessed", "ends", "to", "guess", "the", "boundaries", "of", "the", "plain", "text", "columns", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/utils.py#L80-L117
openstates/billy
billy/scrape/utils.py
PlaintextColumns.getcells
def getcells(self, line): '''Using self.boundaries, extract cells from the given line. ''' for boundary in self.boundaries: cell = line.lstrip()[boundary].strip() if cell: for cell in re.split('\s{3,}', cell): yield cell els...
python
def getcells(self, line): '''Using self.boundaries, extract cells from the given line. ''' for boundary in self.boundaries: cell = line.lstrip()[boundary].strip() if cell: for cell in re.split('\s{3,}', cell): yield cell els...
[ "def", "getcells", "(", "self", ",", "line", ")", ":", "for", "boundary", "in", "self", ".", "boundaries", ":", "cell", "=", "line", ".", "lstrip", "(", ")", "[", "boundary", "]", ".", "strip", "(", ")", "if", "cell", ":", "for", "cell", "in", "r...
Using self.boundaries, extract cells from the given line.
[ "Using", "self", ".", "boundaries", "extract", "cells", "from", "the", "given", "line", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/utils.py#L127-L136
openstates/billy
billy/scrape/utils.py
PlaintextColumns.rows
def rows(self): '''Returns an iterator of row tuples. ''' for line in self.text.splitlines(): yield tuple(self.getcells(line))
python
def rows(self): '''Returns an iterator of row tuples. ''' for line in self.text.splitlines(): yield tuple(self.getcells(line))
[ "def", "rows", "(", "self", ")", ":", "for", "line", "in", "self", ".", "text", ".", "splitlines", "(", ")", ":", "yield", "tuple", "(", "self", ".", "getcells", "(", "line", ")", ")" ]
Returns an iterator of row tuples.
[ "Returns", "an", "iterator", "of", "row", "tuples", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/utils.py#L138-L142
openstates/billy
billy/scrape/utils.py
PlaintextColumns.cells
def cells(self): '''Returns an interator of all cells in the table. ''' for line in self.text.splitlines(): for cell in self.getcells(line): yield cell
python
def cells(self): '''Returns an interator of all cells in the table. ''' for line in self.text.splitlines(): for cell in self.getcells(line): yield cell
[ "def", "cells", "(", "self", ")", ":", "for", "line", "in", "self", ".", "text", ".", "splitlines", "(", ")", ":", "for", "cell", "in", "self", ".", "getcells", "(", "line", ")", ":", "yield", "cell" ]
Returns an interator of all cells in the table.
[ "Returns", "an", "interator", "of", "all", "cells", "in", "the", "table", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/utils.py#L144-L149
openstates/billy
billy/models/pagination.py
PaginatorBase._previous_pages_count
def _previous_pages_count(self): 'A generator of previous page integers.' skip = self.skip if skip == 0: return 0 count, remainder = divmod(skip, self.limit) return count
python
def _previous_pages_count(self): 'A generator of previous page integers.' skip = self.skip if skip == 0: return 0 count, remainder = divmod(skip, self.limit) return count
[ "def", "_previous_pages_count", "(", "self", ")", ":", "skip", "=", "self", ".", "skip", "if", "skip", "==", "0", ":", "return", "0", "count", ",", "remainder", "=", "divmod", "(", "skip", ",", "self", ".", "limit", ")", "return", "count" ]
A generator of previous page integers.
[ "A", "generator", "of", "previous", "page", "integers", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/pagination.py#L17-L23
openstates/billy
billy/models/pagination.py
PaginatorBase.previous_pages_numbers
def previous_pages_numbers(self): 'A generator of previous page integers.' count = self._previous_pages_count() + 1 for i in reversed(range(1, count)): yield i
python
def previous_pages_numbers(self): 'A generator of previous page integers.' count = self._previous_pages_count() + 1 for i in reversed(range(1, count)): yield i
[ "def", "previous_pages_numbers", "(", "self", ")", ":", "count", "=", "self", ".", "_previous_pages_count", "(", ")", "+", "1", "for", "i", "in", "reversed", "(", "range", "(", "1", ",", "count", ")", ")", ":", "yield", "i" ]
A generator of previous page integers.
[ "A", "generator", "of", "previous", "page", "integers", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/pagination.py#L31-L35
openstates/billy
billy/models/pagination.py
PaginatorBase.range_end
def range_end(self): '''"Showing 40 - 50 of 234 results ^ ''' count = self.count range_end = self.range_start + self.limit - 1 if count < range_end: range_end = count return range_end
python
def range_end(self): '''"Showing 40 - 50 of 234 results ^ ''' count = self.count range_end = self.range_start + self.limit - 1 if count < range_end: range_end = count return range_end
[ "def", "range_end", "(", "self", ")", ":", "count", "=", "self", ".", "count", "range_end", "=", "self", ".", "range_start", "+", "self", ".", "limit", "-", "1", "if", "count", "<", "range_end", ":", "range_end", "=", "count", "return", "range_end" ]
"Showing 40 - 50 of 234 results ^
[ "Showing", "40", "-", "50", "of", "234", "results", "^" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/pagination.py#L66-L74
openstates/billy
billy/models/pagination.py
PaginatorBase.pagination_data
def pagination_data(self, max_number_of_links=7): '''Returns a generator of tuples (string, page_number, clickable), where `string` is the text of the html link, `page_number` is the number of the page the link points to, and `clickable` is a boolean indicating whether the link is clicka...
python
def pagination_data(self, max_number_of_links=7): '''Returns a generator of tuples (string, page_number, clickable), where `string` is the text of the html link, `page_number` is the number of the page the link points to, and `clickable` is a boolean indicating whether the link is clicka...
[ "def", "pagination_data", "(", "self", ",", "max_number_of_links", "=", "7", ")", ":", "div", ",", "mod", "=", "divmod", "(", "max_number_of_links", ",", "2", ")", "if", "not", "mod", "==", "1", ":", "msg", "=", "'Max number of links must be odd, was %r.'", ...
Returns a generator of tuples (string, page_number, clickable), where `string` is the text of the html link, `page_number` is the number of the page the link points to, and `clickable` is a boolean indicating whether the link is clickable or not.
[ "Returns", "a", "generator", "of", "tuples", "(", "string", "page_number", "clickable", ")", "where", "string", "is", "the", "text", "of", "the", "html", "link", "page_number", "is", "the", "number", "of", "the", "page", "the", "link", "points", "to", "and...
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/pagination.py#L91-L180
openstates/billy
billy/bin/update.py
_run_scraper
def _run_scraper(scraper_type, options, metadata): """ scraper_type: bills, legislators, committees, votes """ _clear_scraped_data(options.output_dir, scraper_type) scraper = _get_configured_scraper(scraper_type, options, metadata) ua_email = os.environ.get('BILLY_UA_EMAIL') if ua_email...
python
def _run_scraper(scraper_type, options, metadata): """ scraper_type: bills, legislators, committees, votes """ _clear_scraped_data(options.output_dir, scraper_type) scraper = _get_configured_scraper(scraper_type, options, metadata) ua_email = os.environ.get('BILLY_UA_EMAIL') if ua_email...
[ "def", "_run_scraper", "(", "scraper_type", ",", "options", ",", "metadata", ")", ":", "_clear_scraped_data", "(", "options", ".", "output_dir", ",", "scraper_type", ")", "scraper", "=", "_get_configured_scraper", "(", "scraper_type", ",", "options", ",", "metadat...
scraper_type: bills, legislators, committees, votes
[ "scraper_type", ":", "bills", "legislators", "committees", "votes" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/bin/update.py#L58-L115
openstates/billy
billy/importers/bills.py
import_bill
def import_bill(data, standalone_votes, categorizer): """ insert or update a bill data - raw bill JSON standalone_votes - votes scraped separately categorizer - SubjectCategorizer (None - no categorization) """ abbr = data[settings.LEVEL_FIELD] # clean up bill_ids d...
python
def import_bill(data, standalone_votes, categorizer): """ insert or update a bill data - raw bill JSON standalone_votes - votes scraped separately categorizer - SubjectCategorizer (None - no categorization) """ abbr = data[settings.LEVEL_FIELD] # clean up bill_ids d...
[ "def", "import_bill", "(", "data", ",", "standalone_votes", ",", "categorizer", ")", ":", "abbr", "=", "data", "[", "settings", ".", "LEVEL_FIELD", "]", "# clean up bill_ids", "data", "[", "'bill_id'", "]", "=", "fix_bill_id", "(", "data", "[", "'bill_id'", ...
insert or update a bill data - raw bill JSON standalone_votes - votes scraped separately categorizer - SubjectCategorizer (None - no categorization)
[ "insert", "or", "update", "a", "bill" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/bills.py#L175-L385
openstates/billy
billy/importers/bills.py
populate_current_fields
def populate_current_fields(abbr): """ Set/update _current_term and _current_session fields on all bills for a given location. """ meta = db.metadata.find_one({'_id': abbr}) current_term = meta['terms'][-1] current_session = current_term['sessions'][-1] for bill in db.bills.find({settin...
python
def populate_current_fields(abbr): """ Set/update _current_term and _current_session fields on all bills for a given location. """ meta = db.metadata.find_one({'_id': abbr}) current_term = meta['terms'][-1] current_session = current_term['sessions'][-1] for bill in db.bills.find({settin...
[ "def", "populate_current_fields", "(", "abbr", ")", ":", "meta", "=", "db", ".", "metadata", ".", "find_one", "(", "{", "'_id'", ":", "abbr", "}", ")", "current_term", "=", "meta", "[", "'terms'", "]", "[", "-", "1", "]", "current_session", "=", "curre...
Set/update _current_term and _current_session fields on all bills for a given location.
[ "Set", "/", "update", "_current_term", "and", "_current_session", "fields", "on", "all", "bills", "for", "a", "given", "location", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/bills.py#L429-L449
openstates/billy
billy/importers/bills.py
GenericIDMatcher.learn_ids
def learn_ids(self, item_list): """ read in already set ids on objects """ self._reset_sequence() for item in item_list: key = self.nondup_key_for_item(item) self.ids[key] = item[self.id_key]
python
def learn_ids(self, item_list): """ read in already set ids on objects """ self._reset_sequence() for item in item_list: key = self.nondup_key_for_item(item) self.ids[key] = item[self.id_key]
[ "def", "learn_ids", "(", "self", ",", "item_list", ")", ":", "self", ".", "_reset_sequence", "(", ")", "for", "item", "in", "item_list", ":", "key", "=", "self", ".", "nondup_key_for_item", "(", "item", ")", "self", ".", "ids", "[", "key", "]", "=", ...
read in already set ids on objects
[ "read", "in", "already", "set", "ids", "on", "objects" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/bills.py#L522-L527
openstates/billy
billy/importers/bills.py
GenericIDMatcher.set_ids
def set_ids(self, item_list): """ set ids on an object, using internal mapping then new ids """ self._reset_sequence() for item in item_list: key = self.nondup_key_for_item(item) item[self.id_key] = self.ids.get(key) or self._get_next_id()
python
def set_ids(self, item_list): """ set ids on an object, using internal mapping then new ids """ self._reset_sequence() for item in item_list: key = self.nondup_key_for_item(item) item[self.id_key] = self.ids.get(key) or self._get_next_id()
[ "def", "set_ids", "(", "self", ",", "item_list", ")", ":", "self", ".", "_reset_sequence", "(", ")", "for", "item", "in", "item_list", ":", "key", "=", "self", ".", "nondup_key_for_item", "(", "item", ")", "item", "[", "self", ".", "id_key", "]", "=", ...
set ids on an object, using internal mapping then new ids
[ "set", "ids", "on", "an", "object", "using", "internal", "mapping", "then", "new", "ids" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/bills.py#L529-L534
openstates/billy
billy/importers/committees.py
import_committees_from_legislators
def import_committees_from_legislators(current_term, abbr): """ create committees from legislators that have committee roles """ # for all current legislators for legislator in db.legislators.find({'roles': {'$elemMatch': { 'term': current_term, settings.LEVEL_FIELD: abbr}}}): # for al...
python
def import_committees_from_legislators(current_term, abbr): """ create committees from legislators that have committee roles """ # for all current legislators for legislator in db.legislators.find({'roles': {'$elemMatch': { 'term': current_term, settings.LEVEL_FIELD: abbr}}}): # for al...
[ "def", "import_committees_from_legislators", "(", "current_term", ",", "abbr", ")", ":", "# for all current legislators", "for", "legislator", "in", "db", ".", "legislators", ".", "find", "(", "{", "'roles'", ":", "{", "'$elemMatch'", ":", "{", "'term'", ":", "c...
create committees from legislators that have committee roles
[ "create", "committees", "from", "legislators", "that", "have", "committee", "roles" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/committees.py#L16-L63
openstates/billy
billy/scrape/bills.py
Bill.add_sponsor
def add_sponsor(self, type, name, **kwargs): """ Associate a sponsor with this bill. :param type: the type of sponsorship, e.g. 'primary', 'cosponsor' :param name: the name of the sponsor as provided by the official source """ self['sponsors'].append(dict(type=type, name...
python
def add_sponsor(self, type, name, **kwargs): """ Associate a sponsor with this bill. :param type: the type of sponsorship, e.g. 'primary', 'cosponsor' :param name: the name of the sponsor as provided by the official source """ self['sponsors'].append(dict(type=type, name...
[ "def", "add_sponsor", "(", "self", ",", "type", ",", "name", ",", "*", "*", "kwargs", ")", ":", "self", "[", "'sponsors'", "]", ".", "append", "(", "dict", "(", "type", "=", "type", ",", "name", "=", "name", ",", "*", "*", "kwargs", ")", ")" ]
Associate a sponsor with this bill. :param type: the type of sponsorship, e.g. 'primary', 'cosponsor' :param name: the name of the sponsor as provided by the official source
[ "Associate", "a", "sponsor", "with", "this", "bill", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/bills.py#L71-L78
openstates/billy
billy/scrape/bills.py
Bill.add_version
def add_version(self, name, url, mimetype=None, on_duplicate='error', **kwargs): """ Add a version of the text of this bill. :param name: a name given to this version of the text, e.g. 'As Introduced', 'Version 2', 'As amended', 'Enrolled' :param...
python
def add_version(self, name, url, mimetype=None, on_duplicate='error', **kwargs): """ Add a version of the text of this bill. :param name: a name given to this version of the text, e.g. 'As Introduced', 'Version 2', 'As amended', 'Enrolled' :param...
[ "def", "add_version", "(", "self", ",", "name", ",", "url", ",", "mimetype", "=", "None", ",", "on_duplicate", "=", "'error'", ",", "*", "*", "kwargs", ")", ":", "if", "not", "mimetype", ":", "raise", "ValueError", "(", "'mimetype parameter to add_version is...
Add a version of the text of this bill. :param name: a name given to this version of the text, e.g. 'As Introduced', 'Version 2', 'As amended', 'Enrolled' :param url: the location of this version on the legislative website. :param mimetype: MIME type of the document ...
[ "Add", "a", "version", "of", "the", "text", "of", "this", "bill", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/bills.py#L99-L132
openstates/billy
billy/scrape/bills.py
Bill.add_action
def add_action(self, actor, action, date, type=None, committees=None, legislators=None, **kwargs): """ Add an action that was performed on this bill. :param actor: a string representing who performed the action. If the action is associated with one of the chambers t...
python
def add_action(self, actor, action, date, type=None, committees=None, legislators=None, **kwargs): """ Add an action that was performed on this bill. :param actor: a string representing who performed the action. If the action is associated with one of the chambers t...
[ "def", "add_action", "(", "self", ",", "actor", ",", "action", ",", "date", ",", "type", "=", "None", ",", "committees", "=", "None", ",", "legislators", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_cleanup_list", "(", "obj", ",", "defaul...
Add an action that was performed on this bill. :param actor: a string representing who performed the action. If the action is associated with one of the chambers this should be 'upper' or 'lower'. Alternatively, this could be the name of a committee, a specific legislator, or an o...
[ "Add", "an", "action", "that", "was", "performed", "on", "this", "bill", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/bills.py#L134-L188
openstates/billy
billy/scrape/bills.py
Bill.add_companion
def add_companion(self, bill_id, session=None, chamber=None): """ Associate another bill with this one. If session isn't set it will be set to self['session']. """ companion = {'bill_id': bill_id, 'session': session or self['session'], '...
python
def add_companion(self, bill_id, session=None, chamber=None): """ Associate another bill with this one. If session isn't set it will be set to self['session']. """ companion = {'bill_id': bill_id, 'session': session or self['session'], '...
[ "def", "add_companion", "(", "self", ",", "bill_id", ",", "session", "=", "None", ",", "chamber", "=", "None", ")", ":", "companion", "=", "{", "'bill_id'", ":", "bill_id", ",", "'session'", ":", "session", "or", "self", "[", "'session'", "]", ",", "'c...
Associate another bill with this one. If session isn't set it will be set to self['session'].
[ "Associate", "another", "bill", "with", "this", "one", "." ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/bills.py#L203-L212
openstates/billy
billy/web/public/views/misc.py
homepage
def homepage(request): ''' Context: all_metadata Templates: - billy/web/public/homepage.html ''' all_metadata = db.metadata.find() return render(request, templatename('homepage'), dict(all_metadata=all_metadata))
python
def homepage(request): ''' Context: all_metadata Templates: - billy/web/public/homepage.html ''' all_metadata = db.metadata.find() return render(request, templatename('homepage'), dict(all_metadata=all_metadata))
[ "def", "homepage", "(", "request", ")", ":", "all_metadata", "=", "db", ".", "metadata", ".", "find", "(", ")", "return", "render", "(", "request", ",", "templatename", "(", "'homepage'", ")", ",", "dict", "(", "all_metadata", "=", "all_metadata", ")", "...
Context: all_metadata Templates: - billy/web/public/homepage.html
[ "Context", ":", "all_metadata" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/misc.py#L24-L35
openstates/billy
billy/web/public/views/misc.py
downloads
def downloads(request): ''' Context: - all_metadata Templates: - billy/web/public/downloads.html ''' all_metadata = sorted(db.metadata.find(), key=lambda x: x['name']) return render(request, 'billy/web/public/downloads.html', {'all_metadata': all_metadata})
python
def downloads(request): ''' Context: - all_metadata Templates: - billy/web/public/downloads.html ''' all_metadata = sorted(db.metadata.find(), key=lambda x: x['name']) return render(request, 'billy/web/public/downloads.html', {'all_metadata': all_metadata})
[ "def", "downloads", "(", "request", ")", ":", "all_metadata", "=", "sorted", "(", "db", ".", "metadata", ".", "find", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "'name'", "]", ")", "return", "render", "(", "request", ",", "'billy/web/pu...
Context: - all_metadata Templates: - billy/web/public/downloads.html
[ "Context", ":", "-", "all_metadata" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/misc.py#L38-L48
openstates/billy
billy/web/public/views/misc.py
find_your_legislator
def find_your_legislator(request): ''' Context: - request - lat - long - located - legislators Templates: - billy/web/public/find_your_legislator_table.html ''' # check if lat/lon are set # if leg_search is set, they most likely don't have ECMASc...
python
def find_your_legislator(request): ''' Context: - request - lat - long - located - legislators Templates: - billy/web/public/find_your_legislator_table.html ''' # check if lat/lon are set # if leg_search is set, they most likely don't have ECMASc...
[ "def", "find_your_legislator", "(", "request", ")", ":", "# check if lat/lon are set", "# if leg_search is set, they most likely don't have ECMAScript enabled.", "# XXX: fallback behavior here for alpha.", "get", "=", "request", ".", "GET", "context", "=", "{", "}", "template", ...
Context: - request - lat - long - located - legislators Templates: - billy/web/public/find_your_legislator_table.html
[ "Context", ":", "-", "request", "-", "lat", "-", "long", "-", "located", "-", "legislators" ]
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/misc.py#L51-L110