buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def pivot_table( agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype) table = agged if table.index.nlevels > 1: # Related GH #17123 # If index_names are integers, determine whether the integers refer # to the level position or name.
def pivot_table( agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype) table = agged # GH17038, this check should only happen if index is defined (not None) if table.index.nlevels > 1 and index: # Related GH #17123 # If index_names are integers, determine whether the ...
class TestPivotTable: totals = table.loc[("All", ""), value_col] assert totals == self.data[value_col].mean() # no rows rtable = self.data.pivot_table( columns=["AA", "BB"], margins=True, aggfunc=np.mean ) assert isinstance(rtable, Series) ta...
class TestPivotTable: totals = table.loc[("All", ""), value_col] assert totals == self.data[value_col].mean() table = self.data.pivot_table(index=["AA", "BB"], margins=True, aggfunc="mean") for item in ["DD", "EE", "FF"]: totals = table.loc[("All", ""), item]
class TestPivotTable: tm.assert_frame_equal(expected, result) def test_pivot_integer_columns(self): # caused by upstream bug in unstack
class TestPivotTable: tm.assert_frame_equal(expected, result) @pytest.mark.parametrize("cols", [(1, 2), ("a", "b"), (1, "b"), ("a", 1)]) def test_pivot_table_multiindex_only(self, cols): # GH 17038 df2 = DataFrame({cols[0]: [1, 2, 3], cols[1]: [1, 2, 3], "v": [4, 5, 6]}) resul...
import unittest from paramiko import ( Transport, SecurityOptions, ServerInterface, RSAKey, DSSKey, SSHException, ChannelException, Packetizer, ) from paramiko import AUTH_FAILED, AUTH_SUCCESSFUL from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
import unittest from paramiko import ( Transport, SecurityOptions, ServerInterface, RSAKey, DSSKey, SSHException, ChannelException, Packetizer, Channel, ) from paramiko import AUTH_FAILED, AUTH_SUCCESSFUL from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
class NullServer (ServerInterface): def check_global_request(self, kind, msg): self._global_request = kind return False def check_channel_x11_request(self, channel, single_connection, auth_protocol, auth_cookie, screen_number): self._x11_single_connection = single_connection
class NullServer (ServerInterface): def check_global_request(self, kind, msg): self._global_request = kind # NOTE: for w/e reason, older impl of this returned False always, even # tho that's only supposed to occur if the request cannot be served. # For now, leaving that the default ...
class TransportTest(unittest.TestCase): # sendall() accepts a memoryview instance chan.sendall(memoryview(data)) self.assertEqual(sfile.read(len(data)), data)
class TransportTest(unittest.TestCase): # sendall() accepts a memoryview instance chan.sendall(memoryview(data)) self.assertEqual(sfile.read(len(data)), data) def test_server_rejects_open_channel_without_auth(self): try: self.setup_test_server(connect_kwargs=...
import OFS.interfaces from AccessControl import safe_builtins from Acquisition import aq_base from MultiMapping import MultiMapping from zExceptions import NotFound
import OFS.interfaces from AccessControl import safe_builtins from AccessControl.SecurityManagement import getSecurityManager from Acquisition import aq_base from MultiMapping import MultiMapping from zExceptions import NotFound
def boboAwareZopeTraverse(object, path_items, econtext): necessary (bobo-awareness). """ request = getattr(econtext, 'request', None) path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if name == '_': warnings.warn('Traversi...
def boboAwareZopeTraverse(object, path_items, econtext): necessary (bobo-awareness). """ request = getattr(econtext, 'request', None) validate = getSecurityManager().validate path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if OFS...
from chameleon.tales import NotExpr from chameleon.tales import StringExpr from AccessControl.ZopeGuards import guarded_apply from AccessControl.ZopeGuards import guarded_getattr from AccessControl.ZopeGuards import guarded_getitem
from chameleon.tales import NotExpr from chameleon.tales import StringExpr from AccessControl.SecurityManagement import getSecurityManager from AccessControl.ZopeGuards import guarded_apply from AccessControl.ZopeGuards import guarded_getattr from AccessControl.ZopeGuards import guarded_getitem
class BoboAwareZopeTraverse: def traverse(cls, base, request, path_items): """See ``zope.app.pagetemplate.engine``.""" path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if name == '_': warnings.warn...
class BoboAwareZopeTraverse: def traverse(cls, base, request, path_items): """See ``zope.app.pagetemplate.engine``.""" validate = getSecurityManager().validate path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() ...
from AccessControl import safe_builtins from zExceptions import NotFound from zope.component.testing import PlacelessSetup class EngineTestsBase(PlacelessSetup):
from AccessControl import safe_builtins from zExceptions import NotFound from zope.component.testing import PlacelessSetup from zope.location.interfaces import LocationError class EngineTestsBase(PlacelessSetup):
def test_underscore_traversal(self): with self.assertRaises(NotFound): ec.evaluate("context/__class__") with self.assertRaises(NotFound): ec.evaluate("nocall: random/_itertools/repeat") with self.assertRaises(NotFound): ec.evaluate("random/_itertools/repeat/...
def test_underscore_traversal(self): with self.assertRaises(NotFound): ec.evaluate("context/__class__") with self.assertRaises((NotFound, LocationError)): ec.evaluate("nocall: random/_itertools/repeat") with self.assertRaises((NotFound, LocationError)): ec.e...
DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zExceptions import NotFound from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable from .util import useChameleonEngine
DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from zExceptions import NotFound from zope.component import provideUtility from zope.location.interfaces import Locati...
class AqPageTemplate(Implicit, PageTemplate): pass class Folder(util.Base): pass
class AqPageTemplate(Implicit, PageTemplate): pass class AqZopePageTemplate(Implicit, ZopePageTemplate): pass class Folder(util.Base): pass
def setUp(self): self.folder = f = Folder() f.laf = AqPageTemplate() f.t = AqPageTemplate() self.policy = UnitTestSecurityPolicy() self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy) noSecurityManager() # Use the new policy.
def setUp(self): self.folder = f = Folder() f.laf = AqPageTemplate() f.t = AqPageTemplate() f.z = AqZopePageTemplate('testing') self.policy = UnitTestSecurityPolicy() self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy) noSecurityManager() # Use the ne...
def test_underscore_traversal(self): t() t.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises(NotFound): t() t.write('<p tal:content="random/_itertools/repeat/foobar"/>') with self.assertRaises(NotFound): t()
def test_underscore_traversal(self): t() t.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises((NotFound, LocationError)): t() t.write('<p tal:content="random/_itertools/repeat/foobar"/>') with self.assertRaises((NotFound, Locati...
from django.utils.cache import ( ) from django.utils.deprecation import MiddlewareMixin, RemovedInDjango21Warning from django.utils.encoding import force_text from django.utils.six.moves.urllib.parse import urlparse
from django.utils.cache import ( ) from django.utils.deprecation import MiddlewareMixin, RemovedInDjango21Warning from django.utils.encoding import force_text from django.utils.http import escape_leading_slashes from django.utils.six.moves.urllib.parse import urlparse
class CommonMiddleware(MiddlewareMixin): POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'): raise RuntimeError( "You called this URL via %(method)s, but the URL d...
class CommonMiddleware(MiddlewareMixin): POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if settings.DEBUG and request.method in ('POST', 'PUT', ...
from django.utils import lru_cache, six from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str, force_text from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS, urlquote from django.utils.regex_helper import normalize from django...
from django.utils import lru_cache, six from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str, force_text from django.utils.functional import cached_property from django.utils.http import ( RFC3986_SUBDELIMS, escape_leading_slashes, urlquote, ) from django.utils.regex_he...
class RegexURLResolver(LocaleRegexProvider): # safe characters from `pchar` definition of RFC 3986 url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@')) # Don't allow construction of scheme relative urls. if u...
class RegexURLResolver(LocaleRegexProvider): # safe characters from `pchar` definition of RFC 3986 url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@')) # Don't allow construction of scheme relative urls. retu...
def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8', value = unquote(nv[1].replace(b'+', b' ')) r.append((name, value)) return r
def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8', value = unquote(nv[1].replace(b'+', b' ')) r.append((name, value)) return r def escape_leading_slashes(url): """ If redirecting to an absolute path (two leading slashes), a slash must be escaped to prevent...
class CommonMiddlewareTest(SimpleTestCase): self.assertEqual(r.status_code, 301) self.assertEqual(r.url, '/needsquoting%23/') @override_settings(APPEND_SLASH=False, PREPEND_WWW=True) def test_prepend_www(self): request = self.rf.get('/path/')
class CommonMiddlewareTest(SimpleTestCase): self.assertEqual(r.status_code, 301) self.assertEqual(r.url, '/needsquoting%23/') @override_settings(APPEND_SLASH=True) def test_append_slash_leading_slashes(self): """ Paths starting with two slashes are escaped to prevent open redire...
urlpatterns = [ url(r'^noslash$', views.empty_view), url(r'^slash/$', views.empty_view), url(r'^needsquoting#/$', views.empty_view), ]
urlpatterns = [ url(r'^noslash$', views.empty_view), url(r'^slash/$', views.empty_view), url(r'^needsquoting#/$', views.empty_view), # Accepts paths with two leading slashes. url(r'^(.+)/security/$', views.empty_view), ]
class HttpDateProcessingTests(unittest.TestCase): def test_parsing_asctime(self): parsed = http.parse_http_date('Sun Nov 6 08:49:37 1994') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37))
class HttpDateProcessingTests(unittest.TestCase): def test_parsing_asctime(self): parsed = http.parse_http_date('Sun Nov 6 08:49:37 1994') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) class EscapeLeadingSlashesTests(unittest.TestCase): def test(self): ...
def update_user(self, context, user_id, user): raise exception.UserNotFound(user_id=user_id) user_ref = self.identity_api.update_user(context, user_id, user) return {'user': user_ref} def delete_user(self, context, user_id):
def update_user(self, context, user_id, user): raise exception.UserNotFound(user_id=user_id) user_ref = self.identity_api.update_user(context, user_id, user) # If the password was changed or the user was disabled we clear tokens if user.get('password') or user.get('enabled', True) ...
def set_user_enabled(self, context, user_id, user): return self.update_user(context, user_id, user) def set_user_password(self, context, user_id, user): user_ref = self.update_user(context, user_id, user) try: for token_id in self.token_api.list_tokens(context, user_id): ...
def set_user_enabled(self, context, user_id, user): return self.update_user(context, user_id, user) def set_user_password(self, context, user_id, user): return self.update_user(context, user_id, user) def update_user_tenant(self, context, user_id, user): """Update the default tenant.""...
from keystone.common import wsgi class AdminRouter(wsgi.ComposingRouter): def __init__(self): mapper = routes.Mapper()
from keystone.common import wsgi LOG = logging.getLogger(__name__) class AdminRouter(wsgi.ComposingRouter): def __init__(self): mapper = routes.Mapper()
def authenticate(self, context, auth=None): # If the user is disabled don't allow them to authenticate if not user_ref.get('enabled', True): raise exception.Forbidden(message='User has been disabled') except AssertionError as e: raise exce...
def authenticate(self, context, auth=None): # If the user is disabled don't allow them to authenticate if not user_ref.get('enabled', True): LOG.warning('User %s is disabled' % user_id) raise exception.Unauthorized() except AssertionEr...
def authenticate(self, context, auth=None): user_ref = old_token_ref['user'] tenants = self.identity_api.get_tenants_for_user(context, user_ref['id']) if tenant_id:
def authenticate(self, context, auth=None): user_ref = old_token_ref['user'] # If the user is disabled don't allow them to authenticate current_user_ref = self.identity_api.get_user( context=context, ...
def test_change_password_invalidates_token(self): client.tokens.authenticate, token=token_id) def test_user_create_update_delete(self): from keystoneclient import exceptions as client_exceptions
def test_change_password_invalidates_token(self): client.tokens.authenticate, token=token_id) def test_disable_user_invalidates_token(self): from keystoneclient import exceptions as client_exceptions admin_client = self.get_client(admin=True) ...
def test_user_create_update_delete(self): user = client.users.get(user.id) self.assertFalse(user.enabled) self.assertRaises(client_exceptions.AuthorizationFailure, self._client, username=test_username, password='password')
def test_user_create_update_delete(self): user = client.users.get(user.id) self.assertFalse(user.enabled) self.assertRaises(client_exceptions.Unauthorized, self._client, username=test_username, password='password')
def test_user_create_update_delete(self): user = client.users.get(user.id) self.assertFalse(user.enabled) self.assertRaises(client_exceptions.AuthorizationFailure, self._client, username=test_username, password='password')
def test_user_create_update_delete(self): user = client.users.get(user.id) self.assertFalse(user.enabled) self.assertRaises(client_exceptions.Unauthorized, self._client, username=test_username, password='password')
logger = logging.getLogger(__name__) title_regex = re.compile(r"(?<=<title>).*(?=</title>)") id_regex = re.compile(r"(?<=<id>)\d*(?=</id>)") text_regex = re.compile(r"(?<=<text xml:space=\"preserve\">).*(?=</text)") info_regex = re.compile(r"{[^{]*?}") html_regex = re.compile(r"&lt;!--[^-]*--&gt;") ref_regex = re.comp...
logger = logging.getLogger(__name__) title_regex = re.compile(r"(?<=<title>).*(?=</title>)") id_regex = re.compile(r"(?<=<id>)\d*(?=</id>)") text_tag_regex = re.compile(r"(?<=<text).*?(?=>)") text_regex = re.compile(r"(?<=<text>).*(?=</text)") info_regex = re.compile(r"{[^{]*?}") html_regex = re.compile(r"&lt;!--[^-]*...
def _process_wp_text(article_title, article_text, wp_to_id): return None, None # remove the text tags text_search = text_regex.search(article_text) if text_search is None: return None, None text = text_search.group(0)
def _process_wp_text(article_title, article_text, wp_to_id): return None, None # remove the text tags text_search = text_tag_regex.sub("", article_text) text_search = text_regex.search(text_search) if text_search is None: return None, None text = text_search.group(0)
class tqdm(Comparable): # apply custom scale if necessary if unit_scale and unit_scale not in (True, 1): total *= unit_scale n *= unit_scale if rate: rate *= unit_scale # by default rate = 1 / self.avg_time
class tqdm(Comparable): # apply custom scale if necessary if unit_scale and unit_scale not in (True, 1): if total: total *= unit_scale n *= unit_scale if rate: rate *= unit_scale # by default rate = 1 / self.avg_time
def test_infinite_total(): pass @with_setup(pretest, posttest) def test_unit(): """Test SI unit prefix"""
def test_infinite_total(): pass @with_setup(pretest, posttest) def test_nototal(): """Test unknown total length""" with closing(StringIO()) as our_file: for i in tqdm((i for i in range(10)), file=our_file, unit_scale=10): pass assert "100it" in our_file.getvalue() @wi...
class Scheduler(object): if (best_task and batched_params and task.family == best_task.family and len(batched_tasks) < max_batch_size and task.is_batchable() and all( task.params.get(name) == value for name, value in unbatched_params.items())): for na...
class Scheduler(object): if (best_task and batched_params and task.family == best_task.family and len(batched_tasks) < max_batch_size and task.is_batchable() and all( task.params.get(name) == value for name, value in unbatched_params.items()) and ...
class SchedulerApiTest(unittest.TestCase): self.assertEqual({'a': ['1', '2', '3']}, response['task_params']) self.assertEqual('A', response['task_family']) def test_get_work_with_batch_items_with_resources(self): self.sch.add_task_batcher(worker=WORKER, task_family='A', batched_args=['a']) ...
class SchedulerApiTest(unittest.TestCase): self.assertEqual({'a': ['1', '2', '3']}, response['task_params']) self.assertEqual('A', response['task_family']) def test_batch_ignore_items_not_ready(self): self.sch.add_task_batcher(worker=WORKER, task_family='A', batched_args=['a']) self...
class SchedulerApiTest(unittest.TestCase): not_nurtured_statuses = [DONE, UNKNOWN, DISABLED, PENDING, FAILED] for status in nurtured_statuses: print(status) self.assertEqual(set([status.lower()]), set(self.sch.task_list(status, ''))) for status in not_nurtured_statuses:...
class SchedulerApiTest(unittest.TestCase): not_nurtured_statuses = [DONE, UNKNOWN, DISABLED, PENDING, FAILED] for status in nurtured_statuses: self.assertEqual(set([status.lower()]), set(self.sch.task_list(status, ''))) for status in not_nurtured_statuses: self.assertEq...
def test_29248(self): target = os.readlink(r'C:\Users\All Users') self.assertTrue(os.path.samefile(target, r'C:\ProgramData')) @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") class Win32JunctionTests(unittest.TestCase):
def test_29248(self): target = os.readlink(r'C:\Users\All Users') self.assertTrue(os.path.samefile(target, r'C:\ProgramData')) def test_buffer_overflow(self): # Older versions would have a buffer overflow when detecting # whether a link source was a directory. This test ensures we ...
class TimeseriesGenerator(Sequence): self.reverse = reverse self.batch_size = batch_size def __len__(self): return int(np.ceil( (self.end_index - self.start_index) / (self.batch_size * self.stride))) def _empty_batch(self, num_rows):
class TimeseriesGenerator(Sequence): self.reverse = reverse self.batch_size = batch_size if self.start_index > self.end_index: raise ValueError('`start_index+length=%i > end_index=%i` ' 'is disallowed, as no part of the sequence ' ...
class TimeseriesGenerator(Sequence): def __getitem__(self, index): if self.shuffle: rows = np.random.randint( self.start_index, self.end_index, size=self.batch_size) else: i = self.start_index + self.batch_size * self.stride * index rows = np.arang...
class TimeseriesGenerator(Sequence): def __getitem__(self, index): if self.shuffle: rows = np.random.randint( self.start_index, self.end_index + 1, size=self.batch_size) else: i = self.start_index + self.batch_size * self.stride * index rows = np.a...
import numpy as np from numpy.testing import assert_allclose import pytest
from math import ceil import numpy as np from numpy.testing import assert_allclose, assert_raises import pytest
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 5 assert (np.allclose(data_gen[0][0], np.array([[[10], ...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 6 assert (np.allclose(data_gen[0][0], np.array([[[10], ...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 5 assert np.allclose(data_gen[0][0], np.array( [np.array(data[10:19:2]...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 6 assert np.allclose(data_gen[0][0], np.array( [np.array(data[10:19:2])...
from pandas.core.internals.construction import ( sanitize_index, to_arrays, ) from pandas.core.series import Series from pandas.io.formats import console, format as fmt
from pandas.core.internals.construction import ( sanitize_index, to_arrays, ) from pandas.core.ops.missing import dispatch_fill_zeros from pandas.core.series import Series from pandas.io.formats import console, format as fmt
class DataFrame(NDFrame): # iterate over columns return ops.dispatch_to_series(this, other, _arith_op) else: result = _arith_op(this.values, other.values) return self._constructor( result, index=new_index, columns=new_columns, copy=False ...
class DataFrame(NDFrame): # iterate over columns return ops.dispatch_to_series(this, other, _arith_op) else: with np.errstate(all="ignore"): result = _arith_op(this.values, other.values) result = dispatch_fill_zeros(func, this.values, other.values,...
class TestNumericArithmeticUnsorted: tm.assert_index_equal(index + index, 2 * index) tm.assert_index_equal(index - index, 0 * index) assert not (index - index).empty
class TestNumericArithmeticUnsorted: tm.assert_index_equal(index + index, 2 * index) tm.assert_index_equal(index - index, 0 * index) assert not (index - index).empty def test_fill_value_inf_masking(): # GH #27464 make sure we mask 0/1 with Inf and not NaN df = pd.DataFrame({"A": [0, 1,...
class Axes(_AxesBase): @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], label_namer="y") def hlines(self, y, xmin, xmax, colors='k', linestyles='solid', label='', **kwargs): """ Plot horizontal lines at each *y* from *xmin* to *xmax*.
class Axes(_AxesBase): @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], label_namer="y") def hlines(self, y, xmin, xmax, colors=None, linestyles='solid', label='', **kwargs): """ Plot horizontal lines at each *y* from *xmin* to *xmax*.
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: 'k' linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: :rc:`lines.color` linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], label_namer="x") def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', label='', **kwargs): """ Plot vertical lines.
class Axes(_AxesBase): @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], label_namer="x") def vlines(self, x, ymin, ymax, colors=None, linestyles='solid', label='', **kwargs): """ Plot vertical lines.
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: 'k' linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: :rc:`lines.color` linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
def hist2d( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.hlines) def hlines( y, xmin, xmax, colors='k', linestyles='solid', label='', *, data=None, **kwargs): return gca().hlines( y, xmin, xmax, colors=colors, linestyles=lines...
def hist2d( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.hlines) def hlines( y, xmin, xmax, colors=None, linestyles='solid', label='', *, data=None, **kwargs): return gca().hlines( y, xmin, xmax, colors=colors, linestyles=line...
def violinplot( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.vlines) def vlines( x, ymin, ymax, colors='k', linestyles='solid', label='', *, data=None, **kwargs): return gca().vlines( x, ymin, ymax, colors=colors, linestyles=l...
def violinplot( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.vlines) def vlines( x, ymin, ymax, colors=None, linestyles='solid', label='', *, data=None, **kwargs): return gca().vlines( x, ymin, ymax, colors=colors, linestyles=...
def test_vlines(): ax5.set_xlim(0, 15) @image_comparison(['hlines_basic', 'hlines_with_nan', 'hlines_masked'], extensions=['png']) def test_hlines():
def test_vlines(): ax5.set_xlim(0, 15) def test_vlines_default(): fig, ax = plt.subplots() with mpl.rc_context({'lines.color': 'red'}): lines = ax.vlines(0.5, 0, 1) assert mpl.colors.same_color(lines.get_color(), 'red') @image_comparison(['hlines_basic', 'hlines_with_nan', 'hlines_masked...
def test_hlines(): ax5.set_ylim(0, 15) @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5], np.ma.masked_equal([1, 2, 3, 4, 5], 4)]) @check_figures_equal(extensions=["png"])
def test_hlines(): ax5.set_ylim(0, 15) def test_hlines_default(): fig, ax = plt.subplots() with mpl.rc_context({'lines.color': 'red'}): lines = ax.hlines(0.5, 0, 1) assert mpl.colors.same_color(lines.get_color(), 'red') @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5], ...
from django.test.utils import override_settings from django.urls import reverse from django.utils.timezone import now from allauth.account.forms import BaseSignupForm, SignupForm from allauth.account.models import ( EmailAddress, EmailConfirmation,
from django.test.utils import override_settings from django.urls import reverse from django.utils.timezone import now from allauth.account.forms import BaseSignupForm, ResetPasswordForm, SignupForm from allauth.account.models import ( EmailAddress, EmailConfirmation,
class ConfirmationViewTests(TestCase): args=[key])) assert mock_perform_login.called
class ConfirmationViewTests(TestCase): args=[key])) assert mock_perform_login.called class TestCVE2019_19844(TestCase): global_request = RequestFactory().get('/') def test_user_email_unicode_collision(self): User = get_user_model() User.objects.create_user('m...
from collections import OrderedDict from datetime import timedelta
import unicodedata from collections import OrderedDict from datetime import timedelta
from .adapter import get_adapter from .app_settings import EmailVerificationMethod def get_next_redirect_url(request, redirect_field_name="next"): """ Returns the next URL to redirect to, if it was explicitly passed
from .adapter import get_adapter from .app_settings import EmailVerificationMethod def _unicode_ci_compare(s1, s2): """ Perform case-insensitive comparison of two identifiers, using the recommended algorithm from Unicode Technical Report 36, section 2.11.2(B)(2). """ norm_s1 = unicodedata.norm...
def filter_users_by_email(email): from .models import EmailAddress User = get_user_model() mails = EmailAddress.objects.filter(email__iexact=email) users = [e.user for e in mails.prefetch_related('user')] if app_settings.USER_MODEL_EMAIL_FIELD: q_dict = {app_settings.USER_MODEL_EMAIL_FIELD +...
def filter_users_by_email(email): from .models import EmailAddress User = get_user_model() mails = EmailAddress.objects.filter(email__iexact=email) users = [] for e in mails.prefetch_related('user'): if _unicode_ci_compare(e.email, email): users.append(e.user) if app_settings...
class Task(object): exc_desc = '%s[args=%s, kwargs=%s]' % (task_name, args, kwargs) # Fill in the positional arguments positional_params = [(n, p) for n, p in params if p.significant] for i, arg in enumerate(args): if i >= len(positional_params): raise parame...
class Task(object): exc_desc = '%s[args=%s, kwargs=%s]' % (task_name, args, kwargs) # Fill in the positional arguments positional_params = [(n, p) for n, p in params if not p.is_global] for i, arg in enumerate(args): if i >= len(positional_params): raise para...
class ParameterTest(unittest.TestCase): t1 = InsignificantParameterTask(foo='x', bar='y') self.assertEqual(t1.task_id, 'InsignificantParameterTask(bar=y)') t2 = InsignificantParameterTask('z') self.assertEqual(t2.foo, 'foo_default') self.assertEqual(t2.bar, 'z') self.ass...
class ParameterTest(unittest.TestCase): t1 = InsignificantParameterTask(foo='x', bar='y') self.assertEqual(t1.task_id, 'InsignificantParameterTask(bar=y)') t2 = InsignificantParameterTask('u', 'z') self.assertEqual(t2.foo, 'u') self.assertEqual(t2.bar, 'z') self.assertEq...
class TestRemoveGlobalParameters(unittest.TestCase): self.assertTrue(run_exit_status) return run_exit_status def test_use_config_class_1(self): self.run_and_check(['--MyConfig-mc-p', '99', '--mc-r', '55', 'NoopTask']) self.assertEqual(MyConfig().mc_p, 99)
class TestRemoveGlobalParameters(unittest.TestCase): self.assertTrue(run_exit_status) return run_exit_status def test_use_config_class_1(self): self.run_and_check(['--MyConfig-mc-p', '99', '--mc-r', '55', 'NoopTask']) self.assertEqual(MyConfig().mc_p, 99)
class TestRemoveGlobalParameters(unittest.TestCase): self.assertEqual(Dogs().n_dogs, 654) self.assertEqual(CatsWithoutSection().n_cats, 321) class TestParamWithDefaultFromConfig(unittest.TestCase):
class TestRemoveGlobalParameters(unittest.TestCase): self.assertEqual(Dogs().n_dogs, 654) self.assertEqual(CatsWithoutSection().n_cats, 321) def test_global_significant_param(self): """ We don't want any kind of global param to be positional """ class MyTask(luigi.Task): ...
from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_RE = re.compile( '^' # Beginning of word '(.*?)' # The URL in word '([.,:;!]+)' # Allowed non-wrapping, trailing punctuation ...
from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_CHARS = '.,:;!' WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;'), ('"', '"'), ('\'', '\'')] # List of possible strings used for b...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) simple_email_re = re.compile(r'^\S+@\S+\.\...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) @keep_lazy(str, SafeText)
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. match = TRAILING_PUNCTUATION_RE.match(middle) if match: middle = match.group(1) trail = match.group(2) + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS) if middle != stripped: trail = middle[len(stripped):] + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail words = word_split_re.split(force_text(text)) for i, word in enumerate(words): if '.' in word or '@' in word or ':' in word:
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if '@' not ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and simple_email_re.m...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and is_email_simple(m...
from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, html_safe, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, ) from django.utils.safestring import mark_safe
from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, html_safe, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, urlize, ) from django.utils.safestring import mark_safe
class TestUtilsHtml(SimpleTestCase): @html_safe class HtmlClass: pass
class TestUtilsHtml(SimpleTestCase): @html_safe class HtmlClass: pass def test_urlize_unchanged_inputs(self): tests = ( ('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test ('a' + '.' * 1000000) + 'a', # trailing_punctuation catas...
class InvalidModeException(CookiecutterException): Raised when cookiecutter is called with both `no_input==True` and `replay==True` at the same time. """
class InvalidModeException(CookiecutterException): Raised when cookiecutter is called with both `no_input==True` and `replay==True` at the same time. """ class FailedHookException(CookiecutterException): """ Raised when a hook script fails """
from binaryornot.check import is_binary from .exceptions import ( NonTemplatedInputDirException, ContextDecodingException, OutputDirExistsException ) from .find import find_template from .utils import make_sure_path_exists, work_in from .hooks import run_hook, EXIT_SUCCESS def copy_without_render(path, co...
from binaryornot.check import is_binary from .exceptions import ( NonTemplatedInputDirException, ContextDecodingException, FailedHookException, OutputDirExistsException ) from .find import find_template from .utils import make_sure_path_exists, work_in from .hooks import run_hook def copy_without_rend...
def generate_files(repo_dir, context=None, output_dir='.', # run pre-gen hook from repo_dir with work_in(repo_dir): if run_hook('pre_gen_project', project_dir, context) != EXIT_SUCCESS: logging.error("Stopping generation because pre_gen_project" " hook script didn'...
def generate_files(repo_dir, context=None, output_dir='.', # run pre-gen hook from repo_dir with work_in(repo_dir): try: run_hook('pre_gen_project', project_dir, context) except FailedHookException: shutil.rmtree(project_dir, ignore_errors=True) logging.error...
import tempfile from jinja2 import Template from cookiecutter import utils _HOOKS = [
import tempfile from jinja2 import Template from cookiecutter import utils from .exceptions import FailedHookException _HOOKS = [
def run_script(script_path, cwd='.'): shell=run_thru_shell, cwd=cwd ) return proc.wait() def run_script_with_context(script_path, cwd, context):
def run_script(script_path, cwd='.'): shell=run_thru_shell, cwd=cwd ) exit_status = proc.wait() if exit_status != EXIT_SUCCESS: raise FailedHookException( "Hook script failed (exit status: %d)" % exit_status) def run_script_with_context(script_path, cwd, context):
def run_script_with_context(script_path, cwd, context): ) as temp: temp.write(Template(contents).render(**context)) return run_script(temp.name, cwd) def run_hook(hook_name, project_dir, context):
def run_script_with_context(script_path, cwd, context): ) as temp: temp.write(Template(contents).render(**context)) run_script(temp.name, cwd) def run_hook(hook_name, project_dir, context):
def run_hook(hook_name, project_dir, context): script = find_hooks().get(hook_name) if script is None: logging.debug('No hooks found') return EXIT_SUCCESS return run_script_with_context(script, project_dir, context)
def run_hook(hook_name, project_dir, context): script = find_hooks().get(hook_name) if script is None: logging.debug('No hooks found') return run_script_with_context(script, project_dir, context)
Tests for `cookiecutter.hooks` module. import sys import os import stat from cookiecutter import hooks, utils def make_test_repo(name):
Tests for `cookiecutter.hooks` module. import sys import os import stat import pytest from cookiecutter import hooks, utils, exceptions def make_test_repo(name):
class TestExternalHooks(object): hooks.run_hook('post_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt'))
class TestExternalHooks(object): hooks.run_hook('post_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt')) def test_run_failing_hook(self): hook_path = os.path.join(self.hooks_path, 'pre_gen_project.py') tests_dir = os.path.join(self...
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = ( self.regex.fullmatch(path) if self._is_endpoint and self.regex.pattern.endswith('$') else self.regex.search(path) ) if match: # If there are any n...
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append('$') return ''.join(parts), converters
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append(r'\Z') return ''.join(parts), converters
class SimplifiedURLTests(SimpleTestCase): match = p.resolve('space%s/1/' % string.whitespace) self.assertEqual(match.kwargs, {'num': 1}) @override_settings(ROOT_URLCONF='urlpatterns.converter_urls') class ConverterTests(SimpleTestCase):
class SimplifiedURLTests(SimpleTestCase): match = p.resolve('space%s/1/' % string.whitespace) self.assertEqual(match.kwargs, {'num': 1}) def test_path_trailing_newlines(self): tests = [ '/articles/2003/\n', '/articles/2010/\n', '/en/foo/\n', '...
__metaclass__ = type from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute from ansible.utils.collection_loader import AnsibleCollectionLoader def _ensure_default_collection(collection_list=None):
__metaclass__ = type from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute from ansible.utils.collection_loader import AnsibleCollectionLoader from ansible.template import is_template, Environment from ansible.utils.display import Display display = Display() def _ens...
def _ensure_default_collection(collection_list=None): class CollectionSearch: # this needs to be populated before we can resolve tasks/roles/etc _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection) def _load_collections(self, attr, ds): #...
def _ensure_default_collection(collection_list=None): class CollectionSearch: # this needs to be populated before we can resolve tasks/roles/etc _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection, always_post_validat...
class CollectionSearch: if not ds: # don't return an empty collection list, just return None return None return ds
class CollectionSearch: if not ds: # don't return an empty collection list, just return None return None # This duplicates static attr checking logic from post_validate() # because if the user attempts to template a collection name, it will # error before it ever gets to th...
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",
def open_spam(self, url): "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") # Just commented them out. # Can't really tell why keep failing in windows and sparc.
def open_spam(self, url): "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") def test_local_file_open(self): class DummyURLopener(urllib.URLopener): def open_local_file(self, url): return url for url in ('l...
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') # bpo-35907: disallow the file reading with the type not allowed if not hasattr(self, name) or name == 'open_local_file': if proxy: return s...
from cryptography.hazmat.primitives.ciphers import modes class _CipherContext(object): _ENCRYPT = 1 _DECRYPT = 0 _MAX_CHUNK_SIZE = 2 ** 31 - 1 def __init__(self, backend, cipher, mode, operation): self._backend = backend
from cryptography.hazmat.primitives.ciphers import modes class _CipherContext(object): _ENCRYPT = 1 _DECRYPT = 0 _MAX_CHUNK_SIZE = 2 ** 30 - 1 def __init__(self, backend, cipher, mode, operation): self._backend = backend
class core(task.Config): class WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler() def create_remote_scheduler(self, host, port): return rpc.RemoteScheduler(host=host, port=port)
class core(task.Config): class WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler(prune_on_get_work=True) def create_remote_scheduler(self, host, port): return rpc.RemoteScheduler(host=host, port=port)
class scheduler(Config): visualization_graph = parameter.Parameter(default="svg", config_path=dict(section='scheduler', name='visualization-graph')) def fix_time(x): # Backwards compatibility for a fix in Dec 2014. Prior to the fix, pickled state might store datetime objects
class scheduler(Config): visualization_graph = parameter.Parameter(default="svg", config_path=dict(section='scheduler', name='visualization-graph')) prune_on_get_work = parameter.BoolParameter(default=False) def fix_time(x): # Backwards compatibility for a fix in Dec 2014. Prior to the fix, pickled stat...
class Worker(object): def __init__(self, worker_id, last_active=None): self.id = worker_id self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host) self.last_active = last_active # seconds since epoch self.started = time.time() ...
class Worker(object): def __init__(self, worker_id, last_active=None): self.id = worker_id self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host) self.last_active = last_active or time.time() # seconds since epoch self.started...
class CentralPlannerScheduler(Scheduler): # TODO: remove tasks that can't be done, figure out if the worker has absolutely # nothing it can wait for worker_id = kwargs['worker'] # Return remaining tasks that have no FAILED descendents self.update(worker_id, {'host': host})
class CentralPlannerScheduler(Scheduler): # TODO: remove tasks that can't be done, figure out if the worker has absolutely # nothing it can wait for if self._config.prune_on_get_work: self.prune() worker_id = kwargs['worker'] # Return remaining tasks that have no FA...
class WorkerExternalTaskTest(unittest.TestCase): worker_disconnect_delay=3, disable_persist=3, disable_window=5, disable_fai...
class WorkerExternalTaskTest(unittest.TestCase): worker_disconnect_delay=3, disable_persist=3, disable_window=5, disable_fai...