buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir | class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
if tmpdir:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir |
class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
... | class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
# use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT)
cmd += '%s mkdir %s' ... |
class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
basefile = self._escape(self._unquote(basefile))
basetmpdir = tmpdir if tmpdir else self.ge... | class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
basefile =... |
def makeMappingArray(N, data, gamma=1.0):
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
x = x * (N - 1)
xind = (N - 1) * np.linspace(0, 1, N) ** gamma
ind = np.searchsorted(x, xind)[1:-1]
distance = ... | def makeMappingArray(N, data, gamma=1.0):
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
if N == 1:
# convention: use the y = f(x=1) value for a 1-element lookup table
lut = np.array(y0[-1])
el... |
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
def test_resample():
"""
Github issue #6025 pointed to incorrect ListedColormap._resample; | import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
@pytest.mark.parametrize('N, result', [
(5, [1, .6, .2, .1, 0]),
(2, [1, 0]),
(1, [0]),
])
def test_makeMappingArray(N, result):
data = [(0.0, 1.0, 1.0), (0.5, 0.2, 0.2), (1.0, 0.0, 0.0)]
assert_array_almost... |
INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
LOCALHOST = ('127.0.0.1', 'localhost', '::1')
MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script')
MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw')
RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo... | INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
LOCALHOST = ('127.0.0.1', 'localhost', '::1')
MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script')
MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw')
RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo... |
from ansible.module_utils.common._collections_compat import MutableMapping, Muta
from ansible.plugins.loader import connection_loader
from ansible.utils.display import Display
display = Display()
| from ansible.module_utils.common._collections_compat import MutableMapping, Muta
from ansible.plugins.loader import connection_loader
from ansible.utils.display import Display
display = Display()
|
def namespace_facts(facts):
''' return all facts inside 'ansible_facts' w/o an ansible_ prefix '''
deprefixed = {}
for k in facts:
if k in ('ansible_local',):
# exceptions to 'deprefixing'
deprefixed[k] = module_response_deepcopy(facts[k])
else:
deprefixed... | def namespace_facts(facts):
''' return all facts inside 'ansible_facts' w/o an ansible_ prefix '''
deprefixed = {}
for k in facts:
if k.startswith('ansible_') and k not in ('ansible_local',):
deprefixed[k[8:]] = module_response_deepcopy(facts[k])
else:
deprefixed[k] =... |
import json
import yaml
from urllib.request import urlopen
from yaml import Loader, SafeLoader
import csv
from csv import register_dialect, Dialect, QUOTE_MINIMAL | import json
import yaml
from urllib.request import urlopen
from yaml import SafeLoader
import csv
from csv import register_dialect, Dialect, QUOTE_MINIMAL |
def increase_indent(self, flow=False, indentless=False):
def construct_yaml_str(self, node):
return self.construct_scalar(node)
Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
| def increase_indent(self, flow=False, indentless=False):
def construct_yaml_str(self, node):
return self.construct_scalar(node)
SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
|
def load_yaml(yaml_str):
:param unicode yaml_str:
:rtype: dict | list
"""
return yaml.load(yaml_str)
def load_yamlf(fpath, encoding): | def load_yaml(yaml_str):
:param unicode yaml_str:
:rtype: dict | list
"""
return yaml.safe_load(yaml_str)
def load_yamlf(fpath, encoding): |
def load_yamlf(fpath, encoding):
:rtype: dict | list
"""
with codecs.open(fpath, encoding=encoding) as f:
return yaml.load(f)
def load_csvf(fpath, fieldnames, encoding): | def load_yamlf(fpath, encoding):
:rtype: dict | list
"""
with codecs.open(fpath, encoding=encoding) as f:
return yaml.safe_load(f)
def load_csvf(fpath, fieldnames, encoding): |
from __future__ import division, absolute_import, unicode_literals
from owlmixin import util
class TestReplaceKeys:
def test_need_not_snake(self): |
from __future__ import division, absolute_import, unicode_literals
from yaml.constructor import ConstructorError
from owlmixin import util
import pytest
class TestReplaceKeys:
def test_need_not_snake(self): |
def test_docopt(self):
assert util.to_snake("<file_list>") == "file_list"
assert util.to_snake("-o") == "o"
assert util.to_snake("--detail-option") == "detail_option" | def test_docopt(self):
assert util.to_snake("<file_list>") == "file_list"
assert util.to_snake("-o") == "o"
assert util.to_snake("--detail-option") == "detail_option"
class TestLoadYaml:
def test(self):
actual = util.load_yaml('''
id: 1
names:
- tadashi
- aikawa
''')
... |
REQUIRES = [
"pip>=8.0.3,<20.3",
"python-slugify==4.0.1",
"pytz>=2020.5",
"pyyaml==5.3.1",
"requests==2.25.1",
"ruamel.yaml==0.15.100",
"voluptuous==0.12.1", | REQUIRES = [
"pip>=8.0.3,<20.3",
"python-slugify==4.0.1",
"pytz>=2020.5",
"pyyaml==5.4.1",
"requests==2.25.1",
"ruamel.yaml==0.15.100",
"voluptuous==0.12.1", |
class HTTP1Connection(httputil.HTTPConnection):
if content_length is not None:
return self._read_fixed_body(content_length, delegate)
if headers.get("Transfer-Encoding") == "chunked":
return self._read_chunked_body(delegate)
if self.is_client:
return self._re... | class HTTP1Connection(httputil.HTTPConnection):
if content_length is not None:
return self._read_fixed_body(content_length, delegate)
if headers.get("Transfer-Encoding", "").lower() == "chunked":
return self._read_chunked_body(delegate)
if self.is_client:
ret... |
foo=
bar
0
""".replace(b"\n", b"\r\n"))
read_stream_body(self.stream, self.stop)
headers, response = self.wait() | foo=
bar
0
""".replace(b"\n", b"\r\n"))
read_stream_body(self.stream, self.stop)
headers, response = self.wait()
self.assertEqual(json_decode(response), {u'foo': [u'bar']})
def test_chunked_request_uppercase(self):
# As per RFC 2616 section 3.6, "Transfer-Encoding" header's value i... |
def read_fixed_bytes(self, num_bytes: int) -> bytes:
"""
read_bytes = self.read(num_bytes)
if len(read_bytes) < num_bytes:
raise EOFError(read_bytes)
return read_bytes
def read_pascal_bytes(self, string_length_size: int) -> bytes: | def read_fixed_bytes(self, num_bytes: int) -> bytes:
"""
read_bytes = self.read(num_bytes)
if len(read_bytes) < num_bytes:
raise EOFError("Fewer than 'num_bytes' bytes remaining in the "
"underlying bytestream")
return read_bytes
def read_pascal_bytes... |
def from_bytes(
Raises:
ValueError: The provided byte string is not an ``openssh-key-v1``
key list or the declared key count is negative.
UserWarning: The check numbers in the decrypted private byte string
do not match (likely due to an incorrect passphra... | def from_bytes(
Raises:
ValueError: The provided byte string is not an ``openssh-key-v1``
key list, when the declared key count is negative, or when an
EOF is found while parsing the key.
UserWarning: The check numbers in the decrypted private byte strin... |
def from_bytes(
at the end of the decrypted private byte string are not as
expected.
"""
byte_stream = PascalStyleByteStream(byte_string)
header = byte_stream.read_from_format_instructions_dict(
cls.HEADER_FORMAT_INSTRUCTIONS_DICT
)
i... | def from_bytes(
at the end of the decrypted private byte string are not as
expected.
"""
try:
byte_stream = PascalStyleByteStream(byte_string)
header = byte_stream.read_from_format_instructions_dict(
cls.HEADER_FORMAT_INSTRUCTIONS_... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
author:
- xuxinkun
| from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r"""
author:
- xuxinkun
|
DOCUMENTATION = """
options:
kubectl_pod:
description:
- Pod name. Required when the host name does not match pod name.
default: ''
vars:
- name: ansible_kubectl_pod | DOCUMENTATION = """
options:
kubectl_pod:
description:
- Pod name.
- Required when the host name does not match pod name.
default: ''
vars:
- name: ansible_kubectl_pod |
DOCUMENTATION = """
- name: K8S_AUTH_POD
kubectl_container:
description:
- Container name. Required when a pod contains more than one container.
default: ''
vars:
- name: ansible_kubectl_container | DOCUMENTATION = """
- name: K8S_AUTH_POD
kubectl_container:
description:
- Container name.
- Required when a pod contains more than one container.
default: ''
vars:
- name: ansible_kubectl_container |
class Connection(ConnectionBase):
""" Build the local kubectl exec command to run cmd on remote_host
"""
local_cmd = [self.transport_cmd]
# Build command options based on doc string
doc_yaml = AnsibleLoader(self.documentation).get_single_data() | class Connection(ConnectionBase):
""" Build the local kubectl exec command to run cmd on remote_host
"""
local_cmd = [self.transport_cmd]
censored_local_cmd = [self.transport_cmd]
# Build command options based on doc string
doc_yaml = AnsibleLoader(self.documentation).ge... |
class Connection(ConnectionBase):
# Translate verify_ssl to skip_verify_ssl, and output as string
skip_verify_ssl = not self.get_option(key)
local_cmd.append(u'{0}={1}'.format(self.connection_options[key], str(skip_verify_ssl).lower()))
elif not key.endswith('... | class Connection(ConnectionBase):
# Translate verify_ssl to skip_verify_ssl, and output as string
skip_verify_ssl = not self.get_option(key)
local_cmd.append(u'{0}={1}'.format(self.connection_options[key], str(skip_verify_ssl).lower()))
censored_local_cmd.... |
class Connection(ConnectionBase):
""" Run a command in the container """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
local_cmd = self._build_exec_cmd([self._play_context.executable, '-c', cmd])
display.vvv("EXEC %s" % (local_cmd,), host=self._play_cont... | class Connection(ConnectionBase):
""" Run a command in the container """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
local_cmd, censored_local_cmd = self._build_exec_cmd([self._play_context.executable, '-c', cmd])
display.vvv("EXEC %s" % (censored_loca... |
class Connection(ConnectionBase):
count = ' count=0'
else:
count = ''
args = self._build_exec_cmd([self._play_context.executable, "-c", "dd of=%s bs=%s%s" % (out_path, BUFSIZE, count)])
args = [to_bytes(i, errors='surrogate_or_strict') for i in args]
... | class Connection(ConnectionBase):
count = ' count=0'
else:
count = ''
args, dummy = self._build_exec_cmd([self._play_context.executable, "-c", "dd of=%s bs=%s%s" % (out_path, BUFSIZE, count)])
args = [to_bytes(i, errors='surrogate_or_strict') for i in ... |
class Connection(ConnectionBase):
# kubectl doesn't have native support for fetching files from
# running containers, so we use kubectl exec to implement this
args = self._build_exec_cmd([self._play_context.executable, "-c", "dd if=%s bs=%s" % (in_path, BUFSIZE)])
args = [to_bytes(i, er... | class Connection(ConnectionBase):
# kubectl doesn't have native support for fetching files from
# running containers, so we use kubectl exec to implement this
args, dummy = self._build_exec_cmd([self._play_context.executable, "-c", "dd if=%s bs=%s" % (in_path, BUFSIZE)])
args = [to_byte... |
def generate_tokens(readline):
stashed = tok
continue
if token == 'def':
if (stashed
and stashed[0] == NAME
and stashed[1] == 'async'):
... | def generate_tokens(readline):
stashed = tok
continue
if token in ('def', 'for'):
if (stashed
and stashed[0] == NAME
and stashed[1] == 'async'):
... |
class BlackTestCase(unittest.TestCase):
self.assertFormatEqual(expected, actual)
black.assert_stable(source, actual, line_length=ll, mode=mode)
@patch("black.dump_to_file", dump_to_stderr)
def test_fmtonoff(self) -> None:
source, expected = read_data("fmtonoff") | class BlackTestCase(unittest.TestCase):
self.assertFormatEqual(expected, actual)
black.assert_stable(source, actual, line_length=ll, mode=mode)
@patch("black.dump_to_file", dump_to_stderr)
def test_python37(self) -> None:
source, expected = read_data("python37")
actual = fs(sour... |
from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
from pandas.core.series import Series
from pandas.io.formats.printing import pprint_thi... | from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
from pandas.core.indexes.base import InvalidIndexError
from pandas.core.series import Se... |
def get_grouper(
items = obj._data.items
try:
items.get_loc(key)
except (KeyError, TypeError):
# TypeError shows up here if we pass e.g. Int64Index
return False
| def get_grouper(
items = obj._data.items
try:
items.get_loc(key)
except (KeyError, TypeError, InvalidIndexError):
# TypeError shows up here if we pass e.g. Int64Index
return False
|
from pandas.core.arrays.datetimes import (
validate_tz_from_dtype,
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, maybe_extract_name
from pandas.core.indexes.datetimelike import (
DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin, | from pandas.core.arrays.datetimes import (
validate_tz_from_dtype,
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, maybe_extract_name
from pandas.core.indexes.datetimelike import (
DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin, |
class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
if isinstance(key, (datetime, np.datetime64)):
return self.get_value_maybe_box(series, key) | class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
if not is_scalar(key):
raise InvalidIndexError(key)
if isinstance(key, (datetime, np.datetime64)):
... |
class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
-------
loc : int
"""
if is_valid_nat_for_dtype(key, self.dtype):
key = NaT
| class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
-------
loc : int
"""
if not is_scalar(key):
raise InvalidIndexError(key)
if is_valid_nat_for_dtype(key, self.dtype):
key = NaT
|
class MultiIndex(Index):
indexer = self._get_level_indexer(key, level=level)
new_index = maybe_mi_droplevels(indexer, [0], drop_level)
return indexer, new_index
except TypeError:
pass
if not any(isinstance(k, slice) for... | class MultiIndex(Index):
indexer = self._get_level_indexer(key, level=level)
new_index = maybe_mi_droplevels(indexer, [0], drop_level)
return indexer, new_index
except (TypeError, InvalidIndexError):
pass
if not any(isi... |
class Series(base.IndexOpsMixin, generic.NDFrame):
self[:] = value
else:
self.loc[key] = value
except TypeError as e:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): | class Series(base.IndexOpsMixin, generic.NDFrame):
self[:] = value
else:
self.loc[key] = value
except InvalidIndexError:
# e.g. slice
self._set_with(key, value)
except TypeError as e:
if isinstance(key, tuple) and not isins... |
import pytz
import pandas as pd
from pandas import DatetimeIndex, Index, Timestamp, date_range, notna
import pandas._testing as tm
from pandas.tseries.offsets import BDay, CDay
| import pytz
import pandas as pd
from pandas import DatetimeIndex, Index, Timestamp, date_range, notna
import pandas._testing as tm
from pandas.core.indexes.base import InvalidIndexError
from pandas.tseries.offsets import BDay, CDay
|
class TestDatetimeIndex:
with pytest.raises(KeyError, match="'foobar'"):
idx.get_loc("foobar")
with pytest.raises(TypeError):
idx.get_loc(slice(2))
idx = pd.to_datetime(["2000-01-01", "2000-01-04"]) | class TestDatetimeIndex:
with pytest.raises(KeyError, match="'foobar'"):
idx.get_loc("foobar")
with pytest.raises(InvalidIndexError, match=r"slice\(None, 2, None\)"):
idx.get_loc(slice(2))
idx = pd.to_datetime(["2000-01-01", "2000-01-04"]) |
class Model(Container):
val_enqueuer.start(workers=workers, max_queue_size=max_queue_size)
validation_generator = val_enqueuer.get()
else:
validation_generator = validation_data
else:
if len(v... | class Model(Container):
val_enqueuer.start(workers=workers, max_queue_size=max_queue_size)
validation_generator = val_enqueuer.get()
else:
if isinstance(validation_data, Sequence):
validation_generato... |
class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
output_generator = generator
callback_model.stop_training = False
# Construct epoch logs. | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter(generator)
else:
output_generator = g... |
class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
output_generator = generator
while steps_done < steps:
generator_output = next(output_generator) | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter(generator)
else:
output_generator = g... |
class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
output_generator = generator
if verbose == 1:
progbar = Progbar(target=steps) | class Model(Container):
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
else:
if is_sequence:
output_generator = iter(generator)
else:
output_generator = g... |
class Sequence(object):
"""
pass
# Global variables to be shared across processes
_SHARED_SEQUENCES = {} | class Sequence(object):
"""
pass
def __iter__(self):
"""Create an infinite generator that iterate over the Sequence."""
while True:
for item in (self[i] for i in range(len(self))):
yield item
# Global variables to be shared across processes
_SHARED_SEQU... |
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense
from keras.utils.test_utils import keras_test
STEPS_PER_EPOCH = 100
STEPS = 100
WORKERS = 4
@pytest.fixture
def in_tmpdir(tmpdir):
"""Runs a function in a temporary directory. | import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense
from keras.utils.test_utils import keras_test
from keras.utils import Sequence
STEPS_PER_EPOCH = 100
STEPS = 100
WORKERS = 4
class DummySequence(Sequence):
def __getitem__(self, idx):
return np.zeros([10, 2]), np.o... |
def test_multiprocessing_training():
workers=0,
use_multiprocessing=False)
# Test invalid use cases
def invalid_generator():
while True: | def test_multiprocessing_training():
workers=0,
use_multiprocessing=False)
# - For Sequence
model.fit_generator(DummySequence(),
steps_per_epoch=STEPS_PER_EPOCH,
validation_data=custom_generator(True),
... |
def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S)
re_chars = re.compile(r'<.*?>|(.)', re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A... | def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<[^>]+?>|([^<>\s]+)', re.S)
re_chars = re.compile(r'<[^>]+?>|(.)', re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|... |
class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three <br>four ...</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... | class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three ...</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... |
class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')
def test_truncate_words(self):
truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
self.assert... | class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')
def test_truncate_chars_html(self):
perf_test_values = [
(('</a' + '\t' * 50000) + '//>', None),
('&' ... |
class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo...</i>', truncator.words(3, '...', html=True))
truncator = text.Truncator('<p>I <3 python, what about you... | class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo...</i>', truncator.words(3, '...', html=True))
truncator = text.Truncator('<p>I <3 python, what about you... |
def is_safe_url(url, host=None):
url = url.strip()
if not url:
return False
# Chrome treats \ completely as /
url = url.replace('\\', '/')
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsa... | def is_safe_url(url, host=None):
url = url.strip()
if not url:
return False
# Chrome treats \ completely as / in paths but it could be part of some
# basic auth credentials so we need to check both URLs.
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
def ... |
class TestUtilsHttp(unittest.TestCase):
'javascript:alert("XSS")',
'\njavascript:alert(x)',
'\x08//example.com',
'\n'):
self.assertFalse(http.is_safe_url(bad_url, host='testserver'), "%s should be blocked" % bad_... | class TestUtilsHttp(unittest.TestCase):
'javascript:alert("XSS")',
'\njavascript:alert(x)',
'\x08//example.com',
r'http://otherserver\@example.com',
r'http:\\testserver\@example.com',
... |
class TestUtilsHttp(unittest.TestCase):
'https://testserver/',
'HTTPS://testserver/',
'//testserver/',
'/url%20with%20spaces/'):
self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s should be allowed" % good_ur... | class TestUtilsHttp(unittest.TestCase):
'https://testserver/',
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/'):
self.assertTrue(http.is_... |
import asyncio
from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from functools import partial
import keyword
import os
from pathlib import Path
import tokenize
import sys
from typing import (
Dict, Generic, Iterable, Iterator, List, Optional, Set, Tuple, Typ... | import asyncio
from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from functools import partial, wraps
import keyword
import os
from pathlib import Path
import tokenize
import sys
from typing import (
Callable,
Dict,
Generic,
Iterable,
Iterator... |
Depth = int
NodeType = int
LeafID = int
Priority = int
LN = Union[Leaf, Node]
out = partial(click.secho, bold=True, err=True)
err = partial(click.secho, fg='red', err=True)
| Depth = int
NodeType = int
LeafID = int
Priority = int
Index = int
LN = Union[Leaf, Node]
SplitFunc = Callable[['Line', bool], Iterator['Line']]
out = partial(click.secho, bold=True, err=True)
err = partial(click.secho, fg='red', err=True)
|
class Line:
depth: int = 0
leaves: List[Leaf] = Factory(list)
comments: Dict[LeafID, Leaf] = Factory(dict)
bracket_tracker: BracketTracker = Factory(BracketTracker)
inside_brackets: bool = False
has_for: bool = False | class Line:
depth: int = 0
leaves: List[Leaf] = Factory(list)
comments: List[Tuple[Index, Leaf]] = Factory(list)
bracket_tracker: BracketTracker = Factory(BracketTracker)
inside_brackets: bool = False
has_for: bool = False |
class Line:
self.bracket_tracker.mark(leaf)
self.maybe_remove_trailing_comma(leaf)
self.maybe_increment_for_loop_variable(leaf)
if self.maybe_adapt_standalone_comment(leaf):
return
if not self.append_comment(leaf):
self.leaves.append(l... | class Line:
self.bracket_tracker.mark(leaf)
self.maybe_remove_trailing_comma(leaf)
self.maybe_increment_for_loop_variable(leaf)
if not self.append_comment(leaf):
self.leaves.append(leaf)
def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
... |
class Line:
and self.leaves[0].value == 'yield'
)
def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
"""Remove trailing comma if there is one and it's safe."""
if not ( | class Line:
and self.leaves[0].value == 'yield'
)
@property
def contains_standalone_comments(self) -> bool:
"""If so, needs to be split before emitting."""
for leaf in self.leaves:
if leaf.type == STANDALONE_COMMENT:
return True
return Fa... |
class Line:
return False
if closing.type == token.RBRACE:
self.leaves.pop()
return True
if closing.type == token.RSQB:
comma = self.leaves[-1]
if comma.parent and comma.parent.type == syms.listmaker:
self.leaves.pop()
... | class Line:
return False
if closing.type == token.RBRACE:
self.remove_trailing_comma()
return True
if closing.type == token.RSQB:
comma = self.leaves[-1]
if comma.parent and comma.parent.type == syms.listmaker:
self.remove_tra... |
class Line:
break
if commas > 1:
self.leaves.pop()
return True
return False | class Line:
break
if commas > 1:
self.remove_trailing_comma()
return True
return False |
class Line:
return False
def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool:
"""Hack a standalone comment to act as a trailing comment for line splitting.
If this line has brackets and a standalone `comment`, we need to adapt
it to be able to still reformat the line.
... | class Line:
return False
def append_comment(self, comment: Leaf) -> bool:
"""Add an inline or standalone comment to the line."""
if (
comment.type == STANDALONE_COMMENT
and self.bracket_tracker.any_open_brackets()
):
comment.prefix = ''
... |
class Line:
res = f'{first.prefix}{indent}{first.value}'
for leaf in leaves:
res += str(leaf)
for comment in self.comments.values():
res += str(comment)
return res + '\n'
| class Line:
res = f'{first.prefix}{indent}{first.value}'
for leaf in leaves:
res += str(leaf)
for _, comment in self.comments:
res += str(comment)
return res + '\n'
|
class UnformattedLines(Line):
"""Does nothing and returns False."""
return False
def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool:
"""Does nothing and returns False."""
return False
@dataclass
class EmptyLineTracker: | class UnformattedLines(Line):
"""Does nothing and returns False."""
return False
@dataclass
class EmptyLineTracker: |
def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
if isinstance(line, UnformattedLines):
yield line
return
line_str = str(line).strip('\n')
if len(line_str) <= line_length and '\n' not in line_str:
yie... | def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
if isinstance(line, UnformattedLines) or line.is_comment:
yield line
return
line_str = str(line).strip('\n')
if (
len(line_str) <= line_length
... |
def split_line(
# split altogether.
result: List[Line] = []
try:
for l in split_func(line, py36=py36):
if str(l).strip('\n') == line_str:
raise CannotSplit("Split function returned an unchanged result")
| def split_line(
# split altogether.
result: List[Line] = []
try:
for l in split_func(line, py36):
if str(l).strip('\n') == line_str:
raise CannotSplit("Split function returned an unchanged result")
|
def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
):
for leaf in leaves:
result.append(leaf, preformatted=True)
comment_after = line.comments.get(id(leaf))
if comment_after:
result.append(comment_after, preformatted=True)
bracket_s... | def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
):
for leaf in leaves:
result.append(leaf, preformatted=True)
for comment_after in line.comments_after(leaf):
result.append(comment_after, preformatted=True)
bracket_split_succeeded_or_raise(he... |
def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
):
for leaf in leaves:
result.append(leaf, preformatted=True)
comment_after = line.comments.get(id(leaf))
if comment_after:
result.append(comment_after, preformatted=True)
bracket_... | def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
):
for leaf in leaves:
result.append(leaf, preformatted=True)
for comment_after in line.comments_after(leaf):
result.append(comment_after, preformatted=True)
bracket_split_succeeded_or_raise(h... |
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None
)
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
"""Split according to delimiters of the highest priority.
This kind of split doesn't increase indentation.
If `py36` is True, the split wil... | def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None
)
def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
"""Normalize prefix of the first leaf in every line returned by `split_func`.
This is a decorator over relevant split functions.
"""
@wrap... |
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
lowest_depth = sys.maxsize
trailing_comma_safe = True
for leaf in line.leaves:
current_line.append(leaf, preformatted=True)
comment_after = l... | def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
lowest_depth = sys.maxsize
trailing_comma_safe = True
def append_to_line(leaf: Leaf) -> Iterator[Line]:
"""Append `leaf` to current line or to new l... |
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
trailing_comma_safe = trailing_comma_safe and py36
leaf_priority = delimiters.get(id(leaf))
if leaf_priority == delimiter_priority:
normalize_prefix(current_line.leaves[0], inside_brackets=True)
yi... | def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
trailing_comma_safe = trailing_comma_safe and py36
leaf_priority = delimiters.get(id(leaf))
if leaf_priority == delimiter_priority:
yield current_line
current_line = Line(depth=line.depth, inside_... |
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
and trailing_comma_safe
):
current_line.append(Leaf(token.COMMA, ','))
normalize_prefix(current_line.leaves[0], inside_brackets=True)
yield current_line
| def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
and trailing_comma_safe
):
current_line.append(Leaf(token.COMMA, ','))
yield current_line
@dont_increase_indentation
def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]:
"""Spl... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_cantfit(self) -> None:
source, expected = read_data('cantfit') | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_comments3(self) -> None:
source, expected = read_data('comments3')
actual = fs(source)
... |
from xmlrpc.server import DocXMLRPCServer
import http.client
import sys
import threading
import unittest | from xmlrpc.server import DocXMLRPCServer
import http.client
import re
import sys
import threading
import unittest |
def test_annotations(self):
b'method_annotation</strong></a>(x: bytes)</dt></dl>'),
response.read())
if __name__ == '__main__':
unittest.main() | def test_annotations(self):
b'method_annotation</strong></a>(x: bytes)</dt></dl>'),
response.read())
def test_server_title_escape(self):
# bpo-38243: Ensure that the server title and documentation
# are escaped for HTML.
self.serv.set_server_title('test_title<script... |
def export_add(self, x, y):
from http.server import BaseHTTPRequestHandler
from functools import partial
from inspect import signature
import http.server
import socketserver
import sys | def export_add(self, x, y):
from http.server import BaseHTTPRequestHandler
from functools import partial
from inspect import signature
import html
import http.server
import socketserver
import sys |
def generate_html_documentation(self):
methods
)
return documenter.page(self.server_title, documentation)
class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
"""XML-RPC and documentation request handler class. | def generate_html_documentation(self):
methods
)
return documenter.page(html.escape(self.server_title), documentation)
class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
"""XML-RPC and documentation request handler class. |
from xmlrpc.server import DocXMLRPCServer
import http.client
import sys
import threading
import unittest | from xmlrpc.server import DocXMLRPCServer
import http.client
import re
import sys
import threading
import unittest |
def test_annotations(self):
b'method_annotation</strong></a>(x: bytes)</dt></dl>'),
response.read())
if __name__ == '__main__':
unittest.main() | def test_annotations(self):
b'method_annotation</strong></a>(x: bytes)</dt></dl>'),
response.read())
def test_server_title_escape(self):
# bpo-38243: Ensure that the server title and documentation
# are escaped for HTML.
self.serv.set_server_title('test_title<script... |
def export_add(self, x, y):
from http.server import BaseHTTPRequestHandler
from functools import partial
from inspect import signature
import http.server
import socketserver
import sys | def export_add(self, x, y):
from http.server import BaseHTTPRequestHandler
from functools import partial
from inspect import signature
import html
import http.server
import socketserver
import sys |
def generate_html_documentation(self):
methods
)
return documenter.page(self.server_title, documentation)
class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
"""XML-RPC and documentation request handler class. | def generate_html_documentation(self):
methods
)
return documenter.page(html.escape(self.server_title), documentation)
class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
"""XML-RPC and documentation request handler class. |
class TestUtil(unittest.TestCase):
"1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
}''')
def test_js_to_json_edgecases(self):
on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"}) | class TestUtil(unittest.TestCase):
"1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
}''')
inp = '''{"foo":101}'''
self.assertEqual(js_to_json(inp), '''{"foo":101}''')
def test_js_to_json_edgecases(self):
on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
... |
def js_to_json(code):
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
/\*.*?\*/|,(?=\s*[\]}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
[0-9]+(?=\s*:)
''', fix_kv, code)
| def js_to_json(code):
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
/\*.*?\*/|,(?=\s*[\]}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
[0-9]+(?=\s*:)
''', fix_kv, code)
|
def read_fixed_bytes(self, num_bytes: int) -> bytes:
"""
read_bytes = self.read(num_bytes)
if len(read_bytes) < num_bytes:
raise EOFError(read_bytes)
return read_bytes
def read_pascal_bytes(self, string_length_size: int) -> bytes: | def read_fixed_bytes(self, num_bytes: int) -> bytes:
"""
read_bytes = self.read(num_bytes)
if len(read_bytes) < num_bytes:
raise EOFError("Fewer than 'num_bytes' bytes remaining in the "
"underlying bytestream")
return read_bytes
def read_pascal_bytes... |
LOGGING_CONFIG_DEFAULTS = dict(
version=1,
disable_existing_loggers=False,
loggers={
"root": {"level": "INFO", "handlers": ["console"]},
"sanic.error": {
"level": "INFO",
"handlers": ["error_console"], | LOGGING_CONFIG_DEFAULTS = dict(
version=1,
disable_existing_loggers=False,
loggers={
"sanic.root": {"level": "INFO", "handlers": ["console"]},
"sanic.error": {
"level": "INFO",
"handlers": ["error_console"], |
def test_logging_defaults():
reset_logging()
app = Sanic("test_logging")
for fmt in [h.formatter for h in logging.getLogger('root').handlers]:
assert fmt._fmt == LOGGING_CONFIG_DEFAULTS['formatters']['generic']['format']
for fmt in [h.formatter for h in logging.getLogger('sanic.error').handler... | def test_logging_defaults():
reset_logging()
app = Sanic("test_logging")
for fmt in [h.formatter for h in logging.getLogger('sanic.root').handlers]:
assert fmt._fmt == LOGGING_CONFIG_DEFAULTS['formatters']['generic']['format']
for fmt in [h.formatter for h in logging.getLogger('sanic.error').h... |
def test_logging_pass_customer_logconfig():
app = Sanic("test_logging", log_config=modified_config)
for fmt in [h.formatter for h in logging.getLogger('root').handlers]:
assert fmt._fmt == modified_config['formatters']['generic']['format']
for fmt in [h.formatter for h in logging.getLogger('sanic... | def test_logging_pass_customer_logconfig():
app = Sanic("test_logging", log_config=modified_config)
for fmt in [h.formatter for h in logging.getLogger('sanic.root').handlers]:
assert fmt._fmt == modified_config['formatters']['generic']['format']
for fmt in [h.formatter for h in logging.getLogger(... |
def test_logging_pass_customer_logconfig():
def test_log_connection_lost(app, debug, monkeypatch):
""" Should not log Connection lost exception on non debug """
stream = StringIO()
root = logging.getLogger('root')
root.addHandler(logging.StreamHandler(stream))
monkeypatch.setattr(sanic.server, 'logg... | def test_logging_pass_customer_logconfig():
def test_log_connection_lost(app, debug, monkeypatch):
""" Should not log Connection lost exception on non debug """
stream = StringIO()
root = logging.getLogger('sanic.root')
root.addHandler(logging.StreamHandler(stream))
monkeypatch.setattr(sanic.server,... |
def test_log_connection_lost(app, debug, monkeypatch):
assert 'Connection lost before response written @' in log
else:
assert 'Connection lost before response written @' not in log | def test_log_connection_lost(app, debug, monkeypatch):
assert 'Connection lost before response written @' in log
else:
assert 'Connection lost before response written @' not in log
def test_logging_modified_root_logger_config():
reset_logging()
modified_config = LOGGING_CONFIG_DEFAULTS
... |
import grp
import os
import re
import platform
import pwd
import shutil
import socket
import time
import re
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import load_platform_subclass, AnsibleModule
try: | import grp
import os
import re
import platform
import pty
import pwd
import select
import shutil
import socket
import subprocess
import time
from ansible.module_utils._text import to_native, to_bytes, to_text
from ansible.module_utils.basic import load_platform_subclass, AnsibleModule
try: |
class User(object):
cmd.append(self.ssh_comment)
cmd.append('-f')
cmd.append(ssh_key_file)
cmd.append('-N')
if self.ssh_passphrase is not None:
cmd.append(self.ssh_passphrase)
else:
cmd.append('')
(rc, out, err) = self.execute_command(cmd)... | class User(object):
cmd.append(self.ssh_comment)
cmd.append('-f')
cmd.append(ssh_key_file)
if self.ssh_passphrase is not None:
if self.module.check_mode:
self.module.debug('In check mode, would have run: "%s"' % cmd)
return (0, '', '')
... |
setup(
author='Jeff Knupp',
tests_require=['pytest', 'pytest-cov', 'pytest-flask>=0.4.0'],
install_requires=[
'Flask>=0.10.1',
'Flask-SQLAlchemy>=1.0',
'SQLAlchemy==1.2.12',
'Flask-Admin>=1.0.9', | setup(
author='Jeff Knupp',
tests_require=['pytest', 'pytest-cov', 'pytest-flask>=0.4.0'],
install_requires=[
'Flask>=1.0.2',
'Flask-SQLAlchemy>=1.0',
'SQLAlchemy==1.2.12',
'Flask-Admin>=1.0.9', |
async def _has_watch_regex_match(self, text: str) -> Tuple[Union[bool, re.Match]
text = self.clean_input(text)
# Make sure it's not a URL
if URL_RE.search(text):
return False, None
watchlist_patterns = self._get_filterlist_items('filter_token', allowed=False)
for p... | async def _has_watch_regex_match(self, text: str) -> Tuple[Union[bool, re.Match]
text = self.clean_input(text)
watchlist_patterns = self._get_filterlist_items('filter_token', allowed=False)
for pattern in watchlist_patterns:
match = re.search(pattern, text, flags=re.IGNORECASE) |
from cryptography.hazmat.primitives.ciphers import modes
class _CipherContext(object):
_ENCRYPT = 1
_DECRYPT = 0
_MAX_CHUNK_SIZE = 2 ** 31 - 1
def __init__(self, backend, cipher, mode, operation):
self._backend = backend | from cryptography.hazmat.primitives.ciphers import modes
class _CipherContext(object):
_ENCRYPT = 1
_DECRYPT = 0
_MAX_CHUNK_SIZE = 2 ** 30 - 1
def __init__(self, backend, cipher, mode, operation):
self._backend = backend |
import json
import yaml
from urllib.request import urlopen
from yaml import Loader, SafeLoader
import csv
from csv import register_dialect, Dialect, QUOTE_MINIMAL | import json
import yaml
from urllib.request import urlopen
from yaml import SafeLoader
import csv
from csv import register_dialect, Dialect, QUOTE_MINIMAL |
def increase_indent(self, flow=False, indentless=False):
def construct_yaml_str(self, node):
return self.construct_scalar(node)
Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
| def increase_indent(self, flow=False, indentless=False):
def construct_yaml_str(self, node):
return self.construct_scalar(node)
SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
|
def load_yaml(yaml_str):
:param unicode yaml_str:
:rtype: dict | list
"""
return yaml.load(yaml_str)
def load_yamlf(fpath, encoding): | def load_yaml(yaml_str):
:param unicode yaml_str:
:rtype: dict | list
"""
return yaml.safe_load(yaml_str)
def load_yamlf(fpath, encoding): |
def load_yamlf(fpath, encoding):
:rtype: dict | list
"""
with codecs.open(fpath, encoding=encoding) as f:
return yaml.load(f)
def load_csvf(fpath, fieldnames, encoding): | def load_yamlf(fpath, encoding):
:rtype: dict | list
"""
with codecs.open(fpath, encoding=encoding) as f:
return yaml.safe_load(f)
def load_csvf(fpath, fieldnames, encoding): |
from __future__ import division, absolute_import, unicode_literals
from owlmixin import util
class TestReplaceKeys:
def test_need_not_snake(self): |
from __future__ import division, absolute_import, unicode_literals
from yaml.constructor import ConstructorError
from owlmixin import util
import pytest
class TestReplaceKeys:
def test_need_not_snake(self): |
def test_docopt(self):
assert util.to_snake("<file_list>") == "file_list"
assert util.to_snake("-o") == "o"
assert util.to_snake("--detail-option") == "detail_option" | def test_docopt(self):
assert util.to_snake("<file_list>") == "file_list"
assert util.to_snake("-o") == "o"
assert util.to_snake("--detail-option") == "detail_option"
class TestLoadYaml:
def test(self):
actual = util.load_yaml('''
id: 1
names:
- tadashi
- aikawa
''')
... |
class LightSource:
.format(lookup.keys)) from err
# Only apply result where hillshade intensity isn't masked
if hasattr(intensity, 'mask'):
mask = intensity.mask[..., 0]
for i in range(3):
blend[..., i][mask] = rgb[..., i][mask] | class LightSource:
.format(lookup.keys)) from err
# Only apply result where hillshade intensity isn't masked
if np.ma.is_masked(intensity):
mask = intensity.mask[..., 0]
for i in range(3):
blend[..., i][mask] = rgb[..., i][mask] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.