buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
from django.utils.text import (
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext
from .base import Variable, VariableDoesNotExist
from .library import Library
register = Library() | from django.utils.text import (
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext
from .base import VARIABLE_ATTRIBUTE_SEPARATOR
from .library import Library
register = Library() |
def striptags(value):
def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, behave like Variable(arg).resolve
>>> _property_resolver(1)('abc')
'b' | def striptags(value):
def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, chain __getitem__() and getattr().
>>> _property_resolver(1)('abc')
'b' |
def _property_resolver(arg):
try:
float(arg)
except ValueError:
return Variable(arg).resolve
else:
return itemgetter(arg)
| def _property_resolver(arg):
try:
float(arg)
except ValueError:
if VARIABLE_ATTRIBUTE_SEPARATOR + '_' in arg or arg[0] == '_':
raise AttributeError('Access to private variables is forbidden.')
parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR)
def resolve(value):
... |
def dictsort(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg))
except (TypeError, VariableDoesNotExist):
return ''
| def dictsort(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg))
except (AttributeError, TypeError):
return ''
|
def dictsortreversed(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (TypeError, VariableDoesNotExist):
return ''
| def dictsortreversed(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (AttributeError, TypeError):
return ''
|
from django.template.defaultfilters import dictsort
from django.test import SimpleTestCase
class FunctionTests(SimpleTestCase):
def test_sort(self):
sorted_dicts = dictsort(
[{'age': 23, 'name': 'Barbara-Ann'}, | from django.template.defaultfilters import _property_resolver, dictsort
from django.test import SimpleTestCase
class User:
password = 'abc'
_private = 'private'
@property
def test_property(self):
return 'cde'
def test_method(self):
"""This is just a test method."""
class Funct... |
class FunctionTests(SimpleTestCase):
def test_dictsort_complex_sorting_key(self):
"""
Since dictsort uses template.Variable under the hood, it can sort
on keys like 'foo.bar'.
"""
data = [ | class FunctionTests(SimpleTestCase):
def test_dictsort_complex_sorting_key(self):
"""
Since dictsort uses dict.get()/getattr() under the hood, it can sort
on keys like 'foo.bar'.
"""
data = [ |
class FunctionTests(SimpleTestCase):
self.assertEqual(dictsort('Hello!', 'age'), '')
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '') | class FunctionTests(SimpleTestCase):
self.assertEqual(dictsort('Hello!', 'age'), '')
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '')
def test_invalid_args(self):
"""Fail silently if invalid lookups are passed."""
self.assertEqual(dict... |
class FunctionTests(SimpleTestCase):
self.assertEqual(dictsortreversed('Hello!', 'age'), '')
self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
self.assertEqual(dictsortreversed(1, 'age'), '') | class FunctionTests(SimpleTestCase):
self.assertEqual(dictsortreversed('Hello!', 'age'), '')
self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
self.assertEqual(dictsortreversed(1, 'age'), '')
def test_invalid_args(self):
"""Fail silently if invalid lookups are passed."""
... |
from pathlib import Path
from django.conf import settings
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Context, Engine, TemplateDoesNotExist
from django.template.defaultfilters import force_escape, pprint
from django.urls import Resolver404, resolve
from django.utils import tim... | from pathlib import Path
from django.conf import settings
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Context, Engine, TemplateDoesNotExist
from django.template.defaultfilters import pprint
from django.urls import Resolver404, resolve
from django.utils import timezone
from dja... |
class ExceptionReporter:
# Trim large blobs of data
if len(v) > 4096:
v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v))
frame_vars.append((k, force_escape(v)))
frame['vars'] = frame_vars
frames[i] =... | class ExceptionReporter:
# Trim large blobs of data
if len(v) > 4096:
v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v))
frame_vars.append((k, v))
frame['vars'] = frame_vars
frames[i] = frame
|
class ExceptionReporterTests(SimpleTestCase):
request = self.rf.get('/test_view/')
try:
try:
raise AttributeError('Top level')
except AttributeError as explicit:
try:
raise ValueError('Second exception') from explicit
... | class ExceptionReporterTests(SimpleTestCase):
request = self.rf.get('/test_view/')
try:
try:
raise AttributeError(mark_safe('<p>Top level</p>'))
except AttributeError as explicit:
try:
raise ValueError(mark_safe('<p>Second excep... |
class ExceptionReporterTests(SimpleTestCase):
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(2, html.count(explicit_exc.format("Top level")))
self.assertEqual(2, html.count(implic... | class ExceptionReporterTests(SimpleTestCase):
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(2, html.count(explicit_exc.format('<p>Top level</p>')))
self.assertEqual(2... |
def finalize_with_tag(self, tag):
"finalize_with_tag requires OpenSSL >= 1.0.2. To use this "
"method please update OpenSSL"
)
res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
self._ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG,
len(tag), tag | def finalize_with_tag(self, tag):
"finalize_with_tag requires OpenSSL >= 1.0.2. To use this "
"method please update OpenSSL"
)
if len(tag) < self._mode._min_tag_length:
raise ValueError(
"Authentication tag must be {0} bytes or longer.".for... |
def __init__(self, initialization_vector, tag=None, min_tag_length=16):
min_tag_length)
)
self._tag = tag
tag = utils.read_only_property("_tag")
initialization_vector = utils.read_only_property("_initialization_vector") | def __init__(self, initialization_vector, tag=None, min_tag_length=16):
min_tag_length)
)
self._tag = tag
self._min_tag_length = min_tag_length
tag = utils.read_only_property("_tag")
initialization_vector = utils.read_only_property("_initialization_vector... |
def test_gcm_tag_decrypt_finalize(self, backend):
decryptor.finalize()
else:
decryptor.finalize_with_tag(tag) | def test_gcm_tag_decrypt_finalize(self, backend):
decryptor.finalize()
else:
decryptor.finalize_with_tag(tag)
@pytest.mark.supported(
only_if=lambda backend: (
not backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_102 or
backend._lib.CRYPTOGRAPHY_IS_LIBRESS... |
# -*- coding: utf-8 -*-
import pytest
from thefuck.shells import Bash
| # -*- coding: utf-8 -*-
import os
import pytest
from thefuck.shells import Bash
|
class TestBash(object):
return Bash()
@pytest.fixture(autouse=True)
def Popen(self, mocker):
mock = mocker.patch('thefuck.shells.bash.Popen')
mock.return_value.stdout.read.return_value = (
b'alias fuck=\'eval $(thefuck $(fc -ln -1))\'\n'
b'alias l=\'ls -CF\'\n'
... | class TestBash(object):
return Bash()
@pytest.fixture(autouse=True)
def shell_aliases(self):
os.environ['TF_SHELL_ALIASES'] = (
'alias fuck=\'eval $(thefuck $(fc -ln -1))\'\n'
'alias l=\'ls -CF\'\n'
'alias la=\'ls -A\'\n'
'alias ll=\'ls -alF\'')
... |
from subprocess import Popen, PIPE
import os
from ..conf import settings
from ..utils import DEVNULL, memoize, cache
from .generic import Generic
| import os
from ..conf import settings
from ..utils import memoize
from .generic import Generic
|
class Bash(Generic):
def app_alias(self, fuck):
alias = "TF_ALIAS={0}" \
" alias {0}='PYTHONIOENCODING=utf-8" \
" TF_CMD=$(thefuck $(fc -ln -1)) && " \
" eval $TF_CMD".format(fuck)
if settings.alter_history: | class Bash(Generic):
def app_alias(self, fuck):
alias = "TF_ALIAS={0}" \
" alias {0}='PYTHONIOENCODING=utf-8" \
" TF_CMD=$(TF_SHELL_ALIASES=$(alias) thefuck $(fc -ln -1)) && " \
" eval $TF_CMD".format(fuck)
if settings.alter_history: |
class Bash(Generic):
return name, value
@memoize
@cache('.bashrc', '.bash_profile')
def get_aliases(self):
proc = Popen(['bash', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
return dict(
self._parse_alias(alias)
for alias in proc.stdout.read().decode... | class Bash(Generic):
return name, value
@memoize
def get_aliases(self):
raw_aliases = os.environ.get('TF_SHELL_ALIASES', '').split('\n')
return dict(self._parse_alias(alias)
for alias in raw_aliases if alias and '=' in alias)
def _get_history_file_name(self):
... |
class Zsh(Generic):
@memoize
def get_aliases(self):
raw_aliases = os.environ['TF_SHELL_ALIASES'].split('\n')
return dict(self._parse_alias(alias)
for alias in raw_aliases if alias and '=' in alias)
| class Zsh(Generic):
@memoize
def get_aliases(self):
raw_aliases = os.environ.get('TF_SHELL_ALIASES', '').split('\n')
return dict(self._parse_alias(alias)
for alias in raw_aliases if alias and '=' in alias)
|
def handle_write(self):
if self.will_close:
self.handle_close()
def _flush_exception(self, flush):
if flush:
try:
return (flush(), False)
except OSError:
if self.adj.log_socket_errors:
self.logger.exception("Soc... | def handle_write(self):
if self.will_close:
self.handle_close()
def _flush_exception(self, flush, do_close=True):
if flush:
try:
return (flush(do_close=do_close), False)
except OSError:
if self.adj.log_socket_errors:
... |
def received(self, data):
return True
def _flush_some_if_lockable(self):
# Since our task may be appending to the outbuf, we try to acquire
# the lock, but we don't block if we can't.
if self.outbuf_lock.acquire(False):
try:
self._flush_some()
... | def received(self, data):
return True
def _flush_some_if_lockable(self, do_close=True):
# Since our task may be appending to the outbuf, we try to acquire
# the lock, but we don't block if we can't.
if self.outbuf_lock.acquire(False):
try:
self._flush_s... |
def _flush_some(self):
while outbuflen > 0:
chunk = outbuf.get(self.sendbuf_len)
num_sent = self.send(chunk)
if num_sent:
outbuf.skip(num_sent, True) | def _flush_some(self):
while outbuflen > 0:
chunk = outbuf.get(self.sendbuf_len)
num_sent = self.send(chunk, do_close=do_close)
if num_sent:
outbuf.skip(num_sent, True) |
def write_soon(self, data):
self.total_outbufs_len += num_bytes
if self.total_outbufs_len >= self.adj.send_bytes:
(flushed, exception) = self._flush_exception(self._flush_some)
if (
exception | def write_soon(self, data):
self.total_outbufs_len += num_bytes
if self.total_outbufs_len >= self.adj.send_bytes:
(flushed, exception) = self._flush_exception(
self._flush_some, do_close=False
)
if (
... |
def _flush_outbufs_below_high_watermark(self):
if self.total_outbufs_len > self.adj.outbuf_high_watermark:
with self.outbuf_lock:
(_, exception) = self._flush_exception(self._flush_some)
if exception:
# An exception happened while flushing, wake ... | def _flush_outbufs_below_high_watermark(self):
if self.total_outbufs_len > self.adj.outbuf_high_watermark:
with self.outbuf_lock:
(_, exception) = self._flush_exception(self._flush_some, do_close=False)
if exception:
# An exception happened while... |
def accept(self):
else:
return conn, addr
def send(self, data):
try:
result = self.socket.send(data)
return result | def accept(self):
else:
return conn, addr
def send(self, data, do_close=True):
try:
result = self.socket.send(data)
return result |
def send(self, data):
if why.args[0] == EWOULDBLOCK:
return 0
elif why.args[0] in _DISCONNECTED:
self.handle_close()
return 0
else:
raise | def send(self, data):
if why.args[0] == EWOULDBLOCK:
return 0
elif why.args[0] in _DISCONNECTED:
if do_close:
self.handle_close()
return 0
else:
raise |
def test_handle_write_no_notify_after_flush(self):
inst.total_outbufs_len = len(inst.outbufs[0])
inst.adj.send_bytes = 1
inst.adj.outbuf_high_watermark = 2
sock.send = lambda x: False
inst.will_close = False
inst.last_activity = 0
result = inst.handle_write() | def test_handle_write_no_notify_after_flush(self):
inst.total_outbufs_len = len(inst.outbufs[0])
inst.adj.send_bytes = 1
inst.adj.outbuf_high_watermark = 2
sock.send = lambda x, do_close=True: False
inst.will_close = False
inst.last_activity = 0
result = inst.hand... |
def get(self, numbytes):
buf = DummyHugeOutbuffer()
inst.outbufs = [buf]
inst.send = lambda *arg: 0
result = inst._flush_some()
# we are testing that _flush_some doesn't raise an OverflowError
# when one of its outbufs has a __len__ that returns gt sys.maxint | def get(self, numbytes):
buf = DummyHugeOutbuffer()
inst.outbufs = [buf]
inst.send = lambda *arg, do_close: 0
result = inst._flush_some()
# we are testing that _flush_some doesn't raise an OverflowError
# when one of its outbufs has a __len__ that returns gt sys.maxint |
class Worker(object):
Structure for tracking worker activity and keeping their references.
"""
def __init__(self, worker_id, last_active=None):
self.id = worker_id
self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host)
self.la... | class Worker(object):
Structure for tracking worker activity and keeping their references.
"""
def __init__(self, worker_id, last_active=time.time()):
self.id = worker_id
self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host)
... |
class SchedulerTest(unittest.TestCase):
cps = reload_from_disk(cps=cps) # This time without deleting
self.assertEqual(cps.get_work(worker='D')['task_id'], '4')
if __name__ == '__main__':
unittest.main() | class SchedulerTest(unittest.TestCase):
cps = reload_from_disk(cps=cps) # This time without deleting
self.assertEqual(cps.get_work(worker='D')['task_id'], '4')
def test_worker_prune_after_init(self):
worker = luigi.scheduler.Worker(123)
class TmpCfg:
def __init... |
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
self.assertFalse(match_str(
'like_count > 100 & dislike_count <? 50 & description',
{'like_count': 190, 'dislike_count': 10}))
def test_parse_dfxp_time_expr(self):
self.assertEqual(parse_dfxp_time_expr... | ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
self.assertFalse(match_str(
'like_count > 100 & dislike_count <? 50 & description',
{'like_count': 190, 'dislike_count': 10}))
self.assertTrue(match_str('is_live', {'is_live': True}))
self.assertFal... |
def _match_one(filter_part, dct):
return op(actual_value, comparison_value)
UNARY_OPERATORS = {
'': lambda v: v is not None,
'!': lambda v: v is None,
}
operator_rex = re.compile(r'''(?x)\s*
(?P<op>%s)\s*(?P<key>[a-z_]+) | def _match_one(filter_part, dct):
return op(actual_value, comparison_value)
UNARY_OPERATORS = {
'': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
'!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
}
operator_rex = re.compile(r'''(?x)\s*
... |
class Categorical(ExtensionArray, PandasObject):
)
raise ValueError(msg)
codes = np.asarray(codes) # #21767
if len(codes) and not is_integer_dtype(codes):
raise ValueError("codes need to be array-like integers")
| class Categorical(ExtensionArray, PandasObject):
)
raise ValueError(msg)
if is_extension_array_dtype(codes) and is_integer_dtype(codes):
# Avoid the implicit conversion of Int to object
if isna(codes).any():
raise ValueError("codes cannot contain ... |
class TestCategoricalConstructors:
with pytest.raises(ValueError, match=msg):
Categorical.from_codes([0, 1])
@pytest.mark.parametrize("dtype", [None, "category"])
def test_from_inferred_categories(self, dtype):
cats = ["a", "b"] | class TestCategoricalConstructors:
with pytest.raises(ValueError, match=msg):
Categorical.from_codes([0, 1])
def test_from_codes_with_nullable_int(self):
codes = pd.array([0, 1], dtype="Int64")
categories = ["a", "b"]
result = Categorical.from_codes(codes, categories=ca... |
def interpolate_1d(
inds = lib.maybe_convert_objects(inds)
else:
inds = xvalues
result[invalid] = np.interp(inds[invalid], inds[valid], yvalues[valid])
result[preserve_nans] = np.nan
return result
| def interpolate_1d(
inds = lib.maybe_convert_objects(inds)
else:
inds = xvalues
# np.interp requires sorted X values, #21037
indexer = np.argsort(inds[valid])
result[invalid] = np.interp(
inds[invalid], inds[valid][indexer], yvalues[valid][indexer]... |
class TestSeriesInterpolateData:
pytest.skip(
"This interpolation method is not supported for Timedelta Index yet."
) | class TestSeriesInterpolateData:
pytest.skip(
"This interpolation method is not supported for Timedelta Index yet."
)
@pytest.mark.parametrize(
"ascending, expected_values",
[(True, [1, 2, 3, 9, 10]), (False, [10, 9, 3, 2, 1])],
)
def test_interpolate... |
import recurly.errors
from recurly.link_header import parse_link_value
from six.moves import http_client
from six.moves.urllib.parse import urlencode, urljoin, urlsplit
class Money(object):
| import recurly.errors
from recurly.link_header import parse_link_value
from six.moves import http_client
from six.moves.urllib.parse import urlencode, urlsplit, quote
class Money(object):
|
def get(cls, uuid):
can be directly requested with this method.
"""
url = urljoin(recurly.base_uri(), cls.member_path % (uuid,))
resp, elem = cls.element_for_url(url)
return cls.from_element(elem)
| def get(cls, uuid):
can be directly requested with this method.
"""
uuid = quote(str(uuid))
url = recurly.base_uri() + (cls.member_path % (uuid,))
resp, elem = cls.element_for_url(url)
return cls.from_element(elem)
|
def all(cls, **kwargs):
parameters.
"""
url = urljoin(recurly.base_uri(), cls.collection_path)
if kwargs:
url = '%s?%s' % (url, urlencode(kwargs))
return Page.page_for_url(url) | def all(cls, **kwargs):
parameters.
"""
url = recurly.base_uri() + cls.collection_path
if kwargs:
url = '%s?%s' % (url, urlencode(kwargs))
return Page.page_for_url(url) |
def count(cls, **kwargs):
"""Return a count of server side resources given
filtering arguments in kwargs.
"""
url = urljoin(recurly.base_uri(), cls.collection_path)
if kwargs:
url = '%s?%s' % (url, urlencode(kwargs))
return Page.count_for_url(url) | def count(cls, **kwargs):
"""Return a count of server side resources given
filtering arguments in kwargs.
"""
url = recurly.base_uri() + cls.collection_path
if kwargs:
url = '%s?%s' % (url, urlencode(kwargs))
return Page.count_for_url(url) |
def _update(self):
return self.put(self._url)
def _create(self):
url = urljoin(recurly.base_uri(), self.collection_path)
return self.post(url)
def put(self, url): | def _update(self):
return self.put(self._url)
def _create(self):
url = recurly.base_uri() + self.collection_path
return self.post(url)
def put(self, url): |
from thefuck.rules.mkdir_p import match, get_new_command
from tests.utils import Command
def test_match():
assert match(Command('mkdir foo/bar/baz',
stderr='mkdir: foo/bar: No such file or directory'),
None)
@pytest.mark.parametrize('command', [
Command('mkdir foo/b... | from thefuck.rules.mkdir_p import match, get_new_command
from tests.utils import Command
@pytest.mark.parametrize('command', [
Command('mkdir foo/bar/baz', stderr='mkdir: foo/bar: No such file or directory'),
Command('./bin/hdfs dfs -mkdir foo/bar/baz', stderr='mkdir: `foo/bar/baz\': No such file or directory... |
def match(command, settings):
@sudo_support
def get_new_command(command, settings):
return re.sub('^mkdir (.*)', 'mkdir -p \\1', command.script) | def match(command, settings):
@sudo_support
def get_new_command(command, settings):
return re.sub('\\bmkdir (.*)', 'mkdir -p \\1', command.script) |
#!/usr/bin/env python
from __future__ import unicode_literals
| #!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
|
class TestYoutubeDL(unittest.TestCase):
'duration': 30,
'filesize': 10 * 1024,
'playlist_id': '42',
}
second = {
'id': '2', | class TestYoutubeDL(unittest.TestCase):
'duration': 30,
'filesize': 10 * 1024,
'playlist_id': '42',
'uploader': "變態妍字幕版 太妍 тест",
'creator': "тест ' 123 ' тест--",
}
second = {
'id': '2', |
class TestYoutubeDL(unittest.TestCase):
'description': 'foo',
'filesize': 5 * 1024,
'playlist_id': '43',
}
videos = [first, second]
| class TestYoutubeDL(unittest.TestCase):
'description': 'foo',
'filesize': 5 * 1024,
'playlist_id': '43',
'uploader': "тест 123",
}
videos = [first, second]
|
class TestYoutubeDL(unittest.TestCase):
res = get_videos(f)
self.assertEqual(res, ['1'])
def test_playlist_items_selection(self):
entries = [{
'id': compat_str(i), | class TestYoutubeDL(unittest.TestCase):
res = get_videos(f)
self.assertEqual(res, ['1'])
f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
res = get_videos(f)
self.assertEqual(res, ['1'])
f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
res = get_videos(... |
def _match_one(filter_part, dct):
\s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?:
(?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
(?P<strval>(?![0-9.])[a-z0-9A-Z]*)
)
\s*$ | def _match_one(filter_part, dct):
\s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?:
(?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
(?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
(?P<strval>(?![0-9.])[a-z0-9A-Z]*)
)
\s*$ |
def _match_one(filter_part, dct):
if m:
op = COMPARISON_OPERATORS[m.group('op')]
actual_value = dct.get(m.group('key'))
if (m.group('strval') is not None or
# If the original field is a string and matching comparisonvalue is
# a number we should respect the origin of ... | def _match_one(filter_part, dct):
if m:
op = COMPARISON_OPERATORS[m.group('op')]
actual_value = dct.get(m.group('key'))
if (m.group('quotedstrval') is not None or
m.group('strval') is not None or
# If the original field is a string and matching comparisonvalue is
... |
def _match_one(filter_part, dct):
if m.group('op') not in ('=', '!='):
raise ValueError(
'Operator %s does not support string values!' % m.group('op'))
comparison_value = m.group('strval') or m.group('intval')
else:
try:
com... | def _match_one(filter_part, dct):
if m.group('op') not in ('=', '!='):
raise ValueError(
'Operator %s does not support string values!' % m.group('op'))
comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
quote = m.g... |
'usemap',
# Not standard:
'dynsrc', 'lowsrc',
])
# Not in the HTML 4 spec: | 'usemap',
# Not standard:
'dynsrc', 'lowsrc',
# HTML5 formaction
'formaction'
])
# Not in the HTML 4 spec: |
def test_sneaky_js_in_math_style(self):
b'<math><style>/* deleted */</style></math>',
lxml.html.tostring(clean_html(s)))
def test_suite():
suite = unittest.TestSuite() | def test_sneaky_js_in_math_style(self):
b'<math><style>/* deleted */</style></math>',
lxml.html.tostring(clean_html(s)))
def test_formaction_attribute_in_button_input(self):
# The formaction attribute overrides the form's action and should be
# treated as a malicious link at... |
def find_hook(hook_name, hooks_dir='hooks'):
logger.debug('No hooks/dir in template_dir')
return None
for hook_file in os.listdir(hooks_dir):
if valid_hook(hook_file, hook_name):
return os.path.abspath(os.path.join(hooks_dir, hook_file))
return None
def run_script(script_... | def find_hook(hook_name, hooks_dir='hooks'):
logger.debug('No hooks/dir in template_dir')
return None
scripts = []
for hook_file in os.listdir(hooks_dir):
if valid_hook(hook_file, hook_name):
scripts.append(os.path.abspath(os.path.join(hooks_dir, hook_file)))
if len(scr... |
def run_hook(hook_name, project_dir, context):
:param project_dir: The directory to execute the script from.
:param context: Cookiecutter project context.
"""
script = find_hook(hook_name)
if script is None:
logger.debug('No %s hook found', hook_name)
return
logger.debug('Running... | def run_hook(hook_name, project_dir, context):
:param project_dir: The directory to execute the script from.
:param context: Cookiecutter project context.
"""
scripts = find_hook(hook_name)
if not scripts:
logger.debug('No %s hook found', hook_name)
return
logger.debug('Running h... |
import pytest
from cookiecutter import hooks, utils, exceptions
def make_test_repo(name):
"""Create test repository for test setup methods."""
hook_dir = os.path.join(name, 'hooks')
template = os.path.join(name, 'input{{hooks}}') | import pytest
from cookiecutter import hooks, utils, exceptions
def make_test_repo(name, multiple_hooks=False):
"""Create test repository for test setup methods."""
hook_dir = os.path.join(name, 'hooks')
template = os.path.join(name, 'input{{hooks}}') |
def make_test_repo(name):
# Set the execute bit
os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR)
return post
| def make_test_repo(name):
# Set the execute bit
os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR)
# Adding an additional pre script
if multiple_hooks:
if sys.platform.startswith('win'):
pre = 'pre_gen_project.bat'
with open(os.path.join(hook_dir, pre),... |
class TestFindHooks(object):
with utils.work_in(self.repo_path):
expected_pre = os.path.abspath('hooks/pre_gen_project.py')
actual_hook_path = hooks.find_hook('pre_gen_project')
assert expected_pre == actual_hook_path
expected_post = os.path.abspath('hooks/{}'.fo... | class TestFindHooks(object):
with utils.work_in(self.repo_path):
expected_pre = os.path.abspath('hooks/pre_gen_project.py')
actual_hook_path = hooks.find_hook('pre_gen_project')
assert expected_pre == actual_hook_path[0]
expected_post = os.path.abspath('hooks/{}'... |
class TestExternalHooks(object):
def setup_method(self, method):
"""External hooks related tests setup fixture."""
self.post_hook = make_test_repo(self.repo_path)
def teardown_method(self, method):
"""External hooks related tests teardown fixture.""" | class TestExternalHooks(object):
def setup_method(self, method):
"""External hooks related tests setup fixture."""
self.post_hook = make_test_repo(self.repo_path, multiple_hooks=True)
def teardown_method(self, method):
"""External hooks related tests teardown fixture.""" |
class TestExternalHooks(object):
os.remove('python_pre.txt')
if os.path.exists('shell_post.txt'):
os.remove('shell_post.txt')
if os.path.exists('tests/shell_post.txt'):
os.remove('tests/shell_post.txt')
if os.path.exists('tests/test-hooks/input{{hooks}}/python... | class TestExternalHooks(object):
os.remove('python_pre.txt')
if os.path.exists('shell_post.txt'):
os.remove('shell_post.txt')
if os.path.exists('shell_pre.txt'):
os.remove('shell_pre.txt')
if os.path.exists('tests/shell_post.txt'):
os.remove('tests... |
class TestExternalHooks(object):
with utils.work_in(self.repo_path):
hooks.run_hook('pre_gen_project', tests_dir, {})
assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt'))
hooks.run_hook('post_gen_project', tests_dir, {})
assert os.path.isfile(os.path.... | class TestExternalHooks(object):
with utils.work_in(self.repo_path):
hooks.run_hook('pre_gen_project', tests_dir, {})
assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt'))
assert os.path.isfile(os.path.join(tests_dir, 'shell_pre.txt'))
hooks.run_hook('... |
def ct_lt_u32(val_a, val_b):
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
def ct_gt_u32(val_a, val_b):
"""
Return 1 if val_a > val_b, 0 otherwise. Constant time. | def ct_lt_u32(val_a, val_b):
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
def ct_gt_u32(val_a, val_b):
"""
Return 1 if val_a > val_b, 0 otherwise. Constant time. |
def ct_gt_u32(val_a, val_b):
"""
return ct_lt_u32(val_b, val_a)
def ct_le_u32(val_a, val_b):
"""
Return 1 if val_a <= val_b, 0 otherwise. Constant time. | def ct_gt_u32(val_a, val_b):
"""
return ct_lt_u32(val_b, val_a)
def ct_le_u32(val_a, val_b):
"""
Return 1 if val_a <= val_b, 0 otherwise. Constant time. |
def ct_le_u32(val_a, val_b):
"""
return 1 ^ ct_gt_u32(val_a, val_b)
def ct_lsb_prop_u8(val):
"""Propagate LSB to all 8 bits of the returned byte. Constant time."""
val &= 0x01
val |= val << 1
val |= val << 2
val |= val << 4
return val
def ct_isnonzero_u32(val):
"""
Returns 1 if... | def ct_le_u32(val_a, val_b):
"""
return 1 ^ ct_gt_u32(val_a, val_b)
def ct_lsb_prop_u8(val):
"""Propagate LSB to all 8 bits of the returned int. Constant time."""
val &= 0x01
val |= val << 1
val |= val << 2
val |= val << 4
return val
def ct_lsb_prop_u16(val):
"""Propagate LSB to ... |
def ct_isnonzero_u32(val):
val &= 0xffffffff
return (val|(-val&0xffffffff)) >> 31
def ct_neq_u32(val_a, val_b):
"""
Return 1 if val_a != val_b, 0 otherwise. Constant time. | def ct_isnonzero_u32(val):
val &= 0xffffffff
return (val|(-val&0xffffffff)) >> 31
def ct_neq_u32(val_a, val_b):
"""
Return 1 if val_a != val_b, 0 otherwise. Constant time. |
def parsePEMKey(s, private=False, public=False, passwordCallback=None,
def _parseKeyHelper(key, private, public):
if private:
if not key.hasPrivateKey():
raise SyntaxError("Not a private key!")
if public:
return _createPublicKey(key)
if private:
if hasattr(key, "d"):
... | def parsePEMKey(s, private=False, public=False, passwordCallback=None,
def _parseKeyHelper(key, private, public):
if private and not key.hasPrivateKey():
raise SyntaxError("Not a private key!")
if public:
return _createPublicKey(key)
if private:
if cryptomath.m2cryptoLoaded:
... |
from .rsakey import *
from .python_rsakey import Python_RSAKey
from .compat import compatAscii2Bytes
#copied from M2Crypto.util.py, so when we load the local copy of m2
#we can still use it | from .rsakey import *
from .python_rsakey import Python_RSAKey
from .compat import compatAscii2Bytes
import sys
#copied from M2Crypto.util.py, so when we load the local copy of m2
#we can still use it |
def _rawPrivateKeyOp(self, message):
ciphertext = bytesToNumber(bytearray(string))
return ciphertext
def _rawPublicKeyOp(self, ciphertext):
data = numberToByteArray(ciphertext, numBytes(self.n))
string = m2.rsa_public_decrypt(self.rsa, bytes(data), | def _rawPrivateKeyOp(self, message):
ciphertext = bytesToNumber(bytearray(string))
return ciphertext
def _raw_private_key_op_bytes(self, message):
return bytearray(m2.rsa_private_encrypt(self.rsa, bytes(message),
m2.no_padd... |
def _rawPublicKeyOp(self, ciphertext):
message = bytesToNumber(bytearray(string))
return message
def acceptsPassword(self): return True
def write(self, password=None): | def _rawPublicKeyOp(self, ciphertext):
message = bytesToNumber(bytearray(string))
return message
def _raw_public_key_op_bytes(self, ciphertext):
return bytearray(m2.rsa_public_decrypt(self.rsa, bytes(ciphertext),
m2.no_paddi... |
def f():pass
key._hasPrivateKey = False
else:
raise SyntaxError()
return key
finally:
m2.bio_free(bio) | def f():pass
key._hasPrivateKey = False
else:
raise SyntaxError()
if key._hasPrivateKey:
if sys.version_info < (3, 0):
b64_key = str(key.write())
else:
... |
def parsePEM(s, passwordCallback=None):
elif pemSniff(s, "EC PRIVATE KEY"):
bytes = dePem(s, "EC PRIVATE KEY")
return Python_Key._parse_ecc_ssleay(bytes)
else:
raise SyntaxError("Not a PEM private key file")
@staticmethod
def _parse_pkcs8(bytes):
pars... | def parsePEM(s, passwordCallback=None):
elif pemSniff(s, "EC PRIVATE KEY"):
bytes = dePem(s, "EC PRIVATE KEY")
return Python_Key._parse_ecc_ssleay(bytes)
elif pemSniff(s, "PUBLIC KEY"):
bytes = dePem(s, "PUBLIC KEY")
return Python_Key._parse_public_key(byt... |
from . import tlshashlib as hashlib
from ..errors import MaskTooLongError, MessageTooLongError, EncodingError, \
InvalidSignature, UnknownRSAType
class RSAKey(object): | from . import tlshashlib as hashlib
from ..errors import MaskTooLongError, MessageTooLongError, EncodingError, \
InvalidSignature, UnknownRSAType
from .constanttime import ct_isnonzero_u32, ct_neq_u32, ct_lsb_prop_u8, \
ct_lsb_prop_u16, ct_lt_u32
class RSAKey(object): |
def __init__(self, n=0, e=0, key_type="rsa"):
self.e = e
# pylint: enable=invalid-name
self.key_type = key_type
raise NotImplementedError()
def __len__(self): | def __init__(self, n=0, e=0, key_type="rsa"):
self.e = e
# pylint: enable=invalid-name
self.key_type = key_type
self._key_hash = None
raise NotImplementedError()
def __len__(self): |
def RSASSA_PSS_sign(self, mHash, hAlg, sLen=0):
:type sLen: int
:param sLen: length of salt"""
EM = self.EMSA_PSS_encode(mHash, numBits(self.n) - 1, hAlg, sLen)
m = bytesToNumber(EM)
if m >= self.n:
raise MessageTooLongError("Encode output too long")
s = self.... | def RSASSA_PSS_sign(self, mHash, hAlg, sLen=0):
:type sLen: int
:param sLen: length of salt"""
EM = self.EMSA_PSS_encode(mHash, numBits(self.n) - 1, hAlg, sLen)
try:
ret = self._raw_private_key_op_bytes(EM)
except ValueError:
raise MessageTooLongError("Enc... |
def RSASSA_PSS_verify(self, mHash, S, hAlg, sLen=0):
:type sLen: int
:param sLen: Length of salt
"""
if len(bytearray(S)) != len(numberToByteArray(self.n)):
raise InvalidSignature("Invalid signature")
s = bytesToNumber(S)
m = self._rawPublicKeyOp(s)
EM... | def RSASSA_PSS_verify(self, mHash, S, hAlg, sLen=0):
:type sLen: int
:param sLen: Length of salt
"""
try:
EM = self._raw_public_key_op_bytes(S)
except ValueError:
raise InvalidSignature("Invalid signature")
result = self.EMSA_PSS_verify(mHash, EM, ... |
def _raw_pkcs1_sign(self, bytes):
if not self.hasPrivateKey():
raise AssertionError()
paddedBytes = self._addPKCS1Padding(bytes, 1)
m = bytesToNumber(paddedBytes)
if m >= self.n:
raise ValueError()
c = self._rawPrivateKeyOp(m)
sigBytes = numberToBy... | def _raw_pkcs1_sign(self, bytes):
if not self.hasPrivateKey():
raise AssertionError()
paddedBytes = self._addPKCS1Padding(bytes, 1)
return self._raw_private_key_op_bytes(paddedBytes)
def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
"""Sign the passed-i... |
def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
def _raw_pkcs1_verify(self, sigBytes, bytes):
"""Perform verification operation on raw PKCS#1 padded signature"""
if len(sigBytes) != numBytes(self.n):
return False
paddedBytes = self._addPKCS1Padding(bytes, 1)
... | def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
def _raw_pkcs1_verify(self, sigBytes, bytes):
"""Perform verification operation on raw PKCS#1 padded signature"""
try:
checkBytes = self._raw_public_key_op_bytes(sigBytes)
except ValueError:
return F... |
def encrypt(self, bytes):
:returns: A PKCS1 encryption of the passed-in data.
"""
paddedBytes = self._addPKCS1Padding(bytes, 2)
m = bytesToNumber(paddedBytes)
if m >= self.n:
raise ValueError()
c = self._rawPublicKeyOp(m)
encBytes = numberToByteArray(c... | def encrypt(self, bytes):
:returns: A PKCS1 encryption of the passed-in data.
"""
paddedBytes = self._addPKCS1Padding(bytes, 2)
return self._raw_public_key_op_bytes(paddedBytes)
def _dec_prf(self, key, label, out_len):
"""PRF for deterministic implicit rejection in the RSA d... |
def _rawPrivateKeyOp(self, message):
def _rawPublicKeyOp(self, ciphertext):
raise NotImplementedError()
def acceptsPassword(self):
"""Return True if the write() method accepts a password for use
in encrypting the private key. | def _rawPrivateKeyOp(self, message):
def _rawPublicKeyOp(self, ciphertext):
raise NotImplementedError()
def _raw_private_key_op_bytes(self, message):
n = self.n
if len(message) != numBytes(n):
raise ValueError("Message has incorrect length for the key size")
m_int = ... |
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \
ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \
ct_check_cbc_mac_and_pad, ct_compare_digest
from hypothesis import given, example
import hypothesis.strategies as st |
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \
ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \
ct_check_cbc_mac_and_pad, ct_compare_digest, ct_lsb_prop_u16
from hypothesis import given, example
import hypothesis.strategies as st |
def test_ct_lsb_prop_u8(self, i):
self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff))
self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00))
@given(i=st.integers(0,2**32 - 1))
@example(i=0)
def test_ct_isnonzero_u32(self, i): | def test_ct_lsb_prop_u8(self, i):
self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff))
self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00))
@given(i=st.integers(0, 2**16-1))
@example(i=0)
@example(i=255)
@example(i=2**16-1)
def test_ct_lsb_prop_u16(self, i):
... |
from tlslite.utils.python_rsakey import Python_RSAKey
from tlslite.utils.cryptomath import *
from tlslite.errors import *
try:
import mock
from mock import call | from tlslite.utils.python_rsakey import Python_RSAKey
from tlslite.utils.cryptomath import *
from tlslite.errors import *
from tlslite.utils.keyfactory import parsePEMKey
from tlslite.utils.compat import a2b_hex, remove_whitespace
try:
import mock
from mock import call |
def test_addPKCS1Prefix(self):
self.assertEqual(RSAKey.addPKCS1Prefix(data, 'sha1'), bytearray(
b'0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14' +
b' sha-1 hash of data ')) | def test_addPKCS1Prefix(self):
self.assertEqual(RSAKey.addPKCS1Prefix(data, 'sha1'), bytearray(
b'0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14' +
b' sha-1 hash of data '))
class TestRSADecrypt(unittest.TestCase):
@classmethod
def setUpClass(cls):
priv_key = """
-----B... |
class AuthenticationForm(forms.Form):
if username is not None and password:
self.user_cache = authenticate(self.request, username=username, password=password)
if self.user_cache is None:
# An authentication backend may reject inactive users. Check
# if the... | class AuthenticationForm(forms.Form):
if username is not None and password:
self.user_cache = authenticate(self.request, username=username, password=password)
if self.user_cache is None:
raise self.get_invalid_login_error()
else:
self.confirm_l... |
from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth.models import User
from django.test import TestCase
class AdminAuthenticationFormTests(TestCase):
@classmethod
def setUpTestData(cls): | from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
# To verify that the login form rejects inactive users, use an authentication
# backend that allows them.
@override_settings(AUTHENTICATION_BACKENDS=['django.c... |
class UserCreationFormTest(ReloadFormsMixin, TestDataMixin, TestCase):
self.assertTrue(form.is_valid())
class AuthenticationFormTest(TestDataMixin, TestCase):
def test_invalid_username(self): | class UserCreationFormTest(ReloadFormsMixin, TestDataMixin, TestCase):
self.assertTrue(form.is_valid())
# To verify that the login form rejects inactive users, use an authentication
# backend that allows them.
@override_settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBack... |
class AuthenticationFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), [str(form.error_messages['inactive'])])
def test_login_failed(self):
signal_calls = []
| class AuthenticationFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), [str(form.error_messages['inactive'])])
# Use an authentication backend that rejects inactive users.
@override_settings(AUTHENTICATION_BACKENDS=['django.contrib.aut... |
import json
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch | import json
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch |
class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None):
super().__init__(attrs={'class': 'vURLField', **(attrs or {})})
def get_context(self, name, value, attrs):
context = super().ge... | class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None, validator_class=URLValidator):
super().__init__(attrs={'class': 'vURLField', **(attrs or {})})
self.validator = validator_class()
... |
class AdminSplitDateTimeWidgetTest(SimpleTestCase):
class AdminURLWidgetTest(SimpleTestCase):
def test_render(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual( | class AdminSplitDateTimeWidgetTest(SimpleTestCase):
class AdminURLWidgetTest(SimpleTestCase):
def test_get_context_validates_url(self):
w = widgets.AdminURLFieldWidget()
for invalid in ['', '/not/a/full/url/', 'javascript:alert("Danger XSS!")']:
with self.subTest(url=invalid):
... |
class AdminURLWidgetTest(SimpleTestCase):
VALUE_RE = re.compile('value="([^"]+)"')
TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>')
w = widgets.AdminURLFieldWidget()
output = w.render('test', 'http://example.com/<sometag>some text</sometag>')
self.assertEqual(
HREF_RE.sear... | class AdminURLWidgetTest(SimpleTestCase):
VALUE_RE = re.compile('value="([^"]+)"')
TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>')
w = widgets.AdminURLFieldWidget()
output = w.render('test', 'http://example.com/<sometag>some-text</sometag>')
self.assertEqual(
HREF_RE.sear... |
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z1,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
| fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z1,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0, base=10),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
|
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
| fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0, base=10),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
|
class SymLogNorm(Normalize):
*linthresh* allows the user to specify the size of this range
(-*linthresh*, *linthresh*).
"""
def __init__(self, linthresh, linscale=1.0,
vmin=None, vmax=None, clip=False):
"""
Parameters
---------- | class SymLogNorm(Normalize):
*linthresh* allows the user to specify the size of this range
(-*linthresh*, *linthresh*).
"""
def __init__(self, linthresh, linscale=1.0, vmin=None, vmax=None,
clip=False, base=None):
"""
Parameters
---------- |
class SymLogNorm(Normalize):
linscale : float, default: 1
This allows the linear range (-*linthresh* to *linthresh*) to be
stretched relative to the logarithmic range. Its value is the
number of decades to use for each half of the linear range. For
example, when *... | class SymLogNorm(Normalize):
linscale : float, default: 1
This allows the linear range (-*linthresh* to *linthresh*) to be
stretched relative to the logarithmic range. Its value is the
number of powers of *base* (decades for base 10) to use for each
half of the li... |
class SymLogNorm(Normalize):
with np.errstate(invalid="ignore"):
masked = np.abs(a) > self.linthresh
sign = np.sign(a[masked])
log = (self._linscale_adj + np.log(np.abs(a[masked]) / self.linthresh))
log *= sign * self.linthresh
a[masked] = log
a[~masked] *= se... | class SymLogNorm(Normalize):
with np.errstate(invalid="ignore"):
masked = np.abs(a) > self.linthresh
sign = np.sign(a[masked])
log = (self._linscale_adj +
np.log(np.abs(a[masked]) / self.linthresh) / self._log_base)
log *= sign * self.linthresh
a[masked... |
class SymLogNorm(Normalize):
"""Inverse inplace Transformation."""
masked = np.abs(a) > (self.linthresh * self._linscale_adj)
sign = np.sign(a[masked])
exp = np.exp(sign * a[masked] / self.linthresh - self._linscale_adj)
exp *= sign * self.linthresh
a[masked] = exp
... | class SymLogNorm(Normalize):
"""Inverse inplace Transformation."""
masked = np.abs(a) > (self.linthresh * self._linscale_adj)
sign = np.sign(a[masked])
exp = np.power(self._base,
sign * a[masked] / self.linthresh - self._linscale_adj)
exp *= sign * self.lin... |
def test_SymLogNorm():
"""
Test SymLogNorm behavior
"""
norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2)
vals = np.array([-30, -1, 2, 6], dtype=float)
normed_vals = norm(vals)
expected = [0., 0.53980074, 0.826991, 1.02758204] | def test_SymLogNorm():
"""
Test SymLogNorm behavior
"""
norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2, base=np.e)
vals = np.array([-30, -1, 2, 6], dtype=float)
normed_vals = norm(vals)
expected = [0., 0.53980074, 0.826991, 1.02758204] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.