buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class Series(base.IndexOpsMixin, generic.NDFrame): from pandas.core.reshape.concat import concat if isinstance(to_append, (list, tuple)): to_concat = [self] + to_append else: to_concat = [self, to_append] return concat(
class Series(base.IndexOpsMixin, generic.NDFrame): from pandas.core.reshape.concat import concat if isinstance(to_append, (list, tuple)): to_concat = [self] to_concat.extend(to_append) else: to_concat = [self, to_append] return concat(
class TestSeriesCombine: with pytest.raises(ValueError, match=msg): pd.concat([s1, s2], verify_integrity=True) def test_combine_scalar(self): # GH 21248 # Note - combine() with another Series is tested elsewhere because
class TestSeriesCombine: with pytest.raises(ValueError, match=msg): pd.concat([s1, s2], verify_integrity=True) def test_append_tuples(self): # GH 28410 s = pd.Series([1, 2, 3]) list_input = [s, s] tuple_input = (s, s) expected = s.append(list_input) ...
""" import os import threading from itertools import chain
""" import os import re import sys import threading from itertools import chain
_cache = {} _cache_lock = threading.RLock() _dirname = os.path.join(os.path.dirname(__file__), 'locale-data') def normalize_locale(name):
_cache = {} _cache_lock = threading.RLock() _dirname = os.path.join(os.path.dirname(__file__), 'locale-data') _windows_reserved_name_re = re.compile("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$", re.I) def normalize_locale(name):
def normalize_locale(name): return locale_id def exists(name): """Check whether locale data is available for the given locale.
def normalize_locale(name): return locale_id def resolve_locale_filename(name): """ Resolve a locale identifier to a `.dat` path on disk. """ # Clean up any possible relative paths. name = os.path.basename(name) # Ensure we're not left with one of the Windows reserved names. ...
def exists(name): return False if name in _cache: return True file_found = os.path.exists(os.path.join(_dirname, '%s.dat' % name)) return True if file_found else bool(normalize_locale(name))
def exists(name): return False if name in _cache: return True file_found = os.path.exists(resolve_locale_filename(name)) return True if file_found else bool(normalize_locale(name))
def load(name, merge_inherited=True): :raise `IOError`: if no locale data file is found for the given locale identifer, or one of the locales it inherits from """ _cache_lock.acquire() try: data = _cache.get(name)
def load(name, merge_inherited=True): :raise `IOError`: if no locale data file is found for the given locale identifer, or one of the locales it inherits from """ name = os.path.basename(name) _cache_lock.acquire() try: data = _cache.get(name)
def load(name, merge_inherited=True): else: parent = '_'.join(parts[:-1]) data = load(parent).copy() filename = os.path.join(_dirname, '%s.dat' % name) with open(filename, 'rb') as fileobj: if name != 'root' and merge_in...
def load(name, merge_inherited=True): else: parent = '_'.join(parts[:-1]) data = load(parent).copy() filename = resolve_locale_filename(name) with open(filename, 'rb') as fileobj: if name != 'root' and merge_inherited: ...
# individuals. For the exact contribution history, see the revision # history and logs, available at http://babel.edgewall.org/log/. import unittest import random from operator import methodcaller from babel import localedata class MergeResolveTestCase(unittest.TestCase):
# individuals. For the exact contribution history, see the revision # history and logs, available at http://babel.edgewall.org/log/. import os import pickle import sys import tempfile import unittest import random from operator import methodcaller import pytest from babel import localedata, Locale, UnknownLocaleErro...
def listdir_spy(*args): localedata.locale_identifiers.cache = None assert localedata.locale_identifiers() assert len(listdir_calls) == 2
def listdir_spy(*args): localedata.locale_identifiers.cache = None assert localedata.locale_identifiers() assert len(listdir_calls) == 2 def test_locale_name_cleanup(): """ Test that locale identifiers are cleaned up to avoid directory traversal. """ no_exist_name = os.path.join(tempfile.g...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import random import shlex
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import errno import fcntl import os import random import shlex
import subprocess import sys import tempfile import warnings from binascii import hexlify from binascii import unhexlify from binascii import Error as BinasciiError
import subprocess import sys import tempfile import warnings from binascii import hexlify from binascii import unhexlify from binascii import Error as BinasciiError
class VaultEditor: os.remove(tmp_path) def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None): # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=...
class VaultEditor: os.remove(tmp_path) def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None): # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_T...
class VaultEditor: # Figure out the vault id from the file, to select the right secret to re-encrypt it # (duplicates parts of decrypt, but alas...) dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, ...
class VaultEditor: # Figure out the vault id from the file, to select the right secret to re-encrypt it # (duplicates parts of decrypt, but alas...) dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, filename=filename) # vault id here may not be the vault id ac...
class VaultEditor: return data # TODO: add docstrings for arg types since this code is picky about that def write_data(self, data, filename, shred=True): """Write the data bytes to given path This is used to write a byte string to a file or stdout. It is used for
class VaultEditor: return data def write_data(self, data, thefile, shred=True, mode=0o600): # TODO: add docstrings for arg types since this code is picky about that """Write the data bytes to given path This is used to write a byte string to a file or stdout. It is used for
class VaultEditor: should be a byte string and not a text type. :arg data: the byte string (bytes) data :arg filename: filename to save 'data' to. :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered. :returns: None ...
class VaultEditor: should be a byte string and not a text type. :arg data: the byte string (bytes) data :arg thefile: file descriptor or filename to save 'data' to. :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered. :re...
class KeyValueType(object): """A type used with `argparse`.""" def __init__(self, *separators): self.separators = separators def __call__(self, string): found = {} for sep in self.separators: regex = '[^\\\\]' + sep match = re.search(regex, string) ...
class KeyValueType(object): """A type used with `argparse`.""" def __init__(self, *separators): self.separators = separators self.escapes = ['\\\\' + sep for sep in separators] def __call__(self, string): found = {} found_escapes = [] for esc in self.escapes: ...
class TestItemParsing(BaseTest): }) self.assertIn('bar@baz', files) def test_valid_items(self): headers, data, files = cli.parse_items([
class TestItemParsing(BaseTest): }) self.assertIn('bar@baz', files) def test_escape_longsep(self): headers, data, files = cli.parse_items([ self.kv('bob\\:==foo'), ]) self.assertDictEqual(data, { 'bob:=': 'foo', }) def test_valid_item...
def _unstack_multiple(data, clocs, fill_value=None): index = data.index clocs = [index._get_level_number(i) for i in clocs] rlocs = [i for i in range(index.nlevels) if i not in clocs]
def _unstack_multiple(data, clocs, fill_value=None): index = data.index # GH 19966 Make sure if MultiIndexed index has tuple name, they will be # recognised as a whole if clocs in index.names: clocs = [clocs] clocs = [index._get_level_number(i) for i in clocs] rlocs = [i for i in rang...
class TestDataFrameReshape: ) tm.assert_frame_equal(result, expected) def test_unstack_preserve_dtypes(self): # Checks fix for #11847 df = pd.DataFrame(
class TestDataFrameReshape: ) tm.assert_frame_equal(result, expected) def test_unstack_tuplename_in_multiindex(self): # GH 19966 idx = pd.MultiIndex.from_product( [["a", "b", "c"], [1, 2, 3]], names=[("A", "a"), ("B", "b")] ) df = pd.DataFrame({"d": [1] *...
import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import DataFrame, MultiIndex, Series import pandas._testing as tm
import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import DataFrame, Series import pandas._testing as tm
class TestSeriesAnalytics: assert s.is_monotonic is False assert s.is_monotonic_decreasing is True def test_unstack(self): index = MultiIndex( levels=[["bar", "foo"], ["one", "three", "two"]], codes=[[1, 1, 0, 0], [0, 1, 0, 2]], ) s = Series(np.aran...
class TestSeriesAnalytics: assert s.is_monotonic is False assert s.is_monotonic_decreasing is True @pytest.mark.parametrize("func", [np.any, np.all]) @pytest.mark.parametrize("kwargs", [dict(keepdims=True), dict(out=object())]) @td.skip_if_np_lt("1.15")
from thefuck.rules.php_s import get_new_command, match from thefuck.types import Command def test_match(): assert match(Command('php -s localhost:8000', '')) @pytest.mark.parametrize('command', [
from thefuck.rules.php_s import get_new_command, match from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('php -s localhost:8000', ''), Command('php -t pub -s 0.0.0.0:8080', '') ]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [
def test_not_match(command): assert not match(command) def test_get_new_command(): new_command = get_new_command(Command('php -s localhost:8000', '')) assert new_command == 'php -S localhost:8000'
def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('php -s localhost:8000', ''), 'php -S localhost:8000'), (Command('php -t pub -s 0.0.0.0:8080', ''), 'php -t pub -S 0.0.0.0:8080') ]) def test_get_new_command(command, new_command): assert...
from thefuck.utils import replace_argument, for_app @for_app('php') def match(command): return "php -s" in command.script def get_new_command(command): return replace_argument(command.script, "-s", "-S") requires_output = False
from thefuck.utils import replace_argument, for_app @for_app('php') def match(command): return " -s " in command.script def get_new_command(command): return replace_argument(command.script, "-s", "-S")
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries from pandas.core import algorithms from pandas.core.accessor import PandasDelegate from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin from pandas.core.arrays.datetimelike import ( DatetimeLikeArrayMixin, _ensure_datetimelik...
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries from pandas.core import algorithms from pandas.core.accessor import PandasDelegate from pandas.core.arrays import ( DatetimeArray, ExtensionArray, ExtensionOpsMixin, TimedeltaArray, ) from pandas.core.arrays.datetimelike import (...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): if isinstance(maybe_slice, slice): return self[maybe_slice] taken = ExtensionIndex.take( self, indices, axis, allow_fill, fill_value, **kwargs ) # keep freq in PeriodArray/Index, reset otherwise ...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): if isinstance(maybe_slice, slice): return self[maybe_slice] return ExtensionIndex.take( self, indices, axis, allow_fill, fill_value, **kwargs ) _can_hold_na = True _na_value = NaT
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) def repeat(self, repeats, axis=None): nv.validate_repeat(tuple(), dict(axis=axis)) freq = self.freq if is_period_dtype(self) else None return self._shallow_copy(sel...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) def repeat(self, repeats, axis=None): nv.validate_repeat(tuple(), dict(axis=axis)) result = type(self._data)(self.asi8.repeat(repeats), dtype=self.dtype) return sel...
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): self._data._freq = freq # -------------------------------------------------------------------- # Set Operation Methods
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): self._data._freq = freq def _shallow_copy(self, values=None, **kwargs): if values is None: values = self._data if isinstance(values, type(self)): values = values._data attributes = self._get_a...
class TestDatetimeIndex: with pytest.raises(ValueError, match=msg): dt_cls([pd.NaT, pd.Timestamp("2011-01-01").value], freq="D") def test_categorical_preserves_tz(self): # GH#18664 retain tz when going DTI-->Categorical-->DTI # TODO: parametrize over DatetimeIndex/DatetimeArray
class TestDatetimeIndex: with pytest.raises(ValueError, match=msg): dt_cls([pd.NaT, pd.Timestamp("2011-01-01").value], freq="D") # TODO: better place for tests shared by DTI/TDI? @pytest.mark.parametrize( "index", [ pd.date_range("2016-01-01", periods=5, tz="US/P...
import bz2 from collections import abc import gzip from io import BufferedIOBase, BytesIO import mmap import os import pathlib
import bz2 from collections import abc import gzip from io import BufferedIOBase, BytesIO, RawIOBase import mmap import os import pathlib
def get_handle( try: from s3fs import S3File need_text_wrapping = (BufferedIOBase, S3File) except ImportError: need_text_wrapping = BufferedIOBase # type: ignore handles: List[IO] = list() f = path_or_buf
def get_handle( try: from s3fs import S3File need_text_wrapping = (BufferedIOBase, RawIOBase, S3File) except ImportError: need_text_wrapping = (BufferedIOBase, RawIOBase) # type: ignore handles: List[IO] = list() f = path_or_buf
def get_handle( from io import TextIOWrapper g = TextIOWrapper(f, encoding=encoding, newline="") if not isinstance(f, BufferedIOBase): handles.append(g) f = g
def get_handle( from io import TextIOWrapper g = TextIOWrapper(f, encoding=encoding, newline="") if not isinstance(f, (BufferedIOBase, RawIOBase)): handles.append(g) f = g
Module contains tools for processing files into DataFrames or other objects from collections import abc, defaultdict import csv import datetime from io import BufferedIOBase, StringIO, TextIOWrapper import re import sys from textwrap import fill
Module contains tools for processing files into DataFrames or other objects from collections import abc, defaultdict import csv import datetime from io import BufferedIOBase, RawIOBase, StringIO, TextIOWrapper import re import sys from textwrap import fill
class CParserWrapper(ParserBase): # Handle the file object with universal line mode enabled. # We will handle the newline character ourselves later on. if isinstance(src, BufferedIOBase): src = TextIOWrapper(src, encoding=encoding, newline="") kwds["enco...
class CParserWrapper(ParserBase): # Handle the file object with universal line mode enabled. # We will handle the newline character ourselves later on. if isinstance(src, (BufferedIOBase, RawIOBase)): src = TextIOWrapper(src, encoding=encoding, newline="") ...
def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt): ) def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding): # gh-23779: Python csv engine shouldn't error on files opened in binary. parser = all_parsers fpath = os.path.join(csv_dir_path, fname)
def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt): ) def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding): # gh-23779: Python csv engine shouldn't error on files opened in binary. # gh-31575: Python csv engine shouldn't error on files opened in raw binary. parser =...
def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding): result = parser.read_csv(fb, encoding=encoding) tm.assert_frame_equal(expected, result) @pytest.mark.parametrize("pass_encoding", [True, False]) def test_encoding_temp_file(all_parsers, utf_value, encoding_fmt, pass_encoding):
def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding): result = parser.read_csv(fb, encoding=encoding) tm.assert_frame_equal(expected, result) with open(fpath, mode="rb", buffering=0) as fb: result = parser.read_csv(fb, encoding=encoding) tm.assert_frame_equal(expect...
def load_data(path='imdb.npz', path, origin=origin_folder + 'imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path) as f: x_train, labels_train = f['x_train'], f['y_train'] x_test, labels_test = f['x_test'], f['y_test']
def load_data(path='imdb.npz', path, origin=origin_folder + 'imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path, allow_pickle=True) as f: x_train, labels_train = f['x_train'], f['y_train'] x_test, labels_test = f['x_test'], f['y_test']
from jose.constants import ALGORITHMS from jose.exceptions import JWKError from jose.utils import base64url_decode # PyCryptodome's RSA module doesn't have PyCrypto's _RSAobj class # Instead it has a class named RsaKey, which serves the same purpose.
from jose.constants import ALGORITHMS from jose.exceptions import JWKError from jose.utils import base64url_decode from jose.utils import constant_time_string_compare # PyCryptodome's RSA module doesn't have PyCrypto's _RSAobj class # Instead it has a class named RsaKey, which serves the same purpose.
def sign(self, msg): return hmac.new(self.prepared_key, msg, self.hash_alg).digest() def verify(self, msg, sig): return sig == self.sign(msg) class RSAKey(Key):
def sign(self, msg): return hmac.new(self.prepared_key, msg, self.hash_alg).digest() def verify(self, msg, sig): return constant_time_string_compare(sig, self.sign(msg)) class RSAKey(Key):
import base64 def calculate_at_hash(access_token, hash_alg):
import base64 import hmac def calculate_at_hash(access_token, hash_alg):
def timedelta_total_seconds(delta): delta (timedelta): A timedelta to convert to seconds. """ return delta.days * 24 * 60 * 60 + delta.seconds
def timedelta_total_seconds(delta): delta (timedelta): A timedelta to convert to seconds. """ return delta.days * 24 * 60 * 60 + delta.seconds def constant_time_string_compare(a, b): """Helper for comparing string in constant time, independent of the python version being used. Args: ...
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. """ ...
class _ScalarAccessIndexer(_NDFrameIndexerBase): if not isinstance(key, tuple): key = _tuplify(self.ndim, key) if len(key) != self.ndim: raise ValueError("Not enough indexers for scalar access (setting)!") key = list(self._convert_key(key, is_setter=True)) self....
class _ScalarAccessIndexer(_NDFrameIndexerBase): if not isinstance(key, tuple): key = _tuplify(self.ndim, key) key = list(self._convert_key(key, is_setter=True)) if len(key) != self.ndim: raise ValueError("Not enough indexers for scalar access (setting)!") self....
class _AtIndexer(_ScalarAccessIndexer): Require they keys to be the same type as the index. (so we don't fallback) """ # allow arbitrary setting if is_setter: return list(key)
class _AtIndexer(_ScalarAccessIndexer): Require they keys to be the same type as the index. (so we don't fallback) """ # GH 26989 # For series, unpacking key needs to result in the label. # This is already the case for len(key) == 1; e.g. (1,) if self.ndim == 1 an...
def test_iat_series_with_period_index(): expected = ser[index[0]] result = ser.iat[0] assert expected == result
def test_iat_series_with_period_index(): expected = ser[index[0]] result = ser.iat[0] assert expected == result def test_at_with_tuple_index_get(): # GH 26989 # DataFrame.at getter works with Index of tuples df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)]) assert df.index.nlevels == 1...
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...
EXAMPLES = r''' secured: '{{ item.secured }}' state: present with_items: - { name: AWS_ACCESS_KEY, value: ABCD1234 } - { name: AWS_SECRET, value: qwe789poi123vbn0, secured: True } - name: Remove pipeline variable
EXAMPLES = r''' secured: '{{ item.secured }}' state: present with_items: - { name: AWS_ACCESS_KEY, value: ABCD1234, secured: False } - { name: AWS_SECRET, value: qwe789poi123vbn0, secured: True } - name: Remove pipeline variable
EXAMPLES = r''' RETURN = r''' # ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.source_control.bitbucket import BitbucketHelper error_messages = {
EXAMPLES = r''' RETURN = r''' # ''' from ansible.module_utils.basic import AnsibleModule, _load_params from ansible.module_utils.source_control.bitbucket import BitbucketHelper error_messages = {
def delete_pipeline_variable(module, bitbucket, variable_uuid): )) def main(): argument_spec = BitbucketHelper.bitbucket_argument_spec() argument_spec.update(
def delete_pipeline_variable(module, bitbucket, variable_uuid): )) class BitBucketPipelineVariable(AnsibleModule): def __init__(self, *args, **kwargs): params = _load_params() or {} if params.get('secured'): kwargs['argument_spec']['value'].update({'no_log': True}) supe...
def main(): secured=dict(type='bool', default=False), state=dict(type='str', choices=['present', 'absent'], required=True), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, )
def main(): secured=dict(type='bool', default=False), state=dict(type='str', choices=['present', 'absent'], required=True), ) module = BitBucketPipelineVariable( argument_spec=argument_spec, supports_check_mode=True, )
def _can_use_numexpr(op, op_str, a, b, dtype_check): # required min elements (otherwise we are adding overhead) if np.prod(a.shape) > _MIN_ELEMENTS: # check for dtype compatibility dtypes = set() for o in [a, b]: if hasattr(o, "dtypes"): ...
def _can_use_numexpr(op, op_str, a, b, dtype_check): # required min elements (otherwise we are adding overhead) if np.prod(a.shape) > _MIN_ELEMENTS: # check for dtype compatibility dtypes = set() for o in [a, b]: # Series implements dtypes, check for ...
class TestExpressions: operator_name = "truediv" if test_flex: op = lambda x, y: getattr(df, arith)(y) op.__name__ = arith else: op = getattr(operator, operator_name)
class TestExpressions: operator_name = "truediv" if test_flex: op = lambda x, y: getattr(x, arith)(y) op.__name__ = arith else: op = getattr(operator, operator_name)
class TestExpressions: for f in [self.frame, self.frame2, self.mixed, self.mixed2]: for cond in [True, False]: c = np.empty(f.shape, dtype=np.bool_) c.fill(cond) result = expr.where(c, f.values, f.values + 1)
class TestExpressions: for f in [self.frame, self.frame2, self.mixed, self.mixed2]: for cond in [True, False]: c = np.empty(f.shape, dtype=np.bool_) c.fill(cond) result = expr.where(c, f.values, f.values + 1)
class TestExpressions: # GH 22383 - .ne fails if columns containing column name 'dtype' result = test_input.loc[:, ["a", "dtype"]].ne(test_input.loc[:, ["a", "dtype"]]) assert_frame_equal(result, expected)
class TestExpressions: # GH 22383 - .ne fails if columns containing column name 'dtype' result = test_input.loc[:, ["a", "dtype"]].ne(test_input.loc[:, ["a", "dtype"]]) assert_frame_equal(result, expected) @pytest.mark.parametrize( "arith", ("add", "sub", "mul", "mod", "truediv", "f...
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) logger.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exception.BadStoreUri() pieces = urlparse.urlparse(uri)
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) logger.error(_("Invalid store URI: %(reason)s") % locals()) raise exception.BadStoreUri() pieces = urlparse.urlparse(uri)
def parse_uri(self, uri): # the account and user. Combine them into a single username of # account:user if len(cred_parts) == 1: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) logger.error(re...
def parse_uri(self, uri): # the account and user. Combine them into a single username of # account:user if len(cred_parts) == 1: reason = (_("Badly formed credentials in Swift URI.")) logger.error(reason) raise exception.BadStoreUri() ...
def parse_uri(self, uri): path_parts.insert(0, netloc) self.authurl = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI: %s") % uri logger.error(reason) raise exception.BadStoreUri()
def parse_uri(self, uri): path_parts.insert(0, netloc) self.authurl = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI.") logger.error(reason) raise exception.BadStoreUri()
def get(self, location): except swift_client.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def get(self, location): except swift_client.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise
def add(self, image_id, image_file, image_size): except swift_client.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "location %s") % location.get_uri()) msg =...
def add(self, image_id, image_file, image_size): except swift_client.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "this location.")) msg = (_("Failed to add...
def delete(self, location): except swift_client.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def delete(self, location): except swift_client.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: rais...
class RNN(Layer): @property def trainable_weights(self): if isinstance(self.cell, Layer): return self.cell.trainable_weights return []
class RNN(Layer): @property def trainable_weights(self): if not self.trainable: return [] if isinstance(self.cell, Layer): return self.cell.trainable_weights return []
class RNN(Layer): @property def non_trainable_weights(self): if isinstance(self.cell, Layer): return self.cell.non_trainable_weights return []
class RNN(Layer): @property def non_trainable_weights(self): if isinstance(self.cell, Layer): if not self.trainable: return self.cell.weights return self.cell.non_trainable_weights return []
def test_regularizer(layer_class): assert len(layer.get_losses_for(x)) == 1 @keras_test def test_masking_layer(): ''' This test based on a previously failing issue here:
def test_regularizer(layer_class): assert len(layer.get_losses_for(x)) == 1 @rnn_test def test_trainability(layer_class): layer = layer_class(units) layer.build((None, None, embedding_dim)) assert len(layer.weights) == 3 assert len(layer.trainable_weights) == 3 assert len(layer.non_trainable_w...
def create_instance(objcls, settings, crawler, *args, **kwargs): ``*args`` and ``**kwargs`` are forwarded to the constructors. Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``. """ if settings is None: if crawler is None: raise ValueError("Specify at least one...
def create_instance(objcls, settings, crawler, *args, **kwargs): ``*args`` and ``**kwargs`` are forwarded to the constructors. Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``. Raises ``TypeError`` if the resulting instance is ``None`` (e.g. if an extension has not been implemen...
class UtilsMiscTestCase(unittest.TestCase): # 2. with from_settings() constructor # 3. with from_crawler() constructor # 4. with from_settings() and from_crawler() constructor spec_sets = ([], ['from_settings'], ['from_crawler'], ['from_settings', 'from_crawler...
class UtilsMiscTestCase(unittest.TestCase): # 2. with from_settings() constructor # 3. with from_crawler() constructor # 4. with from_settings() and from_crawler() constructor spec_sets = ( ['__qualname__'], ['__qualname__', 'from_settings'], ['_...
class UtilsMiscTestCase(unittest.TestCase): _test_with_crawler(m, settings, crawler) # Check adoption of crawler settings m = mock.MagicMock(spec_set=['from_settings']) create_instance(m, None, crawler, *args, **kwargs) m.from_settings.assert_called_once_with(crawler.setting...
class UtilsMiscTestCase(unittest.TestCase): _test_with_crawler(m, settings, crawler) # Check adoption of crawler settings m = mock.MagicMock(spec_set=['__qualname__', 'from_settings']) create_instance(m, None, crawler, *args, **kwargs) m.from_settings.assert_called_once_with...
class UtilsMiscTestCase(unittest.TestCase): with self.assertRaises(ValueError): create_instance(m, None, None) def test_set_environ(self): assert os.environ.get('some_test_environ') is None with set_environ(some_test_environ='test_value'):
class UtilsMiscTestCase(unittest.TestCase): with self.assertRaises(ValueError): create_instance(m, None, None) m.from_settings.return_value = None with self.assertRaises(TypeError): create_instance(m, settings, None) def test_set_environ(self): assert os.env...
def delete(self, req, id): content_type="text/plain") image = self.get_image_meta_or_404(req, id) if image['protected']: msg = _("Image is protected") logger.debug(msg)
def delete(self, req, id): content_type="text/plain") image = self.get_image_meta_or_404(req, id) if not (req.context.is_admin or image['owner'] == None or image['owner'] == req.context.owner): msg = _("Unable to delete image ...
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc from pandas.core.dtypes.cast import maybe_cast_result from pandas.core.dtypes.common import ( ensure_float, is_datetime64_dtype, is_integer_dtype, is_numeric_dtype, is_object_dtype,
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc from pandas.core.dtypes.cast import maybe_cast_result from pandas.core.dtypes.common import ( ensure_float, is_bool_dtype, is_datetime64_dtype, is_extension_array_dtype, is_integer_dtype, is_numeric_dtype, is_obj...
class GroupBy(_GroupBy[FrameOrSeries]): ) inference = None if is_integer_dtype(vals): inference = np.int64 elif is_datetime64_dtype(vals): inference = "datetime64[ns]" vals = np.asarray(vals).astype(np.float)
class GroupBy(_GroupBy[FrameOrSeries]): ) inference = None if is_integer_dtype(vals.dtype): if is_extension_array_dtype(vals.dtype): vals = vals.to_numpy(dtype=float, na_value=np.nan) inference = np.int64 elif is_bo...
def test_quantile_missing_group_values_correct_results(): tm.assert_frame_equal(result, expected) # pipe # --------------------------------
def test_quantile_missing_group_values_correct_results(): tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "values", [ pd.array([1, 0, None] * 2, dtype="Int64"), pd.array([True, False, None] * 2, dtype="boolean"), ], ) @pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0...
def test_not_match(command): @pytest.mark.parametrize('command, output', [ (Command(script='git push', stderr=git_err), 'git push --force'), (Command(script='git push nvbn', stderr=git_err), 'git push --force nvbn'), (Command(script='git push nvbn master', stderr=git_err), 'git push --force nvbn master')]...
def test_not_match(command): @pytest.mark.parametrize('command, output', [ (Command(script='git push', stderr=git_err), 'git push --force-with-lease'), (Command(script='git push nvbn', stderr=git_err), 'git push --force-with-lease nvbn'), (Command(script='git push nvbn master', stderr=git_err), 'git push ...
def match(command): @git_support def get_new_command(command): return replace_argument(command.script, 'push', 'push --force') enabled_by_default = False
def match(command): @git_support def get_new_command(command): return replace_argument(command.script, 'push', 'push --force-with-lease') enabled_by_default = False
class Language(object): """ if name not in self.pipe_names: raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names)) if ENABLE_PIPELINE_ANALYSIS: analyze_all_pipes(self.pipeline) return self.pipeline.pop(self.pipe_names.index(name)) def __call__(...
class Language(object): """ if name not in self.pipe_names: raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names)) removed = self.pipeline.pop(self.pipe_names.index(name)) if ENABLE_PIPELINE_ANALYSIS: analyze_all_pipes(self.pipeline) return ...
def test_analysis_validate_attrs_valid(): def test_analysis_validate_attrs_invalid(attr): with pytest.raises(ValueError): validate_attrs([attr])
def test_analysis_validate_attrs_valid(): def test_analysis_validate_attrs_invalid(attr): with pytest.raises(ValueError): validate_attrs([attr]) def test_analysis_validate_attrs_remove_pipe(): """Test that attributes are validated correctly on remove.""" spacy.language.ENABLE_PIPELINE_ANALYSIS = T...
def text_to_word_sequence(text, if lower: text = text.lower() if sys.version_info < (3,) and isinstance(text, unicode): translate_map = dict((ord(c), unicode(split)) for c in filters) else: translate_map = maketrans(filters, split * len(filters)) text = text.translate(translate...
def text_to_word_sequence(text, if lower: text = text.lower() if sys.version_info < (3,): if isinstance(text, unicode): translate_map = dict((ord(c), unicode(split)) for c in filters) text = text.translate(translate_map) elif len(split) == 1: translat...
def test_text_to_word_sequence(): assert text_to_word_sequence(text) == ['hello', 'world'] def test_text_to_word_sequence_unicode(): text = u'ali! veli? kırk dokuz elli' assert text_to_word_sequence(text) == [u'ali', u'veli', u'kırk', u'dokuz', u'elli'] def test_tokenizer_unicode(): texts = [u'ali v...
def test_text_to_word_sequence(): assert text_to_word_sequence(text) == ['hello', 'world'] def test_text_to_word_sequence_multichar_split(): text = 'hello!stop?world!' assert text_to_word_sequence(text, split='stop') == ['hello', 'world'] def test_text_to_word_sequence_unicode(): text = u'ali! veli?...
def _find_module_utils(module_name, b_module_data, module_path, module_args, tas # FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it module_json = json.dumps(exec_manifest) b_module_data = exec_wrapper.replace(b"$json_raw = ''", b"$json...
def _find_module_utils(module_name, b_module_data, module_path, module_args, tas # FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it module_json = json.dumps(exec_manifest) # delimit the payload JSON from the wrapper to keep sensitive c...
class ActionModule(ActionBase): exec_data = None # WinRM requires a special wrapper to work with environment variables if self._connection.transport == "winrm": pay = self._connection._create_raw_wrapper_payload(script_cmd, ...
class ActionModule(ActionBase): exec_data = None # WinRM requires a special wrapper to work with environment variables if self._connection.transport == "winrm": pay = self._connection._create_raw_wrapper_payload(script_cmd, env_dict) exec_data = to_byt...
import traceback import json import tempfile import subprocess HAVE_KERBEROS = False try:
import traceback import json import tempfile import subprocess import xml.etree.ElementTree as ET HAVE_KERBEROS = False try:
class Connection(ConnectionBase): return (result.status_code, result.std_out, result.std_err) def is_clixml(self, value): return value.startswith(b"#< CLIXML") # hacky way to get just stdout- not always sure of doc framing here, so use with care def parse_clixml_stream(self, clixml_doc, st...
class Connection(ConnectionBase): return (result.status_code, result.std_out, result.std_err) def is_clixml(self, value): return value.startswith(b"#< CLIXML\r\n") # hacky way to get just stdout- not always sure of doc framing here, so use with care def parse_clixml_stream(self, clixml_doc...
import base64 import os import re import shlex from ansible.errors import AnsibleError from ansible.module_utils._text import to_native, to_text
import base64 import os import re import shlex import pkgutil from ansible.errors import AnsibleError from ansible.module_utils._text import to_native, to_text
begin { # stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives # exec runspace, capture output, cleanup, return module output # NB: do not adjust the following line- it is replaced when doing non-streamed module output $json_raw...
begin { # stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives # exec runspace, capture output, cleanup, return module output # only init and stream in $json_raw if it wasn't set by the enclosing scope if (-not $(Get-Variable "j...
class ShellModule(ShellBase): return self._encode_script(script) def build_module_command(self, env_string, shebang, cmd, arg_path=None): # pipelining bypass if cmd == '': return '-' # non-pipelining
class ShellModule(ShellBase): return self._encode_script(script) def build_module_command(self, env_string, shebang, cmd, arg_path=None): bootstrap_wrapper = pkgutil.get_data("ansible.executor.powershell", "bootstrap_wrapper.ps1") # pipelining bypass if cmd == '': retur...
class ShellModule(ShellBase): cmd_parts = list(map(to_text, cmd_parts)) if shebang and shebang.lower() == '#!powershell': if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): cmd_parts[0] = '"%s.ps1"' % self._unquote(cmd_parts[0]) cmd_parts.insert(0, '&') ...
class ShellModule(ShellBase): cmd_parts = list(map(to_text, cmd_parts)) if shebang and shebang.lower() == '#!powershell': if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): # we're running a module via the bootstrap wrapper cmd_parts[0] = '"%s.ps1"' ...