buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_language_evaluate(nlp): nlp.evaluate([text, gold]) def vector_modification_pipe(doc): doc.vector += 1 return doc
def test_language_evaluate(nlp): nlp.evaluate([text, gold]) def test_evaluate_no_pipe(nlp): """Test that docs are processed correctly within Language.pipe if the component doesn't expose a .pipe method.""" def pipe(doc): return doc text = "hello world" annots = {"cats": {"POSITIV...
def weighted_masked_objective(fn): score_array *= mask # the loss per batch should be proportional # to the number of unmasked samples. score_array /= K.mean(mask) # apply sample weighting if weights is not None:
def weighted_masked_objective(fn): score_array *= mask # the loss per batch should be proportional # to the number of unmasked samples. score_array /= K.mean(mask) + K.epsilon() # apply sample weighting if weights is not None:
from keras import losses from keras import backend as K def test_masking(): np.random.seed(1337) x = np.array([[[1], [1]], [[0], [0]]]) model = Sequential() model.add(Masking(mask_value=0, input_shape=(2, 1))) model.add(TimeDistributed(Dense(1, kernel_initializer='one'))) mod...
from keras import losses from keras import backend as K def create_masking_model(): model = Sequential() model.add(Masking(mask_value=0, input_shape=(None, 1))) model.add(TimeDistributed(Dense(1, kernel_initializer='one'))) model.compile(loss='mse', optimizer='sgd') return model def test_masking...
from pandas.core.dtypes.common import ( ensure_platform_int, is_bool, is_bool_dtype, is_categorical, is_categorical_dtype, is_datetime64_any_dtype, is_dtype_equal,
from pandas.core.dtypes.common import ( ensure_platform_int, is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype, is_dtype_equal,
class Index(IndexOpsMixin, PandasObject): return self._constructor(values, **attributes) except (TypeError, ValueError): pass return Index(values, **attributes) def _update_inplace(self, result, **kwargs):
class Index(IndexOpsMixin, PandasObject): return self._constructor(values, **attributes) except (TypeError, ValueError): pass # Remove tz so Index will try non-DatetimeIndex inference attributes.pop("tz", None) return Index(values, **attributes) ...
class Index(IndexOpsMixin, PandasObject): if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) if is_categorical(target): tgt_values = np.asarray(target) elif self.is_all_dates and target.is_all_dates: # GH 30399 tgt_va...
class Index(IndexOpsMixin, PandasObject): if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) if is_categorical_dtype(target.dtype): tgt_values = np.asarray(target) else: tgt_values = target._get_engine_target()
import numpy as np from pandas._libs import NaT, iNaT, join as libjoin, lib from pandas._libs.tslibs import timezones from pandas._typing import Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, cache_readonly, doc from pan...
import numpy as np from pandas._libs import NaT, iNaT, join as libjoin, lib from pandas._libs.tslibs import timezones from pandas._typing import DtypeObj, Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, cache_readonly, doc...
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.base import IndexOpsMixin import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.extensi...
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.base import IndexOpsMixin import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, ensure_index from pandas.core.i...
class DatetimeIndexOpsMixin(ExtensionIndex): def is_all_dates(self) -> bool: return True # ------------------------------------------------------------------------ # Abstract data attributes
class DatetimeIndexOpsMixin(ExtensionIndex): def is_all_dates(self) -> bool: return True def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ raise AbstractMethodError(self) # -------------------------...
class DatetimeIndexOpsMixin(ExtensionIndex): # try to find the dates return (lhs_mask & rhs_mask).nonzero()[0] # -------------------------------------------------------------------- __add__ = make_wrapped_arith_op("__add__")
class DatetimeIndexOpsMixin(ExtensionIndex): # try to find the dates return (lhs_mask & rhs_mask).nonzero()[0] @Appender(Index.get_indexer_non_unique.__doc__) def get_indexer_non_unique(self, target): target = ensure_index(target) pself, ptarget = self._maybe_promote(tar...
import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts from pandas._libs.tslibs import fields, parsing, timezones from pandas._typing import Label from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import _NS_DTYPE, is_float, is_intege...
import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts from pandas._libs.tslibs import fields, parsing, timezones from pandas._typing import DtypeObj, Label from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( _NS_DTYPE, ...
class DatetimeIndex(DatetimeTimedeltaMixin): return Timestamp(value).asm8 raise ValueError("Passed item and index have different timezone") # -------------------------------------------------------------------- # Rendering Methods
class DatetimeIndex(DatetimeTimedeltaMixin): return Timestamp(value).asm8 raise ValueError("Passed item and index have different timezone") def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ if no...
from pandas._libs.lib import no_default from pandas._libs.tslibs import frequencies as libfrequencies, resolution from pandas._libs.tslibs.parsing import parse_time_string from pandas._libs.tslibs.period import Period from pandas._typing import Label from pandas.util._decorators import Appender, cache_readonly from pa...
from pandas._libs.lib import no_default from pandas._libs.tslibs import frequencies as libfrequencies, resolution from pandas._libs.tslibs.parsing import parse_time_string from pandas._libs.tslibs.period import Period from pandas._typing import DtypeObj, Label from pandas.util._decorators import Appender, cache_readonl...
from pandas.core.dtypes.common import ( is_scalar, pandas_dtype, ) from pandas.core.arrays.period import ( PeriodArray,
from pandas.core.dtypes.common import ( is_scalar, pandas_dtype, ) from pandas.core.dtypes.dtypes import PeriodDtype from pandas.core.arrays.period import ( PeriodArray,
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): # raise when input doesn't have freq raise raise_on_incompatible(self, None) # ------------------------------------------------------------------------ # Rendering Methods
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): # raise when input doesn't have freq raise raise_on_incompatible(self, None) def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ if not isinstance(...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): def get_indexer_non_unique(self, target): target = ensure_index(target) if isinstance(target, PeriodIndex): if target.freq != self.freq: no_matches = -1 * np.ones(self.shape, dtype=np.intp) return no_m...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): def get_indexer_non_unique(self, target): target = ensure_index(target) if not self._is_comparable_dtype(target.dtype): no_matches = -1 * np.ones(self.shape, dtype=np.intp) return no_matches, no_matches target = ...
""" implement the TimedeltaIndex """ from pandas._libs import NaT, Timedelta, index as libindex from pandas._typing import Label from pandas.util._decorators import Appender from pandas.core.dtypes.common import (
""" implement the TimedeltaIndex """ from pandas._libs import NaT, Timedelta, index as libindex from pandas._typing import DtypeObj, Label from pandas.util._decorators import Appender from pandas.core.dtypes.common import (
class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): other = TimedeltaIndex(other) return self, other def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label
class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): other = TimedeltaIndex(other) return self, other def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ return is_timedelta64_dtype(dtype...
def test_convert_almost_null_slice(indices): msg = "'>=' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): idx._convert_slice_indexer(key, "loc")
def test_convert_almost_null_slice(indices): msg = "'>=' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): idx._convert_slice_indexer(key, "loc") dtlike_dtypes = [ np.dtype("timedelta64[ns]"), np.dtype("datetime64[ns]"), pd.DatetimeTZ...
def test_loc_slice_disallows_positional(): with tm.assert_produces_warning(FutureWarning): # GH#31840 deprecated incorrect behavior df.loc[1:3, 1] = 2
def test_loc_slice_disallows_positional(): with tm.assert_produces_warning(FutureWarning): # GH#31840 deprecated incorrect behavior df.loc[1:3, 1] = 2 def test_loc_datetimelike_mismatched_dtypes(): # GH#32650 dont mix and match datetime/timedelta/period dtypes df = pd.DataFrame( n...
""" import logging import OFS.interfaces from AccessControl import safe_builtins
""" import logging import warnings import OFS.interfaces from AccessControl import safe_builtins
def boboAwareZopeTraverse(object, path_items, econtext): while path_items: name = path_items.pop() if OFS.interfaces.ITraversable.providedBy(object): object = object.restrictedTraverse(name) else:
def boboAwareZopeTraverse(object, path_items, econtext): while path_items: name = path_items.pop() if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWarning) ...
"""``chameleon.tales`` expressions.""" from ast import NodeTransformer from ast import parse
"""``chameleon.tales`` expressions.""" import warnings from ast import NodeTransformer from ast import parse
def traverse(cls, base, request, path_items): while path_items: name = path_items.pop() if ITraversable.providedBy(base): base = getattr(base, cls.traverseMethod)(name) else: base = traversePathElement(base, name, path_items, ...
def traverse(cls, base, request, path_items): while path_items: name = path_items.pop() if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWar...
from ..expression import getEngine from . import testHTMLTests
import unittest from ..expression import getEngine from . import testHTMLTests
def setUp(self): # expressions (e.g. the ``zope.tales`` ``not`` expression # returns ``int``, that of ``chameleon.tales`` ``bool`` PREFIX = "CH_"
def setUp(self): # expressions (e.g. the ``zope.tales`` ``not`` expression # returns ``int``, that of ``chameleon.tales`` ``bool`` PREFIX = "CH_" @unittest.skip('The test in the base class relies on a Zope context with' ' the "random" module available in expressions') def tes...
import unittest from AccessControl import safe_builtins from zope.component.testing import PlacelessSetup
import unittest import warnings from AccessControl import safe_builtins from zExceptions import NotFound from zope.component.testing import PlacelessSetup
def test_evaluate_alternative_first_missing(self): self.assertTrue(ec.evaluate('x | nothing') is None) def test_evaluate_dict_key_as_underscore(self): ec = self._makeContext() self.assertEqual(ec.evaluate('d/_'), 'under') def test_evaluate_dict_with_key_from_expansion(self): ec...
def test_evaluate_alternative_first_missing(self): self.assertTrue(ec.evaluate('x | nothing') is None) def test_evaluate_dict_key_as_underscore(self): # Traversing to the name `_` will raise a DeprecationWarning # because it will go away in Zope 6. ec = self._makeContext() w...
def test_list_in_path_expr(self): ec = self._makeContext() self.assertIs(ec.evaluate('nocall: list'), safe_builtins["list"]) class TrustedEngineTests(EngineTestsBase, unittest.TestCase):
def test_list_in_path_expr(self): ec = self._makeContext() self.assertIs(ec.evaluate('nocall: list'), safe_builtins["list"]) def test_underscore_traversal(self): # Prevent traversal to names starting with an underscore (_) ec = self._makeContext() with self.assertRaises(Not...
DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable
DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zExceptions import NotFound from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable
def testPathNothing(self): def testPathAlt(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def testBatchIteration(self): self.assert_expected(self.folder.t, 'CheckBatchIteration.html')
def testPathNothing(self): def testPathAlt(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def testPathTraverse(self): # need to perform this test with a "real" folder from OFS.Folder import Folder f = self.folder self.folder = Folder() self.folde...
def test_unicode_conflict_resolution(self): provideUtility(PreferredCharsetResolver) t = PageTemplate() self.assert_expected(t, 'UnicodeResolution.html')
def test_unicode_conflict_resolution(self): provideUtility(PreferredCharsetResolver) t = PageTemplate() self.assert_expected(t, 'UnicodeResolution.html') def test_underscore_traversal(self): t = self.folder.t t.write('<p tal:define="p context/__class__" />') with se...
from django.utils.text import ( from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import Variable, VariableDoesNotExist from .library import Library register = Library()
from django.utils.text import ( from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import VARIABLE_ATTRIBUTE_SEPARATOR from .library import Library register = Library()
def striptags(value): def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, behave like Variable(arg).resolve >>> _property_resolver(1)('abc') 'b'
def striptags(value): def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b'
def _property_resolver(arg): try: float(arg) except ValueError: return Variable(arg).resolve else: return itemgetter(arg)
def _property_resolver(arg): try: float(arg) except ValueError: if VARIABLE_ATTRIBUTE_SEPARATOR + '_' in arg or arg[0] == '_': raise AttributeError('Access to private variables is forbidden.') parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR) def resolve(value): ...
def dictsort(value, arg): """ try: return sorted(value, key=_property_resolver(arg)) except (TypeError, VariableDoesNotExist): return ''
def dictsort(value, arg): """ try: return sorted(value, key=_property_resolver(arg)) except (AttributeError, TypeError): return ''
def dictsortreversed(value, arg): """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (TypeError, VariableDoesNotExist): return ''
def dictsortreversed(value, arg): """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (AttributeError, TypeError): return ''
from django.template.defaultfilters import dictsort from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_sort(self): sorted_dicts = dictsort( [{'age': 23, 'name': 'Barbara-Ann'},
from django.template.defaultfilters import _property_resolver, dictsort from django.test import SimpleTestCase class User: password = 'abc' _private = 'private' @property def test_property(self): return 'cde' def test_method(self): """This is just a test method.""" class Funct...
class FunctionTests(SimpleTestCase): def test_dictsort_complex_sorting_key(self): """ Since dictsort uses template.Variable under the hood, it can sort on keys like 'foo.bar'. """ data = [
class FunctionTests(SimpleTestCase): def test_dictsort_complex_sorting_key(self): """ Since dictsort uses dict.get()/getattr() under the hood, it can sort on keys like 'foo.bar'. """ data = [
class FunctionTests(SimpleTestCase): self.assertEqual(dictsort('Hello!', 'age'), '') self.assertEqual(dictsort({'a': 1}, 'age'), '') self.assertEqual(dictsort(1, 'age'), '')
class FunctionTests(SimpleTestCase): self.assertEqual(dictsort('Hello!', 'age'), '') self.assertEqual(dictsort({'a': 1}, 'age'), '') self.assertEqual(dictsort(1, 'age'), '') def test_invalid_args(self): """Fail silently if invalid lookups are passed.""" self.assertEqual(dict...
class FunctionTests(SimpleTestCase): self.assertEqual(dictsortreversed('Hello!', 'age'), '') self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') self.assertEqual(dictsortreversed(1, 'age'), '')
class FunctionTests(SimpleTestCase): self.assertEqual(dictsortreversed('Hello!', 'age'), '') self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') self.assertEqual(dictsortreversed(1, 'age'), '') def test_invalid_args(self): """Fail silently if invalid lookups are passed.""" ...
class RobotsTxtMiddleware(object): rp_dfd.callback(rp) def _robots_error(self, failure, netloc): self._parsers.pop(netloc).callback(None)
class RobotsTxtMiddleware(object): rp_dfd.callback(rp) def _robots_error(self, failure, netloc): rp_dfd = self._parsers[netloc] self._parsers[netloc] = None rp_dfd.callback(None)
class RobotsTxtMiddlewareTest(unittest.TestCase): deferred.addCallback(lambda _: self.assertTrue(middleware._logerror.called)) return deferred def test_ignore_robotstxt_request(self): self.crawler.settings.set('ROBOTSTXT_OBEY', True) def ignore_request(request, spider):
class RobotsTxtMiddlewareTest(unittest.TestCase): deferred.addCallback(lambda _: self.assertTrue(middleware._logerror.called)) return deferred def test_robotstxt_immediate_error(self): self.crawler.settings.set('ROBOTSTXT_OBEY', True) err = error.DNSLookupError('Robotstxt address no...
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): start = right[0] if end < start: return type(self)(data=[]) else: lslice = slice(*left.slice_locs(start, end)) left_chunk = left.values[lslice] return self._shallow_copy(left_chunk) ...
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): start = right[0] if end < start: return type(self)(data=[], dtype=self.dtype, freq=self.freq) else: lslice = slice(*left.slice_locs(start, end)) left_chunk = left._values[lslice] ret...
class TestGetItem: def test_dti_business_getitem(self): rng = pd.bdate_range(START, END) smaller = rng[:5] exp = DatetimeIndex(rng.view(np.ndarray)[:5]) tm.assert_index_equal(smaller, exp) assert smaller.freq == rng.freq
class TestGetItem: def test_dti_business_getitem(self): rng = pd.bdate_range(START, END) smaller = rng[:5] exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="B") tm.assert_index_equal(smaller, exp) assert smaller.freq == exp.freq assert smaller.freq == rng.freq
class TestGetItem: def test_dti_custom_getitem(self): rng = pd.bdate_range(START, END, freq="C") smaller = rng[:5] exp = DatetimeIndex(rng.view(np.ndarray)[:5]) tm.assert_index_equal(smaller, exp) assert smaller.freq == rng.freq sliced = rng[::5]
class TestGetItem: def test_dti_custom_getitem(self): rng = pd.bdate_range(START, END, freq="C") smaller = rng[:5] exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="C") tm.assert_index_equal(smaller, exp) assert smaller.freq == exp.freq assert smaller.freq == rng.fr...
class TestDatetimeIndexSetOps: assert result.freq is None assert result.tz == expected.tz def test_intersection_empty(self): # empty same freq GH2129 rng = date_range("6/1/2000", "6/15/2000", freq="T") result = rng[0:0].intersection(rng) assert len(result) ==...
class TestDatetimeIndexSetOps: assert result.freq is None assert result.tz == expected.tz # parametrize over both anchored and non-anchored freqs, as they # have different code paths @pytest.mark.parametrize("freq", ["T", "B"]) def test_intersection_empty(self, tz_aware_fixture...
class TestBusinessDatetimeIndex: b = bdate_range("12/10/2011", "12/20/2011") result = a.intersection(b) tm.assert_index_equal(result, b) def test_month_range_union_tz_pytz(self, sort): from pytz import timezone
class TestBusinessDatetimeIndex: b = bdate_range("12/10/2011", "12/20/2011") result = a.intersection(b) tm.assert_index_equal(result, b) assert result.freq == b.freq def test_month_range_union_tz_pytz(self, sort): from pytz import timezone
class TestCustomDatetimeIndex: b = bdate_range("12/10/2011", "12/20/2011", freq="C") result = a.intersection(b) tm.assert_index_equal(result, b)
class TestCustomDatetimeIndex: b = bdate_range("12/10/2011", "12/20/2011", freq="C") result = a.intersection(b) tm.assert_index_equal(result, b) assert result.freq == b.freq
class TestTimedeltaIndex: result = index_1 & index_2 expected = timedelta_range("1 day 01:00:00", periods=3, freq="h") tm.assert_index_equal(result, expected) def test_intersection_equal(self, sort): # GH 24471 Test intersection outcome given the sort keyword
class TestTimedeltaIndex: result = index_1 & index_2 expected = timedelta_range("1 day 01:00:00", periods=3, freq="h") tm.assert_index_equal(result, expected) assert result.freq == expected.freq def test_intersection_equal(self, sort): # GH 24471 Test intersection outcome gi...
class TestTimedeltaIndex: TimedeltaIndex(["2 hour", "5 hour", "5 hour", "1 hour"], name="other"), TimedeltaIndex(["1 hour", "2 hour"], name=None), ), # reveresed index ( TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx...
class TestTimedeltaIndex: TimedeltaIndex(["2 hour", "5 hour", "5 hour", "1 hour"], name="other"), TimedeltaIndex(["1 hour", "2 hour"], name=None), ), # reversed index ( TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx"...
class TestTimedeltaIndex: tm.assert_index_equal(result, expected) assert result.name == expected.name # if reveresed order, frequency is still the same if all(base == rng[::-1]) and sort is None: assert isinstance(result.freq, Hour) else:
class TestTimedeltaIndex: tm.assert_index_equal(result, expected) assert result.name == expected.name # if reversed order, frequency is still the same if all(base == rng[::-1]) and sort is None: assert isinstance(result.freq, Hour) else:
def _iter_command_classes(module_name): # TODO: add `name` attribute to commands and and merge this function with # scrapy.utils.spider.iter_spider_classes for module in walk_modules(module_name): for obj in vars(module).itervalues(): if inspect.isclass(obj) and \ issubcla...
def _iter_command_classes(module_name): # TODO: add `name` attribute to commands and and merge this function with # scrapy.utils.spider.iter_spider_classes for module in walk_modules(module_name): for obj in vars(module).values(): if inspect.isclass(obj) and \ issubcl...
class TestProcessProtocol(protocol.ProcessProtocol): def __init__(self): self.deferred = defer.Deferred() self.out = '' self.err = '' self.exitcode = None def outReceived(self, data):
class TestProcessProtocol(protocol.ProcessProtocol): def __init__(self): self.deferred = defer.Deferred() self.out = b'' self.err = b'' self.exitcode = None def outReceived(self, data):
class CmdlineTest(unittest.TestCase): self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings' def _execute(self, *new_args, **kwargs): args = (sys.executable, '-m', 'scrapy.cmdline') + new_args proc = Popen(args, stdout=PIPE, stderr=PIPE, env=self.env, **kwargs) comm = pr...
class CmdlineTest(unittest.TestCase): self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings' def _execute(self, *new_args, **kwargs): encoding = getattr(sys.stdout, 'encoding') or 'utf-8' args = (sys.executable, '-m', 'scrapy.cmdline') + new_args proc = Popen(args, stdou...
from twisted.trial import unittest from twisted.internet import defer
import sys from twisted.trial import unittest from twisted.internet import defer
class VersionTest(ProcessTest, unittest.TestCase): @defer.inlineCallbacks def test_output(self): _, out, _ = yield self.execute([]) self.assertEqual(out.strip(), "Scrapy %s" % scrapy.__version__)
class VersionTest(ProcessTest, unittest.TestCase): @defer.inlineCallbacks def test_output(self): encoding = getattr(sys.stdout, 'encoding') or 'utf-8' _, out, _ = yield self.execute([]) self.assertEqual(out.strip().decode(encoding), "Scrapy %s" % scrapy.__version__)
from pandas.core.dtypes.common import ( from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import isna, notna from pandas.core import ops from pandas.core.accessor im...
from pandas.core.dtypes.common import ( from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna from pandas.core import ops from...
class Categorical(NDArrayBackedExtensionArray, PandasObject): Returns True if `key` is in this Categorical. """ # if key is a NaN, check if any NaN is in self. if is_scalar(key) and isna(key): return self.isna().any() return contains(self, key, container=self._codes)
class Categorical(NDArrayBackedExtensionArray, PandasObject): Returns True if `key` is in this Categorical. """ # if key is a NaN, check if any NaN is in self. if is_valid_nat_for_dtype(key, self.categories.dtype): return self.isna().any() return contains(self, key, ...
from pandas.core.dtypes.common import ( is_scalar, ) from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.missing import isna from pandas.core import accessor from pandas.core.algorithms import take_1d
from pandas.core.dtypes.common import ( is_scalar, ) from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna from pandas.core import accessor from pandas.core.algorithms import take_1d
class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate): @doc(Index.__contains__) def __contains__(self, key: Any) -> bool: # if key is a NaN, check if any NaN is in self. if is_scalar(key) and isna(key): return self.hasnans hash(key) return contains(self, ke...
class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate): @doc(Index.__contains__) def __contains__(self, key: Any) -> bool: # if key is a NaN, check if any NaN is in self. if is_valid_nat_for_dtype(key, self.categories.dtype): return self.hasnans return contains(self...
class TestContains: ci = CategoricalIndex(list("aabbca") + [np.nan], categories=list("cabdef")) assert np.nan in ci @pytest.mark.parametrize( "item, expected", [
class TestContains: ci = CategoricalIndex(list("aabbca") + [np.nan], categories=list("cabdef")) assert np.nan in ci @pytest.mark.parametrize("unwrap", [True, False]) def test_contains_na_dtype(self, unwrap): dti = pd.date_range("2016-01-01", periods=100).insert(0, pd.NaT) pi = d...
def url(tgpath, tgparams=None, **kwargs): ''' if not isinstance(tgpath, six.string_types): tgpath = '/'.join(list(tgpath)) if tgpath.startswith('/'): webpath = (config.get('server.webpath') or '').rstrip('/') if tg_util.request_available():
def url(tgpath, tgparams=None, **kwargs): ''' if not isinstance(tgpath, six.string_types): tgpath = '/'.join(list(tgpath)) if not tgpath.startswith('/'): # Do not allow the url() function to be used for external urls. # This function is primarily used in redirect() calls, so this pre...
class S3CopyToTable(rdbms.CopyToTable, _CredentialsMixin): """ logger.info("Inserting file: %s", f) colnames = '' if len(self.columns) > 0: colnames = ",".join([x[0] for x in self.columns]) colnames = '({})'.format(colnames)
class S3CopyToTable(rdbms.CopyToTable, _CredentialsMixin): """ logger.info("Inserting file: %s", f) colnames = '' if self.columns and len(self.columns) > 0: colnames = ",".join([x[0] for x in self.columns]) colnames = '({})'.format(colnames)
class DummyS3CopyToTableBase(luigi.contrib.redshift.S3CopyToTable): user = 'dummy_user' password = 'dummy_password' table = luigi.Parameter(default='dummy_table') columns = ( ('some_text', 'varchar(255)'), ('some_int', 'int'), ) copy_options = ''
class DummyS3CopyToTableBase(luigi.contrib.redshift.S3CopyToTable): user = 'dummy_user' password = 'dummy_password' table = luigi.Parameter(default='dummy_table') columns = luigi.TupleParameter( default=( ('some_text', 'varchar(255)'), ('some_int', 'int'), ) )...
class TestS3CopyToTable(unittest.TestCase): (task.table,), ) class TestS3CopyToSchemaTable(unittest.TestCase): @mock.patch("luigi.contrib.redshift.S3CopyToTable.copy")
class TestS3CopyToTable(unittest.TestCase): (task.table,), ) @mock.patch("luigi.contrib.redshift.RedshiftTarget") def test_s3_copy_with_valid_columns(self, mock_redshift_target): task = DummyS3CopyToTableKey() task.run() # The mocked connection cursor passed to ...
from django.contrib.postgres.fields import ArrayField, JSONField from django.db.models.aggregates import Aggregate from .mixins import OrderableAggMixin
from django.contrib.postgres.fields import ArrayField, JSONField from django.db.models import Value from django.db.models.aggregates import Aggregate from .mixins import OrderableAggMixin
class JSONBAgg(Aggregate): class StringAgg(OrderableAggMixin, Aggregate): function = 'STRING_AGG' template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s'%(ordering)s)" allow_distinct = True def __init__(self, expression, delimiter, **extra): super().__init__(expression, delimiter...
class JSONBAgg(Aggregate): class StringAgg(OrderableAggMixin, Aggregate): function = 'STRING_AGG' template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)' allow_distinct = True def __init__(self, expression, delimiter, **extra): delimiter_expr = Value(str(delimiter)) super()...
from django.db.models.expressions import F, OrderBy class OrderableAggMixin: def __init__(self, expression, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or []
from django.db.models.expressions import F, OrderBy class OrderableAggMixin: def __init__(self, *expressions, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or []
class OrderableAggMixin: (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(expression, **extra) self.ordering = self._parse_expressions(*ordering) def resolve_expression(self, *args, **kwargs):
class OrderableAggMixin: (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(*expressions, **extra) self.ordering = self._parse_expressions(*ordering) def resolve_expression(self, *args, **kwargs):
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_charfield(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimiter=';'))...
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_delimiter_escaping(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimi...
def save_to_file(self, save_file=None, so_path=None): tmp_file = save_file + ".temp" with open(tmp_file, "w+") as f: os.fchmod(f.fileno(), stat.S_IRUSR | stat.S_IWUSR) f.write(json.dumps(saveconf, sort_keys=True, indent=2)) f.write("\n") f.flush() ...
def save_to_file(self, save_file=None, so_path=None): tmp_file = save_file + ".temp" mode = stat.S_IRUSR | stat.S_IWUSR # 0o600 umask = 0o777 ^ mode # Prevents always downgrading umask to 0 # For security, remove file with potentially elevated mode try: os.remove...
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_...
class SitemapSpider(Spider): def _parse_sitemap(self, response): if response.url.endswith('/robots.txt'): for url in sitemap_urls_from_robots(response.body): yield Request(url, callback=self._parse_sitemap) else: body = self._get_sitemap_body(response)
class SitemapSpider(Spider): def _parse_sitemap(self, response): if response.url.endswith('/robots.txt'): for url in sitemap_urls_from_robots(response.text): yield Request(url, callback=self._parse_sitemap) else: body = self._get_sitemap_body(response)
class SitemapSpiderTest(SpiderTest): r = Response(url="http://www.example.com/sitemap.xml.gz", body=self.GZBODY) self.assertSitemapBody(r, self.BODY) class BaseSpiderDeprecationTest(unittest.TestCase):
class SitemapSpiderTest(SpiderTest): r = Response(url="http://www.example.com/sitemap.xml.gz", body=self.GZBODY) self.assertSitemapBody(r, self.BODY) def test_get_sitemap_urls_from_robotstxt(self): robots = b"""# Sitemap files Sitemap: http://example.com/sitemap.xml Sitemap: http://example....
BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT[2:-2] + "$") ZONE_ID_RE = re.compile("(" + ZONE_ID_PAT + r")\]$") SUBAUTHORITY_PAT = (u"^(?:(.*)@)?(%s|%s|%s)(?::([0-9]{0,5}))?$") % ( REG_NAME_PAT, IPV4_PAT, IPV6_ADDRZ_PAT, ) SUBAUTHORITY_RE = re.compile(SUBAUTHORITY_PAT, re.UNICODE | re.DOTALL) ...
BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT[2:-2] + "$") ZONE_ID_RE = re.compile("(" + ZONE_ID_PAT + r")\]$") _HOST_PORT_PAT = ("^(%s|%s|%s)(?::([0-9]{0,5}))?$") % ( REG_NAME_PAT, IPV4_PAT, IPV6_ADDRZ_PAT, ) _HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL) UNRESERVED_CHARS ...
def parse_url(url): scheme = scheme.lower() if authority: auth, host, port = SUBAUTHORITY_RE.match(authority).groups() if auth and normalize_uri: auth = _encode_invalid_chars(auth, USERINFO_CHARS) if port == "":
def parse_url(url): scheme = scheme.lower() if authority: auth, _, host_port = authority.rpartition("@") auth = auth or None host, port = _HOST_PORT_RE.match(host_port).groups() if auth and normalize_uri: auth = _encode_invalid_chars(a...
def test_netloc(self, url, expected_netloc): fragment="hash", ), ), ] @pytest.mark.parametrize("url, expected_url", url_vulnerabilities)
def test_netloc(self, url, expected_netloc): fragment="hash", ), ), # Tons of '@' causing backtracking ("https://" + ("@" * 10000) + "[", False), ( "https://user:" + ("@" * 10000) + "example.com", Url( scheme="https", ...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collection_tar, files_member_obj) ...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) try: with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collectio...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (n_filename, to_native(tar.name))) b_dest_filepath = os.path.join(b_dest, to_bytes(filename, errors='surrogate_or...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (n_filename, to_native(tar.name))) b_dest_filepath = os.path.abspath(os.path.join(b_dest, to_bytes(filename, erro...
__metaclass__ = type import json import os import pytest import tarfile import uuid
__metaclass__ = type import json import os import pytest import re import tarfile import uuid
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): collection._extract_tar_file(tfile, filename, output_dir, temp_dir, checksum) os.path.isfile(output_file)
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): collection._extract_tar_file(tfile, filename, output_dir, temp_dir, checksum) os.path.isfile(output_file) def test_extract_tar_file_outside_dir(tmp_path_factory): filename = u'ÅÑŚÌβŁÈ' temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Coll...
def _make_getset_interval(method_name, lim_name, attr_name): setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), ignore=True) else: setter(self, max(vmin, vmax, oldmax), min(vmin, vmax, oldmin), ignore=True) sel...
def _make_getset_interval(method_name, lim_name, attr_name): setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), ignore=True) else: setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax), ignore=True) sel...
def test_bar_errbar_zorder(): assert capline.zorder > bar.zorder for barlinecol in barlinecols: assert barlinecol.zorder > bar.zorder
def test_bar_errbar_zorder(): assert capline.zorder > bar.zorder for barlinecol in barlinecols: assert barlinecol.zorder > bar.zorder def test_set_ticks_inverted(): fig, ax = plt.subplots() ax.invert_xaxis() ax.set_xticks([.3, .7]) assert ax.get_xlim() == (1, 0)
def login(): login_user(form.user, remember=remember_me, authn_via=["password"]) after_this_request(_commit) if not _security._want_json(request): return redirect(get_post_login_redirect()) if _security._want_json(request): if current_user.is_authenticated: ...
def login(): login_user(form.user, remember=remember_me, authn_via=["password"]) after_this_request(_commit) if _security._want_json(request): return base_render_json(form, include_auth_token=True) return redirect(get_post_login_redirect()) if _security._want_json(reque...
def change_password(): if form.validate_on_submit(): after_this_request(_commit) change_user_password(current_user._get_current_object(), form.new_password.data) if not _security._want_json(request): do_flash(*get_message("PASSWORD_CHANGE")) return redirect( ...
def change_password(): if form.validate_on_submit(): after_this_request(_commit) change_user_password(current_user._get_current_object(), form.new_password.data) if _security._want_json(request): form.user = current_user return base_render_json(form, include_auth_toke...
def test_session_query(in_app_context): assert response.status_code == 200 end_nqueries = get_num_queries(app.security.datastore) assert current_nqueries is None or end_nqueries == (current_nqueries + 2)
def test_session_query(in_app_context): assert response.status_code == 200 end_nqueries = get_num_queries(app.security.datastore) assert current_nqueries is None or end_nqueries == (current_nqueries + 2) @pytest.mark.changeable() def test_no_get_auth_token(app, client): # Test that GETs don't return a...
class HttpRequest: def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must be a tuple cont...
class HttpRequest: def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must be a tup...
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) class IsOverriddenTest(SimpleTestCase): def test_configure(self):
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTOCOL', 'https')) def test_xheader_preferred_to_underlying_request(self): class ProxyRequ...
def __str__(self): class Application: SOCKTYPES = { "tcp": socket.SOCK_STREAM, "udp": socket.SOCK_DGRAM,
def __str__(self): class Application: MAX_LENGTH = 128 * 1024 SOCKTYPES = { "tcp": socket.SOCK_STREAM, "udp": socket.SOCK_DGRAM,
def __call__(self, env, start_response): try: length = int(env["CONTENT_LENGTH"]) except AttributeError: length = -1 try: pr = codec.decode(env["wsgi.input"].read(length)) except codec.ParsingError as e:
def __call__(self, env, start_response): try: length = int(env["CONTENT_LENGTH"]) except AttributeError: raise HTTPException(411, "Length required.") if length < 0: raise HTTPException(411, "Length required.") if length > se...
def _isna_old(obj): raise NotImplementedError("isna is not defined for MultiIndex") elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)): return _isna_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): return obj._construct...
def _isna_old(obj): raise NotImplementedError("isna is not defined for MultiIndex") elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): re...
class TestSeriesAnalytics: ts.iloc[[0, 3, 5]] = np.nan tm.assert_series_equal(ts.count(level=1), right - 1) def test_dot(self): a = Series(np.random.randn(4), index=["p", "q", "r", "s"]) b = DataFrame(
class TestSeriesAnalytics: ts.iloc[[0, 3, 5]] = np.nan tm.assert_series_equal(ts.count(level=1), right - 1) # GH29478 with pd.option_context("use_inf_as_na", True): assert pd.Series([pd.Timestamp("1990/1/1")]).count() == 1 def test_dot(self): a = Series(np.rando...
from parsel.selector import create_root_node import six from scrapy.http.request import Request from scrapy.utils.python import to_bytes, is_listlike class FormRequest(Request):
from parsel.selector import create_root_node import six from scrapy.http.request import Request from scrapy.utils.python import to_bytes, is_listlike from scrapy.utils.response import get_base_url class FormRequest(Request):
class FormRequest(Request): def _get_form_url(form, url): if url is None: return form.action or form.base_url return urljoin(form.base_url, url)
class FormRequest(Request): def _get_form_url(form, url): if url is None: return urljoin(form.base_url, form.action) return urljoin(form.base_url, url)
def _urlencode(seq, enc): def _get_form(response, formname, formid, formnumber, formxpath): """Find the form element """ text = response.body_as_unicode() root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url) forms = root.xpath('//form') if not forms: raise ValueError("N...
def _urlencode(seq, enc): def _get_form(response, formname, formid, formnumber, formxpath): """Find the form element """ text = response.body_as_unicode() root = create_root_node(text, lxml.html.HTMLParser, base_url=get_base_url(response)) forms = root.xpath('//form') if not forms: raise Val...
class FormRequestTest(RequestTest): self.assertEqual(fs[b'test2'], [b'val2']) self.assertEqual(fs[b'button1'], [b'']) def _buildresponse(body, **kwargs): kwargs.setdefault('body', body) kwargs.setdefault('url', 'http://example.com')
class FormRequestTest(RequestTest): self.assertEqual(fs[b'test2'], [b'val2']) self.assertEqual(fs[b'button1'], [b'']) def test_html_base_form_action(self): response = _buildresponse( """ <html> <head> <base href="http://b.com/"> ...
class TestCustomDateRange: result = pd.date_range(start=start, end=end, periods=2, closed="left") expected = DatetimeIndex([start]) tm.assert_index_equal(result, expected)
class TestCustomDateRange: result = pd.date_range(start=start, end=end, periods=2, closed="left") expected = DatetimeIndex([start]) tm.assert_index_equal(result, expected) def test_date_range_with_custom_holidays(): # GH 30593 freq = pd.offsets.CustomBusinessHour(start="15:00", holiday...