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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
srittau/python-asserts | asserts/__init__.py | assert_raises_regex | def assert_raises_regex(exception, regex, msg_fmt="{msg}"):
"""Fail unless an exception with a message that matches a regular
expression is raised within the context.
The regular expression can be a regular expression string or object.
>>> with assert_raises_regex(ValueError, r"\\d+"):
... raise ValueError("Error #42")
...
>>> with assert_raises_regex(ValueError, r"\\d+"):
... raise ValueError("Generic Error")
...
Traceback (most recent call last):
...
AssertionError: 'Generic Error' does not match '\\\\d+'
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type that is expected
* exc_name - expected exception type name
* text - actual error text
* pattern - expected error message as regular expression string
"""
def test(exc):
compiled = re.compile(regex)
if not exc.args:
msg = "{} without message".format(exception.__name__)
fail(
msg_fmt.format(
msg=msg,
text=None,
pattern=compiled.pattern,
exc_type=exception,
exc_name=exception.__name__,
)
)
text = exc.args[0]
if not compiled.search(text):
msg = "{!r} does not match {!r}".format(text, compiled.pattern)
fail(
msg_fmt.format(
msg=msg,
text=text,
pattern=compiled.pattern,
exc_type=exception,
exc_name=exception.__name__,
)
)
context = AssertRaisesRegexContext(exception, regex, msg_fmt)
context.add_test(test)
return context | python | def assert_raises_regex(exception, regex, msg_fmt="{msg}"):
"""Fail unless an exception with a message that matches a regular
expression is raised within the context.
The regular expression can be a regular expression string or object.
>>> with assert_raises_regex(ValueError, r"\\d+"):
... raise ValueError("Error #42")
...
>>> with assert_raises_regex(ValueError, r"\\d+"):
... raise ValueError("Generic Error")
...
Traceback (most recent call last):
...
AssertionError: 'Generic Error' does not match '\\\\d+'
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type that is expected
* exc_name - expected exception type name
* text - actual error text
* pattern - expected error message as regular expression string
"""
def test(exc):
compiled = re.compile(regex)
if not exc.args:
msg = "{} without message".format(exception.__name__)
fail(
msg_fmt.format(
msg=msg,
text=None,
pattern=compiled.pattern,
exc_type=exception,
exc_name=exception.__name__,
)
)
text = exc.args[0]
if not compiled.search(text):
msg = "{!r} does not match {!r}".format(text, compiled.pattern)
fail(
msg_fmt.format(
msg=msg,
text=text,
pattern=compiled.pattern,
exc_type=exception,
exc_name=exception.__name__,
)
)
context = AssertRaisesRegexContext(exception, regex, msg_fmt)
context.add_test(test)
return context | [
"def",
"assert_raises_regex",
"(",
"exception",
",",
"regex",
",",
"msg_fmt",
"=",
"\"{msg}\"",
")",
":",
"def",
"test",
"(",
"exc",
")",
":",
"compiled",
"=",
"re",
".",
"compile",
"(",
"regex",
")",
"if",
"not",
"exc",
".",
"args",
":",
"msg",
"=",... | Fail unless an exception with a message that matches a regular
expression is raised within the context.
The regular expression can be a regular expression string or object.
>>> with assert_raises_regex(ValueError, r"\\d+"):
... raise ValueError("Error #42")
...
>>> with assert_raises_regex(ValueError, r"\\d+"):
... raise ValueError("Generic Error")
...
Traceback (most recent call last):
...
AssertionError: 'Generic Error' does not match '\\\\d+'
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type that is expected
* exc_name - expected exception type name
* text - actual error text
* pattern - expected error message as regular expression string | [
"Fail",
"unless",
"an",
"exception",
"with",
"a",
"message",
"that",
"matches",
"a",
"regular",
"expression",
"is",
"raised",
"within",
"the",
"context",
"."
] | 1d5c797031c68ee27552d1c94e7f918c3d3d0453 | https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L983-L1035 | train | 33,900 |
srittau/python-asserts | asserts/__init__.py | assert_raises_errno | def assert_raises_errno(exception, errno, msg_fmt="{msg}"):
"""Fail unless an exception with a specific errno is raised with the
context.
>>> with assert_raises_errno(OSError, 42):
... raise OSError(42, "OS Error")
...
>>> with assert_raises_errno(OSError, 44):
... raise OSError(17, "OS Error")
...
Traceback (most recent call last):
...
AssertionError: wrong errno: 44 != 17
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type that is expected
* exc_name - expected exception type name
* expected_errno -
* actual_errno - raised errno or None if no matching exception was raised
"""
def check_errno(exc):
if errno != exc.errno:
msg = "wrong errno: {!r} != {!r}".format(errno, exc.errno)
fail(
msg_fmt.format(
msg=msg,
exc_type=exception,
exc_name=exception.__name__,
expected_errno=errno,
actual_errno=exc.errno,
)
)
context = AssertRaisesErrnoContext(exception, errno, msg_fmt)
context.add_test(check_errno)
return context | python | def assert_raises_errno(exception, errno, msg_fmt="{msg}"):
"""Fail unless an exception with a specific errno is raised with the
context.
>>> with assert_raises_errno(OSError, 42):
... raise OSError(42, "OS Error")
...
>>> with assert_raises_errno(OSError, 44):
... raise OSError(17, "OS Error")
...
Traceback (most recent call last):
...
AssertionError: wrong errno: 44 != 17
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type that is expected
* exc_name - expected exception type name
* expected_errno -
* actual_errno - raised errno or None if no matching exception was raised
"""
def check_errno(exc):
if errno != exc.errno:
msg = "wrong errno: {!r} != {!r}".format(errno, exc.errno)
fail(
msg_fmt.format(
msg=msg,
exc_type=exception,
exc_name=exception.__name__,
expected_errno=errno,
actual_errno=exc.errno,
)
)
context = AssertRaisesErrnoContext(exception, errno, msg_fmt)
context.add_test(check_errno)
return context | [
"def",
"assert_raises_errno",
"(",
"exception",
",",
"errno",
",",
"msg_fmt",
"=",
"\"{msg}\"",
")",
":",
"def",
"check_errno",
"(",
"exc",
")",
":",
"if",
"errno",
"!=",
"exc",
".",
"errno",
":",
"msg",
"=",
"\"wrong errno: {!r} != {!r}\"",
".",
"format",
... | Fail unless an exception with a specific errno is raised with the
context.
>>> with assert_raises_errno(OSError, 42):
... raise OSError(42, "OS Error")
...
>>> with assert_raises_errno(OSError, 44):
... raise OSError(17, "OS Error")
...
Traceback (most recent call last):
...
AssertionError: wrong errno: 44 != 17
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type that is expected
* exc_name - expected exception type name
* expected_errno -
* actual_errno - raised errno or None if no matching exception was raised | [
"Fail",
"unless",
"an",
"exception",
"with",
"a",
"specific",
"errno",
"is",
"raised",
"with",
"the",
"context",
"."
] | 1d5c797031c68ee27552d1c94e7f918c3d3d0453 | https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L1038-L1075 | train | 33,901 |
srittau/python-asserts | asserts/__init__.py | assert_succeeds | def assert_succeeds(exception, msg_fmt="{msg}"):
"""Fail if a specific exception is raised within the context.
This assertion should be used for cases, where successfully running a
function signals a successful test, and raising the exception of a
certain type signals a test failure. All other raised exceptions are
passed on and will usually still result in a test error. This can be
used to signal the intent of a block.
>>> l = ["foo", "bar"]
>>> with assert_succeeds(ValueError):
... i = l.index("foo")
...
>>> with assert_succeeds(ValueError):
... raise ValueError()
...
Traceback (most recent call last):
...
AssertionError: ValueError was unexpectedly raised
>>> with assert_succeeds(ValueError):
... raise TypeError("Wrong Error")
...
Traceback (most recent call last):
...
TypeError: Wrong Error
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type
* exc_name - exception type name
* exception - exception that was raised
"""
class _AssertSucceeds(object):
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type and issubclass(exc_type, exception):
msg = exception.__name__ + " was unexpectedly raised"
fail(
msg_fmt.format(
msg=msg,
exc_type=exception,
exc_name=exception.__name__,
exception=exc_val,
)
)
return _AssertSucceeds() | python | def assert_succeeds(exception, msg_fmt="{msg}"):
"""Fail if a specific exception is raised within the context.
This assertion should be used for cases, where successfully running a
function signals a successful test, and raising the exception of a
certain type signals a test failure. All other raised exceptions are
passed on and will usually still result in a test error. This can be
used to signal the intent of a block.
>>> l = ["foo", "bar"]
>>> with assert_succeeds(ValueError):
... i = l.index("foo")
...
>>> with assert_succeeds(ValueError):
... raise ValueError()
...
Traceback (most recent call last):
...
AssertionError: ValueError was unexpectedly raised
>>> with assert_succeeds(ValueError):
... raise TypeError("Wrong Error")
...
Traceback (most recent call last):
...
TypeError: Wrong Error
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type
* exc_name - exception type name
* exception - exception that was raised
"""
class _AssertSucceeds(object):
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type and issubclass(exc_type, exception):
msg = exception.__name__ + " was unexpectedly raised"
fail(
msg_fmt.format(
msg=msg,
exc_type=exception,
exc_name=exception.__name__,
exception=exc_val,
)
)
return _AssertSucceeds() | [
"def",
"assert_succeeds",
"(",
"exception",
",",
"msg_fmt",
"=",
"\"{msg}\"",
")",
":",
"class",
"_AssertSucceeds",
"(",
"object",
")",
":",
"def",
"__enter__",
"(",
"self",
")",
":",
"pass",
"def",
"__exit__",
"(",
"self",
",",
"exc_type",
",",
"exc_val",... | Fail if a specific exception is raised within the context.
This assertion should be used for cases, where successfully running a
function signals a successful test, and raising the exception of a
certain type signals a test failure. All other raised exceptions are
passed on and will usually still result in a test error. This can be
used to signal the intent of a block.
>>> l = ["foo", "bar"]
>>> with assert_succeeds(ValueError):
... i = l.index("foo")
...
>>> with assert_succeeds(ValueError):
... raise ValueError()
...
Traceback (most recent call last):
...
AssertionError: ValueError was unexpectedly raised
>>> with assert_succeeds(ValueError):
... raise TypeError("Wrong Error")
...
Traceback (most recent call last):
...
TypeError: Wrong Error
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - exception type
* exc_name - exception type name
* exception - exception that was raised | [
"Fail",
"if",
"a",
"specific",
"exception",
"is",
"raised",
"within",
"the",
"context",
"."
] | 1d5c797031c68ee27552d1c94e7f918c3d3d0453 | https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L1078-L1127 | train | 33,902 |
srittau/python-asserts | asserts/__init__.py | assert_warns_regex | def assert_warns_regex(warning_type, regex, msg_fmt="{msg}"):
"""Fail unless a warning with a message is issued inside the context.
The message can be a regular expression string or object.
>>> from warnings import warn
>>> with assert_warns_regex(UserWarning, r"#\\d+"):
... warn("Error #42", UserWarning)
...
>>> with assert_warns_regex(UserWarning, r"Expected Error"):
... warn("Generic Error", UserWarning)
...
Traceback (most recent call last):
...
AssertionError: no UserWarning matching 'Expected Error' issued
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - warning type
* exc_name - warning type name
* pattern - expected warning message as regular expression string
"""
def test(warning):
return re.search(regex, str(warning.message)) is not None
context = AssertWarnsRegexContext(warning_type, regex, msg_fmt)
context.add_test(test)
return context | python | def assert_warns_regex(warning_type, regex, msg_fmt="{msg}"):
"""Fail unless a warning with a message is issued inside the context.
The message can be a regular expression string or object.
>>> from warnings import warn
>>> with assert_warns_regex(UserWarning, r"#\\d+"):
... warn("Error #42", UserWarning)
...
>>> with assert_warns_regex(UserWarning, r"Expected Error"):
... warn("Generic Error", UserWarning)
...
Traceback (most recent call last):
...
AssertionError: no UserWarning matching 'Expected Error' issued
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - warning type
* exc_name - warning type name
* pattern - expected warning message as regular expression string
"""
def test(warning):
return re.search(regex, str(warning.message)) is not None
context = AssertWarnsRegexContext(warning_type, regex, msg_fmt)
context.add_test(test)
return context | [
"def",
"assert_warns_regex",
"(",
"warning_type",
",",
"regex",
",",
"msg_fmt",
"=",
"\"{msg}\"",
")",
":",
"def",
"test",
"(",
"warning",
")",
":",
"return",
"re",
".",
"search",
"(",
"regex",
",",
"str",
"(",
"warning",
".",
"message",
")",
")",
"is"... | Fail unless a warning with a message is issued inside the context.
The message can be a regular expression string or object.
>>> from warnings import warn
>>> with assert_warns_regex(UserWarning, r"#\\d+"):
... warn("Error #42", UserWarning)
...
>>> with assert_warns_regex(UserWarning, r"Expected Error"):
... warn("Generic Error", UserWarning)
...
Traceback (most recent call last):
...
AssertionError: no UserWarning matching 'Expected Error' issued
The following msg_fmt arguments are supported:
* msg - the default error message
* exc_type - warning type
* exc_name - warning type name
* pattern - expected warning message as regular expression string | [
"Fail",
"unless",
"a",
"warning",
"with",
"a",
"message",
"is",
"issued",
"inside",
"the",
"context",
"."
] | 1d5c797031c68ee27552d1c94e7f918c3d3d0453 | https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L1249-L1277 | train | 33,903 |
srittau/python-asserts | asserts/__init__.py | assert_json_subset | def assert_json_subset(first, second):
"""Assert that a JSON object or array is a subset of another JSON object
or array.
The first JSON object or array must be supplied as a JSON-compatible
dict or list, the JSON object or array to check must be a string, an
UTF-8 bytes object, or a JSON-compatible list or dict.
A JSON non-object, non-array value is the subset of another JSON value,
if they are equal.
A JSON object is the subset of another JSON object if for each name/value
pair in the former there is a name/value pair in the latter with the same
name. Additionally the value of the former pair must be a subset of the
value of the latter pair.
A JSON array is the subset of another JSON array, if they have the same
number of elements and each element in the former is a subset of the
corresponding element in the latter.
>>> assert_json_subset({}, '{}')
>>> assert_json_subset({}, '{"foo": "bar"}')
>>> assert_json_subset({"foo": "bar"}, '{}')
Traceback (most recent call last):
...
AssertionError: element 'foo' missing from element $
>>> assert_json_subset([1, 2], '[1, 2]')
>>> assert_json_subset([2, 1], '[1, 2]')
Traceback (most recent call last):
...
AssertionError: element $[0] differs: 2 != 1
>>> assert_json_subset([{}], '[{"foo": "bar"}]')
>>> assert_json_subset({}, "INVALID JSON")
Traceback (most recent call last):
...
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
"""
if not isinstance(second, (dict, list, str, bytes)):
raise TypeError("second must be dict, list, str, or bytes")
if isinstance(second, bytes):
second = second.decode("utf-8")
if isinstance(second, _Str):
parsed_second = json_loads(second)
else:
parsed_second = second
if not isinstance(parsed_second, (dict, list)):
raise AssertionError(
"second must decode to dict or list, not {}".format(
type(parsed_second)
)
)
comparer = _JSONComparer(_JSONPath("$"), first, parsed_second)
comparer.assert_() | python | def assert_json_subset(first, second):
"""Assert that a JSON object or array is a subset of another JSON object
or array.
The first JSON object or array must be supplied as a JSON-compatible
dict or list, the JSON object or array to check must be a string, an
UTF-8 bytes object, or a JSON-compatible list or dict.
A JSON non-object, non-array value is the subset of another JSON value,
if they are equal.
A JSON object is the subset of another JSON object if for each name/value
pair in the former there is a name/value pair in the latter with the same
name. Additionally the value of the former pair must be a subset of the
value of the latter pair.
A JSON array is the subset of another JSON array, if they have the same
number of elements and each element in the former is a subset of the
corresponding element in the latter.
>>> assert_json_subset({}, '{}')
>>> assert_json_subset({}, '{"foo": "bar"}')
>>> assert_json_subset({"foo": "bar"}, '{}')
Traceback (most recent call last):
...
AssertionError: element 'foo' missing from element $
>>> assert_json_subset([1, 2], '[1, 2]')
>>> assert_json_subset([2, 1], '[1, 2]')
Traceback (most recent call last):
...
AssertionError: element $[0] differs: 2 != 1
>>> assert_json_subset([{}], '[{"foo": "bar"}]')
>>> assert_json_subset({}, "INVALID JSON")
Traceback (most recent call last):
...
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
"""
if not isinstance(second, (dict, list, str, bytes)):
raise TypeError("second must be dict, list, str, or bytes")
if isinstance(second, bytes):
second = second.decode("utf-8")
if isinstance(second, _Str):
parsed_second = json_loads(second)
else:
parsed_second = second
if not isinstance(parsed_second, (dict, list)):
raise AssertionError(
"second must decode to dict or list, not {}".format(
type(parsed_second)
)
)
comparer = _JSONComparer(_JSONPath("$"), first, parsed_second)
comparer.assert_() | [
"def",
"assert_json_subset",
"(",
"first",
",",
"second",
")",
":",
"if",
"not",
"isinstance",
"(",
"second",
",",
"(",
"dict",
",",
"list",
",",
"str",
",",
"bytes",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"second must be dict, list, str, or bytes\"",
"... | Assert that a JSON object or array is a subset of another JSON object
or array.
The first JSON object or array must be supplied as a JSON-compatible
dict or list, the JSON object or array to check must be a string, an
UTF-8 bytes object, or a JSON-compatible list or dict.
A JSON non-object, non-array value is the subset of another JSON value,
if they are equal.
A JSON object is the subset of another JSON object if for each name/value
pair in the former there is a name/value pair in the latter with the same
name. Additionally the value of the former pair must be a subset of the
value of the latter pair.
A JSON array is the subset of another JSON array, if they have the same
number of elements and each element in the former is a subset of the
corresponding element in the latter.
>>> assert_json_subset({}, '{}')
>>> assert_json_subset({}, '{"foo": "bar"}')
>>> assert_json_subset({"foo": "bar"}, '{}')
Traceback (most recent call last):
...
AssertionError: element 'foo' missing from element $
>>> assert_json_subset([1, 2], '[1, 2]')
>>> assert_json_subset([2, 1], '[1, 2]')
Traceback (most recent call last):
...
AssertionError: element $[0] differs: 2 != 1
>>> assert_json_subset([{}], '[{"foo": "bar"}]')
>>> assert_json_subset({}, "INVALID JSON")
Traceback (most recent call last):
...
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) | [
"Assert",
"that",
"a",
"JSON",
"object",
"or",
"array",
"is",
"a",
"subset",
"of",
"another",
"JSON",
"object",
"or",
"array",
"."
] | 1d5c797031c68ee27552d1c94e7f918c3d3d0453 | https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L1286-L1341 | train | 33,904 |
scidam/cachepy | backends/base.py | BaseBackend.get_data | def get_data(self, data_key, key=''):
"""Get the data from the cache.
:param data_key: a key for accessing the data;
:param key: if provided (e.g. non-empty string), will be used to
decrypt the data as a password;
:returns: the data extracted from the cache, a python object.
"""
flag = False # set to True if data was successfully extracted.
extracted = self.get(data_key, -1)
if extracted != -1:
try:
data, expired, noc, ncalls = self._from_bytes(extracted, key=key)
flag = True
except ValueError:
return None, flag
if noc:
ncalls += 1
self[data_key] = self._to_bytes(data, expired=expired,
key=key, noc=noc,
ncalls=ncalls)
if ncalls >= noc:
self.remove(data_key)
flag = False
if expired and datetime.datetime.now() > expired:
self.remove(data_key)
flag = False
return (data, flag) if flag else (None, flag) | python | def get_data(self, data_key, key=''):
"""Get the data from the cache.
:param data_key: a key for accessing the data;
:param key: if provided (e.g. non-empty string), will be used to
decrypt the data as a password;
:returns: the data extracted from the cache, a python object.
"""
flag = False # set to True if data was successfully extracted.
extracted = self.get(data_key, -1)
if extracted != -1:
try:
data, expired, noc, ncalls = self._from_bytes(extracted, key=key)
flag = True
except ValueError:
return None, flag
if noc:
ncalls += 1
self[data_key] = self._to_bytes(data, expired=expired,
key=key, noc=noc,
ncalls=ncalls)
if ncalls >= noc:
self.remove(data_key)
flag = False
if expired and datetime.datetime.now() > expired:
self.remove(data_key)
flag = False
return (data, flag) if flag else (None, flag) | [
"def",
"get_data",
"(",
"self",
",",
"data_key",
",",
"key",
"=",
"''",
")",
":",
"flag",
"=",
"False",
"# set to True if data was successfully extracted.",
"extracted",
"=",
"self",
".",
"get",
"(",
"data_key",
",",
"-",
"1",
")",
"if",
"extracted",
"!=",
... | Get the data from the cache.
:param data_key: a key for accessing the data;
:param key: if provided (e.g. non-empty string), will be used to
decrypt the data as a password;
:returns: the data extracted from the cache, a python object. | [
"Get",
"the",
"data",
"from",
"the",
"cache",
"."
] | 680eeb7ff04ec9bb634b71cceb0841abaf2d530e | https://github.com/scidam/cachepy/blob/680eeb7ff04ec9bb634b71cceb0841abaf2d530e/backends/base.py#L99-L131 | train | 33,905 |
scidam/cachepy | utils.py | Helpers.encode_safely | def encode_safely(self, data):
"""Encode the data.
"""
encoder = self.base_encoder
result = settings.null
try:
result = encoder(pickle.dumps(data))
except:
warnings.warn("Data could not be serialized.", RuntimeWarning)
return result | python | def encode_safely(self, data):
"""Encode the data.
"""
encoder = self.base_encoder
result = settings.null
try:
result = encoder(pickle.dumps(data))
except:
warnings.warn("Data could not be serialized.", RuntimeWarning)
return result | [
"def",
"encode_safely",
"(",
"self",
",",
"data",
")",
":",
"encoder",
"=",
"self",
".",
"base_encoder",
"result",
"=",
"settings",
".",
"null",
"try",
":",
"result",
"=",
"encoder",
"(",
"pickle",
".",
"dumps",
"(",
"data",
")",
")",
"except",
":",
... | Encode the data. | [
"Encode",
"the",
"data",
"."
] | 680eeb7ff04ec9bb634b71cceb0841abaf2d530e | https://github.com/scidam/cachepy/blob/680eeb7ff04ec9bb634b71cceb0841abaf2d530e/utils.py#L49-L60 | train | 33,906 |
scidam/cachepy | utils.py | Helpers.decode_safely | def decode_safely(self, encoded_data):
"""Inverse for the `encode_safely` function.
"""
decoder = self.base_decoder
result = settings.null
try:
result = pickle.loads(decoder(encoded_data))
except:
warnings.warn("Could not load and deserialize the data.", RuntimeWarning)
return result | python | def decode_safely(self, encoded_data):
"""Inverse for the `encode_safely` function.
"""
decoder = self.base_decoder
result = settings.null
try:
result = pickle.loads(decoder(encoded_data))
except:
warnings.warn("Could not load and deserialize the data.", RuntimeWarning)
return result | [
"def",
"decode_safely",
"(",
"self",
",",
"encoded_data",
")",
":",
"decoder",
"=",
"self",
".",
"base_decoder",
"result",
"=",
"settings",
".",
"null",
"try",
":",
"result",
"=",
"pickle",
".",
"loads",
"(",
"decoder",
"(",
"encoded_data",
")",
")",
"ex... | Inverse for the `encode_safely` function. | [
"Inverse",
"for",
"the",
"encode_safely",
"function",
"."
] | 680eeb7ff04ec9bb634b71cceb0841abaf2d530e | https://github.com/scidam/cachepy/blob/680eeb7ff04ec9bb634b71cceb0841abaf2d530e/utils.py#L63-L74 | train | 33,907 |
scidam/cachepy | utils.py | Helpers.get_function_hash | def get_function_hash(self, func, args=None, kwargs=None, ttl=None, key=None, noc=None):
"""Compute the hash of the function to be evaluated.
"""
base_hash = settings.HASH_FUNCTION()
if PY3:
base_hash.update(func.__name__.encode(settings.DEFAULT_ENCODING))
else:
base_hash.update(func.__name__)
if args:
for a in args:
if PY3:
base_hash.update(repr(a).encode(settings.DEFAULT_ENCODING))
else:
base_hash.update(repr(a))
if kwargs:
for k in sorted(kwargs):
if PY3:
base_hash.update(("{}={}".format(k, repr(kwargs[k]))).encode(settings.DEFAULT_ENCODING))
else:
base_hash.update(("{}={}".format(k, repr(kwargs[k]))))
if ttl:
base_hash.update(str(ttl).encode(settings.DEFAULT_ENCODING))
if key and can_encrypt:
if PY3:
base_hash.update(key.encode(settings.DEFAULT_ENCODING))
else:
base_hash.update(key)
if noc:
base_hash.update(str(noc).encode(settings.DEFAULT_ENCODING))
base_hash_hex = base_hash.hexdigest()
return base_hash_hex | python | def get_function_hash(self, func, args=None, kwargs=None, ttl=None, key=None, noc=None):
"""Compute the hash of the function to be evaluated.
"""
base_hash = settings.HASH_FUNCTION()
if PY3:
base_hash.update(func.__name__.encode(settings.DEFAULT_ENCODING))
else:
base_hash.update(func.__name__)
if args:
for a in args:
if PY3:
base_hash.update(repr(a).encode(settings.DEFAULT_ENCODING))
else:
base_hash.update(repr(a))
if kwargs:
for k in sorted(kwargs):
if PY3:
base_hash.update(("{}={}".format(k, repr(kwargs[k]))).encode(settings.DEFAULT_ENCODING))
else:
base_hash.update(("{}={}".format(k, repr(kwargs[k]))))
if ttl:
base_hash.update(str(ttl).encode(settings.DEFAULT_ENCODING))
if key and can_encrypt:
if PY3:
base_hash.update(key.encode(settings.DEFAULT_ENCODING))
else:
base_hash.update(key)
if noc:
base_hash.update(str(noc).encode(settings.DEFAULT_ENCODING))
base_hash_hex = base_hash.hexdigest()
return base_hash_hex | [
"def",
"get_function_hash",
"(",
"self",
",",
"func",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"key",
"=",
"None",
",",
"noc",
"=",
"None",
")",
":",
"base_hash",
"=",
"settings",
".",
"HASH_FUNCTION",
"(",
... | Compute the hash of the function to be evaluated. | [
"Compute",
"the",
"hash",
"of",
"the",
"function",
"to",
"be",
"evaluated",
"."
] | 680eeb7ff04ec9bb634b71cceb0841abaf2d530e | https://github.com/scidam/cachepy/blob/680eeb7ff04ec9bb634b71cceb0841abaf2d530e/utils.py#L76-L115 | train | 33,908 |
scidam/cachepy | crypter.py | to_bytes | def to_bytes(obj):
"""Ensures that the obj is of byte-type.
"""
if PY3:
if isinstance(obj, str):
return obj.encode(settings.DEFAULT_ENCODING)
else:
return obj if isinstance(obj, bytes) else b''
else:
if isinstance(obj, str):
return obj
else:
return obj.encode(settings.DEFAULT_ENCODING) if isinstance(obj, unicode) else '' | python | def to_bytes(obj):
"""Ensures that the obj is of byte-type.
"""
if PY3:
if isinstance(obj, str):
return obj.encode(settings.DEFAULT_ENCODING)
else:
return obj if isinstance(obj, bytes) else b''
else:
if isinstance(obj, str):
return obj
else:
return obj.encode(settings.DEFAULT_ENCODING) if isinstance(obj, unicode) else '' | [
"def",
"to_bytes",
"(",
"obj",
")",
":",
"if",
"PY3",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"obj",
".",
"encode",
"(",
"settings",
".",
"DEFAULT_ENCODING",
")",
"else",
":",
"return",
"obj",
"if",
"isinstance",
"(",
"ob... | Ensures that the obj is of byte-type. | [
"Ensures",
"that",
"the",
"obj",
"is",
"of",
"byte",
"-",
"type",
"."
] | 680eeb7ff04ec9bb634b71cceb0841abaf2d530e | https://github.com/scidam/cachepy/blob/680eeb7ff04ec9bb634b71cceb0841abaf2d530e/crypter.py#L14-L27 | train | 33,909 |
scidam/cachepy | crypter.py | padding | def padding(s, bs=AES.block_size):
"""Fills a bytes-like object with arbitrary symbols to make its length divisible by `bs`.
"""
s = to_bytes(s)
if len(s) % bs == 0:
res = s + b''.join(map(to_bytes, [random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(bs - 1)])) + to_bytes(chr(96 - bs))
elif len(s) % bs > 0 and len(s) > bs:
res = s + b''.join(map(to_bytes, [random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(bs - len(s) % bs - 1)])) + to_bytes(chr(96 + len(s) % bs - bs))
else:
res = s + b''.join(map(to_bytes, [random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(bs - len(s) - 1)])) + to_bytes(chr(96 + len(s) - bs))
return res | python | def padding(s, bs=AES.block_size):
"""Fills a bytes-like object with arbitrary symbols to make its length divisible by `bs`.
"""
s = to_bytes(s)
if len(s) % bs == 0:
res = s + b''.join(map(to_bytes, [random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(bs - 1)])) + to_bytes(chr(96 - bs))
elif len(s) % bs > 0 and len(s) > bs:
res = s + b''.join(map(to_bytes, [random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(bs - len(s) % bs - 1)])) + to_bytes(chr(96 + len(s) % bs - bs))
else:
res = s + b''.join(map(to_bytes, [random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(bs - len(s) - 1)])) + to_bytes(chr(96 + len(s) - bs))
return res | [
"def",
"padding",
"(",
"s",
",",
"bs",
"=",
"AES",
".",
"block_size",
")",
":",
"s",
"=",
"to_bytes",
"(",
"s",
")",
"if",
"len",
"(",
"s",
")",
"%",
"bs",
"==",
"0",
":",
"res",
"=",
"s",
"+",
"b''",
".",
"join",
"(",
"map",
"(",
"to_bytes... | Fills a bytes-like object with arbitrary symbols to make its length divisible by `bs`. | [
"Fills",
"a",
"bytes",
"-",
"like",
"object",
"with",
"arbitrary",
"symbols",
"to",
"make",
"its",
"length",
"divisible",
"by",
"bs",
"."
] | 680eeb7ff04ec9bb634b71cceb0841abaf2d530e | https://github.com/scidam/cachepy/blob/680eeb7ff04ec9bb634b71cceb0841abaf2d530e/crypter.py#L30-L42 | train | 33,910 |
DavidLP/pilight | pilight/pilight.py | Client.stop | def stop(self):
"""Called to stop the reveiver thread."""
self._stop_thread.set()
# f you want to close the connection in a timely fashion,
# call shutdown() before close().
with self._lock: # Receive thread might use the socket
self.receive_socket.shutdown(socket.SHUT_RDWR)
self.receive_socket.close()
self.send_socket.shutdown(socket.SHUT_RDWR)
self.send_socket.close() | python | def stop(self):
"""Called to stop the reveiver thread."""
self._stop_thread.set()
# f you want to close the connection in a timely fashion,
# call shutdown() before close().
with self._lock: # Receive thread might use the socket
self.receive_socket.shutdown(socket.SHUT_RDWR)
self.receive_socket.close()
self.send_socket.shutdown(socket.SHUT_RDWR)
self.send_socket.close() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_stop_thread",
".",
"set",
"(",
")",
"# f you want to close the connection in a timely fashion,",
"# call shutdown() before close().",
"with",
"self",
".",
"_lock",
":",
"# Receive thread might use the socket",
"self",
"... | Called to stop the reveiver thread. | [
"Called",
"to",
"stop",
"the",
"reveiver",
"thread",
"."
] | a319404034e761892a89c7205b6f1aff6ad8e205 | https://github.com/DavidLP/pilight/blob/a319404034e761892a89c7205b6f1aff6ad8e205/pilight/pilight.py#L111-L121 | train | 33,911 |
DavidLP/pilight | pilight/pilight.py | Client.send_code | def send_code(self, data, acknowledge=True):
"""Send a RF code known to the pilight-daemon.
For protocols look at https://manual.pilight.org/en/api.
When acknowledge is set, it is checked if the code was issued.
:param data: Dictionary with the data
:param acknowledge: Raise IO exception if the code is not
send by the pilight-deamon
"""
if "protocol" not in data:
raise ValueError(
'Pilight data to send does not contain a protocol info. '
'Check the pilight-send doku!', str(data))
# Create message to send
message = {
"action": "send", # Tell pilight daemon to send the data
"code": data,
}
# If connection is closed IOError is raised
self.send_socket.sendall(json.dumps(message).encode())
if acknowledge: # Check if command is acknowledged by pilight daemon
messages = self.send_socket.recv(1024).splitlines()
received = False
for message in messages: # Loop over received messages
if message: # Can be empty due to splitlines
acknowledge_message = json.loads(message.decode())
# Filter correct message
if ('status' in acknowledge_message and
acknowledge_message['status'] == 'success'):
received = True
if not received:
raise IOError('Send code failed. Code: %s', str(data)) | python | def send_code(self, data, acknowledge=True):
"""Send a RF code known to the pilight-daemon.
For protocols look at https://manual.pilight.org/en/api.
When acknowledge is set, it is checked if the code was issued.
:param data: Dictionary with the data
:param acknowledge: Raise IO exception if the code is not
send by the pilight-deamon
"""
if "protocol" not in data:
raise ValueError(
'Pilight data to send does not contain a protocol info. '
'Check the pilight-send doku!', str(data))
# Create message to send
message = {
"action": "send", # Tell pilight daemon to send the data
"code": data,
}
# If connection is closed IOError is raised
self.send_socket.sendall(json.dumps(message).encode())
if acknowledge: # Check if command is acknowledged by pilight daemon
messages = self.send_socket.recv(1024).splitlines()
received = False
for message in messages: # Loop over received messages
if message: # Can be empty due to splitlines
acknowledge_message = json.loads(message.decode())
# Filter correct message
if ('status' in acknowledge_message and
acknowledge_message['status'] == 'success'):
received = True
if not received:
raise IOError('Send code failed. Code: %s', str(data)) | [
"def",
"send_code",
"(",
"self",
",",
"data",
",",
"acknowledge",
"=",
"True",
")",
":",
"if",
"\"protocol\"",
"not",
"in",
"data",
":",
"raise",
"ValueError",
"(",
"'Pilight data to send does not contain a protocol info. '",
"'Check the pilight-send doku!'",
",",
"st... | Send a RF code known to the pilight-daemon.
For protocols look at https://manual.pilight.org/en/api.
When acknowledge is set, it is checked if the code was issued.
:param data: Dictionary with the data
:param acknowledge: Raise IO exception if the code is not
send by the pilight-deamon | [
"Send",
"a",
"RF",
"code",
"known",
"to",
"the",
"pilight",
"-",
"daemon",
"."
] | a319404034e761892a89c7205b6f1aff6ad8e205 | https://github.com/DavidLP/pilight/blob/a319404034e761892a89c7205b6f1aff6ad8e205/pilight/pilight.py#L156-L190 | train | 33,912 |
higlass/higlass-python | higlass/server.py | FuseProcess.setup | def setup(self):
"""
Set up filesystem in user space for http and https
so that we can retrieve tiles from remote sources.
Parameters
----------
tmp_dir: string
The temporary directory where to create the
http and https directories
"""
from simple_httpfs import HttpFs
if not op.exists(self.http_directory):
os.makedirs(self.http_directory)
if not op.exists(self.https_directory):
os.makedirs(self.https_directory)
if not op.exists(self.diskcache_directory):
os.makedirs(self.diskcache_directory)
self.teardown()
disk_cache_size = 2 ** 25
disk_cache_dir = self.diskcache_directory
lru_capacity = 400
print(
"self.diskcache_directory",
self.diskcache_directory,
op.exists(self.diskcache_directory),
)
def start_fuse(directory, protocol):
print("starting fuse")
fuse = FUSE(
HttpFs(
protocol,
disk_cache_size=disk_cache_size,
disk_cache_dir=self.diskcache_directory,
lru_capacity=lru_capacity,
),
directory,
foreground=False,
allow_other=True
)
proc1 = mp.Process(target=start_fuse, args=[self.http_directory, 'http'])
proc1.start()
proc1.join()
proc2 = mp.Process(target=start_fuse, args=[self.https_directory, 'https'])
proc2.start()
proc2.join() | python | def setup(self):
"""
Set up filesystem in user space for http and https
so that we can retrieve tiles from remote sources.
Parameters
----------
tmp_dir: string
The temporary directory where to create the
http and https directories
"""
from simple_httpfs import HttpFs
if not op.exists(self.http_directory):
os.makedirs(self.http_directory)
if not op.exists(self.https_directory):
os.makedirs(self.https_directory)
if not op.exists(self.diskcache_directory):
os.makedirs(self.diskcache_directory)
self.teardown()
disk_cache_size = 2 ** 25
disk_cache_dir = self.diskcache_directory
lru_capacity = 400
print(
"self.diskcache_directory",
self.diskcache_directory,
op.exists(self.diskcache_directory),
)
def start_fuse(directory, protocol):
print("starting fuse")
fuse = FUSE(
HttpFs(
protocol,
disk_cache_size=disk_cache_size,
disk_cache_dir=self.diskcache_directory,
lru_capacity=lru_capacity,
),
directory,
foreground=False,
allow_other=True
)
proc1 = mp.Process(target=start_fuse, args=[self.http_directory, 'http'])
proc1.start()
proc1.join()
proc2 = mp.Process(target=start_fuse, args=[self.https_directory, 'https'])
proc2.start()
proc2.join() | [
"def",
"setup",
"(",
"self",
")",
":",
"from",
"simple_httpfs",
"import",
"HttpFs",
"if",
"not",
"op",
".",
"exists",
"(",
"self",
".",
"http_directory",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"http_directory",
")",
"if",
"not",
"op",
".",
... | Set up filesystem in user space for http and https
so that we can retrieve tiles from remote sources.
Parameters
----------
tmp_dir: string
The temporary directory where to create the
http and https directories | [
"Set",
"up",
"filesystem",
"in",
"user",
"space",
"for",
"http",
"and",
"https",
"so",
"that",
"we",
"can",
"retrieve",
"tiles",
"from",
"remote",
"sources",
"."
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/server.py#L234-L284 | train | 33,913 |
higlass/higlass-python | higlass/server.py | Server.start | def start(self, log_file="/tmp/hgserver.log", log_level=logging.INFO):
"""
Start a lightweight higlass server.
Parameters
----------
log_file: string
Where to place diagnostic log files
log_level: logging.*
What level to log at
"""
for puid in list(self.processes.keys()):
print("terminating:", puid)
self.processes[puid].terminate()
del self.processes[puid]
self.app = create_app(
self.tilesets,
__name__,
log_file=log_file,
log_level=log_level,
file_ids=self.file_ids,
)
# we're going to assign a uuid to each server process so that if anything
# goes wrong, the variable referencing the process doesn't get lost
uuid = slugid.nice()
if self.port is None:
self.port = get_open_port()
target = partial(
self.app.run,
threaded=True,
debug=True,
host="0.0.0.0",
port=self.port,
use_reloader=False,
)
self.processes[uuid] = mp.Process(target=target)
self.processes[uuid].start()
self.connected = False
while not self.connected:
try:
url = "http://{}:{}/api/v1".format(self.host, self.port)
r = requests.head(url)
if r.ok:
self.connected = True
except requests.ConnectionError as err:
time.sleep(0.2) | python | def start(self, log_file="/tmp/hgserver.log", log_level=logging.INFO):
"""
Start a lightweight higlass server.
Parameters
----------
log_file: string
Where to place diagnostic log files
log_level: logging.*
What level to log at
"""
for puid in list(self.processes.keys()):
print("terminating:", puid)
self.processes[puid].terminate()
del self.processes[puid]
self.app = create_app(
self.tilesets,
__name__,
log_file=log_file,
log_level=log_level,
file_ids=self.file_ids,
)
# we're going to assign a uuid to each server process so that if anything
# goes wrong, the variable referencing the process doesn't get lost
uuid = slugid.nice()
if self.port is None:
self.port = get_open_port()
target = partial(
self.app.run,
threaded=True,
debug=True,
host="0.0.0.0",
port=self.port,
use_reloader=False,
)
self.processes[uuid] = mp.Process(target=target)
self.processes[uuid].start()
self.connected = False
while not self.connected:
try:
url = "http://{}:{}/api/v1".format(self.host, self.port)
r = requests.head(url)
if r.ok:
self.connected = True
except requests.ConnectionError as err:
time.sleep(0.2) | [
"def",
"start",
"(",
"self",
",",
"log_file",
"=",
"\"/tmp/hgserver.log\"",
",",
"log_level",
"=",
"logging",
".",
"INFO",
")",
":",
"for",
"puid",
"in",
"list",
"(",
"self",
".",
"processes",
".",
"keys",
"(",
")",
")",
":",
"print",
"(",
"\"terminati... | Start a lightweight higlass server.
Parameters
----------
log_file: string
Where to place diagnostic log files
log_level: logging.*
What level to log at | [
"Start",
"a",
"lightweight",
"higlass",
"server",
"."
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/server.py#L339-L386 | train | 33,914 |
higlass/higlass-python | higlass/server.py | Server.stop | def stop(self):
"""
Stop this server so that the calling process can exit
"""
# unsetup_fuse()
self.fuse_process.teardown()
for uuid in self.processes:
self.processes[uuid].terminate() | python | def stop(self):
"""
Stop this server so that the calling process can exit
"""
# unsetup_fuse()
self.fuse_process.teardown()
for uuid in self.processes:
self.processes[uuid].terminate() | [
"def",
"stop",
"(",
"self",
")",
":",
"# unsetup_fuse()",
"self",
".",
"fuse_process",
".",
"teardown",
"(",
")",
"for",
"uuid",
"in",
"self",
".",
"processes",
":",
"self",
".",
"processes",
"[",
"uuid",
"]",
".",
"terminate",
"(",
")"
] | Stop this server so that the calling process can exit | [
"Stop",
"this",
"server",
"so",
"that",
"the",
"calling",
"process",
"can",
"exit"
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/server.py#L388-L395 | train | 33,915 |
higlass/higlass-python | higlass/server.py | Server.tileset_info | def tileset_info(self, uid):
"""
Return the tileset info for the given tileset
"""
url = "http://{host}:{port}/api/v1/tileset_info/?d={uid}".format(
host=self.host, port=self.port, uid=uid
)
req = requests.get(url)
if req.status_code != 200:
raise ServerError("Error fetching tileset_info:", req.content)
content = json.loads(req.content)
return content[uid] | python | def tileset_info(self, uid):
"""
Return the tileset info for the given tileset
"""
url = "http://{host}:{port}/api/v1/tileset_info/?d={uid}".format(
host=self.host, port=self.port, uid=uid
)
req = requests.get(url)
if req.status_code != 200:
raise ServerError("Error fetching tileset_info:", req.content)
content = json.loads(req.content)
return content[uid] | [
"def",
"tileset_info",
"(",
"self",
",",
"uid",
")",
":",
"url",
"=",
"\"http://{host}:{port}/api/v1/tileset_info/?d={uid}\"",
".",
"format",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"uid",
"=",
"uid",
")",
"req",
... | Return the tileset info for the given tileset | [
"Return",
"the",
"tileset",
"info",
"for",
"the",
"given",
"tileset"
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/server.py#L397-L410 | train | 33,916 |
higlass/higlass-python | higlass/server.py | Server.chromsizes | def chromsizes(self, uid):
"""
Return the chromosome sizes from the given filename
"""
url = "http://{host}:{port}/api/v1/chrom-sizes/?id={uid}".format(
host=self.host, port=self.port, uid=uid
)
req = requests.get(url)
if req.status_code != 200:
raise ServerError("Error fetching chromsizes:", req.content)
return req.content | python | def chromsizes(self, uid):
"""
Return the chromosome sizes from the given filename
"""
url = "http://{host}:{port}/api/v1/chrom-sizes/?id={uid}".format(
host=self.host, port=self.port, uid=uid
)
req = requests.get(url)
if req.status_code != 200:
raise ServerError("Error fetching chromsizes:", req.content)
return req.content | [
"def",
"chromsizes",
"(",
"self",
",",
"uid",
")",
":",
"url",
"=",
"\"http://{host}:{port}/api/v1/chrom-sizes/?id={uid}\"",
".",
"format",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"uid",
"=",
"uid",
")",
"req",
... | Return the chromosome sizes from the given filename | [
"Return",
"the",
"chromosome",
"sizes",
"from",
"the",
"given",
"filename"
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/server.py#L433-L445 | train | 33,917 |
higlass/higlass-python | higlass/viewer.py | display | def display(views, location_sync=[], zoom_sync=[], host='localhost', server_port=None):
'''
Instantiate a HiGlass display with the given views
'''
from .server import Server
from .client import ViewConf
tilesets = []
for view in views:
for track in view.tracks:
if track.tracks:
for track1 in track.tracks:
if track1.tileset:
tilesets += [track1.tileset]
if track.tileset:
tilesets += [track.tileset]
print("tilesets:", tilesets)
server = Server(tilesets, host=host, port=server_port)
server.start()
for view in views:
for track in view.tracks:
if track.tracks:
for track1 in track.tracks:
if ('server' not in track1.viewconf or
track1.viewconf['server'] is None):
track1.viewconf['server'] = server.api_address
else:
if ('server' not in track.viewconf or
track.viewconf['server'] is None):
track.viewconf['server'] = server.api_address
conf = ViewConf(views, location_syncs=location_syncs,
zoom_syncs=zoom_syncs)
return (HiGlassDisplay(viewconf=conf.to_dict()), server, conf) | python | def display(views, location_sync=[], zoom_sync=[], host='localhost', server_port=None):
'''
Instantiate a HiGlass display with the given views
'''
from .server import Server
from .client import ViewConf
tilesets = []
for view in views:
for track in view.tracks:
if track.tracks:
for track1 in track.tracks:
if track1.tileset:
tilesets += [track1.tileset]
if track.tileset:
tilesets += [track.tileset]
print("tilesets:", tilesets)
server = Server(tilesets, host=host, port=server_port)
server.start()
for view in views:
for track in view.tracks:
if track.tracks:
for track1 in track.tracks:
if ('server' not in track1.viewconf or
track1.viewconf['server'] is None):
track1.viewconf['server'] = server.api_address
else:
if ('server' not in track.viewconf or
track.viewconf['server'] is None):
track.viewconf['server'] = server.api_address
conf = ViewConf(views, location_syncs=location_syncs,
zoom_syncs=zoom_syncs)
return (HiGlassDisplay(viewconf=conf.to_dict()), server, conf) | [
"def",
"display",
"(",
"views",
",",
"location_sync",
"=",
"[",
"]",
",",
"zoom_sync",
"=",
"[",
"]",
",",
"host",
"=",
"'localhost'",
",",
"server_port",
"=",
"None",
")",
":",
"from",
".",
"server",
"import",
"Server",
"from",
".",
"client",
"import"... | Instantiate a HiGlass display with the given views | [
"Instantiate",
"a",
"HiGlass",
"display",
"with",
"the",
"given",
"views"
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/viewer.py#L4-L42 | train | 33,918 |
higlass/higlass-python | higlass/viewer.py | view | def view(tilesets):
'''
Create a higlass viewer that displays the specified tilesets
Parameters:
-----------
Returns
-------
Nothing
'''
from .server import Server
from .client import View
curr_view = View()
server = Server()
server.start(tilesets)
for ts in tilesets:
if (ts.track_type is not None
and ts.track_position is not None):
curr_view.add_track(ts.track_type,
ts.track_position,
api_url=server.api_address,
tileset_uuid=ts.uuid,
)
curr_view.server = server
return curr_view | python | def view(tilesets):
'''
Create a higlass viewer that displays the specified tilesets
Parameters:
-----------
Returns
-------
Nothing
'''
from .server import Server
from .client import View
curr_view = View()
server = Server()
server.start(tilesets)
for ts in tilesets:
if (ts.track_type is not None
and ts.track_position is not None):
curr_view.add_track(ts.track_type,
ts.track_position,
api_url=server.api_address,
tileset_uuid=ts.uuid,
)
curr_view.server = server
return curr_view | [
"def",
"view",
"(",
"tilesets",
")",
":",
"from",
".",
"server",
"import",
"Server",
"from",
".",
"client",
"import",
"View",
"curr_view",
"=",
"View",
"(",
")",
"server",
"=",
"Server",
"(",
")",
"server",
".",
"start",
"(",
"tilesets",
")",
"for",
... | Create a higlass viewer that displays the specified tilesets
Parameters:
-----------
Returns
-------
Nothing | [
"Create",
"a",
"higlass",
"viewer",
"that",
"displays",
"the",
"specified",
"tilesets"
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/viewer.py#L45-L73 | train | 33,919 |
higlass/higlass-python | higlass/client.py | Track.change_attributes | def change_attributes(self, **kwargs):
'''
Change an attribute of this track and return a new copy.
'''
new_track = Track(self.viewconf['type'])
new_track.position = self.position
new_track.tileset = self.tileset
new_track.viewconf = json.loads(json.dumps(self.viewconf))
new_track.viewconf = {**new_track.viewconf, **kwargs}
return new_track | python | def change_attributes(self, **kwargs):
'''
Change an attribute of this track and return a new copy.
'''
new_track = Track(self.viewconf['type'])
new_track.position = self.position
new_track.tileset = self.tileset
new_track.viewconf = json.loads(json.dumps(self.viewconf))
new_track.viewconf = {**new_track.viewconf, **kwargs}
return new_track | [
"def",
"change_attributes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"new_track",
"=",
"Track",
"(",
"self",
".",
"viewconf",
"[",
"'type'",
"]",
")",
"new_track",
".",
"position",
"=",
"self",
".",
"position",
"new_track",
".",
"tileset",
"=",
... | Change an attribute of this track and return a new copy. | [
"Change",
"an",
"attribute",
"of",
"this",
"track",
"and",
"return",
"a",
"new",
"copy",
"."
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/client.py#L126-L136 | train | 33,920 |
higlass/higlass-python | higlass/client.py | Track.change_options | def change_options(self, **kwargs):
'''
Change one of the track's options in the viewconf
'''
new_options = json.loads(json.dumps(self.viewconf['options']))
new_options = {**new_options, **kwargs}
return self.change_attributes(options=new_options) | python | def change_options(self, **kwargs):
'''
Change one of the track's options in the viewconf
'''
new_options = json.loads(json.dumps(self.viewconf['options']))
new_options = {**new_options, **kwargs}
return self.change_attributes(options=new_options) | [
"def",
"change_options",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"new_options",
"=",
"json",
".",
"loads",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"viewconf",
"[",
"'options'",
"]",
")",
")",
"new_options",
"=",
"{",
"*",
"*",
"new_optio... | Change one of the track's options in the viewconf | [
"Change",
"one",
"of",
"the",
"track",
"s",
"options",
"in",
"the",
"viewconf"
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/client.py#L138-L145 | train | 33,921 |
higlass/higlass-python | higlass/client.py | View.add_track | def add_track(self, *args, **kwargs):
"""
Add a track to a position.
Parameters
----------
track_type: string
The type of track to add (e.g. "heatmap", "line")
position: string
One of 'top', 'bottom', 'center', 'left', 'right'
tileset: hgflask.tilesets.Tileset
The tileset to be plotted in this track
server: string
The server serving this track
height: int
The height of the track, if it is a top, bottom or a center track
width: int
The width of the track, if it is a left, right or a center track
"""
new_track = Track(*args, **kwargs)
self.tracks = self.tracks + [new_track] | python | def add_track(self, *args, **kwargs):
"""
Add a track to a position.
Parameters
----------
track_type: string
The type of track to add (e.g. "heatmap", "line")
position: string
One of 'top', 'bottom', 'center', 'left', 'right'
tileset: hgflask.tilesets.Tileset
The tileset to be plotted in this track
server: string
The server serving this track
height: int
The height of the track, if it is a top, bottom or a center track
width: int
The width of the track, if it is a left, right or a center track
"""
new_track = Track(*args, **kwargs)
self.tracks = self.tracks + [new_track] | [
"def",
"add_track",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"new_track",
"=",
"Track",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"tracks",
"=",
"self",
".",
"tracks",
"+",
"[",
"new_track",
"]"
] | Add a track to a position.
Parameters
----------
track_type: string
The type of track to add (e.g. "heatmap", "line")
position: string
One of 'top', 'bottom', 'center', 'left', 'right'
tileset: hgflask.tilesets.Tileset
The tileset to be plotted in this track
server: string
The server serving this track
height: int
The height of the track, if it is a top, bottom or a center track
width: int
The width of the track, if it is a left, right or a center track | [
"Add",
"a",
"track",
"to",
"a",
"position",
"."
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/client.py#L203-L223 | train | 33,922 |
higlass/higlass-python | higlass/client.py | View.to_dict | def to_dict(self):
"""
Convert the existing track to a JSON representation.
"""
viewconf = json.loads(json.dumps(self.viewconf))
for track in self.tracks:
if track.position is None:
raise ValueError(
"Track has no position: {}".format(track.viewconf["type"])
)
viewconf["tracks"][track.position] += [track.to_dict()]
return viewconf | python | def to_dict(self):
"""
Convert the existing track to a JSON representation.
"""
viewconf = json.loads(json.dumps(self.viewconf))
for track in self.tracks:
if track.position is None:
raise ValueError(
"Track has no position: {}".format(track.viewconf["type"])
)
viewconf["tracks"][track.position] += [track.to_dict()]
return viewconf | [
"def",
"to_dict",
"(",
"self",
")",
":",
"viewconf",
"=",
"json",
".",
"loads",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"viewconf",
")",
")",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"if",
"track",
".",
"position",
"is",
"None",
":",
... | Convert the existing track to a JSON representation. | [
"Convert",
"the",
"existing",
"track",
"to",
"a",
"JSON",
"representation",
"."
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/client.py#L225-L238 | train | 33,923 |
higlass/higlass-python | higlass/client.py | ViewConf.add_view | def add_view(self, *args, **kwargs):
"""
Add a new view
Parameters
----------
uid: string
The uid of new view
width: int
The width of this of view on a 12 unit grid
height: int
The height of the this view. The height is proportional
to the height of all the views present.
x: int
The position of this view on the grid
y: int
The position of this view on the grid
initialXDoamin: [int, int]
The initial x range of the view
initialYDomain: [int, int]
The initial y range of the view
"""
new_view = View(*args, **kwargs)
for view in self.views:
if view.uid == new_view.uid:
raise ValueError("View with this uid already exists")
self.views += [new_view]
return new_view | python | def add_view(self, *args, **kwargs):
"""
Add a new view
Parameters
----------
uid: string
The uid of new view
width: int
The width of this of view on a 12 unit grid
height: int
The height of the this view. The height is proportional
to the height of all the views present.
x: int
The position of this view on the grid
y: int
The position of this view on the grid
initialXDoamin: [int, int]
The initial x range of the view
initialYDomain: [int, int]
The initial y range of the view
"""
new_view = View(*args, **kwargs)
for view in self.views:
if view.uid == new_view.uid:
raise ValueError("View with this uid already exists")
self.views += [new_view]
return new_view | [
"def",
"add_view",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"new_view",
"=",
"View",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"view",
"in",
"self",
".",
"views",
":",
"if",
"view",
".",
"uid",
"==",
"new_v... | Add a new view
Parameters
----------
uid: string
The uid of new view
width: int
The width of this of view on a 12 unit grid
height: int
The height of the this view. The height is proportional
to the height of all the views present.
x: int
The position of this view on the grid
y: int
The position of this view on the grid
initialXDoamin: [int, int]
The initial x range of the view
initialYDomain: [int, int]
The initial y range of the view | [
"Add",
"a",
"new",
"view"
] | 0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7 | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/client.py#L279-L308 | train | 33,924 |
classam/silly | silly/main.py | _slugify | def _slugify(string):
"""
This is not as good as a proper slugification function, but the input space is limited
>>> _slugify("beets")
'beets'
>>> _slugify("Toaster Strudel")
'toaster-strudel'
Here's why: It handles very little. It doesn't handle esoteric whitespace or symbols:
>>> _slugify("Hat\\nBasket- of justice and some @#*(! symbols")
'hat-basket-of-justice-and-some-symbols'
"""
words = re.split(r'[\W]', string)
clean_words = [w for w in words if w != '']
return '-'.join(clean_words).lower() | python | def _slugify(string):
"""
This is not as good as a proper slugification function, but the input space is limited
>>> _slugify("beets")
'beets'
>>> _slugify("Toaster Strudel")
'toaster-strudel'
Here's why: It handles very little. It doesn't handle esoteric whitespace or symbols:
>>> _slugify("Hat\\nBasket- of justice and some @#*(! symbols")
'hat-basket-of-justice-and-some-symbols'
"""
words = re.split(r'[\W]', string)
clean_words = [w for w in words if w != '']
return '-'.join(clean_words).lower() | [
"def",
"_slugify",
"(",
"string",
")",
":",
"words",
"=",
"re",
".",
"split",
"(",
"r'[\\W]'",
",",
"string",
")",
"clean_words",
"=",
"[",
"w",
"for",
"w",
"in",
"words",
"if",
"w",
"!=",
"''",
"]",
"return",
"'-'",
".",
"join",
"(",
"clean_words"... | This is not as good as a proper slugification function, but the input space is limited
>>> _slugify("beets")
'beets'
>>> _slugify("Toaster Strudel")
'toaster-strudel'
Here's why: It handles very little. It doesn't handle esoteric whitespace or symbols:
>>> _slugify("Hat\\nBasket- of justice and some @#*(! symbols")
'hat-basket-of-justice-and-some-symbols' | [
"This",
"is",
"not",
"as",
"good",
"as",
"a",
"proper",
"slugification",
"function",
"but",
"the",
"input",
"space",
"is",
"limited"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L16-L34 | train | 33,925 |
classam/silly | silly/main.py | slugify_argument | def slugify_argument(func):
"""
Wraps a function that returns a string, adding the 'slugify' argument.
>>> slugified_fn = slugify_argument(lambda *args, **kwargs: "YOU ARE A NICE LADY")
>>> slugified_fn()
'YOU ARE A NICE LADY'
>>> slugified_fn(slugify=True)
'you-are-a-nice-lady'
"""
@six.wraps(func)
def wrapped(*args, **kwargs):
if "slugify" in kwargs and kwargs['slugify']:
return _slugify(func(*args, **kwargs))
else:
return func(*args, **kwargs)
return wrapped | python | def slugify_argument(func):
"""
Wraps a function that returns a string, adding the 'slugify' argument.
>>> slugified_fn = slugify_argument(lambda *args, **kwargs: "YOU ARE A NICE LADY")
>>> slugified_fn()
'YOU ARE A NICE LADY'
>>> slugified_fn(slugify=True)
'you-are-a-nice-lady'
"""
@six.wraps(func)
def wrapped(*args, **kwargs):
if "slugify" in kwargs and kwargs['slugify']:
return _slugify(func(*args, **kwargs))
else:
return func(*args, **kwargs)
return wrapped | [
"def",
"slugify_argument",
"(",
"func",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"slugify\"",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'slugify'",
"]",
":",
"... | Wraps a function that returns a string, adding the 'slugify' argument.
>>> slugified_fn = slugify_argument(lambda *args, **kwargs: "YOU ARE A NICE LADY")
>>> slugified_fn()
'YOU ARE A NICE LADY'
>>> slugified_fn(slugify=True)
'you-are-a-nice-lady' | [
"Wraps",
"a",
"function",
"that",
"returns",
"a",
"string",
"adding",
"the",
"slugify",
"argument",
"."
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L651-L668 | train | 33,926 |
classam/silly | silly/main.py | capitalize_argument | def capitalize_argument(func):
"""
Wraps a function that returns a string, adding the 'capitalize' argument.
>>> capsified_fn = capitalize_argument(lambda *args, **kwargs: "what in the beeswax is this?")
>>> capsified_fn()
'what in the beeswax is this?'
>>> capsified_fn(capitalize=True)
'What In The Beeswax Is This?'
"""
@six.wraps(func)
def wrapped(*args, **kwargs):
if "capitalize" in kwargs and kwargs['capitalize']:
return func(*args, **kwargs).title()
else:
return func(*args, **kwargs)
return wrapped | python | def capitalize_argument(func):
"""
Wraps a function that returns a string, adding the 'capitalize' argument.
>>> capsified_fn = capitalize_argument(lambda *args, **kwargs: "what in the beeswax is this?")
>>> capsified_fn()
'what in the beeswax is this?'
>>> capsified_fn(capitalize=True)
'What In The Beeswax Is This?'
"""
@six.wraps(func)
def wrapped(*args, **kwargs):
if "capitalize" in kwargs and kwargs['capitalize']:
return func(*args, **kwargs).title()
else:
return func(*args, **kwargs)
return wrapped | [
"def",
"capitalize_argument",
"(",
"func",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"capitalize\"",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'capitalize'",
"]",
... | Wraps a function that returns a string, adding the 'capitalize' argument.
>>> capsified_fn = capitalize_argument(lambda *args, **kwargs: "what in the beeswax is this?")
>>> capsified_fn()
'what in the beeswax is this?'
>>> capsified_fn(capitalize=True)
'What In The Beeswax Is This?' | [
"Wraps",
"a",
"function",
"that",
"returns",
"a",
"string",
"adding",
"the",
"capitalize",
"argument",
"."
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L671-L688 | train | 33,927 |
classam/silly | silly/main.py | datetime | def datetime(past=True, random=random):
"""
Returns a random datetime from the past... or the future!
>>> mock_random.seed(0)
>>> datetime(random=mock_random).isoformat()
'1950-02-03T03:04:05'
"""
def year():
if past:
return random.choice(range(1950,2005))
else:
return _datetime.datetime.now().year + random.choice(range(1, 50))
def month():
return random.choice(range(1,12))
def day():
return random.choice(range(1,31))
def hour():
return random.choice(range(0,23))
def minute():
return random.choice(range(0,59))
def second():
return random.choice(range(0,59))
try:
return _datetime.datetime(year=year(),
month=month(),
day=day(),
hour=hour(),
minute=minute(),
second=second())
except ValueError:
return datetime(past=past) | python | def datetime(past=True, random=random):
"""
Returns a random datetime from the past... or the future!
>>> mock_random.seed(0)
>>> datetime(random=mock_random).isoformat()
'1950-02-03T03:04:05'
"""
def year():
if past:
return random.choice(range(1950,2005))
else:
return _datetime.datetime.now().year + random.choice(range(1, 50))
def month():
return random.choice(range(1,12))
def day():
return random.choice(range(1,31))
def hour():
return random.choice(range(0,23))
def minute():
return random.choice(range(0,59))
def second():
return random.choice(range(0,59))
try:
return _datetime.datetime(year=year(),
month=month(),
day=day(),
hour=hour(),
minute=minute(),
second=second())
except ValueError:
return datetime(past=past) | [
"def",
"datetime",
"(",
"past",
"=",
"True",
",",
"random",
"=",
"random",
")",
":",
"def",
"year",
"(",
")",
":",
"if",
"past",
":",
"return",
"random",
".",
"choice",
"(",
"range",
"(",
"1950",
",",
"2005",
")",
")",
"else",
":",
"return",
"_da... | Returns a random datetime from the past... or the future!
>>> mock_random.seed(0)
>>> datetime(random=mock_random).isoformat()
'1950-02-03T03:04:05' | [
"Returns",
"a",
"random",
"datetime",
"from",
"the",
"past",
"...",
"or",
"the",
"future!"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L691-L730 | train | 33,928 |
classam/silly | silly/main.py | a_noun | def a_noun(random=random, *args, **kwargs):
"""
Return a noun, but with an 'a' in front of it. Or an 'an', depending!
>>> mock_random.seed(0)
>>> a_noun(random=mock_random)
'an onion'
>>> a_noun(random=mock_random, capitalize=True)
'A Chimp'
>>> a_noun(random=mock_random, slugify=True)
'a-blister'
"""
return inflectify.a(noun(random=random)) | python | def a_noun(random=random, *args, **kwargs):
"""
Return a noun, but with an 'a' in front of it. Or an 'an', depending!
>>> mock_random.seed(0)
>>> a_noun(random=mock_random)
'an onion'
>>> a_noun(random=mock_random, capitalize=True)
'A Chimp'
>>> a_noun(random=mock_random, slugify=True)
'a-blister'
"""
return inflectify.a(noun(random=random)) | [
"def",
"a_noun",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"inflectify",
".",
"a",
"(",
"noun",
"(",
"random",
"=",
"random",
")",
")"
] | Return a noun, but with an 'a' in front of it. Or an 'an', depending!
>>> mock_random.seed(0)
>>> a_noun(random=mock_random)
'an onion'
>>> a_noun(random=mock_random, capitalize=True)
'A Chimp'
>>> a_noun(random=mock_random, slugify=True)
'a-blister' | [
"Return",
"a",
"noun",
"but",
"with",
"an",
"a",
"in",
"front",
"of",
"it",
".",
"Or",
"an",
"an",
"depending!"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L813-L825 | train | 33,929 |
classam/silly | silly/main.py | plural | def plural(random=random, *args, **kwargs):
"""
Return a plural noun.
>>> mock_random.seed(0)
>>> plural(random=mock_random)
'onions'
>>> plural(random=mock_random, capitalize=True)
'Chimps'
>>> plural(random=mock_random, slugify=True)
'blisters'
"""
return inflectify.plural(random.choice(nouns)) | python | def plural(random=random, *args, **kwargs):
"""
Return a plural noun.
>>> mock_random.seed(0)
>>> plural(random=mock_random)
'onions'
>>> plural(random=mock_random, capitalize=True)
'Chimps'
>>> plural(random=mock_random, slugify=True)
'blisters'
"""
return inflectify.plural(random.choice(nouns)) | [
"def",
"plural",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"inflectify",
".",
"plural",
"(",
"random",
".",
"choice",
"(",
"nouns",
")",
")"
] | Return a plural noun.
>>> mock_random.seed(0)
>>> plural(random=mock_random)
'onions'
>>> plural(random=mock_random, capitalize=True)
'Chimps'
>>> plural(random=mock_random, slugify=True)
'blisters' | [
"Return",
"a",
"plural",
"noun",
"."
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L830-L842 | train | 33,930 |
classam/silly | silly/main.py | lastname | def lastname(random=random, *args, **kwargs):
"""
Return a first name!
>>> mock_random.seed(0)
>>> lastname(random=mock_random)
'chimp'
>>> mock_random.seed(1)
>>> lastname(random=mock_random, capitalize=True)
'Wonderful'
>>> mock_random.seed(2)
>>> lastname(random=mock_random, slugify=True)
'poopbritches'
>>> [lastname(random=mock_random) for x in range(0,10)]
['wonderful', 'chimp', 'onionmighty', 'magnificentslap', 'smellmouse', 'secretbale', 'boatbenchtwirl', 'spectacularmice', 'incrediblebritches', 'poopbritches']
"""
types = [
"{noun}",
"{adjective}",
"{noun}{second_noun}",
"{adjective}{noun}",
"{adjective}{plural}",
"{noun}{verb}",
"{noun}{container}",
"{verb}{noun}",
"{adjective}{verb}",
"{noun}{adjective}",
"{noun}{firstname}",
"{noun}{title}",
"{adjective}{title}",
"{adjective}-{noun}",
"{adjective}-{plural}"
]
return random.choice(types).format(noun=noun(random=random),
second_noun=noun(random=random),
adjective=adjective(random=random),
plural=plural(random=random),
container=container(random=random),
verb=verb(random=random),
firstname=firstname(random=random),
title=title(random=random)) | python | def lastname(random=random, *args, **kwargs):
"""
Return a first name!
>>> mock_random.seed(0)
>>> lastname(random=mock_random)
'chimp'
>>> mock_random.seed(1)
>>> lastname(random=mock_random, capitalize=True)
'Wonderful'
>>> mock_random.seed(2)
>>> lastname(random=mock_random, slugify=True)
'poopbritches'
>>> [lastname(random=mock_random) for x in range(0,10)]
['wonderful', 'chimp', 'onionmighty', 'magnificentslap', 'smellmouse', 'secretbale', 'boatbenchtwirl', 'spectacularmice', 'incrediblebritches', 'poopbritches']
"""
types = [
"{noun}",
"{adjective}",
"{noun}{second_noun}",
"{adjective}{noun}",
"{adjective}{plural}",
"{noun}{verb}",
"{noun}{container}",
"{verb}{noun}",
"{adjective}{verb}",
"{noun}{adjective}",
"{noun}{firstname}",
"{noun}{title}",
"{adjective}{title}",
"{adjective}-{noun}",
"{adjective}-{plural}"
]
return random.choice(types).format(noun=noun(random=random),
second_noun=noun(random=random),
adjective=adjective(random=random),
plural=plural(random=random),
container=container(random=random),
verb=verb(random=random),
firstname=firstname(random=random),
title=title(random=random)) | [
"def",
"lastname",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"types",
"=",
"[",
"\"{noun}\"",
",",
"\"{adjective}\"",
",",
"\"{noun}{second_noun}\"",
",",
"\"{adjective}{noun}\"",
",",
"\"{adjective}{plural}\"",
",",
"\... | Return a first name!
>>> mock_random.seed(0)
>>> lastname(random=mock_random)
'chimp'
>>> mock_random.seed(1)
>>> lastname(random=mock_random, capitalize=True)
'Wonderful'
>>> mock_random.seed(2)
>>> lastname(random=mock_random, slugify=True)
'poopbritches'
>>> [lastname(random=mock_random) for x in range(0,10)]
['wonderful', 'chimp', 'onionmighty', 'magnificentslap', 'smellmouse', 'secretbale', 'boatbenchtwirl', 'spectacularmice', 'incrediblebritches', 'poopbritches'] | [
"Return",
"a",
"first",
"name!"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L881-L925 | train | 33,931 |
classam/silly | silly/main.py | numberwang | def numberwang(random=random, *args, **kwargs):
"""
Return a number that is spelled out.
>>> numberwang(random=mock_random)
'two'
>>> numberwang(random=mock_random, capitalize=True)
'Two'
>>> numberwang(random=mock_random, slugify=True)
'two'
"""
n = random.randint(2, 150)
return inflectify.number_to_words(n) | python | def numberwang(random=random, *args, **kwargs):
"""
Return a number that is spelled out.
>>> numberwang(random=mock_random)
'two'
>>> numberwang(random=mock_random, capitalize=True)
'Two'
>>> numberwang(random=mock_random, slugify=True)
'two'
"""
n = random.randint(2, 150)
return inflectify.number_to_words(n) | [
"def",
"numberwang",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"n",
"=",
"random",
".",
"randint",
"(",
"2",
",",
"150",
")",
"return",
"inflectify",
".",
"number_to_words",
"(",
"n",
")"
] | Return a number that is spelled out.
>>> numberwang(random=mock_random)
'two'
>>> numberwang(random=mock_random, capitalize=True)
'Two'
>>> numberwang(random=mock_random, slugify=True)
'two' | [
"Return",
"a",
"number",
"that",
"is",
"spelled",
"out",
"."
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L947-L960 | train | 33,932 |
classam/silly | silly/main.py | things | def things(random=random, *args, **kwargs):
"""
Return a set of things.
>>> mock_random.seed(0)
>>> things(random=mock_random)
'two secrets, two secrets, and two secrets'
>>> mock_random.seed(1)
>>> things(random=mock_random, capitalize=True)
'A Mighty Poop, A Mighty Poop, And A Mighty Poop'
"""
return inflectify.join([a_thing(random=random), a_thing(random=random), a_thing(random=random)]) | python | def things(random=random, *args, **kwargs):
"""
Return a set of things.
>>> mock_random.seed(0)
>>> things(random=mock_random)
'two secrets, two secrets, and two secrets'
>>> mock_random.seed(1)
>>> things(random=mock_random, capitalize=True)
'A Mighty Poop, A Mighty Poop, And A Mighty Poop'
"""
return inflectify.join([a_thing(random=random), a_thing(random=random), a_thing(random=random)]) | [
"def",
"things",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"inflectify",
".",
"join",
"(",
"[",
"a_thing",
"(",
"random",
"=",
"random",
")",
",",
"a_thing",
"(",
"random",
"=",
"random",
")",
",",... | Return a set of things.
>>> mock_random.seed(0)
>>> things(random=mock_random)
'two secrets, two secrets, and two secrets'
>>> mock_random.seed(1)
>>> things(random=mock_random, capitalize=True)
'A Mighty Poop, A Mighty Poop, And A Mighty Poop' | [
"Return",
"a",
"set",
"of",
"things",
"."
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1092-L1104 | train | 33,933 |
classam/silly | silly/main.py | name | def name(random=random, *args, **kwargs):
"""
Return someone's name
>>> mock_random.seed(0)
>>> name(random=mock_random)
'carl poopbritches'
>>> mock_random.seed(7)
>>> name(random=mock_random, capitalize=True)
'Duke Testy Wonderful'
"""
if random.choice([True, True, True, False]):
return firstname(random=random) + " " + lastname(random=random)
elif random.choice([True, False]):
return title(random=random) + " " + firstname(random=random) + " " + lastname(random=random)
else:
return title(random=random) + " " + lastname(random=random) | python | def name(random=random, *args, **kwargs):
"""
Return someone's name
>>> mock_random.seed(0)
>>> name(random=mock_random)
'carl poopbritches'
>>> mock_random.seed(7)
>>> name(random=mock_random, capitalize=True)
'Duke Testy Wonderful'
"""
if random.choice([True, True, True, False]):
return firstname(random=random) + " " + lastname(random=random)
elif random.choice([True, False]):
return title(random=random) + " " + firstname(random=random) + " " + lastname(random=random)
else:
return title(random=random) + " " + lastname(random=random) | [
"def",
"name",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"random",
".",
"choice",
"(",
"[",
"True",
",",
"True",
",",
"True",
",",
"False",
"]",
")",
":",
"return",
"firstname",
"(",
"random",
"=",
... | Return someone's name
>>> mock_random.seed(0)
>>> name(random=mock_random)
'carl poopbritches'
>>> mock_random.seed(7)
>>> name(random=mock_random, capitalize=True)
'Duke Testy Wonderful' | [
"Return",
"someone",
"s",
"name"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1109-L1126 | train | 33,934 |
classam/silly | silly/main.py | domain | def domain(random=random, *args, **kwargs):
"""
Return a domain
>>> mock_random.seed(0)
>>> domain(random=mock_random)
'onion.net'
>>> domain(random=mock_random)
'bag-of-heroic-chimps.sexy'
"""
words = random.choice([
noun(random=random),
thing(random=random),
adjective(random=random)+noun(random=random),
])
return _slugify(words)+tld(random=random) | python | def domain(random=random, *args, **kwargs):
"""
Return a domain
>>> mock_random.seed(0)
>>> domain(random=mock_random)
'onion.net'
>>> domain(random=mock_random)
'bag-of-heroic-chimps.sexy'
"""
words = random.choice([
noun(random=random),
thing(random=random),
adjective(random=random)+noun(random=random),
])
return _slugify(words)+tld(random=random) | [
"def",
"domain",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"words",
"=",
"random",
".",
"choice",
"(",
"[",
"noun",
"(",
"random",
"=",
"random",
")",
",",
"thing",
"(",
"random",
"=",
"random",
")",
",",
... | Return a domain
>>> mock_random.seed(0)
>>> domain(random=mock_random)
'onion.net'
>>> domain(random=mock_random)
'bag-of-heroic-chimps.sexy' | [
"Return",
"a",
"domain"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1131-L1147 | train | 33,935 |
classam/silly | silly/main.py | email | def email(random=random, *args, **kwargs):
"""
Return an e-mail address
>>> mock_random.seed(0)
>>> email(random=mock_random)
'onion@bag-of-heroic-chimps.sexy'
>>> email(random=mock_random)
'agatha-incrediblebritches-spam@amazingbritches.click'
>>> email(random=mock_random, name="charles")
'charles@secret.xyz'
"""
if 'name' in kwargs and kwargs['name']:
words = kwargs['name']
else:
words = random.choice([
noun(random=random),
name(random=random),
name(random=random)+"+spam",
])
return _slugify(words)+"@"+domain(random=random) | python | def email(random=random, *args, **kwargs):
"""
Return an e-mail address
>>> mock_random.seed(0)
>>> email(random=mock_random)
'onion@bag-of-heroic-chimps.sexy'
>>> email(random=mock_random)
'agatha-incrediblebritches-spam@amazingbritches.click'
>>> email(random=mock_random, name="charles")
'charles@secret.xyz'
"""
if 'name' in kwargs and kwargs['name']:
words = kwargs['name']
else:
words = random.choice([
noun(random=random),
name(random=random),
name(random=random)+"+spam",
])
return _slugify(words)+"@"+domain(random=random) | [
"def",
"email",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'name'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'name'",
"]",
":",
"words",
"=",
"kwargs",
"[",
"'name'",
"]",
"else",
":",
"words",
"=",
"r... | Return an e-mail address
>>> mock_random.seed(0)
>>> email(random=mock_random)
'onion@bag-of-heroic-chimps.sexy'
>>> email(random=mock_random)
'agatha-incrediblebritches-spam@amazingbritches.click'
>>> email(random=mock_random, name="charles")
'charles@secret.xyz' | [
"Return",
"an",
"e",
"-",
"mail",
"address"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1150-L1171 | train | 33,936 |
classam/silly | silly/main.py | phone_number | def phone_number(random=random, *args, **kwargs):
"""
Return a phone number
>>> mock_random.seed(0)
>>> phone_number(random=mock_random)
'555-0000'
>>> phone_number(random=mock_random)
'1-604-555-0000'
>>> phone_number(random=mock_random)
'864-70-555-0000'
"""
return random.choice([
'555-{number}{other_number}{number}{other_number}',
'1-604-555-{number}{other_number}{number}{other_number}',
'864-70-555-{number}{other_number}{number}{other_number}',
'867-5309'
]).format(number=number(random=random),
other_number=number(random=random)) | python | def phone_number(random=random, *args, **kwargs):
"""
Return a phone number
>>> mock_random.seed(0)
>>> phone_number(random=mock_random)
'555-0000'
>>> phone_number(random=mock_random)
'1-604-555-0000'
>>> phone_number(random=mock_random)
'864-70-555-0000'
"""
return random.choice([
'555-{number}{other_number}{number}{other_number}',
'1-604-555-{number}{other_number}{number}{other_number}',
'864-70-555-{number}{other_number}{number}{other_number}',
'867-5309'
]).format(number=number(random=random),
other_number=number(random=random)) | [
"def",
"phone_number",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"'555-{number}{other_number}{number}{other_number}'",
",",
"'1-604-555-{number}{other_number}{number}{other_number}'",
... | Return a phone number
>>> mock_random.seed(0)
>>> phone_number(random=mock_random)
'555-0000'
>>> phone_number(random=mock_random)
'1-604-555-0000'
>>> phone_number(random=mock_random)
'864-70-555-0000' | [
"Return",
"a",
"phone",
"number"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1174-L1193 | train | 33,937 |
classam/silly | silly/main.py | sentence | def sentence(random=random, *args, **kwargs):
"""
Return a whole sentence
>>> mock_random.seed(0)
>>> sentence(random=mock_random)
"Agatha Incrediblebritches can't wait to smell two chimps in Boatbencheston."
>>> mock_random.seed(2)
>>> sentence(random=mock_random, slugify=True)
'blistersecret-studios-is-the-best-company-in-liveronion'
"""
if 'name' in kwargs and kwargs['name']:
nm = kwargs(name)
elif random.choice([True, False, False]):
nm = name(capitalize=True, random=random)
else:
nm = random.choice(people)
def type_one():
return "{name} will {verb} {thing}.".format(name=nm,
verb=verb(random=random),
thing=random.choice([a_thing(random=random),
things(random=random)]))
def type_two():
return "{city} is in {country}.".format(city=city(capitalize=True, random=random),
country=country(capitalize=True, random=random))
def type_three():
return "{name} can't wait to {verb} {thing} in {city}.".format(name=nm,
verb=verb(random=random),
thing=a_thing(random=random),
city=city(capitalize=True, random=random))
def type_four():
return "{name} will head to {company} to buy {thing}.".format(name=nm,
company=company(capitalize=True, random=random),
thing=a_thing(random=random))
def type_five():
return "{company} is the best company in {city}.".format(city=city(capitalize=True, random=random),
company=company(capitalize=True, random=random))
def type_six():
return "To get to {country}, you need to go to {city}, then drive {direction}.".format(
country=country(capitalize=True, random=random),
city=city(capitalize=True, random=random),
direction=direction(random=random))
def type_seven():
return "{name} needs {thing}, badly.".format(name=nm, thing=a_thing(random=random))
def type_eight():
return "{verb} {noun}!".format(verb=verb(capitalize=True, random=random), noun=noun(random=random))
return random.choice([type_one,
type_two,
type_three,
type_four,
type_five,
type_six,
type_seven,
type_eight])() | python | def sentence(random=random, *args, **kwargs):
"""
Return a whole sentence
>>> mock_random.seed(0)
>>> sentence(random=mock_random)
"Agatha Incrediblebritches can't wait to smell two chimps in Boatbencheston."
>>> mock_random.seed(2)
>>> sentence(random=mock_random, slugify=True)
'blistersecret-studios-is-the-best-company-in-liveronion'
"""
if 'name' in kwargs and kwargs['name']:
nm = kwargs(name)
elif random.choice([True, False, False]):
nm = name(capitalize=True, random=random)
else:
nm = random.choice(people)
def type_one():
return "{name} will {verb} {thing}.".format(name=nm,
verb=verb(random=random),
thing=random.choice([a_thing(random=random),
things(random=random)]))
def type_two():
return "{city} is in {country}.".format(city=city(capitalize=True, random=random),
country=country(capitalize=True, random=random))
def type_three():
return "{name} can't wait to {verb} {thing} in {city}.".format(name=nm,
verb=verb(random=random),
thing=a_thing(random=random),
city=city(capitalize=True, random=random))
def type_four():
return "{name} will head to {company} to buy {thing}.".format(name=nm,
company=company(capitalize=True, random=random),
thing=a_thing(random=random))
def type_five():
return "{company} is the best company in {city}.".format(city=city(capitalize=True, random=random),
company=company(capitalize=True, random=random))
def type_six():
return "To get to {country}, you need to go to {city}, then drive {direction}.".format(
country=country(capitalize=True, random=random),
city=city(capitalize=True, random=random),
direction=direction(random=random))
def type_seven():
return "{name} needs {thing}, badly.".format(name=nm, thing=a_thing(random=random))
def type_eight():
return "{verb} {noun}!".format(verb=verb(capitalize=True, random=random), noun=noun(random=random))
return random.choice([type_one,
type_two,
type_three,
type_four,
type_five,
type_six,
type_seven,
type_eight])() | [
"def",
"sentence",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'name'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'name'",
"]",
":",
"nm",
"=",
"kwargs",
"(",
"name",
")",
"elif",
"random",
".",
"choice",
... | Return a whole sentence
>>> mock_random.seed(0)
>>> sentence(random=mock_random)
"Agatha Incrediblebritches can't wait to smell two chimps in Boatbencheston."
>>> mock_random.seed(2)
>>> sentence(random=mock_random, slugify=True)
'blistersecret-studios-is-the-best-company-in-liveronion' | [
"Return",
"a",
"whole",
"sentence"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1198-L1263 | train | 33,938 |
classam/silly | silly/main.py | paragraph | def paragraph(random=random, length=10, *args, **kwargs):
"""
Produces a paragraph of text.
>>> mock_random.seed(0)
>>> paragraph(random=mock_random, length=2)
"Agatha Incrediblebritches can't wait to smell two chimps in Boatbencheston. Wonderfulsecretsound is in Gallifrey."
>>> mock_random.seed(2)
>>> paragraph(random=mock_random, length=2, slugify=True)
'blistersecret-studios-is-the-best-company-in-liveronion-wonderfulsecretsound-is-in-gallifrey'
"""
return " ".join([sentence(random=random) for x in range(0, length)]) | python | def paragraph(random=random, length=10, *args, **kwargs):
"""
Produces a paragraph of text.
>>> mock_random.seed(0)
>>> paragraph(random=mock_random, length=2)
"Agatha Incrediblebritches can't wait to smell two chimps in Boatbencheston. Wonderfulsecretsound is in Gallifrey."
>>> mock_random.seed(2)
>>> paragraph(random=mock_random, length=2, slugify=True)
'blistersecret-studios-is-the-best-company-in-liveronion-wonderfulsecretsound-is-in-gallifrey'
"""
return " ".join([sentence(random=random) for x in range(0, length)]) | [
"def",
"paragraph",
"(",
"random",
"=",
"random",
",",
"length",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"\" \"",
".",
"join",
"(",
"[",
"sentence",
"(",
"random",
"=",
"random",
")",
"for",
"x",
"in",
"range",
"... | Produces a paragraph of text.
>>> mock_random.seed(0)
>>> paragraph(random=mock_random, length=2)
"Agatha Incrediblebritches can't wait to smell two chimps in Boatbencheston. Wonderfulsecretsound is in Gallifrey."
>>> mock_random.seed(2)
>>> paragraph(random=mock_random, length=2, slugify=True)
'blistersecret-studios-is-the-best-company-in-liveronion-wonderfulsecretsound-is-in-gallifrey' | [
"Produces",
"a",
"paragraph",
"of",
"text",
"."
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1268-L1281 | train | 33,939 |
classam/silly | silly/main.py | markdown | def markdown(random=random, length=10, *args, **kwargs):
"""
Produces a bunch of markdown text.
>>> mock_random.seed(0)
>>> markdown(random=mock_random, length=2)
'Nobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.\\nNobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.'
"""
def title_sentence():
return "\n" + "#"*random.randint(1,5) + " " + sentence(capitalize=True, random=random)
def embellish(word):
return random.choice([word, word, word, "**"+word+"**", "_"+word+"_"])
def randomly_markdownify(string):
return " ".join([embellish(word) for word in string.split(" ")])
sentences = []
for i in range(0, length):
sentences.append(random.choice([
title_sentence(),
sentence(random=random),
sentence(random=random),
randomly_markdownify(sentence(random=random))
]))
return "\n".join(sentences) | python | def markdown(random=random, length=10, *args, **kwargs):
"""
Produces a bunch of markdown text.
>>> mock_random.seed(0)
>>> markdown(random=mock_random, length=2)
'Nobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.\\nNobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.'
"""
def title_sentence():
return "\n" + "#"*random.randint(1,5) + " " + sentence(capitalize=True, random=random)
def embellish(word):
return random.choice([word, word, word, "**"+word+"**", "_"+word+"_"])
def randomly_markdownify(string):
return " ".join([embellish(word) for word in string.split(" ")])
sentences = []
for i in range(0, length):
sentences.append(random.choice([
title_sentence(),
sentence(random=random),
sentence(random=random),
randomly_markdownify(sentence(random=random))
]))
return "\n".join(sentences) | [
"def",
"markdown",
"(",
"random",
"=",
"random",
",",
"length",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"title_sentence",
"(",
")",
":",
"return",
"\"\\n\"",
"+",
"\"#\"",
"*",
"random",
".",
"randint",
"(",
"1",
",",... | Produces a bunch of markdown text.
>>> mock_random.seed(0)
>>> markdown(random=mock_random, length=2)
'Nobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.\\nNobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.' | [
"Produces",
"a",
"bunch",
"of",
"markdown",
"text",
"."
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1284-L1311 | train | 33,940 |
classam/silly | silly/main.py | company | def company(random=random, *args, **kwargs):
"""
Produce a company name
>>> mock_random.seed(0)
>>> company(random=mock_random)
'faculty of applied chimp'
>>> mock_random.seed(1)
>>> company(random=mock_random)
'blistersecret studios'
>>> mock_random.seed(2)
>>> company(random=mock_random)
'pooppooppoop studios'
>>> mock_random.seed(3)
>>> company(random=mock_random)
'britchesshop'
>>> mock_random.seed(4)
>>> company(random=mock_random, capitalize=True)
'Mystery Studies Department'
>>> mock_random.seed(5)
>>> company(random=mock_random, slugify=True)
'the-law-offices-of-magnificentslap-boatbench-and-smellmouse'
"""
return random.choice([
"faculty of applied {noun}",
"{noun}{second_noun} studios",
"{noun}{noun}{noun} studios",
"{noun}shop",
"{noun} studies department",
"the law offices of {lastname}, {noun}, and {other_lastname}",
"{country} ministry of {plural}",
"{city} municipal {noun} department",
"{city} plumbing",
"department of {noun} studies",
"{noun} management systems",
"{plural} r us",
"inter{verb}",
"the {noun} warehouse",
"integrated {noun} and {second_noun}",
"the {noun} and {second_noun} pub",
"e-cyber{verb}",
"{adjective}soft",
"{domain} Inc.",
"{thing} incorporated",
"{noun}co",
]).format(noun=noun(random=random),
plural=plural(random=random),
country=country(random=random),
city=city(random=random),
adjective=adjective(random=random),
lastname=lastname(random=random),
other_lastname=lastname(random=random),
domain=domain(random=random),
second_noun=noun(random=random),
verb=verb(random=random),
thing=thing(random=random)) | python | def company(random=random, *args, **kwargs):
"""
Produce a company name
>>> mock_random.seed(0)
>>> company(random=mock_random)
'faculty of applied chimp'
>>> mock_random.seed(1)
>>> company(random=mock_random)
'blistersecret studios'
>>> mock_random.seed(2)
>>> company(random=mock_random)
'pooppooppoop studios'
>>> mock_random.seed(3)
>>> company(random=mock_random)
'britchesshop'
>>> mock_random.seed(4)
>>> company(random=mock_random, capitalize=True)
'Mystery Studies Department'
>>> mock_random.seed(5)
>>> company(random=mock_random, slugify=True)
'the-law-offices-of-magnificentslap-boatbench-and-smellmouse'
"""
return random.choice([
"faculty of applied {noun}",
"{noun}{second_noun} studios",
"{noun}{noun}{noun} studios",
"{noun}shop",
"{noun} studies department",
"the law offices of {lastname}, {noun}, and {other_lastname}",
"{country} ministry of {plural}",
"{city} municipal {noun} department",
"{city} plumbing",
"department of {noun} studies",
"{noun} management systems",
"{plural} r us",
"inter{verb}",
"the {noun} warehouse",
"integrated {noun} and {second_noun}",
"the {noun} and {second_noun} pub",
"e-cyber{verb}",
"{adjective}soft",
"{domain} Inc.",
"{thing} incorporated",
"{noun}co",
]).format(noun=noun(random=random),
plural=plural(random=random),
country=country(random=random),
city=city(random=random),
adjective=adjective(random=random),
lastname=lastname(random=random),
other_lastname=lastname(random=random),
domain=domain(random=random),
second_noun=noun(random=random),
verb=verb(random=random),
thing=thing(random=random)) | [
"def",
"company",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"\"faculty of applied {noun}\"",
",",
"\"{noun}{second_noun} studios\"",
",",
"\"{noun}{noun}{noun} studios\"",
",",
... | Produce a company name
>>> mock_random.seed(0)
>>> company(random=mock_random)
'faculty of applied chimp'
>>> mock_random.seed(1)
>>> company(random=mock_random)
'blistersecret studios'
>>> mock_random.seed(2)
>>> company(random=mock_random)
'pooppooppoop studios'
>>> mock_random.seed(3)
>>> company(random=mock_random)
'britchesshop'
>>> mock_random.seed(4)
>>> company(random=mock_random, capitalize=True)
'Mystery Studies Department'
>>> mock_random.seed(5)
>>> company(random=mock_random, slugify=True)
'the-law-offices-of-magnificentslap-boatbench-and-smellmouse' | [
"Produce",
"a",
"company",
"name"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1332-L1388 | train | 33,941 |
classam/silly | silly/main.py | country | def country(random=random, *args, **kwargs):
"""
Produce a country name
>>> mock_random.seed(0)
>>> country(random=mock_random)
'testasia'
>>> country(random=mock_random, capitalize=True)
'West Xanth'
>>> country(random=mock_random, slugify=True)
'westeros'
"""
return random.choice([
"{country}",
"{direction} {country}"
]).format(country=random.choice(countries),
direction=direction(random=random)) | python | def country(random=random, *args, **kwargs):
"""
Produce a country name
>>> mock_random.seed(0)
>>> country(random=mock_random)
'testasia'
>>> country(random=mock_random, capitalize=True)
'West Xanth'
>>> country(random=mock_random, slugify=True)
'westeros'
"""
return random.choice([
"{country}",
"{direction} {country}"
]).format(country=random.choice(countries),
direction=direction(random=random)) | [
"def",
"country",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"\"{country}\"",
",",
"\"{direction} {country}\"",
"]",
")",
".",
"format",
"(",
"country",
"=",
"random",
... | Produce a country name
>>> mock_random.seed(0)
>>> country(random=mock_random)
'testasia'
>>> country(random=mock_random, capitalize=True)
'West Xanth'
>>> country(random=mock_random, slugify=True)
'westeros' | [
"Produce",
"a",
"country",
"name"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1393-L1410 | train | 33,942 |
classam/silly | silly/main.py | city | def city(random=random, *args, **kwargs):
"""
Produce a city name
>>> mock_random.seed(0)
>>> city(random=mock_random)
'east mysteryhall'
>>> city(random=mock_random, capitalize=True)
'Birmingchimp'
>>> city(random=mock_random, slugify=True)
'wonderfulsecretsound'
"""
return random.choice([
"{direction} {noun}{city_suffix}",
"{noun}{city_suffix}",
"{adjective}{noun}{city_suffix}",
"{plural}{city_suffix}",
"{adjective}{city_suffix}",
"liver{noun}",
"birming{noun}",
"{noun}{city_suffix} {direction}"
]).format(direction=direction(random=random),
adjective=adjective(random=random),
plural=plural(random=random),
city_suffix=city_suffix(random=random),
noun=noun(random=random)) | python | def city(random=random, *args, **kwargs):
"""
Produce a city name
>>> mock_random.seed(0)
>>> city(random=mock_random)
'east mysteryhall'
>>> city(random=mock_random, capitalize=True)
'Birmingchimp'
>>> city(random=mock_random, slugify=True)
'wonderfulsecretsound'
"""
return random.choice([
"{direction} {noun}{city_suffix}",
"{noun}{city_suffix}",
"{adjective}{noun}{city_suffix}",
"{plural}{city_suffix}",
"{adjective}{city_suffix}",
"liver{noun}",
"birming{noun}",
"{noun}{city_suffix} {direction}"
]).format(direction=direction(random=random),
adjective=adjective(random=random),
plural=plural(random=random),
city_suffix=city_suffix(random=random),
noun=noun(random=random)) | [
"def",
"city",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"\"{direction} {noun}{city_suffix}\"",
",",
"\"{noun}{city_suffix}\"",
",",
"\"{adjective}{noun}{city_suffix}\"",
",",
... | Produce a city name
>>> mock_random.seed(0)
>>> city(random=mock_random)
'east mysteryhall'
>>> city(random=mock_random, capitalize=True)
'Birmingchimp'
>>> city(random=mock_random, slugify=True)
'wonderfulsecretsound' | [
"Produce",
"a",
"city",
"name"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1415-L1441 | train | 33,943 |
classam/silly | silly/main.py | postal_code | def postal_code(random=random, *args, **kwargs):
"""
Produce something that vaguely resembles a postal code
>>> mock_random.seed(0)
>>> postal_code(random=mock_random)
'b0b 0c0'
>>> postal_code(random=mock_random, capitalize=True)
'E0E 0F0'
>>> postal_code(random=mock_random, slugify=True)
'h0h-0i0'
"""
return random.choice([
"{letter}{number}{letter} {other_number}{other_letter}{other_number}",
"{number}{other_number}{number}{number}{other_number}",
"{number}{letter}{number}{other_number}{other_letter}"
]).format(
number=number(random=random),
other_number=number(random=random),
letter=letter(random=random),
other_letter=letter(random=random)
) | python | def postal_code(random=random, *args, **kwargs):
"""
Produce something that vaguely resembles a postal code
>>> mock_random.seed(0)
>>> postal_code(random=mock_random)
'b0b 0c0'
>>> postal_code(random=mock_random, capitalize=True)
'E0E 0F0'
>>> postal_code(random=mock_random, slugify=True)
'h0h-0i0'
"""
return random.choice([
"{letter}{number}{letter} {other_number}{other_letter}{other_number}",
"{number}{other_number}{number}{number}{other_number}",
"{number}{letter}{number}{other_number}{other_letter}"
]).format(
number=number(random=random),
other_number=number(random=random),
letter=letter(random=random),
other_letter=letter(random=random)
) | [
"def",
"postal_code",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"\"{letter}{number}{letter} {other_number}{other_letter}{other_number}\"",
",",
"\"{number}{other_number}{number}{number... | Produce something that vaguely resembles a postal code
>>> mock_random.seed(0)
>>> postal_code(random=mock_random)
'b0b 0c0'
>>> postal_code(random=mock_random, capitalize=True)
'E0E 0F0'
>>> postal_code(random=mock_random, slugify=True)
'h0h-0i0' | [
"Produce",
"something",
"that",
"vaguely",
"resembles",
"a",
"postal",
"code"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1446-L1468 | train | 33,944 |
classam/silly | silly/main.py | street | def street(random=random, *args, **kwargs):
"""
Produce something that sounds like a street name
>>> mock_random.seed(0)
>>> street(random=mock_random)
'chimp place'
>>> street(random=mock_random, capitalize=True)
'Boatbench Block'
>>> mock_random.seed(3)
>>> street(random=mock_random, slugify=True)
'central-britches-boulevard'
"""
return random.choice([
"{noun} {street_type}",
"{adjective}{verb} {street_type}",
"{direction} {adjective}{verb} {street_type}",
"{direction} {noun} {street_type}",
"{direction} {lastname} {street_type}",
]).format(noun=noun(random=random),
lastname=lastname(random=random),
direction=direction(random=random),
adjective=adjective(random=random),
verb=verb(random=random),
street_type=random.choice(streets)) | python | def street(random=random, *args, **kwargs):
"""
Produce something that sounds like a street name
>>> mock_random.seed(0)
>>> street(random=mock_random)
'chimp place'
>>> street(random=mock_random, capitalize=True)
'Boatbench Block'
>>> mock_random.seed(3)
>>> street(random=mock_random, slugify=True)
'central-britches-boulevard'
"""
return random.choice([
"{noun} {street_type}",
"{adjective}{verb} {street_type}",
"{direction} {adjective}{verb} {street_type}",
"{direction} {noun} {street_type}",
"{direction} {lastname} {street_type}",
]).format(noun=noun(random=random),
lastname=lastname(random=random),
direction=direction(random=random),
adjective=adjective(random=random),
verb=verb(random=random),
street_type=random.choice(streets)) | [
"def",
"street",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"\"{noun} {street_type}\"",
",",
"\"{adjective}{verb} {street_type}\"",
",",
"\"{direction} {adjective}{verb} {street_typ... | Produce something that sounds like a street name
>>> mock_random.seed(0)
>>> street(random=mock_random)
'chimp place'
>>> street(random=mock_random, capitalize=True)
'Boatbench Block'
>>> mock_random.seed(3)
>>> street(random=mock_random, slugify=True)
'central-britches-boulevard' | [
"Produce",
"something",
"that",
"sounds",
"like",
"a",
"street",
"name"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1474-L1499 | train | 33,945 |
classam/silly | silly/main.py | address | def address(random=random, *args, **kwargs):
"""
A street name plus a number!
>>> mock_random.seed(0)
>>> address(random=mock_random)
'0000 amazingslap boardwalk'
>>> address(random=mock_random, capitalize=True)
'0000 South Throbbingjump Boulevard'
>>> address(random=mock_random, slugify=True)
'two-central-britches-boulevard'
"""
return random.choice([
"{number}{other_number}{number}{other_number} {street}",
"{number}{other_number} {street}",
"{numberwang} {street}",
"apt {numberwang}, {number}{other_number}{other_number} {street}",
"apt {number}{other_number}{number}, {numberwang} {street}",
"po box {number}{other_number}{number}{other_number}",
]).format(number=number(random=random),
other_number=number(random=random),
numberwang=numberwang(random=random),
street=street(random=random)) | python | def address(random=random, *args, **kwargs):
"""
A street name plus a number!
>>> mock_random.seed(0)
>>> address(random=mock_random)
'0000 amazingslap boardwalk'
>>> address(random=mock_random, capitalize=True)
'0000 South Throbbingjump Boulevard'
>>> address(random=mock_random, slugify=True)
'two-central-britches-boulevard'
"""
return random.choice([
"{number}{other_number}{number}{other_number} {street}",
"{number}{other_number} {street}",
"{numberwang} {street}",
"apt {numberwang}, {number}{other_number}{other_number} {street}",
"apt {number}{other_number}{number}, {numberwang} {street}",
"po box {number}{other_number}{number}{other_number}",
]).format(number=number(random=random),
other_number=number(random=random),
numberwang=numberwang(random=random),
street=street(random=random)) | [
"def",
"address",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"\"{number}{other_number}{number}{other_number} {street}\"",
",",
"\"{number}{other_number} {street}\"",
",",
"\"{number... | A street name plus a number!
>>> mock_random.seed(0)
>>> address(random=mock_random)
'0000 amazingslap boardwalk'
>>> address(random=mock_random, capitalize=True)
'0000 South Throbbingjump Boulevard'
>>> address(random=mock_random, slugify=True)
'two-central-britches-boulevard' | [
"A",
"street",
"name",
"plus",
"a",
"number!"
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1504-L1527 | train | 33,946 |
classam/silly | silly/main.py | image | def image(random=random, width=800, height=600, https=False, *args, **kwargs):
"""
Generate the address of a placeholder image.
>>> mock_random.seed(0)
>>> image(random=mock_random)
'http://dummyimage.com/800x600/292929/e3e3e3&text=mighty poop'
>>> image(random=mock_random, width=60, height=60)
'http://placekitten.com/60/60'
>>> image(random=mock_random, width=1920, height=1080)
'http://dummyimage.com/1920x1080/292929/e3e3e3&text=To get to Westeros, you need to go to Britchestown, then drive west.'
>>> image(random=mock_random, https=True, width=1920, height=1080)
'https://dummyimage.com/1920x1080/292929/e3e3e3&text=East Mysteryhall is in Westeros.'
"""
target_fn = noun
if width+height > 300:
target_fn = thing
if width+height > 2000:
target_fn = sentence
s = ""
if https:
s = "s"
if random.choice([True, False]):
return "http{s}://dummyimage.com/{width}x{height}/292929/e3e3e3&text={text}".format(
s=s,
width=width,
height=height,
text=target_fn(random=random))
else:
return "http{s}://placekitten.com/{width}/{height}".format(s=s, width=width, height=height) | python | def image(random=random, width=800, height=600, https=False, *args, **kwargs):
"""
Generate the address of a placeholder image.
>>> mock_random.seed(0)
>>> image(random=mock_random)
'http://dummyimage.com/800x600/292929/e3e3e3&text=mighty poop'
>>> image(random=mock_random, width=60, height=60)
'http://placekitten.com/60/60'
>>> image(random=mock_random, width=1920, height=1080)
'http://dummyimage.com/1920x1080/292929/e3e3e3&text=To get to Westeros, you need to go to Britchestown, then drive west.'
>>> image(random=mock_random, https=True, width=1920, height=1080)
'https://dummyimage.com/1920x1080/292929/e3e3e3&text=East Mysteryhall is in Westeros.'
"""
target_fn = noun
if width+height > 300:
target_fn = thing
if width+height > 2000:
target_fn = sentence
s = ""
if https:
s = "s"
if random.choice([True, False]):
return "http{s}://dummyimage.com/{width}x{height}/292929/e3e3e3&text={text}".format(
s=s,
width=width,
height=height,
text=target_fn(random=random))
else:
return "http{s}://placekitten.com/{width}/{height}".format(s=s, width=width, height=height) | [
"def",
"image",
"(",
"random",
"=",
"random",
",",
"width",
"=",
"800",
",",
"height",
"=",
"600",
",",
"https",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"target_fn",
"=",
"noun",
"if",
"width",
"+",
"height",
">",
"300"... | Generate the address of a placeholder image.
>>> mock_random.seed(0)
>>> image(random=mock_random)
'http://dummyimage.com/800x600/292929/e3e3e3&text=mighty poop'
>>> image(random=mock_random, width=60, height=60)
'http://placekitten.com/60/60'
>>> image(random=mock_random, width=1920, height=1080)
'http://dummyimage.com/1920x1080/292929/e3e3e3&text=To get to Westeros, you need to go to Britchestown, then drive west.'
>>> image(random=mock_random, https=True, width=1920, height=1080)
'https://dummyimage.com/1920x1080/292929/e3e3e3&text=East Mysteryhall is in Westeros.' | [
"Generate",
"the",
"address",
"of",
"a",
"placeholder",
"image",
"."
] | f3202e997d5ebc9e4f98370b08665fd1178a9556 | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L1530-L1563 | train | 33,947 |
andersinno/python-database-sanitizer | database_sanitizer/utils/postgres.py | decode_copy_value | def decode_copy_value(value):
"""
Decodes value received as part of Postgres `COPY` command.
:param value: Value to decode.
:type value: str
:return: Either None if the value is NULL string, or the given value where
escape sequences have been decoded from.
:rtype: str|None
"""
# Test for null values first.
if value == POSTGRES_COPY_NULL_VALUE:
return None
# If there is no backslash present, there's nothing to decode.
#
# This early return provides a little speed-up, because it's very
# common to not have anything to decode and then simple search for
# backslash is faster than the regex sub below.
if '\\' not in value:
return value
return DECODE_REGEX.sub(unescape_single_character, value) | python | def decode_copy_value(value):
"""
Decodes value received as part of Postgres `COPY` command.
:param value: Value to decode.
:type value: str
:return: Either None if the value is NULL string, or the given value where
escape sequences have been decoded from.
:rtype: str|None
"""
# Test for null values first.
if value == POSTGRES_COPY_NULL_VALUE:
return None
# If there is no backslash present, there's nothing to decode.
#
# This early return provides a little speed-up, because it's very
# common to not have anything to decode and then simple search for
# backslash is faster than the regex sub below.
if '\\' not in value:
return value
return DECODE_REGEX.sub(unescape_single_character, value) | [
"def",
"decode_copy_value",
"(",
"value",
")",
":",
"# Test for null values first.",
"if",
"value",
"==",
"POSTGRES_COPY_NULL_VALUE",
":",
"return",
"None",
"# If there is no backslash present, there's nothing to decode.",
"#",
"# This early return provides a little speed-up, because... | Decodes value received as part of Postgres `COPY` command.
:param value: Value to decode.
:type value: str
:return: Either None if the value is NULL string, or the given value where
escape sequences have been decoded from.
:rtype: str|None | [
"Decodes",
"value",
"received",
"as",
"part",
"of",
"Postgres",
"COPY",
"command",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/utils/postgres.py#L59-L82 | train | 33,948 |
andersinno/python-database-sanitizer | database_sanitizer/utils/postgres.py | unescape_single_character | def unescape_single_character(match):
"""
Unescape a single escape sequence found by regular expression.
:param match: Regular expression match object
:rtype: str
:raises: ValueError if the escape sequence is invalid
"""
try:
return DECODE_MAP[match.group(0)]
except KeyError:
value = match.group(0)
if value == '\\':
raise ValueError("Unterminated escape sequence encountered")
raise ValueError(
"Unrecognized escape sequence encountered: {}".format(value)) | python | def unescape_single_character(match):
"""
Unescape a single escape sequence found by regular expression.
:param match: Regular expression match object
:rtype: str
:raises: ValueError if the escape sequence is invalid
"""
try:
return DECODE_MAP[match.group(0)]
except KeyError:
value = match.group(0)
if value == '\\':
raise ValueError("Unterminated escape sequence encountered")
raise ValueError(
"Unrecognized escape sequence encountered: {}".format(value)) | [
"def",
"unescape_single_character",
"(",
"match",
")",
":",
"try",
":",
"return",
"DECODE_MAP",
"[",
"match",
".",
"group",
"(",
"0",
")",
"]",
"except",
"KeyError",
":",
"value",
"=",
"match",
".",
"group",
"(",
"0",
")",
"if",
"value",
"==",
"'\\\\'"... | Unescape a single escape sequence found by regular expression.
:param match: Regular expression match object
:rtype: str
:raises: ValueError if the escape sequence is invalid | [
"Unescape",
"a",
"single",
"escape",
"sequence",
"found",
"by",
"regular",
"expression",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/utils/postgres.py#L85-L101 | train | 33,949 |
andersinno/python-database-sanitizer | database_sanitizer/dump/__init__.py | run | def run(url, output, config):
"""
Extracts database dump from given database URL and outputs sanitized
copy of it into given stream.
:param url: URL to the database which is to be sanitized.
:type url: str
:param output: Stream where sanitized copy of the database dump will be
written into.
:type output: file
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None
"""
parsed_url = urlparse.urlparse(url)
db_module_path = SUPPORTED_DATABASE_MODULES.get(parsed_url.scheme)
if not db_module_path:
raise ValueError("Unsupported database scheme: '%s'" % (parsed_url.scheme,))
db_module = importlib.import_module(db_module_path)
session.reset()
for line in db_module.sanitize(url=parsed_url, config=config):
output.write(line + "\n") | python | def run(url, output, config):
"""
Extracts database dump from given database URL and outputs sanitized
copy of it into given stream.
:param url: URL to the database which is to be sanitized.
:type url: str
:param output: Stream where sanitized copy of the database dump will be
written into.
:type output: file
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None
"""
parsed_url = urlparse.urlparse(url)
db_module_path = SUPPORTED_DATABASE_MODULES.get(parsed_url.scheme)
if not db_module_path:
raise ValueError("Unsupported database scheme: '%s'" % (parsed_url.scheme,))
db_module = importlib.import_module(db_module_path)
session.reset()
for line in db_module.sanitize(url=parsed_url, config=config):
output.write(line + "\n") | [
"def",
"run",
"(",
"url",
",",
"output",
",",
"config",
")",
":",
"parsed_url",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"db_module_path",
"=",
"SUPPORTED_DATABASE_MODULES",
".",
"get",
"(",
"parsed_url",
".",
"scheme",
")",
"if",
"not",
"db_modu... | Extracts database dump from given database URL and outputs sanitized
copy of it into given stream.
:param url: URL to the database which is to be sanitized.
:type url: str
:param output: Stream where sanitized copy of the database dump will be
written into.
:type output: file
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None | [
"Extracts",
"database",
"dump",
"from",
"given",
"database",
"URL",
"and",
"outputs",
"sanitized",
"copy",
"of",
"it",
"into",
"given",
"stream",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/dump/__init__.py#L24-L47 | train | 33,950 |
andersinno/python-database-sanitizer | database_sanitizer/dump/postgres.py | sanitize | def sanitize(url, config):
"""
Obtains dump of an Postgres database by executing `pg_dump` command and
sanitizes it's output.
:param url: URL to the database which is going to be sanitized, parsed by
Python's URL parser.
:type url: six.moves.urllib.parse.ParseResult
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None
"""
if url.scheme not in ("postgres", "postgresql", "postgis"):
raise ValueError("Unsupported database type: '%s'" % (url.scheme,))
process = subprocess.Popen(
(
"pg_dump",
# Force output to be UTF-8 encoded.
"--encoding=utf-8",
# Quote all table and column names, just in case.
"--quote-all-identifiers",
# Luckily `pg_dump` supports DB URLs, so we can just pass it the
# URL as argument to the command.
"--dbname",
url.geturl().replace('postgis://', 'postgresql://'),
),
stdout=subprocess.PIPE,
)
sanitize_value_line = None
current_table = None
current_table_columns = None
for line in io.TextIOWrapper(process.stdout, encoding="utf-8"):
# Eat the trailing new line.
line = line.rstrip("\n")
# Are we currently in middle of `COPY` statement?
if current_table:
# Backslash following a dot marks end of an `COPY` statement.
if line == "\\.":
current_table = None
current_table_columns = None
yield "\\."
continue
if not sanitize_value_line:
yield line
continue
yield sanitize_value_line(line)
continue
# Is the line beginning of `COPY` statement?
copy_line_match = COPY_LINE_PATTERN.match(line)
if not copy_line_match:
yield line
continue
current_table = copy_line_match.group("table")
current_table_columns = parse_column_names(copy_line_match.group("columns"))
sanitize_value_line = get_value_line_sanitizer(
config, current_table, current_table_columns)
yield line | python | def sanitize(url, config):
"""
Obtains dump of an Postgres database by executing `pg_dump` command and
sanitizes it's output.
:param url: URL to the database which is going to be sanitized, parsed by
Python's URL parser.
:type url: six.moves.urllib.parse.ParseResult
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None
"""
if url.scheme not in ("postgres", "postgresql", "postgis"):
raise ValueError("Unsupported database type: '%s'" % (url.scheme,))
process = subprocess.Popen(
(
"pg_dump",
# Force output to be UTF-8 encoded.
"--encoding=utf-8",
# Quote all table and column names, just in case.
"--quote-all-identifiers",
# Luckily `pg_dump` supports DB URLs, so we can just pass it the
# URL as argument to the command.
"--dbname",
url.geturl().replace('postgis://', 'postgresql://'),
),
stdout=subprocess.PIPE,
)
sanitize_value_line = None
current_table = None
current_table_columns = None
for line in io.TextIOWrapper(process.stdout, encoding="utf-8"):
# Eat the trailing new line.
line = line.rstrip("\n")
# Are we currently in middle of `COPY` statement?
if current_table:
# Backslash following a dot marks end of an `COPY` statement.
if line == "\\.":
current_table = None
current_table_columns = None
yield "\\."
continue
if not sanitize_value_line:
yield line
continue
yield sanitize_value_line(line)
continue
# Is the line beginning of `COPY` statement?
copy_line_match = COPY_LINE_PATTERN.match(line)
if not copy_line_match:
yield line
continue
current_table = copy_line_match.group("table")
current_table_columns = parse_column_names(copy_line_match.group("columns"))
sanitize_value_line = get_value_line_sanitizer(
config, current_table, current_table_columns)
yield line | [
"def",
"sanitize",
"(",
"url",
",",
"config",
")",
":",
"if",
"url",
".",
"scheme",
"not",
"in",
"(",
"\"postgres\"",
",",
"\"postgresql\"",
",",
"\"postgis\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Unsupported database type: '%s'\"",
"%",
"(",
"url",
"."... | Obtains dump of an Postgres database by executing `pg_dump` command and
sanitizes it's output.
:param url: URL to the database which is going to be sanitized, parsed by
Python's URL parser.
:type url: six.moves.urllib.parse.ParseResult
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None | [
"Obtains",
"dump",
"of",
"an",
"Postgres",
"database",
"by",
"executing",
"pg_dump",
"command",
"and",
"sanitizes",
"it",
"s",
"output",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/dump/postgres.py#L18-L85 | train | 33,951 |
andersinno/python-database-sanitizer | database_sanitizer/dump/postgres.py | parse_column_names | def parse_column_names(text):
"""
Extracts column names from a string containing quoted and comma separated
column names.
:param text: Line extracted from `COPY` statement containing quoted and
comma separated column names.
:type text: str
:return: Tuple containing just the column names.
:rtype: tuple[str]
"""
return tuple(
re.sub(r"^\"(.*)\"$", r"\1", column_name.strip())
for column_name in text.split(",")
) | python | def parse_column_names(text):
"""
Extracts column names from a string containing quoted and comma separated
column names.
:param text: Line extracted from `COPY` statement containing quoted and
comma separated column names.
:type text: str
:return: Tuple containing just the column names.
:rtype: tuple[str]
"""
return tuple(
re.sub(r"^\"(.*)\"$", r"\1", column_name.strip())
for column_name in text.split(",")
) | [
"def",
"parse_column_names",
"(",
"text",
")",
":",
"return",
"tuple",
"(",
"re",
".",
"sub",
"(",
"r\"^\\\"(.*)\\\"$\"",
",",
"r\"\\1\"",
",",
"column_name",
".",
"strip",
"(",
")",
")",
"for",
"column_name",
"in",
"text",
".",
"split",
"(",
"\",\"",
")... | Extracts column names from a string containing quoted and comma separated
column names.
:param text: Line extracted from `COPY` statement containing quoted and
comma separated column names.
:type text: str
:return: Tuple containing just the column names.
:rtype: tuple[str] | [
"Extracts",
"column",
"names",
"from",
"a",
"string",
"containing",
"quoted",
"and",
"comma",
"separated",
"column",
"names",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/dump/postgres.py#L123-L138 | train | 33,952 |
andersinno/python-database-sanitizer | database_sanitizer/utils/mysql.py | get_mysqldump_args_and_env_from_url | def get_mysqldump_args_and_env_from_url(url):
"""
Constructs list of command line arguments and dictionary of environment
variables that can be given to `mysqldump` executable to obtain database
dump of the database described in given URL.
:param url: Parsed database URL.
:type url: urllib.urlparse.ParseResult
:return: List of command line arguments as well as dictionary of
environment variables that can be used to launch the MySQL dump
process to obtain dump of the database.
:rtype: tuple[list[str],dict[str,str]]
"""
args = [
# Without this, `INSERT INTO` statements will exclude column names from
# the output, which are required for sanitation.
"--complete-insert",
# This enables use for "exteded inserts" where multiple rows of a table
# are included in a single `INSERT INTO` statement (contents of the
# entire table even, if it's within limits). We use it to increase the
# performance of the sanitation and to decrease the dump size.
"--extended-insert",
# This makes the `mysqldump` to attempt to limit size of a single line
# into 10 megabytes. We use it to reduce memory consumption.
"--net_buffer_length=10240",
# Hostname of the database to connect into, should be always present in
# the parsed database URL.
"-h",
url.hostname,
]
env = {}
if url.port is not None:
args.extend(("-P", six.text_type(url.port)))
if url.username:
args.extend(("-u", url.username))
if url.password:
env["MYSQL_PWD"] = url.password
if len(url.path) < 2 or not url.path.startswith("/"):
raise ValueError("Name of the database is missing from the URL")
args.append(url.path[1:])
return args, env | python | def get_mysqldump_args_and_env_from_url(url):
"""
Constructs list of command line arguments and dictionary of environment
variables that can be given to `mysqldump` executable to obtain database
dump of the database described in given URL.
:param url: Parsed database URL.
:type url: urllib.urlparse.ParseResult
:return: List of command line arguments as well as dictionary of
environment variables that can be used to launch the MySQL dump
process to obtain dump of the database.
:rtype: tuple[list[str],dict[str,str]]
"""
args = [
# Without this, `INSERT INTO` statements will exclude column names from
# the output, which are required for sanitation.
"--complete-insert",
# This enables use for "exteded inserts" where multiple rows of a table
# are included in a single `INSERT INTO` statement (contents of the
# entire table even, if it's within limits). We use it to increase the
# performance of the sanitation and to decrease the dump size.
"--extended-insert",
# This makes the `mysqldump` to attempt to limit size of a single line
# into 10 megabytes. We use it to reduce memory consumption.
"--net_buffer_length=10240",
# Hostname of the database to connect into, should be always present in
# the parsed database URL.
"-h",
url.hostname,
]
env = {}
if url.port is not None:
args.extend(("-P", six.text_type(url.port)))
if url.username:
args.extend(("-u", url.username))
if url.password:
env["MYSQL_PWD"] = url.password
if len(url.path) < 2 or not url.path.startswith("/"):
raise ValueError("Name of the database is missing from the URL")
args.append(url.path[1:])
return args, env | [
"def",
"get_mysqldump_args_and_env_from_url",
"(",
"url",
")",
":",
"args",
"=",
"[",
"# Without this, `INSERT INTO` statements will exclude column names from",
"# the output, which are required for sanitation.",
"\"--complete-insert\"",
",",
"# This enables use for \"exteded inserts\" whe... | Constructs list of command line arguments and dictionary of environment
variables that can be given to `mysqldump` executable to obtain database
dump of the database described in given URL.
:param url: Parsed database URL.
:type url: urllib.urlparse.ParseResult
:return: List of command line arguments as well as dictionary of
environment variables that can be used to launch the MySQL dump
process to obtain dump of the database.
:rtype: tuple[list[str],dict[str,str]] | [
"Constructs",
"list",
"of",
"command",
"line",
"arguments",
"and",
"dictionary",
"of",
"environment",
"variables",
"that",
"can",
"be",
"given",
"to",
"mysqldump",
"executable",
"to",
"obtain",
"database",
"dump",
"of",
"the",
"database",
"described",
"in",
"giv... | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/utils/mysql.py#L11-L61 | train | 33,953 |
andersinno/python-database-sanitizer | database_sanitizer/utils/mysql.py | decode_mysql_literal | def decode_mysql_literal(text):
"""
Attempts to decode given MySQL literal into Python value.
:param text: Value to be decoded, as MySQL literal.
:type text: str
:return: Python version of the given MySQL literal.
:rtype: any
"""
if MYSQL_NULL_PATTERN.match(text):
return None
if MYSQL_BOOLEAN_PATTERN.match(text):
return text.lower() == "true"
if MYSQL_FLOAT_PATTERN.match(text):
return float(text)
if MYSQL_INT_PATTERN.match(text):
return int(text)
if MYSQL_STRING_PATTERN.match(text):
return decode_mysql_string_literal(text)
raise ValueError("Unable to decode given value: %r" % (text,)) | python | def decode_mysql_literal(text):
"""
Attempts to decode given MySQL literal into Python value.
:param text: Value to be decoded, as MySQL literal.
:type text: str
:return: Python version of the given MySQL literal.
:rtype: any
"""
if MYSQL_NULL_PATTERN.match(text):
return None
if MYSQL_BOOLEAN_PATTERN.match(text):
return text.lower() == "true"
if MYSQL_FLOAT_PATTERN.match(text):
return float(text)
if MYSQL_INT_PATTERN.match(text):
return int(text)
if MYSQL_STRING_PATTERN.match(text):
return decode_mysql_string_literal(text)
raise ValueError("Unable to decode given value: %r" % (text,)) | [
"def",
"decode_mysql_literal",
"(",
"text",
")",
":",
"if",
"MYSQL_NULL_PATTERN",
".",
"match",
"(",
"text",
")",
":",
"return",
"None",
"if",
"MYSQL_BOOLEAN_PATTERN",
".",
"match",
"(",
"text",
")",
":",
"return",
"text",
".",
"lower",
"(",
")",
"==",
"... | Attempts to decode given MySQL literal into Python value.
:param text: Value to be decoded, as MySQL literal.
:type text: str
:return: Python version of the given MySQL literal.
:rtype: any | [
"Attempts",
"to",
"decode",
"given",
"MySQL",
"literal",
"into",
"Python",
"value",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/utils/mysql.py#L71-L96 | train | 33,954 |
andersinno/python-database-sanitizer | database_sanitizer/utils/mysql.py | decode_mysql_string_literal | def decode_mysql_string_literal(text):
"""
Removes quotes and decodes escape sequences from given MySQL string literal
returning the result.
:param text: MySQL string literal, with the quotes still included.
:type text: str
:return: Given string literal with quotes removed and escape sequences
decoded.
:rtype: str
"""
assert text.startswith("'")
assert text.endswith("'")
# Ditch quotes from the string literal.
text = text[1:-1]
return MYSQL_STRING_ESCAPE_SEQUENCE_PATTERN.sub(
unescape_single_character,
text,
) | python | def decode_mysql_string_literal(text):
"""
Removes quotes and decodes escape sequences from given MySQL string literal
returning the result.
:param text: MySQL string literal, with the quotes still included.
:type text: str
:return: Given string literal with quotes removed and escape sequences
decoded.
:rtype: str
"""
assert text.startswith("'")
assert text.endswith("'")
# Ditch quotes from the string literal.
text = text[1:-1]
return MYSQL_STRING_ESCAPE_SEQUENCE_PATTERN.sub(
unescape_single_character,
text,
) | [
"def",
"decode_mysql_string_literal",
"(",
"text",
")",
":",
"assert",
"text",
".",
"startswith",
"(",
"\"'\"",
")",
"assert",
"text",
".",
"endswith",
"(",
"\"'\"",
")",
"# Ditch quotes from the string literal.",
"text",
"=",
"text",
"[",
"1",
":",
"-",
"1",
... | Removes quotes and decodes escape sequences from given MySQL string literal
returning the result.
:param text: MySQL string literal, with the quotes still included.
:type text: str
:return: Given string literal with quotes removed and escape sequences
decoded.
:rtype: str | [
"Removes",
"quotes",
"and",
"decodes",
"escape",
"sequences",
"from",
"given",
"MySQL",
"string",
"literal",
"returning",
"the",
"result",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/utils/mysql.py#L110-L131 | train | 33,955 |
safarijv/sbo-selenium | sbo_selenium/utils.py | OutputMonitor.wait_for | def wait_for(self, text, seconds):
"""
Returns True when the specified text has appeared in a line of the
output, or False when the specified number of seconds have passed
without that occurring.
"""
found = False
stream = self.stream
start_time = time.time()
while not found:
if time.time() - start_time > seconds:
break
stream.data_available.wait(0.5)
stream.data_unoccupied.clear()
while stream.data:
line = stream.data.pop(0)
value = line.getvalue()
if text in value:
found = True
self.lines.append(value)
stream.data_available.clear()
stream.data_unoccupied.set()
if time.time() - start_time > seconds:
break
return found | python | def wait_for(self, text, seconds):
"""
Returns True when the specified text has appeared in a line of the
output, or False when the specified number of seconds have passed
without that occurring.
"""
found = False
stream = self.stream
start_time = time.time()
while not found:
if time.time() - start_time > seconds:
break
stream.data_available.wait(0.5)
stream.data_unoccupied.clear()
while stream.data:
line = stream.data.pop(0)
value = line.getvalue()
if text in value:
found = True
self.lines.append(value)
stream.data_available.clear()
stream.data_unoccupied.set()
if time.time() - start_time > seconds:
break
return found | [
"def",
"wait_for",
"(",
"self",
",",
"text",
",",
"seconds",
")",
":",
"found",
"=",
"False",
"stream",
"=",
"self",
".",
"stream",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"not",
"found",
":",
"if",
"time",
".",
"time",
"(",
")",... | Returns True when the specified text has appeared in a line of the
output, or False when the specified number of seconds have passed
without that occurring. | [
"Returns",
"True",
"when",
"the",
"specified",
"text",
"has",
"appeared",
"in",
"a",
"line",
"of",
"the",
"output",
"or",
"False",
"when",
"the",
"specified",
"number",
"of",
"seconds",
"have",
"passed",
"without",
"that",
"occurring",
"."
] | 16539f1b17cda18270033db3b64ab25bc05c5664 | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/utils.py#L176-L200 | train | 33,956 |
safarijv/sbo-selenium | sbo_selenium/utils.py | DockerSelenium.command_executor | def command_executor(self):
"""Get the appropriate command executor URL for the Selenium server
running in the Docker container."""
ip_address = self.ip_address if self.ip_address else '127.0.0.1'
return 'http://{}:{}/wd/hub'.format(ip_address, self.port) | python | def command_executor(self):
"""Get the appropriate command executor URL for the Selenium server
running in the Docker container."""
ip_address = self.ip_address if self.ip_address else '127.0.0.1'
return 'http://{}:{}/wd/hub'.format(ip_address, self.port) | [
"def",
"command_executor",
"(",
"self",
")",
":",
"ip_address",
"=",
"self",
".",
"ip_address",
"if",
"self",
".",
"ip_address",
"else",
"'127.0.0.1'",
"return",
"'http://{}:{}/wd/hub'",
".",
"format",
"(",
"ip_address",
",",
"self",
".",
"port",
")"
] | Get the appropriate command executor URL for the Selenium server
running in the Docker container. | [
"Get",
"the",
"appropriate",
"command",
"executor",
"URL",
"for",
"the",
"Selenium",
"server",
"running",
"in",
"the",
"Docker",
"container",
"."
] | 16539f1b17cda18270033db3b64ab25bc05c5664 | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/utils.py#L223-L227 | train | 33,957 |
safarijv/sbo-selenium | sbo_selenium/utils.py | DockerSelenium.start | def start(self):
"""Start the Docker container"""
if self.container_id is not None:
msg = 'The Docker container is already running with ID {}'
raise Exception(msg.format(self.container_id))
process = Popen(['docker ps | grep ":{}"'.format(self.port)],
shell=True, stdout=PIPE)
(grep_output, _grep_error) = process.communicate()
lines = grep_output.split('\n')
for line in lines:
if ':{}'.format(self.port) in line:
other_id = line.split()[0]
msg = 'Port {} is already being used by container {}'
raise Exception(msg.format(self.port, other_id))
self.container_id = check_output(self.command, shell=True).strip()
try:
self.ip_address = check_output(['docker-machine', 'ip']).strip()
except (CalledProcessError, OSError):
self.ip_address = '127.0.0.1'
output = OutputMonitor()
logs_process = Popen(['docker', 'logs', '-f', self.container_id],
stdout=output.stream.input,
stderr=open(os.devnull, 'w'))
ready_log_line = 'Selenium Server is up and running'
if not output.wait_for(ready_log_line, 10):
logs_process.kill()
msg = 'Timeout starting the Selenium server Docker container:\n'
msg += '\n'.join(output.lines)
raise Exception(msg)
logs_process.kill() | python | def start(self):
"""Start the Docker container"""
if self.container_id is not None:
msg = 'The Docker container is already running with ID {}'
raise Exception(msg.format(self.container_id))
process = Popen(['docker ps | grep ":{}"'.format(self.port)],
shell=True, stdout=PIPE)
(grep_output, _grep_error) = process.communicate()
lines = grep_output.split('\n')
for line in lines:
if ':{}'.format(self.port) in line:
other_id = line.split()[0]
msg = 'Port {} is already being used by container {}'
raise Exception(msg.format(self.port, other_id))
self.container_id = check_output(self.command, shell=True).strip()
try:
self.ip_address = check_output(['docker-machine', 'ip']).strip()
except (CalledProcessError, OSError):
self.ip_address = '127.0.0.1'
output = OutputMonitor()
logs_process = Popen(['docker', 'logs', '-f', self.container_id],
stdout=output.stream.input,
stderr=open(os.devnull, 'w'))
ready_log_line = 'Selenium Server is up and running'
if not output.wait_for(ready_log_line, 10):
logs_process.kill()
msg = 'Timeout starting the Selenium server Docker container:\n'
msg += '\n'.join(output.lines)
raise Exception(msg)
logs_process.kill() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"container_id",
"is",
"not",
"None",
":",
"msg",
"=",
"'The Docker container is already running with ID {}'",
"raise",
"Exception",
"(",
"msg",
".",
"format",
"(",
"self",
".",
"container_id",
")",
")",... | Start the Docker container | [
"Start",
"the",
"Docker",
"container"
] | 16539f1b17cda18270033db3b64ab25bc05c5664 | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/utils.py#L229-L261 | train | 33,958 |
safarijv/sbo-selenium | sbo_selenium/utils.py | DockerSelenium.stop | def stop(self):
"""Stop the Docker container"""
if self.container_id is None:
raise Exception('No Docker Selenium container was running')
check_call(['docker', 'stop', self.container_id])
self.container_id = None | python | def stop(self):
"""Stop the Docker container"""
if self.container_id is None:
raise Exception('No Docker Selenium container was running')
check_call(['docker', 'stop', self.container_id])
self.container_id = None | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"container_id",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'No Docker Selenium container was running'",
")",
"check_call",
"(",
"[",
"'docker'",
",",
"'stop'",
",",
"self",
".",
"container_id",
"]",
... | Stop the Docker container | [
"Stop",
"the",
"Docker",
"container"
] | 16539f1b17cda18270033db3b64ab25bc05c5664 | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/utils.py#L263-L268 | train | 33,959 |
andersinno/python-database-sanitizer | database_sanitizer/session.py | hash_text_to_ints | def hash_text_to_ints(value, bit_lengths=(16, 16, 16, 16)):
# type: (str, Sequence[int]) -> Sequence[int]
"""
Hash a text value to a sequence of integers.
Generates a sequence of integer values with given bit-lengths
similarly to `hash_text_to_int`, but allowing generating many
separate numbers with a single call.
:param bit_lengths:
Tuple of bit lengths for the resulting integers. Defines also the
length of the result tuple.
:return:
Tuple of ``n`` integers ``(R_1, ... R_n)`` with the requested
bit-lengths ``(L_1, ..., L_n)`` and values ranging within
``0 <= R_i < 2**L_i`` for each ``i``.
"""
hash_value = hash_text(value)
hex_lengths = [x // 4 for x in bit_lengths]
hex_ranges = (
(sum(hex_lengths[0:i]), sum(hex_lengths[0:(i + 1)]))
for i in range(len(hex_lengths)))
return tuple(int(hash_value[a:b], 16) for (a, b) in hex_ranges) | python | def hash_text_to_ints(value, bit_lengths=(16, 16, 16, 16)):
# type: (str, Sequence[int]) -> Sequence[int]
"""
Hash a text value to a sequence of integers.
Generates a sequence of integer values with given bit-lengths
similarly to `hash_text_to_int`, but allowing generating many
separate numbers with a single call.
:param bit_lengths:
Tuple of bit lengths for the resulting integers. Defines also the
length of the result tuple.
:return:
Tuple of ``n`` integers ``(R_1, ... R_n)`` with the requested
bit-lengths ``(L_1, ..., L_n)`` and values ranging within
``0 <= R_i < 2**L_i`` for each ``i``.
"""
hash_value = hash_text(value)
hex_lengths = [x // 4 for x in bit_lengths]
hex_ranges = (
(sum(hex_lengths[0:i]), sum(hex_lengths[0:(i + 1)]))
for i in range(len(hex_lengths)))
return tuple(int(hash_value[a:b], 16) for (a, b) in hex_ranges) | [
"def",
"hash_text_to_ints",
"(",
"value",
",",
"bit_lengths",
"=",
"(",
"16",
",",
"16",
",",
"16",
",",
"16",
")",
")",
":",
"# type: (str, Sequence[int]) -> Sequence[int]",
"hash_value",
"=",
"hash_text",
"(",
"value",
")",
"hex_lengths",
"=",
"[",
"x",
"/... | Hash a text value to a sequence of integers.
Generates a sequence of integer values with given bit-lengths
similarly to `hash_text_to_int`, but allowing generating many
separate numbers with a single call.
:param bit_lengths:
Tuple of bit lengths for the resulting integers. Defines also the
length of the result tuple.
:return:
Tuple of ``n`` integers ``(R_1, ... R_n)`` with the requested
bit-lengths ``(L_1, ..., L_n)`` and values ranging within
``0 <= R_i < 2**L_i`` for each ``i``. | [
"Hash",
"a",
"text",
"value",
"to",
"a",
"sequence",
"of",
"integers",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/session.py#L50-L72 | train | 33,960 |
andersinno/python-database-sanitizer | database_sanitizer/session.py | hash_text | def hash_text(value, hasher=hashlib.sha256, encoding='utf-8'):
# type: (str, Callable, str) -> str
"""
Generate a hash for a text value.
The hash will be generated by encoding the text to bytes with given
encoding and then generating a hash with HMAC using the session
secret as the key and the given hash function.
:param value: Text value to hash
:param hasher: Hash function to use, SHA256 by default
:param encoding: Encoding to use, UTF-8 by default
:return: Hexadecimal presentation of the hash as a string
"""
return hash_bytes(value.encode(encoding), hasher) | python | def hash_text(value, hasher=hashlib.sha256, encoding='utf-8'):
# type: (str, Callable, str) -> str
"""
Generate a hash for a text value.
The hash will be generated by encoding the text to bytes with given
encoding and then generating a hash with HMAC using the session
secret as the key and the given hash function.
:param value: Text value to hash
:param hasher: Hash function to use, SHA256 by default
:param encoding: Encoding to use, UTF-8 by default
:return: Hexadecimal presentation of the hash as a string
"""
return hash_bytes(value.encode(encoding), hasher) | [
"def",
"hash_text",
"(",
"value",
",",
"hasher",
"=",
"hashlib",
".",
"sha256",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"# type: (str, Callable, str) -> str",
"return",
"hash_bytes",
"(",
"value",
".",
"encode",
"(",
"encoding",
")",
",",
"hasher",
")"
] | Generate a hash for a text value.
The hash will be generated by encoding the text to bytes with given
encoding and then generating a hash with HMAC using the session
secret as the key and the given hash function.
:param value: Text value to hash
:param hasher: Hash function to use, SHA256 by default
:param encoding: Encoding to use, UTF-8 by default
:return: Hexadecimal presentation of the hash as a string | [
"Generate",
"a",
"hash",
"for",
"a",
"text",
"value",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/session.py#L75-L89 | train | 33,961 |
andersinno/python-database-sanitizer | database_sanitizer/session.py | hash_bytes | def hash_bytes(value, hasher=hashlib.sha256):
# type: (bytes, Callable) -> str
"""
Generate a hash for a bytes value.
The hash will be generated by generating a hash with HMAC using the
session secret as the key and the given hash function.
:param value: Bytes value to hash
:param hasher: Hash function to use.
:return: Hexadecimal presentation of the hash as a string
"""
return hmac.new(get_secret(), value, hasher).hexdigest() | python | def hash_bytes(value, hasher=hashlib.sha256):
# type: (bytes, Callable) -> str
"""
Generate a hash for a bytes value.
The hash will be generated by generating a hash with HMAC using the
session secret as the key and the given hash function.
:param value: Bytes value to hash
:param hasher: Hash function to use.
:return: Hexadecimal presentation of the hash as a string
"""
return hmac.new(get_secret(), value, hasher).hexdigest() | [
"def",
"hash_bytes",
"(",
"value",
",",
"hasher",
"=",
"hashlib",
".",
"sha256",
")",
":",
"# type: (bytes, Callable) -> str",
"return",
"hmac",
".",
"new",
"(",
"get_secret",
"(",
")",
",",
"value",
",",
"hasher",
")",
".",
"hexdigest",
"(",
")"
] | Generate a hash for a bytes value.
The hash will be generated by generating a hash with HMAC using the
session secret as the key and the given hash function.
:param value: Bytes value to hash
:param hasher: Hash function to use.
:return: Hexadecimal presentation of the hash as a string | [
"Generate",
"a",
"hash",
"for",
"a",
"bytes",
"value",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/session.py#L92-L104 | train | 33,962 |
andersinno/python-database-sanitizer | database_sanitizer/session.py | _initialize_session | def _initialize_session():
# type: () -> None
"""
Generate a new session key and store it to thread local storage.
"""
sys_random = random.SystemRandom()
_thread_local_storage.secret_key = b''.join(
int2byte(sys_random.randint(0, 255))
for _ in range(SECRET_KEY_BITS // 8)) | python | def _initialize_session():
# type: () -> None
"""
Generate a new session key and store it to thread local storage.
"""
sys_random = random.SystemRandom()
_thread_local_storage.secret_key = b''.join(
int2byte(sys_random.randint(0, 255))
for _ in range(SECRET_KEY_BITS // 8)) | [
"def",
"_initialize_session",
"(",
")",
":",
"# type: () -> None",
"sys_random",
"=",
"random",
".",
"SystemRandom",
"(",
")",
"_thread_local_storage",
".",
"secret_key",
"=",
"b''",
".",
"join",
"(",
"int2byte",
"(",
"sys_random",
".",
"randint",
"(",
"0",
",... | Generate a new session key and store it to thread local storage. | [
"Generate",
"a",
"new",
"session",
"key",
"and",
"store",
"it",
"to",
"thread",
"local",
"storage",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/session.py#L138-L146 | train | 33,963 |
fridiculous/estimators | estimators/evaluations.py | EvaluationMixin._get_proxy_object | def _get_proxy_object(self, obj, ProxyKlass, proxy_klass_attribute):
""" Returns the proxy object for an input object
If the object is already the proxy object, return it.
Otherwise set the appropriate proxy object to the proxy object's attribute
"""
proxy_object = obj
if not isinstance(obj, ProxyKlass):
proxy_object = ProxyKlass(**{proxy_klass_attribute: obj})
return proxy_object | python | def _get_proxy_object(self, obj, ProxyKlass, proxy_klass_attribute):
""" Returns the proxy object for an input object
If the object is already the proxy object, return it.
Otherwise set the appropriate proxy object to the proxy object's attribute
"""
proxy_object = obj
if not isinstance(obj, ProxyKlass):
proxy_object = ProxyKlass(**{proxy_klass_attribute: obj})
return proxy_object | [
"def",
"_get_proxy_object",
"(",
"self",
",",
"obj",
",",
"ProxyKlass",
",",
"proxy_klass_attribute",
")",
":",
"proxy_object",
"=",
"obj",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"ProxyKlass",
")",
":",
"proxy_object",
"=",
"ProxyKlass",
"(",
"*",
"*",
... | Returns the proxy object for an input object
If the object is already the proxy object, return it.
Otherwise set the appropriate proxy object to the proxy object's attribute | [
"Returns",
"the",
"proxy",
"object",
"for",
"an",
"input",
"object"
] | ab5b3d70f16f8372ae1114ac7e54e7791631eb74 | https://github.com/fridiculous/estimators/blob/ab5b3d70f16f8372ae1114ac7e54e7791631eb74/estimators/evaluations.py#L13-L22 | train | 33,964 |
andersinno/python-database-sanitizer | database_sanitizer/config.py | Configuration.from_file | def from_file(cls, filename):
"""
Reads configuration from given path to a file in local file system and
returns parsed version of it.
:param filename: Path to the YAML file in local file system where the
configuration will be read from.
:type filename: str
:return: Configuration instance parsed from given configuration file.
:rtype: Configuration
"""
instance = cls()
with open(filename, "rb") as file_stream:
config_data = yaml.load(file_stream)
instance.load(config_data)
return instance | python | def from_file(cls, filename):
"""
Reads configuration from given path to a file in local file system and
returns parsed version of it.
:param filename: Path to the YAML file in local file system where the
configuration will be read from.
:type filename: str
:return: Configuration instance parsed from given configuration file.
:rtype: Configuration
"""
instance = cls()
with open(filename, "rb") as file_stream:
config_data = yaml.load(file_stream)
instance.load(config_data)
return instance | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
")",
":",
"instance",
"=",
"cls",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"file_stream",
":",
"config_data",
"=",
"yaml",
".",
"load",
"(",
"file_stream",
")",
"instance",
".... | Reads configuration from given path to a file in local file system and
returns parsed version of it.
:param filename: Path to the YAML file in local file system where the
configuration will be read from.
:type filename: str
:return: Configuration instance parsed from given configuration file.
:rtype: Configuration | [
"Reads",
"configuration",
"from",
"given",
"path",
"to",
"a",
"file",
"in",
"local",
"file",
"system",
"and",
"returns",
"parsed",
"version",
"of",
"it",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/config.py#L29-L48 | train | 33,965 |
andersinno/python-database-sanitizer | database_sanitizer/config.py | Configuration.load | def load(self, config_data):
"""
Loads sanitizers according to rulesets defined in given already parsed
configuration file.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any]
"""
if not isinstance(config_data, dict):
raise ConfigurationError(
"Configuration data is %s instead of dict." % (
type(config_data),
)
)
self.load_addon_packages(config_data)
self.load_sanitizers(config_data) | python | def load(self, config_data):
"""
Loads sanitizers according to rulesets defined in given already parsed
configuration file.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any]
"""
if not isinstance(config_data, dict):
raise ConfigurationError(
"Configuration data is %s instead of dict." % (
type(config_data),
)
)
self.load_addon_packages(config_data)
self.load_sanitizers(config_data) | [
"def",
"load",
"(",
"self",
",",
"config_data",
")",
":",
"if",
"not",
"isinstance",
"(",
"config_data",
",",
"dict",
")",
":",
"raise",
"ConfigurationError",
"(",
"\"Configuration data is %s instead of dict.\"",
"%",
"(",
"type",
"(",
"config_data",
")",
",",
... | Loads sanitizers according to rulesets defined in given already parsed
configuration file.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any] | [
"Loads",
"sanitizers",
"according",
"to",
"rulesets",
"defined",
"in",
"given",
"already",
"parsed",
"configuration",
"file",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/config.py#L50-L66 | train | 33,966 |
andersinno/python-database-sanitizer | database_sanitizer/config.py | Configuration.load_addon_packages | def load_addon_packages(self, config_data):
"""
Loads the module paths from which the configuration will attempt to
load sanitizers from. These must be stored as a list of strings under
"config.addons" section of the configuration data.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any]
"""
section_config = config_data.get("config")
if not isinstance(section_config, dict):
if section_config is None:
return
raise ConfigurationError(
"'config' is %s instead of dict" % (
type(section_config),
),
)
section_addons = section_config.get("addons", [])
if not isinstance(section_addons, list):
raise ConfigurationError(
"'config.addons' is %s instead of list" % (
type(section_addons),
),
)
for index, module_path in enumerate(section_addons):
if not isinstance(module_path, six.text_type):
raise ConfigurationError(
"Item %d in 'config.addons' is %s instead of string" % (
index,
type(module_path),
),
)
self.addon_packages = list(section_addons) | python | def load_addon_packages(self, config_data):
"""
Loads the module paths from which the configuration will attempt to
load sanitizers from. These must be stored as a list of strings under
"config.addons" section of the configuration data.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any]
"""
section_config = config_data.get("config")
if not isinstance(section_config, dict):
if section_config is None:
return
raise ConfigurationError(
"'config' is %s instead of dict" % (
type(section_config),
),
)
section_addons = section_config.get("addons", [])
if not isinstance(section_addons, list):
raise ConfigurationError(
"'config.addons' is %s instead of list" % (
type(section_addons),
),
)
for index, module_path in enumerate(section_addons):
if not isinstance(module_path, six.text_type):
raise ConfigurationError(
"Item %d in 'config.addons' is %s instead of string" % (
index,
type(module_path),
),
)
self.addon_packages = list(section_addons) | [
"def",
"load_addon_packages",
"(",
"self",
",",
"config_data",
")",
":",
"section_config",
"=",
"config_data",
".",
"get",
"(",
"\"config\"",
")",
"if",
"not",
"isinstance",
"(",
"section_config",
",",
"dict",
")",
":",
"if",
"section_config",
"is",
"None",
... | Loads the module paths from which the configuration will attempt to
load sanitizers from. These must be stored as a list of strings under
"config.addons" section of the configuration data.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any] | [
"Loads",
"the",
"module",
"paths",
"from",
"which",
"the",
"configuration",
"will",
"attempt",
"to",
"load",
"sanitizers",
"from",
".",
"These",
"must",
"be",
"stored",
"as",
"a",
"list",
"of",
"strings",
"under",
"config",
".",
"addons",
"section",
"of",
... | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/config.py#L68-L104 | train | 33,967 |
andersinno/python-database-sanitizer | database_sanitizer/config.py | Configuration.load_sanitizers | def load_sanitizers(self, config_data):
"""
Loads sanitizers possibly defined in the configuration under dictionary
called "strategy", which should contain mapping of database tables with
column names mapped into sanitizer function names.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any]
"""
section_strategy = config_data.get("strategy")
if not isinstance(section_strategy, dict):
if section_strategy is None:
return
raise ConfigurationError(
"'strategy' is %s instead of dict" % (
type(section_strategy),
),
)
for table_name, column_data in six.iteritems(section_strategy):
if not isinstance(column_data, dict):
if column_data is None:
continue
raise ConfigurationError(
"'strategy.%s' is %s instead of dict" % (
table_name,
type(column_data),
),
)
for column_name, sanitizer_name in six.iteritems(column_data):
if sanitizer_name is None:
continue
if not isinstance(sanitizer_name, six.text_type):
raise ConfigurationError(
"'strategy.%s.%s' is %s instead of string" % (
table_name,
column_name,
type(sanitizer_name),
),
)
sanitizer_callback = self.find_sanitizer(sanitizer_name)
sanitizer_key = "%s.%s" % (table_name, column_name)
self.sanitizers[sanitizer_key] = sanitizer_callback | python | def load_sanitizers(self, config_data):
"""
Loads sanitizers possibly defined in the configuration under dictionary
called "strategy", which should contain mapping of database tables with
column names mapped into sanitizer function names.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any]
"""
section_strategy = config_data.get("strategy")
if not isinstance(section_strategy, dict):
if section_strategy is None:
return
raise ConfigurationError(
"'strategy' is %s instead of dict" % (
type(section_strategy),
),
)
for table_name, column_data in six.iteritems(section_strategy):
if not isinstance(column_data, dict):
if column_data is None:
continue
raise ConfigurationError(
"'strategy.%s' is %s instead of dict" % (
table_name,
type(column_data),
),
)
for column_name, sanitizer_name in six.iteritems(column_data):
if sanitizer_name is None:
continue
if not isinstance(sanitizer_name, six.text_type):
raise ConfigurationError(
"'strategy.%s.%s' is %s instead of string" % (
table_name,
column_name,
type(sanitizer_name),
),
)
sanitizer_callback = self.find_sanitizer(sanitizer_name)
sanitizer_key = "%s.%s" % (table_name, column_name)
self.sanitizers[sanitizer_key] = sanitizer_callback | [
"def",
"load_sanitizers",
"(",
"self",
",",
"config_data",
")",
":",
"section_strategy",
"=",
"config_data",
".",
"get",
"(",
"\"strategy\"",
")",
"if",
"not",
"isinstance",
"(",
"section_strategy",
",",
"dict",
")",
":",
"if",
"section_strategy",
"is",
"None"... | Loads sanitizers possibly defined in the configuration under dictionary
called "strategy", which should contain mapping of database tables with
column names mapped into sanitizer function names.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any] | [
"Loads",
"sanitizers",
"possibly",
"defined",
"in",
"the",
"configuration",
"under",
"dictionary",
"called",
"strategy",
"which",
"should",
"contain",
"mapping",
"of",
"database",
"tables",
"with",
"column",
"names",
"mapped",
"into",
"sanitizer",
"function",
"names... | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/config.py#L106-L151 | train | 33,968 |
andersinno/python-database-sanitizer | database_sanitizer/config.py | Configuration.find_sanitizer | def find_sanitizer(self, name):
"""
Searches for a sanitizer function with given name. The name should
contain two parts separated from each other with a dot, the first
part being the module name while the second being name of the function
contained in the module, when it's being prefixed with "sanitize_".
The lookup process consists from three attempts, which are:
1. First package to look the module will be top level package called
"sanitizers".
2. Module will be looked under the "addon" packages, if they have been
defined.
3. Finally the sanitation function will be looked from the builtin
sanitizers located in "database_sanitizer.sanitizers" package.
If none of these provide any results, ConfigurationError will be
thrown.
:param name: "Full name" of the sanitation function containing name
of the module as well as name of the function.
:type name: str
:return: First function which can be imported with the given name.
:rtype: callable
"""
# Split the sanitizer name into two parts, one containing the Python
# module name, while second containing portion of the function name
# we are looking for.
name_parts = name.split(".")
if len(name_parts) < 2:
raise ConfigurationError(
"Unable to separate module name from function name in '%s'" % (
name,
),
)
module_name_suffix = ".".join(name_parts[:-1])
function_name = "sanitize_%s" % (name_parts[-1],)
# Phase 1: Look for custom sanitizer under a top level package called
# "sanitizers".
module_name = "sanitizers.%s" % (module_name_suffix,)
callback = self.find_sanitizer_from_module(
module_name=module_name,
function_name=function_name,
)
if callback:
return callback
# Phase 2: Look for the sanitizer under "addon" packages, if any of
# such have been defined.
for addon_package_name in self.addon_packages:
module_name = "%s.%s" % (
addon_package_name,
module_name_suffix,
)
callback = self.find_sanitizer_from_module(
module_name=module_name,
function_name=function_name,
)
if callback:
return callback
# Phase 3: Look from builtin sanitizers.
module_name = "database_sanitizer.sanitizers.%s" % (module_name_suffix,)
callback = self.find_sanitizer_from_module(
module_name=module_name,
function_name=function_name,
)
if callback:
return callback
# Give up.
raise ConfigurationError("Unable to find sanitizer called '%s'" % (
name,
)) | python | def find_sanitizer(self, name):
"""
Searches for a sanitizer function with given name. The name should
contain two parts separated from each other with a dot, the first
part being the module name while the second being name of the function
contained in the module, when it's being prefixed with "sanitize_".
The lookup process consists from three attempts, which are:
1. First package to look the module will be top level package called
"sanitizers".
2. Module will be looked under the "addon" packages, if they have been
defined.
3. Finally the sanitation function will be looked from the builtin
sanitizers located in "database_sanitizer.sanitizers" package.
If none of these provide any results, ConfigurationError will be
thrown.
:param name: "Full name" of the sanitation function containing name
of the module as well as name of the function.
:type name: str
:return: First function which can be imported with the given name.
:rtype: callable
"""
# Split the sanitizer name into two parts, one containing the Python
# module name, while second containing portion of the function name
# we are looking for.
name_parts = name.split(".")
if len(name_parts) < 2:
raise ConfigurationError(
"Unable to separate module name from function name in '%s'" % (
name,
),
)
module_name_suffix = ".".join(name_parts[:-1])
function_name = "sanitize_%s" % (name_parts[-1],)
# Phase 1: Look for custom sanitizer under a top level package called
# "sanitizers".
module_name = "sanitizers.%s" % (module_name_suffix,)
callback = self.find_sanitizer_from_module(
module_name=module_name,
function_name=function_name,
)
if callback:
return callback
# Phase 2: Look for the sanitizer under "addon" packages, if any of
# such have been defined.
for addon_package_name in self.addon_packages:
module_name = "%s.%s" % (
addon_package_name,
module_name_suffix,
)
callback = self.find_sanitizer_from_module(
module_name=module_name,
function_name=function_name,
)
if callback:
return callback
# Phase 3: Look from builtin sanitizers.
module_name = "database_sanitizer.sanitizers.%s" % (module_name_suffix,)
callback = self.find_sanitizer_from_module(
module_name=module_name,
function_name=function_name,
)
if callback:
return callback
# Give up.
raise ConfigurationError("Unable to find sanitizer called '%s'" % (
name,
)) | [
"def",
"find_sanitizer",
"(",
"self",
",",
"name",
")",
":",
"# Split the sanitizer name into two parts, one containing the Python",
"# module name, while second containing portion of the function name",
"# we are looking for.",
"name_parts",
"=",
"name",
".",
"split",
"(",
"\".\""... | Searches for a sanitizer function with given name. The name should
contain two parts separated from each other with a dot, the first
part being the module name while the second being name of the function
contained in the module, when it's being prefixed with "sanitize_".
The lookup process consists from three attempts, which are:
1. First package to look the module will be top level package called
"sanitizers".
2. Module will be looked under the "addon" packages, if they have been
defined.
3. Finally the sanitation function will be looked from the builtin
sanitizers located in "database_sanitizer.sanitizers" package.
If none of these provide any results, ConfigurationError will be
thrown.
:param name: "Full name" of the sanitation function containing name
of the module as well as name of the function.
:type name: str
:return: First function which can be imported with the given name.
:rtype: callable | [
"Searches",
"for",
"a",
"sanitizer",
"function",
"with",
"given",
"name",
".",
"The",
"name",
"should",
"contain",
"two",
"parts",
"separated",
"from",
"each",
"other",
"with",
"a",
"dot",
"the",
"first",
"part",
"being",
"the",
"module",
"name",
"while",
... | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/config.py#L153-L229 | train | 33,969 |
andersinno/python-database-sanitizer | database_sanitizer/config.py | Configuration.find_sanitizer_from_module | def find_sanitizer_from_module(module_name, function_name):
"""
Attempts to find sanitizer function from given module. If the module
cannot be imported, or function with given name does not exist in it,
nothing will be returned by this method. Otherwise the found sanitizer
function will be returned.
:param module_name: Name of the module to import the function from.
:type module_name: str
:param function_name: Name of the function to look for inside the
module.
:type function_name: str
:return: Sanitizer function found from the module, if it can be
imported and it indeed contains function with the given name.
Otherwise None will be returned instead.
:rtype: callback|None
"""
try:
module = importlib.import_module(module_name)
except ImportError:
return None
# Look for the function inside the module. At this point it could be
# pretty much anything.
callback = getattr(module, function_name, None)
# Function does not exist in this module? Give up.
if callback is None:
return None
# It's actually callable function? Return it.
if callable(callback):
return callback
# Sanitizer seems to be something else than a function. Throw an
# exception to report such problem.
raise ConfigurationError("'%s' in '%s' is %s instead of function" % (
function_name,
module_name,
type(callback),
)) | python | def find_sanitizer_from_module(module_name, function_name):
"""
Attempts to find sanitizer function from given module. If the module
cannot be imported, or function with given name does not exist in it,
nothing will be returned by this method. Otherwise the found sanitizer
function will be returned.
:param module_name: Name of the module to import the function from.
:type module_name: str
:param function_name: Name of the function to look for inside the
module.
:type function_name: str
:return: Sanitizer function found from the module, if it can be
imported and it indeed contains function with the given name.
Otherwise None will be returned instead.
:rtype: callback|None
"""
try:
module = importlib.import_module(module_name)
except ImportError:
return None
# Look for the function inside the module. At this point it could be
# pretty much anything.
callback = getattr(module, function_name, None)
# Function does not exist in this module? Give up.
if callback is None:
return None
# It's actually callable function? Return it.
if callable(callback):
return callback
# Sanitizer seems to be something else than a function. Throw an
# exception to report such problem.
raise ConfigurationError("'%s' in '%s' is %s instead of function" % (
function_name,
module_name,
type(callback),
)) | [
"def",
"find_sanitizer_from_module",
"(",
"module_name",
",",
"function_name",
")",
":",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"except",
"ImportError",
":",
"return",
"None",
"# Look for the function inside the module. At... | Attempts to find sanitizer function from given module. If the module
cannot be imported, or function with given name does not exist in it,
nothing will be returned by this method. Otherwise the found sanitizer
function will be returned.
:param module_name: Name of the module to import the function from.
:type module_name: str
:param function_name: Name of the function to look for inside the
module.
:type function_name: str
:return: Sanitizer function found from the module, if it can be
imported and it indeed contains function with the given name.
Otherwise None will be returned instead.
:rtype: callback|None | [
"Attempts",
"to",
"find",
"sanitizer",
"function",
"from",
"given",
"module",
".",
"If",
"the",
"module",
"cannot",
"be",
"imported",
"or",
"function",
"with",
"given",
"name",
"does",
"not",
"exist",
"in",
"it",
"nothing",
"will",
"be",
"returned",
"by",
... | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/config.py#L232-L274 | train | 33,970 |
andersinno/python-database-sanitizer | database_sanitizer/config.py | Configuration.get_sanitizer_for | def get_sanitizer_for(self, table_name, column_name):
"""
Get sanitizer for given table and column name.
:param table_name: Name of the database table.
:type table_name: str
:param column_name: Name of the database column.
:type column_name: str
:return: Sanitizer function or None if nothing is configured
:rtype: Optional[Callable[[Optional[str]], Optional[str]]]
"""
sanitizer_key = "%s.%s" % (table_name, column_name)
return self.sanitizers.get(sanitizer_key) | python | def get_sanitizer_for(self, table_name, column_name):
"""
Get sanitizer for given table and column name.
:param table_name: Name of the database table.
:type table_name: str
:param column_name: Name of the database column.
:type column_name: str
:return: Sanitizer function or None if nothing is configured
:rtype: Optional[Callable[[Optional[str]], Optional[str]]]
"""
sanitizer_key = "%s.%s" % (table_name, column_name)
return self.sanitizers.get(sanitizer_key) | [
"def",
"get_sanitizer_for",
"(",
"self",
",",
"table_name",
",",
"column_name",
")",
":",
"sanitizer_key",
"=",
"\"%s.%s\"",
"%",
"(",
"table_name",
",",
"column_name",
")",
"return",
"self",
".",
"sanitizers",
".",
"get",
"(",
"sanitizer_key",
")"
] | Get sanitizer for given table and column name.
:param table_name: Name of the database table.
:type table_name: str
:param column_name: Name of the database column.
:type column_name: str
:return: Sanitizer function or None if nothing is configured
:rtype: Optional[Callable[[Optional[str]], Optional[str]]] | [
"Get",
"sanitizer",
"for",
"given",
"table",
"and",
"column",
"name",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/config.py#L276-L290 | train | 33,971 |
andersinno/python-database-sanitizer | database_sanitizer/config.py | Configuration.sanitize | def sanitize(self, table_name, column_name, value):
"""
Sanitizes given value extracted from the database according to the
sanitation configuration.
TODO: Add support for dates, booleans and other types found in SQL than
string.
:param table_name: Name of the database table from which the value is
from.
:type table_name: str
:param column_name: Name of the database column from which the value is
from.
:type column_name: str
:param value: Value from the database, either in text form or None if
the value is null.
:type value: str|None
:return: Sanitized version of the given value.
:rtype: str|None
"""
sanitizer_callback = self.get_sanitizer_for(table_name, column_name)
return sanitizer_callback(value) if sanitizer_callback else value | python | def sanitize(self, table_name, column_name, value):
"""
Sanitizes given value extracted from the database according to the
sanitation configuration.
TODO: Add support for dates, booleans and other types found in SQL than
string.
:param table_name: Name of the database table from which the value is
from.
:type table_name: str
:param column_name: Name of the database column from which the value is
from.
:type column_name: str
:param value: Value from the database, either in text form or None if
the value is null.
:type value: str|None
:return: Sanitized version of the given value.
:rtype: str|None
"""
sanitizer_callback = self.get_sanitizer_for(table_name, column_name)
return sanitizer_callback(value) if sanitizer_callback else value | [
"def",
"sanitize",
"(",
"self",
",",
"table_name",
",",
"column_name",
",",
"value",
")",
":",
"sanitizer_callback",
"=",
"self",
".",
"get_sanitizer_for",
"(",
"table_name",
",",
"column_name",
")",
"return",
"sanitizer_callback",
"(",
"value",
")",
"if",
"sa... | Sanitizes given value extracted from the database according to the
sanitation configuration.
TODO: Add support for dates, booleans and other types found in SQL than
string.
:param table_name: Name of the database table from which the value is
from.
:type table_name: str
:param column_name: Name of the database column from which the value is
from.
:type column_name: str
:param value: Value from the database, either in text form or None if
the value is null.
:type value: str|None
:return: Sanitized version of the given value.
:rtype: str|None | [
"Sanitizes",
"given",
"value",
"extracted",
"from",
"the",
"database",
"according",
"to",
"the",
"sanitation",
"configuration",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/config.py#L292-L316 | train | 33,972 |
safarijv/sbo-selenium | sbo_selenium/management/commands/selenium.py | Command.add_arguments | def add_arguments(self, parser):
"""Command line arguments for Django 1.8+"""
# Add the underlying test command arguments first
test_command = TestCommand()
test_command.add_arguments(parser)
for option in OPTIONS:
parser.add_argument(*option[0], **option[1]) | python | def add_arguments(self, parser):
"""Command line arguments for Django 1.8+"""
# Add the underlying test command arguments first
test_command = TestCommand()
test_command.add_arguments(parser)
for option in OPTIONS:
parser.add_argument(*option[0], **option[1]) | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"# Add the underlying test command arguments first",
"test_command",
"=",
"TestCommand",
"(",
")",
"test_command",
".",
"add_arguments",
"(",
"parser",
")",
"for",
"option",
"in",
"OPTIONS",
":",
"parser"... | Command line arguments for Django 1.8+ | [
"Command",
"line",
"arguments",
"for",
"Django",
"1",
".",
"8",
"+"
] | 16539f1b17cda18270033db3b64ab25bc05c5664 | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/management/commands/selenium.py#L47-L54 | train | 33,973 |
safarijv/sbo-selenium | sbo_selenium/management/commands/selenium.py | Command.clean | def clean():
"""Clear out any old screenshots"""
screenshot_dir = settings.SELENIUM_SCREENSHOT_DIR
if screenshot_dir and os.path.isdir(screenshot_dir):
rmtree(screenshot_dir, ignore_errors=True) | python | def clean():
"""Clear out any old screenshots"""
screenshot_dir = settings.SELENIUM_SCREENSHOT_DIR
if screenshot_dir and os.path.isdir(screenshot_dir):
rmtree(screenshot_dir, ignore_errors=True) | [
"def",
"clean",
"(",
")",
":",
"screenshot_dir",
"=",
"settings",
".",
"SELENIUM_SCREENSHOT_DIR",
"if",
"screenshot_dir",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"screenshot_dir",
")",
":",
"rmtree",
"(",
"screenshot_dir",
",",
"ignore_errors",
"=",
"True... | Clear out any old screenshots | [
"Clear",
"out",
"any",
"old",
"screenshots"
] | 16539f1b17cda18270033db3b64ab25bc05c5664 | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/management/commands/selenium.py#L67-L71 | train | 33,974 |
safarijv/sbo-selenium | sbo_selenium/management/commands/selenium.py | Command.verify_appium_is_running | def verify_appium_is_running(self):
"""Verify that Appium is running so it can be used for local iOS tests."""
process = Popen(['ps -e | grep "Appium"'], shell=True, stdout=PIPE)
(grep_output, _grep_error) = process.communicate()
lines = grep_output.split('\n')
for line in lines:
if 'Appium.app' in line:
self.stdout.write('Appium is already running')
return True
self.stdout.write('Please launch and configure Appium first')
return False | python | def verify_appium_is_running(self):
"""Verify that Appium is running so it can be used for local iOS tests."""
process = Popen(['ps -e | grep "Appium"'], shell=True, stdout=PIPE)
(grep_output, _grep_error) = process.communicate()
lines = grep_output.split('\n')
for line in lines:
if 'Appium.app' in line:
self.stdout.write('Appium is already running')
return True
self.stdout.write('Please launch and configure Appium first')
return False | [
"def",
"verify_appium_is_running",
"(",
"self",
")",
":",
"process",
"=",
"Popen",
"(",
"[",
"'ps -e | grep \"Appium\"'",
"]",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"PIPE",
")",
"(",
"grep_output",
",",
"_grep_error",
")",
"=",
"process",
".",
"co... | Verify that Appium is running so it can be used for local iOS tests. | [
"Verify",
"that",
"Appium",
"is",
"running",
"so",
"it",
"can",
"be",
"used",
"for",
"local",
"iOS",
"tests",
"."
] | 16539f1b17cda18270033db3b64ab25bc05c5664 | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/management/commands/selenium.py#L279-L289 | train | 33,975 |
fridiculous/estimators | estimators/hashing.py | NumpyHasher.save | def save(self, obj):
""" Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class.
"""
if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
# Compute a hash of the object
# The update function of the hash requires a c_contiguous buffer.
if obj.shape == ():
# 0d arrays need to be flattened because viewing them as bytes
# raises a ValueError exception.
obj_c_contiguous = obj.flatten()
elif obj.flags.c_contiguous:
obj_c_contiguous = obj
elif obj.flags.f_contiguous:
obj_c_contiguous = obj.T
else:
# Cater for non-single-segment arrays: this creates a
# copy, and thus aleviates this issue.
# XXX: There might be a more efficient way of doing this
obj_c_contiguous = obj.flatten()
# memoryview is not supported for some dtypes, e.g. datetime64, see
# https://github.com/numpy/numpy/issues/4983. The
# workaround is to view the array as bytes before
# taking the memoryview.
self._hash.update(
self._getbuffer(obj_c_contiguous.view(self.np.uint8)))
# We store the class, to be able to distinguish between
# Objects with the same binary content, but different
# classes.
if self.coerce_mmap and isinstance(obj, self.np.memmap):
# We don't make the difference between memmap and
# normal ndarrays, to be able to reload previously
# computed results with memmap.
klass = self.np.ndarray
else:
klass = obj.__class__
# We also return the dtype and the shape, to distinguish
# different views on the same data with different dtypes.
# The object will be pickled by the pickler hashed at the end.
obj = (klass, ('HASHED', obj.dtype, obj.shape, obj.strides))
elif isinstance(obj, self.np.dtype):
# Atomic dtype objects are interned by their default constructor:
# np.dtype('f8') is np.dtype('f8')
# This interning is not maintained by a
# pickle.loads + pickle.dumps cycle, because __reduce__
# uses copy=True in the dtype constructor. This
# non-deterministic behavior causes the internal memoizer
# of the hasher to generate different hash values
# depending on the history of the dtype object.
# To prevent the hash from being sensitive to this, we use
# .descr which is a full (and never interned) description of
# the array dtype according to the numpy doc.
klass = obj.__class__
obj = (klass, ('HASHED', obj.descr))
Hasher.save(self, obj) | python | def save(self, obj):
""" Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class.
"""
if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
# Compute a hash of the object
# The update function of the hash requires a c_contiguous buffer.
if obj.shape == ():
# 0d arrays need to be flattened because viewing them as bytes
# raises a ValueError exception.
obj_c_contiguous = obj.flatten()
elif obj.flags.c_contiguous:
obj_c_contiguous = obj
elif obj.flags.f_contiguous:
obj_c_contiguous = obj.T
else:
# Cater for non-single-segment arrays: this creates a
# copy, and thus aleviates this issue.
# XXX: There might be a more efficient way of doing this
obj_c_contiguous = obj.flatten()
# memoryview is not supported for some dtypes, e.g. datetime64, see
# https://github.com/numpy/numpy/issues/4983. The
# workaround is to view the array as bytes before
# taking the memoryview.
self._hash.update(
self._getbuffer(obj_c_contiguous.view(self.np.uint8)))
# We store the class, to be able to distinguish between
# Objects with the same binary content, but different
# classes.
if self.coerce_mmap and isinstance(obj, self.np.memmap):
# We don't make the difference between memmap and
# normal ndarrays, to be able to reload previously
# computed results with memmap.
klass = self.np.ndarray
else:
klass = obj.__class__
# We also return the dtype and the shape, to distinguish
# different views on the same data with different dtypes.
# The object will be pickled by the pickler hashed at the end.
obj = (klass, ('HASHED', obj.dtype, obj.shape, obj.strides))
elif isinstance(obj, self.np.dtype):
# Atomic dtype objects are interned by their default constructor:
# np.dtype('f8') is np.dtype('f8')
# This interning is not maintained by a
# pickle.loads + pickle.dumps cycle, because __reduce__
# uses copy=True in the dtype constructor. This
# non-deterministic behavior causes the internal memoizer
# of the hasher to generate different hash values
# depending on the history of the dtype object.
# To prevent the hash from being sensitive to this, we use
# .descr which is a full (and never interned) description of
# the array dtype according to the numpy doc.
klass = obj.__class__
obj = (klass, ('HASHED', obj.descr))
Hasher.save(self, obj) | [
"def",
"save",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"self",
".",
"np",
".",
"ndarray",
")",
"and",
"not",
"obj",
".",
"dtype",
".",
"hasobject",
":",
"# Compute a hash of the object",
"# The update function of the hash requir... | Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class. | [
"Subclass",
"the",
"save",
"method",
"to",
"hash",
"ndarray",
"subclass",
"rather",
"than",
"pickling",
"them",
".",
"Off",
"course",
"this",
"is",
"a",
"total",
"abuse",
"of",
"the",
"Pickler",
"class",
"."
] | ab5b3d70f16f8372ae1114ac7e54e7791631eb74 | https://github.com/fridiculous/estimators/blob/ab5b3d70f16f8372ae1114ac7e54e7791631eb74/estimators/hashing.py#L209-L267 | train | 33,976 |
andersinno/python-database-sanitizer | database_sanitizer/sanitizers/string.py | sanitize_random | def sanitize_random(value):
"""
Random string of same length as the given value.
"""
if not value:
return value
return ''.join(random.choice(CHARACTERS) for _ in range(len(value))) | python | def sanitize_random(value):
"""
Random string of same length as the given value.
"""
if not value:
return value
return ''.join(random.choice(CHARACTERS) for _ in range(len(value))) | [
"def",
"sanitize_random",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"value",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"CHARACTERS",
")",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"value",
")",
")",
")"
] | Random string of same length as the given value. | [
"Random",
"string",
"of",
"same",
"length",
"as",
"the",
"given",
"value",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/sanitizers/string.py#L25-L31 | train | 33,977 |
andersinno/python-database-sanitizer | database_sanitizer/dump/mysql.py | sanitize | def sanitize(url, config):
"""
Obtains dump of MySQL database by executing `mysqldump` command and
sanitizes it output.
:param url: URL to the database which is going to be sanitized, parsed by
Python's URL parser.
:type url: urllib.urlparse.ParseResult
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None
"""
if url.scheme != "mysql":
raise ValueError("Unsupported database type: '%s'" % (url.scheme,))
args, env = get_mysqldump_args_and_env_from_url(url=url)
process = subprocess.Popen(
args=["mysqldump"] + args,
env=env,
stdout=subprocess.PIPE,
)
return sanitize_from_stream(stream=process.stdout, config=config) | python | def sanitize(url, config):
"""
Obtains dump of MySQL database by executing `mysqldump` command and
sanitizes it output.
:param url: URL to the database which is going to be sanitized, parsed by
Python's URL parser.
:type url: urllib.urlparse.ParseResult
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None
"""
if url.scheme != "mysql":
raise ValueError("Unsupported database type: '%s'" % (url.scheme,))
args, env = get_mysqldump_args_and_env_from_url(url=url)
process = subprocess.Popen(
args=["mysqldump"] + args,
env=env,
stdout=subprocess.PIPE,
)
return sanitize_from_stream(stream=process.stdout, config=config) | [
"def",
"sanitize",
"(",
"url",
",",
"config",
")",
":",
"if",
"url",
".",
"scheme",
"!=",
"\"mysql\"",
":",
"raise",
"ValueError",
"(",
"\"Unsupported database type: '%s'\"",
"%",
"(",
"url",
".",
"scheme",
",",
")",
")",
"args",
",",
"env",
"=",
"get_my... | Obtains dump of MySQL database by executing `mysqldump` command and
sanitizes it output.
:param url: URL to the database which is going to be sanitized, parsed by
Python's URL parser.
:type url: urllib.urlparse.ParseResult
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None | [
"Obtains",
"dump",
"of",
"MySQL",
"database",
"by",
"executing",
"mysqldump",
"command",
"and",
"sanitizes",
"it",
"output",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/dump/mysql.py#L42-L66 | train | 33,978 |
andersinno/python-database-sanitizer | database_sanitizer/dump/mysql.py | sanitize_from_stream | def sanitize_from_stream(stream, config):
"""
Reads dump of MySQL database from given stream and sanitizes it.
:param stream: Stream where the database dump is expected to be available
from, such as stdout of `mysqldump` process.
:type stream: file
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None
"""
for line in io.TextIOWrapper(stream, encoding="utf-8"):
# Eat the trailing new line.
line = line.rstrip("\n")
# If there is no configuration it means that there are no sanitizers
# available.
if not config:
yield line
continue
# Does the line contain `INSERT INTO` statement? If not, use the line
# as-is and continue into next one.
insert_into_match = INSERT_INTO_PATTERN.match(line)
if not insert_into_match:
yield line
continue
table_name = insert_into_match.group("table")
column_names = parse_column_names(insert_into_match.group("columns"))
# Collect sanitizers possibly used for this table and place them into
# a dictionary from which we can look them up by index later.
sanitizers = {}
for index, column_name in enumerate(column_names):
sanitizer = config.get_sanitizer_for(
table_name=table_name,
column_name=column_name,
)
if sanitizer:
sanitizers[index] = sanitizer
# If this table has no sanitizers available, use the line as-is and
# continue into next line.
if len(sanitizers) == 0:
yield line
continue
# Constructs list of tuples containing sanitized column names.
sanitized_value_tuples = []
for values in parse_values(insert_into_match.group("values")):
if len(column_names) != len(values):
raise ValueError("Mismatch between column names and values")
sanitized_values = []
for index, value in enumerate(values):
sanitizer_callback = sanitizers.get(index)
if sanitizer_callback:
value = sanitizer_callback(value)
sanitized_values.append(encode_mysql_literal(value))
sanitized_value_tuples.append(sanitized_values)
# Finally create new `INSERT INTO` statement from the sanitized values.
yield "INSERT INTO `%s` (%s) VALUES %s;" % (
table_name,
", ".join("`" + column_name + "`" for column_name in column_names),
",".join(
"(" + ",".join(value_tuple) + ")"
for value_tuple in sanitized_value_tuples
),
) | python | def sanitize_from_stream(stream, config):
"""
Reads dump of MySQL database from given stream and sanitizes it.
:param stream: Stream where the database dump is expected to be available
from, such as stdout of `mysqldump` process.
:type stream: file
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None
"""
for line in io.TextIOWrapper(stream, encoding="utf-8"):
# Eat the trailing new line.
line = line.rstrip("\n")
# If there is no configuration it means that there are no sanitizers
# available.
if not config:
yield line
continue
# Does the line contain `INSERT INTO` statement? If not, use the line
# as-is and continue into next one.
insert_into_match = INSERT_INTO_PATTERN.match(line)
if not insert_into_match:
yield line
continue
table_name = insert_into_match.group("table")
column_names = parse_column_names(insert_into_match.group("columns"))
# Collect sanitizers possibly used for this table and place them into
# a dictionary from which we can look them up by index later.
sanitizers = {}
for index, column_name in enumerate(column_names):
sanitizer = config.get_sanitizer_for(
table_name=table_name,
column_name=column_name,
)
if sanitizer:
sanitizers[index] = sanitizer
# If this table has no sanitizers available, use the line as-is and
# continue into next line.
if len(sanitizers) == 0:
yield line
continue
# Constructs list of tuples containing sanitized column names.
sanitized_value_tuples = []
for values in parse_values(insert_into_match.group("values")):
if len(column_names) != len(values):
raise ValueError("Mismatch between column names and values")
sanitized_values = []
for index, value in enumerate(values):
sanitizer_callback = sanitizers.get(index)
if sanitizer_callback:
value = sanitizer_callback(value)
sanitized_values.append(encode_mysql_literal(value))
sanitized_value_tuples.append(sanitized_values)
# Finally create new `INSERT INTO` statement from the sanitized values.
yield "INSERT INTO `%s` (%s) VALUES %s;" % (
table_name,
", ".join("`" + column_name + "`" for column_name in column_names),
",".join(
"(" + ",".join(value_tuple) + ")"
for value_tuple in sanitized_value_tuples
),
) | [
"def",
"sanitize_from_stream",
"(",
"stream",
",",
"config",
")",
":",
"for",
"line",
"in",
"io",
".",
"TextIOWrapper",
"(",
"stream",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"# Eat the trailing new line.",
"line",
"=",
"line",
".",
"rstrip",
"(",
"\"\\... | Reads dump of MySQL database from given stream and sanitizes it.
:param stream: Stream where the database dump is expected to be available
from, such as stdout of `mysqldump` process.
:type stream: file
:param config: Optional sanitizer configuration to be used for sanitation
of the values stored in the database.
:type config: database_sanitizer.config.Configuration|None | [
"Reads",
"dump",
"of",
"MySQL",
"database",
"from",
"given",
"stream",
"and",
"sanitizes",
"it",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/dump/mysql.py#L69-L139 | train | 33,979 |
andersinno/python-database-sanitizer | database_sanitizer/dump/mysql.py | parse_column_names | def parse_column_names(text):
"""
Extracts column names from a string containing quoted and comma separated
column names of a table.
:param text: Line extracted from MySQL's `INSERT INTO` statement containing
quoted and comma separated column names.
:type text: str
:return: Tuple containing just the column names.
:rtype: tuple[str]
"""
return tuple(
re.sub(r"^`(.*)`$", r"\1", column_data.strip())
for column_data in text.split(",")
) | python | def parse_column_names(text):
"""
Extracts column names from a string containing quoted and comma separated
column names of a table.
:param text: Line extracted from MySQL's `INSERT INTO` statement containing
quoted and comma separated column names.
:type text: str
:return: Tuple containing just the column names.
:rtype: tuple[str]
"""
return tuple(
re.sub(r"^`(.*)`$", r"\1", column_data.strip())
for column_data in text.split(",")
) | [
"def",
"parse_column_names",
"(",
"text",
")",
":",
"return",
"tuple",
"(",
"re",
".",
"sub",
"(",
"r\"^`(.*)`$\"",
",",
"r\"\\1\"",
",",
"column_data",
".",
"strip",
"(",
")",
")",
"for",
"column_data",
"in",
"text",
".",
"split",
"(",
"\",\"",
")",
"... | Extracts column names from a string containing quoted and comma separated
column names of a table.
:param text: Line extracted from MySQL's `INSERT INTO` statement containing
quoted and comma separated column names.
:type text: str
:return: Tuple containing just the column names.
:rtype: tuple[str] | [
"Extracts",
"column",
"names",
"from",
"a",
"string",
"containing",
"quoted",
"and",
"comma",
"separated",
"column",
"names",
"of",
"a",
"table",
"."
] | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/dump/mysql.py#L142-L157 | train | 33,980 |
andersinno/python-database-sanitizer | database_sanitizer/dump/mysql.py | parse_values | def parse_values(text):
"""
Parses values from a string containing values from extended format `INSERT
INTO` statement. Values will be yielded from the function as tuples, with
one tuple per row in the table.
:param text: Text extracted from MySQL's `INSERT INTO` statement containing
quoted and comma separated column values.
:type text: str
"""
assert text.startswith("(")
pos = 1
values = []
text_len = len(text)
while pos < text_len:
match = VALUE_PATTERN.match(text, pos)
if not match:
break
value = match.group(1)
values.append(decode_mysql_literal(value.strip()))
pos += len(value) + 1
if match.group(2) == ")":
# Skip comma and open parenthesis ",("
pos += 2
yield tuple(values)
values = [] | python | def parse_values(text):
"""
Parses values from a string containing values from extended format `INSERT
INTO` statement. Values will be yielded from the function as tuples, with
one tuple per row in the table.
:param text: Text extracted from MySQL's `INSERT INTO` statement containing
quoted and comma separated column values.
:type text: str
"""
assert text.startswith("(")
pos = 1
values = []
text_len = len(text)
while pos < text_len:
match = VALUE_PATTERN.match(text, pos)
if not match:
break
value = match.group(1)
values.append(decode_mysql_literal(value.strip()))
pos += len(value) + 1
if match.group(2) == ")":
# Skip comma and open parenthesis ",("
pos += 2
yield tuple(values)
values = [] | [
"def",
"parse_values",
"(",
"text",
")",
":",
"assert",
"text",
".",
"startswith",
"(",
"\"(\"",
")",
"pos",
"=",
"1",
"values",
"=",
"[",
"]",
"text_len",
"=",
"len",
"(",
"text",
")",
"while",
"pos",
"<",
"text_len",
":",
"match",
"=",
"VALUE_PATTE... | Parses values from a string containing values from extended format `INSERT
INTO` statement. Values will be yielded from the function as tuples, with
one tuple per row in the table.
:param text: Text extracted from MySQL's `INSERT INTO` statement containing
quoted and comma separated column values.
:type text: str | [
"Parses",
"values",
"from",
"a",
"string",
"containing",
"values",
"from",
"extended",
"format",
"INSERT",
"INTO",
"statement",
".",
"Values",
"will",
"be",
"yielded",
"from",
"the",
"function",
"as",
"tuples",
"with",
"one",
"tuple",
"per",
"row",
"in",
"th... | 742bc1f43526b60f322a48f18c900f94fd446ed4 | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/dump/mysql.py#L160-L185 | train | 33,981 |
fridiculous/estimators | estimators/database.py | HashableFileMixin.persist | def persist(self):
"""a private method that persists an object to the filesystem"""
if self.hash:
with open(self.file_name, 'wb') as f:
pickle.dump(self.object_property, f)
return True
return False | python | def persist(self):
"""a private method that persists an object to the filesystem"""
if self.hash:
with open(self.file_name, 'wb') as f:
pickle.dump(self.object_property, f)
return True
return False | [
"def",
"persist",
"(",
"self",
")",
":",
"if",
"self",
".",
"hash",
":",
"with",
"open",
"(",
"self",
".",
"file_name",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"self",
".",
"object_property",
",",
"f",
")",
"return",
"True",
... | a private method that persists an object to the filesystem | [
"a",
"private",
"method",
"that",
"persists",
"an",
"object",
"to",
"the",
"filesystem"
] | ab5b3d70f16f8372ae1114ac7e54e7791631eb74 | https://github.com/fridiculous/estimators/blob/ab5b3d70f16f8372ae1114ac7e54e7791631eb74/estimators/database.py#L121-L127 | train | 33,982 |
fridiculous/estimators | estimators/database.py | HashableFileMixin.load | def load(self):
"""a private method that loads an object from the filesystem"""
if self.is_persisted:
with open(self.file_name, 'rb') as f:
self.object_property = pickle.load(f) | python | def load(self):
"""a private method that loads an object from the filesystem"""
if self.is_persisted:
with open(self.file_name, 'rb') as f:
self.object_property = pickle.load(f) | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_persisted",
":",
"with",
"open",
"(",
"self",
".",
"file_name",
",",
"'rb'",
")",
"as",
"f",
":",
"self",
".",
"object_property",
"=",
"pickle",
".",
"load",
"(",
"f",
")"
] | a private method that loads an object from the filesystem | [
"a",
"private",
"method",
"that",
"loads",
"an",
"object",
"from",
"the",
"filesystem"
] | ab5b3d70f16f8372ae1114ac7e54e7791631eb74 | https://github.com/fridiculous/estimators/blob/ab5b3d70f16f8372ae1114ac7e54e7791631eb74/estimators/database.py#L129-L133 | train | 33,983 |
lionheart/django-pyodbc | django_pyodbc/operations.py | DatabaseOperations._switch_tz_offset_sql | def _switch_tz_offset_sql(self, field_name, tzname):
"""
Returns the SQL that will convert field_name to UTC from tzname.
"""
field_name = self.quote_name(field_name)
if settings.USE_TZ:
if pytz is None:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("This query requires pytz, "
"but it isn't installed.")
tz = pytz.timezone(tzname)
td = tz.utcoffset(datetime.datetime(2000, 1, 1))
def total_seconds(td):
if hasattr(td, 'total_seconds'):
return td.total_seconds()
else:
return td.days * 24 * 60 * 60 + td.seconds
total_minutes = total_seconds(td) // 60
hours, minutes = divmod(total_minutes, 60)
tzoffset = "%+03d:%02d" % (hours, minutes)
field_name = "CAST(SWITCHOFFSET(TODATETIMEOFFSET(%s, '+00:00'), '%s') AS DATETIME2)" % (field_name, tzoffset)
return field_name | python | def _switch_tz_offset_sql(self, field_name, tzname):
"""
Returns the SQL that will convert field_name to UTC from tzname.
"""
field_name = self.quote_name(field_name)
if settings.USE_TZ:
if pytz is None:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("This query requires pytz, "
"but it isn't installed.")
tz = pytz.timezone(tzname)
td = tz.utcoffset(datetime.datetime(2000, 1, 1))
def total_seconds(td):
if hasattr(td, 'total_seconds'):
return td.total_seconds()
else:
return td.days * 24 * 60 * 60 + td.seconds
total_minutes = total_seconds(td) // 60
hours, minutes = divmod(total_minutes, 60)
tzoffset = "%+03d:%02d" % (hours, minutes)
field_name = "CAST(SWITCHOFFSET(TODATETIMEOFFSET(%s, '+00:00'), '%s') AS DATETIME2)" % (field_name, tzoffset)
return field_name | [
"def",
"_switch_tz_offset_sql",
"(",
"self",
",",
"field_name",
",",
"tzname",
")",
":",
"field_name",
"=",
"self",
".",
"quote_name",
"(",
"field_name",
")",
"if",
"settings",
".",
"USE_TZ",
":",
"if",
"pytz",
"is",
"None",
":",
"from",
"django",
".",
"... | Returns the SQL that will convert field_name to UTC from tzname. | [
"Returns",
"the",
"SQL",
"that",
"will",
"convert",
"field_name",
"to",
"UTC",
"from",
"tzname",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L171-L194 | train | 33,984 |
lionheart/django-pyodbc | django_pyodbc/operations.py | DatabaseOperations.datetime_trunc_sql | def datetime_trunc_sql(self, lookup_type, field_name, tzname):
"""
Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or
'second', returns the SQL that truncates the given datetime field
field_name to a datetime object with only the given specificity, and
a tuple of parameters.
"""
field_name = self._switch_tz_offset_sql(field_name, tzname)
reference_date = '0' # 1900-01-01
if lookup_type in ['minute', 'second']:
# Prevent DATEDIFF overflow by using the first day of the year as
# the reference point. Only using for minute and second to avoid any
# potential performance hit for queries against very large datasets.
reference_date = "CONVERT(datetime2, CONVERT(char(4), {field_name}, 112) + '0101', 112)".format(
field_name=field_name,
)
sql = "DATEADD({lookup}, DATEDIFF({lookup}, {reference_date}, {field_name}), {reference_date})".format(
lookup=lookup_type,
field_name=field_name,
reference_date=reference_date,
)
return sql, [] | python | def datetime_trunc_sql(self, lookup_type, field_name, tzname):
"""
Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or
'second', returns the SQL that truncates the given datetime field
field_name to a datetime object with only the given specificity, and
a tuple of parameters.
"""
field_name = self._switch_tz_offset_sql(field_name, tzname)
reference_date = '0' # 1900-01-01
if lookup_type in ['minute', 'second']:
# Prevent DATEDIFF overflow by using the first day of the year as
# the reference point. Only using for minute and second to avoid any
# potential performance hit for queries against very large datasets.
reference_date = "CONVERT(datetime2, CONVERT(char(4), {field_name}, 112) + '0101', 112)".format(
field_name=field_name,
)
sql = "DATEADD({lookup}, DATEDIFF({lookup}, {reference_date}, {field_name}), {reference_date})".format(
lookup=lookup_type,
field_name=field_name,
reference_date=reference_date,
)
return sql, [] | [
"def",
"datetime_trunc_sql",
"(",
"self",
",",
"lookup_type",
",",
"field_name",
",",
"tzname",
")",
":",
"field_name",
"=",
"self",
".",
"_switch_tz_offset_sql",
"(",
"field_name",
",",
"tzname",
")",
"reference_date",
"=",
"'0'",
"# 1900-01-01",
"if",
"lookup_... | Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or
'second', returns the SQL that truncates the given datetime field
field_name to a datetime object with only the given specificity, and
a tuple of parameters. | [
"Given",
"a",
"lookup_type",
"of",
"year",
"month",
"day",
"hour",
"minute",
"or",
"second",
"returns",
"the",
"SQL",
"that",
"truncates",
"the",
"given",
"datetime",
"field",
"field_name",
"to",
"a",
"datetime",
"object",
"with",
"only",
"the",
"given",
"sp... | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L196-L217 | train | 33,985 |
lionheart/django-pyodbc | django_pyodbc/operations.py | DatabaseOperations.last_insert_id | def last_insert_id(self, cursor, table_name, pk_name):
"""
Given a cursor object that has just performed an INSERT statement into
a table that has an auto-incrementing ID, returns the newly created ID.
This method also receives the table name and the name of the primary-key
column.
"""
# TODO: Check how the `last_insert_id` is being used in the upper layers
# in context of multithreaded access, compare with other backends
# IDENT_CURRENT: http://msdn2.microsoft.com/en-us/library/ms175098.aspx
# SCOPE_IDENTITY: http://msdn2.microsoft.com/en-us/library/ms190315.aspx
# @@IDENTITY: http://msdn2.microsoft.com/en-us/library/ms187342.aspx
# IDENT_CURRENT is not limited by scope and session; it is limited to
# a specified table. IDENT_CURRENT returns the value generated for
# a specific table in any session and any scope.
# SCOPE_IDENTITY and @@IDENTITY return the last identity values that
# are generated in any table in the current session. However,
# SCOPE_IDENTITY returns values inserted only within the current scope;
# @@IDENTITY is not limited to a specific scope.
table_name = self.quote_name(table_name)
cursor.execute("SELECT CAST(IDENT_CURRENT(%s) as bigint)", [table_name])
return cursor.fetchone()[0] | python | def last_insert_id(self, cursor, table_name, pk_name):
"""
Given a cursor object that has just performed an INSERT statement into
a table that has an auto-incrementing ID, returns the newly created ID.
This method also receives the table name and the name of the primary-key
column.
"""
# TODO: Check how the `last_insert_id` is being used in the upper layers
# in context of multithreaded access, compare with other backends
# IDENT_CURRENT: http://msdn2.microsoft.com/en-us/library/ms175098.aspx
# SCOPE_IDENTITY: http://msdn2.microsoft.com/en-us/library/ms190315.aspx
# @@IDENTITY: http://msdn2.microsoft.com/en-us/library/ms187342.aspx
# IDENT_CURRENT is not limited by scope and session; it is limited to
# a specified table. IDENT_CURRENT returns the value generated for
# a specific table in any session and any scope.
# SCOPE_IDENTITY and @@IDENTITY return the last identity values that
# are generated in any table in the current session. However,
# SCOPE_IDENTITY returns values inserted only within the current scope;
# @@IDENTITY is not limited to a specific scope.
table_name = self.quote_name(table_name)
cursor.execute("SELECT CAST(IDENT_CURRENT(%s) as bigint)", [table_name])
return cursor.fetchone()[0] | [
"def",
"last_insert_id",
"(",
"self",
",",
"cursor",
",",
"table_name",
",",
"pk_name",
")",
":",
"# TODO: Check how the `last_insert_id` is being used in the upper layers",
"# in context of multithreaded access, compare with other backends",
"# IDENT_CURRENT: http://msdn2.microso... | Given a cursor object that has just performed an INSERT statement into
a table that has an auto-incrementing ID, returns the newly created ID.
This method also receives the table name and the name of the primary-key
column. | [
"Given",
"a",
"cursor",
"object",
"that",
"has",
"just",
"performed",
"an",
"INSERT",
"statement",
"into",
"a",
"table",
"that",
"has",
"an",
"auto",
"-",
"incrementing",
"ID",
"returns",
"the",
"newly",
"created",
"ID",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L240-L265 | train | 33,986 |
lionheart/django-pyodbc | django_pyodbc/operations.py | DatabaseOperations.quote_name | def quote_name(self, name):
"""
Returns a quoted version of the given table, index or column name. Does
not quote the given name if it's already been quoted.
"""
if name.startswith(self.left_sql_quote) and name.endswith(self.right_sql_quote):
return name # Quoting once is enough.
return '%s%s%s' % (self.left_sql_quote, name, self.right_sql_quote) | python | def quote_name(self, name):
"""
Returns a quoted version of the given table, index or column name. Does
not quote the given name if it's already been quoted.
"""
if name.startswith(self.left_sql_quote) and name.endswith(self.right_sql_quote):
return name # Quoting once is enough.
return '%s%s%s' % (self.left_sql_quote, name, self.right_sql_quote) | [
"def",
"quote_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"self",
".",
"left_sql_quote",
")",
"and",
"name",
".",
"endswith",
"(",
"self",
".",
"right_sql_quote",
")",
":",
"return",
"name",
"# Quoting once is enough.",
... | Returns a quoted version of the given table, index or column name. Does
not quote the given name if it's already been quoted. | [
"Returns",
"a",
"quoted",
"version",
"of",
"the",
"given",
"table",
"index",
"or",
"column",
"name",
".",
"Does",
"not",
"quote",
"the",
"given",
"name",
"if",
"it",
"s",
"already",
"been",
"quoted",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L283-L290 | train | 33,987 |
lionheart/django-pyodbc | django_pyodbc/operations.py | DatabaseOperations.last_executed_query | def last_executed_query(self, cursor, sql, params):
"""
Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by default, but this method
exists for database backends to provide a better implementation
according to their own quoting schemes.
"""
return super(DatabaseOperations, self).last_executed_query(cursor, cursor.last_sql, cursor.last_params) | python | def last_executed_query(self, cursor, sql, params):
"""
Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by default, but this method
exists for database backends to provide a better implementation
according to their own quoting schemes.
"""
return super(DatabaseOperations, self).last_executed_query(cursor, cursor.last_sql, cursor.last_params) | [
"def",
"last_executed_query",
"(",
"self",
",",
"cursor",
",",
"sql",
",",
"params",
")",
":",
"return",
"super",
"(",
"DatabaseOperations",
",",
"self",
")",
".",
"last_executed_query",
"(",
"cursor",
",",
"cursor",
".",
"last_sql",
",",
"cursor",
".",
"l... | Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by default, but this method
exists for database backends to provide a better implementation
according to their own quoting schemes. | [
"Returns",
"a",
"string",
"of",
"the",
"query",
"last",
"executed",
"by",
"the",
"given",
"cursor",
"with",
"placeholders",
"replaced",
"with",
"actual",
"values",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L298-L308 | train | 33,988 |
lionheart/django-pyodbc | django_pyodbc/operations.py | DatabaseOperations.adapt_datetimefield_value | def adapt_datetimefield_value(self, value):
"""
Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.
"""
if value is None:
return None
if self.connection._DJANGO_VERSION >= 14 and settings.USE_TZ:
if timezone.is_aware(value):
# pyodbc donesn't support datetimeoffset
value = value.astimezone(timezone.utc)
if not self.connection.features.supports_microsecond_precision:
value = value.replace(microsecond=0)
return value | python | def adapt_datetimefield_value(self, value):
"""
Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.
"""
if value is None:
return None
if self.connection._DJANGO_VERSION >= 14 and settings.USE_TZ:
if timezone.is_aware(value):
# pyodbc donesn't support datetimeoffset
value = value.astimezone(timezone.utc)
if not self.connection.features.supports_microsecond_precision:
value = value.replace(microsecond=0)
return value | [
"def",
"adapt_datetimefield_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"connection",
".",
"_DJANGO_VERSION",
">=",
"14",
"and",
"settings",
".",
"USE_TZ",
":",
"if",
"timezone",
".",
... | Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns. | [
"Transform",
"a",
"datetime",
"value",
"to",
"an",
"object",
"compatible",
"with",
"what",
"is",
"expected",
"by",
"the",
"backend",
"driver",
"for",
"datetime",
"columns",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L431-L444 | train | 33,989 |
lionheart/django-pyodbc | django_pyodbc/operations.py | DatabaseOperations.adapt_timefield_value | def adapt_timefield_value(self, value):
"""
Transform a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
# SQL Server doesn't support microseconds
if isinstance(value, string_types):
return datetime.datetime(*(time.strptime(value, '%H:%M:%S')[:6]))
return datetime.datetime(1900, 1, 1, value.hour, value.minute, value.second) | python | def adapt_timefield_value(self, value):
"""
Transform a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
# SQL Server doesn't support microseconds
if isinstance(value, string_types):
return datetime.datetime(*(time.strptime(value, '%H:%M:%S')[:6]))
return datetime.datetime(1900, 1, 1, value.hour, value.minute, value.second) | [
"def",
"adapt_timefield_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"# SQL Server doesn't support microseconds",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"datetime",
".",
"dat... | Transform a time value to an object compatible with what is expected
by the backend driver for time columns. | [
"Transform",
"a",
"time",
"value",
"to",
"an",
"object",
"compatible",
"with",
"what",
"is",
"expected",
"by",
"the",
"backend",
"driver",
"for",
"time",
"columns",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L446-L456 | train | 33,990 |
lionheart/django-pyodbc | django_pyodbc/operations.py | DatabaseOperations.convert_values | def convert_values(self, value, field):
"""
Coerce the value returned by the database backend into a consistent
type that is compatible with the field type.
In our case, cater for the fact that SQL Server < 2008 has no
separate Date and Time data types.
TODO: See how we'll handle this for SQL Server >= 2008
"""
if value is None:
return None
if field and field.get_internal_type() == 'DateTimeField':
if isinstance(value, string_types) and value:
value = parse_datetime(value)
return value
elif field and field.get_internal_type() == 'DateField':
if isinstance(value, datetime.datetime):
value = value.date() # extract date
elif isinstance(value, string_types):
value = parse_date(value)
elif field and field.get_internal_type() == 'TimeField':
if (isinstance(value, datetime.datetime) and value.year == 1900 and value.month == value.day == 1):
value = value.time() # extract time
elif isinstance(value, string_types):
# If the value is a string, parse it using parse_time.
value = parse_time(value)
# Some cases (for example when select_related() is used) aren't
# caught by the DateField case above and date fields arrive from
# the DB as datetime instances.
# Implement a workaround stealing the idea from the Oracle
# backend. It's not perfect so the same warning applies (i.e. if a
# query results in valid date+time values with the time part set
# to midnight, this workaround can surprise us by converting them
# to the datetime.date Python type).
elif isinstance(value, datetime.datetime) and value.hour == value.minute == value.second == value.microsecond == 0:
value = value.date()
# Force floats to the correct type
elif value is not None and field and field.get_internal_type() == 'FloatField':
value = float(value)
return value | python | def convert_values(self, value, field):
"""
Coerce the value returned by the database backend into a consistent
type that is compatible with the field type.
In our case, cater for the fact that SQL Server < 2008 has no
separate Date and Time data types.
TODO: See how we'll handle this for SQL Server >= 2008
"""
if value is None:
return None
if field and field.get_internal_type() == 'DateTimeField':
if isinstance(value, string_types) and value:
value = parse_datetime(value)
return value
elif field and field.get_internal_type() == 'DateField':
if isinstance(value, datetime.datetime):
value = value.date() # extract date
elif isinstance(value, string_types):
value = parse_date(value)
elif field and field.get_internal_type() == 'TimeField':
if (isinstance(value, datetime.datetime) and value.year == 1900 and value.month == value.day == 1):
value = value.time() # extract time
elif isinstance(value, string_types):
# If the value is a string, parse it using parse_time.
value = parse_time(value)
# Some cases (for example when select_related() is used) aren't
# caught by the DateField case above and date fields arrive from
# the DB as datetime instances.
# Implement a workaround stealing the idea from the Oracle
# backend. It's not perfect so the same warning applies (i.e. if a
# query results in valid date+time values with the time part set
# to midnight, this workaround can surprise us by converting them
# to the datetime.date Python type).
elif isinstance(value, datetime.datetime) and value.hour == value.minute == value.second == value.microsecond == 0:
value = value.date()
# Force floats to the correct type
elif value is not None and field and field.get_internal_type() == 'FloatField':
value = float(value)
return value | [
"def",
"convert_values",
"(",
"self",
",",
"value",
",",
"field",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"field",
"and",
"field",
".",
"get_internal_type",
"(",
")",
"==",
"'DateTimeField'",
":",
"if",
"isinstance",
"(",
"val... | Coerce the value returned by the database backend into a consistent
type that is compatible with the field type.
In our case, cater for the fact that SQL Server < 2008 has no
separate Date and Time data types.
TODO: See how we'll handle this for SQL Server >= 2008 | [
"Coerce",
"the",
"value",
"returned",
"by",
"the",
"database",
"backend",
"into",
"a",
"consistent",
"type",
"that",
"is",
"compatible",
"with",
"the",
"field",
"type",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L485-L524 | train | 33,991 |
lionheart/django-pyodbc | django_pyodbc/introspection.py | DatabaseIntrospection._is_auto_field | def _is_auto_field(self, cursor, table_name, column_name):
"""
Checks whether column is Identity
"""
# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx
#from django.db import connection
#cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')",
# (connection.ops.quote_name(table_name), column_name))
cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')",
(self.connection.ops.quote_name(table_name), column_name))
return cursor.fetchall()[0][0] | python | def _is_auto_field(self, cursor, table_name, column_name):
"""
Checks whether column is Identity
"""
# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx
#from django.db import connection
#cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')",
# (connection.ops.quote_name(table_name), column_name))
cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')",
(self.connection.ops.quote_name(table_name), column_name))
return cursor.fetchall()[0][0] | [
"def",
"_is_auto_field",
"(",
"self",
",",
"cursor",
",",
"table_name",
",",
"column_name",
")",
":",
"# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx",
"#from django.db import connection",
"#cursor.execute(\"SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')... | Checks whether column is Identity | [
"Checks",
"whether",
"column",
"is",
"Identity"
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/introspection.py#L99-L110 | train | 33,992 |
lionheart/django-pyodbc | django_pyodbc/introspection.py | DatabaseIntrospection.get_table_description | def get_table_description(self, cursor, table_name, identity_check=True):
"""Returns a description of the table, with DB-API cursor.description interface.
The 'auto_check' parameter has been added to the function argspec.
If set to True, the function will check each of the table's fields for the
IDENTITY property (the IDENTITY property is the MSSQL equivalent to an AutoField).
When a field is found with an IDENTITY property, it is given a custom field number
of SQL_AUTOFIELD, which maps to the 'AutoField' value in the DATA_TYPES_REVERSE dict.
"""
# map pyodbc's cursor.columns to db-api cursor description
columns = [[c[3], c[4], None, c[6], c[6], c[8], c[10]] for c in cursor.columns(table=table_name)]
items = []
for column in columns:
if identity_check and self._is_auto_field(cursor, table_name, column[0]):
column[1] = SQL_AUTOFIELD
# The conversion from TextField to CharField below is unwise.
# A SQLServer db field of type "Text" is not interchangeable with a CharField, no matter how short its max_length.
# For example, model.objects.values(<text_field_name>).count() will fail on a sqlserver 'text' field
if column[1] == Database.SQL_WVARCHAR and column[3] < 4000:
column[1] = Database.SQL_WCHAR
items.append(column)
return items | python | def get_table_description(self, cursor, table_name, identity_check=True):
"""Returns a description of the table, with DB-API cursor.description interface.
The 'auto_check' parameter has been added to the function argspec.
If set to True, the function will check each of the table's fields for the
IDENTITY property (the IDENTITY property is the MSSQL equivalent to an AutoField).
When a field is found with an IDENTITY property, it is given a custom field number
of SQL_AUTOFIELD, which maps to the 'AutoField' value in the DATA_TYPES_REVERSE dict.
"""
# map pyodbc's cursor.columns to db-api cursor description
columns = [[c[3], c[4], None, c[6], c[6], c[8], c[10]] for c in cursor.columns(table=table_name)]
items = []
for column in columns:
if identity_check and self._is_auto_field(cursor, table_name, column[0]):
column[1] = SQL_AUTOFIELD
# The conversion from TextField to CharField below is unwise.
# A SQLServer db field of type "Text" is not interchangeable with a CharField, no matter how short its max_length.
# For example, model.objects.values(<text_field_name>).count() will fail on a sqlserver 'text' field
if column[1] == Database.SQL_WVARCHAR and column[3] < 4000:
column[1] = Database.SQL_WCHAR
items.append(column)
return items | [
"def",
"get_table_description",
"(",
"self",
",",
"cursor",
",",
"table_name",
",",
"identity_check",
"=",
"True",
")",
":",
"# map pyodbc's cursor.columns to db-api cursor description",
"columns",
"=",
"[",
"[",
"c",
"[",
"3",
"]",
",",
"c",
"[",
"4",
"]",
",... | Returns a description of the table, with DB-API cursor.description interface.
The 'auto_check' parameter has been added to the function argspec.
If set to True, the function will check each of the table's fields for the
IDENTITY property (the IDENTITY property is the MSSQL equivalent to an AutoField).
When a field is found with an IDENTITY property, it is given a custom field number
of SQL_AUTOFIELD, which maps to the 'AutoField' value in the DATA_TYPES_REVERSE dict. | [
"Returns",
"a",
"description",
"of",
"the",
"table",
"with",
"DB",
"-",
"API",
"cursor",
".",
"description",
"interface",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/introspection.py#L114-L137 | train | 33,993 |
lionheart/django-pyodbc | django_pyodbc/compiler.py | _break | def _break(s, find):
"""Break a string s into the part before the substring to find,
and the part including and after the substring."""
i = s.find(find)
return s[:i], s[i:] | python | def _break(s, find):
"""Break a string s into the part before the substring to find,
and the part including and after the substring."""
i = s.find(find)
return s[:i], s[i:] | [
"def",
"_break",
"(",
"s",
",",
"find",
")",
":",
"i",
"=",
"s",
".",
"find",
"(",
"find",
")",
"return",
"s",
"[",
":",
"i",
"]",
",",
"s",
"[",
"i",
":",
"]"
] | Break a string s into the part before the substring to find,
and the part including and after the substring. | [
"Break",
"a",
"string",
"s",
"into",
"the",
"part",
"before",
"the",
"substring",
"to",
"find",
"and",
"the",
"part",
"including",
"and",
"after",
"the",
"substring",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/compiler.py#L107-L111 | train | 33,994 |
lionheart/django-pyodbc | django_pyodbc/compiler.py | SQLCompiler._fix_aggregates | def _fix_aggregates(self):
"""
MSSQL doesn't match the behavior of the other backends on a few of
the aggregate functions; different return type behavior, different
function names, etc.
MSSQL's implementation of AVG maintains datatype without proding. To
match behavior of other django backends, it needs to not drop remainders.
E.g. AVG([1, 2]) needs to yield 1.5, not 1
"""
try:
# for django 1.10 and up (works starting in 1.8 so I am told)
select = self.query.annotation_select
except AttributeError:
# older
select = self.query.aggregate_select
for alias, aggregate in select.items():
if not hasattr(aggregate, 'sql_function'):
continue
if aggregate.sql_function == 'AVG':# and self.connection.cast_avg_to_float:
# Embed the CAST in the template on this query to
# maintain multi-db support.
select[alias].sql_template = \
'%(function)s(CAST(%(field)s AS FLOAT))'
# translate StdDev function names
elif aggregate.sql_function == 'STDDEV_SAMP':
select[alias].sql_function = 'STDEV'
elif aggregate.sql_function == 'STDDEV_POP':
select[alias].sql_function = 'STDEVP'
# translate Variance function names
elif aggregate.sql_function == 'VAR_SAMP':
select[alias].sql_function = 'VAR'
elif aggregate.sql_function == 'VAR_POP':
select[alias].sql_function = 'VARP' | python | def _fix_aggregates(self):
"""
MSSQL doesn't match the behavior of the other backends on a few of
the aggregate functions; different return type behavior, different
function names, etc.
MSSQL's implementation of AVG maintains datatype without proding. To
match behavior of other django backends, it needs to not drop remainders.
E.g. AVG([1, 2]) needs to yield 1.5, not 1
"""
try:
# for django 1.10 and up (works starting in 1.8 so I am told)
select = self.query.annotation_select
except AttributeError:
# older
select = self.query.aggregate_select
for alias, aggregate in select.items():
if not hasattr(aggregate, 'sql_function'):
continue
if aggregate.sql_function == 'AVG':# and self.connection.cast_avg_to_float:
# Embed the CAST in the template on this query to
# maintain multi-db support.
select[alias].sql_template = \
'%(function)s(CAST(%(field)s AS FLOAT))'
# translate StdDev function names
elif aggregate.sql_function == 'STDDEV_SAMP':
select[alias].sql_function = 'STDEV'
elif aggregate.sql_function == 'STDDEV_POP':
select[alias].sql_function = 'STDEVP'
# translate Variance function names
elif aggregate.sql_function == 'VAR_SAMP':
select[alias].sql_function = 'VAR'
elif aggregate.sql_function == 'VAR_POP':
select[alias].sql_function = 'VARP' | [
"def",
"_fix_aggregates",
"(",
"self",
")",
":",
"try",
":",
"# for django 1.10 and up (works starting in 1.8 so I am told)",
"select",
"=",
"self",
".",
"query",
".",
"annotation_select",
"except",
"AttributeError",
":",
"# older",
"select",
"=",
"self",
".",
"query"... | MSSQL doesn't match the behavior of the other backends on a few of
the aggregate functions; different return type behavior, different
function names, etc.
MSSQL's implementation of AVG maintains datatype without proding. To
match behavior of other django backends, it needs to not drop remainders.
E.g. AVG([1, 2]) needs to yield 1.5, not 1 | [
"MSSQL",
"doesn",
"t",
"match",
"the",
"behavior",
"of",
"the",
"other",
"backends",
"on",
"a",
"few",
"of",
"the",
"aggregate",
"functions",
";",
"different",
"return",
"type",
"behavior",
"different",
"function",
"names",
"etc",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/compiler.py#L171-L205 | train | 33,995 |
lionheart/django-pyodbc | django_pyodbc/compiler.py | SQLCompiler._fix_slicing_order | def _fix_slicing_order(self, outer_fields, inner_select, order, inner_table_name):
"""
Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing.
"""
# Using ROW_NUMBER requires an ordering
if order is None:
meta = self.query.get_meta()
column = meta.pk.db_column or meta.pk.get_attname()
order = '{0}.{1} ASC'.format(
inner_table_name,
self.connection.ops.quote_name(column),
)
else:
alias_id = 0
# remap order for injected subselect
new_order = []
for x in order.split(','):
# find the ordering direction
m = _re_find_order_direction.search(x)
if m:
direction = m.groups()[0]
else:
direction = 'ASC'
# remove the ordering direction
x = _re_find_order_direction.sub('', x)
# remove any namespacing or table name from the column name
col = x.rsplit('.', 1)[-1]
# Is the ordering column missing from the inner select?
# 'inner_select' contains the full query without the leading 'SELECT '.
# It's possible that this can get a false hit if the ordering
# column is used in the WHERE while not being in the SELECT. It's
# not worth the complexity to properly handle that edge case.
if x not in inner_select:
# Ordering requires the column to be selected by the inner select
alias_id += 1
# alias column name
col = '{left_sql_quote}{0}___o{1}{right_sql_quote}'.format(
col.strip(self.connection.ops.left_sql_quote+self.connection.ops.right_sql_quote),
alias_id,
left_sql_quote=self.connection.ops.left_sql_quote,
right_sql_quote=self.connection.ops.right_sql_quote,
)
# add alias to inner_select
inner_select = '({0}) AS {1}, {2}'.format(x, col, inner_select)
new_order.append('{0}.{1} {2}'.format(inner_table_name, col, direction))
order = ', '.join(new_order)
return outer_fields, inner_select, order | python | def _fix_slicing_order(self, outer_fields, inner_select, order, inner_table_name):
"""
Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing.
"""
# Using ROW_NUMBER requires an ordering
if order is None:
meta = self.query.get_meta()
column = meta.pk.db_column or meta.pk.get_attname()
order = '{0}.{1} ASC'.format(
inner_table_name,
self.connection.ops.quote_name(column),
)
else:
alias_id = 0
# remap order for injected subselect
new_order = []
for x in order.split(','):
# find the ordering direction
m = _re_find_order_direction.search(x)
if m:
direction = m.groups()[0]
else:
direction = 'ASC'
# remove the ordering direction
x = _re_find_order_direction.sub('', x)
# remove any namespacing or table name from the column name
col = x.rsplit('.', 1)[-1]
# Is the ordering column missing from the inner select?
# 'inner_select' contains the full query without the leading 'SELECT '.
# It's possible that this can get a false hit if the ordering
# column is used in the WHERE while not being in the SELECT. It's
# not worth the complexity to properly handle that edge case.
if x not in inner_select:
# Ordering requires the column to be selected by the inner select
alias_id += 1
# alias column name
col = '{left_sql_quote}{0}___o{1}{right_sql_quote}'.format(
col.strip(self.connection.ops.left_sql_quote+self.connection.ops.right_sql_quote),
alias_id,
left_sql_quote=self.connection.ops.left_sql_quote,
right_sql_quote=self.connection.ops.right_sql_quote,
)
# add alias to inner_select
inner_select = '({0}) AS {1}, {2}'.format(x, col, inner_select)
new_order.append('{0}.{1} {2}'.format(inner_table_name, col, direction))
order = ', '.join(new_order)
return outer_fields, inner_select, order | [
"def",
"_fix_slicing_order",
"(",
"self",
",",
"outer_fields",
",",
"inner_select",
",",
"order",
",",
"inner_table_name",
")",
":",
"# Using ROW_NUMBER requires an ordering",
"if",
"order",
"is",
"None",
":",
"meta",
"=",
"self",
".",
"query",
".",
"get_meta",
... | Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing. | [
"Apply",
"any",
"necessary",
"fixes",
"to",
"the",
"outer_fields",
"inner_select",
"and",
"order",
"strings",
"due",
"to",
"slicing",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/compiler.py#L346-L393 | train | 33,996 |
lionheart/django-pyodbc | django_pyodbc/compiler.py | SQLCompiler._alias_columns | def _alias_columns(self, sql):
"""Return tuple of SELECT and FROM clauses, aliasing duplicate column names."""
qn = self.connection.ops.quote_name
outer = list()
inner = list()
names_seen = list()
# replace all parens with placeholders
paren_depth, paren_buf = 0, ['']
parens, i = {}, 0
for ch in sql:
if ch == '(':
i += 1
paren_depth += 1
paren_buf.append('')
elif ch == ')':
paren_depth -= 1
key = '_placeholder_{0}'.format(i)
buf = paren_buf.pop()
# store the expanded paren string
buf = re.sub(r'%([^\(])', r'$$$\1', buf)
parens[key] = buf% parens
parens[key] = re.sub(r'\$\$\$([^\(])', r'%\1', parens[key])
#cannot use {} because IBM's DB2 uses {} as quotes
paren_buf[paren_depth] += '(%(' + key + ')s)'
else:
paren_buf[paren_depth] += ch
def _replace_sub(col):
"""Replace all placeholders with expanded values"""
while _re_col_placeholder.search(col):
col = col.format(**parens)
return col
temp_sql = ''.join(paren_buf)
# replace any bare %s with placeholders. Needed when the WHERE
# clause only contains one condition, and isn't wrapped in parens.
# the placeholder_data is used to prevent the variable "i" from
# being interpreted as a local variable in the replacement function
placeholder_data = { "i": i }
def _alias_placeholders(val):
i = placeholder_data["i"]
i += 1
placeholder_data["i"] = i
key = "_placeholder_{0}".format(i)
parens[key] = "%s"
return "%(" + key + ")s"
temp_sql = re.sub("%s", _alias_placeholders, temp_sql)
select_list, from_clause = _break(temp_sql, ' FROM ' + self.connection.ops.left_sql_quote)
for col in [x.strip() for x in select_list.split(',')]:
match = self._re_pat_col.search(col)
if match:
col_name = match.group(1)
col_key = col_name.lower()
if col_key in names_seen:
alias = qn('{0}___{1}'.format(col_name, names_seen.count(col_key)))
outer.append(alias)
inner.append('{0} as {1}'.format(_replace_sub(col), alias))
else:
outer.append(qn(col_name))
inner.append(_replace_sub(col))
names_seen.append(col_key)
else:
raise Exception('Unable to find a column name when parsing SQL: {0}'.format(col))
return ', '.join(outer), ', '.join(inner) + (from_clause % parens) | python | def _alias_columns(self, sql):
"""Return tuple of SELECT and FROM clauses, aliasing duplicate column names."""
qn = self.connection.ops.quote_name
outer = list()
inner = list()
names_seen = list()
# replace all parens with placeholders
paren_depth, paren_buf = 0, ['']
parens, i = {}, 0
for ch in sql:
if ch == '(':
i += 1
paren_depth += 1
paren_buf.append('')
elif ch == ')':
paren_depth -= 1
key = '_placeholder_{0}'.format(i)
buf = paren_buf.pop()
# store the expanded paren string
buf = re.sub(r'%([^\(])', r'$$$\1', buf)
parens[key] = buf% parens
parens[key] = re.sub(r'\$\$\$([^\(])', r'%\1', parens[key])
#cannot use {} because IBM's DB2 uses {} as quotes
paren_buf[paren_depth] += '(%(' + key + ')s)'
else:
paren_buf[paren_depth] += ch
def _replace_sub(col):
"""Replace all placeholders with expanded values"""
while _re_col_placeholder.search(col):
col = col.format(**parens)
return col
temp_sql = ''.join(paren_buf)
# replace any bare %s with placeholders. Needed when the WHERE
# clause only contains one condition, and isn't wrapped in parens.
# the placeholder_data is used to prevent the variable "i" from
# being interpreted as a local variable in the replacement function
placeholder_data = { "i": i }
def _alias_placeholders(val):
i = placeholder_data["i"]
i += 1
placeholder_data["i"] = i
key = "_placeholder_{0}".format(i)
parens[key] = "%s"
return "%(" + key + ")s"
temp_sql = re.sub("%s", _alias_placeholders, temp_sql)
select_list, from_clause = _break(temp_sql, ' FROM ' + self.connection.ops.left_sql_quote)
for col in [x.strip() for x in select_list.split(',')]:
match = self._re_pat_col.search(col)
if match:
col_name = match.group(1)
col_key = col_name.lower()
if col_key in names_seen:
alias = qn('{0}___{1}'.format(col_name, names_seen.count(col_key)))
outer.append(alias)
inner.append('{0} as {1}'.format(_replace_sub(col), alias))
else:
outer.append(qn(col_name))
inner.append(_replace_sub(col))
names_seen.append(col_key)
else:
raise Exception('Unable to find a column name when parsing SQL: {0}'.format(col))
return ', '.join(outer), ', '.join(inner) + (from_clause % parens) | [
"def",
"_alias_columns",
"(",
"self",
",",
"sql",
")",
":",
"qn",
"=",
"self",
".",
"connection",
".",
"ops",
".",
"quote_name",
"outer",
"=",
"list",
"(",
")",
"inner",
"=",
"list",
"(",
")",
"names_seen",
"=",
"list",
"(",
")",
"# replace all parens ... | Return tuple of SELECT and FROM clauses, aliasing duplicate column names. | [
"Return",
"tuple",
"of",
"SELECT",
"and",
"FROM",
"clauses",
"aliasing",
"duplicate",
"column",
"names",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/compiler.py#L395-L468 | train | 33,997 |
lionheart/django-pyodbc | django_pyodbc/compiler.py | SQLInsertCompiler._fix_insert | def _fix_insert(self, sql, params):
"""
Wrap the passed SQL with IDENTITY_INSERT statements and apply
other necessary fixes.
"""
meta = self.query.get_meta()
if meta.has_auto_field:
if hasattr(self.query, 'fields'):
# django 1.4 replaced columns with fields
fields = self.query.fields
auto_field = meta.auto_field
else:
# < django 1.4
fields = self.query.columns
auto_field = meta.auto_field.db_column or meta.auto_field.column
auto_in_fields = auto_field in fields
quoted_table = self.connection.ops.quote_name(meta.db_table)
if not fields or (auto_in_fields and len(fields) == 1 and not params):
# convert format when inserting only the primary key without
# specifying a value
sql = 'INSERT INTO {0} DEFAULT VALUES'.format(
quoted_table
)
params = []
elif auto_in_fields:
# wrap with identity insert
sql = 'SET IDENTITY_INSERT {table} ON;{sql};SET IDENTITY_INSERT {table} OFF'.format(
table=quoted_table,
sql=sql,
)
# mangle SQL to return ID from insert
# http://msdn.microsoft.com/en-us/library/ms177564.aspx
if self.return_id and self.connection.features.can_return_id_from_insert:
col = self.connection.ops.quote_name(meta.pk.db_column or meta.pk.get_attname())
# Determine datatype for use with the table variable that will return the inserted ID
pk_db_type = _re_data_type_terminator.split(meta.pk.db_type(self.connection))[0]
# NOCOUNT ON to prevent additional trigger/stored proc related resultsets
sql = 'SET NOCOUNT ON;{declare_table_var};{sql};{select_return_id}'.format(
sql=sql,
declare_table_var="DECLARE @sqlserver_ado_return_id table ({col_name} {pk_type})".format(
col_name=col,
pk_type=pk_db_type,
),
select_return_id="SELECT * FROM @sqlserver_ado_return_id",
)
output = self._values_repl.format(col=col)
sql = self._re_values_sub.sub(output, sql)
return sql, params | python | def _fix_insert(self, sql, params):
"""
Wrap the passed SQL with IDENTITY_INSERT statements and apply
other necessary fixes.
"""
meta = self.query.get_meta()
if meta.has_auto_field:
if hasattr(self.query, 'fields'):
# django 1.4 replaced columns with fields
fields = self.query.fields
auto_field = meta.auto_field
else:
# < django 1.4
fields = self.query.columns
auto_field = meta.auto_field.db_column or meta.auto_field.column
auto_in_fields = auto_field in fields
quoted_table = self.connection.ops.quote_name(meta.db_table)
if not fields or (auto_in_fields and len(fields) == 1 and not params):
# convert format when inserting only the primary key without
# specifying a value
sql = 'INSERT INTO {0} DEFAULT VALUES'.format(
quoted_table
)
params = []
elif auto_in_fields:
# wrap with identity insert
sql = 'SET IDENTITY_INSERT {table} ON;{sql};SET IDENTITY_INSERT {table} OFF'.format(
table=quoted_table,
sql=sql,
)
# mangle SQL to return ID from insert
# http://msdn.microsoft.com/en-us/library/ms177564.aspx
if self.return_id and self.connection.features.can_return_id_from_insert:
col = self.connection.ops.quote_name(meta.pk.db_column or meta.pk.get_attname())
# Determine datatype for use with the table variable that will return the inserted ID
pk_db_type = _re_data_type_terminator.split(meta.pk.db_type(self.connection))[0]
# NOCOUNT ON to prevent additional trigger/stored proc related resultsets
sql = 'SET NOCOUNT ON;{declare_table_var};{sql};{select_return_id}'.format(
sql=sql,
declare_table_var="DECLARE @sqlserver_ado_return_id table ({col_name} {pk_type})".format(
col_name=col,
pk_type=pk_db_type,
),
select_return_id="SELECT * FROM @sqlserver_ado_return_id",
)
output = self._values_repl.format(col=col)
sql = self._re_values_sub.sub(output, sql)
return sql, params | [
"def",
"_fix_insert",
"(",
"self",
",",
"sql",
",",
"params",
")",
":",
"meta",
"=",
"self",
".",
"query",
".",
"get_meta",
"(",
")",
"if",
"meta",
".",
"has_auto_field",
":",
"if",
"hasattr",
"(",
"self",
".",
"query",
",",
"'fields'",
")",
":",
"... | Wrap the passed SQL with IDENTITY_INSERT statements and apply
other necessary fixes. | [
"Wrap",
"the",
"passed",
"SQL",
"with",
"IDENTITY_INSERT",
"statements",
"and",
"apply",
"other",
"necessary",
"fixes",
"."
] | 46adda7b0bfabfa2640f72592c6f6f407f78b363 | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/compiler.py#L506-L561 | train | 33,998 |
shmuelamar/cbox | examples/head.py | head | def head(line, n: int):
"""returns the first `n` lines"""
global counter
counter += 1
if counter > n:
raise cbox.Stop() # can also raise StopIteration()
return line | python | def head(line, n: int):
"""returns the first `n` lines"""
global counter
counter += 1
if counter > n:
raise cbox.Stop() # can also raise StopIteration()
return line | [
"def",
"head",
"(",
"line",
",",
"n",
":",
"int",
")",
":",
"global",
"counter",
"counter",
"+=",
"1",
"if",
"counter",
">",
"n",
":",
"raise",
"cbox",
".",
"Stop",
"(",
")",
"# can also raise StopIteration()",
"return",
"line"
] | returns the first `n` lines | [
"returns",
"the",
"first",
"n",
"lines"
] | 2d0cda5b3f61a55e530251430bf3d460dcd3732e | https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/examples/head.py#L8-L15 | train | 33,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.