repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
stevearc/dql
dql/models.py
TableMeta.get_indexes
def get_indexes(self): """ Get a dict of index names to index """ ret = {} for index in self.iter_query_indexes(): ret[index.name] = index return ret
python
def get_indexes(self): """ Get a dict of index names to index """ ret = {} for index in self.iter_query_indexes(): ret[index.name] = index return ret
[ "def", "get_indexes", "(", "self", ")", ":", "ret", "=", "{", "}", "for", "index", "in", "self", ".", "iter_query_indexes", "(", ")", ":", "ret", "[", "index", ".", "name", "]", "=", "index", "return", "ret" ]
Get a dict of index names to index
[ "Get", "a", "dict", "of", "index", "names", "to", "index" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L443-L448
train
29,900
stevearc/dql
dql/models.py
TableMeta.from_description
def from_description(cls, table): """ Factory method that uses the dynamo3 'describe' return value """ throughput = table.provisioned_throughput attrs = {} for data in getattr(table, "attribute_definitions", []): field = TableField(data["AttributeName"], TYPES_REV[data["AttributeType"]]) attrs[field.name] = field for data in getattr(table, "key_schema", []): name = data["AttributeName"] attrs[name].key_type = data["KeyType"] for index in getattr(table, "local_secondary_indexes", []): for data in index["KeySchema"]: if data["KeyType"] == "RANGE": name = data["AttributeName"] index_type = index["Projection"]["ProjectionType"] includes = index["Projection"].get("NonKeyAttributes") attrs[name] = attrs[name].to_index( index_type, index["IndexName"], includes ) break global_indexes = {} for index in getattr(table, "global_secondary_indexes", []): idx = GlobalIndex.from_description(index, attrs) global_indexes[idx.name] = idx return cls( table, attrs, global_indexes, throughput["ReadCapacityUnits"], throughput["WriteCapacityUnits"], throughput["NumberOfDecreasesToday"], table.table_size_bytes, )
python
def from_description(cls, table): """ Factory method that uses the dynamo3 'describe' return value """ throughput = table.provisioned_throughput attrs = {} for data in getattr(table, "attribute_definitions", []): field = TableField(data["AttributeName"], TYPES_REV[data["AttributeType"]]) attrs[field.name] = field for data in getattr(table, "key_schema", []): name = data["AttributeName"] attrs[name].key_type = data["KeyType"] for index in getattr(table, "local_secondary_indexes", []): for data in index["KeySchema"]: if data["KeyType"] == "RANGE": name = data["AttributeName"] index_type = index["Projection"]["ProjectionType"] includes = index["Projection"].get("NonKeyAttributes") attrs[name] = attrs[name].to_index( index_type, index["IndexName"], includes ) break global_indexes = {} for index in getattr(table, "global_secondary_indexes", []): idx = GlobalIndex.from_description(index, attrs) global_indexes[idx.name] = idx return cls( table, attrs, global_indexes, throughput["ReadCapacityUnits"], throughput["WriteCapacityUnits"], throughput["NumberOfDecreasesToday"], table.table_size_bytes, )
[ "def", "from_description", "(", "cls", ",", "table", ")", ":", "throughput", "=", "table", ".", "provisioned_throughput", "attrs", "=", "{", "}", "for", "data", "in", "getattr", "(", "table", ",", "\"attribute_definitions\"", ",", "[", "]", ")", ":", "fiel...
Factory method that uses the dynamo3 'describe' return value
[ "Factory", "method", "that", "uses", "the", "dynamo3", "describe", "return", "value" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L451-L483
train
29,901
stevearc/dql
dql/models.py
TableMeta.primary_key_attributes
def primary_key_attributes(self): """ Get the names of the primary key attributes as a tuple """ if self.range_key is None: return (self.hash_key.name,) else: return (self.hash_key.name, self.range_key.name)
python
def primary_key_attributes(self): """ Get the names of the primary key attributes as a tuple """ if self.range_key is None: return (self.hash_key.name,) else: return (self.hash_key.name, self.range_key.name)
[ "def", "primary_key_attributes", "(", "self", ")", ":", "if", "self", ".", "range_key", "is", "None", ":", "return", "(", "self", ".", "hash_key", ".", "name", ",", ")", "else", ":", "return", "(", "self", ".", "hash_key", ".", "name", ",", "self", "...
Get the names of the primary key attributes as a tuple
[ "Get", "the", "names", "of", "the", "primary", "key", "attributes", "as", "a", "tuple" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L489-L494
train
29,902
stevearc/dql
dql/models.py
TableMeta.primary_key_tuple
def primary_key_tuple(self, item): """ Get the primary key tuple from an item """ if self.range_key is None: return (item[self.hash_key.name],) else: return (item[self.hash_key.name], item[self.range_key.name])
python
def primary_key_tuple(self, item): """ Get the primary key tuple from an item """ if self.range_key is None: return (item[self.hash_key.name],) else: return (item[self.hash_key.name], item[self.range_key.name])
[ "def", "primary_key_tuple", "(", "self", ",", "item", ")", ":", "if", "self", ".", "range_key", "is", "None", ":", "return", "(", "item", "[", "self", ".", "hash_key", ".", "name", "]", ",", ")", "else", ":", "return", "(", "item", "[", "self", "."...
Get the primary key tuple from an item
[ "Get", "the", "primary", "key", "tuple", "from", "an", "item" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L496-L501
train
29,903
stevearc/dql
dql/models.py
TableMeta.primary_key
def primary_key(self, hkey, rkey=None): """ Construct a primary key dictionary You can either pass in a (hash_key[, range_key]) as the arguments, or you may pass in an Item itself """ if isinstance(hkey, dict): def decode(val): """ Convert Decimals back to primitives """ if isinstance(val, Decimal): return float(val) return val pkey = {self.hash_key.name: decode(hkey[self.hash_key.name])} if self.range_key is not None: pkey[self.range_key.name] = decode(hkey[self.range_key.name]) return pkey else: pkey = {self.hash_key.name: hkey} if self.range_key is not None: if rkey is None: raise ValueError("Range key is missing!") pkey[self.range_key.name] = rkey return pkey
python
def primary_key(self, hkey, rkey=None): """ Construct a primary key dictionary You can either pass in a (hash_key[, range_key]) as the arguments, or you may pass in an Item itself """ if isinstance(hkey, dict): def decode(val): """ Convert Decimals back to primitives """ if isinstance(val, Decimal): return float(val) return val pkey = {self.hash_key.name: decode(hkey[self.hash_key.name])} if self.range_key is not None: pkey[self.range_key.name] = decode(hkey[self.range_key.name]) return pkey else: pkey = {self.hash_key.name: hkey} if self.range_key is not None: if rkey is None: raise ValueError("Range key is missing!") pkey[self.range_key.name] = rkey return pkey
[ "def", "primary_key", "(", "self", ",", "hkey", ",", "rkey", "=", "None", ")", ":", "if", "isinstance", "(", "hkey", ",", "dict", ")", ":", "def", "decode", "(", "val", ")", ":", "\"\"\" Convert Decimals back to primitives \"\"\"", "if", "isinstance", "(", ...
Construct a primary key dictionary You can either pass in a (hash_key[, range_key]) as the arguments, or you may pass in an Item itself
[ "Construct", "a", "primary", "key", "dictionary" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L503-L529
train
29,904
stevearc/dql
dql/models.py
TableMeta.total_read_throughput
def total_read_throughput(self): """ Combined read throughput of table and global indexes """ total = self.read_throughput for index in itervalues(self.global_indexes): total += index.read_throughput return total
python
def total_read_throughput(self): """ Combined read throughput of table and global indexes """ total = self.read_throughput for index in itervalues(self.global_indexes): total += index.read_throughput return total
[ "def", "total_read_throughput", "(", "self", ")", ":", "total", "=", "self", ".", "read_throughput", "for", "index", "in", "itervalues", "(", "self", ".", "global_indexes", ")", ":", "total", "+=", "index", ".", "read_throughput", "return", "total" ]
Combined read throughput of table and global indexes
[ "Combined", "read", "throughput", "of", "table", "and", "global", "indexes" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L532-L537
train
29,905
stevearc/dql
dql/models.py
TableMeta.total_write_throughput
def total_write_throughput(self): """ Combined write throughput of table and global indexes """ total = self.write_throughput for index in itervalues(self.global_indexes): total += index.write_throughput return total
python
def total_write_throughput(self): """ Combined write throughput of table and global indexes """ total = self.write_throughput for index in itervalues(self.global_indexes): total += index.write_throughput return total
[ "def", "total_write_throughput", "(", "self", ")", ":", "total", "=", "self", ".", "write_throughput", "for", "index", "in", "itervalues", "(", "self", ".", "global_indexes", ")", ":", "total", "+=", "index", ".", "write_throughput", "return", "total" ]
Combined write throughput of table and global indexes
[ "Combined", "write", "throughput", "of", "table", "and", "global", "indexes" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L540-L545
train
29,906
stevearc/dql
dql/models.py
TableMeta.schema
def schema(self): """ The DQL query that will construct this table's schema """ attrs = self.attrs.copy() parts = ["CREATE", "TABLE", self.name, "(%s," % self.hash_key.schema] del attrs[self.hash_key.name] if self.range_key: parts.append(self.range_key.schema + ",") del attrs[self.range_key.name] if attrs: attr_def = ", ".join([attr.schema for attr in itervalues(attrs)]) parts.append(attr_def + ",") parts.append( "THROUGHPUT (%d, %d))" % (self.read_throughput, self.write_throughput) ) parts.extend([g.schema for g in itervalues(self.global_indexes)]) return " ".join(parts) + ";"
python
def schema(self): """ The DQL query that will construct this table's schema """ attrs = self.attrs.copy() parts = ["CREATE", "TABLE", self.name, "(%s," % self.hash_key.schema] del attrs[self.hash_key.name] if self.range_key: parts.append(self.range_key.schema + ",") del attrs[self.range_key.name] if attrs: attr_def = ", ".join([attr.schema for attr in itervalues(attrs)]) parts.append(attr_def + ",") parts.append( "THROUGHPUT (%d, %d))" % (self.read_throughput, self.write_throughput) ) parts.extend([g.schema for g in itervalues(self.global_indexes)]) return " ".join(parts) + ";"
[ "def", "schema", "(", "self", ")", ":", "attrs", "=", "self", ".", "attrs", ".", "copy", "(", ")", "parts", "=", "[", "\"CREATE\"", ",", "\"TABLE\"", ",", "self", ".", "name", ",", "\"(%s,\"", "%", "self", ".", "hash_key", ".", "schema", "]", "del"...
The DQL query that will construct this table's schema
[ "The", "DQL", "query", "that", "will", "construct", "this", "table", "s", "schema" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L574-L590
train
29,907
stevearc/dql
dql/models.py
TableMeta.pformat
def pformat(self): """ Pretty string format """ lines = [] lines.append(("%s (%s)" % (self.name, self.status)).center(50, "-")) lines.append("items: {0:,} ({1:,} bytes)".format(self.item_count, self.size)) cap = self.consumed_capacity.get("__table__", {}) read = "Read: " + format_throughput(self.read_throughput, cap.get("read")) write = "Write: " + format_throughput(self.write_throughput, cap.get("write")) lines.append(read + " " + write) if self.decreases_today > 0: lines.append("decreases today: %d" % self.decreases_today) if self.range_key is None: lines.append(str(self.hash_key)) else: lines.append("%s, %s" % (self.hash_key, self.range_key)) for field in itervalues(self.attrs): if field.key_type == "INDEX": lines.append(str(field)) for index_name, gindex in iteritems(self.global_indexes): cap = self.consumed_capacity.get(index_name) lines.append(gindex.pformat(cap)) return "\n".join(lines)
python
def pformat(self): """ Pretty string format """ lines = [] lines.append(("%s (%s)" % (self.name, self.status)).center(50, "-")) lines.append("items: {0:,} ({1:,} bytes)".format(self.item_count, self.size)) cap = self.consumed_capacity.get("__table__", {}) read = "Read: " + format_throughput(self.read_throughput, cap.get("read")) write = "Write: " + format_throughput(self.write_throughput, cap.get("write")) lines.append(read + " " + write) if self.decreases_today > 0: lines.append("decreases today: %d" % self.decreases_today) if self.range_key is None: lines.append(str(self.hash_key)) else: lines.append("%s, %s" % (self.hash_key, self.range_key)) for field in itervalues(self.attrs): if field.key_type == "INDEX": lines.append(str(field)) for index_name, gindex in iteritems(self.global_indexes): cap = self.consumed_capacity.get(index_name) lines.append(gindex.pformat(cap)) return "\n".join(lines)
[ "def", "pformat", "(", "self", ")", ":", "lines", "=", "[", "]", "lines", ".", "append", "(", "(", "\"%s (%s)\"", "%", "(", "self", ".", "name", ",", "self", ".", "status", ")", ")", ".", "center", "(", "50", ",", "\"-\"", ")", ")", "lines", "....
Pretty string format
[ "Pretty", "string", "format" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L592-L617
train
29,908
stevearc/dql
dql/util.py
resolve
def resolve(val): """ Convert a pyparsing value to the python type """ name = val.getName() if name == "number": try: return int(val.number) except ValueError: return Decimal(val.number) elif name == "str": return unwrap(val.str) elif name == "null": return None elif name == "binary": return Binary(val.binary[2:-1]) elif name == "set": if val.set == "()": return set() return set([resolve(v) for v in val.set]) elif name == "bool": return val.bool == "TRUE" elif name == "list": return [resolve(v) for v in val.list] elif name == "dict": dict_val = {} for k, v in val.dict: dict_val[resolve(k)] = resolve(v) return dict_val elif name == "ts_function": return dt_to_ts(eval_function(val.ts_function)) elif name == "ts_expression": return dt_to_ts(eval_expression(val)) else: raise SyntaxError("Unable to resolve value '%s'" % val)
python
def resolve(val): """ Convert a pyparsing value to the python type """ name = val.getName() if name == "number": try: return int(val.number) except ValueError: return Decimal(val.number) elif name == "str": return unwrap(val.str) elif name == "null": return None elif name == "binary": return Binary(val.binary[2:-1]) elif name == "set": if val.set == "()": return set() return set([resolve(v) for v in val.set]) elif name == "bool": return val.bool == "TRUE" elif name == "list": return [resolve(v) for v in val.list] elif name == "dict": dict_val = {} for k, v in val.dict: dict_val[resolve(k)] = resolve(v) return dict_val elif name == "ts_function": return dt_to_ts(eval_function(val.ts_function)) elif name == "ts_expression": return dt_to_ts(eval_expression(val)) else: raise SyntaxError("Unable to resolve value '%s'" % val)
[ "def", "resolve", "(", "val", ")", ":", "name", "=", "val", ".", "getName", "(", ")", "if", "name", "==", "\"number\"", ":", "try", ":", "return", "int", "(", "val", ".", "number", ")", "except", "ValueError", ":", "return", "Decimal", "(", "val", ...
Convert a pyparsing value to the python type
[ "Convert", "a", "pyparsing", "value", "to", "the", "python", "type" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/util.py#L56-L88
train
29,909
stevearc/dql
dql/util.py
dt_to_ts
def dt_to_ts(value): """ If value is a datetime, convert to timestamp """ if not isinstance(value, datetime): return value return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0
python
def dt_to_ts(value): """ If value is a datetime, convert to timestamp """ if not isinstance(value, datetime): return value return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0
[ "def", "dt_to_ts", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "datetime", ")", ":", "return", "value", "return", "calendar", ".", "timegm", "(", "value", ".", "utctimetuple", "(", ")", ")", "+", "value", ".", "microsecond", "...
If value is a datetime, convert to timestamp
[ "If", "value", "is", "a", "datetime", "convert", "to", "timestamp" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/util.py#L91-L95
train
29,910
stevearc/dql
dql/util.py
eval_function
def eval_function(value): """ Evaluate a timestamp function """ name, args = value[0], value[1:] if name == "NOW": return datetime.utcnow().replace(tzinfo=tzutc()) elif name in ["TIMESTAMP", "TS"]: return parse(unwrap(args[0])).replace(tzinfo=tzlocal()) elif name in ["UTCTIMESTAMP", "UTCTS"]: return parse(unwrap(args[0])).replace(tzinfo=tzutc()) elif name == "MS": return 1000 * resolve(args[0]) else: raise SyntaxError("Unrecognized function %r" % name)
python
def eval_function(value): """ Evaluate a timestamp function """ name, args = value[0], value[1:] if name == "NOW": return datetime.utcnow().replace(tzinfo=tzutc()) elif name in ["TIMESTAMP", "TS"]: return parse(unwrap(args[0])).replace(tzinfo=tzlocal()) elif name in ["UTCTIMESTAMP", "UTCTS"]: return parse(unwrap(args[0])).replace(tzinfo=tzutc()) elif name == "MS": return 1000 * resolve(args[0]) else: raise SyntaxError("Unrecognized function %r" % name)
[ "def", "eval_function", "(", "value", ")", ":", "name", ",", "args", "=", "value", "[", "0", "]", ",", "value", "[", "1", ":", "]", "if", "name", "==", "\"NOW\"", ":", "return", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", ...
Evaluate a timestamp function
[ "Evaluate", "a", "timestamp", "function" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/util.py#L98-L110
train
29,911
stevearc/dql
dql/util.py
eval_interval
def eval_interval(interval): """ Evaluate an interval expression """ kwargs = { "years": 0, "months": 0, "weeks": 0, "days": 0, "hours": 0, "minutes": 0, "seconds": 0, "microseconds": 0, } for section in interval[1:]: name = section.getName() if name == "year": kwargs["years"] += int(section[0]) elif name == "month": kwargs["months"] += int(section[0]) elif name == "week": kwargs["weeks"] += int(section[0]) elif name == "day": kwargs["days"] += int(section[0]) elif name == "hour": kwargs["hours"] += int(section[0]) elif name == "minute": kwargs["minutes"] += int(section[0]) elif name == "second": kwargs["seconds"] += int(section[0]) elif name == "millisecond": kwargs["microseconds"] += 1000 * int(section[0]) elif name == "microsecond": kwargs["microseconds"] += int(section[0]) else: raise SyntaxError("Unrecognized interval type %r: %s" % (name, section)) return relativedelta(**kwargs)
python
def eval_interval(interval): """ Evaluate an interval expression """ kwargs = { "years": 0, "months": 0, "weeks": 0, "days": 0, "hours": 0, "minutes": 0, "seconds": 0, "microseconds": 0, } for section in interval[1:]: name = section.getName() if name == "year": kwargs["years"] += int(section[0]) elif name == "month": kwargs["months"] += int(section[0]) elif name == "week": kwargs["weeks"] += int(section[0]) elif name == "day": kwargs["days"] += int(section[0]) elif name == "hour": kwargs["hours"] += int(section[0]) elif name == "minute": kwargs["minutes"] += int(section[0]) elif name == "second": kwargs["seconds"] += int(section[0]) elif name == "millisecond": kwargs["microseconds"] += 1000 * int(section[0]) elif name == "microsecond": kwargs["microseconds"] += int(section[0]) else: raise SyntaxError("Unrecognized interval type %r: %s" % (name, section)) return relativedelta(**kwargs)
[ "def", "eval_interval", "(", "interval", ")", ":", "kwargs", "=", "{", "\"years\"", ":", "0", ",", "\"months\"", ":", "0", ",", "\"weeks\"", ":", "0", ",", "\"days\"", ":", "0", ",", "\"hours\"", ":", "0", ",", "\"minutes\"", ":", "0", ",", "\"second...
Evaluate an interval expression
[ "Evaluate", "an", "interval", "expression" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/util.py#L113-L147
train
29,912
stevearc/dql
dql/util.py
eval_expression
def eval_expression(value): """ Evaluate a full time expression """ start = eval_function(value.ts_expression[0]) interval = eval_interval(value.ts_expression[2]) op = value.ts_expression[1] if op == "+": return start + interval elif op == "-": return start - interval else: raise SyntaxError("Unrecognized operator %r" % op)
python
def eval_expression(value): """ Evaluate a full time expression """ start = eval_function(value.ts_expression[0]) interval = eval_interval(value.ts_expression[2]) op = value.ts_expression[1] if op == "+": return start + interval elif op == "-": return start - interval else: raise SyntaxError("Unrecognized operator %r" % op)
[ "def", "eval_expression", "(", "value", ")", ":", "start", "=", "eval_function", "(", "value", ".", "ts_expression", "[", "0", "]", ")", "interval", "=", "eval_interval", "(", "value", ".", "ts_expression", "[", "2", "]", ")", "op", "=", "value", ".", ...
Evaluate a full time expression
[ "Evaluate", "a", "full", "time", "expression" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/util.py#L150-L160
train
29,913
stevearc/dql
doc/conf.py
linkcode_resolve
def linkcode_resolve(domain, info): """ Link source code to github """ if domain != 'py' or not info['module']: return None filename = info['module'].replace('.', '/') mod = importlib.import_module(info['module']) basename = os.path.splitext(mod.__file__)[0] if basename.endswith('__init__'): filename += '/__init__' item = mod lineno = '' for piece in info['fullname'].split('.'): item = getattr(item, piece) try: lineno = '#L%d' % inspect.getsourcelines(item)[1] except (TypeError, IOError): pass return ("https://github.com/%s/%s/blob/%s/%s.py%s" % (github_user, project, release, filename, lineno))
python
def linkcode_resolve(domain, info): """ Link source code to github """ if domain != 'py' or not info['module']: return None filename = info['module'].replace('.', '/') mod = importlib.import_module(info['module']) basename = os.path.splitext(mod.__file__)[0] if basename.endswith('__init__'): filename += '/__init__' item = mod lineno = '' for piece in info['fullname'].split('.'): item = getattr(item, piece) try: lineno = '#L%d' % inspect.getsourcelines(item)[1] except (TypeError, IOError): pass return ("https://github.com/%s/%s/blob/%s/%s.py%s" % (github_user, project, release, filename, lineno))
[ "def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "if", "domain", "!=", "'py'", "or", "not", "info", "[", "'module'", "]", ":", "return", "None", "filename", "=", "info", "[", "'module'", "]", ".", "replace", "(", "'.'", ",", "'/'", ")...
Link source code to github
[ "Link", "source", "code", "to", "github" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/doc/conf.py#L39-L57
train
29,914
stevearc/dql
dql/monitor.py
Monitor.run
def run(self, stdscr): """ Initialize curses and refresh in a loop """ self.win = stdscr curses.curs_set(0) stdscr.timeout(0) curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_RED, curses.COLOR_BLACK) while True: self.refresh(True) now = time.time() while time.time() - now < self._refresh_rate: time.sleep(0.1) self.refresh(False)
python
def run(self, stdscr): """ Initialize curses and refresh in a loop """ self.win = stdscr curses.curs_set(0) stdscr.timeout(0) curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_RED, curses.COLOR_BLACK) while True: self.refresh(True) now = time.time() while time.time() - now < self._refresh_rate: time.sleep(0.1) self.refresh(False)
[ "def", "run", "(", "self", ",", "stdscr", ")", ":", "self", ".", "win", "=", "stdscr", "curses", ".", "curs_set", "(", "0", ")", "stdscr", ".", "timeout", "(", "0", ")", "curses", ".", "init_pair", "(", "1", ",", "curses", ".", "COLOR_CYAN", ",", ...
Initialize curses and refresh in a loop
[ "Initialize", "curses", "and", "refresh", "in", "a", "loop" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/monitor.py#L37-L51
train
29,915
stevearc/dql
dql/monitor.py
Monitor._calc_min_width
def _calc_min_width(self, table): """ Calculate the minimum allowable width for a table """ width = len(table.name) cap = table.consumed_capacity["__table__"] width = max(width, 4 + len("%.1f/%d" % (cap["read"], table.read_throughput))) width = max(width, 4 + len("%.1f/%d" % (cap["write"], table.write_throughput))) for index_name, cap in iteritems(table.consumed_capacity): if index_name == "__table__": continue index = table.global_indexes[index_name] width = max( width, 4 + len(index_name + "%.1f/%d" % (cap["read"], index.read_throughput)), ) width = max( width, 4 + len(index_name + "%.1f/%d" % (cap["write"], index.write_throughput)), ) return width
python
def _calc_min_width(self, table): """ Calculate the minimum allowable width for a table """ width = len(table.name) cap = table.consumed_capacity["__table__"] width = max(width, 4 + len("%.1f/%d" % (cap["read"], table.read_throughput))) width = max(width, 4 + len("%.1f/%d" % (cap["write"], table.write_throughput))) for index_name, cap in iteritems(table.consumed_capacity): if index_name == "__table__": continue index = table.global_indexes[index_name] width = max( width, 4 + len(index_name + "%.1f/%d" % (cap["read"], index.read_throughput)), ) width = max( width, 4 + len(index_name + "%.1f/%d" % (cap["write"], index.write_throughput)), ) return width
[ "def", "_calc_min_width", "(", "self", ",", "table", ")", ":", "width", "=", "len", "(", "table", ".", "name", ")", "cap", "=", "table", ".", "consumed_capacity", "[", "\"__table__\"", "]", "width", "=", "max", "(", "width", ",", "4", "+", "len", "("...
Calculate the minimum allowable width for a table
[ "Calculate", "the", "minimum", "allowable", "width", "for", "a", "table" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/monitor.py#L53-L72
train
29,916
stevearc/dql
dql/monitor.py
Monitor._add_throughput
def _add_throughput(self, y, x, width, op, title, available, used): """ Write a single throughput measure to a row """ percent = float(used) / available self.win.addstr(y, x, "[") # Because we have disabled scrolling, writing the lower right corner # character in a terminal can throw an error (this is inside the curses # implementation). If that happens (and it will only ever happen here), # we should just catch it and continue. try: self.win.addstr(y, x + width - 1, "]") except curses.error: pass x += 1 right = "%.1f/%d:%s" % (used, available, op) pieces = self._progress_bar(width - 2, percent, title, right) for color, text in pieces: self.win.addstr(y, x, text, curses.color_pair(color)) x += len(text)
python
def _add_throughput(self, y, x, width, op, title, available, used): """ Write a single throughput measure to a row """ percent = float(used) / available self.win.addstr(y, x, "[") # Because we have disabled scrolling, writing the lower right corner # character in a terminal can throw an error (this is inside the curses # implementation). If that happens (and it will only ever happen here), # we should just catch it and continue. try: self.win.addstr(y, x + width - 1, "]") except curses.error: pass x += 1 right = "%.1f/%d:%s" % (used, available, op) pieces = self._progress_bar(width - 2, percent, title, right) for color, text in pieces: self.win.addstr(y, x, text, curses.color_pair(color)) x += len(text)
[ "def", "_add_throughput", "(", "self", ",", "y", ",", "x", ",", "width", ",", "op", ",", "title", ",", "available", ",", "used", ")", ":", "percent", "=", "float", "(", "used", ")", "/", "available", "self", ".", "win", ".", "addstr", "(", "y", "...
Write a single throughput measure to a row
[ "Write", "a", "single", "throughput", "measure", "to", "a", "row" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/monitor.py#L94-L111
train
29,917
stevearc/dql
dql/monitor.py
Monitor.refresh
def refresh(self, fetch_data): """ Redraw the display """ self.win.erase() height, width = getmaxyx() if curses.is_term_resized(height, width): self.win.clear() curses.resizeterm(height, width) y = 1 # Starts at 1 because of date string x = 0 columns = [] column = [] for table in self._tables: desc = self.engine.describe(table, fetch_data, True) line_count = 1 + 2 * len(desc.consumed_capacity) if (column or columns) and line_count + y > height: columns.append(column) column = [] y = 1 y += line_count column.append(desc) columns.append(column) y = 1 # Calculate the min width of each column column_widths = [] for column in columns: column_widths.append(max(map(self._calc_min_width, column))) # Find how many columns we can support while len(columns) > 1 and sum(column_widths) > width - len(columns) + 1: columns.pop() column_widths.pop() effective_width = width - len(columns) + 1 # Iteratively expand columns until we fit the width or they are all max while sum(column_widths) < effective_width and any( (w < self._max_width for w in column_widths) ): smallest = min(column_widths) i = column_widths.index(smallest) column_widths[i] += 1 status = datetime.now().strftime("%H:%M:%S") status += " %d tables" % len(self._tables) num_displayed = sum(map(len, columns)) if num_displayed < len(self._tables): status += " (%d visible)" % num_displayed self.win.addstr(0, 0, status[:width]) for column, col_width in zip(columns, column_widths): for table in column: cap = table.consumed_capacity["__table__"] self.win.addstr(y, x, table.name, curses.color_pair(1)) self._add_throughput( y + 1, x, col_width, "R", "", table.read_throughput, cap["read"] ) self._add_throughput( y + 2, x, col_width, "W", "", table.write_throughput, cap["write"] ) y += 3 for index_name, cap in iteritems(table.consumed_capacity): if index_name == "__table__": continue index = table.global_indexes[index_name] self._add_throughput( y, x, col_width, "R", index_name, index.read_throughput, cap["read"], ) self._add_throughput( y + 1, x, col_width, "W", index_name, index.write_throughput, cap["write"], ) y += 2 x += col_width + 1 y = 1 self.win.refresh()
python
def refresh(self, fetch_data): """ Redraw the display """ self.win.erase() height, width = getmaxyx() if curses.is_term_resized(height, width): self.win.clear() curses.resizeterm(height, width) y = 1 # Starts at 1 because of date string x = 0 columns = [] column = [] for table in self._tables: desc = self.engine.describe(table, fetch_data, True) line_count = 1 + 2 * len(desc.consumed_capacity) if (column or columns) and line_count + y > height: columns.append(column) column = [] y = 1 y += line_count column.append(desc) columns.append(column) y = 1 # Calculate the min width of each column column_widths = [] for column in columns: column_widths.append(max(map(self._calc_min_width, column))) # Find how many columns we can support while len(columns) > 1 and sum(column_widths) > width - len(columns) + 1: columns.pop() column_widths.pop() effective_width = width - len(columns) + 1 # Iteratively expand columns until we fit the width or they are all max while sum(column_widths) < effective_width and any( (w < self._max_width for w in column_widths) ): smallest = min(column_widths) i = column_widths.index(smallest) column_widths[i] += 1 status = datetime.now().strftime("%H:%M:%S") status += " %d tables" % len(self._tables) num_displayed = sum(map(len, columns)) if num_displayed < len(self._tables): status += " (%d visible)" % num_displayed self.win.addstr(0, 0, status[:width]) for column, col_width in zip(columns, column_widths): for table in column: cap = table.consumed_capacity["__table__"] self.win.addstr(y, x, table.name, curses.color_pair(1)) self._add_throughput( y + 1, x, col_width, "R", "", table.read_throughput, cap["read"] ) self._add_throughput( y + 2, x, col_width, "W", "", table.write_throughput, cap["write"] ) y += 3 for index_name, cap in iteritems(table.consumed_capacity): if index_name == "__table__": continue index = table.global_indexes[index_name] self._add_throughput( y, x, col_width, "R", index_name, index.read_throughput, cap["read"], ) self._add_throughput( y + 1, x, col_width, "W", index_name, index.write_throughput, cap["write"], ) y += 2 x += col_width + 1 y = 1 self.win.refresh()
[ "def", "refresh", "(", "self", ",", "fetch_data", ")", ":", "self", ".", "win", ".", "erase", "(", ")", "height", ",", "width", "=", "getmaxyx", "(", ")", "if", "curses", ".", "is_term_resized", "(", "height", ",", "width", ")", ":", "self", ".", "...
Redraw the display
[ "Redraw", "the", "display" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/monitor.py#L113-L198
train
29,918
stevearc/dql
dql/expressions/selection.py
add
def add(a, b): """ Add two values, ignoring None """ if a is None: if b is None: return None else: return b elif b is None: return a return a + b
python
def add(a, b): """ Add two values, ignoring None """ if a is None: if b is None: return None else: return b elif b is None: return a return a + b
[ "def", "add", "(", "a", ",", "b", ")", ":", "if", "a", "is", "None", ":", "if", "b", "is", "None", ":", "return", "None", "else", ":", "return", "b", "elif", "b", "is", "None", ":", "return", "a", "return", "a", "+", "b" ]
Add two values, ignoring None
[ "Add", "two", "values", "ignoring", "None" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/selection.py#L16-L25
train
29,919
stevearc/dql
dql/expressions/selection.py
sub
def sub(a, b): """ Subtract two values, ignoring None """ if a is None: if b is None: return None else: return -1 * b elif b is None: return a return a - b
python
def sub(a, b): """ Subtract two values, ignoring None """ if a is None: if b is None: return None else: return -1 * b elif b is None: return a return a - b
[ "def", "sub", "(", "a", ",", "b", ")", ":", "if", "a", "is", "None", ":", "if", "b", "is", "None", ":", "return", "None", "else", ":", "return", "-", "1", "*", "b", "elif", "b", "is", "None", ":", "return", "a", "return", "a", "-", "b" ]
Subtract two values, ignoring None
[ "Subtract", "two", "values", "ignoring", "None" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/selection.py#L28-L37
train
29,920
stevearc/dql
dql/expressions/selection.py
mul
def mul(a, b): """ Multiply two values, ignoring None """ if a is None: if b is None: return None else: return b elif b is None: return a return a * b
python
def mul(a, b): """ Multiply two values, ignoring None """ if a is None: if b is None: return None else: return b elif b is None: return a return a * b
[ "def", "mul", "(", "a", ",", "b", ")", ":", "if", "a", "is", "None", ":", "if", "b", "is", "None", ":", "return", "None", "else", ":", "return", "b", "elif", "b", "is", "None", ":", "return", "a", "return", "a", "*", "b" ]
Multiply two values, ignoring None
[ "Multiply", "two", "values", "ignoring", "None" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/selection.py#L40-L49
train
29,921
stevearc/dql
dql/expressions/selection.py
div
def div(a, b): """ Divide two values, ignoring None """ if a is None: if b is None: return None else: return 1 / b elif b is None: return a return a / b
python
def div(a, b): """ Divide two values, ignoring None """ if a is None: if b is None: return None else: return 1 / b elif b is None: return a return a / b
[ "def", "div", "(", "a", ",", "b", ")", ":", "if", "a", "is", "None", ":", "if", "b", "is", "None", ":", "return", "None", "else", ":", "return", "1", "/", "b", "elif", "b", "is", "None", ":", "return", "a", "return", "a", "/", "b" ]
Divide two values, ignoring None
[ "Divide", "two", "values", "ignoring", "None" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/selection.py#L52-L61
train
29,922
stevearc/dql
dql/expressions/selection.py
parse_expression
def parse_expression(clause): """ For a clause that could be a field, value, or expression """ if isinstance(clause, Expression): return clause elif hasattr(clause, "getName") and clause.getName() != "field": if clause.getName() == "nested": return AttributeSelection.from_statement(clause) elif clause.getName() == "function": return SelectFunction.from_statement(clause) else: return Value(resolve(clause[0])) else: return Field(clause[0])
python
def parse_expression(clause): """ For a clause that could be a field, value, or expression """ if isinstance(clause, Expression): return clause elif hasattr(clause, "getName") and clause.getName() != "field": if clause.getName() == "nested": return AttributeSelection.from_statement(clause) elif clause.getName() == "function": return SelectFunction.from_statement(clause) else: return Value(resolve(clause[0])) else: return Field(clause[0])
[ "def", "parse_expression", "(", "clause", ")", ":", "if", "isinstance", "(", "clause", ",", "Expression", ")", ":", "return", "clause", "elif", "hasattr", "(", "clause", ",", "\"getName\"", ")", "and", "clause", ".", "getName", "(", ")", "!=", "\"field\"",...
For a clause that could be a field, value, or expression
[ "For", "a", "clause", "that", "could", "be", "a", "field", "value", "or", "expression" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/selection.py#L67-L79
train
29,923
stevearc/dql
dql/expressions/selection.py
SelectFunction.from_statement
def from_statement(cls, statement): """ Create a selection function from a statement """ if statement[0] in ["TS", "TIMESTAMP", "UTCTIMESTAMP", "UTCTS"]: return TimestampFunction.from_statement(statement) elif statement[0] in ["NOW", "UTCNOW"]: return NowFunction.from_statement(statement) else: raise SyntaxError("Unknown function %r" % statement[0])
python
def from_statement(cls, statement): """ Create a selection function from a statement """ if statement[0] in ["TS", "TIMESTAMP", "UTCTIMESTAMP", "UTCTS"]: return TimestampFunction.from_statement(statement) elif statement[0] in ["NOW", "UTCNOW"]: return NowFunction.from_statement(statement) else: raise SyntaxError("Unknown function %r" % statement[0])
[ "def", "from_statement", "(", "cls", ",", "statement", ")", ":", "if", "statement", "[", "0", "]", "in", "[", "\"TS\"", ",", "\"TIMESTAMP\"", ",", "\"UTCTIMESTAMP\"", ",", "\"UTCTS\"", "]", ":", "return", "TimestampFunction", ".", "from_statement", "(", "sta...
Create a selection function from a statement
[ "Create", "a", "selection", "function", "from", "a", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/selection.py#L246-L253
train
29,924
stevearc/dql
dql/grammar/query.py
select_functions
def select_functions(expr): """ Create the function expressions for selection """ body = Group(expr) return Group( function("timestamp", body, caseless=True) | function("ts", body, caseless=True) | function("utctimestamp", body, caseless=True) | function("utcts", body, caseless=True) | function("now", caseless=True) | function("utcnow", caseless=True) ).setResultsName("function")
python
def select_functions(expr): """ Create the function expressions for selection """ body = Group(expr) return Group( function("timestamp", body, caseless=True) | function("ts", body, caseless=True) | function("utctimestamp", body, caseless=True) | function("utcts", body, caseless=True) | function("now", caseless=True) | function("utcnow", caseless=True) ).setResultsName("function")
[ "def", "select_functions", "(", "expr", ")", ":", "body", "=", "Group", "(", "expr", ")", "return", "Group", "(", "function", "(", "\"timestamp\"", ",", "body", ",", "caseless", "=", "True", ")", "|", "function", "(", "\"ts\"", ",", "body", ",", "casel...
Create the function expressions for selection
[ "Create", "the", "function", "expressions", "for", "selection" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/query.py#L30-L40
train
29,925
stevearc/dql
dql/grammar/query.py
create_selection
def create_selection(): """ Create a selection expression """ operation = Forward() nested = Group(Suppress("(") + operation + Suppress(")")).setResultsName("nested") select_expr = Forward() functions = select_functions(select_expr) maybe_nested = functions | nested | Group(var_val) operation <<= maybe_nested + OneOrMore(oneOf("+ - * /") + maybe_nested) select_expr <<= operation | maybe_nested alias = Group(Suppress(upkey("as")) + var).setResultsName("alias") full_select = Group( Group(select_expr).setResultsName("selection") + Optional(alias) ) return Group( Keyword("*") | upkey("count(*)") | delimitedList(full_select) ).setResultsName("attrs")
python
def create_selection(): """ Create a selection expression """ operation = Forward() nested = Group(Suppress("(") + operation + Suppress(")")).setResultsName("nested") select_expr = Forward() functions = select_functions(select_expr) maybe_nested = functions | nested | Group(var_val) operation <<= maybe_nested + OneOrMore(oneOf("+ - * /") + maybe_nested) select_expr <<= operation | maybe_nested alias = Group(Suppress(upkey("as")) + var).setResultsName("alias") full_select = Group( Group(select_expr).setResultsName("selection") + Optional(alias) ) return Group( Keyword("*") | upkey("count(*)") | delimitedList(full_select) ).setResultsName("attrs")
[ "def", "create_selection", "(", ")", ":", "operation", "=", "Forward", "(", ")", "nested", "=", "Group", "(", "Suppress", "(", "\"(\"", ")", "+", "operation", "+", "Suppress", "(", "\")\"", ")", ")", ".", "setResultsName", "(", "\"nested\"", ")", "select...
Create a selection expression
[ "Create", "a", "selection", "expression" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/query.py#L43-L58
train
29,926
stevearc/dql
dql/grammar/query.py
create_query_constraint
def create_query_constraint(): """ Create a constraint for a query WHERE clause """ op = oneOf("= < > >= <= != <>", caseless=True).setName("operator") basic_constraint = (var + op + var_val).setResultsName("operator") between = ( var + Suppress(upkey("between")) + value + Suppress(and_) + value ).setResultsName("between") is_in = (var + Suppress(upkey("in")) + set_).setResultsName("in") fxn = ( function("attribute_exists", var) | function("attribute_not_exists", var) | function("attribute_type", var, types) | function("begins_with", var, Group(string)) | function("contains", var, value) | (function("size", var) + op + value) ).setResultsName("function") all_constraints = between | basic_constraint | is_in | fxn return Group(all_constraints).setName("constraint")
python
def create_query_constraint(): """ Create a constraint for a query WHERE clause """ op = oneOf("= < > >= <= != <>", caseless=True).setName("operator") basic_constraint = (var + op + var_val).setResultsName("operator") between = ( var + Suppress(upkey("between")) + value + Suppress(and_) + value ).setResultsName("between") is_in = (var + Suppress(upkey("in")) + set_).setResultsName("in") fxn = ( function("attribute_exists", var) | function("attribute_not_exists", var) | function("attribute_type", var, types) | function("begins_with", var, Group(string)) | function("contains", var, value) | (function("size", var) + op + value) ).setResultsName("function") all_constraints = between | basic_constraint | is_in | fxn return Group(all_constraints).setName("constraint")
[ "def", "create_query_constraint", "(", ")", ":", "op", "=", "oneOf", "(", "\"= < > >= <= != <>\"", ",", "caseless", "=", "True", ")", ".", "setName", "(", "\"operator\"", ")", "basic_constraint", "=", "(", "var", "+", "op", "+", "var_val", ")", ".", "setRe...
Create a constraint for a query WHERE clause
[ "Create", "a", "constraint", "for", "a", "query", "WHERE", "clause" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/query.py#L61-L78
train
29,927
stevearc/dql
dql/grammar/query.py
create_where
def create_where(): """ Create a grammar for the 'where' clause used by 'select' """ conjunction = Forward().setResultsName("conjunction") nested = Group(Suppress("(") + conjunction + Suppress(")")).setResultsName( "conjunction" ) maybe_nested = nested | constraint inverted = Group(not_ + maybe_nested).setResultsName("not") full_constraint = maybe_nested | inverted conjunction <<= full_constraint + OneOrMore(and_or + full_constraint) return upkey("where") + Group(conjunction | full_constraint).setResultsName("where")
python
def create_where(): """ Create a grammar for the 'where' clause used by 'select' """ conjunction = Forward().setResultsName("conjunction") nested = Group(Suppress("(") + conjunction + Suppress(")")).setResultsName( "conjunction" ) maybe_nested = nested | constraint inverted = Group(not_ + maybe_nested).setResultsName("not") full_constraint = maybe_nested | inverted conjunction <<= full_constraint + OneOrMore(and_or + full_constraint) return upkey("where") + Group(conjunction | full_constraint).setResultsName("where")
[ "def", "create_where", "(", ")", ":", "conjunction", "=", "Forward", "(", ")", ".", "setResultsName", "(", "\"conjunction\"", ")", "nested", "=", "Group", "(", "Suppress", "(", "\"(\"", ")", "+", "conjunction", "+", "Suppress", "(", "\")\"", ")", ")", "....
Create a grammar for the 'where' clause used by 'select'
[ "Create", "a", "grammar", "for", "the", "where", "clause", "used", "by", "select" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/query.py#L86-L97
train
29,928
stevearc/dql
dql/grammar/query.py
create_keys_in
def create_keys_in(): """ Create a grammer for the 'KEYS IN' clause used for queries """ keys = Group( Optional(Suppress("(")) + value + Optional(Suppress(",") + value) + Optional(Suppress(")")) ) return (Suppress(upkey("keys") + upkey("in")) + delimitedList(keys)).setResultsName( "keys_in" )
python
def create_keys_in(): """ Create a grammer for the 'KEYS IN' clause used for queries """ keys = Group( Optional(Suppress("(")) + value + Optional(Suppress(",") + value) + Optional(Suppress(")")) ) return (Suppress(upkey("keys") + upkey("in")) + delimitedList(keys)).setResultsName( "keys_in" )
[ "def", "create_keys_in", "(", ")", ":", "keys", "=", "Group", "(", "Optional", "(", "Suppress", "(", "\"(\"", ")", ")", "+", "value", "+", "Optional", "(", "Suppress", "(", "\",\"", ")", "+", "value", ")", "+", "Optional", "(", "Suppress", "(", "\")\...
Create a grammer for the 'KEYS IN' clause used for queries
[ "Create", "a", "grammer", "for", "the", "KEYS", "IN", "clause", "used", "for", "queries" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/query.py#L100-L110
train
29,929
stevearc/dql
dql/expressions/base.py
Field.evaluate
def evaluate(self, item): """ Pull the field off the item """ try: for match in PATH_PATTERN.finditer(self.field): path = match.group(0) if path[0] == "[": # If we're selecting an item at a specific index of an # array, we will usually not get back the whole array from # Dynamo. It'll return an array with one element. try: item = item[int(match.group(1))] except IndexError: item = item[0] else: item = item.get(path) except (IndexError, TypeError, AttributeError): return None return item
python
def evaluate(self, item): """ Pull the field off the item """ try: for match in PATH_PATTERN.finditer(self.field): path = match.group(0) if path[0] == "[": # If we're selecting an item at a specific index of an # array, we will usually not get back the whole array from # Dynamo. It'll return an array with one element. try: item = item[int(match.group(1))] except IndexError: item = item[0] else: item = item.get(path) except (IndexError, TypeError, AttributeError): return None return item
[ "def", "evaluate", "(", "self", ",", "item", ")", ":", "try", ":", "for", "match", "in", "PATH_PATTERN", ".", "finditer", "(", "self", ".", "field", ")", ":", "path", "=", "match", ".", "group", "(", "0", ")", "if", "path", "[", "0", "]", "==", ...
Pull the field off the item
[ "Pull", "the", "field", "off", "the", "item" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/base.py#L35-L52
train
29,930
stevearc/dql
bin/install.py
main
def main(): """ Build a standalone dql executable """ venv_dir = tempfile.mkdtemp() try: make_virtualenv(venv_dir) print("Downloading dependencies") pip = os.path.join(venv_dir, "bin", "pip") subprocess.check_call([pip, "install", "pex"]) print("Building executable") pex = os.path.join(venv_dir, "bin", "pex") subprocess.check_call([pex, "dql", "-m", "dql:main", "-o", "dql"]) print("dql executable written to %s" % os.path.abspath("dql")) finally: shutil.rmtree(venv_dir)
python
def main(): """ Build a standalone dql executable """ venv_dir = tempfile.mkdtemp() try: make_virtualenv(venv_dir) print("Downloading dependencies") pip = os.path.join(venv_dir, "bin", "pip") subprocess.check_call([pip, "install", "pex"]) print("Building executable") pex = os.path.join(venv_dir, "bin", "pex") subprocess.check_call([pex, "dql", "-m", "dql:main", "-o", "dql"]) print("dql executable written to %s" % os.path.abspath("dql")) finally: shutil.rmtree(venv_dir)
[ "def", "main", "(", ")", ":", "venv_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "make_virtualenv", "(", "venv_dir", ")", "print", "(", "\"Downloading dependencies\"", ")", "pip", "=", "os", ".", "path", ".", "join", "(", "venv_dir", ",",...
Build a standalone dql executable
[ "Build", "a", "standalone", "dql", "executable" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/bin/install.py#L39-L55
train
29,931
stevearc/dql
dql/expressions/visitor.py
Visitor._maybe_replace_path
def _maybe_replace_path(self, match): """ Regex replacement method that will sub paths when needed """ path = match.group(0) if self._should_replace(path): return self._replace_path(path) else: return path
python
def _maybe_replace_path(self, match): """ Regex replacement method that will sub paths when needed """ path = match.group(0) if self._should_replace(path): return self._replace_path(path) else: return path
[ "def", "_maybe_replace_path", "(", "self", ",", "match", ")", ":", "path", "=", "match", ".", "group", "(", "0", ")", "if", "self", ".", "_should_replace", "(", "path", ")", ":", "return", "self", ".", "_replace_path", "(", "path", ")", "else", ":", ...
Regex replacement method that will sub paths when needed
[ "Regex", "replacement", "method", "that", "will", "sub", "paths", "when", "needed" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/visitor.py#L39-L45
train
29,932
stevearc/dql
dql/expressions/visitor.py
Visitor._should_replace
def _should_replace(self, path): """ True if should replace the path """ return ( self._reserved_words is None or path.upper() in self._reserved_words or "-" in path )
python
def _should_replace(self, path): """ True if should replace the path """ return ( self._reserved_words is None or path.upper() in self._reserved_words or "-" in path )
[ "def", "_should_replace", "(", "self", ",", "path", ")", ":", "return", "(", "self", ".", "_reserved_words", "is", "None", "or", "path", ".", "upper", "(", ")", "in", "self", ".", "_reserved_words", "or", "\"-\"", "in", "path", ")" ]
True if should replace the path
[ "True", "if", "should", "replace", "the", "path" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/visitor.py#L47-L53
train
29,933
stevearc/dql
dql/expressions/visitor.py
Visitor._replace_path
def _replace_path(self, path): """ Get the replacement value for a path """ if path in self._field_to_key: return self._field_to_key[path] next_key = "#f%d" % self._next_field self._next_field += 1 self._field_to_key[path] = next_key self._fields[next_key] = path return next_key
python
def _replace_path(self, path): """ Get the replacement value for a path """ if path in self._field_to_key: return self._field_to_key[path] next_key = "#f%d" % self._next_field self._next_field += 1 self._field_to_key[path] = next_key self._fields[next_key] = path return next_key
[ "def", "_replace_path", "(", "self", ",", "path", ")", ":", "if", "path", "in", "self", ".", "_field_to_key", ":", "return", "self", ".", "_field_to_key", "[", "path", "]", "next_key", "=", "\"#f%d\"", "%", "self", ".", "_next_field", "self", ".", "_next...
Get the replacement value for a path
[ "Get", "the", "replacement", "value", "for", "a", "path" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/visitor.py#L55-L63
train
29,934
stevearc/dql
dql/output.py
wrap
def wrap(string, length, indent): """ Wrap a string at a line length """ newline = "\n" + " " * indent return newline.join((string[i : i + length] for i in range(0, len(string), length)))
python
def wrap(string, length, indent): """ Wrap a string at a line length """ newline = "\n" + " " * indent return newline.join((string[i : i + length] for i in range(0, len(string), length)))
[ "def", "wrap", "(", "string", ",", "length", ",", "indent", ")", ":", "newline", "=", "\"\\n\"", "+", "\" \"", "*", "indent", "return", "newline", ".", "join", "(", "(", "string", "[", "i", ":", "i", "+", "length", "]", "for", "i", "in", "range", ...
Wrap a string at a line length
[ "Wrap", "a", "string", "at", "a", "line", "length" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L41-L44
train
29,935
stevearc/dql
dql/output.py
format_json
def format_json(json_object, indent): """ Pretty-format json data """ indent_str = "\n" + " " * indent json_str = json.dumps(json_object, indent=2, default=serialize_json_var) return indent_str.join(json_str.split("\n"))
python
def format_json(json_object, indent): """ Pretty-format json data """ indent_str = "\n" + " " * indent json_str = json.dumps(json_object, indent=2, default=serialize_json_var) return indent_str.join(json_str.split("\n"))
[ "def", "format_json", "(", "json_object", ",", "indent", ")", ":", "indent_str", "=", "\"\\n\"", "+", "\" \"", "*", "indent", "json_str", "=", "json", ".", "dumps", "(", "json_object", ",", "indent", "=", "2", ",", "default", "=", "serialize_json_var", ")"...
Pretty-format json data
[ "Pretty", "-", "format", "json", "data" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L55-L59
train
29,936
stevearc/dql
dql/output.py
delta_to_str
def delta_to_str(rd): """ Convert a relativedelta to a human-readable string """ parts = [] if rd.days > 0: parts.append("%d day%s" % (rd.days, plural(rd.days))) clock_parts = [] if rd.hours > 0: clock_parts.append("%02d" % rd.hours) if rd.minutes > 0 or rd.hours > 0: clock_parts.append("%02d" % rd.minutes) if rd.seconds > 0 or rd.minutes > 0 or rd.hours > 0: clock_parts.append("%02d" % rd.seconds) if clock_parts: parts.append(":".join(clock_parts)) return " ".join(parts)
python
def delta_to_str(rd): """ Convert a relativedelta to a human-readable string """ parts = [] if rd.days > 0: parts.append("%d day%s" % (rd.days, plural(rd.days))) clock_parts = [] if rd.hours > 0: clock_parts.append("%02d" % rd.hours) if rd.minutes > 0 or rd.hours > 0: clock_parts.append("%02d" % rd.minutes) if rd.seconds > 0 or rd.minutes > 0 or rd.hours > 0: clock_parts.append("%02d" % rd.seconds) if clock_parts: parts.append(":".join(clock_parts)) return " ".join(parts)
[ "def", "delta_to_str", "(", "rd", ")", ":", "parts", "=", "[", "]", "if", "rd", ".", "days", ">", "0", ":", "parts", ".", "append", "(", "\"%d day%s\"", "%", "(", "rd", ".", "days", ",", "plural", "(", "rd", ".", "days", ")", ")", ")", "clock_p...
Convert a relativedelta to a human-readable string
[ "Convert", "a", "relativedelta", "to", "a", "human", "-", "readable", "string" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L62-L76
train
29,937
stevearc/dql
dql/output.py
less_display
def less_display(): """ Use smoke and mirrors to acquire 'less' for pretty paging """ # here's some magic. We want the nice paging from 'less', so we write # the output to a file and use subprocess to run 'less' on the file. # But the file might have sensitive data, so open it in 0600 mode. _, filename = tempfile.mkstemp() mode = stat.S_IRUSR | stat.S_IWUSR outfile = None outfile = os.fdopen(os.open(filename, os.O_WRONLY | os.O_CREAT, mode), "wb") try: yield SmartBuffer(outfile) outfile.flush() subprocess.call(["less", "-FXR", filename]) finally: if outfile is not None: outfile.close() if os.path.exists(filename): os.unlink(filename)
python
def less_display(): """ Use smoke and mirrors to acquire 'less' for pretty paging """ # here's some magic. We want the nice paging from 'less', so we write # the output to a file and use subprocess to run 'less' on the file. # But the file might have sensitive data, so open it in 0600 mode. _, filename = tempfile.mkstemp() mode = stat.S_IRUSR | stat.S_IWUSR outfile = None outfile = os.fdopen(os.open(filename, os.O_WRONLY | os.O_CREAT, mode), "wb") try: yield SmartBuffer(outfile) outfile.flush() subprocess.call(["less", "-FXR", filename]) finally: if outfile is not None: outfile.close() if os.path.exists(filename): os.unlink(filename)
[ "def", "less_display", "(", ")", ":", "# here's some magic. We want the nice paging from 'less', so we write", "# the output to a file and use subprocess to run 'less' on the file.", "# But the file might have sensitive data, so open it in 0600 mode.", "_", ",", "filename", "=", "tempfile", ...
Use smoke and mirrors to acquire 'less' for pretty paging
[ "Use", "smoke", "and", "mirrors", "to", "acquire", "less", "for", "pretty", "paging" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L305-L322
train
29,938
stevearc/dql
dql/output.py
stdout_display
def stdout_display(): """ Print results straight to stdout """ if sys.version_info[0] == 2: yield SmartBuffer(sys.stdout) else: yield SmartBuffer(sys.stdout.buffer)
python
def stdout_display(): """ Print results straight to stdout """ if sys.version_info[0] == 2: yield SmartBuffer(sys.stdout) else: yield SmartBuffer(sys.stdout.buffer)
[ "def", "stdout_display", "(", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "yield", "SmartBuffer", "(", "sys", ".", "stdout", ")", "else", ":", "yield", "SmartBuffer", "(", "sys", ".", "stdout", ".", "buffer", ")" ]
Print results straight to stdout
[ "Print", "results", "straight", "to", "stdout" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L326-L331
train
29,939
stevearc/dql
dql/output.py
BaseFormat.display
def display(self): """ Write results to an output stream """ total = 0 count = 0 for i, result in enumerate(self._results): if total == 0: self.pre_write() self.write(result) count += 1 total += 1 if ( count >= self.pagesize and self.pagesize > 0 and i < len(self._results) - 1 ): self.wait() count = 0 if total == 0: self._ostream.write("No results\n") else: self.post_write()
python
def display(self): """ Write results to an output stream """ total = 0 count = 0 for i, result in enumerate(self._results): if total == 0: self.pre_write() self.write(result) count += 1 total += 1 if ( count >= self.pagesize and self.pagesize > 0 and i < len(self._results) - 1 ): self.wait() count = 0 if total == 0: self._ostream.write("No results\n") else: self.post_write()
[ "def", "display", "(", "self", ")", ":", "total", "=", "0", "count", "=", "0", "for", "i", ",", "result", "in", "enumerate", "(", "self", ".", "_results", ")", ":", "if", "total", "==", "0", ":", "self", ".", "pre_write", "(", ")", "self", ".", ...
Write results to an output stream
[ "Write", "results", "to", "an", "output", "stream" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L109-L129
train
29,940
stevearc/dql
dql/output.py
BaseFormat.format_field
def format_field(self, field): """ Format a single Dynamo value """ if field is None: return "NULL" elif isinstance(field, TypeError): return "TypeError" elif isinstance(field, Decimal): if field % 1 == 0: return str(int(field)) return str(float(field)) elif isinstance(field, set): return "(" + ", ".join([self.format_field(v) for v in field]) + ")" elif isinstance(field, datetime): return field.isoformat() elif isinstance(field, timedelta): rd = relativedelta( seconds=int(field.total_seconds()), microseconds=field.microseconds ) return delta_to_str(rd) elif isinstance(field, Binary): return "<Binary %d>" % len(field.value) pretty = repr(field) if pretty.startswith("u'"): return pretty[1:] return pretty
python
def format_field(self, field): """ Format a single Dynamo value """ if field is None: return "NULL" elif isinstance(field, TypeError): return "TypeError" elif isinstance(field, Decimal): if field % 1 == 0: return str(int(field)) return str(float(field)) elif isinstance(field, set): return "(" + ", ".join([self.format_field(v) for v in field]) + ")" elif isinstance(field, datetime): return field.isoformat() elif isinstance(field, timedelta): rd = relativedelta( seconds=int(field.total_seconds()), microseconds=field.microseconds ) return delta_to_str(rd) elif isinstance(field, Binary): return "<Binary %d>" % len(field.value) pretty = repr(field) if pretty.startswith("u'"): return pretty[1:] return pretty
[ "def", "format_field", "(", "self", ",", "field", ")", ":", "if", "field", "is", "None", ":", "return", "\"NULL\"", "elif", "isinstance", "(", "field", ",", "TypeError", ")", ":", "return", "\"TypeError\"", "elif", "isinstance", "(", "field", ",", "Decimal...
Format a single Dynamo value
[ "Format", "a", "single", "Dynamo", "value" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L147-L171
train
29,941
stevearc/dql
dql/output.py
ColumnFormat._write_header
def _write_header(self): """ Write out the table header """ self._ostream.write(len(self._header) * "-" + "\n") self._ostream.write(self._header) self._ostream.write("\n") self._ostream.write(len(self._header) * "-" + "\n")
python
def _write_header(self): """ Write out the table header """ self._ostream.write(len(self._header) * "-" + "\n") self._ostream.write(self._header) self._ostream.write("\n") self._ostream.write(len(self._header) * "-" + "\n")
[ "def", "_write_header", "(", "self", ")", ":", "self", ".", "_ostream", ".", "write", "(", "len", "(", "self", ".", "_header", ")", "*", "\"-\"", "+", "\"\\n\"", ")", "self", ".", "_ostream", ".", "write", "(", "self", ".", "_header", ")", "self", ...
Write out the table header
[ "Write", "out", "the", "table", "header" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L232-L237
train
29,942
stevearc/dql
dql/output.py
SmartBuffer.write
def write(self, arg): """ Write a string or bytes object to the buffer """ if isinstance(arg, str): arg = arg.encode(self.encoding) return self._buffer.write(arg)
python
def write(self, arg): """ Write a string or bytes object to the buffer """ if isinstance(arg, str): arg = arg.encode(self.encoding) return self._buffer.write(arg)
[ "def", "write", "(", "self", ",", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "str", ")", ":", "arg", "=", "arg", ".", "encode", "(", "self", ".", "encoding", ")", "return", "self", ".", "_buffer", ".", "write", "(", "arg", ")" ]
Write a string or bytes object to the buffer
[ "Write", "a", "string", "or", "bytes", "object", "to", "the", "buffer" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L293-L297
train
29,943
stevearc/dql
dql/cli.py
prompt
def prompt(msg, default=NO_DEFAULT, validate=None): """ Prompt user for input """ while True: response = input(msg + " ").strip() if not response: if default is NO_DEFAULT: continue return default if validate is None or validate(response): return response
python
def prompt(msg, default=NO_DEFAULT, validate=None): """ Prompt user for input """ while True: response = input(msg + " ").strip() if not response: if default is NO_DEFAULT: continue return default if validate is None or validate(response): return response
[ "def", "prompt", "(", "msg", ",", "default", "=", "NO_DEFAULT", ",", "validate", "=", "None", ")", ":", "while", "True", ":", "response", "=", "input", "(", "msg", "+", "\" \"", ")", ".", "strip", "(", ")", "if", "not", "response", ":", "if", "defa...
Prompt user for input
[ "Prompt", "user", "for", "input" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L78-L87
train
29,944
stevearc/dql
dql/cli.py
promptyn
def promptyn(msg, default=None): """ Display a blocking prompt until the user confirms """ while True: yes = "Y" if default else "y" if default or default is None: no = "n" else: no = "N" confirm = prompt("%s [%s/%s]" % (msg, yes, no), "").lower() if confirm in ("y", "yes"): return True elif confirm in ("n", "no"): return False elif not confirm and default is not None: return default
python
def promptyn(msg, default=None): """ Display a blocking prompt until the user confirms """ while True: yes = "Y" if default else "y" if default or default is None: no = "n" else: no = "N" confirm = prompt("%s [%s/%s]" % (msg, yes, no), "").lower() if confirm in ("y", "yes"): return True elif confirm in ("n", "no"): return False elif not confirm and default is not None: return default
[ "def", "promptyn", "(", "msg", ",", "default", "=", "None", ")", ":", "while", "True", ":", "yes", "=", "\"Y\"", "if", "default", "else", "\"y\"", "if", "default", "or", "default", "is", "None", ":", "no", "=", "\"n\"", "else", ":", "no", "=", "\"N...
Display a blocking prompt until the user confirms
[ "Display", "a", "blocking", "prompt", "until", "the", "user", "confirms" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L90-L104
train
29,945
stevearc/dql
dql/cli.py
repl_command
def repl_command(fxn): """ Decorator for cmd methods Parses arguments from the arg string and passes them to the method as *args and **kwargs. """ @functools.wraps(fxn) def wrapper(self, arglist): """Wraps the command method""" args = [] kwargs = {} if arglist: for arg in shlex.split(arglist): if "=" in arg: split = arg.split("=", 1) kwargs[split[0]] = split[1] else: args.append(arg) return fxn(self, *args, **kwargs) return wrapper
python
def repl_command(fxn): """ Decorator for cmd methods Parses arguments from the arg string and passes them to the method as *args and **kwargs. """ @functools.wraps(fxn) def wrapper(self, arglist): """Wraps the command method""" args = [] kwargs = {} if arglist: for arg in shlex.split(arglist): if "=" in arg: split = arg.split("=", 1) kwargs[split[0]] = split[1] else: args.append(arg) return fxn(self, *args, **kwargs) return wrapper
[ "def", "repl_command", "(", "fxn", ")", ":", "@", "functools", ".", "wraps", "(", "fxn", ")", "def", "wrapper", "(", "self", ",", "arglist", ")", ":", "\"\"\"Wraps the command method\"\"\"", "args", "=", "[", "]", "kwargs", "=", "{", "}", "if", "arglist"...
Decorator for cmd methods Parses arguments from the arg string and passes them to the method as *args and **kwargs.
[ "Decorator", "for", "cmd", "methods" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L107-L130
train
29,946
stevearc/dql
dql/cli.py
get_enum_key
def get_enum_key(key, choices): """ Get an enum by prefix or equality """ if key in choices: return key keys = [k for k in choices if k.startswith(key)] if len(keys) == 1: return keys[0]
python
def get_enum_key(key, choices): """ Get an enum by prefix or equality """ if key in choices: return key keys = [k for k in choices if k.startswith(key)] if len(keys) == 1: return keys[0]
[ "def", "get_enum_key", "(", "key", ",", "choices", ")", ":", "if", "key", "in", "choices", ":", "return", "key", "keys", "=", "[", "k", "for", "k", "in", "choices", "if", "k", ".", "startswith", "(", "key", ")", "]", "if", "len", "(", "keys", ")"...
Get an enum by prefix or equality
[ "Get", "an", "enum", "by", "prefix", "or", "equality" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L133-L139
train
29,947
stevearc/dql
dql/cli.py
DQLClient.initialize
def initialize( self, region="us-west-1", host=None, port=8000, config_dir=None, session=None ): """ Set up the repl for execution. """ try: import readline import rlcompleter except ImportError: # Windows doesn't have readline, so gracefully ignore. pass else: # Mac OS X readline compatibility from http://stackoverflow.com/a/7116997 if "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") # Tab-complete names with a '-' in them delims = set(readline.get_completer_delims()) if "-" in delims: delims.remove("-") readline.set_completer_delims("".join(delims)) self._conf_dir = config_dir or os.path.join( os.environ.get("HOME", "."), ".config" ) self.session = session or botocore.session.get_session() self.engine = FragmentEngine() self.engine.caution_callback = self.caution_callback if host is not None: self._local_endpoint = (host, port) self.engine.connect( region, session=self.session, host=host, port=port, is_secure=(host is None) ) self.conf = self.load_config() for key, value in iteritems(DEFAULT_CONFIG): self.conf.setdefault(key, value) self.display = DISPLAYS[self.conf["display"]] self.throttle = TableLimits() self.throttle.load(self.conf["_throttle"])
python
def initialize( self, region="us-west-1", host=None, port=8000, config_dir=None, session=None ): """ Set up the repl for execution. """ try: import readline import rlcompleter except ImportError: # Windows doesn't have readline, so gracefully ignore. pass else: # Mac OS X readline compatibility from http://stackoverflow.com/a/7116997 if "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") # Tab-complete names with a '-' in them delims = set(readline.get_completer_delims()) if "-" in delims: delims.remove("-") readline.set_completer_delims("".join(delims)) self._conf_dir = config_dir or os.path.join( os.environ.get("HOME", "."), ".config" ) self.session = session or botocore.session.get_session() self.engine = FragmentEngine() self.engine.caution_callback = self.caution_callback if host is not None: self._local_endpoint = (host, port) self.engine.connect( region, session=self.session, host=host, port=port, is_secure=(host is None) ) self.conf = self.load_config() for key, value in iteritems(DEFAULT_CONFIG): self.conf.setdefault(key, value) self.display = DISPLAYS[self.conf["display"]] self.throttle = TableLimits() self.throttle.load(self.conf["_throttle"])
[ "def", "initialize", "(", "self", ",", "region", "=", "\"us-west-1\"", ",", "host", "=", "None", ",", "port", "=", "8000", ",", "config_dir", "=", "None", ",", "session", "=", "None", ")", ":", "try", ":", "import", "readline", "import", "rlcompleter", ...
Set up the repl for execution.
[ "Set", "up", "the", "repl", "for", "execution", "." ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L165-L204
train
29,948
stevearc/dql
dql/cli.py
DQLClient.update_prompt
def update_prompt(self): """ Update the prompt """ prefix = "" if self._local_endpoint is not None: prefix += "(%s:%d) " % self._local_endpoint prefix += self.engine.region if self.engine.partial: self.prompt = len(prefix) * " " + "> " else: self.prompt = prefix + "> "
python
def update_prompt(self): """ Update the prompt """ prefix = "" if self._local_endpoint is not None: prefix += "(%s:%d) " % self._local_endpoint prefix += self.engine.region if self.engine.partial: self.prompt = len(prefix) * " " + "> " else: self.prompt = prefix + "> "
[ "def", "update_prompt", "(", "self", ")", ":", "prefix", "=", "\"\"", "if", "self", ".", "_local_endpoint", "is", "not", "None", ":", "prefix", "+=", "\"(%s:%d) \"", "%", "self", ".", "_local_endpoint", "prefix", "+=", "self", ".", "engine", ".", "region",...
Update the prompt
[ "Update", "the", "prompt" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L227-L236
train
29,949
stevearc/dql
dql/cli.py
DQLClient.save_config
def save_config(self): """ Save the conf file """ if not os.path.exists(self._conf_dir): os.makedirs(self._conf_dir) conf_file = os.path.join(self._conf_dir, "dql.json") with open(conf_file, "w") as ofile: json.dump(self.conf, ofile, indent=2)
python
def save_config(self): """ Save the conf file """ if not os.path.exists(self._conf_dir): os.makedirs(self._conf_dir) conf_file = os.path.join(self._conf_dir, "dql.json") with open(conf_file, "w") as ofile: json.dump(self.conf, ofile, indent=2)
[ "def", "save_config", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_conf_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_conf_dir", ")", "conf_file", "=", "os", ".", "path", ".", "join", "(", ...
Save the conf file
[ "Save", "the", "conf", "file" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L254-L260
train
29,950
stevearc/dql
dql/cli.py
DQLClient.load_config
def load_config(self): """ Load your configuration settings from a file """ conf_file = os.path.join(self._conf_dir, "dql.json") if not os.path.exists(conf_file): return {} with open(conf_file, "r") as ifile: return json.load(ifile)
python
def load_config(self): """ Load your configuration settings from a file """ conf_file = os.path.join(self._conf_dir, "dql.json") if not os.path.exists(conf_file): return {} with open(conf_file, "r") as ifile: return json.load(ifile)
[ "def", "load_config", "(", "self", ")", ":", "conf_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_conf_dir", ",", "\"dql.json\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "conf_file", ")", ":", "return", "{", "}", "...
Load your configuration settings from a file
[ "Load", "your", "configuration", "settings", "from", "a", "file" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L262-L268
train
29,951
stevearc/dql
dql/cli.py
DQLClient.do_opt
def do_opt(self, *args, **kwargs): """ Get and set options """ args = list(args) if not args: largest = 0 keys = [key for key in self.conf if not key.startswith("_")] for key in keys: largest = max(largest, len(key)) for key in keys: print("%s : %s" % (key.rjust(largest), self.conf[key])) return option = args.pop(0) if not args and not kwargs: method = getattr(self, "getopt_" + option, None) if method is None: self.getopt_default(option) else: method() else: method = getattr(self, "opt_" + option, None) if method is None: print("Unrecognized option %r" % option) else: method(*args, **kwargs) self.save_config()
python
def do_opt(self, *args, **kwargs): """ Get and set options """ args = list(args) if not args: largest = 0 keys = [key for key in self.conf if not key.startswith("_")] for key in keys: largest = max(largest, len(key)) for key in keys: print("%s : %s" % (key.rjust(largest), self.conf[key])) return option = args.pop(0) if not args and not kwargs: method = getattr(self, "getopt_" + option, None) if method is None: self.getopt_default(option) else: method() else: method = getattr(self, "opt_" + option, None) if method is None: print("Unrecognized option %r" % option) else: method(*args, **kwargs) self.save_config()
[ "def", "do_opt", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "if", "not", "args", ":", "largest", "=", "0", "keys", "=", "[", "key", "for", "key", "in", "self", ".", "conf", "if", "...
Get and set options
[ "Get", "and", "set", "options" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L271-L295
train
29,952
stevearc/dql
dql/cli.py
DQLClient.getopt_default
def getopt_default(self, option): """ Default method to get an option """ if option not in self.conf: print("Unrecognized option %r" % option) return print("%s: %s" % (option, self.conf[option]))
python
def getopt_default(self, option): """ Default method to get an option """ if option not in self.conf: print("Unrecognized option %r" % option) return print("%s: %s" % (option, self.conf[option]))
[ "def", "getopt_default", "(", "self", ",", "option", ")", ":", "if", "option", "not", "in", "self", ".", "conf", ":", "print", "(", "\"Unrecognized option %r\"", "%", "option", ")", "return", "print", "(", "\"%s: %s\"", "%", "(", "option", ",", "self", "...
Default method to get an option
[ "Default", "method", "to", "get", "an", "option" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L301-L306
train
29,953
stevearc/dql
dql/cli.py
DQLClient.complete_opt
def complete_opt(self, text, line, begidx, endidx): """ Autocomplete for options """ tokens = line.split() if len(tokens) == 1: if text: return else: option = "" else: option = tokens[1] if len(tokens) == 1 or (len(tokens) == 2 and text): return [ name[4:] + " " for name in dir(self) if name.startswith("opt_" + text) ] method = getattr(self, "complete_opt_" + option, None) if method is not None: return method(text, line, begidx, endidx)
python
def complete_opt(self, text, line, begidx, endidx): """ Autocomplete for options """ tokens = line.split() if len(tokens) == 1: if text: return else: option = "" else: option = tokens[1] if len(tokens) == 1 or (len(tokens) == 2 and text): return [ name[4:] + " " for name in dir(self) if name.startswith("opt_" + text) ] method = getattr(self, "complete_opt_" + option, None) if method is not None: return method(text, line, begidx, endidx)
[ "def", "complete_opt", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "tokens", "=", "line", ".", "split", "(", ")", "if", "len", "(", "tokens", ")", "==", "1", ":", "if", "text", ":", "return", "else", ":", "optio...
Autocomplete for options
[ "Autocomplete", "for", "options" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L308-L324
train
29,954
stevearc/dql
dql/cli.py
DQLClient.opt_pagesize
def opt_pagesize(self, pagesize): """ Get or set the page size of the query output """ if pagesize != "auto": pagesize = int(pagesize) self.conf["pagesize"] = pagesize
python
def opt_pagesize(self, pagesize): """ Get or set the page size of the query output """ if pagesize != "auto": pagesize = int(pagesize) self.conf["pagesize"] = pagesize
[ "def", "opt_pagesize", "(", "self", ",", "pagesize", ")", ":", "if", "pagesize", "!=", "\"auto\"", ":", "pagesize", "=", "int", "(", "pagesize", ")", "self", ".", "conf", "[", "\"pagesize\"", "]", "=", "pagesize" ]
Get or set the page size of the query output
[ "Get", "or", "set", "the", "page", "size", "of", "the", "query", "output" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L336-L340
train
29,955
stevearc/dql
dql/cli.py
DQLClient._print_enum_opt
def _print_enum_opt(self, option, choices): """ Helper for enum options """ for key in choices: if key == self.conf[option]: print("* %s" % key) else: print(" %s" % key)
python
def _print_enum_opt(self, option, choices): """ Helper for enum options """ for key in choices: if key == self.conf[option]: print("* %s" % key) else: print(" %s" % key)
[ "def", "_print_enum_opt", "(", "self", ",", "option", ",", "choices", ")", ":", "for", "key", "in", "choices", ":", "if", "key", "==", "self", ".", "conf", "[", "option", "]", ":", "print", "(", "\"* %s\"", "%", "key", ")", "else", ":", "print", "(...
Helper for enum options
[ "Helper", "for", "enum", "options" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L346-L352
train
29,956
stevearc/dql
dql/cli.py
DQLClient.opt_display
def opt_display(self, display): """ Set value for display option """ key = get_enum_key(display, DISPLAYS) if key is not None: self.conf["display"] = key self.display = DISPLAYS[key] print("Set display %r" % key) else: print("Unknown display %r" % display)
python
def opt_display(self, display): """ Set value for display option """ key = get_enum_key(display, DISPLAYS) if key is not None: self.conf["display"] = key self.display = DISPLAYS[key] print("Set display %r" % key) else: print("Unknown display %r" % display)
[ "def", "opt_display", "(", "self", ",", "display", ")", ":", "key", "=", "get_enum_key", "(", "display", ",", "DISPLAYS", ")", "if", "key", "is", "not", "None", ":", "self", ".", "conf", "[", "\"display\"", "]", "=", "key", "self", ".", "display", "=...
Set value for display option
[ "Set", "value", "for", "display", "option" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L354-L362
train
29,957
stevearc/dql
dql/cli.py
DQLClient.complete_opt_display
def complete_opt_display(self, text, *_): """ Autocomplete for display option """ return [t + " " for t in DISPLAYS if t.startswith(text)]
python
def complete_opt_display(self, text, *_): """ Autocomplete for display option """ return [t + " " for t in DISPLAYS if t.startswith(text)]
[ "def", "complete_opt_display", "(", "self", ",", "text", ",", "*", "_", ")", ":", "return", "[", "t", "+", "\" \"", "for", "t", "in", "DISPLAYS", "if", "t", ".", "startswith", "(", "text", ")", "]" ]
Autocomplete for display option
[ "Autocomplete", "for", "display", "option" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L368-L370
train
29,958
stevearc/dql
dql/cli.py
DQLClient.opt_format
def opt_format(self, fmt): """ Set value for format option """ key = get_enum_key(fmt, FORMATTERS) if key is not None: self.conf["format"] = key print("Set format %r" % key) else: print("Unknown format %r" % fmt)
python
def opt_format(self, fmt): """ Set value for format option """ key = get_enum_key(fmt, FORMATTERS) if key is not None: self.conf["format"] = key print("Set format %r" % key) else: print("Unknown format %r" % fmt)
[ "def", "opt_format", "(", "self", ",", "fmt", ")", ":", "key", "=", "get_enum_key", "(", "fmt", ",", "FORMATTERS", ")", "if", "key", "is", "not", "None", ":", "self", ".", "conf", "[", "\"format\"", "]", "=", "key", "print", "(", "\"Set format %r\"", ...
Set value for format option
[ "Set", "value", "for", "format", "option" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L372-L379
train
29,959
stevearc/dql
dql/cli.py
DQLClient.complete_opt_format
def complete_opt_format(self, text, *_): """ Autocomplete for format option """ return [t + " " for t in FORMATTERS if t.startswith(text)]
python
def complete_opt_format(self, text, *_): """ Autocomplete for format option """ return [t + " " for t in FORMATTERS if t.startswith(text)]
[ "def", "complete_opt_format", "(", "self", ",", "text", ",", "*", "_", ")", ":", "return", "[", "t", "+", "\" \"", "for", "t", "in", "FORMATTERS", "if", "t", ".", "startswith", "(", "text", ")", "]" ]
Autocomplete for format option
[ "Autocomplete", "for", "format", "option" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L385-L387
train
29,960
stevearc/dql
dql/cli.py
DQLClient.opt_allow_select_scan
def opt_allow_select_scan(self, allow): """ Set option allow_select_scan """ allow = allow.lower() in ("true", "t", "yes", "y") self.conf["allow_select_scan"] = allow self.engine.allow_select_scan = allow
python
def opt_allow_select_scan(self, allow): """ Set option allow_select_scan """ allow = allow.lower() in ("true", "t", "yes", "y") self.conf["allow_select_scan"] = allow self.engine.allow_select_scan = allow
[ "def", "opt_allow_select_scan", "(", "self", ",", "allow", ")", ":", "allow", "=", "allow", ".", "lower", "(", ")", "in", "(", "\"true\"", ",", "\"t\"", ",", "\"yes\"", ",", "\"y\"", ")", "self", ".", "conf", "[", "\"allow_select_scan\"", "]", "=", "al...
Set option allow_select_scan
[ "Set", "option", "allow_select_scan" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L389-L393
train
29,961
stevearc/dql
dql/cli.py
DQLClient.complete_opt_allow_select_scan
def complete_opt_allow_select_scan(self, text, *_): """ Autocomplete for allow_select_scan option """ return [t for t in ("true", "false", "yes", "no") if t.startswith(text.lower())]
python
def complete_opt_allow_select_scan(self, text, *_): """ Autocomplete for allow_select_scan option """ return [t for t in ("true", "false", "yes", "no") if t.startswith(text.lower())]
[ "def", "complete_opt_allow_select_scan", "(", "self", ",", "text", ",", "*", "_", ")", ":", "return", "[", "t", "for", "t", "in", "(", "\"true\"", ",", "\"false\"", ",", "\"yes\"", ",", "\"no\"", ")", "if", "t", ".", "startswith", "(", "text", ".", "...
Autocomplete for allow_select_scan option
[ "Autocomplete", "for", "allow_select_scan", "option" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L395-L397
train
29,962
stevearc/dql
dql/cli.py
DQLClient.do_watch
def do_watch(self, *args): """ Watch Dynamo tables consumed capacity """ tables = [] if not self.engine.cached_descriptions: self.engine.describe_all() all_tables = list(self.engine.cached_descriptions) for arg in args: candidates = set((t for t in all_tables if fnmatch(t, arg))) for t in sorted(candidates): if t not in tables: tables.append(t) mon = Monitor(self.engine, tables) mon.start()
python
def do_watch(self, *args): """ Watch Dynamo tables consumed capacity """ tables = [] if not self.engine.cached_descriptions: self.engine.describe_all() all_tables = list(self.engine.cached_descriptions) for arg in args: candidates = set((t for t in all_tables if fnmatch(t, arg))) for t in sorted(candidates): if t not in tables: tables.append(t) mon = Monitor(self.engine, tables) mon.start()
[ "def", "do_watch", "(", "self", ",", "*", "args", ")", ":", "tables", "=", "[", "]", "if", "not", "self", ".", "engine", ".", "cached_descriptions", ":", "self", ".", "engine", ".", "describe_all", "(", ")", "all_tables", "=", "list", "(", "self", "....
Watch Dynamo tables consumed capacity
[ "Watch", "Dynamo", "tables", "consumed", "capacity" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L400-L413
train
29,963
stevearc/dql
dql/cli.py
DQLClient.complete_watch
def complete_watch(self, text, *_): """ Autocomplete for watch """ return [t + " " for t in self.engine.cached_descriptions if t.startswith(text)]
python
def complete_watch(self, text, *_): """ Autocomplete for watch """ return [t + " " for t in self.engine.cached_descriptions if t.startswith(text)]
[ "def", "complete_watch", "(", "self", ",", "text", ",", "*", "_", ")", ":", "return", "[", "t", "+", "\" \"", "for", "t", "in", "self", ".", "engine", ".", "cached_descriptions", "if", "t", ".", "startswith", "(", "text", ")", "]" ]
Autocomplete for watch
[ "Autocomplete", "for", "watch" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L415-L417
train
29,964
stevearc/dql
dql/cli.py
DQLClient.do_file
def do_file(self, filename): """ Read and execute a .dql file """ with open(filename, "r") as infile: self._run_cmd(infile.read())
python
def do_file(self, filename): """ Read and execute a .dql file """ with open(filename, "r") as infile: self._run_cmd(infile.read())
[ "def", "do_file", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "infile", ":", "self", ".", "_run_cmd", "(", "infile", ".", "read", "(", ")", ")" ]
Read and execute a .dql file
[ "Read", "and", "execute", "a", ".", "dql", "file" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L420-L423
train
29,965
stevearc/dql
dql/cli.py
DQLClient.complete_file
def complete_file(self, text, line, *_): """ Autocomplete DQL file lookup """ leading = line[len("file ") :] curpath = os.path.join(os.path.curdir, leading) def isdql(parent, filename): """ Check if a file is .dql or a dir """ return not filename.startswith(".") and ( os.path.isdir(os.path.join(parent, filename)) or filename.lower().endswith(".dql") ) def addslash(path): """ Append a slash if a file is a directory """ if path.lower().endswith(".dql"): return path + " " else: return path + "/" if not os.path.exists(curpath) or not os.path.isdir(curpath): curpath = os.path.dirname(curpath) return [ addslash(f) for f in os.listdir(curpath) if f.startswith(text) and isdql(curpath, f) ]
python
def complete_file(self, text, line, *_): """ Autocomplete DQL file lookup """ leading = line[len("file ") :] curpath = os.path.join(os.path.curdir, leading) def isdql(parent, filename): """ Check if a file is .dql or a dir """ return not filename.startswith(".") and ( os.path.isdir(os.path.join(parent, filename)) or filename.lower().endswith(".dql") ) def addslash(path): """ Append a slash if a file is a directory """ if path.lower().endswith(".dql"): return path + " " else: return path + "/" if not os.path.exists(curpath) or not os.path.isdir(curpath): curpath = os.path.dirname(curpath) return [ addslash(f) for f in os.listdir(curpath) if f.startswith(text) and isdql(curpath, f) ]
[ "def", "complete_file", "(", "self", ",", "text", ",", "line", ",", "*", "_", ")", ":", "leading", "=", "line", "[", "len", "(", "\"file \"", ")", ":", "]", "curpath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "curdir", ...
Autocomplete DQL file lookup
[ "Autocomplete", "DQL", "file", "lookup" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L425-L450
train
29,966
stevearc/dql
dql/cli.py
DQLClient.do_ls
def do_ls(self, table=None): """ List all tables or print details of one table """ if table is None: fields = OrderedDict( [ ("Name", "name"), ("Status", "status"), ("Read", "total_read_throughput"), ("Write", "total_write_throughput"), ] ) tables = self.engine.describe_all() # Calculate max width of all items for each column sizes = [ 1 + max([len(str(getattr(t, f))) for t in tables] + [len(title)]) for title, f in iteritems(fields) ] # Print the header for size, title in zip(sizes, fields): print(title.ljust(size), end="") print() # Print each table row for row_table in tables: for size, field in zip(sizes, fields.values()): print(str(getattr(row_table, field)).ljust(size), end="") print() else: print(self.engine.describe(table, refresh=True, metrics=True).pformat())
python
def do_ls(self, table=None): """ List all tables or print details of one table """ if table is None: fields = OrderedDict( [ ("Name", "name"), ("Status", "status"), ("Read", "total_read_throughput"), ("Write", "total_write_throughput"), ] ) tables = self.engine.describe_all() # Calculate max width of all items for each column sizes = [ 1 + max([len(str(getattr(t, f))) for t in tables] + [len(title)]) for title, f in iteritems(fields) ] # Print the header for size, title in zip(sizes, fields): print(title.ljust(size), end="") print() # Print each table row for row_table in tables: for size, field in zip(sizes, fields.values()): print(str(getattr(row_table, field)).ljust(size), end="") print() else: print(self.engine.describe(table, refresh=True, metrics=True).pformat())
[ "def", "do_ls", "(", "self", ",", "table", "=", "None", ")", ":", "if", "table", "is", "None", ":", "fields", "=", "OrderedDict", "(", "[", "(", "\"Name\"", ",", "\"name\"", ")", ",", "(", "\"Status\"", ",", "\"status\"", ")", ",", "(", "\"Read\"", ...
List all tables or print details of one table
[ "List", "all", "tables", "or", "print", "details", "of", "one", "table" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L453-L480
train
29,967
stevearc/dql
dql/cli.py
DQLClient.complete_ls
def complete_ls(self, text, *_): """ Autocomplete for ls """ return [t + " " for t in self.engine.cached_descriptions if t.startswith(text)]
python
def complete_ls(self, text, *_): """ Autocomplete for ls """ return [t + " " for t in self.engine.cached_descriptions if t.startswith(text)]
[ "def", "complete_ls", "(", "self", ",", "text", ",", "*", "_", ")", ":", "return", "[", "t", "+", "\" \"", "for", "t", "in", "self", ".", "engine", ".", "cached_descriptions", "if", "t", ".", "startswith", "(", "text", ")", "]" ]
Autocomplete for ls
[ "Autocomplete", "for", "ls" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L482-L484
train
29,968
stevearc/dql
dql/cli.py
DQLClient.do_local
def do_local(self, host="localhost", port=8000): """ Connect to a local DynamoDB instance. Use 'local off' to disable. > local > local host=localhost port=8001 > local off """ port = int(port) if host == "off": self._local_endpoint = None else: self._local_endpoint = (host, port) self.onecmd("use %s" % self.engine.region)
python
def do_local(self, host="localhost", port=8000): """ Connect to a local DynamoDB instance. Use 'local off' to disable. > local > local host=localhost port=8001 > local off """ port = int(port) if host == "off": self._local_endpoint = None else: self._local_endpoint = (host, port) self.onecmd("use %s" % self.engine.region)
[ "def", "do_local", "(", "self", ",", "host", "=", "\"localhost\"", ",", "port", "=", "8000", ")", ":", "port", "=", "int", "(", "port", ")", "if", "host", "==", "\"off\"", ":", "self", ".", "_local_endpoint", "=", "None", "else", ":", "self", ".", ...
Connect to a local DynamoDB instance. Use 'local off' to disable. > local > local host=localhost port=8001 > local off
[ "Connect", "to", "a", "local", "DynamoDB", "instance", ".", "Use", "local", "off", "to", "disable", "." ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L487-L501
train
29,969
stevearc/dql
dql/cli.py
DQLClient.do_use
def do_use(self, region): """ Switch the AWS region > use us-west-1 > use us-east-1 """ if self._local_endpoint is not None: host, port = self._local_endpoint # pylint: disable=W0633 self.engine.connect( region, session=self.session, host=host, port=port, is_secure=False ) else: self.engine.connect(region, session=self.session)
python
def do_use(self, region): """ Switch the AWS region > use us-west-1 > use us-east-1 """ if self._local_endpoint is not None: host, port = self._local_endpoint # pylint: disable=W0633 self.engine.connect( region, session=self.session, host=host, port=port, is_secure=False ) else: self.engine.connect(region, session=self.session)
[ "def", "do_use", "(", "self", ",", "region", ")", ":", "if", "self", ".", "_local_endpoint", "is", "not", "None", ":", "host", ",", "port", "=", "self", ".", "_local_endpoint", "# pylint: disable=W0633", "self", ".", "engine", ".", "connect", "(", "region"...
Switch the AWS region > use us-west-1 > use us-east-1
[ "Switch", "the", "AWS", "region" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L504-L518
train
29,970
stevearc/dql
dql/cli.py
DQLClient.complete_use
def complete_use(self, text, *_): """ Autocomplete for use """ return [t + " " for t in REGIONS if t.startswith(text)]
python
def complete_use(self, text, *_): """ Autocomplete for use """ return [t + " " for t in REGIONS if t.startswith(text)]
[ "def", "complete_use", "(", "self", ",", "text", ",", "*", "_", ")", ":", "return", "[", "t", "+", "\" \"", "for", "t", "in", "REGIONS", "if", "t", ".", "startswith", "(", "text", ")", "]" ]
Autocomplete for use
[ "Autocomplete", "for", "use" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L520-L522
train
29,971
stevearc/dql
dql/cli.py
DQLClient.do_throttle
def do_throttle(self, *args): """ Set the allowed consumed throughput for DQL. # Set the total allowed throughput across all tables > throttle 1000 100 # Set the default allowed throughput per-table/index > throttle default 40% 20% # Set the allowed throughput on a table > throttle mytable 10 10 # Set the allowed throughput on a global index > throttle mytable myindex 40 6 see also: unthrottle """ args = list(args) if not args: print(self.throttle) return if len(args) < 2: return self.onecmd("help throttle") args, read, write = args[:-2], args[-2], args[-1] if len(args) == 2: tablename, indexname = args self.throttle.set_index_limit(tablename, indexname, read, write) elif len(args) == 1: tablename = args[0] if tablename == "default": self.throttle.set_default_limit(read, write) elif tablename == "total": self.throttle.set_total_limit(read, write) else: self.throttle.set_table_limit(tablename, read, write) elif not args: self.throttle.set_total_limit(read, write) else: return self.onecmd("help throttle") self.conf["_throttle"] = self.throttle.save() self.save_config()
python
def do_throttle(self, *args): """ Set the allowed consumed throughput for DQL. # Set the total allowed throughput across all tables > throttle 1000 100 # Set the default allowed throughput per-table/index > throttle default 40% 20% # Set the allowed throughput on a table > throttle mytable 10 10 # Set the allowed throughput on a global index > throttle mytable myindex 40 6 see also: unthrottle """ args = list(args) if not args: print(self.throttle) return if len(args) < 2: return self.onecmd("help throttle") args, read, write = args[:-2], args[-2], args[-1] if len(args) == 2: tablename, indexname = args self.throttle.set_index_limit(tablename, indexname, read, write) elif len(args) == 1: tablename = args[0] if tablename == "default": self.throttle.set_default_limit(read, write) elif tablename == "total": self.throttle.set_total_limit(read, write) else: self.throttle.set_table_limit(tablename, read, write) elif not args: self.throttle.set_total_limit(read, write) else: return self.onecmd("help throttle") self.conf["_throttle"] = self.throttle.save() self.save_config()
[ "def", "do_throttle", "(", "self", ",", "*", "args", ")", ":", "args", "=", "list", "(", "args", ")", "if", "not", "args", ":", "print", "(", "self", ".", "throttle", ")", "return", "if", "len", "(", "args", ")", "<", "2", ":", "return", "self", ...
Set the allowed consumed throughput for DQL. # Set the total allowed throughput across all tables > throttle 1000 100 # Set the default allowed throughput per-table/index > throttle default 40% 20% # Set the allowed throughput on a table > throttle mytable 10 10 # Set the allowed throughput on a global index > throttle mytable myindex 40 6 see also: unthrottle
[ "Set", "the", "allowed", "consumed", "throughput", "for", "DQL", "." ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L525-L564
train
29,972
stevearc/dql
dql/cli.py
DQLClient.do_unthrottle
def do_unthrottle(self, *args): """ Remove the throughput limits for DQL that were set with 'throttle' # Remove all limits > unthrottle # Remove the limit on total allowed throughput > unthrottle total # Remove the default limit > unthrottle default # Remove the limit on a table > unthrottle mytable # Remove the limit on a global index > unthrottle mytable myindex """ if not args: if promptyn("Are you sure you want to clear all throttles?"): self.throttle.load({}) elif len(args) == 1: tablename = args[0] if tablename == "total": self.throttle.set_total_limit() elif tablename == "default": self.throttle.set_default_limit() else: self.throttle.set_table_limit(tablename) elif len(args) == 2: tablename, indexname = args self.throttle.set_index_limit(tablename, indexname) else: self.onecmd("help unthrottle") self.conf["_throttle"] = self.throttle.save() self.save_config()
python
def do_unthrottle(self, *args): """ Remove the throughput limits for DQL that were set with 'throttle' # Remove all limits > unthrottle # Remove the limit on total allowed throughput > unthrottle total # Remove the default limit > unthrottle default # Remove the limit on a table > unthrottle mytable # Remove the limit on a global index > unthrottle mytable myindex """ if not args: if promptyn("Are you sure you want to clear all throttles?"): self.throttle.load({}) elif len(args) == 1: tablename = args[0] if tablename == "total": self.throttle.set_total_limit() elif tablename == "default": self.throttle.set_default_limit() else: self.throttle.set_table_limit(tablename) elif len(args) == 2: tablename, indexname = args self.throttle.set_index_limit(tablename, indexname) else: self.onecmd("help unthrottle") self.conf["_throttle"] = self.throttle.save() self.save_config()
[ "def", "do_unthrottle", "(", "self", ",", "*", "args", ")", ":", "if", "not", "args", ":", "if", "promptyn", "(", "\"Are you sure you want to clear all throttles?\"", ")", ":", "self", ".", "throttle", ".", "load", "(", "{", "}", ")", "elif", "len", "(", ...
Remove the throughput limits for DQL that were set with 'throttle' # Remove all limits > unthrottle # Remove the limit on total allowed throughput > unthrottle total # Remove the default limit > unthrottle default # Remove the limit on a table > unthrottle mytable # Remove the limit on a global index > unthrottle mytable myindex
[ "Remove", "the", "throughput", "limits", "for", "DQL", "that", "were", "set", "with", "throttle" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L567-L600
train
29,973
stevearc/dql
dql/cli.py
DQLClient.completedefault
def completedefault(self, text, line, *_): """ Autocomplete table names in queries """ tokens = line.split() try: before = tokens[-2] complete = before.lower() in ("from", "update", "table", "into") if tokens[0].lower() == "dump": complete = True if complete: return [ t + " " for t in self.engine.cached_descriptions if t.startswith(text) ] except KeyError: pass
python
def completedefault(self, text, line, *_): """ Autocomplete table names in queries """ tokens = line.split() try: before = tokens[-2] complete = before.lower() in ("from", "update", "table", "into") if tokens[0].lower() == "dump": complete = True if complete: return [ t + " " for t in self.engine.cached_descriptions if t.startswith(text) ] except KeyError: pass
[ "def", "completedefault", "(", "self", ",", "text", ",", "line", ",", "*", "_", ")", ":", "tokens", "=", "line", ".", "split", "(", ")", "try", ":", "before", "=", "tokens", "[", "-", "2", "]", "complete", "=", "before", ".", "lower", "(", ")", ...
Autocomplete table names in queries
[ "Autocomplete", "table", "names", "in", "queries" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L605-L620
train
29,974
stevearc/dql
dql/cli.py
DQLClient._run_cmd
def _run_cmd(self, command): """ Run a DQL command """ if self.throttle: tables = self.engine.describe_all(False) limiter = self.throttle.get_limiter(tables) else: limiter = None self.engine.rate_limit = limiter results = self.engine.execute(command) if results is None: pass elif isinstance(results, basestring): print(results) else: with self.display() as ostream: formatter = FORMATTERS[self.conf["format"]]( results, ostream, pagesize=self.conf["pagesize"], width=self.conf["width"], ) formatter.display() print_count = 0 total = None for (cmd_fragment, capacity) in self.engine.consumed_capacities: total += capacity print(cmd_fragment) print(indent(str(capacity))) print_count += 1 if print_count > 1: print("TOTAL") print(indent(str(total)))
python
def _run_cmd(self, command): """ Run a DQL command """ if self.throttle: tables = self.engine.describe_all(False) limiter = self.throttle.get_limiter(tables) else: limiter = None self.engine.rate_limit = limiter results = self.engine.execute(command) if results is None: pass elif isinstance(results, basestring): print(results) else: with self.display() as ostream: formatter = FORMATTERS[self.conf["format"]]( results, ostream, pagesize=self.conf["pagesize"], width=self.conf["width"], ) formatter.display() print_count = 0 total = None for (cmd_fragment, capacity) in self.engine.consumed_capacities: total += capacity print(cmd_fragment) print(indent(str(capacity))) print_count += 1 if print_count > 1: print("TOTAL") print(indent(str(total)))
[ "def", "_run_cmd", "(", "self", ",", "command", ")", ":", "if", "self", ".", "throttle", ":", "tables", "=", "self", ".", "engine", ".", "describe_all", "(", "False", ")", "limiter", "=", "self", ".", "throttle", ".", "get_limiter", "(", "tables", ")",...
Run a DQL command
[ "Run", "a", "DQL", "command" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L622-L653
train
29,975
stevearc/dql
dql/cli.py
DQLClient.run_command
def run_command(self, command): """ Run a command passed in from the command line with -c """ self.display = DISPLAYS["stdout"] self.conf["pagesize"] = 0 self.onecmd(command)
python
def run_command(self, command): """ Run a command passed in from the command line with -c """ self.display = DISPLAYS["stdout"] self.conf["pagesize"] = 0 self.onecmd(command)
[ "def", "run_command", "(", "self", ",", "command", ")", ":", "self", ".", "display", "=", "DISPLAYS", "[", "\"stdout\"", "]", "self", ".", "conf", "[", "\"pagesize\"", "]", "=", "0", "self", ".", "onecmd", "(", "command", ")" ]
Run a command passed in from the command line with -c
[ "Run", "a", "command", "passed", "in", "from", "the", "command", "line", "with", "-", "c" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/cli.py#L667-L671
train
29,976
stevearc/dql
dql/grammar/common.py
function
def function(name, *args, **kwargs): """ Construct a parser for a standard function format """ if kwargs.get("caseless"): name = upkey(name) else: name = Word(name) fxn_args = None for i, arg in enumerate(args): if i == 0: fxn_args = arg else: fxn_args += Suppress(",") + arg if fxn_args is None: return name + Suppress("(") + Suppress(")") if kwargs.get("optparen"): return name + ((Suppress("(") + fxn_args + Suppress(")")) | fxn_args) else: return name + Suppress("(") + fxn_args + Suppress(")")
python
def function(name, *args, **kwargs): """ Construct a parser for a standard function format """ if kwargs.get("caseless"): name = upkey(name) else: name = Word(name) fxn_args = None for i, arg in enumerate(args): if i == 0: fxn_args = arg else: fxn_args += Suppress(",") + arg if fxn_args is None: return name + Suppress("(") + Suppress(")") if kwargs.get("optparen"): return name + ((Suppress("(") + fxn_args + Suppress(")")) | fxn_args) else: return name + Suppress("(") + fxn_args + Suppress(")")
[ "def", "function", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "\"caseless\"", ")", ":", "name", "=", "upkey", "(", "name", ")", "else", ":", "name", "=", "Word", "(", "name", ")", "fxn_args"...
Construct a parser for a standard function format
[ "Construct", "a", "parser", "for", "a", "standard", "function", "format" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/common.py#L27-L44
train
29,977
stevearc/dql
dql/grammar/common.py
make_interval
def make_interval(long_name, short_name): """ Create an interval segment """ return Group( Regex("(-+)?[0-9]+") + ( upkey(long_name + "s") | Regex(long_name + "s").setParseAction(upcaseTokens) | upkey(long_name) | Regex(long_name).setParseAction(upcaseTokens) | upkey(short_name) | Regex(short_name).setParseAction(upcaseTokens) ) ).setResultsName(long_name)
python
def make_interval(long_name, short_name): """ Create an interval segment """ return Group( Regex("(-+)?[0-9]+") + ( upkey(long_name + "s") | Regex(long_name + "s").setParseAction(upcaseTokens) | upkey(long_name) | Regex(long_name).setParseAction(upcaseTokens) | upkey(short_name) | Regex(short_name).setParseAction(upcaseTokens) ) ).setResultsName(long_name)
[ "def", "make_interval", "(", "long_name", ",", "short_name", ")", ":", "return", "Group", "(", "Regex", "(", "\"(-+)?[0-9]+\"", ")", "+", "(", "upkey", "(", "long_name", "+", "\"s\"", ")", "|", "Regex", "(", "long_name", "+", "\"s\"", ")", ".", "setParse...
Create an interval segment
[ "Create", "an", "interval", "segment" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/common.py#L118-L130
train
29,978
stevearc/dql
dql/grammar/__init__.py
create_throughput
def create_throughput(variable=primitive): """ Create a throughput specification """ return ( Suppress(upkey("throughput") | upkey("tp")) + Suppress("(") + variable + Suppress(",") + variable + Suppress(")") ).setResultsName("throughput")
python
def create_throughput(variable=primitive): """ Create a throughput specification """ return ( Suppress(upkey("throughput") | upkey("tp")) + Suppress("(") + variable + Suppress(",") + variable + Suppress(")") ).setResultsName("throughput")
[ "def", "create_throughput", "(", "variable", "=", "primitive", ")", ":", "return", "(", "Suppress", "(", "upkey", "(", "\"throughput\"", ")", "|", "upkey", "(", "\"tp\"", ")", ")", "+", "Suppress", "(", "\"(\"", ")", "+", "variable", "+", "Suppress", "("...
Create a throughput specification
[ "Create", "a", "throughput", "specification" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L48-L57
train
29,979
stevearc/dql
dql/grammar/__init__.py
create_throttle
def create_throttle(): """ Create a THROTTLE statement """ throttle_amount = "*" | Combine(number + "%") | number return Group( function("throttle", throttle_amount, throttle_amount, caseless=True) ).setResultsName("throttle")
python
def create_throttle(): """ Create a THROTTLE statement """ throttle_amount = "*" | Combine(number + "%") | number return Group( function("throttle", throttle_amount, throttle_amount, caseless=True) ).setResultsName("throttle")
[ "def", "create_throttle", "(", ")", ":", "throttle_amount", "=", "\"*\"", "|", "Combine", "(", "number", "+", "\"%\"", ")", "|", "number", "return", "Group", "(", "function", "(", "\"throttle\"", ",", "throttle_amount", ",", "throttle_amount", ",", "caseless",...
Create a THROTTLE statement
[ "Create", "a", "THROTTLE", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L60-L65
train
29,980
stevearc/dql
dql/grammar/__init__.py
_global_index
def _global_index(): """ Create grammar for a global index declaration """ var_and_type = var + Optional(type_) global_dec = Suppress(upkey("global")) + index range_key_etc = Suppress(",") + Group(throughput) | Optional( Group(Suppress(",") + var_and_type).setResultsName("range_key") ) + Optional(Suppress(",") + include_vars) + Optional( Group(Suppress(",") + throughput) ) global_spec = ( Suppress("(") + primitive + Suppress(",") + Group(var_and_type).setResultsName("hash_key") + range_key_etc + Suppress(")") ) return Group(global_dec + global_spec).setName("global index")
python
def _global_index(): """ Create grammar for a global index declaration """ var_and_type = var + Optional(type_) global_dec = Suppress(upkey("global")) + index range_key_etc = Suppress(",") + Group(throughput) | Optional( Group(Suppress(",") + var_and_type).setResultsName("range_key") ) + Optional(Suppress(",") + include_vars) + Optional( Group(Suppress(",") + throughput) ) global_spec = ( Suppress("(") + primitive + Suppress(",") + Group(var_and_type).setResultsName("hash_key") + range_key_etc + Suppress(")") ) return Group(global_dec + global_spec).setName("global index")
[ "def", "_global_index", "(", ")", ":", "var_and_type", "=", "var", "+", "Optional", "(", "type_", ")", "global_dec", "=", "Suppress", "(", "upkey", "(", "\"global\"", ")", ")", "+", "index", "range_key_etc", "=", "Suppress", "(", "\",\"", ")", "+", "Grou...
Create grammar for a global index declaration
[ "Create", "grammar", "for", "a", "global", "index", "declaration" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L106-L123
train
29,981
stevearc/dql
dql/grammar/__init__.py
create_create
def create_create(): """ Create the grammar for the 'create' statement """ create = upkey("create").setResultsName("action") hash_key = Group(upkey("hash") + upkey("key")) range_key = Group(upkey("range") + upkey("key")) local_index = Group( index + Suppress("(") + primitive + Optional(Suppress(",") + include_vars) + Suppress(")") ) index_type = ( (hash_key | range_key | local_index) .setName("index specification") .setResultsName("index") ) attr_declaration = ( Group(var.setResultsName("name") + type_ + Optional(index_type)) .setName("attr") .setResultsName("attr") ) attrs_declaration = ( Suppress("(") + Group(delimitedList(attr_declaration)) .setName("attrs") .setResultsName("attrs") + Optional(Suppress(",") + throughput) + Suppress(")") ) global_index = _global_index() global_indexes = Group(OneOrMore(global_index)).setResultsName("global_indexes") return ( create + table_key + Optional(if_not_exists) + table + attrs_declaration + Optional(global_indexes) )
python
def create_create(): """ Create the grammar for the 'create' statement """ create = upkey("create").setResultsName("action") hash_key = Group(upkey("hash") + upkey("key")) range_key = Group(upkey("range") + upkey("key")) local_index = Group( index + Suppress("(") + primitive + Optional(Suppress(",") + include_vars) + Suppress(")") ) index_type = ( (hash_key | range_key | local_index) .setName("index specification") .setResultsName("index") ) attr_declaration = ( Group(var.setResultsName("name") + type_ + Optional(index_type)) .setName("attr") .setResultsName("attr") ) attrs_declaration = ( Suppress("(") + Group(delimitedList(attr_declaration)) .setName("attrs") .setResultsName("attrs") + Optional(Suppress(",") + throughput) + Suppress(")") ) global_index = _global_index() global_indexes = Group(OneOrMore(global_index)).setResultsName("global_indexes") return ( create + table_key + Optional(if_not_exists) + table + attrs_declaration + Optional(global_indexes) )
[ "def", "create_create", "(", ")", ":", "create", "=", "upkey", "(", "\"create\"", ")", ".", "setResultsName", "(", "\"action\"", ")", "hash_key", "=", "Group", "(", "upkey", "(", "\"hash\"", ")", "+", "upkey", "(", "\"key\"", ")", ")", "range_key", "=", ...
Create the grammar for the 'create' statement
[ "Create", "the", "grammar", "for", "the", "create", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L126-L169
train
29,982
stevearc/dql
dql/grammar/__init__.py
create_delete
def create_delete(): """ Create the grammar for the 'delete' statement """ delete = upkey("delete").setResultsName("action") return ( delete + from_ + table + Optional(keys_in) + Optional(where) + Optional(using) + Optional(throttle) )
python
def create_delete(): """ Create the grammar for the 'delete' statement """ delete = upkey("delete").setResultsName("action") return ( delete + from_ + table + Optional(keys_in) + Optional(where) + Optional(using) + Optional(throttle) )
[ "def", "create_delete", "(", ")", ":", "delete", "=", "upkey", "(", "\"delete\"", ")", ".", "setResultsName", "(", "\"action\"", ")", "return", "(", "delete", "+", "from_", "+", "table", "+", "Optional", "(", "keys_in", ")", "+", "Optional", "(", "where"...
Create the grammar for the 'delete' statement
[ "Create", "the", "grammar", "for", "the", "delete", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L172-L183
train
29,983
stevearc/dql
dql/grammar/__init__.py
create_insert
def create_insert(): """ Create the grammar for the 'insert' statement """ insert = upkey("insert").setResultsName("action") # VALUES attrs = Group(delimitedList(var)).setResultsName("attrs") value_group = Group(Suppress("(") + delimitedList(value) + Suppress(")")) values = Group(delimitedList(value_group)).setResultsName("list_values") values_insert = Suppress("(") + attrs + Suppress(")") + upkey("values") + values # KEYWORDS keyword = Group(var + Suppress("=") + value) item = Group(Suppress("(") + delimitedList(keyword) + Suppress(")")) keyword_insert = delimitedList(item).setResultsName("map_values") return insert + into + table + (values_insert | keyword_insert) + Optional(throttle)
python
def create_insert(): """ Create the grammar for the 'insert' statement """ insert = upkey("insert").setResultsName("action") # VALUES attrs = Group(delimitedList(var)).setResultsName("attrs") value_group = Group(Suppress("(") + delimitedList(value) + Suppress(")")) values = Group(delimitedList(value_group)).setResultsName("list_values") values_insert = Suppress("(") + attrs + Suppress(")") + upkey("values") + values # KEYWORDS keyword = Group(var + Suppress("=") + value) item = Group(Suppress("(") + delimitedList(keyword) + Suppress(")")) keyword_insert = delimitedList(item).setResultsName("map_values") return insert + into + table + (values_insert | keyword_insert) + Optional(throttle)
[ "def", "create_insert", "(", ")", ":", "insert", "=", "upkey", "(", "\"insert\"", ")", ".", "setResultsName", "(", "\"action\"", ")", "# VALUES", "attrs", "=", "Group", "(", "delimitedList", "(", "var", ")", ")", ".", "setResultsName", "(", "\"attrs\"", ")...
Create the grammar for the 'insert' statement
[ "Create", "the", "grammar", "for", "the", "insert", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L186-L201
train
29,984
stevearc/dql
dql/grammar/__init__.py
_create_update_expression
def _create_update_expression(): """ Create the grammar for an update expression """ ine = ( Word("if_not_exists") + Suppress("(") + var + Suppress(",") + var_val + Suppress(")") ) list_append = ( Word("list_append") + Suppress("(") + var_val + Suppress(",") + var_val + Suppress(")") ) fxn = Group(ine | list_append).setResultsName("set_function") # value has to come before var to prevent parsing TRUE/FALSE as variables path = value | fxn | var set_val = (path + oneOf("+ -") + path) | path set_cmd = Group(var + Suppress("=") + set_val) set_expr = (Suppress(upkey("set")) + delimitedList(set_cmd)).setResultsName( "set_expr" ) add_expr = ( Suppress(upkey("add")) + delimitedList(Group(var + value)) ).setResultsName("add_expr") delete_expr = ( Suppress(upkey("delete")) + delimitedList(Group(var + value)) ).setResultsName("delete_expr") remove_expr = (Suppress(upkey("remove")) + delimitedList(var)).setResultsName( "remove_expr" ) return OneOrMore(set_expr | add_expr | delete_expr | remove_expr).setResultsName( "update" )
python
def _create_update_expression(): """ Create the grammar for an update expression """ ine = ( Word("if_not_exists") + Suppress("(") + var + Suppress(",") + var_val + Suppress(")") ) list_append = ( Word("list_append") + Suppress("(") + var_val + Suppress(",") + var_val + Suppress(")") ) fxn = Group(ine | list_append).setResultsName("set_function") # value has to come before var to prevent parsing TRUE/FALSE as variables path = value | fxn | var set_val = (path + oneOf("+ -") + path) | path set_cmd = Group(var + Suppress("=") + set_val) set_expr = (Suppress(upkey("set")) + delimitedList(set_cmd)).setResultsName( "set_expr" ) add_expr = ( Suppress(upkey("add")) + delimitedList(Group(var + value)) ).setResultsName("add_expr") delete_expr = ( Suppress(upkey("delete")) + delimitedList(Group(var + value)) ).setResultsName("delete_expr") remove_expr = (Suppress(upkey("remove")) + delimitedList(var)).setResultsName( "remove_expr" ) return OneOrMore(set_expr | add_expr | delete_expr | remove_expr).setResultsName( "update" )
[ "def", "_create_update_expression", "(", ")", ":", "ine", "=", "(", "Word", "(", "\"if_not_exists\"", ")", "+", "Suppress", "(", "\"(\"", ")", "+", "var", "+", "Suppress", "(", "\",\"", ")", "+", "var_val", "+", "Suppress", "(", "\")\"", ")", ")", "lis...
Create the grammar for an update expression
[ "Create", "the", "grammar", "for", "an", "update", "expression" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L210-L247
train
29,985
stevearc/dql
dql/grammar/__init__.py
create_update
def create_update(): """ Create the grammar for the 'update' statement """ update = upkey("update").setResultsName("action") returns, none, all_, updated, old, new = map( upkey, ["returns", "none", "all", "updated", "old", "new"] ) return_ = returns + Group( none | (all_ + old) | (all_ + new) | (updated + old) | (updated + new) ).setResultsName("returns") return ( update + table + update_expr + Optional(keys_in) + Optional(where) + Optional(using) + Optional(return_) + Optional(throttle) )
python
def create_update(): """ Create the grammar for the 'update' statement """ update = upkey("update").setResultsName("action") returns, none, all_, updated, old, new = map( upkey, ["returns", "none", "all", "updated", "old", "new"] ) return_ = returns + Group( none | (all_ + old) | (all_ + new) | (updated + old) | (updated + new) ).setResultsName("returns") return ( update + table + update_expr + Optional(keys_in) + Optional(where) + Optional(using) + Optional(return_) + Optional(throttle) )
[ "def", "create_update", "(", ")", ":", "update", "=", "upkey", "(", "\"update\"", ")", ".", "setResultsName", "(", "\"action\"", ")", "returns", ",", "none", ",", "all_", ",", "updated", ",", "old", ",", "new", "=", "map", "(", "upkey", ",", "[", "\"...
Create the grammar for the 'update' statement
[ "Create", "the", "grammar", "for", "the", "update", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L250-L268
train
29,986
stevearc/dql
dql/grammar/__init__.py
create_alter
def create_alter(): """ Create the grammar for the 'alter' statement """ alter = upkey("alter").setResultsName("action") prim_or_star = primitive | "*" set_throughput = ( Suppress(upkey("set")) + Optional(Suppress(upkey("index")) + var.setResultsName("index")) + create_throughput(prim_or_star) ) drop_index = ( Suppress(upkey("drop") + upkey("index")) + var + Optional(if_exists) ).setResultsName("drop_index") global_index = _global_index() create_index = ( Suppress(upkey("create")) + global_index.setResultsName("create_index") + Optional(if_not_exists) ) return alter + table_key + table + (set_throughput | drop_index | create_index)
python
def create_alter(): """ Create the grammar for the 'alter' statement """ alter = upkey("alter").setResultsName("action") prim_or_star = primitive | "*" set_throughput = ( Suppress(upkey("set")) + Optional(Suppress(upkey("index")) + var.setResultsName("index")) + create_throughput(prim_or_star) ) drop_index = ( Suppress(upkey("drop") + upkey("index")) + var + Optional(if_exists) ).setResultsName("drop_index") global_index = _global_index() create_index = ( Suppress(upkey("create")) + global_index.setResultsName("create_index") + Optional(if_not_exists) ) return alter + table_key + table + (set_throughput | drop_index | create_index)
[ "def", "create_alter", "(", ")", ":", "alter", "=", "upkey", "(", "\"alter\"", ")", ".", "setResultsName", "(", "\"action\"", ")", "prim_or_star", "=", "primitive", "|", "\"*\"", "set_throughput", "=", "(", "Suppress", "(", "upkey", "(", "\"set\"", ")", ")...
Create the grammar for the 'alter' statement
[ "Create", "the", "grammar", "for", "the", "alter", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L271-L292
train
29,987
stevearc/dql
dql/grammar/__init__.py
create_dump
def create_dump(): """ Create the grammar for the 'dump' statement """ dump = upkey("dump").setResultsName("action") return ( dump + upkey("schema") + Optional(Group(delimitedList(table)).setResultsName("tables")) )
python
def create_dump(): """ Create the grammar for the 'dump' statement """ dump = upkey("dump").setResultsName("action") return ( dump + upkey("schema") + Optional(Group(delimitedList(table)).setResultsName("tables")) )
[ "def", "create_dump", "(", ")", ":", "dump", "=", "upkey", "(", "\"dump\"", ")", ".", "setResultsName", "(", "\"action\"", ")", "return", "(", "dump", "+", "upkey", "(", "\"schema\"", ")", "+", "Optional", "(", "Group", "(", "delimitedList", "(", "table"...
Create the grammar for the 'dump' statement
[ "Create", "the", "grammar", "for", "the", "dump", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L295-L302
train
29,988
stevearc/dql
dql/grammar/__init__.py
create_load
def create_load(): """ Create the grammar for the 'load' statement """ load = upkey("load").setResultsName("action") return ( load + Group(filename).setResultsName("load_file") + upkey("into") + table + Optional(throttle) )
python
def create_load(): """ Create the grammar for the 'load' statement """ load = upkey("load").setResultsName("action") return ( load + Group(filename).setResultsName("load_file") + upkey("into") + table + Optional(throttle) )
[ "def", "create_load", "(", ")", ":", "load", "=", "upkey", "(", "\"load\"", ")", ".", "setResultsName", "(", "\"action\"", ")", "return", "(", "load", "+", "Group", "(", "filename", ")", ".", "setResultsName", "(", "\"load_file\"", ")", "+", "upkey", "("...
Create the grammar for the 'load' statement
[ "Create", "the", "grammar", "for", "the", "load", "statement" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L305-L314
train
29,989
stevearc/dql
dql/grammar/__init__.py
create_parser
def create_parser(): """ Create the language parser """ select = create_select() scan = create_scan() delete = create_delete() update = create_update() insert = create_insert() create = create_create() drop = create_drop() alter = create_alter() dump = create_dump() load = create_load() base = ( select | scan | delete | update | insert | create | drop | alter | dump | load ) explain = upkey("explain").setResultsName("action") + Group( select | scan | delete | update | insert | create | drop | alter ) analyze = upkey("analyze").setResultsName("action") + Group( select | scan | delete | update | insert ) dql = explain | analyze | base dql.ignore("--" + restOfLine) return dql
python
def create_parser(): """ Create the language parser """ select = create_select() scan = create_scan() delete = create_delete() update = create_update() insert = create_insert() create = create_create() drop = create_drop() alter = create_alter() dump = create_dump() load = create_load() base = ( select | scan | delete | update | insert | create | drop | alter | dump | load ) explain = upkey("explain").setResultsName("action") + Group( select | scan | delete | update | insert | create | drop | alter ) analyze = upkey("analyze").setResultsName("action") + Group( select | scan | delete | update | insert ) dql = explain | analyze | base dql.ignore("--" + restOfLine) return dql
[ "def", "create_parser", "(", ")", ":", "select", "=", "create_select", "(", ")", "scan", "=", "create_scan", "(", ")", "delete", "=", "create_delete", "(", ")", "update", "=", "create_update", "(", ")", "insert", "=", "create_insert", "(", ")", "create", ...
Create the language parser
[ "Create", "the", "language", "parser" ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L317-L340
train
29,990
stevearc/dql
dql/__init__.py
main
def main(): """ Start the DQL client. """ parse = argparse.ArgumentParser(description=main.__doc__) parse.add_argument("-c", "--command", help="Run this command and exit") region = os.environ.get("AWS_REGION", "us-west-1") parse.add_argument( "-r", "--region", default=region, help="AWS region to connect to (default %(default)s)", ) parse.add_argument( "-H", "--host", default=None, help="Host to connect to if using a local instance " "(default %(default)s)", ) parse.add_argument( "-p", "--port", default=8000, type=int, help="Port to connect to " "(default %(default)d)", ) parse.add_argument( "--version", action="store_true", help="Print the version and exit" ) args = parse.parse_args() if args.version: print(__version__) return logging.config.dictConfig(LOG_CONFIG) cli = DQLClient() cli.initialize(region=args.region, host=args.host, port=args.port) if args.command: command = args.command.strip() try: cli.run_command(command) if cli.engine.partial: cli.run_command(";") except KeyboardInterrupt: pass else: cli.start()
python
def main(): """ Start the DQL client. """ parse = argparse.ArgumentParser(description=main.__doc__) parse.add_argument("-c", "--command", help="Run this command and exit") region = os.environ.get("AWS_REGION", "us-west-1") parse.add_argument( "-r", "--region", default=region, help="AWS region to connect to (default %(default)s)", ) parse.add_argument( "-H", "--host", default=None, help="Host to connect to if using a local instance " "(default %(default)s)", ) parse.add_argument( "-p", "--port", default=8000, type=int, help="Port to connect to " "(default %(default)d)", ) parse.add_argument( "--version", action="store_true", help="Print the version and exit" ) args = parse.parse_args() if args.version: print(__version__) return logging.config.dictConfig(LOG_CONFIG) cli = DQLClient() cli.initialize(region=args.region, host=args.host, port=args.port) if args.command: command = args.command.strip() try: cli.run_command(command) if cli.engine.partial: cli.run_command(";") except KeyboardInterrupt: pass else: cli.start()
[ "def", "main", "(", ")", ":", "parse", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "main", ".", "__doc__", ")", "parse", ".", "add_argument", "(", "\"-c\"", ",", "\"--command\"", ",", "help", "=", "\"Run this command and exit\"", ")", "r...
Start the DQL client.
[ "Start", "the", "DQL", "client", "." ]
e9d3aa22873076dae5ebd02e35318aa996b1e56a
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/__init__.py#L30-L76
train
29,991
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.build_definitions_example
def build_definitions_example(self): """Parse all definitions in the swagger specification.""" for def_name, def_spec in self.specification.get('definitions', {}).items(): self.build_one_definition_example(def_name)
python
def build_definitions_example(self): """Parse all definitions in the swagger specification.""" for def_name, def_spec in self.specification.get('definitions', {}).items(): self.build_one_definition_example(def_name)
[ "def", "build_definitions_example", "(", "self", ")", ":", "for", "def_name", ",", "def_spec", "in", "self", ".", "specification", ".", "get", "(", "'definitions'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "self", ".", "build_one_definition_example",...
Parse all definitions in the swagger specification.
[ "Parse", "all", "definitions", "in", "the", "swagger", "specification", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L86-L89
train
29,992
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.build_one_definition_example
def build_one_definition_example(self, def_name): """Build the example for the given definition. Args: def_name: Name of the definition. Returns: True if the example has been created, False if an error occured. """ if def_name in self.definitions_example.keys(): # Already processed return True elif def_name not in self.specification['definitions'].keys(): # Def does not exist return False self.definitions_example[def_name] = {} def_spec = self.specification['definitions'][def_name] if def_spec.get('type') == 'array' and 'items' in def_spec: item = self.get_example_from_prop_spec(def_spec['items']) self.definitions_example[def_name] = [item] return True if 'properties' not in def_spec: self.definitions_example[def_name] = self.get_example_from_prop_spec(def_spec) return True # Get properties example value for prop_name, prop_spec in def_spec['properties'].items(): example = self.get_example_from_prop_spec(prop_spec) if example is None: return False self.definitions_example[def_name][prop_name] = example return True
python
def build_one_definition_example(self, def_name): """Build the example for the given definition. Args: def_name: Name of the definition. Returns: True if the example has been created, False if an error occured. """ if def_name in self.definitions_example.keys(): # Already processed return True elif def_name not in self.specification['definitions'].keys(): # Def does not exist return False self.definitions_example[def_name] = {} def_spec = self.specification['definitions'][def_name] if def_spec.get('type') == 'array' and 'items' in def_spec: item = self.get_example_from_prop_spec(def_spec['items']) self.definitions_example[def_name] = [item] return True if 'properties' not in def_spec: self.definitions_example[def_name] = self.get_example_from_prop_spec(def_spec) return True # Get properties example value for prop_name, prop_spec in def_spec['properties'].items(): example = self.get_example_from_prop_spec(prop_spec) if example is None: return False self.definitions_example[def_name][prop_name] = example return True
[ "def", "build_one_definition_example", "(", "self", ",", "def_name", ")", ":", "if", "def_name", "in", "self", ".", "definitions_example", ".", "keys", "(", ")", ":", "# Already processed", "return", "True", "elif", "def_name", "not", "in", "self", ".", "speci...
Build the example for the given definition. Args: def_name: Name of the definition. Returns: True if the example has been created, False if an error occured.
[ "Build", "the", "example", "for", "the", "given", "definition", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L91-L124
train
29,993
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.check_type
def check_type(value, type_def): """Check if the value is in the type given in type_def. Args: value: the var to test. type_def: string representing the type in swagger. Returns: True if the type is correct, False otherwise. """ if type_def == 'integer': try: # We accept string with integer ex: '123' int(value) return True except ValueError: return isinstance(value, six.integer_types) and not isinstance(value, bool) elif type_def == 'number': return isinstance(value, (six.integer_types, float)) and not isinstance(value, bool) elif type_def == 'string': return isinstance(value, (six.text_type, six.string_types, datetime.datetime)) elif type_def == 'boolean': return (isinstance(value, bool) or (isinstance(value, (six.text_type, six.string_types,)) and value.lower() in ['true', 'false']) ) else: return False
python
def check_type(value, type_def): """Check if the value is in the type given in type_def. Args: value: the var to test. type_def: string representing the type in swagger. Returns: True if the type is correct, False otherwise. """ if type_def == 'integer': try: # We accept string with integer ex: '123' int(value) return True except ValueError: return isinstance(value, six.integer_types) and not isinstance(value, bool) elif type_def == 'number': return isinstance(value, (six.integer_types, float)) and not isinstance(value, bool) elif type_def == 'string': return isinstance(value, (six.text_type, six.string_types, datetime.datetime)) elif type_def == 'boolean': return (isinstance(value, bool) or (isinstance(value, (six.text_type, six.string_types,)) and value.lower() in ['true', 'false']) ) else: return False
[ "def", "check_type", "(", "value", ",", "type_def", ")", ":", "if", "type_def", "==", "'integer'", ":", "try", ":", "# We accept string with integer ex: '123'", "int", "(", "value", ")", "return", "True", "except", "ValueError", ":", "return", "isinstance", "(",...
Check if the value is in the type given in type_def. Args: value: the var to test. type_def: string representing the type in swagger. Returns: True if the type is correct, False otherwise.
[ "Check", "if", "the", "value", "is", "in", "the", "type", "given", "in", "type_def", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L127-L154
train
29,994
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser.get_example_from_prop_spec
def get_example_from_prop_spec(self, prop_spec, from_allof=False): """Return an example value from a property specification. Args: prop_spec: the specification of the property. from_allof: whether these properties are part of an allOf section Returns: An example value """ # Read example directly from (X-)Example or Default value easy_keys = ['example', 'x-example', 'default'] for key in easy_keys: if key in prop_spec.keys() and self.use_example: return prop_spec[key] # Enum if 'enum' in prop_spec.keys(): return prop_spec['enum'][0] # From definition if '$ref' in prop_spec.keys(): return self._example_from_definition(prop_spec) # Process AllOf section if 'allOf' in prop_spec.keys(): return self._example_from_allof(prop_spec) # Complex type if 'type' not in prop_spec: return self._example_from_complex_def(prop_spec) # Object - read from properties, without references if prop_spec['type'] == 'object': example, additional_properties = self._get_example_from_properties(prop_spec) if additional_properties or from_allof: return example return [example] # Array if prop_spec['type'] == 'array' or (isinstance(prop_spec['type'], list) and prop_spec['type'][0] == 'array'): return self._example_from_array_spec(prop_spec) # File if prop_spec['type'] == 'file': return (StringIO('my file contents'), 'hello world.txt') # Date time if 'format' in prop_spec.keys() and prop_spec['format'] == 'date-time': return self._get_example_from_basic_type('datetime')[0] # List if isinstance(prop_spec['type'], list): return self._get_example_from_basic_type(prop_spec['type'][0])[0] # Default - basic type logging.info("falling back to basic type, no other match found") return self._get_example_from_basic_type(prop_spec['type'])[0]
python
def get_example_from_prop_spec(self, prop_spec, from_allof=False): """Return an example value from a property specification. Args: prop_spec: the specification of the property. from_allof: whether these properties are part of an allOf section Returns: An example value """ # Read example directly from (X-)Example or Default value easy_keys = ['example', 'x-example', 'default'] for key in easy_keys: if key in prop_spec.keys() and self.use_example: return prop_spec[key] # Enum if 'enum' in prop_spec.keys(): return prop_spec['enum'][0] # From definition if '$ref' in prop_spec.keys(): return self._example_from_definition(prop_spec) # Process AllOf section if 'allOf' in prop_spec.keys(): return self._example_from_allof(prop_spec) # Complex type if 'type' not in prop_spec: return self._example_from_complex_def(prop_spec) # Object - read from properties, without references if prop_spec['type'] == 'object': example, additional_properties = self._get_example_from_properties(prop_spec) if additional_properties or from_allof: return example return [example] # Array if prop_spec['type'] == 'array' or (isinstance(prop_spec['type'], list) and prop_spec['type'][0] == 'array'): return self._example_from_array_spec(prop_spec) # File if prop_spec['type'] == 'file': return (StringIO('my file contents'), 'hello world.txt') # Date time if 'format' in prop_spec.keys() and prop_spec['format'] == 'date-time': return self._get_example_from_basic_type('datetime')[0] # List if isinstance(prop_spec['type'], list): return self._get_example_from_basic_type(prop_spec['type'][0])[0] # Default - basic type logging.info("falling back to basic type, no other match found") return self._get_example_from_basic_type(prop_spec['type'])[0]
[ "def", "get_example_from_prop_spec", "(", "self", ",", "prop_spec", ",", "from_allof", "=", "False", ")", ":", "# Read example directly from (X-)Example or Default value", "easy_keys", "=", "[", "'example'", ",", "'x-example'", ",", "'default'", "]", "for", "key", "in...
Return an example value from a property specification. Args: prop_spec: the specification of the property. from_allof: whether these properties are part of an allOf section Returns: An example value
[ "Return", "an", "example", "value", "from", "a", "property", "specification", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L156-L205
train
29,995
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._get_example_from_properties
def _get_example_from_properties(self, spec): """Get example from the properties of an object defined inline. Args: prop_spec: property specification you want an example of. Returns: An example for the given spec A boolean, whether we had additionalProperties in the spec, or not """ local_spec = deepcopy(spec) # Handle additionalProperties if they exist # we replace additionalProperties with two concrete # properties so that examples can be generated additional_property = False if 'additionalProperties' in local_spec: additional_property = True if 'properties' not in local_spec: local_spec['properties'] = {} local_spec['properties'].update({ 'any_prop1': local_spec['additionalProperties'], 'any_prop2': local_spec['additionalProperties'], }) del(local_spec['additionalProperties']) required = local_spec.get('required', []) required += ['any_prop1', 'any_prop2'] local_spec['required'] = required example = {} properties = local_spec.get('properties') if properties is not None: required = local_spec.get('required', properties.keys()) for inner_name, inner_spec in properties.items(): if inner_name not in required: continue partial = self.get_example_from_prop_spec(inner_spec) # While get_example_from_prop_spec is supposed to return a list, # we don't actually want that when recursing to build from # properties if isinstance(partial, list): partial = partial[0] example[inner_name] = partial return example, additional_property
python
def _get_example_from_properties(self, spec): """Get example from the properties of an object defined inline. Args: prop_spec: property specification you want an example of. Returns: An example for the given spec A boolean, whether we had additionalProperties in the spec, or not """ local_spec = deepcopy(spec) # Handle additionalProperties if they exist # we replace additionalProperties with two concrete # properties so that examples can be generated additional_property = False if 'additionalProperties' in local_spec: additional_property = True if 'properties' not in local_spec: local_spec['properties'] = {} local_spec['properties'].update({ 'any_prop1': local_spec['additionalProperties'], 'any_prop2': local_spec['additionalProperties'], }) del(local_spec['additionalProperties']) required = local_spec.get('required', []) required += ['any_prop1', 'any_prop2'] local_spec['required'] = required example = {} properties = local_spec.get('properties') if properties is not None: required = local_spec.get('required', properties.keys()) for inner_name, inner_spec in properties.items(): if inner_name not in required: continue partial = self.get_example_from_prop_spec(inner_spec) # While get_example_from_prop_spec is supposed to return a list, # we don't actually want that when recursing to build from # properties if isinstance(partial, list): partial = partial[0] example[inner_name] = partial return example, additional_property
[ "def", "_get_example_from_properties", "(", "self", ",", "spec", ")", ":", "local_spec", "=", "deepcopy", "(", "spec", ")", "# Handle additionalProperties if they exist", "# we replace additionalProperties with two concrete", "# properties so that examples can be generated", "addit...
Get example from the properties of an object defined inline. Args: prop_spec: property specification you want an example of. Returns: An example for the given spec A boolean, whether we had additionalProperties in the spec, or not
[ "Get", "example", "from", "the", "properties", "of", "an", "object", "defined", "inline", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L207-L252
train
29,996
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._get_example_from_basic_type
def _get_example_from_basic_type(type): """Get example from the given type. Args: type: the type you want an example of. Returns: An array with two example values of the given type. """ if type == 'integer': return [42, 24] elif type == 'number': return [5.5, 5.5] elif type == 'string': return ['string', 'string2'] elif type == 'datetime': return ['2015-08-28T09:02:57.481Z', '2015-08-28T09:02:57.481Z'] elif type == 'boolean': return [False, True] elif type == 'null': return ['null', 'null']
python
def _get_example_from_basic_type(type): """Get example from the given type. Args: type: the type you want an example of. Returns: An array with two example values of the given type. """ if type == 'integer': return [42, 24] elif type == 'number': return [5.5, 5.5] elif type == 'string': return ['string', 'string2'] elif type == 'datetime': return ['2015-08-28T09:02:57.481Z', '2015-08-28T09:02:57.481Z'] elif type == 'boolean': return [False, True] elif type == 'null': return ['null', 'null']
[ "def", "_get_example_from_basic_type", "(", "type", ")", ":", "if", "type", "==", "'integer'", ":", "return", "[", "42", ",", "24", "]", "elif", "type", "==", "'number'", ":", "return", "[", "5.5", ",", "5.5", "]", "elif", "type", "==", "'string'", ":"...
Get example from the given type. Args: type: the type you want an example of. Returns: An array with two example values of the given type.
[ "Get", "example", "from", "the", "given", "type", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L255-L275
train
29,997
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._definition_from_example
def _definition_from_example(example): """Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the swagger definition json """ assert isinstance(example, dict) def _has_simple_type(value): accepted = (str, int, float, bool) return isinstance(value, accepted) definition = { 'type': 'object', 'properties': {}, } for key, value in example.items(): if not _has_simple_type(value): raise Exception("Not implemented yet") ret_value = None if isinstance(value, str): ret_value = {'type': 'string'} elif isinstance(value, int): ret_value = {'type': 'integer', 'format': 'int64'} elif isinstance(value, float): ret_value = {'type': 'number', 'format': 'double'} elif isinstance(value, bool): ret_value = {'type': 'boolean'} else: raise Exception("Not implemented yet") definition['properties'][key] = ret_value return definition
python
def _definition_from_example(example): """Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the swagger definition json """ assert isinstance(example, dict) def _has_simple_type(value): accepted = (str, int, float, bool) return isinstance(value, accepted) definition = { 'type': 'object', 'properties': {}, } for key, value in example.items(): if not _has_simple_type(value): raise Exception("Not implemented yet") ret_value = None if isinstance(value, str): ret_value = {'type': 'string'} elif isinstance(value, int): ret_value = {'type': 'integer', 'format': 'int64'} elif isinstance(value, float): ret_value = {'type': 'number', 'format': 'double'} elif isinstance(value, bool): ret_value = {'type': 'boolean'} else: raise Exception("Not implemented yet") definition['properties'][key] = ret_value return definition
[ "def", "_definition_from_example", "(", "example", ")", ":", "assert", "isinstance", "(", "example", ",", "dict", ")", "def", "_has_simple_type", "(", "value", ")", ":", "accepted", "=", "(", "str", ",", "int", ",", "float", ",", "bool", ")", "return", "...
Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the swagger definition json
[ "Generates", "a", "swagger", "definition", "json", "from", "a", "given", "example", "Works", "only", "for", "simple", "types", "in", "the", "dict" ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L278-L315
train
29,998
Trax-air/swagger-parser
swagger_parser/swagger_parser.py
SwaggerParser._example_from_allof
def _example_from_allof(self, prop_spec): """Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict """ example_dict = {} for definition in prop_spec['allOf']: update = self.get_example_from_prop_spec(definition, True) example_dict.update(update) return example_dict
python
def _example_from_allof(self, prop_spec): """Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict """ example_dict = {} for definition in prop_spec['allOf']: update = self.get_example_from_prop_spec(definition, True) example_dict.update(update) return example_dict
[ "def", "_example_from_allof", "(", "self", ",", "prop_spec", ")", ":", "example_dict", "=", "{", "}", "for", "definition", "in", "prop_spec", "[", "'allOf'", "]", ":", "update", "=", "self", ".", "get_example_from_prop_spec", "(", "definition", ",", "True", ...
Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict
[ "Get", "the", "examples", "from", "an", "allOf", "section", "." ]
d97f962a417e76320c59c33dcb223e4373e516d5
https://github.com/Trax-air/swagger-parser/blob/d97f962a417e76320c59c33dcb223e4373e516d5/swagger_parser/swagger_parser.py#L317-L330
train
29,999