buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def base_url(url): def urljoin(base, path): if not isinstance(path, compat_str) or not path: return None if re.match(r'^(?:https?:)?//', path): return path if not isinstance(base, compat_str) or not re.match(r'^(?:https?:)?//', base): return None return compat_urlparse.urljoin(...
def base_url(url): def urljoin(base, path): if isinstance(path, bytes): path = path.decode('utf-8') if not isinstance(path, compat_str) or not path: return None if re.match(r'^(?:https?:)?//', path): return path if isinstance(base, bytes): base = base.decode('utf-8') ...
ReferenceError: conole is not defined @pytest.mark.parametrize('test', tests) def test_match(monkeypatch, test): monkeypatch.setenv('EDITOR', 'dummy_editor') assert match(Command(stderr=test[4]), None) @pytest.mark.parametrize('test', tests) def test_not_match(monkeypatch, test): if 'EDITOR' in os.envir...
ReferenceError: conole is not defined @pytest.mark.parametrize('test', tests) def test_match(mocker, monkeypatch, test): mocker.patch('os.path.isfile', return_value=True) monkeypatch.setenv('EDITOR', 'dummy_editor') assert match(Command(stderr=test[4]), None) @pytest.mark.parametrize('test', tests) def ...
def _search(stderr): def match(command, settings): return 'EDITOR' in os.environ and _search(command.stderr) def get_new_command(command, settings):
def _search(stderr): def match(command, settings): if 'EDITOR' not in os.environ: return False m = _search(command.stderr) return m and os.path.isfile(m.group('file')) def get_new_command(command, settings):
def get_weighted_roll_func(cfunc: Callable) -> Callable: def validate_baseindexer_support(func_name: Optional[str]) -> None: # GH 32865: These functions work correctly with a BaseIndexer subclass BASEINDEXER_WHITELIST = { "min", "max", "mean",
def get_weighted_roll_func(cfunc: Callable) -> Callable: def validate_baseindexer_support(func_name: Optional[str]) -> None: # GH 32865: These functions work correctly with a BaseIndexer subclass BASEINDEXER_WHITELIST = { "count", "min", "max", "mean",
class _Rolling_and_Expanding(_Rolling): ) def count(self): if isinstance(self.window, BaseIndexer): validate_baseindexer_support("count") blocks, obj = self._create_blocks() results = []
class _Rolling_and_Expanding(_Rolling): ) def count(self): # GH 32865. Using count with custom BaseIndexer subclass # implementations shouldn't end up here assert not isinstance(self.window, BaseIndexer) blocks, obj = self._create_blocks() results = []
class Rolling(_Rolling_and_Expanding): def count(self): # different impl for freq counting if self.is_freq_type: window_func = self._get_roll_func("roll_count") return self._apply(window_func, center=self.center, name="count")
class Rolling(_Rolling_and_Expanding): def count(self): # different impl for freq counting # GH 32865. Use a custom count function implementation # when using a BaseIndexer subclass as a window if self.is_freq_type or isinstance(self.window, BaseIndexer): window_func = s...
def test_win_type_not_implemented(): df.rolling(indexer, win_type="boxcar") @pytest.mark.parametrize("func", ["count", "skew", "cov", "corr"]) def test_notimplemented_functions(func): # GH 32865 class CustomIndexer(BaseIndexer):
def test_win_type_not_implemented(): df.rolling(indexer, win_type="boxcar") @pytest.mark.parametrize("func", ["skew", "cov", "corr"]) def test_notimplemented_functions(func): # GH 32865 class CustomIndexer(BaseIndexer):
def test_notimplemented_functions(func): @pytest.mark.parametrize( "func,np_func,expected,np_kwargs", [ ("min", np.min, [0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 6.0, 7.0, 8.0, np.nan], {},), ( "max",
def test_notimplemented_functions(func): @pytest.mark.parametrize( "func,np_func,expected,np_kwargs", [ ("count", len, [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 2.0, np.nan], {},), ("min", np.min, [0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 6.0, 7.0, 8.0, np.nan], {},), ( "max",
# this is a package __version__ = "4.6.4" def get_include():
# this is a package __version__ = "4.6.5" def get_include():
import os from shutil import rmtree import string import tempfile from typing import List, Optional, Union, cast import warnings import zipfile
import os from shutil import rmtree import string import tempfile from typing import Any, List, Optional, Union, cast import warnings import zipfile
from pandas._config.localization import ( # noqa:F401 ) import pandas._libs.testing as _testing from pandas._typing import FrameOrSeries from pandas.compat import _get_lzma_file, _import_lzma from pandas.core.dtypes.common import (
from pandas._config.localization import ( # noqa:F401 ) import pandas._libs.testing as _testing from pandas._typing import FilePathOrBuffer, FrameOrSeries from pandas.compat import _get_lzma_file, _import_lzma from pandas.core.dtypes.common import (
def reset_display_options(): pd.reset_option("^display.", silent=True) def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOrSeries: """ Pickle an object and then read it again. Parameters ---------- obj : pandas object The object to pickle and then re-read. ...
def reset_display_options(): pd.reset_option("^display.", silent=True) def round_trip_pickle( obj: Any, path: Optional[FilePathOrBuffer] = None ) -> FrameOrSeries: """ Pickle an object and then read it again. Parameters ---------- obj : any object The object to pickle and then re-...
def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOr pandas object The original object that was pickled and then re-read. """ if path is None: path = f"__{rands(10)}__.pickle" with ensure_clean(path) as path: pd.to_pickle(obj, path) return pd.r...
def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOr pandas object The original object that was pickled and then re-read. """ _path = path if _path is None: _path = f"__{rands(10)}__.pickle" with ensure_clean(_path) as path: pd.to_pickle(obj, _path...
""" pickle compat """ import pickle import warnings from pandas.compat import pickle_compat as pc from pandas.io.common import get_handle, stringify_path def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL): """ Pickle (serialize) object to file.
""" pickle compat """ import pickle from typing import Any, Optional import warnings from pandas._typing import FilePathOrBuffer from pandas.compat import pickle_compat as pc from pandas.io.common import get_filepath_or_buffer, get_handle def to_pickle( obj: Any, filepath_or_buffer: FilePathOrBuffer, co...
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL): ---------- obj : any object Any python object. path : str File path where the pickled object will be stored. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer' A string repres...
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL): ---------- obj : any object Any python object. filepath_or_buffer : str, path object or file-like object File path, URL, or buffer where the pickled object will be stored. .. versionchanged:: 1.0.0 ...
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL): >>> import os >>> os.remove("./dummy.pkl") """ path = stringify_path(path) f, fh = get_handle(path, "wb", compression=compression, is_text=False) if protocol < 0: protocol = pickle.HIGHEST_PROTOCOL try:
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL): >>> import os >>> os.remove("./dummy.pkl") """ fp_or_buf, _, compression, should_close = get_filepath_or_buffer( filepath_or_buffer, compression=compression, mode="wb" ) if not isinstance(fp_or_buf, str) and...
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL): f.close() for _f in fh: _f.close() def read_pickle(path, compression="infer"): """ Load pickled pandas object (or any object) from file.
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL): f.close() for _f in fh: _f.close() if should_close: try: fp_or_buf.close() except ValueError: pass def read_pickle( filepath_or_buffer: FileP...
def read_pickle(path, compression="infer"): Parameters ---------- path : str File path where the pickled object will be loaded. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer', then use gzip, bz2...
def read_pickle(path, compression="infer"): Parameters ---------- filepath_or_buffer : str, path object or file-like object File path, URL, or buffer where the pickled object will be loaded from. .. versionchanged:: 1.0.0 Accept URL. URL is not limited to S3 and GCS. compre...
def read_pickle(path, compression="infer"): >>> import os >>> os.remove("./dummy.pkl") """ path = stringify_path(path) f, fh = get_handle(path, "rb", compression=compression, is_text=False) # 1) try standard library Pickle # 2) try pickle_compat (older pandas version) to handle subclass cha...
def read_pickle(path, compression="infer"): >>> import os >>> os.remove("./dummy.pkl") """ fp_or_buf, _, compression, should_close = get_filepath_or_buffer( filepath_or_buffer, compression=compression ) if not isinstance(fp_or_buf, str) and compression == "infer": compression = N...
def read_pickle(path, compression="infer"): f.close() for _f in fh: _f.close()
def read_pickle(path, compression="infer"): f.close() for _f in fh: _f.close() if should_close: try: fp_or_buf.close() except ValueError: pass
import zipfile import pytest from pandas.compat import _get_lzma_file, _import_lzma, is_platform_little_endian import pandas as pd from pandas import Index
import zipfile import pytest from pandas.compat import _get_lzma_file, _import_lzma, is_platform_little_endian import pandas.util._test_decorators as td import pandas as pd from pandas import Index
def test_unicode_decode_error(datapath): # just test the columns are correct since the values are random excols = pd.Index(["a", "b", "c"]) tm.assert_index_equal(df.columns, excols)
def test_unicode_decode_error(datapath): # just test the columns are correct since the values are random excols = pd.Index(["a", "b", "c"]) tm.assert_index_equal(df.columns, excols) # --------------------- # tests for buffer I/O # --------------------- def test_pickle_buffer_roundtrip(): with tm.ens...
import json from django import forms from django.conf import settings from django.core.exceptions import ValidationError from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch
import json from django import forms from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch
class AdminEmailInputWidget(forms.EmailInput): class AdminURLFieldWidget(forms.URLInput): template_name = 'admin/widgets/url.html' def __init__(self, attrs=None): super().__init__(attrs={'class': 'vURLField', **(attrs or {})}) def get_context(self, name, value, attrs): context = super().ge...
class AdminEmailInputWidget(forms.EmailInput): class AdminURLFieldWidget(forms.URLInput): template_name = 'admin/widgets/url.html' def __init__(self, attrs=None, validator_class=URLValidator): super().__init__(attrs={'class': 'vURLField', **(attrs or {})}) self.validator = validator_class() ...
class AdminSplitDateTimeWidgetTest(SimpleTestCase): class AdminURLWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual(
class AdminSplitDateTimeWidgetTest(SimpleTestCase): class AdminURLWidgetTest(SimpleTestCase): def test_get_context_validates_url(self): w = widgets.AdminURLFieldWidget() for invalid in ['', '/not/a/full/url/', 'javascript:alert("Danger XSS!")']: with self.subTest(url=invalid): ...
class AdminURLWidgetTest(SimpleTestCase): VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>') w = widgets.AdminURLFieldWidget() output = w.render('test', 'http://example.com/<sometag>some text</sometag>') self.assertEqual( HREF_RE.sear...
class AdminURLWidgetTest(SimpleTestCase): VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>') w = widgets.AdminURLFieldWidget() output = w.render('test', 'http://example.com/<sometag>some-text</sometag>') self.assertEqual( HREF_RE.sear...
from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.html import smart_urlquote from django.utils.safestring import mark_safe from django.utils.text import Truncator from django.utils.translation import get_language, gettext as...
from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.html import smart_urlquote from django.utils.http import urlencode from django.utils.text import Truncator from django.utils.translation import get_language, gettext as _
class ForeignKeyRawIdWidget(forms.TextInput): params = self.url_parameters() if params: related_url += '?' + '&amp;'.join('%s=%s' % (k, v) for k, v in params.items()) context['related_url'] = mark_safe(related_url) context['link_title'] = _('Lookup') ...
class ForeignKeyRawIdWidget(forms.TextInput): params = self.url_parameters() if params: related_url += '?' + urlencode(params) context['related_url'] = related_url context['link_title'] = _('Lookup') # The JavaScript code looks for this class....
class Band(models.Model): return self.name class Album(models.Model): band = models.ForeignKey(Band, models.CASCADE) featuring = models.ManyToManyField(Band, related_name='featured')
class Band(models.Model): return self.name class UnsafeLimitChoicesTo(models.Model): band = models.ForeignKey( Band, models.CASCADE, limit_choices_to={'name': '"&><escapeme'}, ) class Album(models.Model): band = models.ForeignKey(Band, models.CASCADE) featuring = mode...
from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual, Inventory, Member, MyFileField, Profile, School, Student, ) from .widgetadmin import site as widget_admin_site
from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual, Inventory, Member, MyFileField, Profile, School, Student, UnsafeLimitChoicesTo, ) from .widgetadmin import site as widget_admin_site
class ForeignKeyRawIdWidgetTest(TestCase): 'Hidden</a></strong>' % {'pk': hidden.pk} ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class ManyToManyRawIdWidgetTest(TestCase):
class ForeignKeyRawIdWidgetTest(TestCase): 'Hidden</a></strong>' % {'pk': hidden.pk} ) def test_render_unsafe_limit_choices_to(self): rel = UnsafeLimitChoicesTo._meta.get_field('band').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTML...
class DatetimeLikeArrayMixin( def _validate_insert_value(self, value): if isinstance(value, self._recognized_scalars): value = self._scalar_type(value) elif is_valid_nat_for_dtype(value, self.dtype): # GH#18295 value = NaT elif lib.is_scalar(value) and isn...
class DatetimeLikeArrayMixin( def _validate_insert_value(self, value): if isinstance(value, self._recognized_scalars): value = self._scalar_type(value) self._check_compatible_with(value, setitem=True) # TODO: if we dont have compat, should we raise or astype(object)? ...
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): ------- new_index : Index """ item = self._data._validate_insert_value(item) freq = None if isinstance(item, self._data._scalar_type) or item is NaT: self._data._check_compatible_with(item, seti...
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): ------- new_index : Index """ if isinstance(item, str): # TODO: Why are strings special? # TODO: Should we attempt _scalar_from_string? return self.astype(object).insert(loc, item) ...
class TestInsert: assert result.name == expected.name assert result.tz == expected.tz assert result.freq is None
class TestInsert: assert result.name == expected.name assert result.tz == expected.tz assert result.freq is None @pytest.mark.parametrize( "item", [0, np.int64(0), np.float64(0), np.array(0), np.timedelta64(456)] ) def test_insert_mismatched_types_rai...
class TestTimedeltaIndexInsert: with pytest.raises(TypeError, match="incompatible label"): idx.insert(0, np.datetime64("NaT")) def test_insert_dont_cast_strings(self): # To match DatetimeIndex and PeriodIndex behavior, dont try to # parse strings to Timedelta
class TestTimedeltaIndexInsert: with pytest.raises(TypeError, match="incompatible label"): idx.insert(0, np.datetime64("NaT")) @pytest.mark.parametrize( "item", [0, np.int64(0), np.float64(0), np.array(0), np.datetime64(456, "us")] ) def test_insert_mismatched_types_raises(self,...
class TestInsertIndexCoercion(CoercionBase): with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo")) msg = "cannot insert DatetimeIndex with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, 1...
class TestInsertIndexCoercion(CoercionBase): with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo")) msg = "cannot insert DatetimeArray with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, 1...
class TestInsertIndexCoercion(CoercionBase): ) # ToDo: must coerce to object msg = "cannot insert TimedeltaIndex with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01")) # ToDo: must coerce to object msg = ...
class TestInsertIndexCoercion(CoercionBase): ) # ToDo: must coerce to object msg = "cannot insert TimedeltaArray with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01")) # ToDo: must coerce to object msg = ...
class TestPartialSetting: df = orig.copy() # don't allow not string inserts msg = "cannot insert DatetimeIndex with incompatible label" with pytest.raises(TypeError, match=msg): df.loc[100.0, :] = df.iloc[0]
class TestPartialSetting: df = orig.copy() # don't allow not string inserts msg = "cannot insert DatetimeArray with incompatible label" with pytest.raises(TypeError, match=msg): df.loc[100.0, :] = df.iloc[0]
class XMLRPCHandlerTests(unittest.TestCase): self.assertEqual(params[11], {'k': [1, {}]}) class TraverseTests(unittest.TestCase): def test_underscore(self): from supervisor import xmlrpc self.assertRaises(xmlrpc.RPCError, xmlrpc.traverse, None, '_', None) def test_notfound(self): ...
class XMLRPCHandlerTests(unittest.TestCase): self.assertEqual(params[11], {'k': [1, {}]}) class TraverseTests(unittest.TestCase): def test_security_disallows_underscore_methods(self): from supervisor import xmlrpc class Root: pass class A: def _danger(self): ...
class supervisor_xmlrpc_handler(xmlrpc_handler): return traverse(self.rpcinterface, method, params) def traverse(ob, method, params): path = method.split('.') for name in path: if name.startswith('_'): # security (don't allow things that start with an underscore to # be ...
class supervisor_xmlrpc_handler(xmlrpc_handler): return traverse(self.rpcinterface, method, params) def traverse(ob, method, params): dotted_parts = method.split('.') # security (CVE-2017-11610, don't allow object traversal) if len(dotted_parts) != 2: raise RPCError(Faults.UNKNOWN_METHOD) ...
class CkMinions: def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None): """ Return a Bool. This function returns if the expression sent in is within the scope of the valid expression """ v_minions = set(self.check_minions(valid, "compound").get("minion...
class CkMinions: def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None): """ Validate the target minions against the possible valid minions. If ``minions`` is provided, they will be compared against the valid minions. Otherwise, ``expr`` and ``tgt_type`` will b...
import salt.utils.minions import salt.utils.network from tests.support.mock import patch
import pytest import salt.utils.minions import salt.utils.network from tests.support.mock import patch
def test_connected_ids(): with patch_net, patch_list, patch_fetch: ret = ckminions.connected_ids() assert ret == {minion}
def test_connected_ids(): with patch_net, patch_list, patch_fetch: ret = ckminions.connected_ids() assert ret == {minion} # These validate_tgt tests make the assumption that CkMinions.check_minions is # correct. In other words, these tests are only worthwhile if check_minions is # also...
setup( author='Jeff Knupp', tests_require=['pytest', 'pytest-cov', 'pytest-flask>=0.4.0'], install_requires=[ 'Flask>=0.10.1', 'Flask-SQLAlchemy>=1.0', 'SQLAlchemy==1.2.12', 'Flask-Admin>=1.0.9',
setup( author='Jeff Knupp', tests_require=['pytest', 'pytest-cov', 'pytest-flask>=0.4.0'], install_requires=[ 'Flask>=1.0.2', 'Flask-SQLAlchemy>=1.0', 'SQLAlchemy==1.2.12', 'Flask-Admin>=1.0.9',
class Axes(_AxesBase): zdelta = 0.1 def line_props_with_rcdefaults(subkey, explicit, zdelta=0): d = {k.split('.')[-1]: v for k, v in rcParams.items() if k.startswith(f'boxplot.{subkey}')} d['zorder'] = zorder + zdelta if explicit is not None: ...
class Axes(_AxesBase): zdelta = 0.1 def line_props_with_rcdefaults(subkey, explicit, zdelta=0, use_marker=True): d = {k.split('.')[-1]: v for k, v in rcParams.items() if k.startswith(f'boxplot.{subkey}')} d['zorder'] = zor...
class Axes(_AxesBase): cbook.normalize_kwargs( boxprops, mpatches.PathPatch._alias_map)) else: final_boxprops = line_props_with_rcdefaults('boxprops', boxprops) final_whiskerprops = line_props_with_rcdefaults( 'whiskerprops', whiskerpro...
class Axes(_AxesBase): cbook.normalize_kwargs( boxprops, mpatches.PathPatch._alias_map)) else: final_boxprops = line_props_with_rcdefaults('boxprops', boxprops, use_marker=False) final_whisker...
def test_boxplot_bad_ci_2(): ax.boxplot([x, x], conf_intervals=[[1, 2], [1]]) @image_comparison(['boxplot_mod_artists_after_plotting.png'], remove_text=True, savefig_kwarg={'dpi': 40}, style='default') def test_boxplot_mod_artist_after_plotting():
def test_boxplot_bad_ci_2(): ax.boxplot([x, x], conf_intervals=[[1, 2], [1]]) def test_boxplot_marker_behavior(): plt.rcParams['lines.marker'] = 's' plt.rcParams['boxplot.flierprops.marker'] = 'o' plt.rcParams['boxplot.meanprops.marker'] = '^' fig, ax = plt.subplots() test_data = np.arange...
class _AxesBase(martist.Artist): if right is None: right = old_right if self.get_xscale() == 'log': if left <= 0: cbook._warn_external( 'Attempted to set non-positive left xlim on a '
class _AxesBase(martist.Artist): if right is None: right = old_right if self.get_xscale() == 'log' and (left <= 0 or right <= 0): # Axes init calls set_xlim(0, 1) before get_xlim() can be called, # so only grab the limits if we really need them. o...
def test_log_scales(): ax.set_xscale('log', basex=9.0) @image_comparison(['stackplot_test_image', 'stackplot_test_image']) def test_stackplot(): fig = plt.figure()
def test_log_scales(): ax.set_xscale('log', basex=9.0) def test_log_scales_invalid(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xscale('log') with pytest.warns(UserWarning, match='Attempted to set non-positive'): ax.set_xlim(-1, 10) @image_comparison(['stackplot_test_image'...
def default_urlconf(request): var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.innerHTML = s.innerHTML == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switch to...
def default_urlconf(request): var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.textContent = s.textContent == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switc...
from django.utils.encoding import python_2_unicode_compatible class Section(models.Model): """ A simple section that links to articles, to test linking to related items
from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Section(models.Model): """ A simple section that links to articles, to test linking to related items
class Section(models.Model): """ name = models.CharField(max_length=100) @property def name_property(self): """
class Section(models.Model): """ name = models.CharField(max_length=100) def __str__(self): return self.name @property def name_property(self): """
def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ s1 = Section.objects.create(name='Test section') Article.objects.create( content='<p>Middle content</p>', date=datetime.datetime(2008, 3, 18, 11, 54, 58), ...
def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ from selenium.webdriver.support.ui import Select s1 = Section.objects.create(name='Test section') Article.objects.create( title='foo', content='<p>Middl...
def test_list_editable_popups(self): self.wait_for_popup() self.selenium.switch_to.window(self.selenium.window_handles[-1]) self.wait_for_text('#content h1', 'Change section') self.selenium.close() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Add pop...
def test_list_editable_popups(self): self.wait_for_popup() self.selenium.switch_to.window(self.selenium.window_handles[-1]) self.wait_for_text('#content h1', 'Change section') name_input = self.selenium.find_element_by_id('id_name') name_input.clear() name_input.send_keys...
class ExtensionBlock(Block): new_values = self.values if inplace else self.values.copy() if isinstance(new, np.ndarray) and len(new) == len(mask): new = new[mask] mask = _safe_reshape(mask, new_values.shape)
class ExtensionBlock(Block): new_values = self.values if inplace else self.values.copy() if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask): new = new[mask] mask = _safe_reshape(mask, new_values.shape)
class TestUpdate: # GH 33215 series.update(other) tm.assert_series_equal(series, expected)
class TestUpdate: # GH 33215 series.update(other) tm.assert_series_equal(series, expected) @pytest.mark.parametrize( "result, target, expected", [ ( Series(["a", None], dtype="string"), Series([None, "b"], dtype="string"), ...
class CkMinions: def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None): """ Return a Bool. This function returns if the expression sent in is within the scope of the valid expression """ v_minions = set(self.check_minions(valid, "compound").get("minion...
class CkMinions: def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None): """ Validate the target minions against the possible valid minions. If ``minions`` is provided, they will be compared against the valid minions. Otherwise, ``expr`` and ``tgt_type`` will b...
import salt.utils.minions import salt.utils.network from tests.support.mock import patch
import pytest import salt.utils.minions import salt.utils.network from tests.support.mock import patch
def test_connected_ids(): with patch_net, patch_list, patch_fetch: ret = ckminions.connected_ids() assert ret == {minion}
def test_connected_ids(): with patch_net, patch_list, patch_fetch: ret = ckminions.connected_ids() assert ret == {minion} # These validate_tgt tests make the assumption that CkMinions.check_minions is # correct. In other words, these tests are only worthwhile if check_minions is # also...
from autobahn.util import _maybe_tls_reason import txaio __all__ = ("WebSocketProtocol",
from autobahn.util import _maybe_tls_reason import txaio import hyperlink __all__ = ("WebSocketProtocol",
def processHandshake(self): # # https://localhost:9000/?redirect=https%3A%2F%2Ftwitter.com%2F&after=3 # url = self.http_request_params['redirect'][0] if 'after' in self.http_request_params and len(sel...
def processHandshake(self): # # https://localhost:9000/?redirect=https%3A%2F%2Ftwitter.com%2F&after=3 # url = hyperlink.URL.from_text(self.http_request_params['redirect'][0]) url = url.to_uri().normal...
from pandas.core.dtypes.common import ( is_unsigned_integer_dtype, pandas_dtype, ) from pandas.core.dtypes.generic import ABCIndexClass, ABCPeriodArray, ABCSeries from pandas.core.dtypes.inference import is_array_like from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
from pandas.core.dtypes.common import ( is_unsigned_integer_dtype, pandas_dtype, ) from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.inference import is_array_like from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
default 'raise' def _round(self, freq, mode, ambiguous, nonexistent): # round the local times values = _ensure_datetimelike_to_i8(self) result = round_nsint64(values, mode, freq) result = self._maybe_mask_results(result, fill_value=NaT) dtype = self.dtype if is_date...
default 'raise' def _round(self, freq, mode, ambiguous, nonexistent): # round the local times if is_datetime64tz_dtype(self): # operate on naive timestamps, then convert back to aware naive = self.tz_localize(None) result = naive._round(freq, mode, ambiguous, non...
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) self._freq = result._freq return self # -------------------------------------------------------------- # Comparison Methods def _ensure_localized( self, arg, ambiguous="raise", nonexistent="raise",...
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) self._freq = result._freq return self # -------------------------------------------------------------- # Reductions
def maybe_infer_freq(freq): freq_infer = True freq = None return freq, freq_infer def _ensure_datetimelike_to_i8(other, to_utc=False): """ Helper for coercing an input scalar or array to i8. Parameters ---------- other : 1d array to_utc : bool, default False ...
def maybe_infer_freq(freq): freq_infer = True freq = None return freq, freq_infer
from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_int64, is_bool_dtype, is_dtype_equal, is_float, is_integer, is_list_like, is_period_dtype, is_scalar, ) from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes....
from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_int64, is_bool_dtype, is_categorical_dtype, is_dtype_equal, is_float, is_integer, is_list_like, is_period_dtype, is_scalar, needs_i8_conversion, ) from pandas.core.dtypes.c...
from pandas.core.arrays import ( ExtensionOpsMixin, TimedeltaArray, ) from pandas.core.arrays.datetimelike import ( DatetimeLikeArrayMixin, _ensure_datetimelike_to_i8, ) import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.numer...
from pandas.core.arrays import ( ExtensionOpsMixin, TimedeltaArray, ) from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.numeric import Int64Index
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): return np.array_equal(self.asi8, other.asi8) def _ensure_localized( self, arg, ambiguous="raise", nonexistent="raise", from_utc=False ): # See DatetimeLikeArrayMixin._ensure_localized.__doc__ if getattr(self, "tz",...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): return np.array_equal(self.asi8, other.asi8) @Appender(_index_shared_docs["contains"] % _index_doc_kwargs) def __contains__(self, key): try:
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["where"] % _index_doc_kwargs) def where(self, cond, other=None): other = _ensure_datetimelike_to_i8(other, to_utc=True) values = _ensure_datetimelike_to_i8(self, to_utc=True) result = np.where(c...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["where"] % _index_doc_kwargs) def where(self, cond, other=None): values = self.view("i8") if is_scalar(other) and isna(other): other = NaT.value else: # Do type inferen...
class TestWhere: i2 = i.copy() i2 = Index([pd.NaT, pd.NaT] + i[2:].tolist()) result = i.where(notna(i2), i2.values) tm.assert_index_equal(result, i2) def test_where_tz(self): i = pd.date_range("20130101", periods=3, tz="US/Eastern") result = i.where(notna(i))
class TestWhere: i2 = i.copy() i2 = Index([pd.NaT, pd.NaT] + i[2:].tolist()) result = i.where(notna(i2), i2._values) tm.assert_index_equal(result, i2) def test_where_invalid_dtypes(self): dti = pd.date_range("20130101", periods=3, tz="US/Eastern") i2 = dti.copy() ...
class TestWhere: result = i.where(notna(i2), i2.values) tm.assert_index_equal(result, i2) class TestTake: def test_take(self):
class TestWhere: result = i.where(notna(i2), i2.values) tm.assert_index_equal(result, i2) def test_where_invalid_dtypes(self): pi = period_range("20130101", periods=5, freq="D") i2 = pi.copy() i2 = pd.PeriodIndex([pd.NaT, pd.NaT] + pi[2:].tolist(), freq="D") with p...
import numpy as np import pytest import pandas as pd from pandas import Index, Timedelta, TimedeltaIndex, timedelta_range import pandas._testing as tm
import numpy as np import pytest import pandas as pd from pandas import Index, Timedelta, TimedeltaIndex, notna, timedelta_range import pandas._testing as tm
class TestGetItem: class TestWhere: # placeholder for symmetry with DatetimeIndex and PeriodIndex tests pass class TestTake:
class TestGetItem: class TestWhere: def test_where_invalid_dtypes(self): tdi = timedelta_range("1 day", periods=3, freq="D", name="idx") i2 = tdi.copy() i2 = Index([pd.NaT, pd.NaT] + tdi[2:].tolist()) with pytest.raises(TypeError, match="Where requires matching dtype"): ...
class Index(IndexOpsMixin, PandasObject): is_null_slicer = start is None and stop is None is_index_slice = is_int(start) and is_int(stop) is_positional = is_index_slice and not self.is_integer() if kind == "getitem": """
class Index(IndexOpsMixin, PandasObject): is_null_slicer = start is None and stop is None is_index_slice = is_int(start) and is_int(stop) is_positional = is_index_slice and not ( self.is_integer() or self.is_categorical() ) if kind == "getitem": """
class CategoricalIndex(Index, accessor.PandasDelegate): take_nd = take def map(self, mapper): """ Map values using input correspondence (a dict, Series, or function).
class CategoricalIndex(Index, accessor.PandasDelegate): take_nd = take @Appender(_index_shared_docs["_maybe_cast_slice_bound"]) def _maybe_cast_slice_bound(self, label, side, kind): if kind == "loc": return label return super()._maybe_cast_slice_bound(label, side, kind) d...
class TestCategoricalIndex: df.reindex(["a"], limit=2) def test_loc_slice(self): # slicing # not implemented ATM # GH9748 msg = ( "cannot do slice indexing on {klass} with these " r"indexers \[1\] of {kind}".format( klass=str(Cate...
class TestCategoricalIndex: df.reindex(["a"], limit=2) def test_loc_slice(self): # GH9748 with pytest.raises(KeyError, match="1"): self.df.loc[1:5] result = self.df.loc["b":"c"] expected = self.df.iloc[[2, 3, 4]] tm.assert_frame_equal(result, expecte...
class TestCategoricalIndex: # GH-17569 cat_idx = CategoricalIndex(idx_values, ordered=ordered_fixture) df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx) # scalar selection result = df.loc[idx_values[0]]
class TestCategoricalIndex: # GH-17569 cat_idx = CategoricalIndex(idx_values, ordered=ordered_fixture) df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx) sl = slice(idx_values[0], idx_values[1]) # scalar selection result = df.loc[idx_values[0]]
class TestCategoricalIndex: expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"]) tm.assert_frame_equal(result, expected) # scalar assignment result = df.copy() result.loc[idx_values[0]] = "qux"
class TestCategoricalIndex: expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"]) tm.assert_frame_equal(result, expected) # slice selection result = df.loc[sl] expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"]) tm.assert_frame_equal(r...
class TestCategoricalIndex: result.loc[idx_values[:2], "A"] = ["qux", "qux2"] expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx) tm.assert_frame_equal(result, expected)
class TestCategoricalIndex: result.loc[idx_values[:2], "A"] = ["qux", "qux2"] expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx) tm.assert_frame_equal(result, expected) # slice assignment result = df.copy() result.loc[sl, "A"] = ["qux", "qux2"] ex...
from django.db import NotSupportedError, transaction from django.db.backends import utils from django.utils import timezone from django.utils.encoding import force_str class BaseDatabaseOperations:
from django.db import NotSupportedError, transaction from django.db.backends import utils from django.utils import timezone from django.utils.encoding import force_str from django.utils.regex_helper import _lazy_re_compile class BaseDatabaseOperations:
class BaseDatabaseOperations: # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported. explain_prefix = None def __init__(self, connection): self.connection = connection self._cache = None
class BaseDatabaseOperations: # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported. explain_prefix = None extract_trunc_lookup_pattern = _lazy_re_compile(r"[\w\-_()]+") def __init__(self, connection): self.connection = connection self._cache = None
class Extract(TimezoneMixin, Transform): super().__init__(expression, **extra) def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) lhs_output_field = self.lhs.output_field if isinstance(lhs_output_field, DateTimeField):
class Extract(TimezoneMixin, Transform): super().__init__(expression, **extra) def as_sql(self, compiler, connection): if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.lookup_name): raise ValueError("Invalid lookup_name: %s" % self.lookup_name) sql, params = com...
class TruncBase(TimezoneMixin, Transform): super().__init__(expression, output_field=output_field, **extra) def as_sql(self, compiler, connection): inner_sql, inner_params = compiler.compile(self.lhs) tzname = None if isinstance(self.lhs.output_field, DateTimeField):
class TruncBase(TimezoneMixin, Transform): super().__init__(expression, output_field=output_field, **extra) def as_sql(self, compiler, connection): if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.kind): raise ValueError("Invalid kind: %s" % self.kind) inner_sql...
class DateFunctionTests(TestCase): self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2) def test_extract_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50,...
class DateFunctionTests(TestCase): self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2) def test_extract_lookup_name_sql_injection(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(201...
class DateFunctionTests(TestCase): ) self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2) def test_trunc_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
class DateFunctionTests(TestCase): ) self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2) def test_trunc_lookup_name_sql_injection(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 1...
def resolve_redirects(self, resp, req, stream=False, timeout=None, except KeyError: pass extract_cookies_to_jar(prepared_request._cookies, prepared_request, resp.raw) prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared...
def resolve_redirects(self, resp, req, stream=False, timeout=None, except KeyError: pass extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared_request._coo...
def _get_object(data, position, as_class, tz_aware, uuid_subtype): object = _elements_to_dict(encoded, as_class, tz_aware, uuid_subtype) position += obj_size if "$ref" in object: return (DBRef(object.pop("$ref"), object.pop("$id"), object.pop("$db", None), object), position) ...
def _get_object(data, position, as_class, tz_aware, uuid_subtype): object = _elements_to_dict(encoded, as_class, tz_aware, uuid_subtype) position += obj_size if "$ref" in object: return (DBRef(object.pop("$ref"), object.pop("$id", None), object.pop("$db", None), object), positi...
from bson.binary import Binary, UUIDLegacy, OLD_UUID_SUBTYPE, UUID_SUBTYPE from bson.code import Code from bson.objectid import ObjectId from bson.py3compat import b from bson.son import SON
from bson.binary import Binary, UUIDLegacy, OLD_UUID_SUBTYPE, UUID_SUBTYPE from bson.code import Code from bson.dbref import DBRef from bson.objectid import ObjectId from bson.py3compat import b from bson.son import SON
def test_bad_encode(self): self.assertRaises(InvalidDocument, c.save, {"x": c}) warnings.simplefilter("default") def test_as_class(self): c = self.db.test c.drop()
def test_bad_encode(self): self.assertRaises(InvalidDocument, c.save, {"x": c}) warnings.simplefilter("default") def test_bad_dbref(self): c = self.db.test c.drop() # Incomplete DBRefs. self.assertRaises( InvalidDocument, c.insert, {'ref': {'...
def __init__(self, password): def load(self, stream): '''read vault steam and return python object''' return yaml.load(self.vault.decrypt(stream)) def dump(self, data, stream=None): '''encrypt data and print stdout or write to stream'''
def __init__(self, password): def load(self, stream): '''read vault steam and return python object''' return yaml.safe_load(self.vault.decrypt(stream)) def dump(self, data, stream=None): '''encrypt data and print stdout or write to stream'''
import os from tempfile import mkstemp from testfixtures import ShouldRaise from ansible.errors import AnsibleError here = os.path.dirname(os.path.abspath(__file__))
import os from tempfile import mkstemp from ansible.errors import AnsibleError from testfixtures import ShouldRaise from yaml.constructor import ConstructorError here = os.path.dirname(os.path.abspath(__file__))
def test_cannot(self): with ShouldRaise(AnsibleError('Decryption failed')): vault.load(open(fpath).read()) class TestVaultDump(object): def _getTargetClass(self):
def test_cannot(self): with ShouldRaise(AnsibleError('Decryption failed')): vault.load(open(fpath).read()) def test_not_pwned(self): fpath = os.path.join(here, 'file', 'pwned.txt') vault = self._makeOne('password') with ShouldRaise(ConstructorError): vault.lo...
def run_tests(self): setup( name='ansible-vault', version='1.0.4', author='Tomohiro NAKAMURA', author_email='quickness.net@gmail.com', url='https://github.com/jptomo/ansible-vault', description='R/W an ansible-vault yaml file', long_description=_read('README.rst'), packages=find_package...
def run_tests(self): setup( name='ansible-vault', version='1.0.5', author='Tomohiro NAKAMURA', author_email='quickness.net@gmail.com', url='https://github.com/tomoh1r/ansible-vault', description='R/W an ansible-vault yaml file', long_description=_read('README.rst'), packages=find_packag...
from django.core.mail import EmailMultiAlternatives from django.template import loader from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.utils.text import capfirst from django.utils.translation import ugettext, ugettext_lazy as _ UserModel = get_user_model() ...
from django.core.mail import EmailMultiAlternatives from django.template import loader from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.utils.six import PY3 from django.utils.text import capfirst from django.utils.translation import ugettext, ugettext_lazy as...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ active_users = UserModel._default_manager.filter(**{ '%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True, ...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_na...
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] email_field_name = UserModel.get_email_field_name() for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override context = { 'email': email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64...
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override user_email = getattr(user, email_field_name) context = { 'email': user_email, 'domain': domain, ...
class PasswordResetForm(forms.Form): context.update(extra_email_context) self.send_mail( subject_template_name, email_template_name, context, from_email, email, html_email_template_name=html_email_template_name, )
class PasswordResetForm(forms.Form): context.update(extra_email_context) self.send_mail( subject_template_name, email_template_name, context, from_email, user_email, html_email_template_name=html_email_template_name, )
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_nonexistent_email(self): """ Test nonexistent email address. This should not fail because it would
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_user_email_unicode_collision(self): User.objects.create_user('mike123', 'mike@example.org', 'test123') User.ob...
Make api awesomeness ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import inspect import os # Import Salt libs import salt.log # pylint: disable=W0611 import salt.client import salt.config import salt.runner import salt.syspaths import salt.wheel import salt.utils.a...
Make api awesomeness ''' from __future__ import absolute_import, print_function, unicode_literals import copy # Import Python libs import inspect import logging import os # Import Salt libs import salt.log # pylint: disable=W0611 import salt.auth import salt.client import salt.config import salt.daemons.masterapi i...