buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin): ) _engine_type = libindex.DatetimeEngine _tz = None _freq = None
class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin): ) _engine_type = libindex.DatetimeEngine _supports_partial_string_indexing = True _tz = None _freq = None
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): _data = None _engine_type = libindex.PeriodEngine # ------------------------------------------------------------------------ # Index Constructors
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): _data = None _engine_type = libindex.PeriodEngine _supports_partial_string_indexing = True # ------------------------------------------------------------------------ # Index Constructors
class _LocIndexer(_LocationIndexer): if isinstance(ax, MultiIndex): return False if not ax.is_unique: return False
class _LocIndexer(_LocationIndexer): if isinstance(ax, MultiIndex): return False if isinstance(k, str) and ax._supports_partial_string_indexing: # partial string indexing, df.loc['2000', 'A'] # should not be considered scalar retur...
class _LocIndexer(_LocationIndexer): """Translate any partial string timestamp matches in key, returning the new key (GH 10331)""" if isinstance(labels, MultiIndex): if isinstance(key, str) and labels.levels[0].is_all_dates: # Convert key '2016-01-01' to ...
class _LocIndexer(_LocationIndexer): """Translate any partial string timestamp matches in key, returning the new key (GH 10331)""" if isinstance(labels, MultiIndex): if ( isinstance(key, str) and labels.levels[0]._supports_partial_string_indexing ...
class _LocIndexer(_LocationIndexer): # (..., slice('2016-01-01', '2016-01-01', None), ...) new_key = [] for i, component in enumerate(key): if isinstance(component, str) and labels.levels[i].is_all_dates: new_key.append(slice(co...
class _LocIndexer(_LocationIndexer): # (..., slice('2016-01-01', '2016-01-01', None), ...) new_key = [] for i, component in enumerate(key): if ( isinstance(component, str) and labels.levels[i]._supports_p...
def convert_to_index_sliceable(obj, key): # We might have a datetimelike string that we can translate to a # slice here via partial string indexing if idx.is_all_dates: try: return idx._get_string_slice(key) except (KeyError, ValueError, NotImplementedErr...
def convert_to_index_sliceable(obj, key): # We might have a datetimelike string that we can translate to a # slice here via partial string indexing if idx._supports_partial_string_indexing: try: return idx._get_string_slice(key) except (KeyError, ValueErr...
class TestSlicing: with pytest.raises(ValueError, match="The index must be timezone"): df = df.tz_localize(None) df[start:end]
class TestSlicing: with pytest.raises(ValueError, match="The index must be timezone"): df = df.tz_localize(None) df[start:end] def test_slice_reduce_to_series(self): # GH 27516 df = pd.DataFrame( {"A": range(24)}, index=pd.date_range("2000", periods=24, f...
import warnings import numpy as np from pandas._libs import NaT, Timestamp, lib, tslib import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare
import warnings import numpy as np from pandas._libs import NaT, Timestamp, lib, tslib, writers import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare
class Block(PandasObject): mask = isna(values) if not self.is_object and not quoting: values = values.astype(str) else: values = np.array(values, dtype="object")
class Block(PandasObject): mask = isna(values) if not self.is_object and not quoting: itemsize = writers.word_len(na_rep) values = values.astype("<U{size}".format(size=itemsize)) else: values = np.array(values, dtype="object")
z assert len(zp.filelist) == 1 archived_file = os.path.basename(zp.filelist[0].filename) assert archived_file == expected_arcname
z assert len(zp.filelist) == 1 archived_file = os.path.basename(zp.filelist[0].filename) assert archived_file == expected_arcname @pytest.mark.parametrize("df_new_type", ["Int64"]) def test_to_csv_na_rep_long_string(self, df_new_type): # see gh-25099 df = pd....
from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
from urllib.parse import quote from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, str): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, str): exception_repr = message context = { 'request_path': quote(request.path), 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) con...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested resource was not found on this server.</p>') body = template.render(Context(context)) content_type = 't...
import unittest from django.core.exceptions import ImproperlyConfigured
import sys import unittest from django.core.exceptions import ImproperlyConfigured
try: except ImportError: # Python < 3.5 HTTPStatus = None class HandlerTests(SimpleTestCase):
try: except ImportError: # Python < 3.5 HTTPStatus = None PY37 = sys.version_info >= (3, 7, 0) class HandlerTests(SimpleTestCase):
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertContains(response, '~%A9helloworld', status_code=404) response = self.client.get('d%aao%aaw%aan%aal%aao%aaa%aad%aa/') self.assertContains(response, 'd%AAo...
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertEqual(response.status_code, 404) self.assertEqual(response.context['request_path'], '/~%25A9helloworld' if PY37 else '/%7E%25A9helloworld') response = sel...
class RadialLocator(mticker.Locator): :class:`~matplotlib.ticker.Locator` (which may be different depending on the scale of the *r*-axis. """ def __init__(self, base, axes=None): self.base = base self._axes = axes
class RadialLocator(mticker.Locator): :class:`~matplotlib.ticker.Locator` (which may be different depending on the scale of the *r*-axis. """ def __init__(self, base, axes=None): self.base = base self._axes = axes
class RadialLocator(mticker.Locator): # docstring inherited return self.base.refresh() def view_limits(self, vmin, vmax): vmin, vmax = self.base.view_limits(vmin, vmax) if vmax > vmin:
class RadialLocator(mticker.Locator): # docstring inherited return self.base.refresh() def nonsingular(self, vmin, vmax): # docstring inherited return ((0, 1) if (vmin, vmax) == (-np.inf, np.inf) # Init. limits. else self.base.nonsingular(vmin, vmax)) def view_...
def test_log_scales_invalid(): ax.set_ylim(-1, 10) @image_comparison(['stackplot_test_image', 'stackplot_test_image']) def test_stackplot(): fig = plt.figure()
def test_log_scales_invalid(): ax.set_ylim(-1, 10) def test_polar_no_data(): plt.subplot(projection="polar") ax = plt.gca() assert ax.get_rmin() == 0 and ax.get_rmax() == 1 plt.close("all") # Used to behave differently (by triggering an autoscale with no data). plt.polar() ax = plt...
# All kinds of schemes besides just javascript: that can cause # execution: _is_image_dataurl = re.compile( r'^data:image/.+;base64', re.I).search _is_possibly_malicious_scheme = re.compile( r'(?:javascript|jscript|livescript|vbscript|data|about|mocha):', re.I).search def _is_javascript_scheme(s): if _...
# All kinds of schemes besides just javascript: that can cause # execution: _find_image_dataurls = re.compile( r'^data:image/(.+);base64,', re.I).findall _is_possibly_malicious_scheme = re.compile( r'(javascript|jscript|livescript|vbscript|data|about|mocha):', re.I).findall # SVG images can contain script ...
import unittest from lxml.tests.common_imports import make_doctest
import base64 import gzip import unittest from lxml.tests.common_imports import make_doctest
def test_sneaky_import_in_style(self): cleaned, "%s -> %s" % (style_code, cleaned)) def test_formaction_attribute_in_button_input(self): # The formaction attribute overrides the form's action and should be # treated as a malicious link attribute
def test_sneaky_import_in_style(self): cleaned, "%s -> %s" % (style_code, cleaned)) def test_svg_data_links(self): # Remove SVG images with potentially insecure content. svg = b'<svg onload="alert(123)" />' svgz = gzip.compress(svg) svg_b64 = base64...
class tqdm(Comparable): # apply custom scale if necessary if unit_scale and unit_scale not in (True, 1): total *= unit_scale n *= unit_scale if rate: rate *= unit_scale # by default rate = 1 / self.avg_time
class tqdm(Comparable): # apply custom scale if necessary if unit_scale and unit_scale not in (True, 1): if total: total *= unit_scale n *= unit_scale if rate: rate *= unit_scale # by default rate = 1 / self.avg_time
def test_infinite_total(): pass @with_setup(pretest, posttest) def test_unit(): """Test SI unit prefix"""
def test_infinite_total(): pass @with_setup(pretest, posttest) def test_nototal(): """Test unknown total length""" with closing(StringIO()) as our_file: for i in tqdm((i for i in range(10)), file=our_file, unit_scale=10): pass assert "100it" in our_file.getvalue() @wi...
class Parser: for date_unit in date_units: try: new_data = to_datetime(new_data, errors="raise", unit=date_unit) except (ValueError, OverflowError): continue return new_data, True return data, False
class Parser: for date_unit in date_units: try: new_data = to_datetime(new_data, errors="raise", unit=date_unit) except (ValueError, OverflowError, TypeError): continue return new_data, True return data, False
DataFrame\\.index values are different \\(100\\.0 %\\) # GH 31615 result = pd.DataFrame([[nulls_fixture]]).to_json() assert result == '{"0":{"0":null}}'
DataFrame\\.index values are different \\(100\\.0 %\\) # GH 31615 result = pd.DataFrame([[nulls_fixture]]).to_json() assert result == '{"0":{"0":null}}' def test_readjson_bool_series(self): # GH31464 result = read_json("[true, true, false]", typ="series") expected = ...
class HTTPRequest(HTTPMessage): ) headers = dict(self._orig.headers) if 'Host' not in headers: headers['Host'] = url.netloc.split('@')[-1] headers = ['%s: %s' % (name, value)
class HTTPRequest(HTTPMessage): ) headers = dict(self._orig.headers) if 'Host' not in self._orig.headers: headers['Host'] = url.netloc.split('@')[-1] headers = ['%s: %s' % (name, value)
def _set_uid_gid(tarinfo): return archive_name def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False): # XXX see if we want to keep an external call here if verbose: zipoptions = "-r" else: zipoptions = "-rq" from distutils.errors import DistutilsExecError ...
def _set_uid_gid(tarinfo): return archive_name def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger): # XXX see if we want to keep an external call here if verbose: zipoptions = "-r" else: zipoptions = "-rq" cmd = ["zip", zipoptions, zip_filename, base_dir] i...
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it",
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it",
class TestUtil(unittest.TestCase): 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'}") self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
class TestUtil(unittest.TestCase): inp = '''{"foo":101}''' self.assertEqual(js_to_json(inp), '''{"foo":101}''') inp = '''{"duration": "00:01:07"}''' self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''') def test_js_to_json_edgecases(self): on = js_to_json("{abc_...
def js_to_json(code): }.get(m.group(0), m.group(0)), v[1:-1]) INTEGER_TABLE = ( (r'^0[xX][0-9a-fA-F]+', 16), (r'^0+[0-7]+', 8), ) for regex, base in INTEGER_TABLE: im = re.match(regex, v) if im: i = int(im.group(0), ba...
def js_to_json(code): }.get(m.group(0), m.group(0)), v[1:-1]) INTEGER_TABLE = ( (r'^(0[xX][0-9a-fA-F]+)\s*:?$', 16), (r'^(0+[0-7]+)\s*:?$', 8), ) for regex, base in INTEGER_TABLE: im = re.match(regex, v) if im: i = int...
def target_version_option_callback( @click.option( "--config", type=click.Path( exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False ), is_eager=True, callback=read_pyproject_toml,
def target_version_option_callback( @click.option( "--config", type=click.Path( exists=True, file_okay=True, dir_okay=False, readable=True, allow_dash=False ), is_eager=True, callback=read_pyproject_toml,
class BlackTestCase(unittest.TestCase): raise result.exception self.assertEqual(result.exit_code, 0) class BlackDTestCase(AioHTTPTestCase): async def get_application(self) -> web.Application:
class BlackTestCase(unittest.TestCase): raise result.exception self.assertEqual(result.exit_code, 0) def test_invalid_config_return_code(self) -> None: tmp_file = Path(black.dump_to_file()) try: tmp_config = Path(black.dump_to_file()) tmp_config.u...
def test_29248(self): target = os.readlink(r'C:\Users\All Users') self.assertTrue(os.path.samefile(target, r'C:\ProgramData')) @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") class Win32JunctionTests(unittest.TestCase):
def test_29248(self): target = os.readlink(r'C:\Users\All Users') self.assertTrue(os.path.samefile(target, r'C:\ProgramData')) def test_buffer_overflow(self): # Older versions would have a buffer overflow when detecting # whether a link source was a directory. This test ensures we ...
def bar(foo: Foo): # fails due to returndatasize being nonzero but also lt 64 assert_tx_failed(lambda: c.bar(bad_1.address)) c.bar(bad_2.address)
def bar(foo: Foo): # fails due to returndatasize being nonzero but also lt 64 assert_tx_failed(lambda: c.bar(bad_1.address)) c.bar(bad_2.address) def test_contract_address_evaluation(get_contract): callee_code = """ # implements: Foo interface Counter: def increment_counter(): nonpayable @extern...
def _extcodesize_check(address): return ["assert", ["extcodesize", address]] def ir_for_external_call(call_expr, context): from vyper.codegen.expr import Expr # TODO rethink this circular import contract_address = Expr.parse_value_expr(call_expr.func.value, context) call_kwargs = _parse_kwargs(call_...
def _extcodesize_check(address): return ["assert", ["extcodesize", address]] def _external_call_helper(contract_address, args_ir, call_kwargs, call_expr, context): # expr.func._metadata["type"].return_type is more accurate # than fn_sig.return_type in the case of JSON interfaces. fn_type = call_expr.f...
def ir_for_external_call(call_expr, context): ret.append(ret_unpacker) return IRnode.from_list(ret, typ=return_t, location=MEMORY)
def ir_for_external_call(call_expr, context): ret.append(ret_unpacker) return IRnode.from_list(ret, typ=return_t, location=MEMORY) def ir_for_external_call(call_expr, context): from vyper.codegen.expr import Expr # TODO rethink this circular import contract_address = Expr.parse_value_expr(call_...
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): str_number = '{:f}'.format(number) else: str_number = six.text_type(number) if str_number[0] == '-':
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponen...
class TestNumberFormat(TestCase): self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34') self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3') self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.0000...
class TestNumberFormat(TestCase): self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34') self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3') self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.0000...
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: """ container: Optional[LN] = container_of(leaf) while container is not None and container.type != token.ENDMARKER: is_fmt_on = False for comment in list_comments(container.prefix, is_endmarker=False): if comment.value in FM...
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: """ container: Optional[LN] = container_of(leaf) while container is not None and container.type != token.ENDMARKER: if fmt_on(container): return # fix for fmt: on in children if contains_fmt_on_at_column(container, ...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_remove_empty_parentheses_after_class(self) -> None: source, expected = read_data("class_blank_paren...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_fmtonoff4(self) -> None: source, expected = read_data("fmtonoff4") actual = fs(source) ...
from .helper import on_ci "Tests/images/crash_1.tif", "Tests/images/crash_2.tif", "Tests/images/crash-2020-10-test.tif", ], ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data")
from .helper import on_ci "Tests/images/crash_1.tif", "Tests/images/crash_2.tif", "Tests/images/crash-2020-10-test.tif", "Tests/images/crash-1152ec2d1a1a71395b6f2ce6721c38924d025bf3.tif", "Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif", ], ) @pytest.mark.fil...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): @cache_readonly def _engine(self): # To avoid a reference cycle, pass a weakref of self to _engine_type. period = weakref.ref(self) return self._engine_type(period, len(self)) @doc(Index.__contains__)
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): @cache_readonly def _engine(self): # To avoid a reference cycle, pass a weakref of self._values to _engine_type. period = weakref.ref(self._values) return self._engine_type(period, len(self)) @doc(Index.__contains__)
def test_get_level_values_na(): result = index.get_level_values(0) expected = pd.Index([], dtype=object) tm.assert_index_equal(result, expected)
def test_get_level_values_na(): result = index.get_level_values(0) expected = pd.Index([], dtype=object) tm.assert_index_equal(result, expected) def test_get_level_values_when_periods(): # GH33131. See also discussion in GH32669. # This test can probably be removed when PeriodIndex._engine is remo...
class SimpleTaskState(object): def get_necessary_tasks(self): necessary_tasks = set() for task in self.get_active_tasks(): if task.status not in (DONE, DISABLED) or \ getattr(task, 'scheduler_disable_time', None) is not None: necessary_tasks.update(tas...
class SimpleTaskState(object): def get_necessary_tasks(self): necessary_tasks = set() for task in self.get_active_tasks(): if task.status not in (DONE, DISABLED, UNKNOWN) or \ task.scheduler_disable_time is not None: necessary_tasks.update(task.deps) ...
from helpers import unittest from nose.plugins.attrib import attr import luigi.notifications from luigi.scheduler import DISABLED, DONE, FAILED, PENDING, CentralPlannerScheduler luigi.notifications.DEBUG = True WORKER = 'myworker'
from helpers import unittest from nose.plugins.attrib import attr import luigi.notifications from luigi.scheduler import DISABLED, DONE, FAILED, PENDING, \ UNKNOWN, CentralPlannerScheduler luigi.notifications.DEBUG = True WORKER = 'myworker'
class CentralPlannerTest(unittest.TestCase): self.assertTrue(0 <= res < NUM_PENDING) self.sch.add_task(worker=WORKER, task_id=str(res), status=DONE) if __name__ == '__main__': unittest.main()
class CentralPlannerTest(unittest.TestCase): self.assertTrue(0 <= res < NUM_PENDING) self.sch.add_task(worker=WORKER, task_id=str(res), status=DONE) def test_assistants_dont_nurture_finished_statuses(self): """ Assistants should not affect longevity of DONE tasks Al...
class TestBash(object): assert 'TF_ALIAS=fuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING=utf-8' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines(['ls', 'rm']) assert list(shell.get_history()) == ['ls', 'rm']
class TestBash(object): assert 'TF_ALIAS=fuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING=utf-8' in shell.app_alias('fuck') def test_app_alias_variables_correctly_set(self, shell): alias = shell.app_alias('fuck') assert "alias fuck='TF_CMD=$(TF_ALIAS" in alias asser...
class TestZsh(object): assert 'thefuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines([': 1432613911:0;ls', ': 1432613916:0;rm']) assert list(shell.get_history()) == ['ls', 'rm']
class TestZsh(object): assert 'thefuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING' in shell.app_alias('fuck') def test_app_alias_variables_correctly_set(self, shell): alias = shell.app_alias('fuck') assert "alias fuck='TF_CMD=$(TF_ALIAS" in alias assert '$(TF_ALIAS...
from .generic import Generic 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.al...
from .generic import Generic class Bash(Generic): def app_alias(self, fuck): # It is VERY important to have the variables declared WITHIN the alias alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ " TF_SHELL_ALIASES=$(alias)" \ ...
class Fish(Generic): return ['cd', 'grep', 'ls', 'man', 'open'] def app_alias(self, fuck): return ('function {0} -d "Correct your previous console command"\n' ' set -l fucked_up_command $history[1]\n' ' env TF_ALIAS={0} PYTHONIOENCODING=utf-8'
class Fish(Generic): return ['cd', 'grep', 'ls', 'man', 'open'] def app_alias(self, fuck): # It is VERY important to have the variables declared WITHIN the alias return ('function {0} -d "Correct your previous console command"\n' ' set -l fucked_up_command $history[1]\n...
from .generic import Generic class Zsh(Generic): def app_alias(self, alias_name): alias = "alias {0}='TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ ' TF_SHELL_ALIASES=$(alias)' \ " TF_CMD=$(thefuck $(fc -ln -1 | tail -n 1)) &&" \ " eval $TF_CMD"...
from .generic import Generic class Zsh(Generic): def app_alias(self, alias_name): # It is VERY important to have the variables declared WITHIN the alias alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ " TF_SHELL_ALIASES=$(alias)" \ ...
class CorrectedCommand(object): compatibility_call(self.side_effect, old_cmd, self.script) # This depends on correct setting of PYTHONIOENCODING by the alias: logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '>-not-set-<'))) print(self.script)
class CorrectedCommand(object): compatibility_call(self.side_effect, old_cmd, self.script) # This depends on correct setting of PYTHONIOENCODING by the alias: logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '!!not-set!!'))) print(self.script)
def rnn(step_function, inputs, initial_states, tiled_mask_t = tf.tile(mask_t, tf.stack([1, tf.shape(output)[1]])) output = tf.where(tiled_mask_t, output, states[0]) new_states = [tf.where(tiled_mask_t, new_states[i], states[i]) for i...
def rnn(step_function, inputs, initial_states, tiled_mask_t = tf.tile(mask_t, tf.stack([1, tf.shape(output)[1]])) output = tf.where(tiled_mask_t, output, states[0]) new_states = [ tf.where(tf.tile(mask_t, tf.stack...
class TestBackend(object): assert_allclose(outputs_list[i - 1], outputs_list[i], atol=1e-05) assert_allclose(state_list[i - 1], state_list[i], atol=1e-05) def test_rnn_no_states(self): # implement a simple RNN without states input_dim = 8
class TestBackend(object): assert_allclose(outputs_list[i - 1], outputs_list[i], atol=1e-05) assert_allclose(state_list[i - 1], state_list[i], atol=1e-05) def test_rnn_additional_states(self): # implement a simple RNN with an additional state # whose shape is differe...
from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import timezone from django.utils.html import conditional_escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe
from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import timezone from django.utils.html import conditional_escape, escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe
class CycleNode(Node): class DebugNode(Node): def render(self, context): from pprint import pformat output = [pformat(val) for val in context] output.append('\n\n') output.append(pformat(sys.modules)) return ''.join(output)
class CycleNode(Node): class DebugNode(Node): def render(self, context): if not settings.DEBUG: return '' from pprint import pformat output = [escape(pformat(val)) for val in context] output.append('\n\n') output.append(escape(pformat(sys.modules))) retu...
import sys from django.contrib.auth.models import Group from django.template import ( Context, Engine, TemplateDoesNotExist, TemplateSyntaxError, )
import sys from django.template import ( Context, Engine, TemplateDoesNotExist, TemplateSyntaxError, )
class TemplateTestMixin: with self.assertRaises(NoReverseMatch): t.render(Context()) def test_debug_tag_non_ascii(self): """ #23060 -- Test non-ASCII model representation in debug output. """ group = Group(name="清風") c1 = Context({"objs": [group]}) ...
class TemplateTestMixin: with self.assertRaises(NoReverseMatch): t.render(Context()) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template
from keystone import exception from keystone import policy from keystone import token from keystone.common import manager from keystone.common import wsgi CONF = config.CONF class Manager(manager.Manager): """Default pivot point for the Identity backend.
from keystone import exception from keystone import policy from keystone import token from keystone.common import logging from keystone.common import manager from keystone.common import wsgi CONF = config.CONF LOG = logging.getLogger(__name__) class Manager(manager.Manager): """Default pivot point for the Iden...
def set_user_enabled(self, context, user_id, user): return self.update_user(context, user_id, user) def set_user_password(self, context, user_id, user): return self.update_user(context, user_id, user) def update_user_tenant(self, context, user_id, user): """Update the default tenant.""...
def set_user_enabled(self, context, user_id, user): return self.update_user(context, user_id, user) def set_user_password(self, context, user_id, user): user_ref = self.update_user(context, user_id, user) try: for token_id in self.token_api.list_tokens(context, user_id): ...
def delete_token(self, token_id): return self.db.delete('token-%s' % token_id) except KeyError: raise exception.TokenNotFound(token_id=token_id)
def delete_token(self, token_id): return self.db.delete('token-%s' % token_id) except KeyError: raise exception.TokenNotFound(token_id=token_id) def list_tokens(self, user_id): tokens = [] now = datetime.datetime.utcnow() for token, user_ref in self.db.items(...
def delete_token(self, token_id): with session.begin(): session.delete(token_ref) session.flush()
def delete_token(self, token_id): with session.begin(): session.delete(token_ref) session.flush() def list_tokens(self, user_id): session = self.get_session() tokens = [] now = datetime.datetime.utcnow() for token_ref in session.query(TokenModel)\ ...
def delete_token(self, token_id): """ raise exception.NotImplemented() def _get_default_expire_time(self): """Determine when a token should expire based on the config.
def delete_token(self, token_id): """ raise exception.NotImplemented() def list_tokens(self, user_id): """Returns a list of current token_id's for a user :param user_id: identity of the user :type user_id: string :returns: list of token_id's """ rai...
def test_invalid_user_password(self): username='blah', password='blah') def test_user_create_update_delete(self): from keystoneclient import exceptions as client_exceptions
def test_invalid_user_password(self): username='blah', password='blah') def test_change_password_invalidates_token(self): from keystoneclient import exceptions as client_exceptions client = self.get_client(admin=True) username = uuid.uui...
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] =...
def main(): 'test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1', 'test/utils/shippable/timing.py', 'test/integration/targets/old_style_modules_posix/library/helloworld.sh', # Python 3-only. Only run by release engineers 'hacking/release-an...
def main(): 'test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1', 'test/utils/shippable/timing.py', 'test/integration/targets/old_style_modules_posix/library/helloworld.sh', 'test/integration/targets/gathering_facts/library/bogus_facts', # P...
""" Constants specific to the SQL storage portion of the ORM. """ # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space.
""" Constants specific to the SQL storage portion of the ORM. """ from django.utils.regex_helper import _lazy_re_compile # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space.
ORDER_DIR = { 'ASC': ('ASC', 'DESC'), 'DESC': ('DESC', 'ASC'), } # SQL join types. INNER = 'INNER JOIN'
ORDER_DIR = { 'ASC': ('ASC', 'DESC'), 'DESC': ('DESC', 'ASC'), } ORDER_PATTERN = _lazy_re_compile(r'[-+]?[.\w]+$') # SQL join types. INNER = 'INNER JOIN'
from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import ( BaseTable, Empty, Join, MultiJoin, )
from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import ( INNER, LOUTER, ORDER_DIR, ORDER_PATTERN, SINGLE, ) from django.db.models.sql.datastructures import ( BaseTable, Empty, Joi...
class Query(BaseExpression): errors = [] for item in ordering: if isinstance(item, str): if '.' in item: warnings.warn( 'Passing column raw column aliases to order_by() is ' 'deprecated. Wrap %r in a RawSQL e...
class Query(BaseExpression): errors = [] for item in ordering: if isinstance(item, str): if '.' in item and ORDER_PATTERN.match(item): warnings.warn( 'Passing column raw column aliases to order_by() is ' 'dep...
class QuerySetExceptionTests(SimpleTestCase): with self.assertRaisesMessage(FieldError, msg): Article.objects.order_by('*') def test_invalid_queryset_model(self): msg = 'Cannot use QuerySet for "Article": Use a QuerySet for "ExtraInfo".' with self.assertRaisesMessage(ValueError,...
class QuerySetExceptionTests(SimpleTestCase): with self.assertRaisesMessage(FieldError, msg): Article.objects.order_by('*') def test_order_by_escape_prevention(self): msg = ( "Cannot resolve keyword 'queries.name);' into field. Choices are: " "created, id, name" ...
def init_ndarray(values, index, columns, dtype=None, copy=False): return arrays_to_mgr([values], columns, index, columns, dtype=dtype) elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype): # GH#19157 if columns is None: columns = [0] return arrays_to_m...
def init_ndarray(values, index, columns, dtype=None, copy=False): return arrays_to_mgr([values], columns, index, columns, dtype=dtype) elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype): # GH#19157 if isinstance(values, np.ndarray) and values.ndim > 1: # GH...
class TestDataFrameConstructorWithDatetimeTZ: "datetime64[ns, CET]", ] assert (res.dtypes == expected_dtypes).all()
class TestDataFrameConstructorWithDatetimeTZ: "datetime64[ns, CET]", ] assert (res.dtypes == expected_dtypes).all() def test_from_2d_ndarray_with_dtype(self): # GH#12513 array_dim2 = np.arange(10).reshape((5, 2)) df = pd.DataFrame(array_dim2, dtype="datetime64[ns...
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1, padding = _preprocess_padding(padding) if tf_data_format == 'NHWC': spatial_start_dim = 1 strides = (1, 1) + strides + (1,) else: spatial_start_dim = 2 strides = (1, 1, 1) + strides x = tf.expand_dims(...
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1, padding = _preprocess_padding(padding) if tf_data_format == 'NHWC': spatial_start_dim = 1 strides = (1,) + strides * 2 + (1,) else: spatial_start_dim = 2 strides = (1, 1) + strides * 2 x = tf.expand_di...
def test_separable_conv_1d(): num_step = 9 for padding in _convolution_paddings: for multiplier in [1, 2]: for dilation_rate in [1, 2]: if padding == 'same': continue if dilation_rate != 1: continue lay...
def test_separable_conv_1d(): num_step = 9 for padding in _convolution_paddings: for strides in [1, 2]: for multiplier in [1, 2]: for dilation_rate in [1, 2]: if padding == 'same' and strides != 1: continue if d...
import warnings import zlib from functools import wraps from urllib.parse import urldefrag, urljoin, urlunparse as _urlunparse from zope.interface import implementer
import warnings import zlib from functools import wraps from typing import Iterable from urllib.parse import urldefrag, urljoin, urlunparse as _urlunparse from zope.interface import implementer
def _handleResponse(self, response): return response @implementer(IAgent) class RedirectAgent: """
def _handleResponse(self, response): return response _canonicalHeaderName = Headers()._canonicalNameCaps _defaultSensitiveHeaders = frozenset( [ b"Authorization", b"Cookie", b"Cookie2", b"Proxy-Authorization", b"WWW-Authenticate", ] ) @implementer(IAgent) clas...
class RedirectAgent: @param redirectLimit: The maximum number of times the agent is allowed to follow redirects before failing with a L{error.InfiniteRedirection}. @cvar _redirectResponses: A L{list} of HTTP status codes to be redirected for I{GET} and I{HEAD} methods.
class RedirectAgent: @param redirectLimit: The maximum number of times the agent is allowed to follow redirects before failing with a L{error.InfiniteRedirection}. @param sensitiveHeaderNames: An iterable of C{bytes} enumerating the names of headers that must not be transmitted when redirecting...
class RedirectAgent: ] _seeOtherResponses = [http.SEE_OTHER] def __init__(self, agent, redirectLimit=20): self._agent = agent self._redirectLimit = redirectLimit def request(self, method, uri, headers=None, bodyProducer=None): """
class RedirectAgent: ] _seeOtherResponses = [http.SEE_OTHER] def __init__( self, agent: IAgent, redirectLimit: int = 20, sensitiveHeaderNames: Iterable[bytes] = (), ): self._agent = agent self._redirectLimit = redirectLimit sensitive = {_canonical...
def _handleRedirect(self, response, method, uri, headers, redirectCount): ) raise ResponseFailed([Failure(err)], response) location = self._resolveLocation(uri, locationHeaders[0]) deferred = self._agent.request(method, location, headers) def _chainResponse(newResponse):
def _handleRedirect(self, response, method, uri, headers, redirectCount): ) raise ResponseFailed([Failure(err)], response) location = self._resolveLocation(uri, locationHeaders[0]) if headers: parsedURI = URI.fromBytes(uri) parsedLocation = URI.fromBytes(l...
class IAgent(Interface): obtained by combining a number of (hypothetical) implementations:: baseAgent = Agent(reactor) redirect = BrowserLikeRedirectAgent(baseAgent, limit=10) authenticate = AuthenticateAgent( redirect, [diskStore.credentials, GtkAuthInterface()]) cookie...
class IAgent(Interface): obtained by combining a number of (hypothetical) implementations:: baseAgent = Agent(reactor) decode = ContentDecoderAgent(baseAgent, [(b"gzip", GzipDecoder())]) cookie = CookieAgent(decode, diskStore.cookie) authenticate = AuthenticateAgent( coo...
import zlib from http.cookiejar import CookieJar from io import BytesIO from unittest import skipIf from zope.interface.declarations import implementer from zope.interface.verify import verifyObject
import zlib from http.cookiejar import CookieJar from io import BytesIO from typing import TYPE_CHECKING, List, Optional, Tuple from unittest import SkipTest, skipIf from zope.interface.declarations import implementer from zope.interface.verify import verifyObject
URIInjectionTestsMixin, ) try: from twisted.internet import ssl as _ssl except ImportError:
URIInjectionTestsMixin, ) # Creatively lie to mypy about the nature of inheritance, since dealing with # expectations of a mixin class is basically impossible (don't use mixins). if TYPE_CHECKING: testMixinClass = TestCase runtimeTestCase = object else: testMixinClass = object runtimeTestCase = Tes...
class StubHTTPProtocol(Protocol): request method is appended to this list. """ def __init__(self): self.requests = [] self.state = "QUIESCENT" def request(self, request):
class StubHTTPProtocol(Protocol): request method is appended to this list. """ def __init__(self) -> None: self.requests: List[Tuple[Request, Deferred[IResponse]]] = [] self.state = "QUIESCENT" def request(self, request):
def getConnection(this, key, ep): self.assertEqual(agent._pool.connected, True) class _RedirectAgentTestsMixin: """ Test cases mixin for L{RedirectAgentTests} and L{BrowserLikeRedirectAgentTests}. """ def test_noRedirect(self): """ L{client.RedirectAgent} behaves like L{cl...
def getConnection(this, key, ep): self.assertEqual(agent._pool.connected, True) SENSITIVE_HEADERS = [ b"authorization", b"cookie", b"cookie2", b"proxy-authorization", b"www-authenticate", ] class _RedirectAgentTestsMixin(testMixinClass): """ Test cases mixin for L{RedirectAgentTe...
def test_noRedirect(self): self.assertIdentical(response, result) self.assertIdentical(result.previousResponse, None) def _testRedirectDefault(self, code): """ When getting a redirect, L{client.RedirectAgent} follows the URL specified in the L{Location} header field and make...
def test_noRedirect(self): self.assertIdentical(response, result) self.assertIdentical(result.previousResponse, None) def _testRedirectDefault( self, code: int, crossScheme: bool = False, crossDomain: bool = False, crossPort: bool = False, requestHead...
def _testRedirectDefault(self, code): self.assertEqual(b"/bar", req2.uri) host, port = self.reactor.tcpClients.pop()[:2] self.assertEqual(EXAMPLE_COM_IP, host) self.assertEqual(expectedPort, port) def test_redirect301(self): """
def _testRedirectDefault(self, code): self.assertEqual(b"/bar", req2.uri) host, port = self.reactor.tcpClients.pop()[:2] self.assertEqual(EXAMPLE_NET_IP if crossDomain else EXAMPLE_COM_IP, host) self.assertEqual(targetPort, port) return req2 def test_redirect301(self): ...
def test_redirect301(self): """ self._testRedirectDefault(301) def test_redirect302(self): """ L{client.RedirectAgent} follows redirects on status code 302.
def test_redirect301(self): """ self._testRedirectDefault(301) def test_redirect301Scheme(self): """ L{client.RedirectAgent} follows cross-scheme redirects. """ self._testRedirectDefault( 301, crossScheme=True, ) def test_redirect...
def test_redirect308(self): """ self._testRedirectDefault(308) def _testRedirectToGet(self, code, method): """ L{client.RedirectAgent} changes the method to I{GET} when getting
def test_redirect308(self): """ self._testRedirectDefault(308) def _sensitiveHeadersTest( self, expectedHostHeader: bytes = b"example.com", **crossKwargs: bool ) -> None: """ L{client.RedirectAgent} scrubs sensitive headers when redirecting between differing orig...
def test_responseHistory(self): class RedirectAgentTests( TestCase, FakeReactorAndConnectMixin, _RedirectAgentTestsMixin, AgentTestsMixin ): """ Tests for L{client.RedirectAgent}.
def test_responseHistory(self): class RedirectAgentTests( FakeReactorAndConnectMixin, _RedirectAgentTestsMixin, AgentTestsMixin, runtimeTestCase, ): """ Tests for L{client.RedirectAgent}.
def makeAgent(self): """ @return: a new L{twisted.web.client.RedirectAgent} """ return client.RedirectAgent(self.buildAgentForWrapperTest(self.reactor)) def setUp(self): self.reactor = self.createReactor()
def makeAgent(self): """ @return: a new L{twisted.web.client.RedirectAgent} """ return client.RedirectAgent( self.buildAgentForWrapperTest(self.reactor), sensitiveHeaderNames=[b"X-Custom-sensitive"], ) def setUp(self): self.reactor = self.crea...
def test_302OnPost(self): class BrowserLikeRedirectAgentTests( TestCase, FakeReactorAndConnectMixin, _RedirectAgentTestsMixin, AgentTestsMixin ): """ Tests for L{client.BrowserLikeRedirectAgent}.
def test_302OnPost(self): class BrowserLikeRedirectAgentTests( FakeReactorAndConnectMixin, _RedirectAgentTestsMixin, AgentTestsMixin, runtimeTestCase, ): """ Tests for L{client.BrowserLikeRedirectAgent}.
def makeAgent(self): @return: a new L{twisted.web.client.BrowserLikeRedirectAgent} """ return client.BrowserLikeRedirectAgent( self.buildAgentForWrapperTest(self.reactor) ) def setUp(self):
def makeAgent(self): @return: a new L{twisted.web.client.BrowserLikeRedirectAgent} """ return client.BrowserLikeRedirectAgent( self.buildAgentForWrapperTest(self.reactor), sensitiveHeaderNames=[b"x-Custom-sensitive"], ) def setUp(self):
class WrappedRequest(object): return name in self.request.headers def get_header(self, name, default=None): return to_native_str(self.request.headers.get(name, default)) def header_items(self): return [ (to_native_str(k), [to_native_str(x) for x in v]) for k, v ...
class WrappedRequest(object): return name in self.request.headers def get_header(self, name, default=None): return to_native_str(self.request.headers.get(name, default), errors='replace') def header_items(self): return [ (to_native_str(k, errors...
class WrappedResponse(object): # python3 cookiejars calls get_all def get_all(self, name, default=None): return [to_native_str(v) for v in self.response.headers.getlist(name)] # python2 cookiejars calls getheaders getheaders = get_all
class WrappedResponse(object): # python3 cookiejars calls get_all def get_all(self, name, default=None): return [to_native_str(v, errors='replace') for v in self.response.headers.getlist(name)] # python2 cookiejars calls getheaders getheaders = get_all
class CookiesMiddlewareTest(TestCase): del self.mw def test_basic(self): headers = {'Set-Cookie': 'C1=value1; path=/'} req = Request('http://scrapytest.org/') assert self.mw.process_request(req, self.spider) is None assert 'Cookie' not in req.headers res = Response(...
class CookiesMiddlewareTest(TestCase): del self.mw def test_basic(self): req = Request('http://scrapytest.org/') assert self.mw.process_request(req, self.spider) is None assert 'Cookie' not in req.headers headers = {'Set-Cookie': 'C1=value1; path=/'} res = Response(...