buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class DRTVIE(SubtitlesInfoExtractor): } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') programcard = self._download_json( 'http://www.dr.dk/mu/programcard/expanded/%s' % video_id, video_id, 'Downloading video JSON')
class DRTVIE(SubtitlesInfoExtractor): } def _real_extract(self, url): video_id = self._match_id(url) programcard = self._download_json( 'http://www.dr.dk/mu/programcard/expanded/%s' % video_id, video_id, 'Downloading video JSON')
class DRTVIE(SubtitlesInfoExtractor): title = data['Title'] description = data['Description'] timestamp = parse_iso8601(data['CreatedTime'][:-5]) thumbnail = None duration = None
class DRTVIE(SubtitlesInfoExtractor): title = data['Title'] description = data['Description'] timestamp = parse_iso8601(data['CreatedTime']) thumbnail = None duration = None
def parse_iso8601(date_str, delimiter='T'): return None m = re.search( r'Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$', date_str) if not m: timezone = datetime.timedelta()
def parse_iso8601(date_str, delimiter='T'): return None m = re.search( r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)', date_str) if not m: timezone = datetime.timedelta()
def parse_iso8601(date_str, delimiter='T'): timezone = datetime.timedelta( hours=sign * int(m.group('hours')), minutes=sign * int(m.group('minutes'))) date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter) dt = datetime.datetime.strptime(date_str, date_format) - timez...
def parse_iso8601(date_str, delimiter='T'): timezone = datetime.timedelta( hours=sign * int(m.group('hours')), minutes=sign * int(m.group('minutes'))) date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter) dt = datetime.datetime.strptime(date_str, date_format) - timezo...
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...
The `pillar_roots` wheel module is used to manage files under the pillar roots directories on the master server. """ # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os # Import salt libs import salt.utils.files import salt.utils.path # Import 3rd-party libs from ...
The `pillar_roots` wheel module is used to manage files under the pillar roots directories on the master server. """ from __future__ import absolute_import, print_function, unicode_literals import os import salt.utils.files import salt.utils.path import salt.utils.verify from salt.ext import six
def write(data, path, saltenv="base", index=0): return ( "The path passed in {0} is not relative to the environment " "{1}" ).format(path, saltenv) dest = os.path.join(__opts__["pillar_roots"][saltenv][index], path) dest_dir = os.path.dirname(dest) if not os.path.isdir(dest_dir):
def write(data, path, saltenv="base", index=0): return ( "The path passed in {0} is not relative to the environment " "{1}" ).format(path, saltenv) roots_dir = __opts__["pillar_roots"][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.verify.clean_path(roots_...
def stderr(branch_name): def new_command(branch_name): return [cmd.format(branch_name) for cmd in [ 'git branch -d {0} && git branch {0}', 'git branch -D {0} && git branch {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, branch_name', [ ('git branch foo', 'foo'), ('git branch b...
def stderr(branch_name): def new_command(branch_name): return [cmd.format(branch_name) for cmd in [ 'git branch -d {0} && git branch {0}', 'git branch -d {0} && git checkout -b {0}', 'git branch -D {0} && git branch {0}', 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}'...
from thefuck.utils import eager @git_support def match(command): return ('branch' in command.script and "fatal: A branch named '" in command.stderr and " already exists." in command.stderr)
from thefuck.utils import eager @git_support def match(command): return ("fatal: A branch named '" in command.stderr and " already exists." in command.stderr)
def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '([^']*)' already exists.", command.stderr)[0] new_command_templates = [['git branch -d {0}', 'git branch {0}'], ['git branch -D {0}', 'git branch {0}'], ['git checko...
def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '([^']*)' already exists.", command.stderr)[0] new_command_templates = [['git branch -d {0}', 'git branch {0}'], ['git branch -d {0}', 'git checkout -b {0}'], ['git b...
class _Window(PandasObject, SelectionMixin): except (ValueError, TypeError): raise TypeError("cannot handle this type -> {0}".format(values.dtype)) # Always convert inf to nan values[np.isinf(values)] = np.NaN return values
class _Window(PandasObject, SelectionMixin): except (ValueError, TypeError): raise TypeError("cannot handle this type -> {0}".format(values.dtype)) # Convert inf to nan for C funcs inf = np.isinf(values) if inf.any(): values = np.where(inf, np.nan, values...
class TestRolling(Base): result = df.rolling(2, axis=axis_frame).count() tm.assert_frame_equal(result, expected)
class TestRolling(Base): result = df.rolling(2, axis=axis_frame).count() tm.assert_frame_equal(result, expected) def test_readonly_array(self): # GH-27766 arr = np.array([1, 3, np.nan, 3, 5]) arr.setflags(write=False) result = pd.Series(arr).rolling(2).mean() ...
from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
from urllib.parse import quote from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, str): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, str): exception_repr = message context = { 'request_path': quote(request.path), 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) con...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested resource was not found on this server.</p>') body = template.render(Context(context)) content_type = 't...
from django.db import close_old_connections, connection from django.test import ( RequestFactory, SimpleTestCase, TransactionTestCase, override_settings, ) class HandlerTests(SimpleTestCase):
from django.db import close_old_connections, connection from django.test import ( RequestFactory, SimpleTestCase, TransactionTestCase, override_settings, ) from django.utils.version import PY37 class HandlerTests(SimpleTestCase):
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertContains(response, '~%A9helloworld', status_code=404) response = self.client.get('d%aao%aaw%aan%aal%aao%aaa%aad%aa/') self.assertContains(response, 'd%AAo...
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertEqual(response.status_code, 404) self.assertEqual(response.context['request_path'], '/~%25A9helloworld' if PY37 else '/%7E%25A9helloworld') response = sel...
class ModelAdmin(BaseModelAdmin): ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): inline_admin_formsets = [] for inline, formset in zip(inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(i...
class ModelAdmin(BaseModelAdmin): ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): # Edit permissions on parent model are required for editable inlines. can_edit_parent = self.has_change_permission(request, obj) if obj else self.has_add_permission(request) ...
class ModelAdmin(BaseModelAdmin): else: obj = self.get_object(request, unquote(object_id), to_field) if not self.has_view_or_change_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(...
class ModelAdmin(BaseModelAdmin): else: obj = self.get_object(request, unquote(object_id), to_field) if request.method == 'POST': if not self.has_change_permission(request, obj): raise PermissionDenied else: if not self.has...
from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase
from selenium.common.exceptions import NoSuchElementException from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase
class TestInlinePermissions(TestCase): ) @override_settings(ROOT_URLCONF='admin_inlines.urls') class SeleniumTests(AdminSeleniumTestCase):
class TestInlinePermissions(TestCase): ) @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestReadOnlyChangeViewInlinePermissions(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user('testing', password='password', is_staff=True) cls.user.user...
class SeleniumTests(AdminSeleniumTestCase): self.assertEqual(ProfileCollection.objects.all().count(), 1) self.assertEqual(Profile.objects.all().count(), 3) def test_delete_inlines(self): self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + r...
class SeleniumTests(AdminSeleniumTestCase): self.assertEqual(ProfileCollection.objects.all().count(), 1) self.assertEqual(Profile.objects.all().count(), 3) def test_add_inline_link_absent_for_view_only_parent_model(self): user = User.objects.create_user('testing', password='password', is_st...
class ArticleAdmin9(admin.ModelAdmin): site9 = admin.AdminSite(name='admin9') site9.register(Article, ArticleAdmin9) class ArticleAdmin10(admin.ModelAdmin): def has_change_permission(self, request, obj=None): return False site10 = admin.AdminSite(name='admin10') site10.register(Article, ArticleAdmin10)
class ArticleAdmin9(admin.ModelAdmin): site9 = admin.AdminSite(name='admin9') site9.register(Article, ArticleAdmin9)
class AdminViewPermissionsTest(TestCase): self.assertEqual(post.status_code, 403) self.client.get(reverse('admin:logout')) # view user should be able to view the article but not change any of them # (the POST can be sent, but no modification occurs) self.client.force_login(self....
class AdminViewPermissionsTest(TestCase): self.assertEqual(post.status_code, 403) self.client.get(reverse('admin:logout')) # view user can view articles but not make changes. self.client.force_login(self.viewuser) response = self.client.get(article_changelist_url) self.a...
class AdminViewPermissionsTest(TestCase): self.assertContains(response, '<label>Extra form field:</label>') self.assertContains(response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close</a>') post = self.client.post(article_change_url, change_dict) self.assertEq...
class AdminViewPermissionsTest(TestCase): self.assertContains(response, '<label>Extra form field:</label>') self.assertContains(response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close</a>') post = self.client.post(article_change_url, change_dict) self.assertEq...
class AdminViewPermissionsTest(TestCase): response = self.client.get(change_url_3) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_3, {'name': 'changed'}) self.assertRedirects(response, self.index_url) sel...
class AdminViewPermissionsTest(TestCase): response = self.client.get(change_url_3) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_3, {'name': 'changed'}) self.assertEqual(response.status_code, 403) self.a...
class AdminViewPermissionsTest(TestCase): self.assertEqual(response.context['title'], 'View article') self.assertContains(response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close</a>') def test_change_view_post_without_object_change_permission(self): """A POST re...
class AdminViewPermissionsTest(TestCase): self.assertEqual(response.context['title'], 'View article') self.assertContains(response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close</a>') def test_change_view_save_as_new(self): """ 'Save as new' should raise...
class AdminInlineTests(TestCase): self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated") def test_simple_inline_permissions(self): """ Changes aren't allowed without change permissions for the inline object. """ ...
class AdminInlineTests(TestCase): self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated") def test_explicit_autofield_inline(self): "A model with an explicit autofield primary key can be saved as inlines. Regression for #8093" #...
urlpatterns = [ # All admin views accept `extra_context` to allow adding it like this: path('test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}), path('test_admin/admin9/', admin.site9.urls), path('test_admin/admin10/', admin.site10.urls), path('test_...
urlpatterns = [ # All admin views accept `extra_context` to allow adding it like this: path('test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}), path('test_admin/admin9/', admin.site9.urls), path('test_admin/has_permission_admin/', custom_has_permission_...
class ChangelistTests(AuthViewsTestCase): data['password'] = 'shouldnotchange' change_url = reverse('auth_test_admin:auth_user_change', args=(u.pk,)) response = self.client.post(change_url, data) self.assertRedirects(response, reverse('auth_test_admin:auth_user_changelist')) u.re...
class ChangelistTests(AuthViewsTestCase): data['password'] = 'shouldnotchange' change_url = reverse('auth_test_admin:auth_user_change', args=(u.pk,)) response = self.client.post(change_url, data) self.assertEqual(response.status_code, 403) u.refresh_from_db() self.assertE...
def _partition_tasks(worker): set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks} set_tasks["already_done"] = {task for (task, status, ext) in task_history if status == 'DONE' and task not in pending_tasks and tas...
def _partition_tasks(worker): set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks} set_tasks["already_done"] = {task for (task, status, ext) in task_history if status == 'DONE' and task not in pending_tasks and tas...
def _depth_first_search(set_tasks, current_task, visited): for task in current_task._requires(): if task not in visited: _depth_first_search(set_tasks, task, visited) if task in set_tasks["failed"] or task in set_tasks["upstream_failure"]: set_tasks["upstr...
def _depth_first_search(set_tasks, current_task, visited): for task in current_task._requires(): if task not in visited: _depth_first_search(set_tasks, task, visited) if task in set_tasks["ever_failed"] or task in set_tasks["upstream_failure"]: set_tasks["...
def _get_comments(group_tasks): _ORDERED_STATUSES = ( "already_done", "completed", "failed", "scheduling_error", "still_pending",
def _get_comments(group_tasks): _ORDERED_STATUSES = ( "already_done", "completed", "ever_failed", "failed", "scheduling_error", "still_pending",
def _summary_format(set_tasks, worker): str_output += 'Did not run any tasks' smiley = "" reason = "" if set_tasks["failed"]: smiley = ":(" reason = "there were failed tasks" if set_tasks["scheduling_error"]: reason += " and tasks whose scheduling failed" elif...
def _summary_format(set_tasks, worker): str_output += 'Did not run any tasks' smiley = "" reason = "" if set_tasks["ever_failed"]: if not set_tasks["failed"]: smiley = ":)" reason = "there were failed tasks but they all suceeded in a retry" else: s...
class ExecutionSummaryTest(LuigiTestCase): self.assertIn('Luigi Execution Summary', s) self.assertNotIn('00:00:00', s) self.assertNotIn('\n\n\n', s)
class ExecutionSummaryTest(LuigiTestCase): self.assertIn('Luigi Execution Summary', s) self.assertNotIn('00:00:00', s) self.assertNotIn('\n\n\n', s) """ Test that a task once crashing and then succeeding should be counted as no failure. """ def test_status_with_task_retry(self):...
class RetcodesTest(LuigiTestCase): with mock.patch('luigi.scheduler.Scheduler.add_task', new_func): self.run_and_expect('RequiringTask', 0) self.run_and_expect('RequiringTask --retcode-not-run 5', 5)
class RetcodesTest(LuigiTestCase): with mock.patch('luigi.scheduler.Scheduler.add_task', new_func): self.run_and_expect('RequiringTask', 0) self.run_and_expect('RequiringTask --retcode-not-run 5', 5) """ Test that a task once crashing and then succeeding should be counted as no ...
def get_catalog(self, user_id, tenant_id, metadata=None): class ServiceController(wsgi.Application): def __init__(self): self.catalog_api = Manager() super(ServiceController, self).__init__() # CRUD extensions # NOTE(termie): this OS-KSADM stuff is not very consistent def get_services(s...
def get_catalog(self, user_id, tenant_id, metadata=None): class ServiceController(wsgi.Application): def __init__(self): self.catalog_api = Manager() self.identity_api = identity.Manager() self.policy_api = policy.Manager() self.token_api = token.Manager() super(ServiceContro...
import httplib import json from lxml import etree import nose.exc
import httplib import json import uuid from lxml import etree import nose.exc
def assertValidMultipleChoiceResponse(self, r): def assertValidVersionResponse(self, r): self.assertValidVersion(r.body.get('version')) class XmlTestCase(RestfulTestCase, CoreApiTests): xmlns = 'http://docs.openstack.org/identity/api/v2.0'
def assertValidMultipleChoiceResponse(self, r): def assertValidVersionResponse(self, r): self.assertValidVersion(r.body.get('version')) def test_service_crud_requires_auth(self): """Service CRUD should 401 without an X-Auth-Token (bug 1006822).""" # values here don't matter because we s...
'pytz', 'pyOpenSSL', 'python-dateutil', 'six' ]
'pytz', 'pyOpenSSL', 'python-dateutil', 'defusedxml', 'six' ]
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree root_logger = logging.getLogger(__name__) root_logger.level = logging.NOTSET
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree import defusedxml.ElementTree root_logger = logging.getLogger(__name__) root_logger.level = logging.NOTSET
def create_class_from_xml_string(target_class, xml_string): """ if not isinstance(xml_string, six.binary_type): xml_string = xml_string.encode('utf-8') tree = ElementTree.fromstring(xml_string) return create_class_from_element_tree(target_class, tree)
def create_class_from_xml_string(target_class, xml_string): """ if not isinstance(xml_string, six.binary_type): xml_string = xml_string.encode('utf-8') tree = defusedxml.ElementTree.fromstring(xml_string) return create_class_from_element_tree(target_class, tree)
def loadd(self, ava): def extension_element_from_string(xml_string): element_tree = ElementTree.fromstring(xml_string) return _extension_element_from_element_tree(element_tree)
def loadd(self, ava): def extension_element_from_string(xml_string): element_tree = defusedxml.ElementTree.fromstring(xml_string) return _extension_element_from_element_tree(element_tree)
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/" FORM_SPEC = """<form method="post" action="%s">
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree import defusedxml.ElementTree NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/" FORM_SPEC = """<form method="post" action="%s">
def parse_soap_enveloped_saml(text, body_class, header_class=None): :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = ElementTree.fromstring(text) assert envelope.tag == '{%s}Envelope' % NAMESPACE # print(len(envelope))
def parse_soap_enveloped_saml(text, body_class, header_class=None): :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = defusedxml.ElementTree.fromstring(text) assert envelope.tag == '{%s}Envelope' % NAMESPACE # print(len(envelope))
except ImportError: #noinspection PyUnresolvedReferences from elementtree import ElementTree logger = logging.getLogger(__name__)
except ImportError: #noinspection PyUnresolvedReferences from elementtree import ElementTree import defusedxml.ElementTree logger = logging.getLogger(__name__)
def parse_soap_enveloped_saml_thingy(text, expected_tags): :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelope = ElementTree.fromstring(text) # Make sure it's a SOAP message assert envelope.tag == '{%s}Envelope' % soapenv.NAMESP...
def parse_soap_enveloped_saml_thingy(text, expected_tags): :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelope = defusedxml.ElementTree.fromstring(text) # Make sure it's a SOAP message assert envelope.tag == '{%s}Envelope' % soa...
def class_instances_from_soap_enveloped_saml_thingies(text, modules): :return: The body and headers as class instances """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc)
def class_instances_from_soap_enveloped_saml_thingies(text, modules): :return: The body and headers as class instances """ try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc)
def open_soap_envelope(text): :return: dictionary with two keys "body"/"header" """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc)
def open_soap_envelope(text): :return: dictionary with two keys "body"/"header" """ try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc)
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree ITEMS = { NameID: ["""<?xml version="1.0" encoding="utf-8"?>
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree from defusedxml.common import EntitiesForbidden ITEMS = { NameID: ["""<?xml version="1.0" encoding="utf-8"?>
def test_create_class_from_xml_string_wrong_class_spec(): assert kl == None def test_ee_1(): ee = saml2.extension_element_from_string( """<?xml version='1.0' encoding='UTF-8'?><foo>bar</foo>""")
def test_create_class_from_xml_string_wrong_class_spec(): assert kl == None def test_create_class_from_xml_string_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> ]> ...
def test_ee_7(): assert nid.text.strip() == "http://federationX.org" def test_extension_element_loadd(): ava = {'attributes': {}, 'tag': 'ExternalEntityAttributeAuthority',
def test_ee_7(): assert nid.text.strip() == "http://federationX.org" def test_ee_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> ]> <lolz>&lol1;</lolz> """ w...
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree import saml2.samlp as samlp from saml2.samlp import NAMESPACE as SAMLP_NAMESPACE NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/"
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree from defusedxml.common import EntitiesForbidden from pytest import raises import saml2.samlp as samlp from saml2.samlp import NAMESPACE as SAMLP_NAMESPACE from saml2 import soap NAMESPACE = "http://schemas....
def test_make_soap_envelope(): assert len(body) == 1 saml_part = body[0] assert saml_part.tag == '{%s}AuthnRequest' % SAMLP_NAMESPACE
def test_make_soap_envelope(): assert len(body) == 1 saml_part = body[0] assert saml_part.tag == '{%s}AuthnRequest' % SAMLP_NAMESPACE def test_parse_soap_enveloped_saml_thingy_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY ...
from future.backports.urllib.parse import parse_qs from future.backports.urllib.parse import urlencode from future.backports.urllib.parse import urlparse from saml2.argtree import add_path from saml2.cert import OpenSSLWrapper
from future.backports.urllib.parse import parse_qs from future.backports.urllib.parse import urlencode from future.backports.urllib.parse import urlparse from pytest import raises from saml2.argtree import add_path from saml2.cert import OpenSSLWrapper
from saml2.authn_context import INTERNETPROTOCOLPASSWORD from saml2.client import Saml2Client from saml2.config import SPConfig from saml2.response import LogoutResponse from saml2.saml import NAMEID_FORMAT_PERSISTENT, EncryptedAssertion, Advice from saml2.saml import NAMEID_FORMAT_TRANSIENT
from saml2.authn_context import INTERNETPROTOCOLPASSWORD from saml2.client import Saml2Client from saml2.config import SPConfig from saml2.pack import parse_soap_enveloped_saml from saml2.response import LogoutResponse from saml2.saml import NAMEID_FORMAT_PERSISTENT, EncryptedAssertion, Advice from saml2.saml import NA...
from saml2.s_utils import factory from saml2.time_util import in_a_while, a_while_ago from fakeIDP import FakeIDP from fakeIDP import unpack_form from pathutils import full_path
from saml2.s_utils import factory from saml2.time_util import in_a_while, a_while_ago from defusedxml.common import EntitiesForbidden from fakeIDP import FakeIDP from fakeIDP import unpack_form from pathutils import full_path
def test_negotiated_post_sso(self): 'http://www.example.com/login' assert ac.authn_context_class_ref.text == INTERNETPROTOCOLPASSWORD # if __name__ == "__main__": # tc = TestClient()
def test_negotiated_post_sso(self): 'http://www.example.com/login' assert ac.authn_context_class_ref.text == INTERNETPROTOCOLPASSWORD def test_parse_soap_enveloped_saml_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTI...
The implementations of the hdfs clients. The hadoop cli client and the snakebite client. """ from luigi.contrib.hdfs import config as hdfs_config from luigi.contrib.hdfs import snakebite_client as hdfs_snakebite_client from luigi.contrib.hdfs import webhdfs_client as hdfs_webhdfs_client from luigi.contrib.hdfs import...
The implementations of the hdfs clients. The hadoop cli client and the snakebite client. """ import logging import threading from luigi.contrib.hdfs import config as hdfs_config from luigi.contrib.hdfs import snakebite_client as hdfs_snakebite_client from luigi.contrib.hdfs import webhdfs_client as hdfs_webhdfs_client...
def makecmdoptions(self): def __str__(self): return "<SvnAuth username=%s ...>" %(self.username,) rex_blame = re.compile(r'\s*(\d+)\s*(\S+) (.*)') class SvnWCCommandPath(common.PathBase): """ path implementation offering access/modification to svn working copies.
def makecmdoptions(self): def __str__(self): return "<SvnAuth username=%s ...>" %(self.username,) rex_blame = re.compile(r'\s*(\d+)\s+(\S+) (.*)') class SvnWCCommandPath(common.PathBase): """ path implementation offering access/modification to svn working copies.
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task): def __init__(self): if not isinstance(self.dataflow_params, DataflowParamKeys): raise ValueError("dataflow_params must be of type DataflowParamKeys") @abstractmethod def dataflow_executable(self):
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task): def __init__(self): if not isinstance(self.dataflow_params, DataflowParamKeys): raise ValueError("dataflow_params must be of type DataflowParamKeys") super(BeamDataflowJobTask, self).__init__() @abstractmethod def da...
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task): @staticmethod def get_target_path(target): if isinstance(target, luigi.LocalTarget) or isinstance(target, gcs.GCSTarget): return target.path elif isinstance(target, bigquery.BigQueryTarget): "{}:{}.{}".format...
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task): @staticmethod def get_target_path(target): """ Given a luigi Target, determine a stringly typed path to pass as a Dataflow job argument. """ if isinstance(target, luigi.LocalTarget) or isinstance(targ...
import json import luigi from luigi.contrib import beam_dataflow from luigi import local_target import mock from mock import MagicMock, patch
import json import luigi from luigi.contrib import beam_dataflow, bigquery, gcs from luigi import local_target import mock from mock import MagicMock, patch
class BeamDataflowTest(unittest.TestCase): self.assertEqual(TestTaskDictOfMixedCompleteOutput().complete(), False) def test_dataflow_runner_resolution(self): task = SimpleTestTask() # Test that supported runners are passed through
class BeamDataflowTest(unittest.TestCase): self.assertEqual(TestTaskDictOfMixedCompleteOutput().complete(), False) def test_get_target_path(self): bq_target = bigquery.BigQueryTarget("p", "d", "t", client="fake_client") self.assertEqual( SimpleTestTask.get_target_path(bq_target...
) from .jwks_client import PyJWKClient __version__ = "2.3.0" __title__ = "PyJWT" __description__ = "JSON Web Token implementation in Python"
) from .jwks_client import PyJWKClient __version__ = "2.4.0" __title__ = "PyJWT" __description__ = "JSON Web Token implementation in Python"
der_to_raw_signature, force_bytes, from_base64url_uint, raw_to_der_signature, to_base64url_uint, )
der_to_raw_signature, force_bytes, from_base64url_uint, is_pem_format, is_ssh_key, raw_to_der_signature, to_base64url_uint, )
def __init__(self, hash_alg): def prepare_key(self, key): key = force_bytes(key) invalid_strings = [ b"-----BEGIN PUBLIC KEY-----", b"-----BEGIN CERTIFICATE-----", b"-----BEGIN RSA PUBLIC KEY-----", b"ssh-rsa", ] if any(string_value i...
def __init__(self, hash_alg): def prepare_key(self, key): key = force_bytes(key) if is_pem_format(key) or is_ssh_key(key): raise InvalidKeyError( "The specified key is an asymmetric key or x509 certificate and" " should not be used as an HMAC secret."
def __init__(self, **kwargs): pass def prepare_key(self, key): if isinstance( key, (Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey), ): return key if isinstance(key, (bytes, str)): ...
def __init__(self, **kwargs): pass def prepare_key(self, key): if isinstance(key, (bytes, str)): if isinstance(key, str): key = key.encode("utf-8") str_key = key.decode("utf-8") if "-----BEGIN PUBLIC" in str_key: ...
import base64 import binascii from typing import Any, Union try:
import base64 import binascii import re from typing import Any, Union try:
def raw_to_der_signature(raw_sig: bytes, curve: EllipticCurve) -> bytes: s = bytes_to_number(raw_sig[num_bytes:]) return encode_dss_signature(r, s)
def raw_to_der_signature(raw_sig: bytes, curve: EllipticCurve) -> bytes: s = bytes_to_number(raw_sig[num_bytes:]) return encode_dss_signature(r, s) # Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252 _PEMS = { b"CERTIFICATE", b"TRUSTED CERT...
class TestOKPAlgorithms: def test_okp_ed25519_should_reject_non_string_key(self): algo = OKPAlgorithm() with pytest.raises(TypeError): algo.prepare_key(None) with open(key_path("testkey_ed25519")) as keyfile:
class TestOKPAlgorithms: def test_okp_ed25519_should_reject_non_string_key(self): algo = OKPAlgorithm() with pytest.raises(InvalidKeyError): algo.prepare_key(None) with open(key_path("testkey_ed25519")) as keyfile:
class Model(Container): nested_weighted_metrics = _collect_metrics(weighted_metrics, self.output_names) self.metrics_updates = [] self.stateful_metric_names = [] with K.name_scope('metrics'): for i in range(len(self.outputs)): if i in skip_target_indices:
class Model(Container): nested_weighted_metrics = _collect_metrics(weighted_metrics, self.output_names) self.metrics_updates = [] self.stateful_metric_names = [] self.stateful_metric_functions = [] with K.name_scope('metrics'): for i in range(len(self.outputs)): ...
class Model(Container): # stateful metrics (i.e. metrics layers). if isinstance(metric_fn, Layer) and metric_fn.stateful: self.stateful_metric_names.append(metric_name) self.metrics_updates += metric_fn.updates ...
class Model(Container): # stateful metrics (i.e. metrics layers). if isinstance(metric_fn, Layer) and metric_fn.stateful: self.stateful_metric_names.append(metric_name) self.stateful_metric_functions.append(metric_fn...
class Model(Container): for epoch in range(initial_epoch, epochs): # Reset stateful metrics for m in self.metrics: if isinstance(m, Layer) and m.stateful: m.reset_states() callbacks.on_epoch_begin(epoch) epoch_logs = {} ...
class Model(Container): for epoch in range(initial_epoch, epochs): # Reset stateful metrics for m in self.stateful_metric_functions: m.reset_states() callbacks.on_epoch_begin(epoch) epoch_logs = {} if steps_per_epoch is not None:
class Model(Container): """ if hasattr(self, 'metrics'): for m in self.metrics: if isinstance(m, Layer) and m.stateful: m.reset_states() stateful_metric_indices = [ i for i, name in enumerate(self.metrics_names) ...
class Model(Container): """ if hasattr(self, 'metrics'): for m in self.stateful_metric_functions: m.reset_states() stateful_metric_indices = [ i for i, name in enumerate(self.metrics_names) if str(name) in self.stateful_metric_name...
class Model(Container): # Construct epoch logs. epoch_logs = {} while epoch < epochs: for m in self.metrics: if isinstance(m, Layer) and m.stateful: m.reset_states() callbacks.on_epoch_begin(epoch) ...
class Model(Container): # Construct epoch logs. epoch_logs = {} while epoch < epochs: for m in self.stateful_metric_functions: m.reset_states() callbacks.on_epoch_begin(epoch) steps_done = 0 batch_ind...
class Model(Container): stateful_metric_indices = [] if hasattr(self, 'metrics'): for i, m in enumerate(self.metrics): if isinstance(m, Layer) and m.stateful: m.reset_states() stateful_metric_indices = [ i for i, name in enumer...
class Model(Container): stateful_metric_indices = [] if hasattr(self, 'metrics'): for m in self.stateful_metric_functions: m.reset_states() stateful_metric_indices = [ i for i, name in enumerate(self.metrics_names) if str(name) in ...
def test_sparse_top_k_categorical_accuracy(): @keras_test def test_stateful_metrics(): np.random.seed(1334) class BinaryTruePositives(keras.layers.Layer):
def test_sparse_top_k_categorical_accuracy(): @keras_test @pytest.mark.parametrize('metrics_mode', ['list', 'dict']) def test_stateful_metrics(metrics_mode): np.random.seed(1334) class BinaryTruePositives(keras.layers.Layer):
def test_stateful_metrics(): # Test on simple model inputs = keras.Input(shape=(2,)) outputs = keras.layers.Dense(1, activation='sigmoid')(inputs) model = keras.Model(inputs, outputs) model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['acc', metr...
def test_stateful_metrics(): # Test on simple model inputs = keras.Input(shape=(2,)) outputs = keras.layers.Dense(1, activation='sigmoid', name='out')(inputs) model = keras.Model(inputs, outputs) if metrics_mode == 'list': model.compile(optimizer='sgd', loss='binary_c...
from youtube_dl import YoutubeDL from youtube_dl.compat import compat_str from youtube_dl.extractor import YoutubeIE from youtube_dl.postprocessor.common import PostProcessor from youtube_dl.utils import match_filter_func TEST_URL = 'http://localhost/sample.mp4'
from youtube_dl import YoutubeDL from youtube_dl.compat import compat_str from youtube_dl.extractor import YoutubeIE from youtube_dl.postprocessor.common import PostProcessor from youtube_dl.utils import ExtractorError, match_filter_func TEST_URL = 'http://localhost/sample.mp4'
class TestFormatSelection(unittest.TestCase): downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts] self.assertEqual(downloaded_ids, ['B', 'C', 'D']) class TestYoutubeDL(unittest.TestCase): def test_subtitles(self):
class TestFormatSelection(unittest.TestCase): downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts] self.assertEqual(downloaded_ids, ['B', 'C', 'D']) ydl = YDL({'format': 'best[height<40]'}) try: ydl.process_ie_result(info_dict) except ExtractorE...
class YoutubeDL(object): format_spec = selector.selector def selector_function(formats): if format_spec == 'all': for f in formats: yield f
class YoutubeDL(object): format_spec = selector.selector def selector_function(formats): formats = list(formats) if not formats: return if format_spec == 'all': for f in formats: ...
import copy import datetime from functools import partial import string from typing import TYPE_CHECKING, Optional, Tuple, Union import warnings import numpy as np from pandas._libs import Timedelta, hashtable as libhashtable, lib import pandas._libs.join as libjoin from pandas._typing import FrameOrSeries from panda...
import copy import datetime from functools import partial import string from typing import TYPE_CHECKING, Optional, Tuple, Union, cast import warnings import numpy as np from pandas._libs import Timedelta, hashtable as libhashtable, lib import pandas._libs.join as libjoin from pandas._typing import ArrayLike, FrameOr...
from pandas.core.dtypes.common import ( is_array_like, is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64tz_dtype, is_dtype_equal,
from pandas.core.dtypes.common import ( is_array_like, is_bool, is_bool_dtype, is_categorical, is_categorical_dtype, is_datetime64tz_dtype, is_dtype_equal,
def _get_join_indexers( # get left & right join labels and num. of levels at each location mapped = ( _factorize_keys(left_keys[n], right_keys[n], sort=sort) for n in range(len(left_keys)) ) zipped = zip(*mapped)
def _get_join_indexers( # get left & right join labels and num. of levels at each location mapped = ( _factorize_keys(left_keys[n], right_keys[n], sort=sort, how=how) for n in range(len(left_keys)) ) zipped = zip(*mapped)
def _get_join_indexers( # factorize keys to a dense i8 space # `count` is the num. of unique keys # set(lkey) | set(rkey) == range(count) lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort) # preserve left frame order if how == 'left' and sort == False kwargs = copy.copy(kwargs) if h...
def _get_join_indexers( # factorize keys to a dense i8 space # `count` is the num. of unique keys # set(lkey) | set(rkey) == range(count) lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort, how=how) # preserve left frame order if how == 'left' and sort == False kwargs = copy.copy(kwargs)...
def _right_outer_join(x, y, max_groups): return left_indexer, right_indexer def _factorize_keys(lk, rk, sort=True): # Some pre-processing for non-ndarray lk / rk lk = extract_array(lk, extract_numpy=True) rk = extract_array(rk, extract_numpy=True)
def _right_outer_join(x, y, max_groups): return left_indexer, right_indexer def _factorize_keys( lk: ArrayLike, rk: ArrayLike, sort: bool = True, how: str = "inner" ) -> Tuple[np.array, np.array, int]: """ Encode left and right keys as enumerated types. This is used to get the join indexers to be...
def _factorize_keys(lk, rk, sort=True): rk, _ = rk._values_for_factorize() elif ( is_categorical_dtype(lk) and is_categorical_dtype(rk) and lk.is_dtype_equal(rk) ): if lk.categories.equals(rk.categories): # if we exactly match in categories, allow us to factorize on codes ...
def _factorize_keys(lk, rk, sort=True): rk, _ = rk._values_for_factorize() elif ( is_categorical_dtype(lk) and is_categorical_dtype(rk) and is_dtype_equal(lk, rk) ): assert is_categorical(lk) and is_categorical(rk) lk = cast(Categorical, lk) rk = cast(Categorical, rk) ...
def _factorize_keys(lk, rk, sort=True): np.putmask(rlab, rmask, count) count += 1 return llab, rlab, count
def _factorize_keys(lk, rk, sort=True): np.putmask(rlab, rmask, count) count += 1 if how == "right": return rlab, llab, count return llab, rlab, count
class TestMerge: # GH 24212 # pd.merge gets [0, 1, 2, -1, -1, -1] as left_indexer, ensure that # -1 is interpreted as a missing value instead of the last element df1 = pd.DataFrame({"a": [1, 2, 3], "key": [0, 2, 2]}, index=index) df2 = pd.DataFrame({"b": [1, 2, 3, 4, 5]}) ...
class TestMerge: # GH 24212 # pd.merge gets [0, 1, 2, -1, -1, -1] as left_indexer, ensure that # -1 is interpreted as a missing value instead of the last element df1 = pd.DataFrame({"a": [0, 1, 2], "key": [0, 1, 2]}, index=index) df2 = pd.DataFrame({"b": [0, 1, 2, 3, 4, 5]}) ...
class TestMerge: result = left.merge(right, left_on="key", right_index=True, how="right") tm.assert_frame_equal(result, expected) def test_merge_take_missing_values_from_index_of_other_dtype(self): # GH 24212 left = pd.DataFrame(
class TestMerge: result = left.merge(right, left_on="key", right_index=True, how="right") tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("how", ["left", "right"]) def test_merge_preserves_row_order(self, how): # GH 27453 left_df = pd.DataFrame({"animal": ["dog"...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collection_tar, files_member_obj) ...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) try: with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collectio...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (to_native(filename, errors='surrogate_or_strict'), to_native(tar.name))) b_dest_filepath = os.path.join(b_dest, ...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (to_native(filename, errors='surrogate_or_strict'), to_native(tar.name))) b_dest_filepath = os.path.abspath(os.pa...
__metaclass__ = type import json import os import pytest import tarfile import uuid
__metaclass__ = type import json import os import pytest import re import tarfile import uuid
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): os.path.isfile(output_file) def test_require_one_of_collections_requirements_with_both(): cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify', 'namespace.collection', '-r', 'requirements.yml'])
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): os.path.isfile(output_file) def test_extract_tar_file_outside_dir(tmp_path_factory): filename = u'ÅÑŚÌβŁÈ' temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Collections' % to_native(filename))) tar_file = os.path.join(temp_dir, to_bytes('%s...
class AdminReadonlyField: except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: if getattr(attr, 'boolean', False): result_repr = _boolean_icon(value)
class AdminReadonlyField: except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if field in self.form.fields: widget = self.form[field].field.widget # This isn't elegant but suffices for contrib.auth'...
UserModel = get_user_model() class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs)
UserModel = get_user_model() class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' read_only = True def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs)
from django.contrib.auth import ( from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, SetPasswordForm, ) from django.contrib.auth.models import User from django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, LoginView, logout_then_login, redirect_to_login, ) from djang...
from django.contrib.auth import ( from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, SetPasswordForm, ) from django.contrib.auth.models import Permission, User from django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, LoginView, logout_then_login, redirect_to_login, ...