buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class CLI(with_metaclass(ABCMeta, object)): except EOFError: pass return (sshpass, becomepass) def validate_conflicts(self, op, vault_opts=False, runas_opts=False, fork_opts=False, vault_rekey_opts=False):
class CLI(with_metaclass(ABCMeta, object)): except EOFError: pass # we 'wrap' the passwords to prevent templating as # they can contain special chars and trigger it incorrectly if sshpass: sshpass = AnsibleUnsafeBytes(sshpass) if becomepass: b...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.six import string_types, text_type from ansible.module_utils._text import to_text from ansible.module_utils.common._collections_compat import Mapping, MutableSequence, Set
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.six import string_types, text_type, binary_type from ansible.module_utils._text import to_text from ansible.module_utils.common._collections_compat import Mapping, MutableSequence, Set
class AnsibleUnsafeText(text_type, AnsibleUnsafe): pass class UnsafeProxy(object): def __new__(cls, obj, *args, **kwargs): # In our usage we should only receive unicode strings. # This conditional and conversion exists to sanity check the values # we're given but we may want to take it...
class AnsibleUnsafeText(text_type, AnsibleUnsafe): pass class AnsibleUnsafeBytes(binary_type, AnsibleUnsafe): pass class UnsafeProxy(object): def __new__(cls, obj, *args, **kwargs): # In our usage we should only receive unicode strings. # This conditional and conversion exists to sanity ...
def create_cloned_field(field: ModelField) -> ModelField: original_type.__name__, __config__=original_type.__config__ ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f use_type.__validators__ = original_type.__validators__ if PYDANTIC_1: ...
def create_cloned_field(field: ModelField) -> ModelField: original_type.__name__, __config__=original_type.__config__ ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field(f) use_type.__validators__ = original_type.__validators__ ...
import stat import tarfile import zipfile class ArchiveException(Exception): """
import stat import tarfile import zipfile from django.core.exceptions import SuspiciousOperation class ArchiveException(Exception): """
class BaseArchive: return False return True def extract(self): raise NotImplementedError('subclasses of BaseArchive must provide an extract() method')
class BaseArchive: return False return True def target_filename(self, to_path, name): target_path = os.path.abspath(to_path) filename = os.path.abspath(os.path.join(target_path, name)) if not filename.startswith(target_path): raise SuspiciousOperation("Ar...
class TarArchive(BaseArchive): name = member.name if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if member.isdir(): if filename: os.makedirs(filename, exist_ok=True)
class TarArchive(BaseArchive): name = member.name if leading: name = self.split_leading_dir(name)[1] filename = self.target_filename(to_path, name) if member.isdir(): if filename: os.makedirs(filename, exist_ok=True)
class ZipArchive(BaseArchive): info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if filename.endswith(('/', '\\')): # A directory os.makedirs(filenam...
class ZipArchive(BaseArchive): info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] if not name: continue filename = self.target_filename(to_path, name) if name.endswith(('/', '\\')): ...
import sys import tempfile import unittest from django.utils import archive
import sys import tempfile import unittest from django.core.exceptions import SuspiciousOperation from django.test import SimpleTestCase from django.utils import archive
class TestArchive(unittest.TestCase): # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, 'no_permissions') self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask)
class TestArchive(unittest.TestCase): # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, 'no_permissions') self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask) class TestArchiveInvalid(SimpleTestCase): def test_ext...
from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils.decorators import method_decorator from django.utils.inspect import ( func_accepts_kwargs, func_accepts_var_args, get_func_full_arg...
from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils._os import safe_join from django.utils.decorators import method_decorator from django.utils.inspect import ( func_accepts_kwargs, f...
class TemplateDetailView(BaseAdminDocsView): else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(directory) / template if template_file.exists(): templ...
class TemplateDetailView(BaseAdminDocsView): else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(safe_join(directory, template)) if template_file.exists(): ...
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.assertContains(response, 'View documentation') @override_settings(TEMPLATES=[{ 'NAME': 'ONE', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.assertContains(response, 'View documentation') @unittest.skipUnless(utils.docutils_is_available, 'no docutils installed.') class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_logi...
def l2_normalize(x, axis=-1): return x / np.sqrt(y) def binary_crossentropy(target, output, from_logits=False): if not from_logits: output = np.clip(output, 1e-7, 1 - 1e-7)
def l2_normalize(x, axis=-1): return x / np.sqrt(y) def in_top_k(predictions, targets, k): top_k = np.argsort(-predictions)[:, :k] targets = targets.reshape(-1, 1) return np.any(targets == top_k, axis=-1) def binary_crossentropy(target, output, from_logits=False): if not from_logits: out...
class TestBackend(object): check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=-1) check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=1) def test_in_top_k(self): batch_size = 20 num_classes = 10
class TestBackend(object): check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=-1) check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=1) @pytest.mark.skipif(K.backend() == 'cntk', reason='Bug in CNTK') def test_in_top_k(self): batch_size = 20 num...
class TestBackend(object): # (k == 0 or k > num_classes) does not raise an error # but just return an unmeaningful tensor. for k in range(num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(target...
class TestBackend(object): # (k == 0 or k > num_classes) does not raise an error # but just return an unmeaningful tensor. for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(tar...
class TestBackend(object): for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(targets, dtype='int32'), k)) for b in [KTH, KTF]] assert_list_pairwise(z_list) ...
class TestBackend(object): for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(targets, dtype='int32'), k)) for b in WITH_NP] assert_list_pairwise(z_list) @...
def get_write_function(output): stderr.write(s) elif isinstance(output, (pycompat.PathLike, str)): def write(s): with open(output_path, 'a') as output_file: output_file.write(s) else: assert isinstance(output, utils.WritableStream)
def get_write_function(output): stderr.write(s) elif isinstance(output, (pycompat.PathLike, str)): def write(s): with open(output, 'a') as output_file: output_file.write(s) else: assert isinstance(output, utils.WritableStream)
import abc from python_toolbox import caching from python_toolbox import sys_tools import pysnooper
import abc from python_toolbox import caching from python_toolbox import sys_tools from python_toolbox import temp_file_tools import pysnooper
def test_method_and_prefix(): ), prefix='ZZZ' )
def test_method_and_prefix(): ), prefix='ZZZ' ) def test_file_output(): with temp_file_tools.create_temp_folder(prefix='pysnooper') as folder: path = folder / 'foo.log' @pysnooper.snoop(str(path)) def my_function(foo): x = 7 y = 8 ret...
class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, global_step=...
class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, var_list=params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, glo...
def test_tfoptimizer(): optimizer.from_config(None) if __name__ == '__main__': pytest.main([__file__])
def test_tfoptimizer(): optimizer.from_config(None) @pytest.mark.skipif((K.backend() != 'tensorflow'), reason='Requires TensorFlow backend') def test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer(): from keras import constraints from tensorflow import train ...
from ansible.module_utils.urls import open_url from ansible.utils.display import Display from ansible.utils.hashing import secure_hash_s display = Display()
from ansible.module_utils.urls import open_url from ansible.utils.display import Display from ansible.utils.hashing import secure_hash_s try: from urllib.parse import urlparse except ImportError: # Python 2 from urlparse import urlparse display = Display()
class GalaxyAPI: data = self._call_galaxy(url) results = data['results'] done = (data.get('next_link', None) is None) while not done: url = _urljoin(self.api_server, data['next_link']) data = self._call_galaxy(url) results +...
class GalaxyAPI: data = self._call_galaxy(url) results = data['results'] done = (data.get('next_link', None) is None) # https://github.com/ansible/ansible/issues/64355 # api_server contains part of the API path but next_link includes the the /api part so stri...
def test_get_collection_versions_pagination(api_version, token_type, token_ins, assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type assert mock_open.mock_calls[1][2]['headers']['Authorization'] == '%s my token' % token_type assert mock_open.mock_calls[2][2...
def test_get_collection_versions_pagination(api_version, token_type, token_ins, assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type assert mock_open.mock_calls[1][2]['headers']['Authorization'] == '%s my token' % token_type assert mock_open.mock_calls[2][2...
def count_leading_spaces(s): def process_list_block(docstring, starting_point, section_end, leading_spaces, marker): ending_point = docstring.find('\n\n', starting_point) block = docstring[starting_point:(None if ending_point == -1 else ending_point -...
def count_leading_spaces(s): def process_list_block(docstring, starting_point, section_end, leading_spaces, marker): ending_point = docstring.find('\n\n', starting_point) block = docstring[starting_point:(ending_point - 1 if ending_point > -1 else sec...
y = layer(x) '''} def test_doc_lists(): docstring = autogen.process_docstring(test_doc1['doc']) assert markdown(docstring) == markdown(test_doc1['result']) dummy_docstring = """Multiplies 2 tensors (and/or variables) and returns a *tensor*.
y = layer(x) '''} test_doc_with_arguments_as_last_block = { 'doc': """Base class for recurrent layers. # Arguments return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. return_state: Boolean. Whether to return the last state ...
from django.db import NotSupportedError, transaction from django.db.backends import utils from django.utils import timezone from django.utils.encoding import force_str class BaseDatabaseOperations:
from django.db import NotSupportedError, transaction from django.db.backends import utils from django.utils import timezone from django.utils.encoding import force_str from django.utils.regex_helper import _lazy_re_compile class BaseDatabaseOperations:
class BaseDatabaseOperations: # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported. explain_prefix = None def __init__(self, connection): self.connection = connection self._cache = None
class BaseDatabaseOperations: # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported. explain_prefix = None extract_trunc_lookup_pattern = _lazy_re_compile(r"[\w\-_()]+") def __init__(self, connection): self.connection = connection self._cache = None
class Extract(TimezoneMixin, Transform): super().__init__(expression, **extra) def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) lhs_output_field = self.lhs.output_field if isinstance(lhs_output_field, DateTimeField):
class Extract(TimezoneMixin, Transform): super().__init__(expression, **extra) def as_sql(self, compiler, connection): if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.lookup_name): raise ValueError("Invalid lookup_name: %s" % self.lookup_name) sql, params = com...
class TruncBase(TimezoneMixin, Transform): super().__init__(expression, output_field=output_field, **extra) def as_sql(self, compiler, connection): inner_sql, inner_params = compiler.compile(self.lhs) tzname = None if isinstance(self.lhs.output_field, DateTimeField):
class TruncBase(TimezoneMixin, Transform): super().__init__(expression, output_field=output_field, **extra) def as_sql(self, compiler, connection): if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.kind): raise ValueError("Invalid kind: %s" % self.kind) inner_sql...
class DateFunctionTests(TestCase): self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2) def test_extract_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50,...
class DateFunctionTests(TestCase): self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2) def test_extract_lookup_name_sql_injection(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(201...
class DateFunctionTests(TestCase): [obj], ) def test_trunc_func(self): start_datetime = datetime(999, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
class DateFunctionTests(TestCase): [obj], ) def test_trunc_lookup_name_sql_injection(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(...
class AnsibleModule(object): (k, v) = x.split("=",1) except Exception, e: self.fail_json(msg="this module requires key=value arguments (%s)" % (items)) params[k] = v params2 = json.loads(MODULE_COMPLEX_ARGS) params2.update(params)
class AnsibleModule(object): (k, v) = x.split("=",1) except Exception, e: self.fail_json(msg="this module requires key=value arguments (%s)" % (items)) if k in params: self.fail_json(msg="duplicate parameter: %s (value=%s)" % (k, v)) pa...
import sys import pipes import jinja2 import subprocess import getpass import ansible.constants as C
import sys import pipes import jinja2 import subprocess import shlex import getpass import ansible.constants as C
class Runner(object): return actual_user # *****************************************************
class Runner(object): return actual_user def _count_module_args(self, args): ''' Count the number of k=v pairs in the supplied module args. This is basically a specialized version of parse_kv() from utils with a few minor changes. ''' options = {} if...
class Runner(object): items_terms = self.module_vars.get('items_lookup_terms', '') items_terms = template.template(basedir, items_terms, inject) items = utils.plugins.lookup_loader.get(items_plugin, runner=self, basedir=basedir).run(items_terms, inject=inject) if type(ite...
class Runner(object): items_terms = self.module_vars.get('items_lookup_terms', '') items_terms = template.template(basedir, items_terms, inject) items = utils.plugins.lookup_loader.get(items_plugin, runner=self, basedir=basedir).run(items_terms, inject=inject) # strip out...
class Runner(object): # render module_args and complex_args templates try: module_args = template.template(self.basedir, module_args, inject, fail_on_undefined=self.error_on_undefined_vars) complex_args = template.template(self.basedir, complex_args, inject, fail_on_undefined=se...
class Runner(object): # render module_args and complex_args templates try: # When templating module_args, we need to be careful to ensure # that no variables inadvertantly (or maliciously) add params # to the list of args. We do this by counting the number of k=v ...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(src))) if self.runner.no...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module new_module_args = dict( src=xfered, dest=dest, original_basename=os.path.basename(src), ) module_args_tmp...
class ActionModule(object): # src and dest here come after original and override them # we pass dest only to make sure it includes trailing slash in case of recursive copy module_args_tmp = "%s src=%s dest=%s original_basename=%s" % (module_args, ...
class ActionModule(object): # src and dest here come after original and override them # we pass dest only to make sure it includes trailing slash in case of recursive copy new_module_args = dict( src=tmp_src, dest=dest, ...
class ActionModule(object): tmp_src = tmp_path + source_rel # Build temporary module_args. module_args_tmp = "%s src=%s original_basename=%s" % (module_args, pipes.quote(tmp_src), pipes.quote(source_rel)) if self.runner.n...
class ActionModule(object): tmp_src = tmp_path + source_rel # Build temporary module_args. new_module_args = dict( src=tmp_src, dest=dest, ) if self.runner.noop_on_check(inject): ...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(source))) if self.runner...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module new_module_args = dict( src=xfered, dest=dest, original_basename=os.path.basename(source), ) module_args_tmp...
VERBOSITY=0 MAX_FILE_SIZE_FOR_DIFF=1*1024*1024 try: import json except ImportError:
VERBOSITY=0 MAX_FILE_SIZE_FOR_DIFF=1*1024*1024 # caching the compilation of the regex used # to check for lookup calls within data LOOKUP_REGEX=re.compile(r'lookup\s*\(') try: import json except ImportError:
def json_loads(data): return json.loads(data) def _clean_data(orig_data): ''' remove template tags from a string ''' data = orig_data if isinstance(orig_data, basestring): for pattern,replacement in (('{{','{#'), ('}}','#}'), ('{%','{#'), ('%}','#}')): data = data.replace(pattern, ...
def json_loads(data): return json.loads(data) def _clean_data(orig_data, from_remote=False, from_inventory=False): ''' remove template tags from a string ''' data = orig_data if isinstance(orig_data, basestring): sub_list = [('{%','{#'), ('%}','#}')] if from_remote or (from_inventory a...
def parse_json(raw_data, from_remote=False): return { "failed" : True, "parsed" : False, "msg" : orig_data } if from_remote: results = _clean_data_struct(results) return results def smush_braces(data): ''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed wei...
def parse_json(raw_data, from_remote=False): return { "failed" : True, "parsed" : False, "msg" : orig_data } if from_remote: results = _clean_data_struct(results, from_remote, from_inventory) return results def merge_module_args(current_args, new_args): ''' merges either a diction...
def parse_kv(args): for x in vargs: if "=" in x: k, v = x.split("=",1) options[k]=v return options def merge_hash(a, b):
def parse_kv(args): for x in vargs: if "=" in x: k, v = x.split("=",1) options[k] = v return options def merge_hash(a, b):
def list_intersection(a, b): def safe_eval(expr, locals={}, include_exceptions=False): ''' this is intended for allowing things like: with_items: a_list_variable where Jinja2 would return a string but we do not want to allow it to call functions (outside of Jinja2, where the env is constrained)...
def list_intersection(a, b): def safe_eval(expr, locals={}, include_exceptions=False): ''' This is intended for allowing things like: with_items: a_list_variable Where Jinja2 would return a string but we do not want to allow it to call functions (outside of Jinja2, where the env is constrained). I...
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...
class Poll(models.Model): class Question(models.Model): poll = models.ForeignKey(Poll, models.CASCADE)
class Poll(models.Model): class Question(models.Model): text = models.CharField(max_length=40) poll = models.ForeignKey(Poll, models.CASCADE)
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.assertEqual(response.status_code, 302) self.assertRedirects(respo...
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.assertEqual(RowLevelC...
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: url(r'^test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}), url(r'^test_admin/admin9/', admin.site9.urls), url(r'^test_admin/admin10/', admin.site10.urls), url(r'^t...
urlpatterns = [ # All admin views accept `extra_context` to allow adding it like this: url(r'^test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}), url(r'^test_admin/admin9/', admin.site9.urls), url(r'^test_admin/has_permission_admin/', custom_has_permissi...
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...
from pandas.core.dtypes.common import ( from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import isna, notna from pandas.core import ops from pandas.core.accessor im...
from pandas.core.dtypes.common import ( from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna from pandas.core import ops from...
class Categorical(NDArrayBackedExtensionArray, PandasObject): Returns True if `key` is in this Categorical. """ # if key is a NaN, check if any NaN is in self. if is_scalar(key) and isna(key): return self.isna().any() return contains(self, key, container=self._codes)
class Categorical(NDArrayBackedExtensionArray, PandasObject): Returns True if `key` is in this Categorical. """ # if key is a NaN, check if any NaN is in self. if is_valid_nat_for_dtype(key, self.categories.dtype): return self.isna().any() return contains(self, key, ...
from pandas.core.dtypes.common import ( is_scalar, ) from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.missing import isna from pandas.core import accessor from pandas.core.algorithms import take_1d
from pandas.core.dtypes.common import ( is_scalar, ) from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna from pandas.core import accessor from pandas.core.algorithms import take_1d
class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate): @doc(Index.__contains__) def __contains__(self, key: Any) -> bool: # if key is a NaN, check if any NaN is in self. if is_scalar(key) and isna(key): return self.hasnans hash(key) return contains(self, ke...
class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate): @doc(Index.__contains__) def __contains__(self, key: Any) -> bool: # if key is a NaN, check if any NaN is in self. if is_valid_nat_for_dtype(key, self.categories.dtype): return self.hasnans return contains(self...
class TestContains: ci = CategoricalIndex(list("aabbca") + [np.nan], categories=list("cabdef")) assert np.nan in ci @pytest.mark.parametrize( "item, expected", [
class TestContains: ci = CategoricalIndex(list("aabbca") + [np.nan], categories=list("cabdef")) assert np.nan in ci @pytest.mark.parametrize("unwrap", [True, False]) def test_contains_na_dtype(self, unwrap): dti = pd.date_range("2016-01-01", periods=100).insert(0, pd.NaT) pi = d...
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in...
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodySchema_kwargs: Dict[str, Any] = dict(default...
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: else: BodySchema = params.Body field = Field( name="body", type_=BodyModel,
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: else: BodySchema = params.Body body_param_media_types = [ getattr(f.schema, "media_type") for f in flat_dependant.body_params if isinstance(f.schema, params.Body) ] if len(...
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(None), ) return field
def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(**BodySchema_kwargs), ) return field
class TestYoutubeDL(unittest.TestCase): 'extractor': 'TEST', 'duration': 30, 'filesize': 10 * 1024, } second = { 'id': '2',
class TestYoutubeDL(unittest.TestCase): 'extractor': 'TEST', 'duration': 30, 'filesize': 10 * 1024, 'playlist_id': '42', } second = { 'id': '2',
class TestYoutubeDL(unittest.TestCase): 'duration': 10, 'description': 'foo', 'filesize': 5 * 1024, } videos = [first, second]
class TestYoutubeDL(unittest.TestCase): 'duration': 10, 'description': 'foo', 'filesize': 5 * 1024, 'playlist_id': '43', } videos = [first, second]
class TestYoutubeDL(unittest.TestCase): res = get_videos(f) self.assertEqual(res, ['1']) def test_playlist_items_selection(self): entries = [{ 'id': compat_str(i),
class TestYoutubeDL(unittest.TestCase): res = get_videos(f) self.assertEqual(res, ['1']) f = match_filter_func('playlist_id = 42') res = get_videos(f) self.assertEqual(res, ['1']) def test_playlist_items_selection(self): entries = [{ 'id': compat_str(i),
def _match_one(filter_part, dct): m = operator_rex.search(filter_part) if m: op = COMPARISON_OPERATORS[m.group('op')] if m.group('strval') is not None: if m.group('op') not in ('=', '!='): raise ValueError( 'Operator %s does not support string valu...
def _match_one(filter_part, dct): m = operator_rex.search(filter_part) if m: op = COMPARISON_OPERATORS[m.group('op')] actual_value = dct.get(m.group('key')) if (m.group('strval') is not None or # If the original field is a string and matching comparisonvalue is # ...
def _match_one(filter_part, dct): raise ValueError( 'Invalid integer value %r in filter part %r' % ( m.group('intval'), filter_part)) actual_value = dct.get(m.group('key')) if actual_value is None: return m.group('none_i...
def _match_one(filter_part, dct): raise ValueError( 'Invalid integer value %r in filter part %r' % ( m.group('intval'), filter_part)) if actual_value is None: return m.group('none_inclusive') return op(actual_value, comp...
def main(): # request makes further api requests app.run(host='0.0.0.0', port=settings.config.api_port, debug=True, threaded=True, use_reloader=False, ssl_context=context)
def main(): # request makes further api requests app.run(host='0.0.0.0', port=settings.config.api_port, debug=settings.config.debug, use_evalex=False, threaded=True, use_reloader=False, ssl_context=context)
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # There is no hostname validation when DEBUG=True if settings.DEBUG: return host domain, port = split_domain_port(host) if domain and ...
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_hosts: ...
class CsrfViewMiddlewareTest(SimpleTestCase): self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self._check_token_present(resp, csrf_id=csrf_cookie.value) @override_settings(DEBUG=True) def test_https_bad_referer(self): """ Test that a POST HTTPS request with a bad ref...
class CsrfViewMiddlewareTest(SimpleTestCase): self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self._check_token_present(resp, csrf_id=csrf_cookie.value) @override_settings(DEBUG=True, ALLOWED_HOSTS=['www.example.com']) def test_https_bad_referer(self): """ Test that ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_disabled_in_debug_mode(self): """If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass.""" request = HttpRequest() ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ ...
from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.html import smart_urlquote from django.utils.safestring import mark_safe from django.utils.text import Truncator from django.utils.translation import get_language, gettext as...
from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.html import smart_urlquote from django.utils.http import urlencode from django.utils.text import Truncator from django.utils.translation import get_language, gettext as _
class ForeignKeyRawIdWidget(forms.TextInput): params = self.url_parameters() if params: related_url += '?' + '&amp;'.join('%s=%s' % (k, v) for k, v in params.items()) context['related_url'] = mark_safe(related_url) context['link_title'] = _('Lookup') ...
class ForeignKeyRawIdWidget(forms.TextInput): params = self.url_parameters() if params: related_url += '?' + urlencode(params) context['related_url'] = related_url context['link_title'] = _('Lookup') # The JavaScript code looks for this class....
class Band(models.Model): return self.name class Album(models.Model): band = models.ForeignKey(Band, models.CASCADE) featuring = models.ManyToManyField(Band, related_name='featured')
class Band(models.Model): return self.name class UnsafeLimitChoicesTo(models.Model): band = models.ForeignKey( Band, models.CASCADE, limit_choices_to={'name': '"&><escapeme'}, ) class Album(models.Model): band = models.ForeignKey(Band, models.CASCADE) featuring = mode...
from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual, Inventory, Member, MyFileField, Profile, School, Student, ) from .widgetadmin import site as widget_admin_site
from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual, Inventory, Member, MyFileField, Profile, School, Student, UnsafeLimitChoicesTo, ) from .widgetadmin import site as widget_admin_site
class ForeignKeyRawIdWidgetTest(TestCase): 'Hidden</a></strong>' % {'pk': hidden.pk} ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class ManyToManyRawIdWidgetTest(TestCase):
class ForeignKeyRawIdWidgetTest(TestCase): 'Hidden</a></strong>' % {'pk': hidden.pk} ) def test_render_unsafe_limit_choices_to(self): rel = UnsafeLimitChoicesTo._meta.get_field('band').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTML...
from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode from django.utils.functional import cached_property from django.utils.tree impo...
from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode from django.utils.functional import cached_property from django.utils.regex_hel...
class Query(BaseExpression): alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def add_annotation(self, annotation, alias, is_summary=False, select=True): """Add a single annotation expression to the Query.""" annotation = annotation.resolve_expression( ...
class Query(BaseExpression): alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation mar...
class Query(BaseExpression): else: param_iter = iter([]) for name, entry in select.items(): entry = str(entry) entry_params = [] pos = entry.find("%s")
class Query(BaseExpression): else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s")
class AggregateTestCase(TestCase): ) self.assertEqual(len(qs), 6) def test_exists_extra_where_with_aggregate(self): qs = Book.objects.annotate( count=Count("id"),
class AggregateTestCase(TestCase): ) self.assertEqual(len(qs), 6) def test_alias_sql_injection(self): crafted_alias = """injected_name" from "aggregation_author"; --""" msg = ( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolo...
class NonAggregateAnnotationTestCase(TestCase): ], ) class AliasTests(TestCase): @classmethod
class NonAggregateAnnotationTestCase(TestCase): ], ) def test_alias_sql_injection(self): crafted_alias = """injected_name" from "annotations_book"; --""" msg = ( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL ...
class AliasTests(TestCase): with self.subTest(operation=operation): with self.assertRaisesMessage(FieldError, msg): getattr(qs, operation)("rating_alias")
class AliasTests(TestCase): with self.subTest(operation=operation): with self.assertRaisesMessage(FieldError, msg): getattr(qs, operation)("rating_alias") def test_alias_sql_injection(self): crafted_alias = """injected_name" from "annotations_book"; --""" ...
class ValuesExpressionsTests(TestCase): [{"salary": 10}, {"salary": 20}, {"salary": 30}], ) def test_values_expression_group_by(self): # values() applies annotate() first, so values selected are grouped by # id, not firstname.
class ValuesExpressionsTests(TestCase): [{"salary": 10}, {"salary": 20}, {"salary": 30}], ) def test_values_expression_alias_sql_injection(self): crafted_alias = """injected_name" from "expressions_company"; --""" msg = ( "Column aliases cannot contain whitespace cha...
class Queries5Tests(TestCase): Note.objects.extra(select={"foo": "'bar %%s'"})[0].foo, "bar %s" ) def test_queryset_reuse(self): # Using querysets doesn't mutate aliases. authors = Author.objects.filter(Q(name="a1") | Q(name="nonexistent"))
class Queries5Tests(TestCase): Note.objects.extra(select={"foo": "'bar %%s'"})[0].foo, "bar %s" ) def test_extra_select_alias_sql_injection(self): crafted_alias = """injected_name" from "queries_note"; --""" msg = ( "Column aliases cannot contain whitespace character...
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). type: bool default: 'no'
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). - This setting affects packages installed from a repository as well as "local" packages installed from the filesystem or a URL. ...
class DnfModule(YumDnf): results=[], ) if self.download_only: for package in self.base.transaction.install_set: response['results'].append("Downloaded: {0}".format(package))
class DnfModule(YumDnf): results=[], ) # Validate GPG. This is NOT done in dnf.Base (it's done in the # upstream CLI subclass of dnf.Base) if not self.disable_gpg_check: for package in self.base.transaction....
class AsyncHTTPClient(Configurable): return self._closed = True if self._instance_cache is not None: if self._instance_cache.get(self.io_loop) is not self: raise RuntimeError("inconsistent AsyncHTTPClient cache") del self._instance_cache[self.io_loop] ...
class AsyncHTTPClient(Configurable): return self._closed = True if self._instance_cache is not None: cached_val = self._instance_cache.pop(self.io_loop, None) # If there's an object other than self in the instance # cache for our IOLoop, something has gott...
import copy import threading import datetime from io import BytesIO import time import typing # noqa: F401 import unicodedata import unittest from tornado.escape import utf8, native_str from tornado import gen from tornado.httpclient import ( HTTPRequest,
import copy import threading import datetime from io import BytesIO import subprocess import sys import time import typing # noqa: F401 import unicodedata import unittest from tornado.escape import utf8, native_str, to_unicode from tornado import gen from tornado.httpclient import ( HTTPRequest,
class SyncHTTPClientTest(unittest.TestCase): self.assertEqual(assertion.exception.code, 404) class HTTPRequestTestCase(unittest.TestCase): def test_headers(self): request = HTTPRequest("http://example.com", headers={"foo": "bar"})
class SyncHTTPClientTest(unittest.TestCase): self.assertEqual(assertion.exception.code, 404) class SyncHTTPClientSubprocessTest(unittest.TestCase): def test_destructor_log(self): # Regression test for # https://github.com/tornadoweb/tornado/issues/2539 # # In the past, the ...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): logging.basicConfig(filename=path, level=logging.DEBUG, format='%(asctime)s p=%(process)d u...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): # NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG loggin...
def getallmatchingheaders(self, name): lst.append(line) return lst def parse_headers(fp, _class=HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes ...
def getallmatchingheaders(self, name): lst.append(line) return lst def _read_headers(fp): """Reads potential header lines into a list from a file pointer. Length of line is limited by _MAXLINE, and number of headers is limited by _MAXHEADERS. """ headers = [] while True...
def parse_headers(fp, _class=HTTPMessage): raise HTTPException("got more than %d headers" % _MAXHEADERS) if line in (b'\r\n', b'\n', b''): break hstring = b''.join(headers).decode('iso-8859-1') return email.parser.Parser(_class=_class).parsestr(hstring)
def parse_headers(fp, _class=HTTPMessage): raise HTTPException("got more than %d headers" % _MAXHEADERS) if line in (b'\r\n', b'\n', b''): break return headers def parse_headers(fp, _class=HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants ...
def begin(self): if status != CONTINUE: break # skip the header from the 100 response while True: skip = self.fp.readline(_MAXLINE + 1) if len(skip) > _MAXLINE: raise LineTooLong("header line") skip =...
def begin(self): if status != CONTINUE: break # skip the header from the 100 response skipped_headers = _read_headers(self.fp) if self.debuglevel > 0: print("headers:", skipped_headers) del skipped_headers self.code = s...